1//===- unittests/Basic/LineOffsetMappingTest.cpp - Test LineOffsetMapping -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Basic/SourceManager.h"
10#include "gtest/gtest.h"
11
12using namespace clang;
13using namespace clang::SrcMgr;
14using namespace llvm;
15
16namespace {
17
18TEST(LineOffsetMappingTest, empty) {
19 LineOffsetMapping Mapping;
20 EXPECT_FALSE(Mapping);
21
22#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
23 EXPECT_DEATH((void)Mapping.getLines(), "Storage");
24#endif
25}
26
27TEST(LineOffsetMappingTest, construct) {
28 BumpPtrAllocator Alloc;
29 unsigned Offsets[] = {0, 10, 20};
30 LineOffsetMapping Mapping(Offsets, Alloc);
31 EXPECT_EQ(3u, Mapping.size());
32 EXPECT_EQ(0u, Mapping[0]);
33 EXPECT_EQ(10u, Mapping[1]);
34 EXPECT_EQ(20u, Mapping[2]);
35
36#if !defined(NDEBUG) && GTEST_HAS_DEATH_TEST
37 EXPECT_DEATH((void)Mapping[3], "Invalid index");
38#endif
39}
40
41TEST(LineOffsetMappingTest, constructTwo) {
42 // Confirm allocation size is big enough, convering an off-by-one bug.
43 BumpPtrAllocator Alloc;
44 unsigned Offsets1[] = {0, 10};
45 unsigned Offsets2[] = {0, 20};
46 LineOffsetMapping Mapping1(Offsets1, Alloc);
47 LineOffsetMapping Mapping2(Offsets2, Alloc);
48
49 // Need to check Mapping1 *after* building Mapping2.
50 EXPECT_EQ(2u, Mapping1.size());
51 EXPECT_EQ(0u, Mapping1[0]);
52 EXPECT_EQ(10u, Mapping1[1]);
53 EXPECT_EQ(2u, Mapping2.size());
54 EXPECT_EQ(0u, Mapping2[0]);
55 EXPECT_EQ(20u, Mapping2[1]);
56}
57
58TEST(LineOffsetMappingTest, get) {
59 BumpPtrAllocator Alloc;
60 StringRef Source = "first line\n"
61 "second line\n";
62 auto Mapping = LineOffsetMapping::get(Buffer: MemoryBufferRef(Source, ""), Alloc);
63 EXPECT_EQ(3u, Mapping.size());
64 EXPECT_EQ(0u, Mapping[0]);
65 EXPECT_EQ(11u, Mapping[1]);
66 EXPECT_EQ(23u, Mapping[2]);
67}
68
69TEST(LineOffsetMappingTest, getMissingFinalNewline) {
70 BumpPtrAllocator Alloc;
71 StringRef Source = "first line\n"
72 "second line";
73 auto Mapping = LineOffsetMapping::get(Buffer: MemoryBufferRef(Source, ""), Alloc);
74 EXPECT_EQ(2u, Mapping.size());
75 EXPECT_EQ(0u, Mapping[0]);
76 EXPECT_EQ(11u, Mapping[1]);
77}
78
79} // end namespace
80

source code of clang/unittests/Basic/LineOffsetMappingTest.cpp