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)
78 MacrosSkippedByRemoveParentheses.insert(&IdentTable.get(
Macro));
81 for (
const auto &TypeName : Style.TypeNames)
82 TypeNames.insert(&IdentTable.get(TypeName));
83 for (
const auto &VariableTemplate : Style.VariableTemplates)
84 VariableTemplates.insert(&IdentTable.get(VariableTemplate));
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())
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 (tryMergeCSharpUtf8StringLiteral())
213 if (tryTransformCSharpForEach())
215 if (tryMergeTokens(CSharpNullConditionalLSquare,
216 TT_CSharpNullConditionalLSquare)) {
218 Tokens.back()->Tok.setKind(tok::l_square);
224 if (tryMergeNSStringLiteral())
227 if (Style.isJavaScript()) {
228 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
231 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
233 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
236 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
237 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
240 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
242 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
244 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
246 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
248 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
249 Tokens.back()->Tok.setKind(tok::starequal);
252 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
253 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
255 Tokens.back()->Tok.setKind(tok::equal);
258 if (tryMergeJSPrivateIdentifier())
260 }
else if (Style.isJava()) {
262 tok::greater, tok::greater, tok::greaterequal};
263 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
265 }
else if (Style.isVerilog()) {
267 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
268 Tokens.end()[-2]->is(tok::numeric_constant) &&
269 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
271 tryMergeTokens(2, TT_Unknown)) {
275 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
283 if (Tokens.back()->TokenText.size() == 1 &&
284 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
285 TT_BinaryOperator)) {
286 Tokens.back()->Tok.setKind(tok::caret);
290 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
291 Tokens.back()->Tok.setKind(tok::lessless);
294 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
295 Tokens.back()->Tok.setKind(tok::greatergreater);
298 if (tryMergeTokensAny({{tok::lessless, tok::equal},
299 {tok::lessless, tok::lessequal},
300 {tok::greatergreater, tok::equal},
301 {tok::greatergreater, tok::greaterequal},
302 {tok::colon, tok::equal},
303 {tok::colon, tok::slash}},
304 TT_BinaryOperator)) {
309 if (tryMergeTokensAny({{tok::star, tok::star},
310 {tok::lessless, tok::less},
311 {tok::greatergreater, tok::greater},
312 {tok::exclaimequal, tok::equal},
313 {tok::exclaimequal, tok::question},
314 {tok::equalequal, tok::equal},
315 {tok::equalequal, tok::question}},
316 TT_BinaryOperator)) {
321 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
322 {tok::plus, tok::star, tok::greater},
323 {tok::minusequal, tok::greater},
324 {tok::minus, tok::star, tok::greater},
325 {tok::equal, tok::greater},
326 {tok::star, tok::greater},
327 {tok::pipeequal, tok::greater},
328 {tok::pipe, tok::arrow}},
329 TT_BinaryOperator)) {
333 if (tryMergeTokens({tok::less, tok::arrow}, TT_BinaryOperator) ||
334 Tokens.back()->
is(tok::arrow)) {
335 Tokens.back()->Tok.setKind(tok::equalequal);
338 if (Tokens.size() >= 3 &&
339 Tokens[Tokens.size() - 3]->is(Keywords.kw_verilogHash) &&
340 Tokens[Tokens.size() - 2]->isOneOf(tok::minus, tok::equal) &&
341 Tokens[Tokens.size() - 1]->is(Keywords.kw_verilogHash) &&
342 tryMergeTokens(3, TT_BinaryOperator)) {
343 Tokens.back()->setFinalizedType(TT_BinaryOperator);
347 }
else if (Style.isTableGen()) {
349 if (tryMergeTokens({tok::l_square, tok::l_brace},
350 TT_TableGenMultiLineString)) {
352 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
353 Tokens.back()->Tok.setKind(tok::string_literal);
358 if (tryMergeTokens({tok::exclaim, tok::identifier},
359 TT_TableGenBangOperator)) {
360 Tokens.back()->Tok.setKind(tok::identifier);
361 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
362 if (Tokens.back()->TokenText ==
"!cond")
363 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
365 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
368 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
371 Tokens.back()->Tok.setKind(tok::identifier);
372 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
373 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
377 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
378 Tokens.back()->Tok.setKind(tok::numeric_constant);
381 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
382 Tokens.back()->Tok.setKind(tok::numeric_constant);
388bool FormatTokenLexer::tryMergeNSStringLiteral() {
389 if (Tokens.size() < 2)
391 auto &At = *(Tokens.end() - 2);
392 auto &
String = *(Tokens.end() - 1);
393 if (At->isNot(tok::at) ||
String->isNot(tok::string_literal))
395 At->Tok.setKind(tok::string_literal);
396 At->TokenText = StringRef(At->TokenText.begin(),
397 String->TokenText.end() - At->TokenText.begin());
398 At->ColumnWidth +=
String->ColumnWidth;
399 At->setType(TT_ObjCStringLiteral);
400 Tokens.erase(Tokens.end() - 1);
404bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
407 if (Tokens.size() < 2)
409 auto &Hash = *(Tokens.end() - 2);
410 auto &Identifier = *(Tokens.end() - 1);
411 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
413 Hash->Tok.setKind(tok::identifier);
415 StringRef(Hash->TokenText.begin(),
416 Identifier->TokenText.end() - Hash->TokenText.begin());
417 Hash->ColumnWidth += Identifier->ColumnWidth;
418 Hash->setType(TT_JsPrivateIdentifier);
419 Tokens.erase(Tokens.end() - 1);
428bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
429 if (Tokens.size() < 2)
433 const auto String = *(Tokens.end() - 1);
434 if (
String->isNot(tok::string_literal))
437 auto Prefix = *(Tokens.end() - 2);
438 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
441 if (Tokens.size() > 2) {
442 const auto Tok = *(Tokens.end() - 3);
443 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
444 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
446 Tok->ColumnWidth += Prefix->ColumnWidth;
447 Tokens.erase(Tokens.end() - 2);
453 Prefix->Tok.setKind(tok::string_literal);
455 StringRef(Prefix->TokenText.begin(),
456 String->TokenText.end() - Prefix->TokenText.begin());
457 Prefix->ColumnWidth +=
String->ColumnWidth;
458 Prefix->setType(TT_CSharpStringLiteral);
459 Tokens.erase(Tokens.end() - 1);
463bool FormatTokenLexer::tryMergeCSharpUtf8StringLiteral() {
464 if (Tokens.size() < 2)
467 const auto *Suffix = Tokens.back();
468 if (Suffix->TokenText !=
"u8" || Suffix->hasWhitespaceBefore())
471 auto *
String = *(Tokens.end() - 2);
472 if (
String->isNot(tok::string_literal))
475 String->Tok.setKind(tok::utf8_string_literal);
477 StringRef(
String->TokenText.begin(),
478 Suffix->TokenText.end() -
String->TokenText.begin());
479 String->ColumnWidth += Suffix->ColumnWidth;
480 String->setFinalizedType(TT_CSharpStringLiteral);
487const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
488 "assembly",
"module",
"field",
"event",
"method",
489 "param",
"property",
"return",
"type",
492bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
493 if (Tokens.size() < 2)
495 auto &NullishCoalescing = *(Tokens.end() - 2);
496 auto &
Equal = *(Tokens.end() - 1);
497 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
498 Equal->isNot(tok::equal)) {
501 NullishCoalescing->Tok.setKind(tok::equal);
502 NullishCoalescing->TokenText =
503 StringRef(NullishCoalescing->TokenText.begin(),
504 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
505 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
506 NullishCoalescing->setType(TT_NullCoalescingEqual);
507 Tokens.erase(Tokens.end() - 1);
511bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
512 if (Tokens.size() < 2)
514 const auto At = *(Tokens.end() - 2);
515 if (At->isNot(tok::at))
517 const auto Keyword = *(Tokens.end() - 1);
520 if (!Keywords.isCSharpKeyword(*
Keyword))
523 At->Tok.setKind(tok::identifier);
524 At->TokenText = StringRef(At->TokenText.begin(),
525 Keyword->TokenText.end() - At->TokenText.begin());
526 At->ColumnWidth +=
Keyword->ColumnWidth;
527 At->setType(
Keyword->getType());
528 Tokens.erase(Tokens.end() - 1);
533bool FormatTokenLexer::tryTransformCSharpForEach() {
536 auto &Identifier = *(Tokens.end() - 1);
537 if (Identifier->isNot(tok::identifier))
539 if (Identifier->TokenText !=
"foreach")
542 Identifier->setType(TT_ForEachMacro);
543 Identifier->Tok.setKind(tok::kw_for);
547bool FormatTokenLexer::tryMergeForEach() {
548 if (Tokens.size() < 2)
550 auto &For = *(Tokens.end() - 2);
551 auto &Each = *(Tokens.end() - 1);
552 if (For->isNot(tok::kw_for))
554 if (Each->isNot(tok::identifier))
556 if (Each->TokenText !=
"each")
559 For->setType(TT_ForEachMacro);
560 For->Tok.setKind(tok::kw_for);
562 For->TokenText = StringRef(For->TokenText.begin(),
563 Each->TokenText.end() - For->TokenText.begin());
564 For->ColumnWidth += Each->ColumnWidth;
565 Tokens.erase(Tokens.end() - 1);
569bool FormatTokenLexer::tryMergeLessLess() {
571 if (Tokens.size() < 3)
574 auto First = Tokens.end() - 3;
579 if (
First[1]->hasWhitespaceBefore())
582 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
583 if (
X &&
X->is(tok::less))
587 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
590 First[0]->Tok.setKind(tok::lessless);
591 First[0]->TokenText =
"<<";
592 First[0]->ColumnWidth += 1;
593 Tokens.erase(Tokens.end() - 2);
597bool FormatTokenLexer::tryMergeGreaterGreater() {
599 if (Tokens.size() < 2)
602 auto First = Tokens.end() - 2;
607 if (
First[1]->hasWhitespaceBefore())
610 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
611 if (
Tok &&
Tok->isNot(tok::kw_operator))
614 First[0]->Tok.setKind(tok::greatergreater);
615 First[0]->TokenText =
">>";
616 First[0]->ColumnWidth += 1;
617 Tokens.erase(Tokens.end() - 1);
621bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
622 if (Tokens.size() < 2)
625 auto *
First = Tokens.end() - 2;
626 auto &Suffix =
First[1];
627 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
635 if (!
Text.ends_with(
"_"))
640 Tokens.erase(&Suffix);
646 if (Tokens.size() < Kinds.size())
649 const auto *
First = Tokens.end() - Kinds.size();
650 for (
unsigned i = 0; i < Kinds.size(); ++i)
654 return tryMergeTokens(Kinds.size(), NewType);
657bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
658 if (Tokens.size() < Count)
661 const auto *
First = Tokens.end() - Count;
662 unsigned AddLength = 0;
663 for (
size_t i = 1; i < Count; ++i) {
666 if (
First[i]->hasWhitespaceBefore())
668 AddLength +=
First[i]->TokenText.size();
671 Tokens.resize(Tokens.size() - Count + 1);
673 First[0]->TokenText.size() + AddLength);
674 First[0]->ColumnWidth += AddLength;
675 First[0]->setType(NewType);
679bool FormatTokenLexer::tryMergeTokensAny(
681 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
682 return tryMergeTokens(Kinds, NewType);
691 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
692 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
693 tok::colon, tok::question, tok::tilde) ||
694 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
695 tok::kw_else, tok::kw_void, tok::kw_typeof,
696 Keywords.kw_instanceof, Keywords.kw_in) ||
697 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
700bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
710 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
711 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
715 if (!precedesOperand(Prev))
721void FormatTokenLexer::tryParseJavaTextBlock() {
722 if (FormatTok->TokenText !=
"\"\"")
725 const auto *S = Lex->getBufferLocation();
726 const auto *End = Lex->getBuffer().end();
728 if (S == End || *S !=
'\"')
734 bool Escaped =
false;
735 for (
int Count = 0; Count < 3 && S < End; ++S) {
753 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
760void FormatTokenLexer::tryParseJSRegexLiteral() {
762 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
766 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
769 if (FT->isNot(tok::comment)) {
775 if (!canPrecedeRegexLiteral(Prev))
779 const char *Offset = Lex->getBufferLocation();
780 const char *RegexBegin = Offset - RegexToken->TokenText.size();
781 StringRef Buffer = Lex->getBuffer();
782 bool InCharacterClass =
false;
783 bool HaveClosingSlash =
false;
784 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
794 InCharacterClass =
true;
797 InCharacterClass =
false;
800 if (!InCharacterClass)
801 HaveClosingSlash =
true;
806 RegexToken->setType(TT_RegexLiteral);
808 RegexToken->Tok.setKind(tok::string_literal);
809 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
810 RegexToken->ColumnWidth = RegexToken->TokenText.size();
812 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
817 auto Repeated = [&Begin, End]() {
818 return Begin + 1 < End && Begin[1] == Begin[0];
833 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
845 ++UnmatchedOpeningBraceCount;
853 else if (UnmatchedOpeningBraceCount > 0)
854 --UnmatchedOpeningBraceCount;
860 if (UnmatchedOpeningBraceCount > 0)
863 if (Verbatim && Repeated()) {
874void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
877 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
880 auto &
TokenText = CSharpStringLiteral->TokenText;
882 bool Verbatim =
false;
883 bool Interpolated =
false;
884 const bool Utf8 =
TokenText.ends_with(
"u8");
888 }
else if (
TokenText.starts_with(R
"(@")")) {
890 }
else if (
TokenText.starts_with(R
"($")")) {
895 if (!Verbatim && !Interpolated)
898 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
899 const char *Offset = StrBegin;
900 Offset += Verbatim && Interpolated ? 3 : 2;
902 const auto End = Lex->getBuffer().end();
913 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
917 size_t FirstBreak = LiteralText.find(
'\n');
918 StringRef FirstLineText = FirstBreak == StringRef::npos
920 : LiteralText.substr(0, FirstBreak);
922 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
924 size_t LastBreak = LiteralText.rfind(
'\n');
925 if (LastBreak != StringRef::npos) {
926 CSharpStringLiteral->IsMultiline =
true;
927 unsigned StartColumn = 0;
928 CSharpStringLiteral->LastLineColumnWidth =
930 StartColumn, Style.TabWidth, Encoding);
933 assert(Offset < End);
934 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
937void FormatTokenLexer::handleTableGenMultilineString() {
939 if (MultiLineString->isNot(TT_TableGenMultiLineString))
942 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
944 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
945 if (CloseOffset == StringRef::npos)
947 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
948 MultiLineString->TokenText =
Text;
949 resetLexer(SourceMgr.getFileOffset(
950 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
951 auto FirstLineText =
Text;
952 auto FirstBreak =
Text.find(
'\n');
954 if (FirstBreak != StringRef::npos) {
955 MultiLineString->IsMultiline =
true;
956 FirstLineText =
Text.substr(0, FirstBreak + 1);
958 auto LastBreak =
Text.rfind(
'\n');
960 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
961 Style.TabWidth, Encoding);
965 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
968void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
972 if (
Tok->isNot(tok::numeric_constant))
974 StringRef
Text =
Tok->TokenText;
985 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
987 if (NonDigitPos == StringRef::npos)
989 char FirstNonDigit =
Text[NonDigitPos];
990 if (NonDigitPos <
Text.size() - 1) {
991 char TheNext =
Text[NonDigitPos + 1];
993 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
996 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
999 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
1001 Tok->Tok.setKind(tok::identifier);
1002 Tok->Tok.setIdentifierInfo(
nullptr);
1006void FormatTokenLexer::handleTemplateStrings() {
1009 if (BacktickToken->is(tok::l_brace)) {
1013 if (BacktickToken->is(tok::r_brace)) {
1014 if (StateStack.size() == 1)
1020 }
else if (BacktickToken->is(tok::unknown) &&
1021 BacktickToken->TokenText ==
"`") {
1028 const char *Offset = Lex->getBufferLocation();
1029 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
1030 for (; Offset != Lex->getBuffer().end(); ++Offset) {
1031 if (Offset[0] ==
'`') {
1036 if (Offset[0] ==
'\\') {
1038 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1047 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1048 BacktickToken->setType(TT_TemplateString);
1049 BacktickToken->Tok.setKind(tok::string_literal);
1050 BacktickToken->TokenText = LiteralText;
1053 size_t FirstBreak = LiteralText.find(
'\n');
1054 StringRef FirstLineText = FirstBreak == StringRef::npos
1056 : LiteralText.substr(0, FirstBreak);
1058 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1059 size_t LastBreak = LiteralText.rfind(
'\n');
1060 if (LastBreak != StringRef::npos) {
1061 BacktickToken->IsMultiline =
true;
1062 unsigned StartColumn = 0;
1063 BacktickToken->LastLineColumnWidth =
1065 StartColumn, Style.TabWidth, Encoding);
1068 SourceLocation loc = Lex->getSourceLocation(Offset);
1069 resetLexer(SourceMgr.getFileOffset(loc));
1072void FormatTokenLexer::tryParsePythonComment() {
1074 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1077 const char *CommentBegin =
1078 Lex->getBufferLocation() - HashToken->TokenText.size();
1079 size_t From = CommentBegin - Lex->getBuffer().begin();
1080 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1081 if (To == StringRef::npos)
1082 To = Lex->getBuffer().size();
1083 size_t Len = To - From;
1084 HashToken->setType(TT_LineComment);
1085 HashToken->Tok.setKind(tok::comment);
1086 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1087 SourceLocation Loc = To < Lex->getBuffer().size()
1088 ? Lex->getSourceLocation(CommentBegin + Len)
1089 : SourceMgr.getLocForEndOfFile(ID);
1090 resetLexer(SourceMgr.getFileOffset(Loc));
1093bool FormatTokenLexer::tryMerge_TMacro() {
1094 if (Tokens.size() < 4)
1097 if (
Last->isNot(tok::r_paren))
1101 if (
String->isNot(tok::string_literal) ||
String->IsMultiline)
1104 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1108 if (
Macro->TokenText !=
"_T")
1111 const char *Start =
Macro->TokenText.data();
1112 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1113 String->TokenText = StringRef(Start, End - Start);
1115 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1119 String->TokenText,
String->OriginalColumn, Style.TabWidth, Encoding);
1121 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1127 if (FirstInLineIndex >= Tokens.size())
1128 FirstInLineIndex = Tokens.size() - 1;
1132bool FormatTokenLexer::tryMergeConflictMarkers() {
1133 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1147 unsigned FirstInLineOffset;
1148 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1149 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1150 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1152 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1153 if (LineOffset == StringRef::npos)
1158 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1159 StringRef LineStart;
1160 if (FirstSpace == StringRef::npos)
1161 LineStart = Buffer.substr(LineOffset);
1163 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1166 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1167 Type = TT_ConflictStart;
1168 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1169 LineStart ==
"====") {
1170 Type = TT_ConflictAlternative;
1171 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1172 Type = TT_ConflictEnd;
1175 if (
Type != TT_Unknown) {
1178 Tokens.resize(FirstInLineIndex + 1);
1182 Tokens.back()->setType(
Type);
1183 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1185 Tokens.push_back(
Next);
1194 Token
Tok = FormatTok->
Tok;
1195 StringRef
TokenText = FormatTok->TokenText;
1198 FormatTok =
new (Allocator.Allocate())
FormatToken;
1199 FormatTok->Tok =
Tok;
1200 SourceLocation TokLocation =
1201 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1202 FormatTok->Tok.setLocation(TokLocation);
1203 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1205 FormatTok->ColumnWidth = 1;
1217void FormatTokenLexer::truncateToken(
size_t NewLen) {
1218 assert(NewLen <= FormatTok->
TokenText.size());
1219 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1220 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1221 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1223 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1225 FormatTok->Tok.setLength(NewLen);
1235 const unsigned char *
const Begin =
Text.bytes_begin();
1236 const unsigned char *
const End =
Text.bytes_end();
1237 const unsigned char *Cur = Begin;
1241 }
else if (Cur[0] ==
'\\') {
1247 const auto *Lookahead = Cur + 1;
1254 Cur = Lookahead + 1;
1265 return getStashedToken();
1268 FormatTok =
new (Allocator.Allocate())
FormatToken;
1269 readRawToken(*FormatTok);
1270 SourceLocation WhitespaceStart =
1272 FormatTok->
IsFirst = IsFirstToken;
1273 IsFirstToken =
false;
1279 unsigned WhitespaceLength = TrailingWhitespace;
1280 while (FormatTok->
isNot(tok::eof)) {
1282 if (LeadingWhitespace == 0)
1284 if (LeadingWhitespace < FormatTok->
TokenText.size())
1285 truncateToken(LeadingWhitespace);
1287 bool InEscape =
false;
1288 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1294 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1309 i > 0 &&
Text[i - 1] ==
'\n' &&
1310 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1311 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1323 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1330 assert([&]() ->
bool {
1334 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1344 WhitespaceLength +=
Text.size();
1345 readRawToken(*FormatTok);
1348 if (FormatTok->is(tok::unknown))
1349 FormatTok->setType(TT_ImplicitStringLiteral);
1351 const bool IsCpp = Style.isCpp();
1360 if (
const auto Text = FormatTok->TokenText;
1361 Text.starts_with(
"//") &&
1362 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1363 assert(FormatTok->is(tok::comment));
1364 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1365 Pos =
Text.find(
'\\', Pos)) {
1366 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1367 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1374 if (Style.isVerilog()) {
1375 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1376 SmallVector<StringRef, 1> Matches;
1382 if (FormatTok->is(tok::numeric_constant)) {
1384 auto Quote = FormatTok->TokenText.find(
'\'');
1385 if (Quote != StringRef::npos)
1386 truncateToken(Quote);
1387 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1388 FormatTok->Tok.setKind(tok::raw_identifier);
1389 }
else if (FormatTok->is(tok::raw_identifier)) {
1390 if (FormatTok->TokenText ==
"`") {
1391 FormatTok->Tok.setIdentifierInfo(
nullptr);
1392 FormatTok->Tok.setKind(tok::hash);
1393 }
else if (FormatTok->TokenText ==
"``") {
1394 FormatTok->Tok.setIdentifierInfo(
nullptr);
1395 FormatTok->Tok.setKind(tok::hashhash);
1396 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1397 NumberBase.match(FormatTok->TokenText, &Matches)) {
1402 truncateToken(Matches[0].size());
1403 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1408 FormatTok->WhitespaceRange = SourceRange(
1409 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1411 FormatTok->OriginalColumn = Column;
1413 TrailingWhitespace = 0;
1414 if (FormatTok->is(tok::comment)) {
1416 StringRef UntrimmedText = FormatTok->TokenText;
1417 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1418 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1419 }
else if (FormatTok->is(tok::raw_identifier)) {
1420 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1421 FormatTok->Tok.setIdentifierInfo(&Info);
1422 FormatTok->Tok.setKind(Info.getTokenID());
1423 if (Style.isJava() &&
1424 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1425 tok::kw_operator)) {
1426 FormatTok->Tok.setKind(tok::identifier);
1427 }
else if (Style.isJavaScript() &&
1428 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1429 tok::kw_operator)) {
1430 FormatTok->Tok.setKind(tok::identifier);
1431 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1432 FormatTok->Tok.setKind(tok::identifier);
1433 }
else if (Style.isVerilog()) {
1434 if (Keywords.isVerilogIdentifier(*FormatTok))
1435 FormatTok->Tok.setKind(tok::identifier);
1438 if (Tokens.size() - FirstInLineIndex >= 3u &&
1439 Tokens[FirstInLineIndex]->is(tok::hash) &&
1440 Tokens[FirstInLineIndex + 1u]->is(tok::pp_pragma) &&
1441 Tokens[FirstInLineIndex + 2u]->is(Keywords.kw_protect) &&
1443 Keywords.kw_data_block, Keywords.kw_data_decrypt_key,
1444 Keywords.kw_data_public_key, Keywords.kw_digest_block,
1445 Keywords.kw_digest_decrypt_key, Keywords.kw_digest_public_key,
1446 Keywords.kw_key_block, Keywords.kw_key_public_key)) {
1447 VerilogProtectedBlock =
true;
1450 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1451 Greater || FormatTok->is(tok::lessless)) {
1452 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1453 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1456 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1457 tryParseJavaTextBlock();
1460 if (Style.isVerilog() && !Tokens.empty() &&
1461 Tokens.back()->is(TT_VerilogNumberBase) &&
1462 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1464 FormatTok->Tok.setKind(tok::numeric_constant);
1469 StringRef
Text = FormatTok->TokenText;
1470 size_t FirstNewlinePos =
Text.find(
'\n');
1471 if (FirstNewlinePos == StringRef::npos) {
1474 FormatTok->ColumnWidth =
1476 Column += FormatTok->ColumnWidth;
1478 FormatTok->IsMultiline =
true;
1480 StringRef FirstLine =
Text.substr(0, FirstNewlinePos);
1481 if (FirstLine.ends_with(
"\r"))
1482 FirstLine = FirstLine.drop_back();
1486 FirstLine, Column, Style.TabWidth, Encoding);
1491 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1492 Column = FormatTok->LastLineColumnWidth;
1496 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1497 auto it = Macros.find(Identifier);
1498 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1499 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1501 it != Macros.end()) {
1502 FormatTok->setType(it->second);
1503 if (it->second == TT_IfMacro) {
1508 FormatTok->Tok.setKind(tok::kw_if);
1510 }
else if (FormatTok->is(tok::identifier)) {
1511 if (MacroBlockBeginRegex.match(
Text))
1512 FormatTok->setType(TT_MacroBlockBegin);
1513 else if (MacroBlockEndRegex.match(
Text))
1514 FormatTok->setType(TT_MacroBlockEnd);
1515 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1516 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1517 else if (TemplateNames.contains(Identifier))
1518 FormatTok->setFinalizedType(TT_TemplateName);
1519 else if (TypeNames.contains(Identifier))
1520 FormatTok->setFinalizedType(TT_TypeName);
1521 else if (VariableTemplates.contains(Identifier))
1522 FormatTok->setFinalizedType(TT_VariableTemplate);
1531 if (!VerilogProtectedBlock ||
Tok.NewlinesBefore == 0)
1533 VerilogProtectedBlock =
false;
1538 const char *
const Start = Lex->getBufferLocation();
1539 size_t Len = Lex->getBuffer().end() - Start;
1546 static const llvm::Regex NextDirective(
"[\n\r][ \t]*`[^\n\r]");
1547 SmallVector<StringRef, 1> Matches;
1548 if (NextDirective.match(StringRef(Start, Len), &Matches)) {
1549 assert(Matches.size() == 1);
1550 Len = Matches[0].begin() - Start;
1553 Tok.Tok.setKind(tok::string_literal);
1554 Tok.Tok.setLength(Len);
1555 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1556 Tok.setFinalizedType(TT_VerilogProtected);
1557 Lex->seek(Lex->getCurrentBufferOffset() + Len,
1562bool FormatTokenLexer::readRawTokenVerilogSpecific(
FormatToken &
Tok) {
1563 if (readVerilogProtected(
Tok))
1565 const char *Start = Lex->getBufferLocation();
1575 if (Start[1] ==
'`')
1588 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1591 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1592 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1593 Start[Len] !=
' ') {
1596 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1597 Start[Len + 2] ==
'\n') {
1599 }
else if (Start[Len] ==
'\\' &&
1600 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1614 Tok.Tok.setKind(tok::raw_identifier);
1615 Tok.Tok.setLength(Len);
1616 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1617 Tok.Tok.setRawIdentifierData(Start);
1618 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1625 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok))
1626 Lex->LexFromRawLexer(
Tok.Tok);
1627 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1628 Tok.Tok.getLength());
1631 if (
Tok.is(tok::unknown)) {
1632 if (
Tok.TokenText.starts_with(
"\"")) {
1633 Tok.Tok.setKind(tok::string_literal);
1634 Tok.IsUnterminatedLiteral =
true;
1635 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1636 Tok.Tok.setKind(tok::string_literal);
1640 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1641 Tok.Tok.setKind(tok::string_literal);
1644 FormattingDisabled =
false;
1646 Tok.Finalized = FormattingDisabled;
1649 FormattingDisabled =
true;
1652void FormatTokenLexer::resetLexer(
unsigned Offset) {
1653 StringRef Buffer = SourceMgr.getBufferData(ID);
1654 Lex = std::make_unique<Lexer>(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1655 Buffer.begin(), Buffer.begin() + Offset,
1657 Lex->SetKeepWhitespaceMode(
true);
1658 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.
@ Macros
Canonicalize -D and -U options.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Top level wrappers for InstallAPI frontend operations.
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
@ 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',...
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.