#include "clang/Tooling/Syntax/Tokens.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
using namespace clang;
using namespace clang::syntax;
namespace {
llvm::ArrayRef<syntax::Token>
getTokensCovering(llvm::ArrayRef<syntax::Token> Toks, SourceRange R,
const SourceManager &SM) {
if (R.isInvalid())
return {};
const syntax::Token *Begin =
llvm::partition_point(Toks, [&](const syntax::Token &T) {
return SM.isBeforeInTranslationUnit(T.location(), R.getBegin());
});
const syntax::Token *End =
llvm::partition_point(Toks, [&](const syntax::Token &T) {
return !SM.isBeforeInTranslationUnit(R.getEnd(), T.location());
});
if (Begin > End)
return {};
return {Begin, End};
}
SourceRange spelledForExpandedSlow(SourceLocation First, SourceLocation Last,
SourceLocation Prev, SourceLocation Next,
FileID TargetFile,
const SourceManager &SM) {
assert(SM.getSLocEntry(TargetFile).isFile());
while (First.isMacroID() && Last.isMacroID()) {
auto DecFirst = SM.getDecomposedLoc(First);
auto DecLast = SM.getDecomposedLoc(Last);
auto &ExpFirst = SM.getSLocEntry(DecFirst.first).getExpansion();
auto &ExpLast = SM.getSLocEntry(DecLast.first).getExpansion();
if (!ExpFirst.isMacroArgExpansion() || !ExpLast.isMacroArgExpansion())
break;
if (ExpFirst.getExpansionLocStart() != ExpLast.getExpansionLocStart())
break;
auto &ExpMacro =
SM.getSLocEntry(SM.getFileID(ExpFirst.getExpansionLocStart()))
.getExpansion();
if (ExpMacro.getExpansionLocStart().isMacroID())
break;
First = ExpFirst.getSpellingLoc().getLocWithOffset(DecFirst.second);
Last = ExpLast.getSpellingLoc().getLocWithOffset(DecLast.second);
auto AdjustBound = [&](SourceLocation &Bound) {
if (Bound.isInvalid() || !Bound.isMacroID()) return;
auto DecBound = SM.getDecomposedLoc(Bound);
auto &ExpBound = SM.getSLocEntry(DecBound.first).getExpansion();
if (ExpBound.isMacroArgExpansion() &&
ExpBound.getExpansionLocStart() == ExpFirst.getExpansionLocStart()) {
Bound = ExpBound.getSpellingLoc().getLocWithOffset(DecBound.second);
return;
}
while (Bound.isMacroID()) {
SourceRange Exp = SM.getImmediateExpansionRange(Bound).getAsRange();
if (Exp.getBegin() == ExpMacro.getExpansionLocStart()) {
Bound = (&Bound == &Prev) ? Exp.getBegin() : Exp.getEnd();
return;
}
Bound = (&Bound == &Prev) ? Exp.getEnd() : Exp.getBegin();
}
};
AdjustBound(Prev);
AdjustBound(Next);
}
SourceRange Candidate =
SM.getExpansionRange(SourceRange(First, Last)).getAsRange();
auto DecFirst = SM.getDecomposedExpansionLoc(Candidate.getBegin());
auto DecLast = SM.getDecomposedLoc(Candidate.getEnd());
if (Candidate.isInvalid() || DecFirst.first != TargetFile || DecLast.first != TargetFile)
return SourceRange();
if (Prev.isValid()) {
auto Dec = SM.getDecomposedLoc(SM.getExpansionRange(Prev).getBegin());
if (Dec.first != DecFirst.first || Dec.second >= DecFirst.second)
return SourceRange();
}
if (Next.isValid()) {
auto Dec = SM.getDecomposedLoc(SM.getExpansionRange(Next).getEnd());
if (Dec.first != DecLast.first || Dec.second <= DecLast.second)
return SourceRange();
}
return Candidate;
}
}
syntax::Token::Token(SourceLocation Location, unsigned Length,
tok::TokenKind Kind)
: Location(Location), Length(Length), Kind(Kind) {
assert(Location.isValid());
}
syntax::Token::Token(const clang::Token &T)
: Token(T.getLocation(), T.getLength(), T.getKind()) {
assert(!T.isAnnotation());
}
llvm::StringRef syntax::Token::text(const SourceManager &SM) const {
bool Invalid = false;
const char *Start = SM.getCharacterData(location(), &Invalid);
assert(!Invalid);
return llvm::StringRef(Start, length());
}
FileRange syntax::Token::range(const SourceManager &SM) const {
assert(location().isFileID() && "must be a spelled token");
FileID File;
unsigned StartOffset;
std::tie(File, StartOffset) = SM.getDecomposedLoc(location());
return FileRange(File, StartOffset, StartOffset + length());
}
FileRange syntax::Token::range(const SourceManager &SM,
const syntax::Token &First,
const syntax::Token &Last) {
auto F = First.range(SM);
auto L = Last.range(SM);
assert(F.file() == L.file() && "tokens from different files");
assert((F == L || F.endOffset() <= L.beginOffset()) &&
"wrong order of tokens");
return FileRange(F.file(), F.beginOffset(), L.endOffset());
}
llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS, const Token &T) {
return OS << T.str();
}
FileRange::FileRange(FileID File, unsigned BeginOffset, unsigned EndOffset)
: File(File), Begin(BeginOffset), End(EndOffset) {
assert(File.isValid());
assert(BeginOffset <= EndOffset);
}
FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc,
unsigned Length) {
assert(BeginLoc.isValid());
assert(BeginLoc.isFileID());
std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc);
End = Begin + Length;
}
FileRange::FileRange(const SourceManager &SM, SourceLocation BeginLoc,
SourceLocation EndLoc) {
assert(BeginLoc.isValid());
assert(BeginLoc.isFileID());
assert(EndLoc.isValid());
assert(EndLoc.isFileID());
assert(SM.getFileID(BeginLoc) == SM.getFileID(EndLoc));
assert(SM.getFileOffset(BeginLoc) <= SM.getFileOffset(EndLoc));
std::tie(File, Begin) = SM.getDecomposedLoc(BeginLoc);
End = SM.getFileOffset(EndLoc);
}
llvm::raw_ostream &syntax::operator<<(llvm::raw_ostream &OS,
const FileRange &R) {
return OS << llvm::formatv("FileRange(file = {0}, offsets = {1}-{2})",
R.file().getHashValue(), R.beginOffset(),
R.endOffset());
}
llvm::StringRef FileRange::text(const SourceManager &SM) const {
bool Invalid = false;
StringRef Text = SM.getBufferData(File, &Invalid);
if (Invalid)
return "";
assert(Begin <= Text.size());
assert(End <= Text.size());
return Text.substr(Begin, length());
}
void TokenBuffer::indexExpandedTokens() {
if (!ExpandedTokIndex.empty())
return;
ExpandedTokIndex.reserve(ExpandedTokens.size());
for (size_t I = 0, E = ExpandedTokens.size(); I != E; ++I) {
SourceLocation Loc = ExpandedTokens[I].location();
if (Loc.isValid())
ExpandedTokIndex[Loc] = I;
}
}
llvm::ArrayRef<syntax::Token> TokenBuffer::expandedTokens(SourceRange R) const {
if (R.isInvalid())
return {};
if (!ExpandedTokIndex.empty()) {
const auto B = ExpandedTokIndex.find(R.getBegin());
const auto E = ExpandedTokIndex.find(R.getEnd());
if (B != ExpandedTokIndex.end() && E != ExpandedTokIndex.end()) {
const Token *L = ExpandedTokens.data() + B->getSecond();
const Token *R = ExpandedTokens.data() + E->getSecond() + 1;
if (L > R)
return {};
return {L, R};
}
}
return getTokensCovering(expandedTokens(), R, *SourceMgr);
}
CharSourceRange FileRange::toCharRange(const SourceManager &SM) const {
return CharSourceRange(
SourceRange(SM.getComposedLoc(File, Begin), SM.getComposedLoc(File, End)),
false);
}
std::pair<const syntax::Token *, const TokenBuffer::Mapping *>
TokenBuffer::spelledForExpandedToken(const syntax::Token *Expanded) const {
assert(Expanded);
assert(ExpandedTokens.data() <= Expanded &&
Expanded < ExpandedTokens.data() + ExpandedTokens.size());
auto FileIt = Files.find(
SourceMgr->getFileID(SourceMgr->getExpansionLoc(Expanded->location())));
assert(FileIt != Files.end() && "no file for an expanded token");
const MarkedFile &File = FileIt->second;
unsigned ExpandedIndex = Expanded - ExpandedTokens.data();
auto It = llvm::partition_point(File.Mappings, [&](const Mapping &M) {
return M.BeginExpanded <= ExpandedIndex;
});
if (It == File.Mappings.begin()) {
return {&File.SpelledTokens[ExpandedIndex - File.BeginExpanded],
nullptr};
}
--It;
if (ExpandedIndex < It->EndExpanded)
return {&File.SpelledTokens[It->BeginSpelled], &*It};
return {
&File.SpelledTokens[It->EndSpelled + (ExpandedIndex - It->EndExpanded)],
nullptr};
}
const TokenBuffer::Mapping *
TokenBuffer::mappingStartingBeforeSpelled(const MarkedFile &F,
const syntax::Token *Spelled) {
assert(F.SpelledTokens.data() <= Spelled);
unsigned SpelledI = Spelled - F.SpelledTokens.data();
assert(SpelledI < F.SpelledTokens.size());
auto It = llvm::partition_point(F.Mappings, [SpelledI](const Mapping &M) {
return M.BeginSpelled <= SpelledI;
});
if (It == F.Mappings.begin())
return nullptr;
--It;
return &*It;
}
llvm::SmallVector<llvm::ArrayRef<syntax::Token>, 1>
TokenBuffer::expandedForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const {
if (Spelled.empty())
return {};
const auto &File = fileForSpelled(Spelled);
auto *FrontMapping = mappingStartingBeforeSpelled(File, &Spelled.front());
unsigned SpelledFrontI = &Spelled.front() - File.SpelledTokens.data();
assert(SpelledFrontI < File.SpelledTokens.size());
unsigned ExpandedBegin;
if (!FrontMapping) {
ExpandedBegin = File.BeginExpanded + SpelledFrontI;
} else if (SpelledFrontI < FrontMapping->EndSpelled) {
if (SpelledFrontI != FrontMapping->BeginSpelled) {
return {}; }
ExpandedBegin = FrontMapping->BeginExpanded;
} else {
ExpandedBegin =
FrontMapping->EndExpanded + (SpelledFrontI - FrontMapping->EndSpelled);
}
auto *BackMapping = mappingStartingBeforeSpelled(File, &Spelled.back());
unsigned SpelledBackI = &Spelled.back() - File.SpelledTokens.data();
unsigned ExpandedEnd;
if (!BackMapping) {
ExpandedEnd = File.BeginExpanded + SpelledBackI + 1;
} else if (SpelledBackI < BackMapping->EndSpelled) {
if (SpelledBackI + 1 != BackMapping->EndSpelled) {
return {}; }
ExpandedEnd = BackMapping->EndExpanded;
} else {
ExpandedEnd =
BackMapping->EndExpanded + (SpelledBackI - BackMapping->EndSpelled) + 1;
}
assert(ExpandedBegin < ExpandedTokens.size());
assert(ExpandedEnd < ExpandedTokens.size());
if (ExpandedBegin == ExpandedEnd)
return {};
return {llvm::makeArrayRef(ExpandedTokens.data() + ExpandedBegin,
ExpandedTokens.data() + ExpandedEnd)};
}
llvm::ArrayRef<syntax::Token> TokenBuffer::spelledTokens(FileID FID) const {
auto It = Files.find(FID);
assert(It != Files.end());
return It->second.SpelledTokens;
}
const syntax::Token *TokenBuffer::spelledTokenAt(SourceLocation Loc) const {
assert(Loc.isFileID());
const auto *Tok = llvm::partition_point(
spelledTokens(SourceMgr->getFileID(Loc)),
[&](const syntax::Token &Tok) { return Tok.location() < Loc; });
if (!Tok || Tok->location() != Loc)
return nullptr;
return Tok;
}
std::string TokenBuffer::Mapping::str() const {
return std::string(
llvm::formatv("spelled tokens: [{0},{1}), expanded tokens: [{2},{3})",
BeginSpelled, EndSpelled, BeginExpanded, EndExpanded));
}
llvm::Optional<llvm::ArrayRef<syntax::Token>>
TokenBuffer::spelledForExpanded(llvm::ArrayRef<syntax::Token> Expanded) const {
if (Expanded.empty())
return llvm::None;
const syntax::Token *First = &Expanded.front();
const syntax::Token *Last = &Expanded.back();
const syntax::Token *FirstSpelled, *LastSpelled;
const TokenBuffer::Mapping *FirstMapping, *LastMapping;
std::tie(FirstSpelled, FirstMapping) = spelledForExpandedToken(First);
std::tie(LastSpelled, LastMapping) = spelledForExpandedToken(Last);
FileID FID = SourceMgr->getFileID(FirstSpelled->location());
if (FID != SourceMgr->getFileID(LastSpelled->location()))
return llvm::None;
const MarkedFile &File = Files.find(FID)->second;
if (FirstMapping && FirstMapping == LastMapping &&
SourceMgr->isMacroArgExpansion(First->location()) &&
SourceMgr->isMacroArgExpansion(Last->location())) {
SourceLocation Prev = (First == &ExpandedTokens.front())
? SourceLocation()
: (First - 1)->location();
SourceLocation Next = (Last == &ExpandedTokens.back())
? SourceLocation()
: (Last + 1)->location();
SourceRange Range = spelledForExpandedSlow(
First->location(), Last->location(), Prev, Next, FID, *SourceMgr);
if (Range.isInvalid())
return llvm::None;
return getTokensCovering(File.SpelledTokens, Range, *SourceMgr);
}
unsigned FirstExpanded = Expanded.begin() - ExpandedTokens.data();
unsigned LastExpanded = Expanded.end() - ExpandedTokens.data();
if (FirstMapping && FirstExpanded != FirstMapping->BeginExpanded)
return llvm::None;
if (LastMapping && LastMapping->EndExpanded != LastExpanded)
return llvm::None;
return llvm::makeArrayRef(
FirstMapping ? File.SpelledTokens.data() + FirstMapping->BeginSpelled
: FirstSpelled,
LastMapping ? File.SpelledTokens.data() + LastMapping->EndSpelled
: LastSpelled + 1);
}
TokenBuffer::Expansion TokenBuffer::makeExpansion(const MarkedFile &F,
const Mapping &M) const {
Expansion E;
E.Spelled = llvm::makeArrayRef(F.SpelledTokens.data() + M.BeginSpelled,
F.SpelledTokens.data() + M.EndSpelled);
E.Expanded = llvm::makeArrayRef(ExpandedTokens.data() + M.BeginExpanded,
ExpandedTokens.data() + M.EndExpanded);
return E;
}
const TokenBuffer::MarkedFile &
TokenBuffer::fileForSpelled(llvm::ArrayRef<syntax::Token> Spelled) const {
assert(!Spelled.empty());
assert(Spelled.front().location().isFileID() && "not a spelled token");
auto FileIt = Files.find(SourceMgr->getFileID(Spelled.front().location()));
assert(FileIt != Files.end() && "file not tracked by token buffer");
const auto &File = FileIt->second;
assert(File.SpelledTokens.data() <= Spelled.data() &&
Spelled.end() <=
(File.SpelledTokens.data() + File.SpelledTokens.size()) &&
"Tokens not in spelled range");
#ifndef NDEBUG
auto T1 = Spelled.back().location();
auto T2 = File.SpelledTokens.back().location();
assert(T1 == T2 || sourceManager().isBeforeInTranslationUnit(T1, T2));
#endif
return File;
}
llvm::Optional<TokenBuffer::Expansion>
TokenBuffer::expansionStartingAt(const syntax::Token *Spelled) const {
assert(Spelled);
const auto &File = fileForSpelled(*Spelled);
unsigned SpelledIndex = Spelled - File.SpelledTokens.data();
auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) {
return M.BeginSpelled < SpelledIndex;
});
if (M == File.Mappings.end() || M->BeginSpelled != SpelledIndex)
return llvm::None;
return makeExpansion(File, *M);
}
std::vector<TokenBuffer::Expansion> TokenBuffer::expansionsOverlapping(
llvm::ArrayRef<syntax::Token> Spelled) const {
if (Spelled.empty())
return {};
const auto &File = fileForSpelled(Spelled);
unsigned SpelledBeginIndex = Spelled.begin() - File.SpelledTokens.data();
unsigned SpelledEndIndex = Spelled.end() - File.SpelledTokens.data();
auto M = llvm::partition_point(File.Mappings, [&](const Mapping &M) {
return M.EndSpelled <= SpelledBeginIndex;
});
std::vector<TokenBuffer::Expansion> Expansions;
for (; M != File.Mappings.end() && M->BeginSpelled < SpelledEndIndex; ++M)
Expansions.push_back(makeExpansion(File, *M));
return Expansions;
}
llvm::ArrayRef<syntax::Token>
syntax::spelledTokensTouching(SourceLocation Loc,
llvm::ArrayRef<syntax::Token> Tokens) {
assert(Loc.isFileID());
auto *Right = llvm::partition_point(
Tokens, [&](const syntax::Token &Tok) { return Tok.location() < Loc; });
bool AcceptRight = Right != Tokens.end() && Right->location() <= Loc;
bool AcceptLeft =
Right != Tokens.begin() && (Right - 1)->endLocation() >= Loc;
return llvm::makeArrayRef(Right - (AcceptLeft ? 1 : 0),
Right + (AcceptRight ? 1 : 0));
}
llvm::ArrayRef<syntax::Token>
syntax::spelledTokensTouching(SourceLocation Loc,
const syntax::TokenBuffer &Tokens) {
return spelledTokensTouching(
Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc)));
}
const syntax::Token *
syntax::spelledIdentifierTouching(SourceLocation Loc,
llvm::ArrayRef<syntax::Token> Tokens) {
for (const syntax::Token &Tok : spelledTokensTouching(Loc, Tokens)) {
if (Tok.kind() == tok::identifier)
return &Tok;
}
return nullptr;
}
const syntax::Token *
syntax::spelledIdentifierTouching(SourceLocation Loc,
const syntax::TokenBuffer &Tokens) {
return spelledIdentifierTouching(
Loc, Tokens.spelledTokens(Tokens.sourceManager().getFileID(Loc)));
}
std::vector<const syntax::Token *>
TokenBuffer::macroExpansions(FileID FID) const {
auto FileIt = Files.find(FID);
assert(FileIt != Files.end() && "file not tracked by token buffer");
auto &File = FileIt->second;
std::vector<const syntax::Token *> Expansions;
auto &Spelled = File.SpelledTokens;
for (auto Mapping : File.Mappings) {
const syntax::Token *Token = &Spelled[Mapping.BeginSpelled];
if (Token->kind() == tok::TokenKind::identifier)
Expansions.push_back(Token);
}
return Expansions;
}
std::vector<syntax::Token> syntax::tokenize(const FileRange &FR,
const SourceManager &SM,
const LangOptions &LO) {
std::vector<syntax::Token> Tokens;
IdentifierTable Identifiers(LO);
auto AddToken = [&](clang::Token T) {
if (T.getKind() == tok::raw_identifier && !T.needsCleaning() &&
!T.hasUCN()) { clang::IdentifierInfo &II = Identifiers.get(T.getRawIdentifier());
T.setIdentifierInfo(&II);
T.setKind(II.getTokenID());
}
Tokens.push_back(syntax::Token(T));
};
auto SrcBuffer = SM.getBufferData(FR.file());
Lexer L(SM.getLocForStartOfFile(FR.file()), LO, SrcBuffer.data(),
SrcBuffer.data() + FR.beginOffset(),
SrcBuffer.data() + SrcBuffer.size());
clang::Token T;
while (!L.LexFromRawLexer(T) && L.getCurrentBufferOffset() < FR.endOffset())
AddToken(T);
if (SM.getFileOffset(T.getLocation()) < FR.endOffset())
AddToken(T);
return Tokens;
}
std::vector<syntax::Token> syntax::tokenize(FileID FID, const SourceManager &SM,
const LangOptions &LO) {
return tokenize(syntax::FileRange(FID, 0, SM.getFileIDSize(FID)), SM, LO);
}
class TokenCollector::CollectPPExpansions : public PPCallbacks {
public:
CollectPPExpansions(TokenCollector &C) : Collector(&C) {}
void disable() { Collector = nullptr; }
void MacroExpands(const clang::Token &MacroNameTok, const MacroDefinition &MD,
SourceRange Range, const MacroArgs *Args) override {
if (!Collector)
return;
const auto &SM = Collector->PP.getSourceManager();
if (!Range.getEnd().isFileID())
return;
if (LastExpansionEnd.isValid() &&
!SM.isBeforeInTranslationUnit(LastExpansionEnd, Range.getEnd()))
return;
if (!Range.getBegin().isFileID()) {
Range.setBegin(SM.getExpansionLoc(Range.getBegin()));
assert(Collector->Expansions.count(Range.getBegin()) &&
"Overlapping macros should have same expansion location");
}
Collector->Expansions[Range.getBegin()] = Range.getEnd();
LastExpansionEnd = Range.getEnd();
}
private:
TokenCollector *Collector;
SourceLocation LastExpansionEnd;
};
TokenCollector::TokenCollector(Preprocessor &PP) : PP(PP) {
PP.setTokenWatcher([this](const clang::Token &T) {
if (T.isAnnotation())
return;
DEBUG_WITH_TYPE("collect-tokens", llvm::dbgs()
<< "Token: "
<< syntax::Token(T).dumpForTests(
this->PP.getSourceManager())
<< "\n"
);
Expanded.push_back(syntax::Token(T));
});
auto CB = std::make_unique<CollectPPExpansions>(*this);
this->Collector = CB.get();
PP.addPPCallbacks(std::move(CB));
}
class TokenCollector::Builder {
public:
Builder(std::vector<syntax::Token> Expanded, PPExpansions CollectedExpansions,
const SourceManager &SM, const LangOptions &LangOpts)
: Result(SM), CollectedExpansions(std::move(CollectedExpansions)), SM(SM),
LangOpts(LangOpts) {
Result.ExpandedTokens = std::move(Expanded);
}
TokenBuffer build() && {
assert(!Result.ExpandedTokens.empty());
assert(Result.ExpandedTokens.back().kind() == tok::eof);
buildSpelledTokens();
while (NextExpanded < Result.ExpandedTokens.size() - 1 ) {
discard();
unsigned OldPosition = NextExpanded;
advance();
if (NextExpanded == OldPosition)
diagnoseAdvanceFailure();
}
for (const auto &File : Result.Files)
discard(File.first);
#ifndef NDEBUG
for (auto &pair : Result.Files) {
auto &mappings = pair.second.Mappings;
assert(llvm::is_sorted(mappings, [](const TokenBuffer::Mapping &M1,
const TokenBuffer::Mapping &M2) {
return M1.BeginSpelled < M2.BeginSpelled &&
M1.EndSpelled < M2.EndSpelled &&
M1.BeginExpanded < M2.BeginExpanded &&
M1.EndExpanded < M2.EndExpanded;
}));
}
#endif
return std::move(Result);
}
private:
void discard(llvm::Optional<FileID> Drain = llvm::None) {
SourceLocation Target =
Drain ? SM.getLocForEndOfFile(*Drain)
: SM.getExpansionLoc(
Result.ExpandedTokens[NextExpanded].location());
FileID File = SM.getFileID(Target);
const auto &SpelledTokens = Result.Files[File].SpelledTokens;
auto &NextSpelled = this->NextSpelled[File];
TokenBuffer::Mapping Mapping;
Mapping.BeginSpelled = NextSpelled;
Mapping.BeginExpanded = Mapping.EndExpanded =
Drain ? Result.Files[*Drain].EndExpanded : NextExpanded;
auto FlushMapping = [&, this] {
Mapping.EndSpelled = NextSpelled;
if (Mapping.BeginSpelled != Mapping.EndSpelled)
Result.Files[File].Mappings.push_back(Mapping);
Mapping.BeginSpelled = NextSpelled;
};
while (NextSpelled < SpelledTokens.size() &&
SpelledTokens[NextSpelled].location() < Target) {
SourceLocation KnownEnd =
CollectedExpansions.lookup(SpelledTokens[NextSpelled].location());
if (KnownEnd.isValid()) {
FlushMapping(); while (NextSpelled < SpelledTokens.size() &&
SpelledTokens[NextSpelled].location() <= KnownEnd)
++NextSpelled;
FlushMapping(); } else {
++NextSpelled;
}
}
FlushMapping();
}
void advance() {
const syntax::Token &Tok = Result.ExpandedTokens[NextExpanded];
SourceLocation Expansion = SM.getExpansionLoc(Tok.location());
FileID File = SM.getFileID(Expansion);
const auto &SpelledTokens = Result.Files[File].SpelledTokens;
auto &NextSpelled = this->NextSpelled[File];
if (Tok.location().isFileID()) {
while (NextSpelled < SpelledTokens.size() &&
NextExpanded < Result.ExpandedTokens.size() &&
SpelledTokens[NextSpelled].location() ==
Result.ExpandedTokens[NextExpanded].location()) {
++NextSpelled;
++NextExpanded;
}
} else {
auto End = CollectedExpansions.lookup(Expansion);
assert(End.isValid() && "Macro expansion wasn't captured?");
TokenBuffer::Mapping Mapping;
Mapping.BeginExpanded = NextExpanded;
Mapping.BeginSpelled = NextSpelled;
while (NextSpelled < SpelledTokens.size() &&
SpelledTokens[NextSpelled].location() <= End)
++NextSpelled;
while (NextExpanded < Result.ExpandedTokens.size() &&
SM.getExpansionLoc(
Result.ExpandedTokens[NextExpanded].location()) == Expansion)
++NextExpanded;
Mapping.EndExpanded = NextExpanded;
Mapping.EndSpelled = NextSpelled;
Result.Files[File].Mappings.push_back(Mapping);
}
}
void diagnoseAdvanceFailure() {
#ifndef NDEBUG
for (unsigned I = (NextExpanded < 10) ? 0 : NextExpanded - 10;
I < NextExpanded + 5 && I < Result.ExpandedTokens.size(); ++I) {
const char *L =
(I == NextExpanded) ? "!! " : (I < NextExpanded) ? "ok " : " ";
llvm::errs() << L << Result.ExpandedTokens[I].dumpForTests(SM) << "\n";
}
#endif
llvm_unreachable("Couldn't map expanded token to spelled tokens!");
}
void buildSpelledTokens() {
for (unsigned I = 0; I < Result.ExpandedTokens.size(); ++I) {
const auto &Tok = Result.ExpandedTokens[I];
auto FID = SM.getFileID(SM.getExpansionLoc(Tok.location()));
auto It = Result.Files.try_emplace(FID);
TokenBuffer::MarkedFile &File = It.first->second;
File.EndExpanded = Tok.kind() == tok::eof ? I : I + 1;
if (!It.second)
continue; File.BeginExpanded = I;
File.SpelledTokens = tokenize(FID, SM, LangOpts);
}
}
TokenBuffer Result;
unsigned NextExpanded = 0; llvm::DenseMap<FileID, unsigned> NextSpelled; PPExpansions CollectedExpansions;
const SourceManager &SM;
const LangOptions &LangOpts;
};
TokenBuffer TokenCollector::consume() && {
PP.setTokenWatcher(nullptr);
Collector->disable();
return Builder(std::move(Expanded), std::move(Expansions),
PP.getSourceManager(), PP.getLangOpts())
.build();
}
std::string syntax::Token::str() const {
return std::string(llvm::formatv("Token({0}, length = {1})",
tok::getTokenName(kind()), length()));
}
std::string syntax::Token::dumpForTests(const SourceManager &SM) const {
return std::string(llvm::formatv("Token(`{0}`, {1}, length = {2})", text(SM),
tok::getTokenName(kind()), length()));
}
std::string TokenBuffer::dumpForTests() const {
auto PrintToken = [this](const syntax::Token &T) -> std::string {
if (T.kind() == tok::eof)
return "<eof>";
return std::string(T.text(*SourceMgr));
};
auto DumpTokens = [this, &PrintToken](llvm::raw_ostream &OS,
llvm::ArrayRef<syntax::Token> Tokens) {
if (Tokens.empty()) {
OS << "<empty>";
return;
}
OS << Tokens[0].text(*SourceMgr);
for (unsigned I = 1; I < Tokens.size(); ++I) {
if (Tokens[I].kind() == tok::eof)
continue;
OS << " " << PrintToken(Tokens[I]);
}
};
std::string Dump;
llvm::raw_string_ostream OS(Dump);
OS << "expanded tokens:\n"
<< " ";
DumpTokens(OS, llvm::makeArrayRef(ExpandedTokens).drop_back());
OS << "\n";
std::vector<FileID> Keys;
for (auto F : Files)
Keys.push_back(F.first);
llvm::sort(Keys);
for (FileID ID : Keys) {
const MarkedFile &File = Files.find(ID)->second;
auto *Entry = SourceMgr->getFileEntryForID(ID);
if (!Entry)
continue; OS << llvm::formatv("file '{0}'\n", Entry->getName())
<< " spelled tokens:\n"
<< " ";
DumpTokens(OS, File.SpelledTokens);
OS << "\n";
if (File.Mappings.empty()) {
OS << " no mappings.\n";
continue;
}
OS << " mappings:\n";
for (auto &M : File.Mappings) {
OS << llvm::formatv(
" ['{0}'_{1}, '{2}'_{3}) => ['{4}'_{5}, '{6}'_{7})\n",
PrintToken(File.SpelledTokens[M.BeginSpelled]), M.BeginSpelled,
M.EndSpelled == File.SpelledTokens.size()
? "<eof>"
: PrintToken(File.SpelledTokens[M.EndSpelled]),
M.EndSpelled, PrintToken(ExpandedTokens[M.BeginExpanded]),
M.BeginExpanded, PrintToken(ExpandedTokens[M.EndExpanded]),
M.EndExpanded);
}
}
return Dump;
}