1 //===- unittests/Serialization/SourceLocationEncodingTests.cpp ------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Serialization/SourceLocationEncoding.h"
11 #include "gtest/gtest.h"
16 using namespace clang
;
19 using LocSeq
= SourceLocationSequence
;
21 // Convert a single source location into encoded form and back.
22 // If ExpectedEncoded is provided, verify the encoded value too.
23 // Loc is the raw (in-memory) form of SourceLocation.
24 void roundTrip(SourceLocation::UIntTy Loc
,
25 std::optional
<uint64_t> ExpectedEncoded
= std::nullopt
) {
26 uint64_t ActualEncoded
=
27 SourceLocationEncoding::encode(SourceLocation::getFromRawEncoding(Loc
));
29 ASSERT_EQ(ActualEncoded
, *ExpectedEncoded
) << "Encoding " << Loc
;
30 SourceLocation::UIntTy DecodedEncoded
=
31 SourceLocationEncoding::decode(ActualEncoded
).getRawEncoding();
32 ASSERT_EQ(DecodedEncoded
, Loc
) << "Decoding " << ActualEncoded
;
35 // As above, but use sequence encoding for a series of locations.
36 void roundTrip(std::vector
<SourceLocation::UIntTy
> Locs
,
37 std::vector
<uint64_t> ExpectedEncoded
= {}) {
38 std::vector
<uint64_t> ActualEncoded
;
42 ActualEncoded
.push_back(SourceLocationEncoding::encode(
43 SourceLocation::getFromRawEncoding(L
), Seq
));
44 if (!ExpectedEncoded
.empty())
45 ASSERT_EQ(ActualEncoded
, ExpectedEncoded
)
46 << "Encoding " << testing::PrintToString(Locs
);
48 std::vector
<SourceLocation::UIntTy
> DecodedEncoded
;
51 for (auto L
: ActualEncoded
) {
52 SourceLocation Loc
= SourceLocationEncoding::decode(L
, Seq
);
53 DecodedEncoded
.push_back(Loc
.getRawEncoding());
55 ASSERT_EQ(DecodedEncoded
, Locs
)
56 << "Decoding " << testing::PrintToString(ActualEncoded
);
60 constexpr SourceLocation::UIntTy MacroBit
=
61 1 << (sizeof(SourceLocation::UIntTy
) * CHAR_BIT
- 1);
62 constexpr SourceLocation::UIntTy Big
= MacroBit
>> 1;
63 constexpr SourceLocation::UIntTy Biggest
= -1;
65 TEST(SourceLocationEncoding
, Individual
) {
68 roundTrip(MacroBit
, 1);
69 roundTrip(MacroBit
| 5, 11);
72 roundTrip(MacroBit
| Big
);
73 roundTrip(MacroBit
| Big
+ 1);
76 TEST(SourceLocationEncoding
, Sequence
) {
77 roundTrip({1, 2, 3, 3, 2, 1},
79 5, // +2 (+1 of non-raw)
85 roundTrip({100, 0, 100},
91 roundTrip({1, Big
}, {2, ((Big
- 1) << 2) + 1});
92 roundTrip({2, MacroBit
| Big
}, {4, ((Big
- 1) << 2) - 1});
94 roundTrip({3, MacroBit
| 5, MacroBit
| 4, 3},
96 11, // +5 (+2 of non-raw + set macro bit)
98 6} // -3 (-2 of non-raw, clear macro bit)
102 {123 | MacroBit
, 1, 9, Biggest
, Big
, Big
+ 1, 0, MacroBit
| Big
, 0});