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), MacroBlockBeginRegex(Style.MacroBlockBegin),
37 MacroBlockEndRegex(Style.MacroBlockEnd), VerilogProtectedBlock(
false) {
38 Lex = std::make_unique<Lexer>(ID, SourceMgr.getBufferOrFake(ID), SourceMgr,
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);
91 enum { FO_None, FO_CurrentLine, FO_NextLine } FormatOff = FO_None;
92 llvm::Regex FormatOffRegex(Style.OneLineFormatOffRegex);
94 Tokens.push_back(getNextToken());
96 auto &
Tok = *Tokens.back();
102 Tok.Finalized =
true;
103 FormatOff = FO_CurrentLine;
108 Tok.Finalized =
true;
114 if (!FormattingDisabled && FormatOffRegex.match(
Tok.TokenText)) {
115 if (
Tok.is(tok::comment) &&
117 Tok.Finalized =
true;
118 FormatOff = FO_NextLine;
120 for (
auto *
Token : reverse(Tokens)) {
121 Token->Finalized =
true;
122 if (
Token->NewlinesBefore > 0)
125 FormatOff = FO_CurrentLine;
130 if (Style.isJavaScript()) {
131 tryParseJSRegexLiteral();
132 handleTemplateStrings();
133 }
else if (Style.isTextProto()) {
134 tryParsePythonComment();
137 tryMergePreviousTokens();
139 if (Style.isCSharp()) {
142 handleCSharpVerbatimAndInterpolatedStrings();
143 }
else if (Style.isTableGen()) {
144 handleTableGenMultilineString();
145 handleTableGenNumericLikeIdentifier();
148 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
149 FirstInLineIndex = Tokens.size() - 1;
150 }
while (Tokens.back()->isNot(tok::eof));
152 if (Style.InsertNewlineAtEOF) {
153 auto &TokEOF = *Tokens.back();
154 if (TokEOF.NewlinesBefore == 0) {
155 TokEOF.NewlinesBefore = 1;
156 TokEOF.OriginalColumn = 0;
163void FormatTokenLexer::tryMergePreviousTokens() {
164 if (tryMerge_TMacro())
166 if (tryMergeConflictMarkers())
168 if (tryMergeLessLess())
170 if (tryMergeGreaterGreater())
172 if (tryMergeForEach())
175 if ((Style.Language == FormatStyle::LK_Cpp ||
176 Style.Language == FormatStyle::LK_ObjC) &&
177 tryMergeUserDefinedLiteral()) {
181 if (Style.isJavaScript() || Style.isCSharp()) {
182 static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
184 static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
186 static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
188 if (tryMergeTokens(FatArrow, TT_FatArrow))
190 if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
192 Tokens.back()->Tok.setKind(tok::pipepipe);
195 if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
197 Tokens.back()->Tok.setKind(tok::period);
200 if (tryMergeNullishCoalescingEqual())
203 if (Style.isCSharp()) {
205 tok::question, tok::l_square};
207 if (tryMergeCSharpKeywordVariables())
209 if (tryMergeCSharpStringLiteral())
211 if (tryTransformCSharpForEach())
213 if (tryMergeTokens(CSharpNullConditionalLSquare,
214 TT_CSharpNullConditionalLSquare)) {
216 Tokens.back()->Tok.setKind(tok::l_square);
222 if (tryMergeNSStringLiteral())
225 if (Style.isJavaScript()) {
226 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
229 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
231 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
234 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
235 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
238 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
240 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
242 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
244 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
246 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
247 Tokens.back()->Tok.setKind(tok::starequal);
250 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
251 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
253 Tokens.back()->Tok.setKind(tok::equal);
256 if (tryMergeJSPrivateIdentifier())
258 }
else if (Style.isJava()) {
260 tok::greater, tok::greater, tok::greaterequal};
261 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
263 }
else if (Style.isVerilog()) {
265 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
266 Tokens.end()[-2]->is(tok::numeric_constant) &&
267 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
269 tryMergeTokens(2, TT_Unknown)) {
273 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
281 if (Tokens.back()->TokenText.size() == 1 &&
282 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
283 TT_BinaryOperator)) {
284 Tokens.back()->Tok.setKind(tok::caret);
288 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
289 Tokens.back()->Tok.setKind(tok::lessless);
292 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
293 Tokens.back()->Tok.setKind(tok::greatergreater);
296 if (tryMergeTokensAny({{tok::lessless, tok::equal},
297 {tok::lessless, tok::lessequal},
298 {tok::greatergreater, tok::equal},
299 {tok::greatergreater, tok::greaterequal},
300 {tok::colon, tok::equal},
301 {tok::colon, tok::slash}},
302 TT_BinaryOperator)) {
307 if (tryMergeTokensAny({{tok::star, tok::star},
308 {tok::lessless, tok::less},
309 {tok::greatergreater, tok::greater},
310 {tok::exclaimequal, tok::equal},
311 {tok::exclaimequal, tok::question},
312 {tok::equalequal, tok::equal},
313 {tok::equalequal, tok::question}},
314 TT_BinaryOperator)) {
319 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
320 {tok::plus, tok::star, tok::greater},
321 {tok::minusequal, tok::greater},
322 {tok::minus, tok::star, tok::greater},
323 {tok::less, tok::arrow},
324 {tok::equal, tok::greater},
325 {tok::star, tok::greater},
326 {tok::pipeequal, tok::greater},
327 {tok::pipe, tok::arrow}},
328 TT_BinaryOperator) ||
329 Tokens.back()->
is(tok::arrow)) {
333 if (Tokens.size() >= 3 &&
334 Tokens[Tokens.size() - 3]->is(Keywords.kw_verilogHash) &&
335 Tokens[Tokens.size() - 2]->isOneOf(tok::minus, tok::equal) &&
336 Tokens[Tokens.size() - 1]->is(Keywords.kw_verilogHash) &&
337 tryMergeTokens(3, TT_BinaryOperator)) {
338 Tokens.back()->setFinalizedType(TT_BinaryOperator);
342 }
else if (Style.isTableGen()) {
344 if (tryMergeTokens({tok::l_square, tok::l_brace},
345 TT_TableGenMultiLineString)) {
347 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
348 Tokens.back()->Tok.setKind(tok::string_literal);
353 if (tryMergeTokens({tok::exclaim, tok::identifier},
354 TT_TableGenBangOperator)) {
355 Tokens.back()->Tok.setKind(tok::identifier);
356 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
357 if (Tokens.back()->TokenText ==
"!cond")
358 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
360 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
363 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
366 Tokens.back()->Tok.setKind(tok::identifier);
367 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
368 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
372 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
373 Tokens.back()->Tok.setKind(tok::numeric_constant);
376 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
377 Tokens.back()->Tok.setKind(tok::numeric_constant);
383bool FormatTokenLexer::tryMergeNSStringLiteral() {
384 if (Tokens.size() < 2)
386 auto &At = *(Tokens.end() - 2);
387 auto &String = *(Tokens.end() - 1);
388 if (At->isNot(tok::at) || String->isNot(tok::string_literal))
390 At->Tok.setKind(tok::string_literal);
391 At->TokenText = StringRef(At->TokenText.begin(),
392 String->TokenText.end() - At->TokenText.begin());
393 At->ColumnWidth += String->ColumnWidth;
394 At->setType(TT_ObjCStringLiteral);
395 Tokens.erase(Tokens.end() - 1);
399bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
402 if (Tokens.size() < 2)
404 auto &Hash = *(Tokens.end() - 2);
405 auto &Identifier = *(Tokens.end() - 1);
406 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
408 Hash->Tok.setKind(tok::identifier);
410 StringRef(Hash->TokenText.begin(),
411 Identifier->TokenText.end() - Hash->TokenText.begin());
412 Hash->ColumnWidth += Identifier->ColumnWidth;
413 Hash->setType(TT_JsPrivateIdentifier);
414 Tokens.erase(Tokens.end() - 1);
423bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
424 if (Tokens.size() < 2)
428 const auto String = *(Tokens.end() - 1);
429 if (String->isNot(tok::string_literal))
432 auto Prefix = *(Tokens.end() - 2);
433 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
436 if (Tokens.size() > 2) {
437 const auto Tok = *(Tokens.end() - 3);
438 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
439 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
441 Tok->ColumnWidth += Prefix->ColumnWidth;
442 Tokens.erase(Tokens.end() - 2);
448 Prefix->Tok.setKind(tok::string_literal);
450 StringRef(Prefix->TokenText.begin(),
451 String->TokenText.end() - Prefix->TokenText.begin());
452 Prefix->ColumnWidth += String->ColumnWidth;
453 Prefix->setType(TT_CSharpStringLiteral);
454 Tokens.erase(Tokens.end() - 1);
460const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
461 "assembly",
"module",
"field",
"event",
"method",
462 "param",
"property",
"return",
"type",
465bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
466 if (Tokens.size() < 2)
468 auto &NullishCoalescing = *(Tokens.end() - 2);
469 auto &
Equal = *(Tokens.end() - 1);
470 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
471 Equal->isNot(tok::equal)) {
474 NullishCoalescing->Tok.setKind(tok::equal);
475 NullishCoalescing->TokenText =
476 StringRef(NullishCoalescing->TokenText.begin(),
477 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
478 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
479 NullishCoalescing->setType(TT_NullCoalescingEqual);
480 Tokens.erase(Tokens.end() - 1);
484bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
485 if (Tokens.size() < 2)
487 const auto At = *(Tokens.end() - 2);
488 if (At->isNot(tok::at))
490 const auto Keyword = *(Tokens.end() - 1);
493 if (!Keywords.isCSharpKeyword(*
Keyword))
496 At->Tok.setKind(tok::identifier);
497 At->TokenText = StringRef(At->TokenText.begin(),
498 Keyword->TokenText.end() - At->TokenText.begin());
499 At->ColumnWidth +=
Keyword->ColumnWidth;
500 At->setType(
Keyword->getType());
501 Tokens.erase(Tokens.end() - 1);
506bool FormatTokenLexer::tryTransformCSharpForEach() {
509 auto &Identifier = *(Tokens.end() - 1);
510 if (Identifier->isNot(tok::identifier))
512 if (Identifier->TokenText !=
"foreach")
515 Identifier->setType(TT_ForEachMacro);
516 Identifier->Tok.setKind(tok::kw_for);
520bool FormatTokenLexer::tryMergeForEach() {
521 if (Tokens.size() < 2)
523 auto &For = *(Tokens.end() - 2);
524 auto &Each = *(Tokens.end() - 1);
525 if (For->isNot(tok::kw_for))
527 if (Each->isNot(tok::identifier))
529 if (Each->TokenText !=
"each")
532 For->setType(TT_ForEachMacro);
533 For->Tok.setKind(tok::kw_for);
535 For->TokenText = StringRef(For->TokenText.begin(),
536 Each->TokenText.end() - For->TokenText.begin());
537 For->ColumnWidth += Each->ColumnWidth;
538 Tokens.erase(Tokens.end() - 1);
542bool FormatTokenLexer::tryMergeLessLess() {
544 if (Tokens.size() < 3)
547 auto First = Tokens.end() - 3;
552 if (
First[1]->hasWhitespaceBefore())
555 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
556 if (
X &&
X->is(tok::less))
560 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
563 First[0]->Tok.setKind(tok::lessless);
564 First[0]->TokenText =
"<<";
565 First[0]->ColumnWidth += 1;
566 Tokens.erase(Tokens.end() - 2);
570bool FormatTokenLexer::tryMergeGreaterGreater() {
572 if (Tokens.size() < 2)
575 auto First = Tokens.end() - 2;
580 if (
First[1]->hasWhitespaceBefore())
583 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
584 if (
Tok &&
Tok->isNot(tok::kw_operator))
587 First[0]->Tok.setKind(tok::greatergreater);
588 First[0]->TokenText =
">>";
589 First[0]->ColumnWidth += 1;
590 Tokens.erase(Tokens.end() - 1);
594bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
595 if (Tokens.size() < 2)
598 auto *
First = Tokens.end() - 2;
599 auto &Suffix =
First[1];
600 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
608 if (!
Text.ends_with(
"_"))
613 Tokens.erase(&Suffix);
619 if (Tokens.size() < Kinds.size())
622 const auto *
First = Tokens.end() - Kinds.size();
623 for (
unsigned i = 0; i < Kinds.size(); ++i)
627 return tryMergeTokens(Kinds.size(), NewType);
630bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
631 if (Tokens.size() < Count)
634 const auto *
First = Tokens.end() - Count;
635 unsigned AddLength = 0;
636 for (
size_t i = 1; i < Count; ++i) {
639 if (
First[i]->hasWhitespaceBefore())
641 AddLength +=
First[i]->TokenText.size();
644 Tokens.resize(Tokens.size() - Count + 1);
646 First[0]->TokenText.size() + AddLength);
647 First[0]->ColumnWidth += AddLength;
648 First[0]->setType(NewType);
652bool FormatTokenLexer::tryMergeTokensAny(
654 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
655 return tryMergeTokens(Kinds, NewType);
664 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
665 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
666 tok::colon, tok::question, tok::tilde) ||
667 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
668 tok::kw_else, tok::kw_void, tok::kw_typeof,
669 Keywords.kw_instanceof, Keywords.kw_in) ||
670 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
673bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
683 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
684 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
688 if (!precedesOperand(Prev))
694void FormatTokenLexer::tryParseJavaTextBlock() {
695 if (FormatTok->TokenText !=
"\"\"")
698 const auto *S = Lex->getBufferLocation();
699 const auto *End = Lex->getBuffer().end();
701 if (S == End || *S !=
'\"')
707 bool Escaped =
false;
708 for (
int Count = 0; Count < 3 && S < End; ++S) {
726 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
733void FormatTokenLexer::tryParseJSRegexLiteral() {
735 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
739 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
742 if (FT->isNot(tok::comment)) {
748 if (!canPrecedeRegexLiteral(Prev))
752 const char *Offset = Lex->getBufferLocation();
753 const char *RegexBegin = Offset - RegexToken->TokenText.size();
754 StringRef Buffer = Lex->getBuffer();
755 bool InCharacterClass =
false;
756 bool HaveClosingSlash =
false;
757 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
767 InCharacterClass =
true;
770 InCharacterClass =
false;
773 if (!InCharacterClass)
774 HaveClosingSlash =
true;
779 RegexToken->setType(TT_RegexLiteral);
781 RegexToken->Tok.setKind(tok::string_literal);
782 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
783 RegexToken->ColumnWidth = RegexToken->TokenText.size();
785 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
790 auto Repeated = [&Begin, End]() {
791 return Begin + 1 < End && Begin[1] == Begin[0];
806 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
818 ++UnmatchedOpeningBraceCount;
826 else if (UnmatchedOpeningBraceCount > 0)
827 --UnmatchedOpeningBraceCount;
833 if (UnmatchedOpeningBraceCount > 0)
836 if (Verbatim && Repeated()) {
847void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
850 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
853 auto &
TokenText = CSharpStringLiteral->TokenText;
855 bool Verbatim =
false;
856 bool Interpolated =
false;
860 }
else if (
TokenText.starts_with(R
"(@")")) {
862 }
else if (
TokenText.starts_with(R
"($")")) {
867 if (!Verbatim && !Interpolated)
870 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
871 const char *Offset = StrBegin;
872 Offset += Verbatim && Interpolated ? 3 : 2;
874 const auto End = Lex->getBuffer().end();
882 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
886 size_t FirstBreak = LiteralText.find(
'\n');
887 StringRef FirstLineText = FirstBreak == StringRef::npos
889 : LiteralText.substr(0, FirstBreak);
891 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
893 size_t LastBreak = LiteralText.rfind(
'\n');
894 if (LastBreak != StringRef::npos) {
895 CSharpStringLiteral->IsMultiline =
true;
896 unsigned StartColumn = 0;
897 CSharpStringLiteral->LastLineColumnWidth =
899 StartColumn, Style.TabWidth, Encoding);
902 assert(Offset < End);
903 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
906void FormatTokenLexer::handleTableGenMultilineString() {
908 if (MultiLineString->isNot(TT_TableGenMultiLineString))
911 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
913 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
914 if (CloseOffset == StringRef::npos)
916 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
917 MultiLineString->TokenText =
Text;
918 resetLexer(SourceMgr.getFileOffset(
919 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
920 auto FirstLineText =
Text;
921 auto FirstBreak =
Text.find(
'\n');
923 if (FirstBreak != StringRef::npos) {
924 MultiLineString->IsMultiline =
true;
925 FirstLineText =
Text.substr(0, FirstBreak + 1);
927 auto LastBreak =
Text.rfind(
'\n');
929 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
930 Style.TabWidth, Encoding);
934 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
937void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
941 if (
Tok->isNot(tok::numeric_constant))
943 StringRef
Text =
Tok->TokenText;
954 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
956 if (NonDigitPos == StringRef::npos)
958 char FirstNonDigit =
Text[NonDigitPos];
959 if (NonDigitPos <
Text.size() - 1) {
960 char TheNext =
Text[NonDigitPos + 1];
962 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
965 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
968 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
970 Tok->Tok.setKind(tok::identifier);
971 Tok->Tok.setIdentifierInfo(
nullptr);
975void FormatTokenLexer::handleTemplateStrings() {
978 if (BacktickToken->is(tok::l_brace)) {
982 if (BacktickToken->is(tok::r_brace)) {
983 if (StateStack.size() == 1)
989 }
else if (BacktickToken->is(tok::unknown) &&
990 BacktickToken->TokenText ==
"`") {
997 const char *Offset = Lex->getBufferLocation();
998 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
999 for (; Offset != Lex->getBuffer().end(); ++Offset) {
1000 if (Offset[0] ==
'`') {
1005 if (Offset[0] ==
'\\') {
1007 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1016 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1017 BacktickToken->setType(TT_TemplateString);
1018 BacktickToken->Tok.setKind(tok::string_literal);
1019 BacktickToken->TokenText = LiteralText;
1022 size_t FirstBreak = LiteralText.find(
'\n');
1023 StringRef FirstLineText = FirstBreak == StringRef::npos
1025 : LiteralText.substr(0, FirstBreak);
1027 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1028 size_t LastBreak = LiteralText.rfind(
'\n');
1029 if (LastBreak != StringRef::npos) {
1030 BacktickToken->IsMultiline =
true;
1031 unsigned StartColumn = 0;
1032 BacktickToken->LastLineColumnWidth =
1034 StartColumn, Style.TabWidth, Encoding);
1037 SourceLocation loc = Lex->getSourceLocation(Offset);
1038 resetLexer(SourceMgr.getFileOffset(loc));
1041void FormatTokenLexer::tryParsePythonComment() {
1043 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1046 const char *CommentBegin =
1047 Lex->getBufferLocation() - HashToken->TokenText.size();
1048 size_t From = CommentBegin - Lex->getBuffer().begin();
1049 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1050 if (To == StringRef::npos)
1051 To = Lex->getBuffer().size();
1052 size_t Len = To - From;
1053 HashToken->setType(TT_LineComment);
1054 HashToken->Tok.setKind(tok::comment);
1055 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1056 SourceLocation Loc = To < Lex->getBuffer().size()
1057 ? Lex->getSourceLocation(CommentBegin + Len)
1058 : SourceMgr.getLocForEndOfFile(ID);
1059 resetLexer(SourceMgr.getFileOffset(Loc));
1062bool FormatTokenLexer::tryMerge_TMacro() {
1063 if (Tokens.size() < 4)
1066 if (
Last->isNot(tok::r_paren))
1070 if (String->isNot(tok::string_literal) || String->IsMultiline)
1073 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1077 if (
Macro->TokenText !=
"_T")
1080 const char *Start =
Macro->TokenText.data();
1081 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1082 String->TokenText = StringRef(Start, End - Start);
1083 String->IsFirst =
Macro->IsFirst;
1084 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1085 String->WhitespaceRange =
Macro->WhitespaceRange;
1086 String->OriginalColumn =
Macro->OriginalColumn;
1088 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1089 String->NewlinesBefore =
Macro->NewlinesBefore;
1090 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1095 Tokens.back() = String;
1096 if (FirstInLineIndex >= Tokens.size())
1097 FirstInLineIndex = Tokens.size() - 1;
1101bool FormatTokenLexer::tryMergeConflictMarkers() {
1102 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1116 unsigned FirstInLineOffset;
1117 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1118 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1119 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1121 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1122 if (LineOffset == StringRef::npos)
1127 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1128 StringRef LineStart;
1129 if (FirstSpace == StringRef::npos)
1130 LineStart = Buffer.substr(LineOffset);
1132 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1135 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1136 Type = TT_ConflictStart;
1137 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1138 LineStart ==
"====") {
1139 Type = TT_ConflictAlternative;
1140 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1141 Type = TT_ConflictEnd;
1144 if (
Type != TT_Unknown) {
1147 Tokens.resize(FirstInLineIndex + 1);
1151 Tokens.back()->setType(
Type);
1152 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1154 Tokens.push_back(
Next);
1163 Token
Tok = FormatTok->
Tok;
1164 StringRef
TokenText = FormatTok->TokenText;
1167 FormatTok =
new (Allocator.Allocate())
FormatToken;
1168 FormatTok->Tok =
Tok;
1169 SourceLocation TokLocation =
1170 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1171 FormatTok->Tok.setLocation(TokLocation);
1172 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1174 FormatTok->ColumnWidth = 1;
1186void FormatTokenLexer::truncateToken(
size_t NewLen) {
1187 assert(NewLen <= FormatTok->
TokenText.size());
1188 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1189 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1190 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1192 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1194 FormatTok->Tok.setLength(NewLen);
1204 const unsigned char *
const Begin =
Text.bytes_begin();
1205 const unsigned char *
const End =
Text.bytes_end();
1206 const unsigned char *Cur = Begin;
1210 }
else if (Cur[0] ==
'\\') {
1216 const auto *Lookahead = Cur + 1;
1223 Cur = Lookahead + 1;
1234 return getStashedToken();
1237 FormatTok =
new (Allocator.Allocate())
FormatToken;
1238 readRawToken(*FormatTok);
1239 SourceLocation WhitespaceStart =
1241 FormatTok->
IsFirst = IsFirstToken;
1242 IsFirstToken =
false;
1248 unsigned WhitespaceLength = TrailingWhitespace;
1249 while (FormatTok->
isNot(tok::eof)) {
1251 if (LeadingWhitespace == 0)
1253 if (LeadingWhitespace < FormatTok->
TokenText.size())
1254 truncateToken(LeadingWhitespace);
1256 bool InEscape =
false;
1257 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1263 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1278 i > 0 &&
Text[i - 1] ==
'\n' &&
1279 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1280 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1292 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1299 assert([&]() ->
bool {
1303 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1313 WhitespaceLength +=
Text.size();
1314 readRawToken(*FormatTok);
1317 if (FormatTok->is(tok::unknown))
1318 FormatTok->setType(TT_ImplicitStringLiteral);
1320 const bool IsCpp = Style.isCpp();
1329 if (
const auto Text = FormatTok->TokenText;
1330 Text.starts_with(
"//") &&
1331 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1332 assert(FormatTok->is(tok::comment));
1333 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1334 Pos =
Text.find(
'\\', Pos)) {
1335 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1336 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1343 if (Style.isVerilog()) {
1344 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1345 SmallVector<StringRef, 1> Matches;
1351 if (FormatTok->is(tok::numeric_constant)) {
1353 auto Quote = FormatTok->TokenText.find(
'\'');
1354 if (Quote != StringRef::npos)
1355 truncateToken(Quote);
1356 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1357 FormatTok->Tok.setKind(tok::raw_identifier);
1358 }
else if (FormatTok->is(tok::raw_identifier)) {
1359 if (FormatTok->TokenText ==
"`") {
1360 FormatTok->Tok.setIdentifierInfo(
nullptr);
1361 FormatTok->Tok.setKind(tok::hash);
1362 }
else if (FormatTok->TokenText ==
"``") {
1363 FormatTok->Tok.setIdentifierInfo(
nullptr);
1364 FormatTok->Tok.setKind(tok::hashhash);
1365 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1366 NumberBase.match(FormatTok->TokenText, &Matches)) {
1371 truncateToken(Matches[0].size());
1372 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1377 FormatTok->WhitespaceRange = SourceRange(
1378 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1380 FormatTok->OriginalColumn = Column;
1382 TrailingWhitespace = 0;
1383 if (FormatTok->is(tok::comment)) {
1385 StringRef UntrimmedText = FormatTok->TokenText;
1386 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1387 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1388 }
else if (FormatTok->is(tok::raw_identifier)) {
1389 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1390 FormatTok->Tok.setIdentifierInfo(&Info);
1391 FormatTok->Tok.setKind(Info.getTokenID());
1392 if (Style.isJava() &&
1393 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1394 tok::kw_operator)) {
1395 FormatTok->Tok.setKind(tok::identifier);
1396 }
else if (Style.isJavaScript() &&
1397 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1398 tok::kw_operator)) {
1399 FormatTok->Tok.setKind(tok::identifier);
1400 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1401 FormatTok->Tok.setKind(tok::identifier);
1402 }
else if (Style.isVerilog()) {
1403 if (Keywords.isVerilogIdentifier(*FormatTok))
1404 FormatTok->Tok.setKind(tok::identifier);
1407 if (Tokens.size() - FirstInLineIndex >= 3u &&
1408 Tokens[FirstInLineIndex]->is(tok::hash) &&
1409 Tokens[FirstInLineIndex + 1u]->is(tok::pp_pragma) &&
1410 Tokens[FirstInLineIndex + 2u]->is(Keywords.kw_protect) &&
1412 Keywords.kw_data_block, Keywords.kw_data_decrypt_key,
1413 Keywords.kw_data_public_key, Keywords.kw_digest_block,
1414 Keywords.kw_digest_decrypt_key, Keywords.kw_digest_public_key,
1415 Keywords.kw_key_block, Keywords.kw_key_public_key)) {
1416 VerilogProtectedBlock =
true;
1419 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1420 Greater || FormatTok->is(tok::lessless)) {
1421 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1422 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1425 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1426 tryParseJavaTextBlock();
1429 if (Style.isVerilog() && !Tokens.empty() &&
1430 Tokens.back()->is(TT_VerilogNumberBase) &&
1431 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1433 FormatTok->Tok.setKind(tok::numeric_constant);
1438 StringRef
Text = FormatTok->TokenText;
1439 size_t FirstNewlinePos =
Text.find(
'\n');
1440 if (FirstNewlinePos == StringRef::npos) {
1443 FormatTok->ColumnWidth =
1445 Column += FormatTok->ColumnWidth;
1447 FormatTok->IsMultiline =
true;
1451 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1456 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1457 Column = FormatTok->LastLineColumnWidth;
1461 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1462 auto it = Macros.find(Identifier);
1463 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1464 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1466 it != Macros.end()) {
1467 FormatTok->setType(it->second);
1468 if (it->second == TT_IfMacro) {
1473 FormatTok->Tok.setKind(tok::kw_if);
1475 }
else if (FormatTok->is(tok::identifier)) {
1476 if (MacroBlockBeginRegex.match(
Text))
1477 FormatTok->setType(TT_MacroBlockBegin);
1478 else if (MacroBlockEndRegex.match(
Text))
1479 FormatTok->setType(TT_MacroBlockEnd);
1480 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1481 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1482 else if (TemplateNames.contains(Identifier))
1483 FormatTok->setFinalizedType(TT_TemplateName);
1484 else if (TypeNames.contains(Identifier))
1485 FormatTok->setFinalizedType(TT_TypeName);
1486 else if (VariableTemplates.contains(Identifier))
1487 FormatTok->setFinalizedType(TT_VariableTemplate);
1496 if (!VerilogProtectedBlock ||
Tok.NewlinesBefore == 0)
1498 VerilogProtectedBlock =
false;
1503 const char *
const Start = Lex->getBufferLocation();
1504 size_t Len = Lex->getBuffer().end() - Start;
1511 static const llvm::Regex NextDirective(
"[\n\r][ \t]*`[^\n\r]");
1512 SmallVector<StringRef, 1> Matches;
1513 if (NextDirective.match(StringRef(Start, Len), &Matches)) {
1514 assert(Matches.size() == 1);
1515 Len = Matches[0].begin() - Start;
1518 Tok.Tok.setKind(tok::string_literal);
1519 Tok.Tok.setLength(Len);
1520 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1521 Tok.setFinalizedType(TT_VerilogProtected);
1522 Lex->seek(Lex->getCurrentBufferOffset() + Len,
1527bool FormatTokenLexer::readRawTokenVerilogSpecific(
FormatToken &
Tok) {
1528 if (readVerilogProtected(
Tok))
1530 const char *Start = Lex->getBufferLocation();
1540 if (Start[1] ==
'`')
1553 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1556 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1557 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1558 Start[Len] !=
' ') {
1561 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1562 Start[Len + 2] ==
'\n') {
1564 }
else if (Start[Len] ==
'\\' &&
1565 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1579 Tok.Tok.setKind(tok::raw_identifier);
1580 Tok.Tok.setLength(Len);
1581 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1582 Tok.Tok.setRawIdentifierData(Start);
1583 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1590 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok))
1591 Lex->LexFromRawLexer(
Tok.Tok);
1592 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1593 Tok.Tok.getLength());
1596 if (
Tok.is(tok::unknown)) {
1597 if (
Tok.TokenText.starts_with(
"\"")) {
1598 Tok.Tok.setKind(tok::string_literal);
1599 Tok.IsUnterminatedLiteral =
true;
1600 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1601 Tok.Tok.setKind(tok::string_literal);
1605 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1606 Tok.Tok.setKind(tok::string_literal);
1609 FormattingDisabled =
false;
1611 Tok.Finalized = FormattingDisabled;
1614 FormattingDisabled =
true;
1617void FormatTokenLexer::resetLexer(
unsigned Offset) {
1618 StringRef Buffer = SourceMgr.getBufferData(ID);
1619 Lex = std::make_unique<Lexer>(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1620 Buffer.begin(), Buffer.begin() + Offset,
1622 Lex->SetKeepWhitespaceMode(
true);
1623 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.