#include "clang/Serialization/SourceLocationEncoding.h"
#include "gtest/gtest.h"
#include <climits>
using namespace llvm;
using namespace clang;
namespace {
using LocSeq = SourceLocationSequence;
void roundTrip(SourceLocation::UIntTy Loc,
llvm::Optional<uint64_t> ExpectedEncoded = llvm::None) {
uint64_t ActualEncoded =
SourceLocationEncoding::encode(SourceLocation::getFromRawEncoding(Loc));
if (ExpectedEncoded)
ASSERT_EQ(ActualEncoded, *ExpectedEncoded) << "Encoding " << Loc;
SourceLocation::UIntTy DecodedEncoded =
SourceLocationEncoding::decode(ActualEncoded).getRawEncoding();
ASSERT_EQ(DecodedEncoded, Loc) << "Decoding " << ActualEncoded;
}
void roundTrip(std::vector<SourceLocation::UIntTy> Locs,
std::vector<uint64_t> ExpectedEncoded = {}) {
std::vector<uint64_t> ActualEncoded;
{
LocSeq::State Seq;
for (auto L : Locs)
ActualEncoded.push_back(SourceLocationEncoding::encode(
SourceLocation::getFromRawEncoding(L), Seq));
if (!ExpectedEncoded.empty())
ASSERT_EQ(ActualEncoded, ExpectedEncoded)
<< "Encoding " << testing::PrintToString(Locs);
}
std::vector<SourceLocation::UIntTy> DecodedEncoded;
{
LocSeq::State Seq;
for (auto L : ActualEncoded) {
SourceLocation Loc = SourceLocationEncoding::decode(L, Seq);
DecodedEncoded.push_back(Loc.getRawEncoding());
}
ASSERT_EQ(DecodedEncoded, Locs)
<< "Decoding " << testing::PrintToString(ActualEncoded);
}
}
constexpr SourceLocation::UIntTy MacroBit =
1 << (sizeof(SourceLocation::UIntTy) * CHAR_BIT - 1);
constexpr SourceLocation::UIntTy Big = MacroBit >> 1;
constexpr SourceLocation::UIntTy Biggest = -1;
TEST(SourceLocationEncoding, Individual) {
roundTrip(1, 2);
roundTrip(100, 200);
roundTrip(MacroBit, 1);
roundTrip(MacroBit | 5, 11);
roundTrip(Big);
roundTrip(Big + 1);
roundTrip(MacroBit | Big);
roundTrip(MacroBit | Big + 1);
}
TEST(SourceLocationEncoding, Sequence) {
roundTrip({1, 2, 3, 3, 2, 1},
{2, 5, 5, 1, 4, 4} );
roundTrip({100, 0, 100},
{200, 0, 1} );
roundTrip({1, Big}, {2, ((Big - 1) << 2) + 1});
roundTrip({2, MacroBit | Big}, {4, ((Big - 1) << 2) - 1});
roundTrip({3, MacroBit | 5, MacroBit | 4, 3},
{6, 11, 4, 6} );
roundTrip(
{123 | MacroBit, 1, 9, Biggest, Big, Big + 1, 0, MacroBit | Big, 0});
}
}