#include "clang/Lex/Preprocessor.h"
using namespace clang;
void Preprocessor::EnableBacktrackAtThisPos() {
BacktrackPositions.push_back(CachedLexPos);
EnterCachingLexMode();
}
void Preprocessor::CommitBacktrackedTokens() {
assert(!BacktrackPositions.empty()
&& "EnableBacktrackAtThisPos was not called!");
BacktrackPositions.pop_back();
}
void Preprocessor::Backtrack() {
assert(!BacktrackPositions.empty()
&& "EnableBacktrackAtThisPos was not called!");
CachedLexPos = BacktrackPositions.back();
BacktrackPositions.pop_back();
recomputeCurLexerKind();
}
void Preprocessor::CachingLex(Token &Result) {
if (!InCachingLexMode())
return;
if (CachedLexPos < CachedTokens.size()) {
Result = CachedTokens[CachedLexPos++];
return;
}
ExitCachingLexMode();
Lex(Result);
if (isBacktrackEnabled()) {
EnterCachingLexMode();
CachedTokens.push_back(Result);
++CachedLexPos;
return;
}
if (CachedLexPos < CachedTokens.size()) {
EnterCachingLexMode();
} else {
CachedTokens.clear();
CachedLexPos = 0;
}
}
void Preprocessor::EnterCachingLexMode() {
if (InCachingLexMode())
return;
PushIncludeMacroStack();
CurLexerKind = CLK_CachingLexer;
}
const Token &Preprocessor::PeekAhead(unsigned N) {
assert(CachedLexPos + N > CachedTokens.size() && "Confused caching.");
ExitCachingLexMode();
for (unsigned C = CachedLexPos + N - CachedTokens.size(); C > 0; --C) {
CachedTokens.push_back(Token());
Lex(CachedTokens.back());
}
EnterCachingLexMode();
return CachedTokens.back();
}
void Preprocessor::AnnotatePreviousCachedTokens(const Token &Tok) {
assert(Tok.isAnnotation() && "Expected annotation token");
assert(CachedLexPos != 0 && "Expected to have some cached tokens");
assert(CachedTokens[CachedLexPos-1].getLastLoc() == Tok.getAnnotationEndLoc()
&& "The annotation should be until the most recent cached token");
for (CachedTokensTy::size_type i = CachedLexPos; i != 0; --i) {
CachedTokensTy::iterator AnnotBegin = CachedTokens.begin() + i-1;
if (AnnotBegin->getLocation() == Tok.getLocation()) {
assert((BacktrackPositions.empty() || BacktrackPositions.back() < i) &&
"The backtrack pos points inside the annotated tokens!");
if (i < CachedLexPos)
CachedTokens.erase(AnnotBegin + 1, CachedTokens.begin() + CachedLexPos);
*AnnotBegin = Tok;
CachedLexPos = i;
return;
}
}
}