21#include "llvm/Support/Regex.h"
29 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
34 Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
35 Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
36 FormattingDisabled(
false), FormatOffRegex(Style.OneLineFormatOffRegex),
37 MacroBlockBeginRegex(Style.MacroBlockBegin),
38 MacroBlockEndRegex(Style.MacroBlockEnd) {
39 Lex.reset(
new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts));
40 Lex->SetKeepWhitespaceMode(
true);
42 for (
const std::string &ForEachMacro : Style.ForEachMacros) {
43 auto Identifier = &IdentTable.get(ForEachMacro);
44 Macros.insert({Identifier, TT_ForEachMacro});
46 for (
const std::string &IfMacro : Style.IfMacros) {
47 auto Identifier = &IdentTable.get(IfMacro);
48 Macros.insert({Identifier, TT_IfMacro});
50 for (
const std::string &AttributeMacro : Style.AttributeMacros) {
51 auto Identifier = &IdentTable.get(AttributeMacro);
52 Macros.insert({Identifier, TT_AttributeMacro});
54 for (
const std::string &StatementMacro : Style.StatementMacros) {
55 auto Identifier = &IdentTable.get(StatementMacro);
56 Macros.insert({Identifier, TT_StatementMacro});
58 for (
const std::string &TypenameMacro : Style.TypenameMacros) {
59 auto Identifier = &IdentTable.get(TypenameMacro);
60 Macros.insert({Identifier, TT_TypenameMacro});
62 for (
const std::string &NamespaceMacro : Style.NamespaceMacros) {
63 auto Identifier = &IdentTable.get(NamespaceMacro);
64 Macros.insert({Identifier, TT_NamespaceMacro});
66 for (
const std::string &WhitespaceSensitiveMacro :
67 Style.WhitespaceSensitiveMacros) {
68 auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
69 Macros.insert({Identifier, TT_UntouchableMacroFunc});
71 for (
const std::string &StatementAttributeLikeMacro :
72 Style.StatementAttributeLikeMacros) {
73 auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
74 Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
77 for (
const auto &
Macro : Style.MacrosSkippedByRemoveParentheses)
81 for (
const auto &TypeName : Style.TypeNames)
82 TypeNames.insert(&IdentTable.get(TypeName));
83 for (
const auto &VariableTemplate : Style.VariableTemplates)
88 assert(Tokens.empty());
89 assert(FirstInLineIndex == 0);
90 enum { FO_None, FO_CurrentLine, FO_NextLine } FormatOff = FO_None;
92 Tokens.push_back(getNextToken());
93 auto &
Tok = *Tokens.back();
100 Tok.Finalized =
true;
101 FormatOff = FO_CurrentLine;
106 Tok.Finalized =
true;
112 if (!FormattingDisabled && FormatOffRegex.match(
Tok.TokenText)) {
113 if (
Tok.is(tok::comment) &&
115 Tok.Finalized =
true;
116 FormatOff = FO_NextLine;
118 for (
auto *
Token : reverse(Tokens)) {
119 Token->Finalized =
true;
120 if (
Token->NewlinesBefore > 0)
123 FormatOff = FO_CurrentLine;
127 if (Style.isJavaScript()) {
128 tryParseJSRegexLiteral();
129 handleTemplateStrings();
130 }
else if (Style.isTextProto()) {
131 tryParsePythonComment();
133 tryMergePreviousTokens();
134 if (Style.isCSharp()) {
137 handleCSharpVerbatimAndInterpolatedStrings();
138 }
else if (Style.isTableGen()) {
139 handleTableGenMultilineString();
140 handleTableGenNumericLikeIdentifier();
142 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
143 FirstInLineIndex = Tokens.size() - 1;
144 }
while (Tokens.back()->isNot(tok::eof));
145 if (Style.InsertNewlineAtEOF) {
146 auto &TokEOF = *Tokens.back();
147 if (TokEOF.NewlinesBefore == 0) {
148 TokEOF.NewlinesBefore = 1;
149 TokEOF.OriginalColumn = 0;
155void FormatTokenLexer::tryMergePreviousTokens() {
156 if (tryMerge_TMacro())
158 if (tryMergeConflictMarkers())
160 if (tryMergeLessLess())
162 if (tryMergeGreaterGreater())
164 if (tryMergeForEach())
166 if (Style.isCpp() && tryTransformTryUsageForC())
169 if ((Style.Language == FormatStyle::LK_Cpp ||
170 Style.Language == FormatStyle::LK_ObjC) &&
171 tryMergeUserDefinedLiteral()) {
175 if (Style.isJavaScript() || Style.isCSharp()) {
176 static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
178 static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
180 static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
182 if (tryMergeTokens(FatArrow, TT_FatArrow))
184 if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
186 Tokens.back()->Tok.setKind(tok::pipepipe);
189 if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
191 Tokens.back()->Tok.setKind(tok::period);
194 if (tryMergeNullishCoalescingEqual())
197 if (Style.isCSharp()) {
199 tok::question, tok::l_square};
201 if (tryMergeCSharpKeywordVariables())
203 if (tryMergeCSharpStringLiteral())
205 if (tryTransformCSharpForEach())
207 if (tryMergeTokens(CSharpNullConditionalLSquare,
208 TT_CSharpNullConditionalLSquare)) {
210 Tokens.back()->Tok.setKind(tok::l_square);
216 if (tryMergeNSStringLiteral())
219 if (Style.isJavaScript()) {
220 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
223 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
225 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
228 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
229 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
232 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
234 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
236 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
238 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
240 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
241 Tokens.back()->Tok.setKind(tok::starequal);
244 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
245 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
247 Tokens.back()->Tok.setKind(tok::equal);
250 if (tryMergeJSPrivateIdentifier())
252 }
else if (Style.isJava()) {
254 tok::greater, tok::greater, tok::greaterequal};
255 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
257 }
else if (Style.isVerilog()) {
259 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
260 Tokens.end()[-2]->is(tok::numeric_constant) &&
261 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
263 tryMergeTokens(2, TT_Unknown)) {
267 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
275 if (Tokens.back()->TokenText.size() == 1 &&
276 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
277 TT_BinaryOperator)) {
278 Tokens.back()->Tok.setKind(tok::caret);
282 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
283 Tokens.back()->Tok.setKind(tok::lessless);
286 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
287 Tokens.back()->Tok.setKind(tok::greatergreater);
290 if (tryMergeTokensAny({{tok::lessless, tok::equal},
291 {tok::lessless, tok::lessequal},
292 {tok::greatergreater, tok::equal},
293 {tok::greatergreater, tok::greaterequal},
294 {tok::colon, tok::equal},
295 {tok::colon, tok::slash}},
296 TT_BinaryOperator)) {
301 if (tryMergeTokensAny({{tok::star, tok::star},
302 {tok::lessless, tok::less},
303 {tok::greatergreater, tok::greater},
304 {tok::exclaimequal, tok::equal},
305 {tok::exclaimequal, tok::question},
306 {tok::equalequal, tok::equal},
307 {tok::equalequal, tok::question}},
308 TT_BinaryOperator)) {
313 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
314 {tok::plus, tok::star, tok::greater},
315 {tok::minusequal, tok::greater},
316 {tok::minus, tok::star, tok::greater},
317 {tok::less, tok::arrow},
318 {tok::equal, tok::greater},
319 {tok::star, tok::greater},
320 {tok::pipeequal, tok::greater},
321 {tok::pipe, tok::arrow},
322 {tok::hash, tok::minus, tok::hash},
323 {tok::hash, tok::equal, tok::hash}},
324 TT_BinaryOperator) ||
325 Tokens.back()->
is(tok::arrow)) {
329 }
else if (Style.isTableGen()) {
331 if (tryMergeTokens({tok::l_square, tok::l_brace},
332 TT_TableGenMultiLineString)) {
334 Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
335 Tokens.back()->Tok.setKind(tok::string_literal);
340 if (tryMergeTokens({tok::exclaim, tok::identifier},
341 TT_TableGenBangOperator)) {
342 Tokens.back()->Tok.setKind(tok::identifier);
343 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
344 if (Tokens.back()->TokenText ==
"!cond")
345 Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
347 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
350 if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
353 Tokens.back()->Tok.setKind(tok::identifier);
354 Tokens.back()->Tok.setIdentifierInfo(
nullptr);
355 Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
359 if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
360 Tokens.back()->Tok.setKind(tok::numeric_constant);
363 if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
364 Tokens.back()->Tok.setKind(tok::numeric_constant);
370bool FormatTokenLexer::tryMergeNSStringLiteral() {
371 if (Tokens.size() < 2)
373 auto &At = *(Tokens.end() - 2);
374 auto &String = *(Tokens.end() - 1);
375 if (At->isNot(tok::at) || String->isNot(tok::string_literal))
377 At->Tok.setKind(tok::string_literal);
378 At->TokenText = StringRef(At->TokenText.begin(),
379 String->TokenText.end() - At->TokenText.begin());
380 At->ColumnWidth += String->ColumnWidth;
381 At->setType(TT_ObjCStringLiteral);
382 Tokens.erase(Tokens.end() - 1);
386bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
389 if (Tokens.size() < 2)
391 auto &Hash = *(Tokens.end() - 2);
392 auto &Identifier = *(Tokens.end() - 1);
393 if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
395 Hash->Tok.setKind(tok::identifier);
397 StringRef(Hash->TokenText.begin(),
398 Identifier->TokenText.end() - Hash->TokenText.begin());
399 Hash->ColumnWidth += Identifier->ColumnWidth;
400 Hash->setType(TT_JsPrivateIdentifier);
401 Tokens.erase(Tokens.end() - 1);
410bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
411 if (Tokens.size() < 2)
415 const auto String = *(Tokens.end() - 1);
416 if (String->isNot(tok::string_literal))
419 auto Prefix = *(Tokens.end() - 2);
420 if (Prefix->isNot(tok::at) && Prefix->TokenText !=
"$")
423 if (Tokens.size() > 2) {
424 const auto Tok = *(Tokens.end() - 3);
425 if ((
Tok->TokenText ==
"$" && Prefix->is(tok::at)) ||
426 (
Tok->is(tok::at) && Prefix->TokenText ==
"$")) {
428 Tok->ColumnWidth += Prefix->ColumnWidth;
429 Tokens.erase(Tokens.end() - 2);
435 Prefix->Tok.setKind(tok::string_literal);
437 StringRef(Prefix->TokenText.begin(),
438 String->TokenText.end() - Prefix->TokenText.begin());
439 Prefix->ColumnWidth += String->ColumnWidth;
440 Prefix->setType(TT_CSharpStringLiteral);
441 Tokens.erase(Tokens.end() - 1);
447const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
448 "assembly",
"module",
"field",
"event",
"method",
449 "param",
"property",
"return",
"type",
452bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
453 if (Tokens.size() < 2)
455 auto &NullishCoalescing = *(Tokens.end() - 2);
456 auto &
Equal = *(Tokens.end() - 1);
457 if (NullishCoalescing->isNot(TT_NullCoalescingOperator) ||
458 Equal->isNot(tok::equal)) {
461 NullishCoalescing->Tok.setKind(tok::equal);
462 NullishCoalescing->TokenText =
463 StringRef(NullishCoalescing->TokenText.begin(),
464 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
465 NullishCoalescing->ColumnWidth +=
Equal->ColumnWidth;
466 NullishCoalescing->setType(TT_NullCoalescingEqual);
467 Tokens.erase(Tokens.end() - 1);
471bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
472 if (Tokens.size() < 2)
474 const auto At = *(Tokens.end() - 2);
475 if (At->isNot(tok::at))
477 const auto Keyword = *(Tokens.end() - 1);
480 if (!Keywords.isCSharpKeyword(*
Keyword))
483 At->Tok.setKind(tok::identifier);
484 At->TokenText = StringRef(At->TokenText.begin(),
485 Keyword->TokenText.end() - At->TokenText.begin());
486 At->ColumnWidth +=
Keyword->ColumnWidth;
487 At->setType(
Keyword->getType());
488 Tokens.erase(Tokens.end() - 1);
493bool FormatTokenLexer::tryTransformCSharpForEach() {
496 auto &Identifier = *(Tokens.end() - 1);
497 if (Identifier->isNot(tok::identifier))
499 if (Identifier->TokenText !=
"foreach")
502 Identifier->setType(TT_ForEachMacro);
503 Identifier->Tok.setKind(tok::kw_for);
507bool FormatTokenLexer::tryMergeForEach() {
508 if (Tokens.size() < 2)
510 auto &For = *(Tokens.end() - 2);
511 auto &Each = *(Tokens.end() - 1);
512 if (For->isNot(tok::kw_for))
514 if (Each->isNot(tok::identifier))
516 if (Each->TokenText !=
"each")
519 For->setType(TT_ForEachMacro);
520 For->Tok.setKind(tok::kw_for);
522 For->TokenText = StringRef(For->TokenText.begin(),
523 Each->TokenText.end() - For->TokenText.begin());
524 For->ColumnWidth += Each->ColumnWidth;
525 Tokens.erase(Tokens.end() - 1);
529bool FormatTokenLexer::tryTransformTryUsageForC() {
530 if (Tokens.size() < 2)
532 auto &Try = *(Tokens.end() - 2);
533 if (Try->isNot(tok::kw_try))
535 auto &
Next = *(Tokens.end() - 1);
536 if (
Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
539 if (Tokens.size() > 2) {
540 auto &At = *(Tokens.end() - 3);
545 Try->Tok.setKind(tok::identifier);
549bool FormatTokenLexer::tryMergeLessLess() {
551 if (Tokens.size() < 3)
554 auto First = Tokens.end() - 3;
559 if (
First[1]->hasWhitespaceBefore())
562 auto X = Tokens.size() > 3 ?
First[-1] :
nullptr;
563 if (
X &&
X->is(tok::less))
567 if ((!
X ||
X->isNot(tok::kw_operator)) && Y->is(tok::less))
570 First[0]->Tok.setKind(tok::lessless);
571 First[0]->TokenText =
"<<";
572 First[0]->ColumnWidth += 1;
573 Tokens.erase(Tokens.end() - 2);
577bool FormatTokenLexer::tryMergeGreaterGreater() {
579 if (Tokens.size() < 2)
582 auto First = Tokens.end() - 2;
587 if (
First[1]->hasWhitespaceBefore())
590 auto Tok = Tokens.size() > 2 ?
First[-1] :
nullptr;
591 if (
Tok &&
Tok->isNot(tok::kw_operator))
594 First[0]->Tok.setKind(tok::greatergreater);
595 First[0]->TokenText =
">>";
596 First[0]->ColumnWidth += 1;
597 Tokens.erase(Tokens.end() - 1);
601bool FormatTokenLexer::tryMergeUserDefinedLiteral() {
602 if (Tokens.size() < 2)
605 auto *
First = Tokens.end() - 2;
606 auto &Suffix =
First[1];
607 if (Suffix->hasWhitespaceBefore() || Suffix->TokenText !=
"$")
615 if (!
Text.ends_with(
"_"))
620 Tokens.erase(&Suffix);
626 if (Tokens.size() < Kinds.size())
629 const auto *
First = Tokens.end() - Kinds.size();
630 for (
unsigned i = 0; i < Kinds.size(); ++i)
634 return tryMergeTokens(Kinds.size(), NewType);
637bool FormatTokenLexer::tryMergeTokens(
size_t Count,
TokenType NewType) {
638 if (Tokens.size() < Count)
641 const auto *
First = Tokens.end() - Count;
642 unsigned AddLength = 0;
643 for (
size_t i = 1; i < Count; ++i) {
646 if (
First[i]->hasWhitespaceBefore())
648 AddLength +=
First[i]->TokenText.size();
651 Tokens.resize(Tokens.size() - Count + 1);
653 First[0]->TokenText.size() + AddLength);
654 First[0]->ColumnWidth += AddLength;
655 First[0]->setType(NewType);
659bool FormatTokenLexer::tryMergeTokensAny(
661 return llvm::any_of(Kinds, [
this, NewType](ArrayRef<tok::TokenKind> Kinds) {
662 return tryMergeTokens(Kinds, NewType);
671 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
672 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
673 tok::colon, tok::question, tok::tilde) ||
674 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
675 tok::kw_else, tok::kw_void, tok::kw_typeof,
676 Keywords.kw_instanceof, Keywords.kw_in) ||
677 Tok->isPlacementOperator() ||
Tok->isBinaryOperator();
680bool FormatTokenLexer::canPrecedeRegexLiteral(
FormatToken *Prev) {
690 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
691 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
695 if (!precedesOperand(Prev))
701void FormatTokenLexer::tryParseJavaTextBlock() {
702 if (FormatTok->TokenText !=
"\"\"")
705 const auto *S = Lex->getBufferLocation();
706 const auto *End = Lex->getBuffer().end();
708 if (S == End || *S !=
'\"')
714 for (
int Count = 0; Count < 3 && S < End; ++S) {
728 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(S)));
735void FormatTokenLexer::tryParseJSRegexLiteral() {
737 if (RegexToken->isNoneOf(tok::slash, tok::slashequal))
741 for (
FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
744 if (FT->isNot(tok::comment)) {
750 if (!canPrecedeRegexLiteral(Prev))
754 const char *Offset = Lex->getBufferLocation();
755 const char *RegexBegin = Offset - RegexToken->TokenText.size();
756 StringRef Buffer = Lex->getBuffer();
757 bool InCharacterClass =
false;
758 bool HaveClosingSlash =
false;
759 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
769 InCharacterClass =
true;
772 InCharacterClass =
false;
775 if (!InCharacterClass)
776 HaveClosingSlash =
true;
781 RegexToken->setType(TT_RegexLiteral);
783 RegexToken->Tok.setKind(tok::string_literal);
784 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
785 RegexToken->ColumnWidth = RegexToken->TokenText.size();
787 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
792 auto Repeated = [&Begin, End]() {
793 return Begin + 1 < End && Begin[1] == Begin[0];
808 for (
int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
820 ++UnmatchedOpeningBraceCount;
828 else if (UnmatchedOpeningBraceCount > 0)
829 --UnmatchedOpeningBraceCount;
835 if (UnmatchedOpeningBraceCount > 0)
838 if (Verbatim && Repeated()) {
849void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
852 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
855 auto &
TokenText = CSharpStringLiteral->TokenText;
857 bool Verbatim =
false;
858 bool Interpolated =
false;
862 }
else if (
TokenText.starts_with(R
"(@")")) {
864 }
else if (
TokenText.starts_with(R
"($")")) {
869 if (!Verbatim && !Interpolated)
872 const char *StrBegin = Lex->getBufferLocation() -
TokenText.size();
873 const char *Offset = StrBegin;
874 Offset += Verbatim && Interpolated ? 3 : 2;
876 const auto End = Lex->getBuffer().end();
884 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
888 size_t FirstBreak = LiteralText.find(
'\n');
889 StringRef FirstLineText = FirstBreak == StringRef::npos
891 : LiteralText.substr(0, FirstBreak);
893 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
895 size_t LastBreak = LiteralText.rfind(
'\n');
896 if (LastBreak != StringRef::npos) {
897 CSharpStringLiteral->IsMultiline =
true;
898 unsigned StartColumn = 0;
899 CSharpStringLiteral->LastLineColumnWidth =
901 StartColumn, Style.TabWidth, Encoding);
904 assert(Offset < End);
905 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
908void FormatTokenLexer::handleTableGenMultilineString() {
910 if (MultiLineString->isNot(TT_TableGenMultiLineString))
913 auto OpenOffset = Lex->getCurrentBufferOffset() - 2 ;
915 auto CloseOffset = Lex->getBuffer().find(
"}]", OpenOffset);
916 if (CloseOffset == StringRef::npos)
918 auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
919 MultiLineString->TokenText =
Text;
920 resetLexer(SourceMgr.getFileOffset(
921 Lex->getSourceLocation(Lex->getBufferLocation() - 2 +
Text.size())));
922 auto FirstLineText =
Text;
923 auto FirstBreak =
Text.find(
'\n');
925 if (FirstBreak != StringRef::npos) {
926 MultiLineString->IsMultiline =
true;
927 FirstLineText =
Text.substr(0, FirstBreak + 1);
929 auto LastBreak =
Text.rfind(
'\n');
931 Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
932 Style.TabWidth, Encoding);
936 FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
939void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
943 if (
Tok->isNot(tok::numeric_constant))
945 StringRef
Text =
Tok->TokenText;
956 const auto NonDigitPos =
Text.find_if([](
char C) {
return !isdigit(
C); });
958 if (NonDigitPos == StringRef::npos)
960 char FirstNonDigit =
Text[NonDigitPos];
961 if (NonDigitPos <
Text.size() - 1) {
962 char TheNext =
Text[NonDigitPos + 1];
964 if (FirstNonDigit ==
'b' && (TheNext ==
'0' || TheNext ==
'1'))
967 if (FirstNonDigit ==
'x' && isxdigit(TheNext))
970 if (isalpha(FirstNonDigit) || FirstNonDigit ==
'_') {
972 Tok->Tok.setKind(tok::identifier);
973 Tok->Tok.setIdentifierInfo(
nullptr);
977void FormatTokenLexer::handleTemplateStrings() {
980 if (BacktickToken->is(tok::l_brace)) {
984 if (BacktickToken->is(tok::r_brace)) {
985 if (StateStack.size() == 1)
991 }
else if (BacktickToken->is(tok::unknown) &&
992 BacktickToken->TokenText ==
"`") {
999 const char *Offset = Lex->getBufferLocation();
1000 const char *TmplBegin = Offset - BacktickToken->TokenText.size();
1001 for (; Offset != Lex->getBuffer().end(); ++Offset) {
1002 if (Offset[0] ==
'`') {
1007 if (Offset[0] ==
'\\') {
1009 }
else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] ==
'$' &&
1018 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
1019 BacktickToken->setType(TT_TemplateString);
1020 BacktickToken->Tok.setKind(tok::string_literal);
1021 BacktickToken->TokenText = LiteralText;
1024 size_t FirstBreak = LiteralText.find(
'\n');
1025 StringRef FirstLineText = FirstBreak == StringRef::npos
1027 : LiteralText.substr(0, FirstBreak);
1029 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
1030 size_t LastBreak = LiteralText.rfind(
'\n');
1031 if (LastBreak != StringRef::npos) {
1032 BacktickToken->IsMultiline =
true;
1033 unsigned StartColumn = 0;
1034 BacktickToken->LastLineColumnWidth =
1036 StartColumn, Style.TabWidth, Encoding);
1039 SourceLocation loc = Lex->getSourceLocation(Offset);
1040 resetLexer(SourceMgr.getFileOffset(loc));
1043void FormatTokenLexer::tryParsePythonComment() {
1045 if (HashToken->isNoneOf(tok::hash, tok::hashhash))
1048 const char *CommentBegin =
1049 Lex->getBufferLocation() - HashToken->TokenText.size();
1050 size_t From = CommentBegin - Lex->getBuffer().begin();
1051 size_t To = Lex->getBuffer().find_first_of(
'\n', From);
1052 if (To == StringRef::npos)
1053 To = Lex->getBuffer().size();
1054 size_t Len = To - From;
1055 HashToken->setType(TT_LineComment);
1056 HashToken->Tok.setKind(tok::comment);
1057 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
1058 SourceLocation Loc = To < Lex->getBuffer().size()
1059 ? Lex->getSourceLocation(CommentBegin + Len)
1060 : SourceMgr.getLocForEndOfFile(ID);
1061 resetLexer(SourceMgr.getFileOffset(Loc));
1064bool FormatTokenLexer::tryMerge_TMacro() {
1065 if (Tokens.size() < 4)
1068 if (
Last->isNot(tok::r_paren))
1072 if (String->isNot(tok::string_literal) || String->IsMultiline)
1075 if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
1079 if (
Macro->TokenText !=
"_T")
1082 const char *Start =
Macro->TokenText.data();
1083 const char *End =
Last->TokenText.data() +
Last->TokenText.size();
1084 String->TokenText = StringRef(Start, End - Start);
1085 String->IsFirst =
Macro->IsFirst;
1086 String->LastNewlineOffset =
Macro->LastNewlineOffset;
1087 String->WhitespaceRange =
Macro->WhitespaceRange;
1088 String->OriginalColumn =
Macro->OriginalColumn;
1090 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
1091 String->NewlinesBefore =
Macro->NewlinesBefore;
1092 String->HasUnescapedNewline =
Macro->HasUnescapedNewline;
1097 Tokens.back() = String;
1098 if (FirstInLineIndex >= Tokens.size())
1099 FirstInLineIndex = Tokens.size() - 1;
1103bool FormatTokenLexer::tryMergeConflictMarkers() {
1104 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1118 unsigned FirstInLineOffset;
1119 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1120 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1121 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1123 auto LineOffset = Buffer.rfind(
'\n', FirstInLineOffset);
1124 if (LineOffset == StringRef::npos)
1129 auto FirstSpace = Buffer.find_first_of(
" \n", LineOffset);
1130 StringRef LineStart;
1131 if (FirstSpace == StringRef::npos)
1132 LineStart = Buffer.substr(LineOffset);
1134 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1137 if (LineStart ==
"<<<<<<<" || LineStart ==
">>>>") {
1138 Type = TT_ConflictStart;
1139 }
else if (LineStart ==
"|||||||" || LineStart ==
"=======" ||
1140 LineStart ==
"====") {
1141 Type = TT_ConflictAlternative;
1142 }
else if (LineStart ==
">>>>>>>" || LineStart ==
"<<<<") {
1143 Type = TT_ConflictEnd;
1146 if (
Type != TT_Unknown) {
1149 Tokens.resize(FirstInLineIndex + 1);
1153 Tokens.back()->setType(
Type);
1154 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1156 Tokens.push_back(
Next);
1165 Token
Tok = FormatTok->
Tok;
1166 StringRef
TokenText = FormatTok->TokenText;
1169 FormatTok =
new (Allocator.Allocate())
FormatToken;
1170 FormatTok->Tok =
Tok;
1171 SourceLocation TokLocation =
1172 FormatTok->Tok.getLocation().getLocWithOffset(
Tok.getLength() - 1);
1173 FormatTok->Tok.setLocation(TokLocation);
1174 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1176 FormatTok->ColumnWidth = 1;
1188void FormatTokenLexer::truncateToken(
size_t NewLen) {
1189 assert(NewLen <= FormatTok->
TokenText.size());
1190 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1191 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1192 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1194 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1196 FormatTok->Tok.setLength(NewLen);
1206 const unsigned char *
const Begin =
Text.bytes_begin();
1207 const unsigned char *
const End =
Text.bytes_end();
1208 const unsigned char *Cur = Begin;
1212 }
else if (Cur[0] ==
'\\') {
1218 const auto *Lookahead = Cur + 1;
1225 Cur = Lookahead + 1;
1236 return getStashedToken();
1239 FormatTok =
new (Allocator.Allocate())
FormatToken;
1240 readRawToken(*FormatTok);
1241 SourceLocation WhitespaceStart =
1243 FormatTok->
IsFirst = IsFirstToken;
1244 IsFirstToken =
false;
1250 unsigned WhitespaceLength = TrailingWhitespace;
1251 while (FormatTok->
isNot(tok::eof)) {
1253 if (LeadingWhitespace == 0)
1255 if (LeadingWhitespace < FormatTok->
TokenText.size())
1256 truncateToken(LeadingWhitespace);
1258 bool InEscape =
false;
1259 for (
int i = 0, e =
Text.size(); i != e; ++i) {
1265 if (i + 1 < e &&
Text[i + 1] ==
'\n')
1280 i > 0 &&
Text[i - 1] ==
'\n' &&
1281 ((i + 1 < e &&
Text[i + 1] ==
'\n') ||
1282 (i + 2 < e &&
Text[i + 1] ==
'\r' &&
Text[i + 2] ==
'\n'))) {
1294 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1301 assert([&]() ->
bool {
1305 return j <
Text.size() && (
Text[j] ==
'\n' ||
Text[j] ==
'\r');
1315 WhitespaceLength +=
Text.size();
1316 readRawToken(*FormatTok);
1319 if (FormatTok->is(tok::unknown))
1320 FormatTok->setType(TT_ImplicitStringLiteral);
1322 const bool IsCpp = Style.isCpp();
1331 if (
const auto Text = FormatTok->TokenText;
1332 Text.starts_with(
"//") &&
1333 (IsCpp || Style.isJavaScript() || Style.isJava())) {
1334 assert(FormatTok->is(tok::comment));
1335 for (
auto Pos =
Text.find(
'\\'); Pos++ != StringRef::npos;
1336 Pos =
Text.find(
'\\', Pos)) {
1337 if (Pos <
Text.size() &&
Text[Pos] ==
'\n' &&
1338 (!IsCpp ||
Text.substr(Pos + 1).ltrim().starts_with(
"//"))) {
1345 if (Style.isVerilog()) {
1346 static const llvm::Regex NumberBase(
"^s?[bdho]", llvm::Regex::IgnoreCase);
1347 SmallVector<StringRef, 1> Matches;
1353 if (FormatTok->is(tok::numeric_constant)) {
1355 auto Quote = FormatTok->TokenText.find(
'\'');
1356 if (Quote != StringRef::npos)
1357 truncateToken(Quote);
1358 }
else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1359 FormatTok->Tok.setKind(tok::raw_identifier);
1360 }
else if (FormatTok->is(tok::raw_identifier)) {
1361 if (FormatTok->TokenText ==
"`") {
1362 FormatTok->Tok.setIdentifierInfo(
nullptr);
1363 FormatTok->Tok.setKind(tok::hash);
1364 }
else if (FormatTok->TokenText ==
"``") {
1365 FormatTok->Tok.setIdentifierInfo(
nullptr);
1366 FormatTok->Tok.setKind(tok::hashhash);
1367 }
else if (!Tokens.empty() && Tokens.back()->is(Keywords.kw_apostrophe) &&
1368 NumberBase.match(FormatTok->TokenText, &Matches)) {
1373 truncateToken(Matches[0].size());
1374 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1379 FormatTok->WhitespaceRange = SourceRange(
1380 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1382 FormatTok->OriginalColumn = Column;
1384 TrailingWhitespace = 0;
1385 if (FormatTok->is(tok::comment)) {
1387 StringRef UntrimmedText = FormatTok->TokenText;
1388 FormatTok->TokenText = FormatTok->TokenText.rtrim(
" \t\v\f");
1389 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1390 }
else if (FormatTok->is(tok::raw_identifier)) {
1391 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1392 FormatTok->Tok.setIdentifierInfo(&Info);
1393 FormatTok->Tok.setKind(Info.getTokenID());
1394 if (Style.isJava() &&
1395 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1396 tok::kw_operator)) {
1397 FormatTok->Tok.setKind(tok::identifier);
1398 }
else if (Style.isJavaScript() &&
1399 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1400 tok::kw_operator)) {
1401 FormatTok->Tok.setKind(tok::identifier);
1402 }
else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1403 FormatTok->Tok.setKind(tok::identifier);
1405 }
else if (
const bool Greater = FormatTok->is(tok::greatergreater);
1406 Greater || FormatTok->is(tok::lessless)) {
1407 FormatTok->Tok.setKind(
Greater ? tok::greater : tok::less);
1408 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1411 }
else if (Style.isJava() && FormatTok->is(tok::string_literal)) {
1412 tryParseJavaTextBlock();
1415 if (Style.isVerilog() && !Tokens.empty() &&
1416 Tokens.back()->is(TT_VerilogNumberBase) &&
1417 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1419 FormatTok->Tok.setKind(tok::numeric_constant);
1424 StringRef
Text = FormatTok->TokenText;
1425 size_t FirstNewlinePos =
Text.find(
'\n');
1426 if (FirstNewlinePos == StringRef::npos) {
1429 FormatTok->ColumnWidth =
1431 Column += FormatTok->ColumnWidth;
1433 FormatTok->IsMultiline =
true;
1437 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1442 Text.substr(
Text.find_last_of(
'\n') + 1), 0, Style.TabWidth, Encoding);
1443 Column = FormatTok->LastLineColumnWidth;
1447 auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1448 auto it = Macros.find(Identifier);
1449 if ((Tokens.empty() || !Tokens.back()->Tok.getIdentifierInfo() ||
1450 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() !=
1452 it != Macros.end()) {
1453 FormatTok->setType(it->second);
1454 if (it->second == TT_IfMacro) {
1459 FormatTok->Tok.setKind(tok::kw_if);
1461 }
else if (FormatTok->is(tok::identifier)) {
1462 if (MacroBlockBeginRegex.match(
Text))
1463 FormatTok->setType(TT_MacroBlockBegin);
1464 else if (MacroBlockEndRegex.match(
Text))
1465 FormatTok->setType(TT_MacroBlockEnd);
1466 else if (MacrosSkippedByRemoveParentheses.contains(Identifier))
1467 FormatTok->setFinalizedType(TT_FunctionLikeMacro);
1468 else if (TemplateNames.contains(Identifier))
1469 FormatTok->setFinalizedType(TT_TemplateName);
1470 else if (TypeNames.contains(Identifier))
1471 FormatTok->setFinalizedType(TT_TypeName);
1472 else if (VariableTemplates.contains(Identifier))
1473 FormatTok->setFinalizedType(TT_VariableTemplate);
1480bool FormatTokenLexer::readRawTokenVerilogSpecific(Token &
Tok) {
1481 const char *Start = Lex->getBufferLocation();
1491 if (Start[1] ==
'`')
1504 if (Start[1] ==
'\r' || Start[1] ==
'\n')
1507 while (Start[Len] !=
'\0' && Start[Len] !=
'\f' && Start[Len] !=
'\n' &&
1508 Start[Len] !=
'\r' && Start[Len] !=
'\t' && Start[Len] !=
'\v' &&
1509 Start[Len] !=
' ') {
1512 if (Start[Len] ==
'\\' && Start[Len + 1] ==
'\r' &&
1513 Start[Len + 2] ==
'\n') {
1515 }
else if (Start[Len] ==
'\\' &&
1516 (Start[Len + 1] ==
'\r' || Start[Len + 1] ==
'\n')) {
1530 Tok.setKind(tok::raw_identifier);
1532 Tok.setLocation(Lex->getSourceLocation(Start, Len));
1533 Tok.setRawIdentifierData(Start);
1534 Lex->seek(Lex->getCurrentBufferOffset() + Len,
false);
1541 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(
Tok.Tok))
1542 Lex->LexFromRawLexer(
Tok.Tok);
1543 Tok.TokenText = StringRef(SourceMgr.getCharacterData(
Tok.Tok.getLocation()),
1544 Tok.Tok.getLength());
1547 if (
Tok.is(tok::unknown)) {
1548 if (
Tok.TokenText.starts_with(
"\"")) {
1549 Tok.Tok.setKind(tok::string_literal);
1550 Tok.IsUnterminatedLiteral =
true;
1551 }
else if (Style.isJavaScript() &&
Tok.TokenText ==
"''") {
1552 Tok.Tok.setKind(tok::string_literal);
1556 if ((Style.isJavaScript() || Style.isProto()) &&
Tok.is(tok::char_constant))
1557 Tok.Tok.setKind(tok::string_literal);
1560 FormattingDisabled =
false;
1562 Tok.Finalized = FormattingDisabled;
1565 FormattingDisabled =
true;
1568void FormatTokenLexer::resetLexer(
unsigned Offset) {
1569 StringRef Buffer = SourceMgr.getBufferData(ID);
1570 Lex.reset(
new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1571 Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
1572 Lex->SetKeepWhitespaceMode(
true);
1573 TrailingWhitespace = 0;
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Implements an efficient mapping from strings to IdentifierInfo nodes.
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
uint32_t Literal
Literals are represented as positive integers.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
std::vector< std::string > Macros
A list of macros of the form <definition>=<expansion> .
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::vector< std::string > TypeNames
A vector of non-keyword identifiers that should be interpreted as type names.
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
@ Keyword
The name has been typo-corrected to a keyword.
@ Type
The name was classified as a type.
std::vector< std::string > MacrosSkippedByRemoveParentheses
A vector of function-like macros whose invocations should be skipped by RemoveParentheses.
std::vector< std::string > TemplateNames
A vector of non-keyword identifiers that should be interpreted as template names.
std::vector< std::string > VariableTemplates
A vector of non-keyword identifiers that should be interpreted as variable template names.