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), VerilogProtectedBlock(
false) {
39 Lex = std::make_unique<Lexer>(ID, SourceMgr.getBufferOrFake(ID), SourceMgr,
41 Lex->SetKeepWhitespaceMode(
true);
43 for (
const std::string &ForEachMacro : Style.ForEachMacros) {
44 auto Identifier = &IdentTable.get(ForEachMacro);
45 Macros.insert({Identifier, TT_ForEachMacro});
47 for (
const std::string &IfMacro : Style.IfMacros) {
48 auto Identifier = &IdentTable.get(IfMacro);
49 Macros.insert({Identifier, TT_IfMacro});
51 for (
const std::string &AttributeMacro : Style.AttributeMacros) {
52 auto Identifier = &IdentTable.get(AttributeMacro);
53 Macros.insert({Identifier, TT_AttributeMacro});
55 for (
const std::string &StatementMacro : Style.StatementMacros) {
56 auto Identifier = &IdentTable.get(StatementMacro);
57 Macros.insert({Identifier, TT_StatementMacro});
59 for (
const std::string &TypenameMacro : Style.TypenameMacros) {
60 auto Identifier = &IdentTable.get(TypenameMacro);
61 Macros.insert({Identifier, TT_TypenameMacro});
63 for (
const std::string &NamespaceMacro : Style.NamespaceMacros) {
64 auto Identifier = &IdentTable.get(NamespaceMacro);
65 Macros.insert({Identifier, TT_NamespaceMacro});
67 for (
const std::string &WhitespaceSensitiveMacro :
68 Style.WhitespaceSensitiveMacros) {
69 auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
70 Macros.insert({Identifier, TT_UntouchableMacroFunc});
72 for (
const std::string &StatementAttributeLikeMacro :
73 Style.StatementAttributeLikeMacros) {
74 auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
75 Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
78 for (
const auto &
Macro : Style.MacrosSkippedByRemoveParentheses)
82 for (
const auto &TypeName : Style.TypeNames)
83 TypeNames.insert(&IdentTable.get(TypeName));
84 for (
const auto &VariableTemplate : Style.VariableTemplates)
89 assert(Tokens.empty());
90 assert(FirstInLineIndex == 0);
91 enum { FO_None, FO_CurrentLine, FO_NextLine } FormatOff = FO_None;
93 Tokens.push_back(getNextToken());
94 auto &
Tok = *Tokens.back();
101 Tok.Finalized =
true;
102 FormatOff = FO_CurrentLine;
107 Tok.Finalized =
true;
113 if (!FormattingDisabled && FormatOffRegex.match(
Tok.TokenText)) {
114 if (
Tok.is(tok::comment) &&
116 Tok.Finalized =
true;
117 FormatOff = FO_NextLine;
119 for (
auto *
Token : reverse(Tokens)) {
120 Token->Finalized =
true;
121 if (
Token->NewlinesBefore > 0)
124 FormatOff = FO_CurrentLine;
128 if (Style.isJavaScript()) {
129 tryParseJSRegexLiteral();
130 handleTemplateStrings();
131 }
else if (Style.isTextProto()) {
132 tryParsePythonComment();
134 tryMergePreviousTokens();
135 if (Style.isCSharp()) {
138 handleCSharpVerbatimAndInterpolatedStrings();
139 }
else if (Style.isTableGen()) {
140 handleTableGenMultilineString();
141 handleTableGenNumericLikeIdentifier();
143 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
144 FirstInLineIndex = Tokens.size() - 1;
145 }
while (Tokens.back()->isNot(tok::eof));
146 if (Style.InsertNewlineAtEOF) {
147 auto &TokEOF = *Tokens.back();
148 if (TokEOF.NewlinesBefore == 0) {
149 TokEOF.NewlinesBefore = 1;
150 TokEOF.OriginalColumn = 0;
156void FormatTokenLexer::tryMergePreviousTokens() {
157 if (tryMerge_TMacro())
159 if (tryMergeConflictMarkers())
161 if (tryMergeLessLess())
163 if (tryMergeGreaterGreater())
165 if (tryMergeForEach())
168 if ((Style.Language == FormatStyle::LK_Cpp ||
169 Style.Language == FormatStyle::LK_ObjC) &&
170 tryMergeUserDefinedLiteral()) {
174 if (Style.isJavaScript() || Style.isCSharp()) {
175 static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
177 static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
179 static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
181 if (tryMergeTokens(FatArrow, TT_FatArrow))
183 if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
185 Tokens.back()->Tok.setKind(tok::pipepipe);
188 if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
190 Tokens.back()->Tok.setKind(tok::period);
193 if (tryMergeNullishCoalescingEqual())
196 if (Style.isCSharp()) {
198 tok::question, tok::l_square};
200 if (tryMergeCSharpKeywordVariables())
202 if (tryMergeCSharpStringLiteral())
204 if (tryTransformCSharpForEach())
206 if (tryMergeTokens(CSharpNullConditionalLSquare,
207 TT_CSharpNullConditionalLSquare)) {
209 Tokens.back()->Tok.setKind(tok::l_square);
215 if (tryMergeNSStringLiteral())
218 if (Style.isJavaScript()) {
219 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
222 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
224 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
227 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
228 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
231 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
233 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
235 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
237 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
239 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
240 Tokens.back()->Tok.setKind(tok::starequal);
243 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
244 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
246 Tokens.back()->Tok.setKind(tok::equal);
249 if (tryMergeJSPrivateIdentifier())
251 }
else if (Style.isJava()) {
253 tok::greater, tok::greater, tok::greaterequal};
254 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
256 }
else if (Style.isVerilog()) {
258 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
259 Tokens.end()[-2]->is(tok::numeric_constant) &&
260 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
262 tryMergeTokens(2, TT_Unknown)) {
266 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
274 if (Tokens.back()->TokenText.size() == 1 &&
275 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
276 TT_BinaryOperator)) {
277 Tokens.back()->Tok.setKind(tok::caret);
281 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
282 Tokens.back()->Tok.setKind(tok::lessless);
285 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
286 Tokens.back()->Tok.setKind(tok::greatergreater);
289 if (tryMergeTokensAny({{tok::lessless, tok::equal},
290 {tok::lessless, tok::lessequal},
291 {tok::greatergreater, tok::equal},
292 {tok::greatergreater, tok::greaterequal},
293 {tok::colon, tok::equal},
294 {tok::colon, tok::slash}},
295 TT_BinaryOperator)) {
300 if (tryMergeTokensAny({{tok::star, tok::star},
301 {tok::lessless, tok::less},
302 {tok::greatergreater, tok::greater},
303 {tok::exclaimequal, tok::equal},
304 {tok::exclaimequal, tok::question},
305 {tok::equalequal, tok::equal},
306 {tok::equalequal, tok::question}},
307 TT_BinaryOperator)) {
312 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
313 {tok::plus, tok::star, tok::greater},
314 {tok::minusequal, tok::greater},
315 {tok::minus, tok::star, tok::greater},
316 {tok::less, tok::arrow},
317 {tok::equal, tok::greater},
318 {tok::star, tok::greater},
319 {tok::pipeequal, tok::greater},
320 {tok::pipe, tok::arrow}},
321 TT_BinaryOperator) ||
322 Tokens.back()->
is(tok::arrow)) {
326 if (Tokens.size() >= 3 &&
327 Tokens[Tokens.size() - 3]->is(Keywords.kw_verilogHash) &&
328 Tokens[Tokens.size() - 2]->isOneOf(tok::minus, tok::equal) &&
329 Tokens[Tokens.size() - 1]->is(Keywords.kw_verilogHash) &&
330 tryMergeTokens(3, TT_BinaryOperator)) {
331 Tokens.back()->setFinalizedType(TT_BinaryOperator);
335 }
else if (Style.isTableGen()) {
337 if (tryMergeTokens({tok::l_square, tok::l_brace},
338 TT_TableGenMultiLineString)) {
340 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
341 Tokens.back()->Tok.setKind(tok::string_literal);
346 if (tryMergeTokens({tok::exclaim, tok::identifier},
347 TT_TableGenBangOperator)) {
348 Tokens.back()->Tok.setKind(tok::identifier);
349 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
350 if (Tokens.back()->TokenText ==
"!cond")
351 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
353 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
356 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
359 Tokens.back()->Tok.setKind(tok::identifier);
360 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
361 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
365 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
366 Tokens.back()->Tok.setKind(tok::numeric_constant);
369 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
370 Tokens.back()->Tok.setKind(tok::numeric_constant);
376bool FormatTokenLexer::tryMergeNSStringLiteral() {
377 if (Tokens.size() < 2)
379 auto &At = *(Tokens.end() - 2);
380 auto &String = *(Tokens.end() - 1);
381 if (At->isNot(tok::at) || String->isNot(tok::string_literal))
383 At->Tok.setKind(tok::string_literal);
384 At->TokenText = StringRef(At->TokenText.begin(),
385 String->TokenText.end() - At->TokenText.begin());
386 At->ColumnWidth += String->ColumnWidth;
387 At->setType(TT_ObjCStringLiteral);
388 Tokens.erase(Tokens.end() - 1);
392bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
395 if (Tokens.size() < 2)
397 auto &Hash = *(Tokens.end() - 2);
398 auto &Identifier = *(Tokens.end() - 1);
399 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
401 Hash->Tok.setKind(tok::identifier);
403 StringRef(Hash->TokenText.begin(),
404 Identifier->TokenText.end() - Hash->TokenText.begin());
405 Hash->ColumnWidth += Identifier->ColumnWidth;
406 Hash->setType(TT_JsPrivateIdentifier);
407 Tokens.erase(Tokens.end() - 1);
416bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
417 if (Tokens.size() < 2)
421 const auto String = *(Tokens.end() - 1);
422 if (String->isNot(tok::string_literal))
425 auto Prefix = *(Tokens.end() - 2);
426 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
429 if (Tokens.size() > 2) {
430 const auto Tok = *(Tokens.end() - 3);
431 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
432 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
434 Tok->ColumnWidth += Prefix->ColumnWidth;
435 Tokens.erase(Tokens.end() - 2);
441 Prefix->Tok.setKind(tok::string_literal);
443 StringRef(Prefix->TokenText.begin(),
444 String->TokenText.end() - Prefix->TokenText.begin());
445 Prefix->ColumnWidth += String->ColumnWidth;
446 Prefix->setType(TT_CSharpStringLiteral);
447 Tokens.erase(Tokens.end() - 1);
453const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
454 "assembly",
"module",
"field",
"event",
"method",
455 "param",
"property",
"return",
"type",
458bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
459 if (Tokens.size() < 2)
461 auto &NullishCoalescing = *(Tokens.end() - 2);
462 auto &
Equal = *(Tokens.end() - 1);
463 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
464 Equal->isNot(tok::equal)) {
467 NullishCoalescing->Tok.setKind(tok::equal);
468 NullishCoalescing->TokenText =
469 StringRef(NullishCoalescing->TokenText.begin(),
470 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
471 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
472 NullishCoalescing->setType(TT_NullCoalescingEqual);
473 Tokens.erase(Tokens.end() - 1);
477bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
478 if (Tokens.size() < 2)
480 const auto At = *(Tokens.end() - 2);
481 if (At->isNot(tok::at))
483 const auto Keyword = *(Tokens.end() - 1);
486 if (!Keywords.isCSharpKeyword(*
Keyword))
489 At->Tok.setKind(tok::identifier);
490 At->TokenText = StringRef(At->TokenText.begin(),
491 Keyword->TokenText.end() - At->TokenText.begin());
492 At->ColumnWidth +=
Keyword->ColumnWidth;
493 At->setType(
Keyword->getType());
494 Tokens.erase(Tokens.end() - 1);
499bool FormatTokenLexer::tryTransformCSharpForEach() {
502 auto &Identifier = *(Tokens.end() - 1);
503 if (Identifier->isNot(tok::identifier))
505 if (Identifier->TokenText !=
"foreach")
508 Identifier->setType(TT_ForEachMacro);
509 Identifier->Tok.setKind(tok::kw_for);
513bool FormatTokenLexer::tryMergeForEach() {
514 if (Tokens.size() < 2)
516 auto &For = *(Tokens.end() - 2);
517 auto &Each = *(Tokens.end() - 1);
518 if (For->isNot(tok::kw_for))
520 if (Each->isNot(tok::identifier))
522 if (Each->TokenText !=
"each")
525 For->setType(TT_ForEachMacro);
526 For->Tok.setKind(tok::kw_for);
528 For->TokenText = StringRef(For->TokenText.begin(),
529 Each->TokenText.end() - For->TokenText.begin());
530 For->ColumnWidth += Each->ColumnWidth;
531 Tokens.erase(Tokens.end() - 1);
535bool FormatTokenLexer::tryMergeLessLess() {
537 if (Tokens.size() < 3)
540 auto First = Tokens.end() - 3;
545 if (
First[1]->hasWhitespaceBefore())
548 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
549 if (
X &&
X->is(tok::less))
553 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
556 First[0]->Tok.setKind(tok::lessless);
557 First[0]->TokenText =
"<<";
558 First[0]->ColumnWidth += 1;
559 Tokens.erase(Tokens.end() - 2);
563bool FormatTokenLexer::tryMergeGreaterGreater() {
565 if (Tokens.size() < 2)
568 auto First = Tokens.end() - 2;
573 if (
First[1]->hasWhitespaceBefore())
576 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
577 if (
Tok &&
Tok->isNot(tok::kw_operator))
580 First[0]->Tok.setKind(tok::greatergreater);
581 First[0]->TokenText =
">>";
582 First[0]->ColumnWidth += 1;
583 Tokens.erase(Tokens.end() - 1);
587bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
588 if (Tokens.size() < 2)
591 auto *
First = Tokens.end() - 2;
592 auto &Suffix =
First[1];
593 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
601 if (!
Text.ends_with(
"_"))
606 Tokens.erase(&Suffix);
612 if (Tokens.size() < Kinds.size())
615 const auto *
First = Tokens.end() - Kinds.size();
616 for (
unsigned i = 0; i < Kinds.size(); ++i)
620 return tryMergeTokens(Kinds.size(), NewType);
623bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
624 if (Tokens.size() < Count)
627 const auto *
First = Tokens.end() - Count;
628 unsigned AddLength = 0;
629 for (
size_t i = 1; i < Count; ++i) {
632 if (
First[i]->hasWhitespaceBefore())
634 AddLength +=
First[i]->TokenText.size();
637 Tokens.resize(Tokens.size() - Count + 1);
639 First[0]->TokenText.size() + AddLength);
640 First[0]->ColumnWidth += AddLength;
641 First[0]->setType(NewType);
645bool FormatTokenLexer::tryMergeTokensAny(
647 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
648 return tryMergeTokens(Kinds, NewType);
657 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
658 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
659 tok::colon, tok::question, tok::tilde) ||
660 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
661 tok::kw_else, tok::kw_void, tok::kw_typeof,
662 Keywords.kw_instanceof, Keywords.kw_in) ||
663 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
666bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
676 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
677 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
681 if (!precedesOperand(Prev))
687void FormatTokenLexer::tryParseJavaTextBlock() {
688 if (FormatTok->TokenText !=
"\"\"")
691 const auto *S = Lex->getBufferLocation();
692 const auto *End = Lex->getBuffer().end();
694 if (S == End || *S !=
'\"')
700 bool Escaped =
false;
701 for (
int Count = 0; Count < 3 && S < End; ++S) {
719 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
726void FormatTokenLexer::tryParseJSRegexLiteral() {
728 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
732 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
735 if (FT->isNot(tok::comment)) {
741 if (!canPrecedeRegexLiteral(Prev))
745 const char *Offset = Lex->getBufferLocation();
746 const char *RegexBegin = Offset - RegexToken->TokenText.size();
747 StringRef Buffer = Lex->getBuffer();
748 bool InCharacterClass =
false;
749 bool HaveClosingSlash =
false;
750 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
760 InCharacterClass =
true;
763 InCharacterClass =
false;
766 if (!InCharacterClass)
767 HaveClosingSlash =
true;
772 RegexToken->setType(TT_RegexLiteral);
774 RegexToken->Tok.setKind(tok::string_literal);
775 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
776 RegexToken->ColumnWidth = RegexToken->TokenText.size();
778 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
783 auto Repeated = [&Begin, End]() {
784 return Begin + 1 < End && Begin[1] == Begin[0];
799 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
811 ++UnmatchedOpeningBraceCount;
819 else if (UnmatchedOpeningBraceCount > 0)
820 --UnmatchedOpeningBraceCount;
826 if (UnmatchedOpeningBraceCount > 0)
829 if (Verbatim && Repeated()) {
840void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
843 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
846 auto &
TokenText = CSharpStringLiteral->TokenText;
848 bool Verbatim =
false;
849 bool Interpolated =
false;
853 }
else if (
TokenText.starts_with(R
"(@")")) {
855 }
else if (
TokenText.starts_with(R
"($")")) {
860 if (!Verbatim && !Interpolated)
863 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
864 const char *Offset = StrBegin;
865 Offset += Verbatim && Interpolated ? 3 : 2;
867 const auto End = Lex->getBuffer().end();
875 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
879 size_t FirstBreak = LiteralText.find(
'\n');
880 StringRef FirstLineText = FirstBreak == StringRef::npos
882 : LiteralText.substr(0, FirstBreak);
884 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
886 size_t LastBreak = LiteralText.rfind(
'\n');
887 if (LastBreak != StringRef::npos) {
888 CSharpStringLiteral->IsMultiline =
true;
889 unsigned StartColumn = 0;
890 CSharpStringLiteral->LastLineColumnWidth =
892 StartColumn, Style.TabWidth, Encoding);
895 assert(Offset < End);
896 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
899void FormatTokenLexer::handleTableGenMultilineString() {
901 if (MultiLineString->isNot(TT_TableGenMultiLineString))
904 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
906 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
907 if (CloseOffset == StringRef::npos)
909 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
910 MultiLineString->TokenText =
Text;
911 resetLexer(SourceMgr.getFileOffset(
912 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
913 auto FirstLineText =
Text;
914 auto FirstBreak =
Text.find(
'\n');
916 if (FirstBreak != StringRef::npos) {
917 MultiLineString->IsMultiline =
true;
918 FirstLineText =
Text.substr(0, FirstBreak + 1);
920 auto LastBreak =
Text.rfind(
'\n');
922 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
923 Style.TabWidth, Encoding);
927 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
930void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
934 if (
Tok->isNot(tok::numeric_constant))
936 StringRef
Text =
Tok->TokenText;
947 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
949 if (NonDigitPos == StringRef::npos)
951 char FirstNonDigit =
Text[NonDigitPos];
952 if (NonDigitPos <
Text.size() - 1) {
953 char TheNext =
Text[NonDigitPos + 1];
955 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
958 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
961 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
963 Tok->Tok.setKind(tok::identifier);
964 Tok->Tok.setIdentifierInfo(
nullptr);
968void FormatTokenLexer::handleTemplateStrings() {
971 if (BacktickToken->is(tok::l_brace)) {
975 if (BacktickToken->is(tok::r_brace)) {
976 if (StateStack.size() == 1)
982 }
else if (BacktickToken->is(tok::unknown) &&
983 BacktickToken->TokenText ==
"`") {
990 const char *Offset = Lex->getBufferLocation();
991 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
992 for (; Offset != Lex->getBuffer().end(); ++Offset) {
993 if (Offset[0] ==
'`') {
998 if (Offset[0] ==
'\\') {
1000 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1009 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1010 BacktickToken->setType(TT_TemplateString);
1011 BacktickToken->Tok.setKind(tok::string_literal);
1012 BacktickToken->TokenText = LiteralText;
1015 size_t FirstBreak = LiteralText.find(
'\n');
1016 StringRef FirstLineText = FirstBreak == StringRef::npos
1018 : LiteralText.substr(0, FirstBreak);
1020 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1021 size_t LastBreak = LiteralText.rfind(
'\n');
1022 if (LastBreak != StringRef::npos) {
1023 BacktickToken->IsMultiline =
true;
1024 unsigned StartColumn = 0;
1025 BacktickToken->LastLineColumnWidth =
1027 StartColumn, Style.TabWidth, Encoding);
1030 SourceLocation loc = Lex->getSourceLocation(Offset);
1031 resetLexer(SourceMgr.getFileOffset(loc));
1034void FormatTokenLexer::tryParsePythonComment() {
1036 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1039 const char *CommentBegin =
1040 Lex->getBufferLocation() - HashToken->TokenText.size();
1041 size_t From = CommentBegin - Lex->getBuffer().begin();
1042 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1043 if (To == StringRef::npos)
1044 To = Lex->getBuffer().size();
1045 size_t Len = To - From;
1046 HashToken->setType(TT_LineComment);
1047 HashToken->Tok.setKind(tok::comment);
1048 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1049 SourceLocation Loc = To < Lex->getBuffer().size()
1050 ? Lex->getSourceLocation(CommentBegin + Len)
1051 : SourceMgr.getLocForEndOfFile(ID);
1052 resetLexer(SourceMgr.getFileOffset(Loc));
1055bool FormatTokenLexer::tryMerge_TMacro() {
1056 if (Tokens.size() < 4)
1059 if (
Last->isNot(tok::r_paren))
1063 if (String->isNot(tok::string_literal) || String->IsMultiline)
1066 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1070 if (
Macro->TokenText !=
"_T")
1073 const char *Start =
Macro->TokenText.data();
1074 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1075 String->TokenText = StringRef(Start, End - Start);
1076 String->IsFirst =
Macro->IsFirst;
1077 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1078 String->WhitespaceRange =
Macro->WhitespaceRange;
1079 String->OriginalColumn =
Macro->OriginalColumn;
1081 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1082 String->NewlinesBefore =
Macro->NewlinesBefore;
1083 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1088 Tokens.back() = String;
1089 if (FirstInLineIndex >= Tokens.size())
1090 FirstInLineIndex = Tokens.size() - 1;
1094bool FormatTokenLexer::tryMergeConflictMarkers() {
1095 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1109 unsigned FirstInLineOffset;
1110 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1111 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1112 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1114 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1115 if (LineOffset == StringRef::npos)
1120 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1121 StringRef LineStart;
1122 if (FirstSpace == StringRef::npos)
1123 LineStart = Buffer.substr(LineOffset);
1125 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1128 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1129 Type = TT_ConflictStart;
1130 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1131 LineStart ==
"====") {
1132 Type = TT_ConflictAlternative;
1133 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1134 Type = TT_ConflictEnd;
1137 if (
Type != TT_Unknown) {
1140 Tokens.resize(FirstInLineIndex + 1);
1144 Tokens.back()->setType(
Type);
1145 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1147 Tokens.push_back(
Next);
1156 Token
Tok = FormatTok->
Tok;
1157 StringRef
TokenText = FormatTok->TokenText;
1160 FormatTok =
new (Allocator.Allocate())
FormatToken;
1161 FormatTok->Tok =
Tok;
1162 SourceLocation TokLocation =
1163 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1164 FormatTok->Tok.setLocation(TokLocation);
1165 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1167 FormatTok->ColumnWidth = 1;
1179void FormatTokenLexer::truncateToken(
size_t NewLen) {
1180 assert(NewLen <= FormatTok->
TokenText.size());
1181 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1182 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1183 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1185 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1187 FormatTok->Tok.setLength(NewLen);
1197 const unsigned char *
const Begin =
Text.bytes_begin();
1198 const unsigned char *
const End =
Text.bytes_end();
1199 const unsigned char *Cur = Begin;
1203 }
else if (Cur[0] ==
'\\') {
1209 const auto *Lookahead = Cur + 1;
1216 Cur = Lookahead + 1;
1227 return getStashedToken();
1230 FormatTok =
new (Allocator.Allocate())
FormatToken;
1231 readRawToken(*FormatTok);
1232 SourceLocation WhitespaceStart =
1234 FormatTok->
IsFirst = IsFirstToken;
1235 IsFirstToken =
false;
1241 unsigned WhitespaceLength = TrailingWhitespace;
1242 while (FormatTok->
isNot(tok::eof)) {
1244 if (LeadingWhitespace == 0)
1246 if (LeadingWhitespace < FormatTok->
TokenText.size())
1247 truncateToken(LeadingWhitespace);
1249 bool InEscape =
false;
1250 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1256 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1271 i > 0 &&
Text[i - 1] ==
'\n' &&
1272 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1273 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1285 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1292 assert([&]() ->
bool {
1296 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1306 WhitespaceLength +=
Text.size();
1307 readRawToken(*FormatTok);
1310 if (FormatTok->is(tok::unknown))
1311 FormatTok->setType(TT_ImplicitStringLiteral);
1313 const bool IsCpp = Style.isCpp();
1322 if (
const auto Text = FormatTok->TokenText;
1323 Text.starts_with(
"//") &&
1324 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1325 assert(FormatTok->is(tok::comment));
1326 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1327 Pos =
Text.find(
'\\', Pos)) {
1328 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1329 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1336 if (Style.isVerilog()) {
1337 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1338 SmallVector<StringRef, 1> Matches;
1344 if (FormatTok->is(tok::numeric_constant)) {
1346 auto Quote = FormatTok->TokenText.find(
'\'');
1347 if (Quote != StringRef::npos)
1348 truncateToken(Quote);
1349 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1350 FormatTok->Tok.setKind(tok::raw_identifier);
1351 }
else if (FormatTok->is(tok::raw_identifier)) {
1352 if (FormatTok->TokenText ==
"`") {
1353 FormatTok->Tok.setIdentifierInfo(
nullptr);
1354 FormatTok->Tok.setKind(tok::hash);
1355 }
else if (FormatTok->TokenText ==
"``") {
1356 FormatTok->Tok.setIdentifierInfo(
nullptr);
1357 FormatTok->Tok.setKind(tok::hashhash);
1358 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1359 NumberBase.match(FormatTok->TokenText, &Matches)) {
1364 truncateToken(Matches[0].size());
1365 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1370 FormatTok->WhitespaceRange = SourceRange(
1371 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1373 FormatTok->OriginalColumn = Column;
1375 TrailingWhitespace = 0;
1376 if (FormatTok->is(tok::comment)) {
1378 StringRef UntrimmedText = FormatTok->TokenText;
1379 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1380 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1381 }
else if (FormatTok->is(tok::raw_identifier)) {
1382 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1383 FormatTok->Tok.setIdentifierInfo(&Info);
1384 FormatTok->Tok.setKind(Info.getTokenID());
1385 if (Style.isJava() &&
1386 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1387 tok::kw_operator)) {
1388 FormatTok->Tok.setKind(tok::identifier);
1389 }
else if (Style.isJavaScript() &&
1390 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1391 tok::kw_operator)) {
1392 FormatTok->Tok.setKind(tok::identifier);
1393 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1394 FormatTok->Tok.setKind(tok::identifier);
1395 }
else if (Style.isVerilog()) {
1396 if (Keywords.isVerilogIdentifier(*FormatTok))
1397 FormatTok->Tok.setKind(tok::identifier);
1400 if (Tokens.size() - FirstInLineIndex >= 3u &&
1401 Tokens[FirstInLineIndex]->is(tok::hash) &&
1402 Tokens[FirstInLineIndex + 1u]->is(tok::pp_pragma) &&
1403 Tokens[FirstInLineIndex + 2u]->is(Keywords.kw_protect) &&
1405 Keywords.kw_data_block, Keywords.kw_data_decrypt_key,
1406 Keywords.kw_data_public_key, Keywords.kw_digest_block,
1407 Keywords.kw_digest_decrypt_key, Keywords.kw_digest_public_key,
1408 Keywords.kw_key_block, Keywords.kw_key_public_key)) {
1409 VerilogProtectedBlock =
true;
1412 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1413 Greater || FormatTok->is(tok::lessless)) {
1414 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1415 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1418 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1419 tryParseJavaTextBlock();
1422 if (Style.isVerilog() && !Tokens.empty() &&
1423 Tokens.back()->is(TT_VerilogNumberBase) &&
1424 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1426 FormatTok->Tok.setKind(tok::numeric_constant);
1431 StringRef
Text = FormatTok->TokenText;
1432 size_t FirstNewlinePos =
Text.find(
'\n');
1433 if (FirstNewlinePos == StringRef::npos) {
1436 FormatTok->ColumnWidth =
1438 Column += FormatTok->ColumnWidth;
1440 FormatTok->IsMultiline =
true;
1444 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1449 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1450 Column = FormatTok->LastLineColumnWidth;
1454 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1455 auto it = Macros.find(Identifier);
1456 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1457 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1459 it != Macros.end()) {
1460 FormatTok->setType(it->second);
1461 if (it->second == TT_IfMacro) {
1466 FormatTok->Tok.setKind(tok::kw_if);
1468 }
else if (FormatTok->is(tok::identifier)) {
1469 if (MacroBlockBeginRegex.match(
Text))
1470 FormatTok->setType(TT_MacroBlockBegin);
1471 else if (MacroBlockEndRegex.match(
Text))
1472 FormatTok->setType(TT_MacroBlockEnd);
1473 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1474 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1475 else if (TemplateNames.contains(Identifier))
1476 FormatTok->setFinalizedType(TT_TemplateName);
1477 else if (TypeNames.contains(Identifier))
1478 FormatTok->setFinalizedType(TT_TypeName);
1479 else if (VariableTemplates.contains(Identifier))
1480 FormatTok->setFinalizedType(TT_VariableTemplate);
1489 if (!VerilogProtectedBlock ||
Tok.NewlinesBefore == 0)
1491 VerilogProtectedBlock =
false;
1496 const char *
const Start = Lex->getBufferLocation();
1497 size_t Len = Lex->getBuffer().end() - Start;
1504 static const llvm::Regex NextDirective(
"[\n\r][ \t]*`[^\n\r]");
1505 SmallVector<StringRef, 1> Matches;
1506 if (NextDirective.match(StringRef(Start, Len), &Matches)) {
1507 assert(Matches.size() == 1);
1508 Len = Matches[0].begin() - Start;
1511 Tok.Tok.setKind(tok::string_literal);
1512 Tok.Tok.setLength(Len);
1513 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1514 Tok.setFinalizedType(TT_VerilogProtected);
1515 Lex->seek(Lex->getCurrentBufferOffset() + Len,
1520bool FormatTokenLexer::readRawTokenVerilogSpecific(
FormatToken &
Tok) {
1521 if (readVerilogProtected(
Tok))
1523 const char *Start = Lex->getBufferLocation();
1533 if (Start[1] ==
'`')
1546 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1549 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1550 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1551 Start[Len] !=
' ') {
1554 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1555 Start[Len + 2] ==
'\n') {
1557 }
else if (Start[Len] ==
'\\' &&
1558 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1572 Tok.Tok.setKind(tok::raw_identifier);
1573 Tok.Tok.setLength(Len);
1574 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1575 Tok.Tok.setRawIdentifierData(Start);
1576 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1583 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok))
1584 Lex->LexFromRawLexer(
Tok.Tok);
1585 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1586 Tok.Tok.getLength());
1589 if (
Tok.is(tok::unknown)) {
1590 if (
Tok.TokenText.starts_with(
"\"")) {
1591 Tok.Tok.setKind(tok::string_literal);
1592 Tok.IsUnterminatedLiteral =
true;
1593 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1594 Tok.Tok.setKind(tok::string_literal);
1598 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1599 Tok.Tok.setKind(tok::string_literal);
1602 FormattingDisabled =
false;
1604 Tok.Finalized = FormattingDisabled;
1607 FormattingDisabled =
true;
1610void FormatTokenLexer::resetLexer(
unsigned Offset) {
1611 StringRef Buffer = SourceMgr.getBufferData(ID);
1612 Lex = std::make_unique<Lexer>(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1613 Buffer.begin(), Buffer.begin() + Offset,
1615 Lex->SetKeepWhitespaceMode(
true);
1616 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.
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.