#include "FormatTokenLexer.h"
#include "FormatToken.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "llvm/Support/Regex.h"
namespace clang {
namespace format {
FormatTokenLexer::FormatTokenLexer(
const SourceManager &SourceMgr, FileID ID, unsigned Column,
const FormatStyle &Style, encoding::Encoding Encoding,
llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
IdentifierTable &IdentTable)
: FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
Column(Column), TrailingWhitespace(0),
LangOpts(getFormattingLangOpts(Style)), SourceMgr(SourceMgr), ID(ID),
Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
MacroBlockEndRegex(Style.MacroBlockEnd) {
Lex.reset(new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts));
Lex->SetKeepWhitespaceMode(true);
for (const std::string &ForEachMacro : Style.ForEachMacros) {
auto Identifier = &IdentTable.get(ForEachMacro);
Macros.insert({Identifier, TT_ForEachMacro});
}
for (const std::string &IfMacro : Style.IfMacros) {
auto Identifier = &IdentTable.get(IfMacro);
Macros.insert({Identifier, TT_IfMacro});
}
for (const std::string &AttributeMacro : Style.AttributeMacros) {
auto Identifier = &IdentTable.get(AttributeMacro);
Macros.insert({Identifier, TT_AttributeMacro});
}
for (const std::string &StatementMacro : Style.StatementMacros) {
auto Identifier = &IdentTable.get(StatementMacro);
Macros.insert({Identifier, TT_StatementMacro});
}
for (const std::string &TypenameMacro : Style.TypenameMacros) {
auto Identifier = &IdentTable.get(TypenameMacro);
Macros.insert({Identifier, TT_TypenameMacro});
}
for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
auto Identifier = &IdentTable.get(NamespaceMacro);
Macros.insert({Identifier, TT_NamespaceMacro});
}
for (const std::string &WhitespaceSensitiveMacro :
Style.WhitespaceSensitiveMacros) {
auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
Macros.insert({Identifier, TT_UntouchableMacroFunc});
}
for (const std::string &StatementAttributeLikeMacro :
Style.StatementAttributeLikeMacros) {
auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
}
}
ArrayRef<FormatToken *> FormatTokenLexer::lex() {
assert(Tokens.empty());
assert(FirstInLineIndex == 0);
do {
Tokens.push_back(getNextToken());
if (Style.isJavaScript()) {
tryParseJSRegexLiteral();
handleTemplateStrings();
}
if (Style.Language == FormatStyle::LK_TextProto)
tryParsePythonComment();
tryMergePreviousTokens();
if (Style.isCSharp()) {
handleCSharpVerbatimAndInterpolatedStrings();
}
if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
FirstInLineIndex = Tokens.size() - 1;
} while (Tokens.back()->isNot(tok::eof));
return Tokens;
}
void FormatTokenLexer::tryMergePreviousTokens() {
if (tryMerge_TMacro())
return;
if (tryMergeConflictMarkers())
return;
if (tryMergeLessLess())
return;
if (tryMergeForEach())
return;
if (Style.isCpp() && tryTransformTryUsageForC())
return;
if (Style.isJavaScript() || Style.isCSharp()) {
static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
tok::question};
static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
tok::period};
static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
if (tryMergeTokens(FatArrow, TT_FatArrow))
return;
if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
Tokens.back()->Tok.setKind(tok::pipepipe);
return;
}
if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
Tokens.back()->Tok.setKind(tok::period);
return;
}
if (tryMergeNullishCoalescingEqual())
return;
}
if (Style.isCSharp()) {
static const tok::TokenKind CSharpNullConditionalLSquare[] = {
tok::question, tok::l_square};
if (tryMergeCSharpKeywordVariables())
return;
if (tryMergeCSharpStringLiteral())
return;
if (tryTransformCSharpForEach())
return;
if (tryMergeTokens(CSharpNullConditionalLSquare,
TT_CSharpNullConditionalLSquare)) {
Tokens.back()->Tok.setKind(tok::l_square);
return;
}
}
if (tryMergeNSStringLiteral())
return;
if (Style.isJavaScript()) {
static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
tok::equal};
static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
tok::greaterequal};
static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
tok::starequal};
static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
return;
if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
return;
if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
return;
if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
return;
if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
Tokens.back()->Tok.setKind(tok::starequal);
return;
}
if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
Tokens.back()->Tok.setKind(tok::equal);
return;
}
if (tryMergeJSPrivateIdentifier())
return;
}
if (Style.Language == FormatStyle::LK_Java) {
static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
tok::greater, tok::greater, tok::greaterequal};
if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
return;
}
}
bool FormatTokenLexer::tryMergeNSStringLiteral() {
if (Tokens.size() < 2)
return false;
auto &At = *(Tokens.end() - 2);
auto &String = *(Tokens.end() - 1);
if (!At->is(tok::at) || !String->is(tok::string_literal))
return false;
At->Tok.setKind(tok::string_literal);
At->TokenText = StringRef(At->TokenText.begin(),
String->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += String->ColumnWidth;
At->setType(TT_ObjCStringLiteral);
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
if (Tokens.size() < 2)
return false;
auto &Hash = *(Tokens.end() - 2);
auto &Identifier = *(Tokens.end() - 1);
if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier))
return false;
Hash->Tok.setKind(tok::identifier);
Hash->TokenText =
StringRef(Hash->TokenText.begin(),
Identifier->TokenText.end() - Hash->TokenText.begin());
Hash->ColumnWidth += Identifier->ColumnWidth;
Hash->setType(TT_JsPrivateIdentifier);
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
if (Tokens.size() < 2)
return false;
auto &String = *(Tokens.end() - 1);
if (!String->is(tok::string_literal))
return false;
auto &At = *(Tokens.end() - 2);
if (!(At->is(tok::at) || At->TokenText == "$"))
return false;
if (Tokens.size() > 2 && At->is(tok::at)) {
auto &Dollar = *(Tokens.end() - 3);
if (Dollar->TokenText == "$") {
Dollar->Tok.setKind(tok::string_literal);
Dollar->TokenText =
StringRef(Dollar->TokenText.begin(),
String->TokenText.end() - Dollar->TokenText.begin());
Dollar->ColumnWidth += (At->ColumnWidth + String->ColumnWidth);
Dollar->setType(TT_CSharpStringLiteral);
Tokens.erase(Tokens.end() - 2);
Tokens.erase(Tokens.end() - 1);
return true;
}
}
At->Tok.setKind(tok::string_literal);
At->TokenText = StringRef(At->TokenText.begin(),
String->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += String->ColumnWidth;
At->setType(TT_CSharpStringLiteral);
Tokens.erase(Tokens.end() - 1);
return true;
}
const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
"assembly", "module", "field", "event", "method",
"param", "property", "return", "type",
};
bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
if (Tokens.size() < 2)
return false;
auto &NullishCoalescing = *(Tokens.end() - 2);
auto &Equal = *(Tokens.end() - 1);
if (NullishCoalescing->getType() != TT_NullCoalescingOperator ||
!Equal->is(tok::equal)) {
return false;
}
NullishCoalescing->Tok.setKind(tok::equal); NullishCoalescing->TokenText =
StringRef(NullishCoalescing->TokenText.begin(),
Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
NullishCoalescing->ColumnWidth += Equal->ColumnWidth;
NullishCoalescing->setType(TT_NullCoalescingEqual);
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
if (Tokens.size() < 2)
return false;
auto &At = *(Tokens.end() - 2);
auto &Keyword = *(Tokens.end() - 1);
if (!At->is(tok::at))
return false;
if (!Keywords.isCSharpKeyword(*Keyword))
return false;
At->Tok.setKind(tok::identifier);
At->TokenText = StringRef(At->TokenText.begin(),
Keyword->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += Keyword->ColumnWidth;
At->setType(Keyword->getType());
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryTransformCSharpForEach() {
if (Tokens.size() < 1)
return false;
auto &Identifier = *(Tokens.end() - 1);
if (!Identifier->is(tok::identifier))
return false;
if (Identifier->TokenText != "foreach")
return false;
Identifier->setType(TT_ForEachMacro);
Identifier->Tok.setKind(tok::kw_for);
return true;
}
bool FormatTokenLexer::tryMergeForEach() {
if (Tokens.size() < 2)
return false;
auto &For = *(Tokens.end() - 2);
auto &Each = *(Tokens.end() - 1);
if (!For->is(tok::kw_for))
return false;
if (!Each->is(tok::identifier))
return false;
if (Each->TokenText != "each")
return false;
For->setType(TT_ForEachMacro);
For->Tok.setKind(tok::kw_for);
For->TokenText = StringRef(For->TokenText.begin(),
Each->TokenText.end() - For->TokenText.begin());
For->ColumnWidth += Each->ColumnWidth;
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryTransformTryUsageForC() {
if (Tokens.size() < 2)
return false;
auto &Try = *(Tokens.end() - 2);
if (!Try->is(tok::kw_try))
return false;
auto &Next = *(Tokens.end() - 1);
if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
return false;
if (Tokens.size() > 2) {
auto &At = *(Tokens.end() - 3);
if (At->is(tok::at))
return false;
}
Try->Tok.setKind(tok::identifier);
return true;
}
bool FormatTokenLexer::tryMergeLessLess() {
if (Tokens.size() < 3)
return false;
auto First = Tokens.end() - 3;
if (First[0]->isNot(tok::less) || First[1]->isNot(tok::less))
return false;
if (First[1]->hasWhitespaceBefore())
return false;
auto X = Tokens.size() > 3 ? First[-1] : nullptr;
auto Y = First[2];
if ((X && X->is(tok::less)) || Y->is(tok::less))
return false;
if (X && X->is(tok::kw_operator) && Y->is(tok::greater))
return false;
First[0]->Tok.setKind(tok::lessless);
First[0]->TokenText = "<<";
First[0]->ColumnWidth += 1;
Tokens.erase(Tokens.end() - 2);
return true;
}
bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
TokenType NewType) {
if (Tokens.size() < Kinds.size())
return false;
SmallVectorImpl<FormatToken *>::const_iterator First =
Tokens.end() - Kinds.size();
if (!First[0]->is(Kinds[0]))
return false;
unsigned AddLength = 0;
for (unsigned i = 1; i < Kinds.size(); ++i) {
if (!First[i]->is(Kinds[i]) || First[i]->hasWhitespaceBefore())
return false;
AddLength += First[i]->TokenText.size();
}
Tokens.resize(Tokens.size() - Kinds.size() + 1);
First[0]->TokenText = StringRef(First[0]->TokenText.data(),
First[0]->TokenText.size() + AddLength);
First[0]->ColumnWidth += AddLength;
First[0]->setType(NewType);
return true;
}
bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
tok::colon, tok::question, tok::tilde) ||
Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
Tok->isBinaryOperator();
}
bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
if (!Prev)
return true;
if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
if (!precedesOperand(Prev))
return false;
return true;
}
void FormatTokenLexer::tryParseJSRegexLiteral() {
FormatToken *RegexToken = Tokens.back();
if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
return;
FormatToken *Prev = nullptr;
for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
if (FT->isNot(tok::comment)) {
Prev = FT;
break;
}
}
if (!canPrecedeRegexLiteral(Prev))
return;
const char *Offset = Lex->getBufferLocation();
const char *RegexBegin = Offset - RegexToken->TokenText.size();
StringRef Buffer = Lex->getBuffer();
bool InCharacterClass = false;
bool HaveClosingSlash = false;
for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
switch (*Offset) {
case '\\':
++Offset;
break;
case '[':
InCharacterClass = true;
break;
case ']':
InCharacterClass = false;
break;
case '/':
if (!InCharacterClass)
HaveClosingSlash = true;
break;
}
}
RegexToken->setType(TT_RegexLiteral);
RegexToken->Tok.setKind(tok::string_literal);
RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
RegexToken->ColumnWidth = RegexToken->TokenText.size();
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
}
static auto lexCSharpString(const char *Begin, const char *End, bool Verbatim,
bool Interpolated) {
auto Repeated = [&Begin, End]() {
return Begin + 1 < End && Begin[1] == Begin[0];
};
for (int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
switch (*Begin) {
case '\\':
if (!Verbatim)
++Begin;
break;
case '{':
if (Interpolated) {
if (Repeated())
++Begin;
else
++UnmatchedOpeningBraceCount;
}
break;
case '}':
if (Interpolated) {
if (Repeated())
++Begin;
else if (UnmatchedOpeningBraceCount > 0)
--UnmatchedOpeningBraceCount;
else
return End;
}
break;
case '"':
if (UnmatchedOpeningBraceCount > 0)
break;
if (Verbatim && Repeated()) {
++Begin;
break;
}
return Begin;
}
}
return End;
}
void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
FormatToken *CSharpStringLiteral = Tokens.back();
if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
return;
auto &TokenText = CSharpStringLiteral->TokenText;
bool Verbatim = false;
bool Interpolated = false;
if (TokenText.startswith(R"($@")")) {
Verbatim = true;
Interpolated = true;
} else if (TokenText.startswith(R"(@")")) {
Verbatim = true;
} else if (TokenText.startswith(R"($")")) {
Interpolated = true;
}
if (!Verbatim && !Interpolated)
return;
const char *StrBegin = Lex->getBufferLocation() - TokenText.size();
const char *Offset = StrBegin;
if (Verbatim && Interpolated)
Offset += 3;
else
Offset += 2;
const auto End = Lex->getBuffer().end();
Offset = lexCSharpString(Offset, End, Verbatim, Interpolated);
if (Offset >= End)
return;
StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
TokenText = LiteralText;
size_t FirstBreak = LiteralText.find('\n');
StringRef FirstLineText = FirstBreak == StringRef::npos
? LiteralText
: LiteralText.substr(0, FirstBreak);
CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
Encoding);
size_t LastBreak = LiteralText.rfind('\n');
if (LastBreak != StringRef::npos) {
CSharpStringLiteral->IsMultiline = true;
unsigned StartColumn = 0;
CSharpStringLiteral->LastLineColumnWidth =
encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
StartColumn, Style.TabWidth, Encoding);
}
assert(Offset < End);
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
}
void FormatTokenLexer::handleTemplateStrings() {
FormatToken *BacktickToken = Tokens.back();
if (BacktickToken->is(tok::l_brace)) {
StateStack.push(LexerState::NORMAL);
return;
}
if (BacktickToken->is(tok::r_brace)) {
if (StateStack.size() == 1)
return;
StateStack.pop();
if (StateStack.top() != LexerState::TEMPLATE_STRING)
return;
} else if (BacktickToken->is(tok::unknown) &&
BacktickToken->TokenText == "`") {
StateStack.push(LexerState::TEMPLATE_STRING);
} else {
return; }
const char *Offset = Lex->getBufferLocation();
const char *TmplBegin = Offset - BacktickToken->TokenText.size(); for (; Offset != Lex->getBuffer().end(); ++Offset) {
if (Offset[0] == '`') {
StateStack.pop();
break;
}
if (Offset[0] == '\\') {
++Offset; } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
Offset[1] == '{') {
StateStack.push(LexerState::NORMAL);
++Offset;
break;
}
}
StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
BacktickToken->setType(TT_TemplateString);
BacktickToken->Tok.setKind(tok::string_literal);
BacktickToken->TokenText = LiteralText;
size_t FirstBreak = LiteralText.find('\n');
StringRef FirstLineText = FirstBreak == StringRef::npos
? LiteralText
: LiteralText.substr(0, FirstBreak);
BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
size_t LastBreak = LiteralText.rfind('\n');
if (LastBreak != StringRef::npos) {
BacktickToken->IsMultiline = true;
unsigned StartColumn = 0; BacktickToken->LastLineColumnWidth =
encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
StartColumn, Style.TabWidth, Encoding);
}
SourceLocation loc = Offset < Lex->getBuffer().end()
? Lex->getSourceLocation(Offset + 1)
: SourceMgr.getLocForEndOfFile(ID);
resetLexer(SourceMgr.getFileOffset(loc));
}
void FormatTokenLexer::tryParsePythonComment() {
FormatToken *HashToken = Tokens.back();
if (!HashToken->isOneOf(tok::hash, tok::hashhash))
return;
const char *CommentBegin =
Lex->getBufferLocation() - HashToken->TokenText.size(); size_t From = CommentBegin - Lex->getBuffer().begin();
size_t To = Lex->getBuffer().find_first_of('\n', From);
if (To == StringRef::npos)
To = Lex->getBuffer().size();
size_t Len = To - From;
HashToken->setType(TT_LineComment);
HashToken->Tok.setKind(tok::comment);
HashToken->TokenText = Lex->getBuffer().substr(From, Len);
SourceLocation Loc = To < Lex->getBuffer().size()
? Lex->getSourceLocation(CommentBegin + Len)
: SourceMgr.getLocForEndOfFile(ID);
resetLexer(SourceMgr.getFileOffset(Loc));
}
bool FormatTokenLexer::tryMerge_TMacro() {
if (Tokens.size() < 4)
return false;
FormatToken *Last = Tokens.back();
if (!Last->is(tok::r_paren))
return false;
FormatToken *String = Tokens[Tokens.size() - 2];
if (!String->is(tok::string_literal) || String->IsMultiline)
return false;
if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
return false;
FormatToken *Macro = Tokens[Tokens.size() - 4];
if (Macro->TokenText != "_T")
return false;
const char *Start = Macro->TokenText.data();
const char *End = Last->TokenText.data() + Last->TokenText.size();
String->TokenText = StringRef(Start, End - Start);
String->IsFirst = Macro->IsFirst;
String->LastNewlineOffset = Macro->LastNewlineOffset;
String->WhitespaceRange = Macro->WhitespaceRange;
String->OriginalColumn = Macro->OriginalColumn;
String->ColumnWidth = encoding::columnWidthWithTabs(
String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
String->NewlinesBefore = Macro->NewlinesBefore;
String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Tokens.pop_back();
Tokens.pop_back();
Tokens.pop_back();
Tokens.back() = String;
if (FirstInLineIndex >= Tokens.size())
FirstInLineIndex = Tokens.size() - 1;
return true;
}
bool FormatTokenLexer::tryMergeConflictMarkers() {
if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
return false;
FileID ID;
unsigned FirstInLineOffset;
std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
if (LineOffset == StringRef::npos)
LineOffset = 0;
else
++LineOffset;
auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
StringRef LineStart;
if (FirstSpace == StringRef::npos)
LineStart = Buffer.substr(LineOffset);
else
LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
TokenType Type = TT_Unknown;
if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
Type = TT_ConflictStart;
} else if (LineStart == "|||||||" || LineStart == "=======" ||
LineStart == "====") {
Type = TT_ConflictAlternative;
} else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
Type = TT_ConflictEnd;
}
if (Type != TT_Unknown) {
FormatToken *Next = Tokens.back();
Tokens.resize(FirstInLineIndex + 1);
Tokens.back()->setType(Type);
Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
Tokens.push_back(Next);
return true;
}
return false;
}
FormatToken *FormatTokenLexer::getStashedToken() {
Token Tok = FormatTok->Tok;
StringRef TokenText = FormatTok->TokenText;
unsigned OriginalColumn = FormatTok->OriginalColumn;
FormatTok = new (Allocator.Allocate()) FormatToken;
FormatTok->Tok = Tok;
SourceLocation TokLocation =
FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
FormatTok->Tok.setLocation(TokLocation);
FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
FormatTok->TokenText = TokenText;
FormatTok->ColumnWidth = 1;
FormatTok->OriginalColumn = OriginalColumn + 1;
return FormatTok;
}
void FormatTokenLexer::truncateToken(size_t NewLen) {
assert(NewLen <= FormatTok->TokenText.size());
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
Encoding);
FormatTok->Tok.setLength(NewLen);
}
static size_t countLeadingWhitespace(StringRef Text) {
const unsigned char *const Begin = Text.bytes_begin();
const unsigned char *const End = Text.bytes_end();
const unsigned char *Cur = Begin;
while (Cur < End) {
if (isspace(Cur[0])) {
++Cur;
} else if (Cur[0] == '\\' && (Cur[1] == '\n' || Cur[1] == '\r')) {
assert(End - Cur >= 2);
Cur += 2;
} else if (Cur[0] == '?' && Cur[1] == '?' && Cur[2] == '/' &&
(Cur[3] == '\n' || Cur[3] == '\r')) {
assert(End - Cur >= 4);
Cur += 4;
} else {
break;
}
}
return Cur - Begin;
}
FormatToken *FormatTokenLexer::getNextToken() {
if (StateStack.top() == LexerState::TOKEN_STASHED) {
StateStack.pop();
return getStashedToken();
}
FormatTok = new (Allocator.Allocate()) FormatToken;
readRawToken(*FormatTok);
SourceLocation WhitespaceStart =
FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
FormatTok->IsFirst = IsFirstToken;
IsFirstToken = false;
unsigned WhitespaceLength = TrailingWhitespace;
while (FormatTok->isNot(tok::eof)) {
auto LeadingWhitespace = countLeadingWhitespace(FormatTok->TokenText);
if (LeadingWhitespace == 0)
break;
if (LeadingWhitespace < FormatTok->TokenText.size())
truncateToken(LeadingWhitespace);
StringRef Text = FormatTok->TokenText;
bool InEscape = false;
for (int i = 0, e = Text.size(); i != e; ++i) {
switch (Text[i]) {
case '\r':
if (i + 1 < e && Text[i + 1] == '\n')
break;
LLVM_FALLTHROUGH;
case '\n':
++FormatTok->NewlinesBefore;
if (!InEscape)
FormatTok->HasUnescapedNewline = true;
else
InEscape = false;
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
Column = 0;
break;
case '\f':
case '\v':
Column = 0;
break;
case ' ':
++Column;
break;
case '\t':
Column +=
Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
break;
case '\\':
case '?':
case '/':
assert(Text.substr(i, 2) == "\\\r" || Text.substr(i, 2) == "\\\n" ||
Text.substr(i, 4) == "\?\?/\r" ||
Text.substr(i, 4) == "\?\?/\n" ||
(i >= 1 && (Text.substr(i - 1, 4) == "\?\?/\r" ||
Text.substr(i - 1, 4) == "\?\?/\n")) ||
(i >= 2 && (Text.substr(i - 2, 4) == "\?\?/\r" ||
Text.substr(i - 2, 4) == "\?\?/\n")));
InEscape = true;
break;
default:
assert(false);
break;
}
}
WhitespaceLength += Text.size();
readRawToken(*FormatTok);
}
if (FormatTok->is(tok::unknown))
FormatTok->setType(TT_ImplicitStringLiteral);
if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
size_t BackslashPos = FormatTok->TokenText.find('\\');
while (BackslashPos != StringRef::npos) {
if (BackslashPos + 1 < FormatTok->TokenText.size() &&
FormatTok->TokenText[BackslashPos + 1] == '\n') {
truncateToken(BackslashPos + 1);
break;
}
BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
}
}
if (Style.isVerilog()) {
if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
FormatTok->Tok.setKind(tok::raw_identifier);
} else if (FormatTok->is(tok::raw_identifier)) {
if (FormatTok->TokenText == "`") {
FormatTok->Tok.setIdentifierInfo(nullptr);
FormatTok->Tok.setKind(tok::hash);
} else if (FormatTok->TokenText == "``") {
FormatTok->Tok.setIdentifierInfo(nullptr);
FormatTok->Tok.setKind(tok::hashhash);
}
}
}
FormatTok->WhitespaceRange = SourceRange(
WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
FormatTok->OriginalColumn = Column;
TrailingWhitespace = 0;
if (FormatTok->is(tok::comment)) {
StringRef UntrimmedText = FormatTok->TokenText;
FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
} else if (FormatTok->is(tok::raw_identifier)) {
IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
FormatTok->Tok.setIdentifierInfo(&Info);
FormatTok->Tok.setKind(Info.getTokenID());
if (Style.Language == FormatStyle::LK_Java &&
FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
tok::kw_operator)) {
FormatTok->Tok.setKind(tok::identifier);
FormatTok->Tok.setIdentifierInfo(nullptr);
} else if (Style.isJavaScript() &&
FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
tok::kw_operator)) {
FormatTok->Tok.setKind(tok::identifier);
FormatTok->Tok.setIdentifierInfo(nullptr);
}
} else if (FormatTok->is(tok::greatergreater)) {
FormatTok->Tok.setKind(tok::greater);
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
++Column;
StateStack.push(LexerState::TOKEN_STASHED);
} else if (FormatTok->is(tok::lessless)) {
FormatTok->Tok.setKind(tok::less);
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
++Column;
StateStack.push(LexerState::TOKEN_STASHED);
}
StringRef Text = FormatTok->TokenText;
size_t FirstNewlinePos = Text.find('\n');
if (FirstNewlinePos == StringRef::npos) {
FormatTok->ColumnWidth =
encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
Column += FormatTok->ColumnWidth;
} else {
FormatTok->IsMultiline = true;
FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
Column = FormatTok->LastLineColumnWidth;
}
if (Style.isCpp()) {
auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
tok::pp_define) &&
it != Macros.end()) {
FormatTok->setType(it->second);
if (it->second == TT_IfMacro) {
FormatTok->Tok.setKind(tok::kw_if);
}
} else if (FormatTok->is(tok::identifier)) {
if (MacroBlockBeginRegex.match(Text))
FormatTok->setType(TT_MacroBlockBegin);
else if (MacroBlockEndRegex.match(Text))
FormatTok->setType(TT_MacroBlockEnd);
}
}
return FormatTok;
}
bool FormatTokenLexer::readRawTokenVerilogSpecific(Token &Tok) {
static const llvm::Regex VerilogToken(R"re(^('|``?|\\(\\)re"
"(\r?\n|\r)|[^[:space:]])*)");
SmallVector<StringRef, 4> Matches;
const char *Start = Lex->getBufferLocation();
if (!VerilogToken.match(StringRef(Start, Lex->getBuffer().end() - Start),
&Matches)) {
return false;
}
if (Start[0] == '\\' && (Start[1] == '\r' || Start[1] == '\n'))
return false;
size_t Len = Matches[0].size();
Tok.setKind(tok::raw_identifier);
Tok.setLength(Len);
Tok.setLocation(Lex->getSourceLocation(Start, Len));
Tok.setRawIdentifierData(Start);
Lex->seek(Lex->getCurrentBufferOffset() + Len, false);
return true;
}
void FormatTokenLexer::readRawToken(FormatToken &Tok) {
if (!Style.isVerilog() || !readRawTokenVerilogSpecific(Tok.Tok))
Lex->LexFromRawLexer(Tok.Tok);
Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
Tok.Tok.getLength());
if (Tok.is(tok::unknown)) {
if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
Tok.Tok.setKind(tok::string_literal);
Tok.IsUnterminatedLiteral = true;
} else if (Style.isJavaScript() && Tok.TokenText == "''") {
Tok.Tok.setKind(tok::string_literal);
}
}
if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
Tok.is(tok::char_constant)) {
Tok.Tok.setKind(tok::string_literal);
}
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
Tok.TokenText == "/* clang-format on */")) {
FormattingDisabled = false;
}
Tok.Finalized = FormattingDisabled;
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
Tok.TokenText == "/* clang-format off */")) {
FormattingDisabled = true;
}
}
void FormatTokenLexer::resetLexer(unsigned Offset) {
StringRef Buffer = SourceMgr.getBufferData(ID);
LangOpts = getFormattingLangOpts(Style);
Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
Lex->SetKeepWhitespaceMode(true);
TrailingWhitespace = 0;
}
} }