xref: /llvm-project/clang/lib/Format/FormatTokenLexer.cpp (revision 6a471611a4b98396abb0680229aa0694ffe88a43)
1 //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements FormatTokenLexer, which tokenizes a source file
11 /// into a FormatToken stream suitable for ClangFormat.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "FormatTokenLexer.h"
16 #include "TokenAnalyzer.h"
17 
18 namespace clang {
19 namespace format {
20 
21 FormatTokenLexer::FormatTokenLexer(
22     const SourceManager &SourceMgr, FileID ID, unsigned Column,
23     const FormatStyle &Style, encoding::Encoding Encoding,
24     llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
25     IdentifierTable &IdentTable)
26     : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
27       Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
28       Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
29       Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
30       FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
31       MacroBlockEndRegex(Style.MacroBlockEnd) {
32   assert(LangOpts.CPlusPlus);
33   Lex.reset(new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts));
34   Lex->SetKeepWhitespaceMode(true);
35 
36   for (const std::string &ForEachMacro : Style.ForEachMacros) {
37     auto Identifier = &IdentTable.get(ForEachMacro);
38     Macros.insert({Identifier, TT_ForEachMacro});
39   }
40   for (const std::string &IfMacro : Style.IfMacros) {
41     auto Identifier = &IdentTable.get(IfMacro);
42     Macros.insert({Identifier, TT_IfMacro});
43   }
44   for (const std::string &AttributeMacro : Style.AttributeMacros) {
45     auto Identifier = &IdentTable.get(AttributeMacro);
46     Macros.insert({Identifier, TT_AttributeMacro});
47   }
48   for (const std::string &StatementMacro : Style.StatementMacros) {
49     auto Identifier = &IdentTable.get(StatementMacro);
50     Macros.insert({Identifier, TT_StatementMacro});
51   }
52   for (const std::string &TypenameMacro : Style.TypenameMacros) {
53     auto Identifier = &IdentTable.get(TypenameMacro);
54     Macros.insert({Identifier, TT_TypenameMacro});
55   }
56   for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
57     auto Identifier = &IdentTable.get(NamespaceMacro);
58     Macros.insert({Identifier, TT_NamespaceMacro});
59   }
60   for (const std::string &WhitespaceSensitiveMacro :
61        Style.WhitespaceSensitiveMacros) {
62     auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
63     Macros.insert({Identifier, TT_UntouchableMacroFunc});
64   }
65   for (const std::string &StatementAttributeLikeMacro :
66        Style.StatementAttributeLikeMacros) {
67     auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
68     Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
69   }
70 
71   for (const auto &TypeName : Style.TypeNames)
72     TypeNames.insert(&IdentTable.get(TypeName));
73 }
74 
75 ArrayRef<FormatToken *> FormatTokenLexer::lex() {
76   assert(Tokens.empty());
77   assert(FirstInLineIndex == 0);
78   do {
79     Tokens.push_back(getNextToken());
80     if (Style.isJavaScript()) {
81       tryParseJSRegexLiteral();
82       handleTemplateStrings();
83     }
84     if (Style.Language == FormatStyle::LK_TextProto)
85       tryParsePythonComment();
86     tryMergePreviousTokens();
87     if (Style.isCSharp()) {
88       // This needs to come after tokens have been merged so that C#
89       // string literals are correctly identified.
90       handleCSharpVerbatimAndInterpolatedStrings();
91     }
92     if (Style.isTableGen()) {
93       handleTableGenMultilineString();
94       handleTableGenNumericLikeIdentifier();
95     }
96     if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
97       FirstInLineIndex = Tokens.size() - 1;
98   } while (Tokens.back()->isNot(tok::eof));
99   return Tokens;
100 }
101 
102 void FormatTokenLexer::tryMergePreviousTokens() {
103   if (tryMerge_TMacro())
104     return;
105   if (tryMergeConflictMarkers())
106     return;
107   if (tryMergeLessLess())
108     return;
109   if (tryMergeGreaterGreater())
110     return;
111   if (tryMergeForEach())
112     return;
113   if (Style.isCpp() && tryTransformTryUsageForC())
114     return;
115 
116   if (Style.isJavaScript() || Style.isCSharp()) {
117     static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
118                                                                tok::question};
119     static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
120                                                              tok::period};
121     static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
122 
123     if (tryMergeTokens(FatArrow, TT_FatArrow))
124       return;
125     if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
126       // Treat like the "||" operator (as opposed to the ternary ?).
127       Tokens.back()->Tok.setKind(tok::pipepipe);
128       return;
129     }
130     if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
131       // Treat like a regular "." access.
132       Tokens.back()->Tok.setKind(tok::period);
133       return;
134     }
135     if (tryMergeNullishCoalescingEqual())
136       return;
137   }
138 
139   if (Style.isCSharp()) {
140     static const tok::TokenKind CSharpNullConditionalLSquare[] = {
141         tok::question, tok::l_square};
142 
143     if (tryMergeCSharpKeywordVariables())
144       return;
145     if (tryMergeCSharpStringLiteral())
146       return;
147     if (tryTransformCSharpForEach())
148       return;
149     if (tryMergeTokens(CSharpNullConditionalLSquare,
150                        TT_CSharpNullConditionalLSquare)) {
151       // Treat like a regular "[" operator.
152       Tokens.back()->Tok.setKind(tok::l_square);
153       return;
154     }
155   }
156 
157   if (tryMergeNSStringLiteral())
158     return;
159 
160   if (Style.isJavaScript()) {
161     static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
162     static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
163                                                    tok::equal};
164     static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
165                                                   tok::greaterequal};
166     static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
167     static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
168                                                            tok::starequal};
169     static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
170     static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
171 
172     // FIXME: Investigate what token type gives the correct operator priority.
173     if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
174       return;
175     if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
176       return;
177     if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
178       return;
179     if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
180       return;
181     if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
182       Tokens.back()->Tok.setKind(tok::starequal);
183       return;
184     }
185     if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
186         tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
187       // Treat like the "=" assignment operator.
188       Tokens.back()->Tok.setKind(tok::equal);
189       return;
190     }
191     if (tryMergeJSPrivateIdentifier())
192       return;
193   }
194 
195   if (Style.Language == FormatStyle::LK_Java) {
196     static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
197         tok::greater, tok::greater, tok::greaterequal};
198     if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
199       return;
200   }
201 
202   if (Style.isVerilog()) {
203     // Merge the number following a base like `'h?a0`.
204     if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
205         Tokens.end()[-2]->is(tok::numeric_constant) &&
206         Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
207                                tok::question) &&
208         tryMergeTokens(2, TT_Unknown)) {
209       return;
210     }
211     // Part select.
212     if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
213                           TT_BitFieldColon)) {
214       return;
215     }
216     // Xnor. The combined token is treated as a caret which can also be either a
217     // unary or binary operator. The actual type is determined in
218     // TokenAnnotator. We also check the token length so we know it is not
219     // already a merged token.
220     if (Tokens.back()->TokenText.size() == 1 &&
221         tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
222                           TT_BinaryOperator)) {
223       Tokens.back()->Tok.setKind(tok::caret);
224       return;
225     }
226     // Signed shift and distribution weight.
227     if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
228       Tokens.back()->Tok.setKind(tok::lessless);
229       return;
230     }
231     if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
232       Tokens.back()->Tok.setKind(tok::greatergreater);
233       return;
234     }
235     if (tryMergeTokensAny({{tok::lessless, tok::equal},
236                            {tok::lessless, tok::lessequal},
237                            {tok::greatergreater, tok::equal},
238                            {tok::greatergreater, tok::greaterequal},
239                            {tok::colon, tok::equal},
240                            {tok::colon, tok::slash}},
241                           TT_BinaryOperator)) {
242       Tokens.back()->ForcedPrecedence = prec::Assignment;
243       return;
244     }
245     // Exponentiation, signed shift, case equality, and wildcard equality.
246     if (tryMergeTokensAny({{tok::star, tok::star},
247                            {tok::lessless, tok::less},
248                            {tok::greatergreater, tok::greater},
249                            {tok::exclaimequal, tok::equal},
250                            {tok::exclaimequal, tok::question},
251                            {tok::equalequal, tok::equal},
252                            {tok::equalequal, tok::question}},
253                           TT_BinaryOperator)) {
254       return;
255     }
256     // Module paths in specify blocks and the implication and boolean equality
257     // operators.
258     if (tryMergeTokensAny({{tok::plusequal, tok::greater},
259                            {tok::plus, tok::star, tok::greater},
260                            {tok::minusequal, tok::greater},
261                            {tok::minus, tok::star, tok::greater},
262                            {tok::less, tok::arrow},
263                            {tok::equal, tok::greater},
264                            {tok::star, tok::greater},
265                            {tok::pipeequal, tok::greater},
266                            {tok::pipe, tok::arrow},
267                            {tok::hash, tok::minus, tok::hash},
268                            {tok::hash, tok::equal, tok::hash}},
269                           TT_BinaryOperator) ||
270         Tokens.back()->is(tok::arrow)) {
271       Tokens.back()->ForcedPrecedence = prec::Comma;
272       return;
273     }
274   }
275   if (Style.isTableGen()) {
276     // TableGen's Multi line string starts with [{
277     if (tryMergeTokens({tok::l_square, tok::l_brace},
278                        TT_TableGenMultiLineString)) {
279       // Set again with finalizing. This must never be annotated as other types.
280       Tokens.back()->setFinalizedType(TT_TableGenMultiLineString);
281       Tokens.back()->Tok.setKind(tok::string_literal);
282       return;
283     }
284     // TableGen's bang operator is the form !<name>.
285     // !cond is a special case with specific syntax.
286     if (tryMergeTokens({tok::exclaim, tok::identifier},
287                        TT_TableGenBangOperator)) {
288       Tokens.back()->Tok.setKind(tok::identifier);
289       Tokens.back()->Tok.setIdentifierInfo(nullptr);
290       if (Tokens.back()->TokenText == "!cond")
291         Tokens.back()->setFinalizedType(TT_TableGenCondOperator);
292       else
293         Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
294       return;
295     }
296     if (tryMergeTokens({tok::exclaim, tok::kw_if}, TT_TableGenBangOperator)) {
297       // Here, "! if" becomes "!if".  That is, ! captures if even when the space
298       // exists. That is only one possibility in TableGen's syntax.
299       Tokens.back()->Tok.setKind(tok::identifier);
300       Tokens.back()->Tok.setIdentifierInfo(nullptr);
301       Tokens.back()->setFinalizedType(TT_TableGenBangOperator);
302       return;
303     }
304     // +, - with numbers are literals. Not unary operators.
305     if (tryMergeTokens({tok::plus, tok::numeric_constant}, TT_Unknown)) {
306       Tokens.back()->Tok.setKind(tok::numeric_constant);
307       return;
308     }
309     if (tryMergeTokens({tok::minus, tok::numeric_constant}, TT_Unknown)) {
310       Tokens.back()->Tok.setKind(tok::numeric_constant);
311       return;
312     }
313   }
314 }
315 
316 bool FormatTokenLexer::tryMergeNSStringLiteral() {
317   if (Tokens.size() < 2)
318     return false;
319   auto &At = *(Tokens.end() - 2);
320   auto &String = *(Tokens.end() - 1);
321   if (At->isNot(tok::at) || String->isNot(tok::string_literal))
322     return false;
323   At->Tok.setKind(tok::string_literal);
324   At->TokenText = StringRef(At->TokenText.begin(),
325                             String->TokenText.end() - At->TokenText.begin());
326   At->ColumnWidth += String->ColumnWidth;
327   At->setType(TT_ObjCStringLiteral);
328   Tokens.erase(Tokens.end() - 1);
329   return true;
330 }
331 
332 bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
333   // Merges #idenfier into a single identifier with the text #identifier
334   // but the token tok::identifier.
335   if (Tokens.size() < 2)
336     return false;
337   auto &Hash = *(Tokens.end() - 2);
338   auto &Identifier = *(Tokens.end() - 1);
339   if (Hash->isNot(tok::hash) || Identifier->isNot(tok::identifier))
340     return false;
341   Hash->Tok.setKind(tok::identifier);
342   Hash->TokenText =
343       StringRef(Hash->TokenText.begin(),
344                 Identifier->TokenText.end() - Hash->TokenText.begin());
345   Hash->ColumnWidth += Identifier->ColumnWidth;
346   Hash->setType(TT_JsPrivateIdentifier);
347   Tokens.erase(Tokens.end() - 1);
348   return true;
349 }
350 
351 // Search for verbatim or interpolated string literals @"ABC" or
352 // $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to
353 // prevent splitting of @, $ and ".
354 // Merging of multiline verbatim strings with embedded '"' is handled in
355 // handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
356 bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
357   if (Tokens.size() < 2)
358     return false;
359 
360   // Look for @"aaaaaa" or $"aaaaaa".
361   const auto String = *(Tokens.end() - 1);
362   if (String->isNot(tok::string_literal))
363     return false;
364 
365   auto Prefix = *(Tokens.end() - 2);
366   if (Prefix->isNot(tok::at) && Prefix->TokenText != "$")
367     return false;
368 
369   if (Tokens.size() > 2) {
370     const auto Tok = *(Tokens.end() - 3);
371     if ((Tok->TokenText == "$" && Prefix->is(tok::at)) ||
372         (Tok->is(tok::at) && Prefix->TokenText == "$")) {
373       // This looks like $@"aaa" or @$"aaa" so we need to combine all 3 tokens.
374       Tok->ColumnWidth += Prefix->ColumnWidth;
375       Tokens.erase(Tokens.end() - 2);
376       Prefix = Tok;
377     }
378   }
379 
380   // Convert back into just a string_literal.
381   Prefix->Tok.setKind(tok::string_literal);
382   Prefix->TokenText =
383       StringRef(Prefix->TokenText.begin(),
384                 String->TokenText.end() - Prefix->TokenText.begin());
385   Prefix->ColumnWidth += String->ColumnWidth;
386   Prefix->setType(TT_CSharpStringLiteral);
387   Tokens.erase(Tokens.end() - 1);
388   return true;
389 }
390 
391 // Valid C# attribute targets:
392 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
393 const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
394     "assembly", "module",   "field",  "event", "method",
395     "param",    "property", "return", "type",
396 };
397 
398 bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
399   if (Tokens.size() < 2)
400     return false;
401   auto &NullishCoalescing = *(Tokens.end() - 2);
402   auto &Equal = *(Tokens.end() - 1);
403   if (NullishCoalescing->getType() != TT_NullCoalescingOperator ||
404       Equal->isNot(tok::equal)) {
405     return false;
406   }
407   NullishCoalescing->Tok.setKind(tok::equal); // no '??=' in clang tokens.
408   NullishCoalescing->TokenText =
409       StringRef(NullishCoalescing->TokenText.begin(),
410                 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
411   NullishCoalescing->ColumnWidth += Equal->ColumnWidth;
412   NullishCoalescing->setType(TT_NullCoalescingEqual);
413   Tokens.erase(Tokens.end() - 1);
414   return true;
415 }
416 
417 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
418   if (Tokens.size() < 2)
419     return false;
420   const auto At = *(Tokens.end() - 2);
421   if (At->isNot(tok::at))
422     return false;
423   const auto Keyword = *(Tokens.end() - 1);
424   if (Keyword->TokenText == "$")
425     return false;
426   if (!Keywords.isCSharpKeyword(*Keyword))
427     return false;
428 
429   At->Tok.setKind(tok::identifier);
430   At->TokenText = StringRef(At->TokenText.begin(),
431                             Keyword->TokenText.end() - At->TokenText.begin());
432   At->ColumnWidth += Keyword->ColumnWidth;
433   At->setType(Keyword->getType());
434   Tokens.erase(Tokens.end() - 1);
435   return true;
436 }
437 
438 // In C# transform identifier foreach into kw_foreach
439 bool FormatTokenLexer::tryTransformCSharpForEach() {
440   if (Tokens.size() < 1)
441     return false;
442   auto &Identifier = *(Tokens.end() - 1);
443   if (Identifier->isNot(tok::identifier))
444     return false;
445   if (Identifier->TokenText != "foreach")
446     return false;
447 
448   Identifier->setType(TT_ForEachMacro);
449   Identifier->Tok.setKind(tok::kw_for);
450   return true;
451 }
452 
453 bool FormatTokenLexer::tryMergeForEach() {
454   if (Tokens.size() < 2)
455     return false;
456   auto &For = *(Tokens.end() - 2);
457   auto &Each = *(Tokens.end() - 1);
458   if (For->isNot(tok::kw_for))
459     return false;
460   if (Each->isNot(tok::identifier))
461     return false;
462   if (Each->TokenText != "each")
463     return false;
464 
465   For->setType(TT_ForEachMacro);
466   For->Tok.setKind(tok::kw_for);
467 
468   For->TokenText = StringRef(For->TokenText.begin(),
469                              Each->TokenText.end() - For->TokenText.begin());
470   For->ColumnWidth += Each->ColumnWidth;
471   Tokens.erase(Tokens.end() - 1);
472   return true;
473 }
474 
475 bool FormatTokenLexer::tryTransformTryUsageForC() {
476   if (Tokens.size() < 2)
477     return false;
478   auto &Try = *(Tokens.end() - 2);
479   if (Try->isNot(tok::kw_try))
480     return false;
481   auto &Next = *(Tokens.end() - 1);
482   if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
483     return false;
484 
485   if (Tokens.size() > 2) {
486     auto &At = *(Tokens.end() - 3);
487     if (At->is(tok::at))
488       return false;
489   }
490 
491   Try->Tok.setKind(tok::identifier);
492   return true;
493 }
494 
495 bool FormatTokenLexer::tryMergeLessLess() {
496   // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
497   if (Tokens.size() < 3)
498     return false;
499 
500   auto First = Tokens.end() - 3;
501   if (First[0]->isNot(tok::less) || First[1]->isNot(tok::less))
502     return false;
503 
504   // Only merge if there currently is no whitespace between the two "<".
505   if (First[1]->hasWhitespaceBefore())
506     return false;
507 
508   auto X = Tokens.size() > 3 ? First[-1] : nullptr;
509   if (X && X->is(tok::less))
510     return false;
511 
512   auto Y = First[2];
513   if ((!X || X->isNot(tok::kw_operator)) && Y->is(tok::less))
514     return false;
515 
516   First[0]->Tok.setKind(tok::lessless);
517   First[0]->TokenText = "<<";
518   First[0]->ColumnWidth += 1;
519   Tokens.erase(Tokens.end() - 2);
520   return true;
521 }
522 
523 bool FormatTokenLexer::tryMergeGreaterGreater() {
524   // Merge kw_operator,greater,greater into kw_operator,greatergreater.
525   if (Tokens.size() < 2)
526     return false;
527 
528   auto First = Tokens.end() - 2;
529   if (First[0]->isNot(tok::greater) || First[1]->isNot(tok::greater))
530     return false;
531 
532   // Only merge if there currently is no whitespace between the first two ">".
533   if (First[1]->hasWhitespaceBefore())
534     return false;
535 
536   auto Tok = Tokens.size() > 2 ? First[-1] : nullptr;
537   if (Tok && Tok->isNot(tok::kw_operator))
538     return false;
539 
540   First[0]->Tok.setKind(tok::greatergreater);
541   First[0]->TokenText = ">>";
542   First[0]->ColumnWidth += 1;
543   Tokens.erase(Tokens.end() - 1);
544   return true;
545 }
546 
547 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
548                                       TokenType NewType) {
549   if (Tokens.size() < Kinds.size())
550     return false;
551 
552   SmallVectorImpl<FormatToken *>::const_iterator First =
553       Tokens.end() - Kinds.size();
554   for (unsigned i = 0; i < Kinds.size(); ++i)
555     if (First[i]->isNot(Kinds[i]))
556       return false;
557 
558   return tryMergeTokens(Kinds.size(), NewType);
559 }
560 
561 bool FormatTokenLexer::tryMergeTokens(size_t Count, TokenType NewType) {
562   if (Tokens.size() < Count)
563     return false;
564 
565   SmallVectorImpl<FormatToken *>::const_iterator First = Tokens.end() - Count;
566   unsigned AddLength = 0;
567   for (size_t i = 1; i < Count; ++i) {
568     // If there is whitespace separating the token and the previous one,
569     // they should not be merged.
570     if (First[i]->hasWhitespaceBefore())
571       return false;
572     AddLength += First[i]->TokenText.size();
573   }
574 
575   Tokens.resize(Tokens.size() - Count + 1);
576   First[0]->TokenText = StringRef(First[0]->TokenText.data(),
577                                   First[0]->TokenText.size() + AddLength);
578   First[0]->ColumnWidth += AddLength;
579   First[0]->setType(NewType);
580   return true;
581 }
582 
583 bool FormatTokenLexer::tryMergeTokensAny(
584     ArrayRef<ArrayRef<tok::TokenKind>> Kinds, TokenType NewType) {
585   return llvm::any_of(Kinds, [this, NewType](ArrayRef<tok::TokenKind> Kinds) {
586     return tryMergeTokens(Kinds, NewType);
587   });
588 }
589 
590 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
591 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
592   // NB: This is not entirely correct, as an r_paren can introduce an operand
593   // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
594   // corner case to not matter in practice, though.
595   return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
596                       tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
597                       tok::colon, tok::question, tok::tilde) ||
598          Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
599                       tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
600                       tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
601          Tok->isBinaryOperator();
602 }
603 
604 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
605   if (!Prev)
606     return true;
607 
608   // Regex literals can only follow after prefix unary operators, not after
609   // postfix unary operators. If the '++' is followed by a non-operand
610   // introducing token, the slash here is the operand and not the start of a
611   // regex.
612   // `!` is an unary prefix operator, but also a post-fix operator that casts
613   // away nullability, so the same check applies.
614   if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
615     return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
616 
617   // The previous token must introduce an operand location where regex
618   // literals can occur.
619   if (!precedesOperand(Prev))
620     return false;
621 
622   return true;
623 }
624 
625 // Tries to parse a JavaScript Regex literal starting at the current token,
626 // if that begins with a slash and is in a location where JavaScript allows
627 // regex literals. Changes the current token to a regex literal and updates
628 // its text if successful.
629 void FormatTokenLexer::tryParseJSRegexLiteral() {
630   FormatToken *RegexToken = Tokens.back();
631   if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
632     return;
633 
634   FormatToken *Prev = nullptr;
635   for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
636     // NB: Because previous pointers are not initialized yet, this cannot use
637     // Token.getPreviousNonComment.
638     if (FT->isNot(tok::comment)) {
639       Prev = FT;
640       break;
641     }
642   }
643 
644   if (!canPrecedeRegexLiteral(Prev))
645     return;
646 
647   // 'Manually' lex ahead in the current file buffer.
648   const char *Offset = Lex->getBufferLocation();
649   const char *RegexBegin = Offset - RegexToken->TokenText.size();
650   StringRef Buffer = Lex->getBuffer();
651   bool InCharacterClass = false;
652   bool HaveClosingSlash = false;
653   for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
654     // Regular expressions are terminated with a '/', which can only be
655     // escaped using '\' or a character class between '[' and ']'.
656     // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
657     switch (*Offset) {
658     case '\\':
659       // Skip the escaped character.
660       ++Offset;
661       break;
662     case '[':
663       InCharacterClass = true;
664       break;
665     case ']':
666       InCharacterClass = false;
667       break;
668     case '/':
669       if (!InCharacterClass)
670         HaveClosingSlash = true;
671       break;
672     }
673   }
674 
675   RegexToken->setType(TT_RegexLiteral);
676   // Treat regex literals like other string_literals.
677   RegexToken->Tok.setKind(tok::string_literal);
678   RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
679   RegexToken->ColumnWidth = RegexToken->TokenText.size();
680 
681   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
682 }
683 
684 static auto lexCSharpString(const char *Begin, const char *End, bool Verbatim,
685                             bool Interpolated) {
686   auto Repeated = [&Begin, End]() {
687     return Begin + 1 < End && Begin[1] == Begin[0];
688   };
689 
690   // Look for a terminating '"' in the current file buffer.
691   // Make no effort to format code within an interpolated or verbatim string.
692   //
693   // Interpolated strings could contain { } with " characters inside.
694   // $"{x ?? "null"}"
695   // should not be split into $"{x ?? ", null, "}" but should be treated as a
696   // single string-literal.
697   //
698   // We opt not to try and format expressions inside {} within a C#
699   // interpolated string. Formatting expressions within an interpolated string
700   // would require similar work as that done for JavaScript template strings
701   // in `handleTemplateStrings()`.
702   for (int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
703     switch (*Begin) {
704     case '\\':
705       if (!Verbatim)
706         ++Begin;
707       break;
708     case '{':
709       if (Interpolated) {
710         // {{ inside an interpolated string is escaped, so skip it.
711         if (Repeated())
712           ++Begin;
713         else
714           ++UnmatchedOpeningBraceCount;
715       }
716       break;
717     case '}':
718       if (Interpolated) {
719         // }} inside an interpolated string is escaped, so skip it.
720         if (Repeated())
721           ++Begin;
722         else if (UnmatchedOpeningBraceCount > 0)
723           --UnmatchedOpeningBraceCount;
724         else
725           return End;
726       }
727       break;
728     case '"':
729       if (UnmatchedOpeningBraceCount > 0)
730         break;
731       // "" within a verbatim string is an escaped double quote: skip it.
732       if (Verbatim && Repeated()) {
733         ++Begin;
734         break;
735       }
736       return Begin;
737     }
738   }
739 
740   return End;
741 }
742 
743 void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
744   FormatToken *CSharpStringLiteral = Tokens.back();
745 
746   if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
747     return;
748 
749   auto &TokenText = CSharpStringLiteral->TokenText;
750 
751   bool Verbatim = false;
752   bool Interpolated = false;
753   if (TokenText.starts_with(R"($@")") || TokenText.starts_with(R"(@$")")) {
754     Verbatim = true;
755     Interpolated = true;
756   } else if (TokenText.starts_with(R"(@")")) {
757     Verbatim = true;
758   } else if (TokenText.starts_with(R"($")")) {
759     Interpolated = true;
760   }
761 
762   // Deal with multiline strings.
763   if (!Verbatim && !Interpolated)
764     return;
765 
766   const char *StrBegin = Lex->getBufferLocation() - TokenText.size();
767   const char *Offset = StrBegin;
768   if (Verbatim && Interpolated)
769     Offset += 3;
770   else
771     Offset += 2;
772 
773   const auto End = Lex->getBuffer().end();
774   Offset = lexCSharpString(Offset, End, Verbatim, Interpolated);
775 
776   // Make no attempt to format code properly if a verbatim string is
777   // unterminated.
778   if (Offset >= End)
779     return;
780 
781   StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
782   TokenText = LiteralText;
783 
784   // Adjust width for potentially multiline string literals.
785   size_t FirstBreak = LiteralText.find('\n');
786   StringRef FirstLineText = FirstBreak == StringRef::npos
787                                 ? LiteralText
788                                 : LiteralText.substr(0, FirstBreak);
789   CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
790       FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
791       Encoding);
792   size_t LastBreak = LiteralText.rfind('\n');
793   if (LastBreak != StringRef::npos) {
794     CSharpStringLiteral->IsMultiline = true;
795     unsigned StartColumn = 0;
796     CSharpStringLiteral->LastLineColumnWidth =
797         encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
798                                       StartColumn, Style.TabWidth, Encoding);
799   }
800 
801   assert(Offset < End);
802   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
803 }
804 
805 void FormatTokenLexer::handleTableGenMultilineString() {
806   FormatToken *MultiLineString = Tokens.back();
807   if (MultiLineString->isNot(TT_TableGenMultiLineString))
808     return;
809 
810   auto OpenOffset = Lex->getCurrentBufferOffset() - 2 /* "[{" */;
811   // "}]" is the end of multi line string.
812   auto CloseOffset = Lex->getBuffer().find("}]", OpenOffset);
813   if (CloseOffset == StringRef::npos)
814     return;
815   auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 2);
816   MultiLineString->TokenText = Text;
817   resetLexer(SourceMgr.getFileOffset(
818       Lex->getSourceLocation(Lex->getBufferLocation() - 2 + Text.size())));
819   auto FirstLineText = Text;
820   auto FirstBreak = Text.find('\n');
821   // Set ColumnWidth and LastLineColumnWidth when it has multiple lines.
822   if (FirstBreak != StringRef::npos) {
823     MultiLineString->IsMultiline = true;
824     FirstLineText = Text.substr(0, FirstBreak + 1);
825     // LastLineColumnWidth holds the width of the last line.
826     auto LastBreak = Text.rfind('\n');
827     MultiLineString->LastLineColumnWidth = encoding::columnWidthWithTabs(
828         Text.substr(LastBreak + 1), MultiLineString->OriginalColumn,
829         Style.TabWidth, Encoding);
830   }
831   // ColumnWidth holds only the width of the first line.
832   MultiLineString->ColumnWidth = encoding::columnWidthWithTabs(
833       FirstLineText, MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
834 }
835 
836 void FormatTokenLexer::handleTableGenNumericLikeIdentifier() {
837   FormatToken *Tok = Tokens.back();
838   // TableGen identifiers can begin with digits. Such tokens are lexed as
839   // numeric_constant now.
840   if (Tok->isNot(tok::numeric_constant))
841     return;
842   StringRef Text = Tok->TokenText;
843   // The following check is based on llvm::TGLexer::LexToken.
844   // That lexes the token as a number if any of the following holds:
845   // 1. It starts with '+', '-'.
846   // 2. All the characters are digits.
847   // 3. The first non-digit character is 'b', and the next is '0' or '1'.
848   // 4. The first non-digit character is 'x', and the next is a hex digit.
849   // Note that in the case 3 and 4, if the next character does not exists in
850   // this token, the token is an identifier.
851   if (Text.size() < 1 || Text[0] == '+' || Text[0] == '-')
852     return;
853   const auto NonDigitPos = Text.find_if([](char C) { return !isdigit(C); });
854   // All the characters are digits
855   if (NonDigitPos == StringRef::npos)
856     return;
857   char FirstNonDigit = Text[NonDigitPos];
858   if (NonDigitPos < Text.size() - 1) {
859     char TheNext = Text[NonDigitPos + 1];
860     // Regarded as a binary number.
861     if (FirstNonDigit == 'b' && (TheNext == '0' || TheNext == '1'))
862       return;
863     // Regarded as hex number.
864     if (FirstNonDigit == 'x' && isxdigit(TheNext))
865       return;
866   }
867   if (isalpha(FirstNonDigit) || FirstNonDigit == '_') {
868     // This is actually an identifier in TableGen.
869     Tok->Tok.setKind(tok::identifier);
870     Tok->Tok.setIdentifierInfo(nullptr);
871   }
872 }
873 
874 void FormatTokenLexer::handleTemplateStrings() {
875   FormatToken *BacktickToken = Tokens.back();
876 
877   if (BacktickToken->is(tok::l_brace)) {
878     StateStack.push(LexerState::NORMAL);
879     return;
880   }
881   if (BacktickToken->is(tok::r_brace)) {
882     if (StateStack.size() == 1)
883       return;
884     StateStack.pop();
885     if (StateStack.top() != LexerState::TEMPLATE_STRING)
886       return;
887     // If back in TEMPLATE_STRING, fallthrough and continue parsing the
888   } else if (BacktickToken->is(tok::unknown) &&
889              BacktickToken->TokenText == "`") {
890     StateStack.push(LexerState::TEMPLATE_STRING);
891   } else {
892     return; // Not actually a template
893   }
894 
895   // 'Manually' lex ahead in the current file buffer.
896   const char *Offset = Lex->getBufferLocation();
897   const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
898   for (; Offset != Lex->getBuffer().end(); ++Offset) {
899     if (Offset[0] == '`') {
900       StateStack.pop();
901       ++Offset;
902       break;
903     }
904     if (Offset[0] == '\\') {
905       ++Offset; // Skip the escaped character.
906     } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
907                Offset[1] == '{') {
908       // '${' introduces an expression interpolation in the template string.
909       StateStack.push(LexerState::NORMAL);
910       Offset += 2;
911       break;
912     }
913   }
914 
915   StringRef LiteralText(TmplBegin, Offset - TmplBegin);
916   BacktickToken->setType(TT_TemplateString);
917   BacktickToken->Tok.setKind(tok::string_literal);
918   BacktickToken->TokenText = LiteralText;
919 
920   // Adjust width for potentially multiline string literals.
921   size_t FirstBreak = LiteralText.find('\n');
922   StringRef FirstLineText = FirstBreak == StringRef::npos
923                                 ? LiteralText
924                                 : LiteralText.substr(0, FirstBreak);
925   BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
926       FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
927   size_t LastBreak = LiteralText.rfind('\n');
928   if (LastBreak != StringRef::npos) {
929     BacktickToken->IsMultiline = true;
930     unsigned StartColumn = 0; // The template tail spans the entire line.
931     BacktickToken->LastLineColumnWidth =
932         encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
933                                       StartColumn, Style.TabWidth, Encoding);
934   }
935 
936   SourceLocation loc = Lex->getSourceLocation(Offset);
937   resetLexer(SourceMgr.getFileOffset(loc));
938 }
939 
940 void FormatTokenLexer::tryParsePythonComment() {
941   FormatToken *HashToken = Tokens.back();
942   if (!HashToken->isOneOf(tok::hash, tok::hashhash))
943     return;
944   // Turn the remainder of this line into a comment.
945   const char *CommentBegin =
946       Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
947   size_t From = CommentBegin - Lex->getBuffer().begin();
948   size_t To = Lex->getBuffer().find_first_of('\n', From);
949   if (To == StringRef::npos)
950     To = Lex->getBuffer().size();
951   size_t Len = To - From;
952   HashToken->setType(TT_LineComment);
953   HashToken->Tok.setKind(tok::comment);
954   HashToken->TokenText = Lex->getBuffer().substr(From, Len);
955   SourceLocation Loc = To < Lex->getBuffer().size()
956                            ? Lex->getSourceLocation(CommentBegin + Len)
957                            : SourceMgr.getLocForEndOfFile(ID);
958   resetLexer(SourceMgr.getFileOffset(Loc));
959 }
960 
961 bool FormatTokenLexer::tryMerge_TMacro() {
962   if (Tokens.size() < 4)
963     return false;
964   FormatToken *Last = Tokens.back();
965   if (Last->isNot(tok::r_paren))
966     return false;
967 
968   FormatToken *String = Tokens[Tokens.size() - 2];
969   if (String->isNot(tok::string_literal) || String->IsMultiline)
970     return false;
971 
972   if (Tokens[Tokens.size() - 3]->isNot(tok::l_paren))
973     return false;
974 
975   FormatToken *Macro = Tokens[Tokens.size() - 4];
976   if (Macro->TokenText != "_T")
977     return false;
978 
979   const char *Start = Macro->TokenText.data();
980   const char *End = Last->TokenText.data() + Last->TokenText.size();
981   String->TokenText = StringRef(Start, End - Start);
982   String->IsFirst = Macro->IsFirst;
983   String->LastNewlineOffset = Macro->LastNewlineOffset;
984   String->WhitespaceRange = Macro->WhitespaceRange;
985   String->OriginalColumn = Macro->OriginalColumn;
986   String->ColumnWidth = encoding::columnWidthWithTabs(
987       String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
988   String->NewlinesBefore = Macro->NewlinesBefore;
989   String->HasUnescapedNewline = Macro->HasUnescapedNewline;
990 
991   Tokens.pop_back();
992   Tokens.pop_back();
993   Tokens.pop_back();
994   Tokens.back() = String;
995   if (FirstInLineIndex >= Tokens.size())
996     FirstInLineIndex = Tokens.size() - 1;
997   return true;
998 }
999 
1000 bool FormatTokenLexer::tryMergeConflictMarkers() {
1001   if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
1002     return false;
1003 
1004   // Conflict lines look like:
1005   // <marker> <text from the vcs>
1006   // For example:
1007   // >>>>>>> /file/in/file/system at revision 1234
1008   //
1009   // We merge all tokens in a line that starts with a conflict marker
1010   // into a single token with a special token type that the unwrapped line
1011   // parser will use to correctly rebuild the underlying code.
1012 
1013   FileID ID;
1014   // Get the position of the first token in the line.
1015   unsigned FirstInLineOffset;
1016   std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
1017       Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
1018   StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
1019   // Calculate the offset of the start of the current line.
1020   auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
1021   if (LineOffset == StringRef::npos)
1022     LineOffset = 0;
1023   else
1024     ++LineOffset;
1025 
1026   auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
1027   StringRef LineStart;
1028   if (FirstSpace == StringRef::npos)
1029     LineStart = Buffer.substr(LineOffset);
1030   else
1031     LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
1032 
1033   TokenType Type = TT_Unknown;
1034   if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
1035     Type = TT_ConflictStart;
1036   } else if (LineStart == "|||||||" || LineStart == "=======" ||
1037              LineStart == "====") {
1038     Type = TT_ConflictAlternative;
1039   } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
1040     Type = TT_ConflictEnd;
1041   }
1042 
1043   if (Type != TT_Unknown) {
1044     FormatToken *Next = Tokens.back();
1045 
1046     Tokens.resize(FirstInLineIndex + 1);
1047     // We do not need to build a complete token here, as we will skip it
1048     // during parsing anyway (as we must not touch whitespace around conflict
1049     // markers).
1050     Tokens.back()->setType(Type);
1051     Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
1052 
1053     Tokens.push_back(Next);
1054     return true;
1055   }
1056 
1057   return false;
1058 }
1059 
1060 FormatToken *FormatTokenLexer::getStashedToken() {
1061   // Create a synthesized second '>' or '<' token.
1062   Token Tok = FormatTok->Tok;
1063   StringRef TokenText = FormatTok->TokenText;
1064 
1065   unsigned OriginalColumn = FormatTok->OriginalColumn;
1066   FormatTok = new (Allocator.Allocate()) FormatToken;
1067   FormatTok->Tok = Tok;
1068   SourceLocation TokLocation =
1069       FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
1070   FormatTok->Tok.setLocation(TokLocation);
1071   FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
1072   FormatTok->TokenText = TokenText;
1073   FormatTok->ColumnWidth = 1;
1074   FormatTok->OriginalColumn = OriginalColumn + 1;
1075 
1076   return FormatTok;
1077 }
1078 
1079 /// Truncate the current token to the new length and make the lexer continue
1080 /// from the end of the truncated token. Used for other languages that have
1081 /// different token boundaries, like JavaScript in which a comment ends at a
1082 /// line break regardless of whether the line break follows a backslash. Also
1083 /// used to set the lexer to the end of whitespace if the lexer regards
1084 /// whitespace and an unrecognized symbol as one token.
1085 void FormatTokenLexer::truncateToken(size_t NewLen) {
1086   assert(NewLen <= FormatTok->TokenText.size());
1087   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
1088       Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
1089   FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
1090   FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1091       FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
1092       Encoding);
1093   FormatTok->Tok.setLength(NewLen);
1094 }
1095 
1096 /// Count the length of leading whitespace in a token.
1097 static size_t countLeadingWhitespace(StringRef Text) {
1098   // Basically counting the length matched by this regex.
1099   // "^([\n\r\f\v \t]|(\\\\|\\?\\?/)[\n\r])+"
1100   // Directly using the regex turned out to be slow. With the regex
1101   // version formatting all files in this directory took about 1.25
1102   // seconds. This version took about 0.5 seconds.
1103   const unsigned char *const Begin = Text.bytes_begin();
1104   const unsigned char *const End = Text.bytes_end();
1105   const unsigned char *Cur = Begin;
1106   while (Cur < End) {
1107     if (isspace(Cur[0])) {
1108       ++Cur;
1109     } else if (Cur[0] == '\\' && (Cur[1] == '\n' || Cur[1] == '\r')) {
1110       // A '\' followed by a newline always escapes the newline, regardless
1111       // of whether there is another '\' before it.
1112       // The source has a null byte at the end. So the end of the entire input
1113       // isn't reached yet. Also the lexer doesn't break apart an escaped
1114       // newline.
1115       assert(End - Cur >= 2);
1116       Cur += 2;
1117     } else if (Cur[0] == '?' && Cur[1] == '?' && Cur[2] == '/' &&
1118                (Cur[3] == '\n' || Cur[3] == '\r')) {
1119       // Newlines can also be escaped by a '?' '?' '/' trigraph. By the way, the
1120       // characters are quoted individually in this comment because if we write
1121       // them together some compilers warn that we have a trigraph in the code.
1122       assert(End - Cur >= 4);
1123       Cur += 4;
1124     } else {
1125       break;
1126     }
1127   }
1128   return Cur - Begin;
1129 }
1130 
1131 FormatToken *FormatTokenLexer::getNextToken() {
1132   if (StateStack.top() == LexerState::TOKEN_STASHED) {
1133     StateStack.pop();
1134     return getStashedToken();
1135   }
1136 
1137   FormatTok = new (Allocator.Allocate()) FormatToken;
1138   readRawToken(*FormatTok);
1139   SourceLocation WhitespaceStart =
1140       FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1141   FormatTok->IsFirst = IsFirstToken;
1142   IsFirstToken = false;
1143 
1144   // Consume and record whitespace until we find a significant token.
1145   // Some tok::unknown tokens are not just whitespace, e.g. whitespace
1146   // followed by a symbol such as backtick. Those symbols may be
1147   // significant in other languages.
1148   unsigned WhitespaceLength = TrailingWhitespace;
1149   while (FormatTok->isNot(tok::eof)) {
1150     auto LeadingWhitespace = countLeadingWhitespace(FormatTok->TokenText);
1151     if (LeadingWhitespace == 0)
1152       break;
1153     if (LeadingWhitespace < FormatTok->TokenText.size())
1154       truncateToken(LeadingWhitespace);
1155     StringRef Text = FormatTok->TokenText;
1156     bool InEscape = false;
1157     for (int i = 0, e = Text.size(); i != e; ++i) {
1158       switch (Text[i]) {
1159       case '\r':
1160         // If this is a CRLF sequence, break here and the LF will be handled on
1161         // the next loop iteration. Otherwise, this is a single Mac CR, treat it
1162         // the same as a single LF.
1163         if (i + 1 < e && Text[i + 1] == '\n')
1164           break;
1165         [[fallthrough]];
1166       case '\n':
1167         ++FormatTok->NewlinesBefore;
1168         if (!InEscape)
1169           FormatTok->HasUnescapedNewline = true;
1170         else
1171           InEscape = false;
1172         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1173         Column = 0;
1174         break;
1175       case '\f':
1176       case '\v':
1177         Column = 0;
1178         break;
1179       case ' ':
1180         ++Column;
1181         break;
1182       case '\t':
1183         Column +=
1184             Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1185         break;
1186       case '\\':
1187       case '?':
1188       case '/':
1189         // The text was entirely whitespace when this loop was entered. Thus
1190         // this has to be an escape sequence.
1191         assert(Text.substr(i, 2) == "\\\r" || Text.substr(i, 2) == "\\\n" ||
1192                Text.substr(i, 4) == "\?\?/\r" ||
1193                Text.substr(i, 4) == "\?\?/\n" ||
1194                (i >= 1 && (Text.substr(i - 1, 4) == "\?\?/\r" ||
1195                            Text.substr(i - 1, 4) == "\?\?/\n")) ||
1196                (i >= 2 && (Text.substr(i - 2, 4) == "\?\?/\r" ||
1197                            Text.substr(i - 2, 4) == "\?\?/\n")));
1198         InEscape = true;
1199         break;
1200       default:
1201         // This shouldn't happen.
1202         assert(false);
1203         break;
1204       }
1205     }
1206     WhitespaceLength += Text.size();
1207     readRawToken(*FormatTok);
1208   }
1209 
1210   if (FormatTok->is(tok::unknown))
1211     FormatTok->setType(TT_ImplicitStringLiteral);
1212 
1213   // JavaScript and Java do not allow to escape the end of the line with a
1214   // backslash. Backslashes are syntax errors in plain source, but can occur in
1215   // comments. When a single line comment ends with a \, it'll cause the next
1216   // line of code to be lexed as a comment, breaking formatting. The code below
1217   // finds comments that contain a backslash followed by a line break, truncates
1218   // the comment token at the backslash, and resets the lexer to restart behind
1219   // the backslash.
1220   if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
1221       FormatTok->is(tok::comment) && FormatTok->TokenText.starts_with("//")) {
1222     size_t BackslashPos = FormatTok->TokenText.find('\\');
1223     while (BackslashPos != StringRef::npos) {
1224       if (BackslashPos + 1 < FormatTok->TokenText.size() &&
1225           FormatTok->TokenText[BackslashPos + 1] == '\n') {
1226         truncateToken(BackslashPos + 1);
1227         break;
1228       }
1229       BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
1230     }
1231   }
1232 
1233   if (Style.isVerilog()) {
1234     static const llvm::Regex NumberBase("^s?[bdho]", llvm::Regex::IgnoreCase);
1235     SmallVector<StringRef, 1> Matches;
1236     // Verilog uses the backtick instead of the hash for preprocessor stuff.
1237     // And it uses the hash for delays and parameter lists. In order to continue
1238     // using `tok::hash` in other places, the backtick gets marked as the hash
1239     // here.  And in order to tell the backtick and hash apart for
1240     // Verilog-specific stuff, the hash becomes an identifier.
1241     if (FormatTok->is(tok::numeric_constant)) {
1242       // In Verilog the quote is not part of a number.
1243       auto Quote = FormatTok->TokenText.find('\'');
1244       if (Quote != StringRef::npos)
1245         truncateToken(Quote);
1246     } else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1247       FormatTok->Tok.setKind(tok::raw_identifier);
1248     } else if (FormatTok->is(tok::raw_identifier)) {
1249       if (FormatTok->TokenText == "`") {
1250         FormatTok->Tok.setIdentifierInfo(nullptr);
1251         FormatTok->Tok.setKind(tok::hash);
1252       } else if (FormatTok->TokenText == "``") {
1253         FormatTok->Tok.setIdentifierInfo(nullptr);
1254         FormatTok->Tok.setKind(tok::hashhash);
1255       } else if (Tokens.size() > 0 &&
1256                  Tokens.back()->is(Keywords.kw_apostrophe) &&
1257                  NumberBase.match(FormatTok->TokenText, &Matches)) {
1258         // In Verilog in a based number literal like `'b10`, there may be
1259         // whitespace between `'b` and `10`. Therefore we handle the base and
1260         // the rest of the number literal as two tokens. But if there is no
1261         // space in the input code, we need to manually separate the two parts.
1262         truncateToken(Matches[0].size());
1263         FormatTok->setFinalizedType(TT_VerilogNumberBase);
1264       }
1265     }
1266   }
1267 
1268   FormatTok->WhitespaceRange = SourceRange(
1269       WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1270 
1271   FormatTok->OriginalColumn = Column;
1272 
1273   TrailingWhitespace = 0;
1274   if (FormatTok->is(tok::comment)) {
1275     // FIXME: Add the trimmed whitespace to Column.
1276     StringRef UntrimmedText = FormatTok->TokenText;
1277     FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1278     TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1279   } else if (FormatTok->is(tok::raw_identifier)) {
1280     IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1281     FormatTok->Tok.setIdentifierInfo(&Info);
1282     FormatTok->Tok.setKind(Info.getTokenID());
1283     if (Style.Language == FormatStyle::LK_Java &&
1284         FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1285                            tok::kw_operator)) {
1286       FormatTok->Tok.setKind(tok::identifier);
1287       FormatTok->Tok.setIdentifierInfo(nullptr);
1288     } else if (Style.isJavaScript() &&
1289                FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1290                                   tok::kw_operator)) {
1291       FormatTok->Tok.setKind(tok::identifier);
1292       FormatTok->Tok.setIdentifierInfo(nullptr);
1293     } else if (Style.isTableGen() && !Keywords.isTableGenKeyword(*FormatTok)) {
1294       FormatTok->Tok.setKind(tok::identifier);
1295       FormatTok->Tok.setIdentifierInfo(nullptr);
1296     }
1297   } else if (FormatTok->is(tok::greatergreater)) {
1298     FormatTok->Tok.setKind(tok::greater);
1299     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1300     ++Column;
1301     StateStack.push(LexerState::TOKEN_STASHED);
1302   } else if (FormatTok->is(tok::lessless)) {
1303     FormatTok->Tok.setKind(tok::less);
1304     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1305     ++Column;
1306     StateStack.push(LexerState::TOKEN_STASHED);
1307   }
1308 
1309   if (Style.isVerilog() && Tokens.size() > 0 &&
1310       Tokens.back()->is(TT_VerilogNumberBase) &&
1311       FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1312     // Mark the number following a base like `'h?a0` as a number.
1313     FormatTok->Tok.setKind(tok::numeric_constant);
1314   }
1315 
1316   // Now FormatTok is the next non-whitespace token.
1317 
1318   StringRef Text = FormatTok->TokenText;
1319   size_t FirstNewlinePos = Text.find('\n');
1320   if (FirstNewlinePos == StringRef::npos) {
1321     // FIXME: ColumnWidth actually depends on the start column, we need to
1322     // take this into account when the token is moved.
1323     FormatTok->ColumnWidth =
1324         encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1325     Column += FormatTok->ColumnWidth;
1326   } else {
1327     FormatTok->IsMultiline = true;
1328     // FIXME: ColumnWidth actually depends on the start column, we need to
1329     // take this into account when the token is moved.
1330     FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1331         Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1332 
1333     // The last line of the token always starts in column 0.
1334     // Thus, the length can be precomputed even in the presence of tabs.
1335     FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1336         Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
1337     Column = FormatTok->LastLineColumnWidth;
1338   }
1339 
1340   if (Style.isCpp()) {
1341     auto *Identifier = FormatTok->Tok.getIdentifierInfo();
1342     auto it = Macros.find(Identifier);
1343     if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1344           Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1345               tok::pp_define) &&
1346         it != Macros.end()) {
1347       FormatTok->setType(it->second);
1348       if (it->second == TT_IfMacro) {
1349         // The lexer token currently has type tok::kw_unknown. However, for this
1350         // substitution to be treated correctly in the TokenAnnotator, faking
1351         // the tok value seems to be needed. Not sure if there's a more elegant
1352         // way.
1353         FormatTok->Tok.setKind(tok::kw_if);
1354       }
1355     } else if (FormatTok->is(tok::identifier)) {
1356       if (MacroBlockBeginRegex.match(Text))
1357         FormatTok->setType(TT_MacroBlockBegin);
1358       else if (MacroBlockEndRegex.match(Text))
1359         FormatTok->setType(TT_MacroBlockEnd);
1360       else if (TypeNames.contains(Identifier))
1361         FormatTok->setFinalizedType(TT_TypeName);
1362     }
1363   }
1364 
1365   return FormatTok;
1366 }
1367 
1368 bool FormatTokenLexer::readRawTokenVerilogSpecific(Token &Tok) {
1369   // In Verilog the quote is not a character literal.
1370   //
1371   // Make the backtick and double backtick identifiers to match against them
1372   // more easily.
1373   //
1374   // In Verilog an escaped identifier starts with backslash and ends with
1375   // whitespace. Unless that whitespace is an escaped newline. A backslash can
1376   // also begin an escaped newline outside of an escaped identifier. We check
1377   // for that outside of the Regex since we can't use negative lookhead
1378   // assertions. Simply changing the '*' to '+' breaks stuff as the escaped
1379   // identifier may have a length of 0 according to Section A.9.3.
1380   // FIXME: If there is an escaped newline in the middle of an escaped
1381   // identifier, allow for pasting the two lines together, But escaped
1382   // identifiers usually occur only in generated code anyway.
1383   static const llvm::Regex VerilogToken(R"re(^('|``?|\\(\\)re"
1384                                         "(\r?\n|\r)|[^[:space:]])*)");
1385 
1386   SmallVector<StringRef, 4> Matches;
1387   const char *Start = Lex->getBufferLocation();
1388   if (!VerilogToken.match(StringRef(Start, Lex->getBuffer().end() - Start),
1389                           &Matches)) {
1390     return false;
1391   }
1392   // There is a null byte at the end of the buffer, so we don't have to check
1393   // Start[1] is within the buffer.
1394   if (Start[0] == '\\' && (Start[1] == '\r' || Start[1] == '\n'))
1395     return false;
1396   size_t Len = Matches[0].size();
1397 
1398   // The kind has to be an identifier so we can match it against those defined
1399   // in Keywords. The kind has to be set before the length because the setLength
1400   // function checks that the kind is not an annotation.
1401   Tok.setKind(tok::raw_identifier);
1402   Tok.setLength(Len);
1403   Tok.setLocation(Lex->getSourceLocation(Start, Len));
1404   Tok.setRawIdentifierData(Start);
1405   Lex->seek(Lex->getCurrentBufferOffset() + Len, /*IsAtStartofline=*/false);
1406   return true;
1407 }
1408 
1409 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
1410   // For Verilog, first see if there is a special token, and fall back to the
1411   // normal lexer if there isn't one.
1412   if (!Style.isVerilog() || !readRawTokenVerilogSpecific(Tok.Tok))
1413     Lex->LexFromRawLexer(Tok.Tok);
1414   Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1415                             Tok.Tok.getLength());
1416   // For formatting, treat unterminated string literals like normal string
1417   // literals.
1418   if (Tok.is(tok::unknown)) {
1419     if (Tok.TokenText.starts_with("\"")) {
1420       Tok.Tok.setKind(tok::string_literal);
1421       Tok.IsUnterminatedLiteral = true;
1422     } else if (Style.isJavaScript() && Tok.TokenText == "''") {
1423       Tok.Tok.setKind(tok::string_literal);
1424     }
1425   }
1426 
1427   if ((Style.isJavaScript() || Style.isProto()) && Tok.is(tok::char_constant))
1428     Tok.Tok.setKind(tok::string_literal);
1429 
1430   if (Tok.is(tok::comment) && isClangFormatOn(Tok.TokenText))
1431     FormattingDisabled = false;
1432 
1433   Tok.Finalized = FormattingDisabled;
1434 
1435   if (Tok.is(tok::comment) && isClangFormatOff(Tok.TokenText))
1436     FormattingDisabled = true;
1437 }
1438 
1439 void FormatTokenLexer::resetLexer(unsigned Offset) {
1440   StringRef Buffer = SourceMgr.getBufferData(ID);
1441   assert(LangOpts.CPlusPlus);
1442   Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1443                       Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
1444   Lex->SetKeepWhitespaceMode(true);
1445   TrailingWhitespace = 0;
1446 }
1447 
1448 } // namespace format
1449 } // namespace clang
1450