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 (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::less, tok::arrow},
326 {tok::equal, tok::greater},
327 {tok::star, tok::greater},
328 {tok::pipeequal, tok::greater},
329 {tok::pipe, tok::arrow}},
330 TT_BinaryOperator) ||
331 Tokens.back()->
is(tok::arrow)) {
335 if (Tokens.size() >= 3 &&
336 Tokens[Tokens.size() - 3]->is(Keywords.kw_verilogHash) &&
337 Tokens[Tokens.size() - 2]->isOneOf(tok::minus, tok::equal) &&
338 Tokens[Tokens.size() - 1]->is(Keywords.kw_verilogHash) &&
339 tryMergeTokens(3, TT_BinaryOperator)) {
340 Tokens.back()->setFinalizedType(TT_BinaryOperator);
344 }
else if (Style.isTableGen()) {
346 if (tryMergeTokens({tok::l_square, tok::l_brace},
347 TT_TableGenMultiLineString)) {
349 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
350 Tokens.back()->Tok.setKind(tok::string_literal);
355 if (tryMergeTokens({tok::exclaim, tok::identifier},
356 TT_TableGenBangOperator)) {
357 Tokens.back()->Tok.setKind(tok::identifier);
358 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
359 if (Tokens.back()->TokenText ==
"!cond")
360 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
362 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
365 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
368 Tokens.back()->Tok.setKind(tok::identifier);
369 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
370 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
374 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
375 Tokens.back()->Tok.setKind(tok::numeric_constant);
378 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
379 Tokens.back()->Tok.setKind(tok::numeric_constant);
385bool FormatTokenLexer::tryMergeNSStringLiteral() {
386 if (Tokens.size() < 2)
388 auto &At = *(Tokens.end() - 2);
389 auto &String = *(Tokens.end() - 1);
390 if (At->isNot(tok::at) || String->isNot(tok::string_literal))
392 At->Tok.setKind(tok::string_literal);
393 At->TokenText = StringRef(At->TokenText.begin(),
394 String->TokenText.end() - At->TokenText.begin());
395 At->ColumnWidth += String->ColumnWidth;
396 At->setType(TT_ObjCStringLiteral);
397 Tokens.erase(Tokens.end() - 1);
401bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
404 if (Tokens.size() < 2)
406 auto &Hash = *(Tokens.end() - 2);
407 auto &Identifier = *(Tokens.end() - 1);
408 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
410 Hash->Tok.setKind(tok::identifier);
412 StringRef(Hash->TokenText.begin(),
413 Identifier->TokenText.end() - Hash->TokenText.begin());
414 Hash->ColumnWidth += Identifier->ColumnWidth;
415 Hash->setType(TT_JsPrivateIdentifier);
416 Tokens.erase(Tokens.end() - 1);
425bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
426 if (Tokens.size() < 2)
430 const auto String = *(Tokens.end() - 1);
431 if (String->isNot(tok::string_literal))
434 auto Prefix = *(Tokens.end() - 2);
435 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
438 if (Tokens.size() > 2) {
439 const auto Tok = *(Tokens.end() - 3);
440 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
441 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
443 Tok->ColumnWidth += Prefix->ColumnWidth;
444 Tokens.erase(Tokens.end() - 2);
450 Prefix->Tok.setKind(tok::string_literal);
452 StringRef(Prefix->TokenText.begin(),
453 String->TokenText.end() - Prefix->TokenText.begin());
454 Prefix->ColumnWidth += String->ColumnWidth;
455 Prefix->setType(TT_CSharpStringLiteral);
456 Tokens.erase(Tokens.end() - 1);
460bool FormatTokenLexer::tryMergeCSharpUtf8StringLiteral() {
461 if (Tokens.size() < 2)
464 const auto *Suffix = Tokens.back();
465 if (Suffix->TokenText !=
"u8" || Suffix->hasWhitespaceBefore())
468 auto *String = *(Tokens.end() - 2);
469 if (String->isNot(tok::string_literal))
472 String->Tok.setKind(tok::utf8_string_literal);
474 StringRef(String->TokenText.begin(),
475 Suffix->TokenText.end() - String->TokenText.begin());
476 String->ColumnWidth += Suffix->ColumnWidth;
477 String->setFinalizedType(TT_CSharpStringLiteral);
484const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
485 "assembly",
"module",
"field",
"event",
"method",
486 "param",
"property",
"return",
"type",
489bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
490 if (Tokens.size() < 2)
492 auto &NullishCoalescing = *(Tokens.end() - 2);
493 auto &
Equal = *(Tokens.end() - 1);
494 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
495 Equal->isNot(tok::equal)) {
498 NullishCoalescing->Tok.setKind(tok::equal);
499 NullishCoalescing->TokenText =
500 StringRef(NullishCoalescing->TokenText.begin(),
501 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
502 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
503 NullishCoalescing->setType(TT_NullCoalescingEqual);
504 Tokens.erase(Tokens.end() - 1);
508bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
509 if (Tokens.size() < 2)
511 const auto At = *(Tokens.end() - 2);
512 if (At->isNot(tok::at))
514 const auto Keyword = *(Tokens.end() - 1);
517 if (!Keywords.isCSharpKeyword(*
Keyword))
520 At->Tok.setKind(tok::identifier);
521 At->TokenText = StringRef(At->TokenText.begin(),
522 Keyword->TokenText.end() - At->TokenText.begin());
523 At->ColumnWidth +=
Keyword->ColumnWidth;
524 At->setType(
Keyword->getType());
525 Tokens.erase(Tokens.end() - 1);
530bool FormatTokenLexer::tryTransformCSharpForEach() {
533 auto &Identifier = *(Tokens.end() - 1);
534 if (Identifier->isNot(tok::identifier))
536 if (Identifier->TokenText !=
"foreach")
539 Identifier->setType(TT_ForEachMacro);
540 Identifier->Tok.setKind(tok::kw_for);
544bool FormatTokenLexer::tryMergeForEach() {
545 if (Tokens.size() < 2)
547 auto &For = *(Tokens.end() - 2);
548 auto &Each = *(Tokens.end() - 1);
549 if (For->isNot(tok::kw_for))
551 if (Each->isNot(tok::identifier))
553 if (Each->TokenText !=
"each")
556 For->setType(TT_ForEachMacro);
557 For->Tok.setKind(tok::kw_for);
559 For->TokenText = StringRef(For->TokenText.begin(),
560 Each->TokenText.end() - For->TokenText.begin());
561 For->ColumnWidth += Each->ColumnWidth;
562 Tokens.erase(Tokens.end() - 1);
566bool FormatTokenLexer::tryMergeLessLess() {
568 if (Tokens.size() < 3)
571 auto First = Tokens.end() - 3;
576 if (
First[1]->hasWhitespaceBefore())
579 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
580 if (
X &&
X->is(tok::less))
584 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
587 First[0]->Tok.setKind(tok::lessless);
588 First[0]->TokenText =
"<<";
589 First[0]->ColumnWidth += 1;
590 Tokens.erase(Tokens.end() - 2);
594bool FormatTokenLexer::tryMergeGreaterGreater() {
596 if (Tokens.size() < 2)
599 auto First = Tokens.end() - 2;
604 if (
First[1]->hasWhitespaceBefore())
607 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
608 if (
Tok &&
Tok->isNot(tok::kw_operator))
611 First[0]->Tok.setKind(tok::greatergreater);
612 First[0]->TokenText =
">>";
613 First[0]->ColumnWidth += 1;
614 Tokens.erase(Tokens.end() - 1);
618bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
619 if (Tokens.size() < 2)
622 auto *
First = Tokens.end() - 2;
623 auto &Suffix =
First[1];
624 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
632 if (!
Text.ends_with(
"_"))
637 Tokens.erase(&Suffix);
643 if (Tokens.size() < Kinds.size())
646 const auto *
First = Tokens.end() - Kinds.size();
647 for (
unsigned i = 0; i < Kinds.size(); ++i)
651 return tryMergeTokens(Kinds.size(), NewType);
654bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
655 if (Tokens.size() < Count)
658 const auto *
First = Tokens.end() - Count;
659 unsigned AddLength = 0;
660 for (
size_t i = 1; i < Count; ++i) {
663 if (
First[i]->hasWhitespaceBefore())
665 AddLength +=
First[i]->TokenText.size();
668 Tokens.resize(Tokens.size() - Count + 1);
670 First[0]->TokenText.size() + AddLength);
671 First[0]->ColumnWidth += AddLength;
672 First[0]->setType(NewType);
676bool FormatTokenLexer::tryMergeTokensAny(
678 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
679 return tryMergeTokens(Kinds, NewType);
688 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
689 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
690 tok::colon, tok::question, tok::tilde) ||
691 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
692 tok::kw_else, tok::kw_void, tok::kw_typeof,
693 Keywords.kw_instanceof, Keywords.kw_in) ||
694 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
697bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
707 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
708 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
712 if (!precedesOperand(Prev))
718void FormatTokenLexer::tryParseJavaTextBlock() {
719 if (FormatTok->TokenText !=
"\"\"")
722 const auto *S = Lex->getBufferLocation();
723 const auto *End = Lex->getBuffer().end();
725 if (S == End || *S !=
'\"')
731 bool Escaped =
false;
732 for (
int Count = 0; Count < 3 && S < End; ++S) {
750 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
757void FormatTokenLexer::tryParseJSRegexLiteral() {
759 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
763 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
766 if (FT->isNot(tok::comment)) {
772 if (!canPrecedeRegexLiteral(Prev))
776 const char *Offset = Lex->getBufferLocation();
777 const char *RegexBegin = Offset - RegexToken->TokenText.size();
778 StringRef Buffer = Lex->getBuffer();
779 bool InCharacterClass =
false;
780 bool HaveClosingSlash =
false;
781 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
791 InCharacterClass =
true;
794 InCharacterClass =
false;
797 if (!InCharacterClass)
798 HaveClosingSlash =
true;
803 RegexToken->setType(TT_RegexLiteral);
805 RegexToken->Tok.setKind(tok::string_literal);
806 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
807 RegexToken->ColumnWidth = RegexToken->TokenText.size();
809 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
814 auto Repeated = [&Begin, End]() {
815 return Begin + 1 < End && Begin[1] == Begin[0];
830 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
842 ++UnmatchedOpeningBraceCount;
850 else if (UnmatchedOpeningBraceCount > 0)
851 --UnmatchedOpeningBraceCount;
857 if (UnmatchedOpeningBraceCount > 0)
860 if (Verbatim && Repeated()) {
871void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
874 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
877 auto &
TokenText = CSharpStringLiteral->TokenText;
879 bool Verbatim =
false;
880 bool Interpolated =
false;
881 const bool Utf8 =
TokenText.ends_with(
"u8");
885 }
else if (
TokenText.starts_with(R
"(@")")) {
887 }
else if (
TokenText.starts_with(R
"($")")) {
892 if (!Verbatim && !Interpolated)
895 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
896 const char *Offset = StrBegin;
897 Offset += Verbatim && Interpolated ? 3 : 2;
899 const auto End = Lex->getBuffer().end();
910 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
914 size_t FirstBreak = LiteralText.find(
'\n');
915 StringRef FirstLineText = FirstBreak == StringRef::npos
917 : LiteralText.substr(0, FirstBreak);
919 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
921 size_t LastBreak = LiteralText.rfind(
'\n');
922 if (LastBreak != StringRef::npos) {
923 CSharpStringLiteral->IsMultiline =
true;
924 unsigned StartColumn = 0;
925 CSharpStringLiteral->LastLineColumnWidth =
927 StartColumn, Style.TabWidth, Encoding);
930 assert(Offset < End);
931 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
934void FormatTokenLexer::handleTableGenMultilineString() {
936 if (MultiLineString->isNot(TT_TableGenMultiLineString))
939 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
941 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
942 if (CloseOffset == StringRef::npos)
944 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
945 MultiLineString->TokenText =
Text;
946 resetLexer(SourceMgr.getFileOffset(
947 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
948 auto FirstLineText =
Text;
949 auto FirstBreak =
Text.find(
'\n');
951 if (FirstBreak != StringRef::npos) {
952 MultiLineString->IsMultiline =
true;
953 FirstLineText =
Text.substr(0, FirstBreak + 1);
955 auto LastBreak =
Text.rfind(
'\n');
957 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
958 Style.TabWidth, Encoding);
962 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
965void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
969 if (
Tok->isNot(tok::numeric_constant))
971 StringRef
Text =
Tok->TokenText;
982 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
984 if (NonDigitPos == StringRef::npos)
986 char FirstNonDigit =
Text[NonDigitPos];
987 if (NonDigitPos <
Text.size() - 1) {
988 char TheNext =
Text[NonDigitPos + 1];
990 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
993 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
996 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
998 Tok->Tok.setKind(tok::identifier);
999 Tok->Tok.setIdentifierInfo(
nullptr);
1003void FormatTokenLexer::handleTemplateStrings() {
1006 if (BacktickToken->is(tok::l_brace)) {
1010 if (BacktickToken->is(tok::r_brace)) {
1011 if (StateStack.size() == 1)
1017 }
else if (BacktickToken->is(tok::unknown) &&
1018 BacktickToken->TokenText ==
"`") {
1025 const char *Offset = Lex->getBufferLocation();
1026 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
1027 for (; Offset != Lex->getBuffer().end(); ++Offset) {
1028 if (Offset[0] ==
'`') {
1033 if (Offset[0] ==
'\\') {
1035 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1044 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1045 BacktickToken->setType(TT_TemplateString);
1046 BacktickToken->Tok.setKind(tok::string_literal);
1047 BacktickToken->TokenText = LiteralText;
1050 size_t FirstBreak = LiteralText.find(
'\n');
1051 StringRef FirstLineText = FirstBreak == StringRef::npos
1053 : LiteralText.substr(0, FirstBreak);
1055 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1056 size_t LastBreak = LiteralText.rfind(
'\n');
1057 if (LastBreak != StringRef::npos) {
1058 BacktickToken->IsMultiline =
true;
1059 unsigned StartColumn = 0;
1060 BacktickToken->LastLineColumnWidth =
1062 StartColumn, Style.TabWidth, Encoding);
1065 SourceLocation loc = Lex->getSourceLocation(Offset);
1066 resetLexer(SourceMgr.getFileOffset(loc));
1069void FormatTokenLexer::tryParsePythonComment() {
1071 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1074 const char *CommentBegin =
1075 Lex->getBufferLocation() - HashToken->TokenText.size();
1076 size_t From = CommentBegin - Lex->getBuffer().begin();
1077 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1078 if (To == StringRef::npos)
1079 To = Lex->getBuffer().size();
1080 size_t Len = To - From;
1081 HashToken->setType(TT_LineComment);
1082 HashToken->Tok.setKind(tok::comment);
1083 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1084 SourceLocation Loc = To < Lex->getBuffer().size()
1085 ? Lex->getSourceLocation(CommentBegin + Len)
1086 : SourceMgr.getLocForEndOfFile(ID);
1087 resetLexer(SourceMgr.getFileOffset(Loc));
1090bool FormatTokenLexer::tryMerge_TMacro() {
1091 if (Tokens.size() < 4)
1094 if (
Last->isNot(tok::r_paren))
1098 if (String->isNot(tok::string_literal) || String->IsMultiline)
1101 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1105 if (
Macro->TokenText !=
"_T")
1108 const char *Start =
Macro->TokenText.data();
1109 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1110 String->TokenText = StringRef(Start, End - Start);
1111 String->IsFirst =
Macro->IsFirst;
1112 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1113 String->WhitespaceRange =
Macro->WhitespaceRange;
1114 String->OriginalColumn =
Macro->OriginalColumn;
1116 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1117 String->NewlinesBefore =
Macro->NewlinesBefore;
1118 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1123 Tokens.back() = String;
1124 if (FirstInLineIndex >= Tokens.size())
1125 FirstInLineIndex = Tokens.size() - 1;
1129bool FormatTokenLexer::tryMergeConflictMarkers() {
1130 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1144 unsigned FirstInLineOffset;
1145 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1146 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1147 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1149 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1150 if (LineOffset == StringRef::npos)
1155 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1156 StringRef LineStart;
1157 if (FirstSpace == StringRef::npos)
1158 LineStart = Buffer.substr(LineOffset);
1160 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1163 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1164 Type = TT_ConflictStart;
1165 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1166 LineStart ==
"====") {
1167 Type = TT_ConflictAlternative;
1168 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1169 Type = TT_ConflictEnd;
1172 if (
Type != TT_Unknown) {
1175 Tokens.resize(FirstInLineIndex + 1);
1179 Tokens.back()->setType(
Type);
1180 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1182 Tokens.push_back(
Next);
1191 Token
Tok = FormatTok->
Tok;
1192 StringRef
TokenText = FormatTok->TokenText;
1195 FormatTok =
new (Allocator.Allocate())
FormatToken;
1196 FormatTok->Tok =
Tok;
1197 SourceLocation TokLocation =
1198 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1199 FormatTok->Tok.setLocation(TokLocation);
1200 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1202 FormatTok->ColumnWidth = 1;
1214void FormatTokenLexer::truncateToken(
size_t NewLen) {
1215 assert(NewLen <= FormatTok->
TokenText.size());
1216 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1217 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1218 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1220 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1222 FormatTok->Tok.setLength(NewLen);
1232 const unsigned char *
const Begin =
Text.bytes_begin();
1233 const unsigned char *
const End =
Text.bytes_end();
1234 const unsigned char *Cur = Begin;
1238 }
else if (Cur[0] ==
'\\') {
1244 const auto *Lookahead = Cur + 1;
1251 Cur = Lookahead + 1;
1262 return getStashedToken();
1265 FormatTok =
new (Allocator.Allocate())
FormatToken;
1266 readRawToken(*FormatTok);
1267 SourceLocation WhitespaceStart =
1269 FormatTok->
IsFirst = IsFirstToken;
1270 IsFirstToken =
false;
1276 unsigned WhitespaceLength = TrailingWhitespace;
1277 while (FormatTok->
isNot(tok::eof)) {
1279 if (LeadingWhitespace == 0)
1281 if (LeadingWhitespace < FormatTok->
TokenText.size())
1282 truncateToken(LeadingWhitespace);
1284 bool InEscape =
false;
1285 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1291 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1306 i > 0 &&
Text[i - 1] ==
'\n' &&
1307 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1308 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1320 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1327 assert([&]() ->
bool {
1331 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1341 WhitespaceLength +=
Text.size();
1342 readRawToken(*FormatTok);
1345 if (FormatTok->is(tok::unknown))
1346 FormatTok->setType(TT_ImplicitStringLiteral);
1348 const bool IsCpp = Style.isCpp();
1357 if (
const auto Text = FormatTok->TokenText;
1358 Text.starts_with(
"//") &&
1359 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1360 assert(FormatTok->is(tok::comment));
1361 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1362 Pos =
Text.find(
'\\', Pos)) {
1363 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1364 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1371 if (Style.isVerilog()) {
1372 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1373 SmallVector<StringRef, 1> Matches;
1379 if (FormatTok->is(tok::numeric_constant)) {
1381 auto Quote = FormatTok->TokenText.find(
'\'');
1382 if (Quote != StringRef::npos)
1383 truncateToken(Quote);
1384 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1385 FormatTok->Tok.setKind(tok::raw_identifier);
1386 }
else if (FormatTok->is(tok::raw_identifier)) {
1387 if (FormatTok->TokenText ==
"`") {
1388 FormatTok->Tok.setIdentifierInfo(
nullptr);
1389 FormatTok->Tok.setKind(tok::hash);
1390 }
else if (FormatTok->TokenText ==
"``") {
1391 FormatTok->Tok.setIdentifierInfo(
nullptr);
1392 FormatTok->Tok.setKind(tok::hashhash);
1393 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1394 NumberBase.match(FormatTok->TokenText, &Matches)) {
1399 truncateToken(Matches[0].size());
1400 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1405 FormatTok->WhitespaceRange = SourceRange(
1406 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1408 FormatTok->OriginalColumn = Column;
1410 TrailingWhitespace = 0;
1411 if (FormatTok->is(tok::comment)) {
1413 StringRef UntrimmedText = FormatTok->TokenText;
1414 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1415 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1416 }
else if (FormatTok->is(tok::raw_identifier)) {
1417 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1418 FormatTok->Tok.setIdentifierInfo(&Info);
1419 FormatTok->Tok.setKind(Info.getTokenID());
1420 if (Style.isJava() &&
1421 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1422 tok::kw_operator)) {
1423 FormatTok->Tok.setKind(tok::identifier);
1424 }
else if (Style.isJavaScript() &&
1425 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1426 tok::kw_operator)) {
1427 FormatTok->Tok.setKind(tok::identifier);
1428 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1429 FormatTok->Tok.setKind(tok::identifier);
1430 }
else if (Style.isVerilog()) {
1431 if (Keywords.isVerilogIdentifier(*FormatTok))
1432 FormatTok->Tok.setKind(tok::identifier);
1435 if (Tokens.size() - FirstInLineIndex >= 3u &&
1436 Tokens[FirstInLineIndex]->is(tok::hash) &&
1437 Tokens[FirstInLineIndex + 1u]->is(tok::pp_pragma) &&
1438 Tokens[FirstInLineIndex + 2u]->is(Keywords.kw_protect) &&
1440 Keywords.kw_data_block, Keywords.kw_data_decrypt_key,
1441 Keywords.kw_data_public_key, Keywords.kw_digest_block,
1442 Keywords.kw_digest_decrypt_key, Keywords.kw_digest_public_key,
1443 Keywords.kw_key_block, Keywords.kw_key_public_key)) {
1444 VerilogProtectedBlock =
true;
1447 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1448 Greater || FormatTok->is(tok::lessless)) {
1449 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1450 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1453 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1454 tryParseJavaTextBlock();
1457 if (Style.isVerilog() && !Tokens.empty() &&
1458 Tokens.back()->is(TT_VerilogNumberBase) &&
1459 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1461 FormatTok->Tok.setKind(tok::numeric_constant);
1466 StringRef
Text = FormatTok->TokenText;
1467 size_t FirstNewlinePos =
Text.find(
'\n');
1468 if (FirstNewlinePos == StringRef::npos) {
1471 FormatTok->ColumnWidth =
1473 Column += FormatTok->ColumnWidth;
1475 FormatTok->IsMultiline =
true;
1479 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1484 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1485 Column = FormatTok->LastLineColumnWidth;
1489 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1490 auto it = Macros.find(Identifier);
1491 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1492 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1494 it != Macros.end()) {
1495 FormatTok->setType(it->second);
1496 if (it->second == TT_IfMacro) {
1501 FormatTok->Tok.setKind(tok::kw_if);
1503 }
else if (FormatTok->is(tok::identifier)) {
1504 if (MacroBlockBeginRegex.match(
Text))
1505 FormatTok->setType(TT_MacroBlockBegin);
1506 else if (MacroBlockEndRegex.match(
Text))
1507 FormatTok->setType(TT_MacroBlockEnd);
1508 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1509 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1510 else if (TemplateNames.contains(Identifier))
1511 FormatTok->setFinalizedType(TT_TemplateName);
1512 else if (TypeNames.contains(Identifier))
1513 FormatTok->setFinalizedType(TT_TypeName);
1514 else if (VariableTemplates.contains(Identifier))
1515 FormatTok->setFinalizedType(TT_VariableTemplate);
1524 if (!VerilogProtectedBlock ||
Tok.NewlinesBefore == 0)
1526 VerilogProtectedBlock =
false;
1531 const char *
const Start = Lex->getBufferLocation();
1532 size_t Len = Lex->getBuffer().end() - Start;
1539 static const llvm::Regex NextDirective(
"[\n\r][ \t]*`[^\n\r]");
1540 SmallVector<StringRef, 1> Matches;
1541 if (NextDirective.match(StringRef(Start, Len), &Matches)) {
1542 assert(Matches.size() == 1);
1543 Len = Matches[0].begin() - Start;
1546 Tok.Tok.setKind(tok::string_literal);
1547 Tok.Tok.setLength(Len);
1548 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1549 Tok.setFinalizedType(TT_VerilogProtected);
1550 Lex->seek(Lex->getCurrentBufferOffset() + Len,
1555bool FormatTokenLexer::readRawTokenVerilogSpecific(
FormatToken &
Tok) {
1556 if (readVerilogProtected(
Tok))
1558 const char *Start = Lex->getBufferLocation();
1568 if (Start[1] ==
'`')
1581 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1584 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1585 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1586 Start[Len] !=
' ') {
1589 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1590 Start[Len + 2] ==
'\n') {
1592 }
else if (Start[Len] ==
'\\' &&
1593 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1607 Tok.Tok.setKind(tok::raw_identifier);
1608 Tok.Tok.setLength(Len);
1609 Tok.Tok.setLocation(Lex->getSourceLocation(Start, Len));
1610 Tok.Tok.setRawIdentifierData(Start);
1611 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1618 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok))
1619 Lex->LexFromRawLexer(
Tok.Tok);
1620 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1621 Tok.Tok.getLength());
1624 if (
Tok.is(tok::unknown)) {
1625 if (
Tok.TokenText.starts_with(
"\"")) {
1626 Tok.Tok.setKind(tok::string_literal);
1627 Tok.IsUnterminatedLiteral =
true;
1628 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1629 Tok.Tok.setKind(tok::string_literal);
1633 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1634 Tok.Tok.setKind(tok::string_literal);
1637 FormattingDisabled =
false;
1639 Tok.Finalized = FormattingDisabled;
1642 FormattingDisabled =
true;
1645void FormatTokenLexer::resetLexer(
unsigned Offset) {
1646 StringRef Buffer = SourceMgr.getBufferData(ID);
1647 Lex = std::make_unique<Lexer>(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1648 Buffer.begin(), Buffer.begin() + Offset,
1650 Lex->SetKeepWhitespaceMode(
true);
1651 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.