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
= SourceLocationEncoding::encode(
27 SourceLocation::getFromRawEncoding(Loc
), /*BaseOffset=*/0,
28 /*BaseModuleFileIndex=*/0);
29 if (ExpectedEncoded
) {
30 ASSERT_EQ(ActualEncoded
, *ExpectedEncoded
) << "Encoding " << Loc
;
32 SourceLocation::UIntTy DecodedEncoded
=
33 SourceLocationEncoding::decode(ActualEncoded
).first
.getRawEncoding();
34 ASSERT_EQ(DecodedEncoded
, Loc
) << "Decoding " << ActualEncoded
;
37 // As above, but use sequence encoding for a series of locations.
38 void roundTrip(std::vector
<SourceLocation::UIntTy
> Locs
,
39 std::vector
<uint64_t> ExpectedEncoded
= {}) {
40 std::vector
<uint64_t> ActualEncoded
;
44 ActualEncoded
.push_back(SourceLocationEncoding::encode(
45 SourceLocation::getFromRawEncoding(L
), /*BaseOffset=*/0,
46 /*BaseModuleFileIndex=*/0, Seq
));
47 if (!ExpectedEncoded
.empty()) {
48 ASSERT_EQ(ActualEncoded
, ExpectedEncoded
)
49 << "Encoding " << testing::PrintToString(Locs
);
52 std::vector
<SourceLocation::UIntTy
> DecodedEncoded
;
55 for (auto L
: ActualEncoded
) {
56 SourceLocation Loc
= SourceLocationEncoding::decode(L
, Seq
).first
;
57 DecodedEncoded
.push_back(Loc
.getRawEncoding());
59 ASSERT_EQ(DecodedEncoded
, Locs
)
60 << "Decoding " << testing::PrintToString(ActualEncoded
);
64 constexpr SourceLocation::UIntTy MacroBit
=
65 1 << (sizeof(SourceLocation::UIntTy
) * CHAR_BIT
- 1);
66 constexpr SourceLocation::UIntTy Big
= MacroBit
>> 1;
67 constexpr SourceLocation::UIntTy Biggest
= -1;
69 TEST(SourceLocationEncoding
, Individual
) {
72 roundTrip(MacroBit
, 1);
73 roundTrip(MacroBit
| 5, 11);
76 roundTrip(MacroBit
| Big
);
77 roundTrip(MacroBit
| (Big
+ 1));
80 TEST(SourceLocationEncoding
, Sequence
) {
81 roundTrip({1, 2, 3, 3, 2, 1},
83 5, // +2 (+1 of non-raw)
89 roundTrip({100, 0, 100},
95 roundTrip({1, Big
}, {2, ((Big
- 1) << 2) + 1});
96 roundTrip({2, MacroBit
| Big
}, {4, ((Big
- 1) << 2) - 1});
98 roundTrip({3, MacroBit
| 5, MacroBit
| 4, 3},
100 11, // +5 (+2 of non-raw + set macro bit)
102 6} // -3 (-2 of non-raw, clear macro bit)
106 {123 | MacroBit
, 1, 9, Biggest
, Big
, Big
+ 1, 0, MacroBit
| Big
, 0});