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