21#include "llvm/Support/Regex.h"
29 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
34 Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
35 Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
36 FormattingDisabled(
false), FormatOffRegex(Style.OneLineFormatOffRegex),
37 MacroBlockBeginRegex(Style.MacroBlockBegin),
38 MacroBlockEndRegex(Style.MacroBlockEnd) {
39 Lex.reset(
new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts));
40 Lex->SetKeepWhitespaceMode(
true);
42 for (
const std::string &ForEachMacro : Style.ForEachMacros) {
43 auto Identifier = &IdentTable.get(ForEachMacro);
44 Macros.insert({Identifier, TT_ForEachMacro});
46 for (
const std::string &IfMacro : Style.IfMacros) {
47 auto Identifier = &IdentTable.get(IfMacro);
48 Macros.insert({Identifier, TT_IfMacro});
50 for (
const std::string &AttributeMacro : Style.AttributeMacros) {
51 auto Identifier = &IdentTable.get(AttributeMacro);
52 Macros.insert({Identifier, TT_AttributeMacro});
54 for (
const std::string &StatementMacro : Style.StatementMacros) {
55 auto Identifier = &IdentTable.get(StatementMacro);
56 Macros.insert({Identifier, TT_StatementMacro});
58 for (
const std::string &TypenameMacro : Style.TypenameMacros) {
59 auto Identifier = &IdentTable.get(TypenameMacro);
60 Macros.insert({Identifier, TT_TypenameMacro});
62 for (
const std::string &NamespaceMacro : Style.NamespaceMacros) {
63 auto Identifier = &IdentTable.get(NamespaceMacro);
64 Macros.insert({Identifier, TT_NamespaceMacro});
66 for (
const std::string &WhitespaceSensitiveMacro :
67 Style.WhitespaceSensitiveMacros) {
68 auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
69 Macros.insert({Identifier, TT_UntouchableMacroFunc});
71 for (
const std::string &StatementAttributeLikeMacro :
72 Style.StatementAttributeLikeMacros) {
73 auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
74 Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
77 for (
const auto &
Macro : Style.MacrosSkippedByRemoveParentheses)
81 for (
const auto &TypeName : Style.TypeNames)
82 TypeNames.insert(&IdentTable.get(TypeName));
83 for (
const auto &VariableTemplate : Style.VariableTemplates)
88 assert(Tokens.empty());
89 assert(FirstInLineIndex == 0);
90 enum { FO_None, FO_CurrentLine, FO_NextLine } FormatOff = FO_None;
92 Tokens.push_back(getNextToken());
93 auto &
Tok = *Tokens.back();
100 Tok.Finalized =
true;
101 FormatOff = FO_CurrentLine;
106 Tok.Finalized =
true;
112 if (!FormattingDisabled && FormatOffRegex.match(
Tok.TokenText)) {
113 if (
Tok.is(tok::comment) &&
115 Tok.Finalized =
true;
116 FormatOff = FO_NextLine;
118 for (
auto *
Token : reverse(Tokens)) {
119 Token->Finalized =
true;
120 if (
Token->NewlinesBefore > 0)
123 FormatOff = FO_CurrentLine;
127 if (Style.isJavaScript()) {
128 tryParseJSRegexLiteral();
129 handleTemplateStrings();
130 }
else if (Style.isTextProto()) {
131 tryParsePythonComment();
133 tryMergePreviousTokens();
134 if (Style.isCSharp()) {
137 handleCSharpVerbatimAndInterpolatedStrings();
138 }
else if (Style.isTableGen()) {
139 handleTableGenMultilineString();
140 handleTableGenNumericLikeIdentifier();
142 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
143 FirstInLineIndex = Tokens.size() - 1;
144 }
while (Tokens.back()->isNot(tok::eof));
145 if (Style.InsertNewlineAtEOF) {
146 auto &TokEOF = *Tokens.back();
147 if (TokEOF.NewlinesBefore == 0) {
148 TokEOF.NewlinesBefore = 1;
149 TokEOF.OriginalColumn = 0;
155void FormatTokenLexer::tryMergePreviousTokens() {
156 if (tryMerge_TMacro())
158 if (tryMergeConflictMarkers())
160 if (tryMergeLessLess())
162 if (tryMergeGreaterGreater())
164 if (tryMergeForEach())
167 if ((Style.Language == FormatStyle::LK_Cpp ||
168 Style.Language == FormatStyle::LK_ObjC) &&
169 tryMergeUserDefinedLiteral()) {
173 if (Style.isJavaScript() || Style.isCSharp()) {
174 static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
176 static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
178 static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
180 if (tryMergeTokens(FatArrow, TT_FatArrow))
182 if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
184 Tokens.back()->Tok.setKind(tok::pipepipe);
187 if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
189 Tokens.back()->Tok.setKind(tok::period);
192 if (tryMergeNullishCoalescingEqual())
195 if (Style.isCSharp()) {
197 tok::question, tok::l_square};
199 if (tryMergeCSharpKeywordVariables())
201 if (tryMergeCSharpStringLiteral())
203 if (tryTransformCSharpForEach())
205 if (tryMergeTokens(CSharpNullConditionalLSquare,
206 TT_CSharpNullConditionalLSquare)) {
208 Tokens.back()->Tok.setKind(tok::l_square);
214 if (tryMergeNSStringLiteral())
217 if (Style.isJavaScript()) {
218 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
221 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
223 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
226 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
227 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
230 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
232 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
234 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
236 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
238 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
239 Tokens.back()->Tok.setKind(tok::starequal);
242 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
243 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
245 Tokens.back()->Tok.setKind(tok::equal);
248 if (tryMergeJSPrivateIdentifier())
250 }
else if (Style.isJava()) {
252 tok::greater, tok::greater, tok::greaterequal};
253 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
255 }
else if (Style.isVerilog()) {
257 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
258 Tokens.end()[-2]->is(tok::numeric_constant) &&
259 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
261 tryMergeTokens(2, TT_Unknown)) {
265 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
273 if (Tokens.back()->TokenText.size() == 1 &&
274 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
275 TT_BinaryOperator)) {
276 Tokens.back()->Tok.setKind(tok::caret);
280 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
281 Tokens.back()->Tok.setKind(tok::lessless);
284 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
285 Tokens.back()->Tok.setKind(tok::greatergreater);
288 if (tryMergeTokensAny({{tok::lessless, tok::equal},
289 {tok::lessless, tok::lessequal},
290 {tok::greatergreater, tok::equal},
291 {tok::greatergreater, tok::greaterequal},
292 {tok::colon, tok::equal},
293 {tok::colon, tok::slash}},
294 TT_BinaryOperator)) {
299 if (tryMergeTokensAny({{tok::star, tok::star},
300 {tok::lessless, tok::less},
301 {tok::greatergreater, tok::greater},
302 {tok::exclaimequal, tok::equal},
303 {tok::exclaimequal, tok::question},
304 {tok::equalequal, tok::equal},
305 {tok::equalequal, tok::question}},
306 TT_BinaryOperator)) {
311 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
312 {tok::plus, tok::star, tok::greater},
313 {tok::minusequal, tok::greater},
314 {tok::minus, tok::star, tok::greater},
315 {tok::less, tok::arrow},
316 {tok::equal, tok::greater},
317 {tok::star, tok::greater},
318 {tok::pipeequal, tok::greater},
319 {tok::pipe, tok::arrow}},
320 TT_BinaryOperator) ||
321 Tokens.back()->
is(tok::arrow)) {
325 if (Tokens.size() >= 3 &&
326 Tokens[Tokens.size() - 3]->is(Keywords.kw_verilogHash) &&
327 Tokens[Tokens.size() - 2]->isOneOf(tok::minus, tok::equal) &&
328 Tokens[Tokens.size() - 1]->is(Keywords.kw_verilogHash) &&
329 tryMergeTokens(3, TT_BinaryOperator)) {
330 Tokens.back()->setFinalizedType(TT_BinaryOperator);
334 }
else if (Style.isTableGen()) {
336 if (tryMergeTokens({tok::l_square, tok::l_brace},
337 TT_TableGenMultiLineString)) {
339 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
340 Tokens.back()->Tok.setKind(tok::string_literal);
345 if (tryMergeTokens({tok::exclaim, tok::identifier},
346 TT_TableGenBangOperator)) {
347 Tokens.back()->Tok.setKind(tok::identifier);
348 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
349 if (Tokens.back()->TokenText ==
"!cond")
350 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
352 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
355 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
358 Tokens.back()->Tok.setKind(tok::identifier);
359 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
360 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
364 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
365 Tokens.back()->Tok.setKind(tok::numeric_constant);
368 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
369 Tokens.back()->Tok.setKind(tok::numeric_constant);
375bool FormatTokenLexer::tryMergeNSStringLiteral() {
376 if (Tokens.size() < 2)
378 auto &At = *(Tokens.end() - 2);
379 auto &String = *(Tokens.end() - 1);
380 if (At->isNot(tok::at) || String->isNot(tok::string_literal))
382 At->Tok.setKind(tok::string_literal);
383 At->TokenText = StringRef(At->TokenText.begin(),
384 String->TokenText.end() - At->TokenText.begin());
385 At->ColumnWidth += String->ColumnWidth;
386 At->setType(TT_ObjCStringLiteral);
387 Tokens.erase(Tokens.end() - 1);
391bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
394 if (Tokens.size() < 2)
396 auto &Hash = *(Tokens.end() - 2);
397 auto &Identifier = *(Tokens.end() - 1);
398 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
400 Hash->Tok.setKind(tok::identifier);
402 StringRef(Hash->TokenText.begin(),
403 Identifier->TokenText.end() - Hash->TokenText.begin());
404 Hash->ColumnWidth += Identifier->ColumnWidth;
405 Hash->setType(TT_JsPrivateIdentifier);
406 Tokens.erase(Tokens.end() - 1);
415bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
416 if (Tokens.size() < 2)
420 const auto String = *(Tokens.end() - 1);
421 if (String->isNot(tok::string_literal))
424 auto Prefix = *(Tokens.end() - 2);
425 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
428 if (Tokens.size() > 2) {
429 const auto Tok = *(Tokens.end() - 3);
430 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
431 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
433 Tok->ColumnWidth += Prefix->ColumnWidth;
434 Tokens.erase(Tokens.end() - 2);
440 Prefix->Tok.setKind(tok::string_literal);
442 StringRef(Prefix->TokenText.begin(),
443 String->TokenText.end() - Prefix->TokenText.begin());
444 Prefix->ColumnWidth += String->ColumnWidth;
445 Prefix->setType(TT_CSharpStringLiteral);
446 Tokens.erase(Tokens.end() - 1);
452const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
453 "assembly",
"module",
"field",
"event",
"method",
454 "param",
"property",
"return",
"type",
457bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
458 if (Tokens.size() < 2)
460 auto &NullishCoalescing = *(Tokens.end() - 2);
461 auto &
Equal = *(Tokens.end() - 1);
462 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
463 Equal->isNot(tok::equal)) {
466 NullishCoalescing->Tok.setKind(tok::equal);
467 NullishCoalescing->TokenText =
468 StringRef(NullishCoalescing->TokenText.begin(),
469 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
470 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
471 NullishCoalescing->setType(TT_NullCoalescingEqual);
472 Tokens.erase(Tokens.end() - 1);
476bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
477 if (Tokens.size() < 2)
479 const auto At = *(Tokens.end() - 2);
480 if (At->isNot(tok::at))
482 const auto Keyword = *(Tokens.end() - 1);
485 if (!Keywords.isCSharpKeyword(*
Keyword))
488 At->Tok.setKind(tok::identifier);
489 At->TokenText = StringRef(At->TokenText.begin(),
490 Keyword->TokenText.end() - At->TokenText.begin());
491 At->ColumnWidth +=
Keyword->ColumnWidth;
492 At->setType(
Keyword->getType());
493 Tokens.erase(Tokens.end() - 1);
498bool FormatTokenLexer::tryTransformCSharpForEach() {
501 auto &Identifier = *(Tokens.end() - 1);
502 if (Identifier->isNot(tok::identifier))
504 if (Identifier->TokenText !=
"foreach")
507 Identifier->setType(TT_ForEachMacro);
508 Identifier->Tok.setKind(tok::kw_for);
512bool FormatTokenLexer::tryMergeForEach() {
513 if (Tokens.size() < 2)
515 auto &For = *(Tokens.end() - 2);
516 auto &Each = *(Tokens.end() - 1);
517 if (For->isNot(tok::kw_for))
519 if (Each->isNot(tok::identifier))
521 if (Each->TokenText !=
"each")
524 For->setType(TT_ForEachMacro);
525 For->Tok.setKind(tok::kw_for);
527 For->TokenText = StringRef(For->TokenText.begin(),
528 Each->TokenText.end() - For->TokenText.begin());
529 For->ColumnWidth += Each->ColumnWidth;
530 Tokens.erase(Tokens.end() - 1);
534bool FormatTokenLexer::tryMergeLessLess() {
536 if (Tokens.size() < 3)
539 auto First = Tokens.end() - 3;
544 if (
First[1]->hasWhitespaceBefore())
547 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
548 if (
X &&
X->is(tok::less))
552 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
555 First[0]->Tok.setKind(tok::lessless);
556 First[0]->TokenText =
"<<";
557 First[0]->ColumnWidth += 1;
558 Tokens.erase(Tokens.end() - 2);
562bool FormatTokenLexer::tryMergeGreaterGreater() {
564 if (Tokens.size() < 2)
567 auto First = Tokens.end() - 2;
572 if (
First[1]->hasWhitespaceBefore())
575 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
576 if (
Tok &&
Tok->isNot(tok::kw_operator))
579 First[0]->Tok.setKind(tok::greatergreater);
580 First[0]->TokenText =
">>";
581 First[0]->ColumnWidth += 1;
582 Tokens.erase(Tokens.end() - 1);
586bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
587 if (Tokens.size() < 2)
590 auto *
First = Tokens.end() - 2;
591 auto &Suffix =
First[1];
592 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
600 if (!
Text.ends_with(
"_"))
605 Tokens.erase(&Suffix);
611 if (Tokens.size() < Kinds.size())
614 const auto *
First = Tokens.end() - Kinds.size();
615 for (
unsigned i = 0; i < Kinds.size(); ++i)
619 return tryMergeTokens(Kinds.size(), NewType);
622bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
623 if (Tokens.size() < Count)
626 const auto *
First = Tokens.end() - Count;
627 unsigned AddLength = 0;
628 for (
size_t i = 1; i < Count; ++i) {
631 if (
First[i]->hasWhitespaceBefore())
633 AddLength +=
First[i]->TokenText.size();
636 Tokens.resize(Tokens.size() - Count + 1);
638 First[0]->TokenText.size() + AddLength);
639 First[0]->ColumnWidth += AddLength;
640 First[0]->setType(NewType);
644bool FormatTokenLexer::tryMergeTokensAny(
646 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
647 return tryMergeTokens(Kinds, NewType);
656 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
657 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
658 tok::colon, tok::question, tok::tilde) ||
659 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
660 tok::kw_else, tok::kw_void, tok::kw_typeof,
661 Keywords.kw_instanceof, Keywords.kw_in) ||
662 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
665bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
675 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
676 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
680 if (!precedesOperand(Prev))
686void FormatTokenLexer::tryParseJavaTextBlock() {
687 if (FormatTok->TokenText !=
"\"\"")
690 const auto *S = Lex->getBufferLocation();
691 const auto *End = Lex->getBuffer().end();
693 if (S == End || *S !=
'\"')
699 bool Escaped =
false;
700 for (
int Count = 0; Count < 3 && S < End; ++S) {
718 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
725void FormatTokenLexer::tryParseJSRegexLiteral() {
727 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
731 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
734 if (FT->isNot(tok::comment)) {
740 if (!canPrecedeRegexLiteral(Prev))
744 const char *Offset = Lex->getBufferLocation();
745 const char *RegexBegin = Offset - RegexToken->TokenText.size();
746 StringRef Buffer = Lex->getBuffer();
747 bool InCharacterClass =
false;
748 bool HaveClosingSlash =
false;
749 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
759 InCharacterClass =
true;
762 InCharacterClass =
false;
765 if (!InCharacterClass)
766 HaveClosingSlash =
true;
771 RegexToken->setType(TT_RegexLiteral);
773 RegexToken->Tok.setKind(tok::string_literal);
774 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
775 RegexToken->ColumnWidth = RegexToken->TokenText.size();
777 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
782 auto Repeated = [&Begin, End]() {
783 return Begin + 1 < End && Begin[1] == Begin[0];
798 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
810 ++UnmatchedOpeningBraceCount;
818 else if (UnmatchedOpeningBraceCount > 0)
819 --UnmatchedOpeningBraceCount;
825 if (UnmatchedOpeningBraceCount > 0)
828 if (Verbatim && Repeated()) {
839void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
842 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
845 auto &
TokenText = CSharpStringLiteral->TokenText;
847 bool Verbatim =
false;
848 bool Interpolated =
false;
852 }
else if (
TokenText.starts_with(R
"(@")")) {
854 }
else if (
TokenText.starts_with(R
"($")")) {
859 if (!Verbatim && !Interpolated)
862 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
863 const char *Offset = StrBegin;
864 Offset += Verbatim && Interpolated ? 3 : 2;
866 const auto End = Lex->getBuffer().end();
874 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
878 size_t FirstBreak = LiteralText.find(
'\n');
879 StringRef FirstLineText = FirstBreak == StringRef::npos
881 : LiteralText.substr(0, FirstBreak);
883 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
885 size_t LastBreak = LiteralText.rfind(
'\n');
886 if (LastBreak != StringRef::npos) {
887 CSharpStringLiteral->IsMultiline =
true;
888 unsigned StartColumn = 0;
889 CSharpStringLiteral->LastLineColumnWidth =
891 StartColumn, Style.TabWidth, Encoding);
894 assert(Offset < End);
895 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
898void FormatTokenLexer::handleTableGenMultilineString() {
900 if (MultiLineString->isNot(TT_TableGenMultiLineString))
903 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
905 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
906 if (CloseOffset == StringRef::npos)
908 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
909 MultiLineString->TokenText =
Text;
910 resetLexer(SourceMgr.getFileOffset(
911 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
912 auto FirstLineText =
Text;
913 auto FirstBreak =
Text.find(
'\n');
915 if (FirstBreak != StringRef::npos) {
916 MultiLineString->IsMultiline =
true;
917 FirstLineText =
Text.substr(0, FirstBreak + 1);
919 auto LastBreak =
Text.rfind(
'\n');
921 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
922 Style.TabWidth, Encoding);
926 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
929void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
933 if (
Tok->isNot(tok::numeric_constant))
935 StringRef
Text =
Tok->TokenText;
946 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
948 if (NonDigitPos == StringRef::npos)
950 char FirstNonDigit =
Text[NonDigitPos];
951 if (NonDigitPos <
Text.size() - 1) {
952 char TheNext =
Text[NonDigitPos + 1];
954 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
957 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
960 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
962 Tok->Tok.setKind(tok::identifier);
963 Tok->Tok.setIdentifierInfo(
nullptr);
967void FormatTokenLexer::handleTemplateStrings() {
970 if (BacktickToken->is(tok::l_brace)) {
974 if (BacktickToken->is(tok::r_brace)) {
975 if (StateStack.size() == 1)
981 }
else if (BacktickToken->is(tok::unknown) &&
982 BacktickToken->TokenText ==
"`") {
989 const char *Offset = Lex->getBufferLocation();
990 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
991 for (; Offset != Lex->getBuffer().end(); ++Offset) {
992 if (Offset[0] ==
'`') {
997 if (Offset[0] ==
'\\') {
999 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1008 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1009 BacktickToken->setType(TT_TemplateString);
1010 BacktickToken->Tok.setKind(tok::string_literal);
1011 BacktickToken->TokenText = LiteralText;
1014 size_t FirstBreak = LiteralText.find(
'\n');
1015 StringRef FirstLineText = FirstBreak == StringRef::npos
1017 : LiteralText.substr(0, FirstBreak);
1019 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1020 size_t LastBreak = LiteralText.rfind(
'\n');
1021 if (LastBreak != StringRef::npos) {
1022 BacktickToken->IsMultiline =
true;
1023 unsigned StartColumn = 0;
1024 BacktickToken->LastLineColumnWidth =
1026 StartColumn, Style.TabWidth, Encoding);
1029 SourceLocation loc = Lex->getSourceLocation(Offset);
1030 resetLexer(SourceMgr.getFileOffset(loc));
1033void FormatTokenLexer::tryParsePythonComment() {
1035 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1038 const char *CommentBegin =
1039 Lex->getBufferLocation() - HashToken->TokenText.size();
1040 size_t From = CommentBegin - Lex->getBuffer().begin();
1041 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1042 if (To == StringRef::npos)
1043 To = Lex->getBuffer().size();
1044 size_t Len = To - From;
1045 HashToken->setType(TT_LineComment);
1046 HashToken->Tok.setKind(tok::comment);
1047 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1048 SourceLocation Loc = To < Lex->getBuffer().size()
1049 ? Lex->getSourceLocation(CommentBegin + Len)
1050 : SourceMgr.getLocForEndOfFile(ID);
1051 resetLexer(SourceMgr.getFileOffset(Loc));
1054bool FormatTokenLexer::tryMerge_TMacro() {
1055 if (Tokens.size() < 4)
1058 if (
Last->isNot(tok::r_paren))
1062 if (String->isNot(tok::string_literal) || String->IsMultiline)
1065 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1069 if (
Macro->TokenText !=
"_T")
1072 const char *Start =
Macro->TokenText.data();
1073 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1074 String->TokenText = StringRef(Start, End - Start);
1075 String->IsFirst =
Macro->IsFirst;
1076 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1077 String->WhitespaceRange =
Macro->WhitespaceRange;
1078 String->OriginalColumn =
Macro->OriginalColumn;
1080 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1081 String->NewlinesBefore =
Macro->NewlinesBefore;
1082 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1087 Tokens.back() = String;
1088 if (FirstInLineIndex >= Tokens.size())
1089 FirstInLineIndex = Tokens.size() - 1;
1093bool FormatTokenLexer::tryMergeConflictMarkers() {
1094 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1108 unsigned FirstInLineOffset;
1109 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1110 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1111 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1113 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1114 if (LineOffset == StringRef::npos)
1119 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1120 StringRef LineStart;
1121 if (FirstSpace == StringRef::npos)
1122 LineStart = Buffer.substr(LineOffset);
1124 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1127 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1128 Type = TT_ConflictStart;
1129 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1130 LineStart ==
"====") {
1131 Type = TT_ConflictAlternative;
1132 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1133 Type = TT_ConflictEnd;
1136 if (
Type != TT_Unknown) {
1139 Tokens.resize(FirstInLineIndex + 1);
1143 Tokens.back()->setType(
Type);
1144 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1146 Tokens.push_back(
Next);
1155 Token
Tok = FormatTok->
Tok;
1156 StringRef
TokenText = FormatTok->TokenText;
1159 FormatTok =
new (Allocator.Allocate())
FormatToken;
1160 FormatTok->Tok =
Tok;
1161 SourceLocation TokLocation =
1162 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1163 FormatTok->Tok.setLocation(TokLocation);
1164 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1166 FormatTok->ColumnWidth = 1;
1178void FormatTokenLexer::truncateToken(
size_t NewLen) {
1179 assert(NewLen <= FormatTok->
TokenText.size());
1180 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1181 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1182 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1184 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1186 FormatTok->Tok.setLength(NewLen);
1196 const unsigned char *
const Begin =
Text.bytes_begin();
1197 const unsigned char *
const End =
Text.bytes_end();
1198 const unsigned char *Cur = Begin;
1202 }
else if (Cur[0] ==
'\\') {
1208 const auto *Lookahead = Cur + 1;
1215 Cur = Lookahead + 1;
1226 return getStashedToken();
1229 FormatTok =
new (Allocator.Allocate())
FormatToken;
1230 readRawToken(*FormatTok);
1231 SourceLocation WhitespaceStart =
1233 FormatTok->
IsFirst = IsFirstToken;
1234 IsFirstToken =
false;
1240 unsigned WhitespaceLength = TrailingWhitespace;
1241 while (FormatTok->
isNot(tok::eof)) {
1243 if (LeadingWhitespace == 0)
1245 if (LeadingWhitespace < FormatTok->
TokenText.size())
1246 truncateToken(LeadingWhitespace);
1248 bool InEscape =
false;
1249 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1255 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1270 i > 0 &&
Text[i - 1] ==
'\n' &&
1271 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1272 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1284 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1291 assert([&]() ->
bool {
1295 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1305 WhitespaceLength +=
Text.size();
1306 readRawToken(*FormatTok);
1309 if (FormatTok->is(tok::unknown))
1310 FormatTok->setType(TT_ImplicitStringLiteral);
1312 const bool IsCpp = Style.isCpp();
1321 if (
const auto Text = FormatTok->TokenText;
1322 Text.starts_with(
"//") &&
1323 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1324 assert(FormatTok->is(tok::comment));
1325 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1326 Pos =
Text.find(
'\\', Pos)) {
1327 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1328 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1335 if (Style.isVerilog()) {
1336 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1337 SmallVector<StringRef, 1> Matches;
1343 if (FormatTok->is(tok::numeric_constant)) {
1345 auto Quote = FormatTok->TokenText.find(
'\'');
1346 if (Quote != StringRef::npos)
1347 truncateToken(Quote);
1348 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1349 FormatTok->Tok.setKind(tok::raw_identifier);
1350 }
else if (FormatTok->is(tok::raw_identifier)) {
1351 if (FormatTok->TokenText ==
"`") {
1352 FormatTok->Tok.setIdentifierInfo(
nullptr);
1353 FormatTok->Tok.setKind(tok::hash);
1354 }
else if (FormatTok->TokenText ==
"``") {
1355 FormatTok->Tok.setIdentifierInfo(
nullptr);
1356 FormatTok->Tok.setKind(tok::hashhash);
1357 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1358 NumberBase.match(FormatTok->TokenText, &Matches)) {
1363 truncateToken(Matches[0].size());
1364 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1369 FormatTok->WhitespaceRange = SourceRange(
1370 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1372 FormatTok->OriginalColumn = Column;
1374 TrailingWhitespace = 0;
1375 if (FormatTok->is(tok::comment)) {
1377 StringRef UntrimmedText = FormatTok->TokenText;
1378 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1379 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1380 }
else if (FormatTok->is(tok::raw_identifier)) {
1381 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1382 FormatTok->Tok.setIdentifierInfo(&Info);
1383 FormatTok->Tok.setKind(Info.getTokenID());
1384 if (Style.isJava() &&
1385 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1386 tok::kw_operator)) {
1387 FormatTok->Tok.setKind(tok::identifier);
1388 }
else if (Style.isJavaScript() &&
1389 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1390 tok::kw_operator)) {
1391 FormatTok->Tok.setKind(tok::identifier);
1392 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1393 FormatTok->Tok.setKind(tok::identifier);
1394 }
else if (Style.isVerilog() && Keywords.isVerilogIdentifier(*FormatTok)) {
1395 FormatTok->Tok.setKind(tok::identifier);
1397 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1398 Greater || FormatTok->is(tok::lessless)) {
1399 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1400 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1403 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1404 tryParseJavaTextBlock();
1407 if (Style.isVerilog() && !Tokens.empty() &&
1408 Tokens.back()->is(TT_VerilogNumberBase) &&
1409 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1411 FormatTok->Tok.setKind(tok::numeric_constant);
1416 StringRef
Text = FormatTok->TokenText;
1417 size_t FirstNewlinePos =
Text.find(
'\n');
1418 if (FirstNewlinePos == StringRef::npos) {
1421 FormatTok->ColumnWidth =
1423 Column += FormatTok->ColumnWidth;
1425 FormatTok->IsMultiline =
true;
1429 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1434 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1435 Column = FormatTok->LastLineColumnWidth;
1439 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1440 auto it = Macros.find(Identifier);
1441 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1442 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1444 it != Macros.end()) {
1445 FormatTok->setType(it->second);
1446 if (it->second == TT_IfMacro) {
1451 FormatTok->Tok.setKind(tok::kw_if);
1453 }
else if (FormatTok->is(tok::identifier)) {
1454 if (MacroBlockBeginRegex.match(
Text))
1455 FormatTok->setType(TT_MacroBlockBegin);
1456 else if (MacroBlockEndRegex.match(
Text))
1457 FormatTok->setType(TT_MacroBlockEnd);
1458 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1459 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1460 else if (TemplateNames.contains(Identifier))
1461 FormatTok->setFinalizedType(TT_TemplateName);
1462 else if (TypeNames.contains(Identifier))
1463 FormatTok->setFinalizedType(TT_TypeName);
1464 else if (VariableTemplates.contains(Identifier))
1465 FormatTok->setFinalizedType(TT_VariableTemplate);
1472bool FormatTokenLexer::readRawTokenVerilogSpecific(Token &
Tok) {
1473 const char *Start = Lex->getBufferLocation();
1483 if (Start[1] ==
'`')
1496 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1499 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1500 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1501 Start[Len] !=
' ') {
1504 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1505 Start[Len + 2] ==
'\n') {
1507 }
else if (Start[Len] ==
'\\' &&
1508 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1522 Tok.setKind(tok::raw_identifier);
1524 Tok.setLocation(Lex->getSourceLocation(Start, Len));
1525 Tok.setRawIdentifierData(Start);
1526 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1533 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok.Tok))
1534 Lex->LexFromRawLexer(
Tok.Tok);
1535 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1536 Tok.Tok.getLength());
1539 if (
Tok.is(tok::unknown)) {
1540 if (
Tok.TokenText.starts_with(
"\"")) {
1541 Tok.Tok.setKind(tok::string_literal);
1542 Tok.IsUnterminatedLiteral =
true;
1543 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1544 Tok.Tok.setKind(tok::string_literal);
1548 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1549 Tok.Tok.setKind(tok::string_literal);
1552 FormattingDisabled =
false;
1554 Tok.Finalized = FormattingDisabled;
1557 FormattingDisabled =
true;
1560void FormatTokenLexer::resetLexer(
unsigned Offset) {
1561 StringRef Buffer = SourceMgr.getBufferData(ID);
1562 Lex.reset(
new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1563 Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
1564 Lex->SetKeepWhitespaceMode(
true);
1565 TrailingWhitespace = 0;
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements an efficient mapping from strings to IdentifierInfo nodes.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
uint32_t Literal
Literals are represented as positive integers.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::vector< std::string > TypeNames
A vector of non-keyword identifiers that should be interpreted as type names.
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
@ Keyword
The name has been typo-corrected to a keyword.
@ Type
The name was classified as a type.
std::vector< std::string > MacrosSkippedByRemoveParentheses
A vector of function-like macros whose invocations should be skipped by RemoveParentheses.
std::vector< std::string > TemplateNames
A vector of non-keyword identifiers that should be interpreted as template names.
std::vector< std::string > VariableTemplates
A vector of non-keyword identifiers that should be interpreted as variable template names.