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     if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
93       FirstInLineIndex = Tokens.size() - 1;
94   } while (Tokens.back()->isNot(tok::eof));
95   return Tokens;
96 }
97 
98 void FormatTokenLexer::tryMergePreviousTokens() {
99   if (tryMerge_TMacro())
100     return;
101   if (tryMergeConflictMarkers())
102     return;
103   if (tryMergeLessLess())
104     return;
105   if (tryMergeForEach())
106     return;
107   if (Style.isCpp() && tryTransformTryUsageForC())
108     return;
109 
110   if (Style.isJavaScript() || Style.isCSharp()) {
111     static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
112                                                                tok::question};
113     static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
114                                                              tok::period};
115     static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
116 
117     if (tryMergeTokens(FatArrow, TT_FatArrow))
118       return;
119     if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
120       // Treat like the "||" operator (as opposed to the ternary ?).
121       Tokens.back()->Tok.setKind(tok::pipepipe);
122       return;
123     }
124     if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
125       // Treat like a regular "." access.
126       Tokens.back()->Tok.setKind(tok::period);
127       return;
128     }
129     if (tryMergeNullishCoalescingEqual())
130       return;
131   }
132 
133   if (Style.isCSharp()) {
134     static const tok::TokenKind CSharpNullConditionalLSquare[] = {
135         tok::question, tok::l_square};
136 
137     if (tryMergeCSharpKeywordVariables())
138       return;
139     if (tryMergeCSharpStringLiteral())
140       return;
141     if (tryTransformCSharpForEach())
142       return;
143     if (tryMergeTokens(CSharpNullConditionalLSquare,
144                        TT_CSharpNullConditionalLSquare)) {
145       // Treat like a regular "[" operator.
146       Tokens.back()->Tok.setKind(tok::l_square);
147       return;
148     }
149   }
150 
151   if (tryMergeNSStringLiteral())
152     return;
153 
154   if (Style.isJavaScript()) {
155     static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
156     static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
157                                                    tok::equal};
158     static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
159                                                   tok::greaterequal};
160     static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
161     static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
162                                                            tok::starequal};
163     static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
164     static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
165 
166     // FIXME: Investigate what token type gives the correct operator priority.
167     if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
168       return;
169     if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
170       return;
171     if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
172       return;
173     if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
174       return;
175     if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
176       Tokens.back()->Tok.setKind(tok::starequal);
177       return;
178     }
179     if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
180         tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
181       // Treat like the "=" assignment operator.
182       Tokens.back()->Tok.setKind(tok::equal);
183       return;
184     }
185     if (tryMergeJSPrivateIdentifier())
186       return;
187   }
188 
189   if (Style.Language == FormatStyle::LK_Java) {
190     static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
191         tok::greater, tok::greater, tok::greaterequal};
192     if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
193       return;
194   }
195 }
196 
197 bool FormatTokenLexer::tryMergeNSStringLiteral() {
198   if (Tokens.size() < 2)
199     return false;
200   auto &At = *(Tokens.end() - 2);
201   auto &String = *(Tokens.end() - 1);
202   if (!At->is(tok::at) || !String->is(tok::string_literal))
203     return false;
204   At->Tok.setKind(tok::string_literal);
205   At->TokenText = StringRef(At->TokenText.begin(),
206                             String->TokenText.end() - At->TokenText.begin());
207   At->ColumnWidth += String->ColumnWidth;
208   At->setType(TT_ObjCStringLiteral);
209   Tokens.erase(Tokens.end() - 1);
210   return true;
211 }
212 
213 bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
214   // Merges #idenfier into a single identifier with the text #identifier
215   // but the token tok::identifier.
216   if (Tokens.size() < 2)
217     return false;
218   auto &Hash = *(Tokens.end() - 2);
219   auto &Identifier = *(Tokens.end() - 1);
220   if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier))
221     return false;
222   Hash->Tok.setKind(tok::identifier);
223   Hash->TokenText =
224       StringRef(Hash->TokenText.begin(),
225                 Identifier->TokenText.end() - Hash->TokenText.begin());
226   Hash->ColumnWidth += Identifier->ColumnWidth;
227   Hash->setType(TT_JsPrivateIdentifier);
228   Tokens.erase(Tokens.end() - 1);
229   return true;
230 }
231 
232 // Search for verbatim or interpolated string literals @"ABC" or
233 // $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to
234 // prevent splitting of @, $ and ".
235 // Merging of multiline verbatim strings with embedded '"' is handled in
236 // handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
237 bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
238   if (Tokens.size() < 2)
239     return false;
240 
241   // Interpolated strings could contain { } with " characters inside.
242   // $"{x ?? "null"}"
243   // should not be split into $"{x ?? ", null, "}" but should treated as a
244   // single string-literal.
245   //
246   // We opt not to try and format expressions inside {} within a C#
247   // interpolated string. Formatting expressions within an interpolated string
248   // would require similar work as that done for JavaScript template strings
249   // in `handleTemplateStrings()`.
250   auto &CSharpInterpolatedString = *(Tokens.end() - 2);
251   if (CSharpInterpolatedString->getType() == TT_CSharpStringLiteral &&
252       (CSharpInterpolatedString->TokenText.startswith(R"($")") ||
253        CSharpInterpolatedString->TokenText.startswith(R"($@")"))) {
254     int UnmatchedOpeningBraceCount = 0;
255 
256     auto TokenTextSize = CSharpInterpolatedString->TokenText.size();
257     for (size_t Index = 0; Index < TokenTextSize; ++Index) {
258       char C = CSharpInterpolatedString->TokenText[Index];
259       if (C == '{') {
260         // "{{"  inside an interpolated string is an escaped '{' so skip it.
261         if (Index + 1 < TokenTextSize &&
262             CSharpInterpolatedString->TokenText[Index + 1] == '{') {
263           ++Index;
264           continue;
265         }
266         ++UnmatchedOpeningBraceCount;
267       } else if (C == '}') {
268         // "}}"  inside an interpolated string is an escaped '}' so skip it.
269         if (Index + 1 < TokenTextSize &&
270             CSharpInterpolatedString->TokenText[Index + 1] == '}') {
271           ++Index;
272           continue;
273         }
274         --UnmatchedOpeningBraceCount;
275       }
276     }
277 
278     if (UnmatchedOpeningBraceCount > 0) {
279       auto &NextToken = *(Tokens.end() - 1);
280       CSharpInterpolatedString->TokenText =
281           StringRef(CSharpInterpolatedString->TokenText.begin(),
282                     NextToken->TokenText.end() -
283                         CSharpInterpolatedString->TokenText.begin());
284       CSharpInterpolatedString->ColumnWidth += NextToken->ColumnWidth;
285       Tokens.erase(Tokens.end() - 1);
286       return true;
287     }
288   }
289 
290   // Look for @"aaaaaa" or $"aaaaaa".
291   auto &String = *(Tokens.end() - 1);
292   if (!String->is(tok::string_literal))
293     return false;
294 
295   auto &At = *(Tokens.end() - 2);
296   if (!(At->is(tok::at) || At->TokenText == "$"))
297     return false;
298 
299   if (Tokens.size() > 2 && At->is(tok::at)) {
300     auto &Dollar = *(Tokens.end() - 3);
301     if (Dollar->TokenText == "$") {
302       // This looks like $@"aaaaa" so we need to combine all 3 tokens.
303       Dollar->Tok.setKind(tok::string_literal);
304       Dollar->TokenText =
305           StringRef(Dollar->TokenText.begin(),
306                     String->TokenText.end() - Dollar->TokenText.begin());
307       Dollar->ColumnWidth += (At->ColumnWidth + String->ColumnWidth);
308       Dollar->setType(TT_CSharpStringLiteral);
309       Tokens.erase(Tokens.end() - 2);
310       Tokens.erase(Tokens.end() - 1);
311       return true;
312     }
313   }
314 
315   // Convert back into just a string_literal.
316   At->Tok.setKind(tok::string_literal);
317   At->TokenText = StringRef(At->TokenText.begin(),
318                             String->TokenText.end() - At->TokenText.begin());
319   At->ColumnWidth += String->ColumnWidth;
320   At->setType(TT_CSharpStringLiteral);
321   Tokens.erase(Tokens.end() - 1);
322   return true;
323 }
324 
325 // Valid C# attribute targets:
326 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
327 const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
328     "assembly", "module",   "field",  "event", "method",
329     "param",    "property", "return", "type",
330 };
331 
332 bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
333   if (Tokens.size() < 2)
334     return false;
335   auto &NullishCoalescing = *(Tokens.end() - 2);
336   auto &Equal = *(Tokens.end() - 1);
337   if (NullishCoalescing->getType() != TT_NullCoalescingOperator ||
338       !Equal->is(tok::equal))
339     return false;
340   NullishCoalescing->Tok.setKind(tok::equal); // no '??=' in clang tokens.
341   NullishCoalescing->TokenText =
342       StringRef(NullishCoalescing->TokenText.begin(),
343                 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
344   NullishCoalescing->ColumnWidth += Equal->ColumnWidth;
345   NullishCoalescing->setType(TT_NullCoalescingEqual);
346   Tokens.erase(Tokens.end() - 1);
347   return true;
348 }
349 
350 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
351   if (Tokens.size() < 2)
352     return false;
353   auto &At = *(Tokens.end() - 2);
354   auto &Keyword = *(Tokens.end() - 1);
355   if (!At->is(tok::at))
356     return false;
357   if (!Keywords.isCSharpKeyword(*Keyword))
358     return false;
359 
360   At->Tok.setKind(tok::identifier);
361   At->TokenText = StringRef(At->TokenText.begin(),
362                             Keyword->TokenText.end() - At->TokenText.begin());
363   At->ColumnWidth += Keyword->ColumnWidth;
364   At->setType(Keyword->getType());
365   Tokens.erase(Tokens.end() - 1);
366   return true;
367 }
368 
369 // In C# transform identifier foreach into kw_foreach
370 bool FormatTokenLexer::tryTransformCSharpForEach() {
371   if (Tokens.size() < 1)
372     return false;
373   auto &Identifier = *(Tokens.end() - 1);
374   if (!Identifier->is(tok::identifier))
375     return false;
376   if (Identifier->TokenText != "foreach")
377     return false;
378 
379   Identifier->setType(TT_ForEachMacro);
380   Identifier->Tok.setKind(tok::kw_for);
381   return true;
382 }
383 
384 bool FormatTokenLexer::tryMergeForEach() {
385   if (Tokens.size() < 2)
386     return false;
387   auto &For = *(Tokens.end() - 2);
388   auto &Each = *(Tokens.end() - 1);
389   if (!For->is(tok::kw_for))
390     return false;
391   if (!Each->is(tok::identifier))
392     return false;
393   if (Each->TokenText != "each")
394     return false;
395 
396   For->setType(TT_ForEachMacro);
397   For->Tok.setKind(tok::kw_for);
398 
399   For->TokenText = StringRef(For->TokenText.begin(),
400                              Each->TokenText.end() - For->TokenText.begin());
401   For->ColumnWidth += Each->ColumnWidth;
402   Tokens.erase(Tokens.end() - 1);
403   return true;
404 }
405 
406 bool FormatTokenLexer::tryTransformTryUsageForC() {
407   if (Tokens.size() < 2)
408     return false;
409   auto &Try = *(Tokens.end() - 2);
410   if (!Try->is(tok::kw_try))
411     return false;
412   auto &Next = *(Tokens.end() - 1);
413   if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
414     return false;
415 
416   if (Tokens.size() > 2) {
417     auto &At = *(Tokens.end() - 3);
418     if (At->is(tok::at))
419       return false;
420   }
421 
422   Try->Tok.setKind(tok::identifier);
423   return true;
424 }
425 
426 bool FormatTokenLexer::tryMergeLessLess() {
427   // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
428   if (Tokens.size() < 3)
429     return false;
430 
431   auto First = Tokens.end() - 3;
432   if (First[0]->isNot(tok::less) || First[1]->isNot(tok::less))
433     return false;
434 
435   // Only merge if there currently is no whitespace between the two "<".
436   if (First[1]->hasWhitespaceBefore())
437     return false;
438 
439   auto X = Tokens.size() > 3 ? First[-1] : nullptr;
440   auto Y = First[2];
441   if ((X && X->is(tok::less)) || Y->is(tok::less))
442     return false;
443 
444   // Do not remove a whitespace between the two "<" e.g. "operator< <>".
445   if (X && X->is(tok::kw_operator) && Y->is(tok::greater))
446     return false;
447 
448   First[0]->Tok.setKind(tok::lessless);
449   First[0]->TokenText = "<<";
450   First[0]->ColumnWidth += 1;
451   Tokens.erase(Tokens.end() - 2);
452   return true;
453 }
454 
455 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
456                                       TokenType NewType) {
457   if (Tokens.size() < Kinds.size())
458     return false;
459 
460   SmallVectorImpl<FormatToken *>::const_iterator First =
461       Tokens.end() - Kinds.size();
462   if (!First[0]->is(Kinds[0]))
463     return false;
464   unsigned AddLength = 0;
465   for (unsigned i = 1; i < Kinds.size(); ++i) {
466     if (!First[i]->is(Kinds[i]) || First[i]->hasWhitespaceBefore())
467       return false;
468     AddLength += First[i]->TokenText.size();
469   }
470   Tokens.resize(Tokens.size() - Kinds.size() + 1);
471   First[0]->TokenText = StringRef(First[0]->TokenText.data(),
472                                   First[0]->TokenText.size() + AddLength);
473   First[0]->ColumnWidth += AddLength;
474   First[0]->setType(NewType);
475   return true;
476 }
477 
478 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
479 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
480   // NB: This is not entirely correct, as an r_paren can introduce an operand
481   // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
482   // corner case to not matter in practice, though.
483   return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
484                       tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
485                       tok::colon, tok::question, tok::tilde) ||
486          Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
487                       tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
488                       tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
489          Tok->isBinaryOperator();
490 }
491 
492 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
493   if (!Prev)
494     return true;
495 
496   // Regex literals can only follow after prefix unary operators, not after
497   // postfix unary operators. If the '++' is followed by a non-operand
498   // introducing token, the slash here is the operand and not the start of a
499   // regex.
500   // `!` is an unary prefix operator, but also a post-fix operator that casts
501   // away nullability, so the same check applies.
502   if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
503     return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
504 
505   // The previous token must introduce an operand location where regex
506   // literals can occur.
507   if (!precedesOperand(Prev))
508     return false;
509 
510   return true;
511 }
512 
513 // Tries to parse a JavaScript Regex literal starting at the current token,
514 // if that begins with a slash and is in a location where JavaScript allows
515 // regex literals. Changes the current token to a regex literal and updates
516 // its text if successful.
517 void FormatTokenLexer::tryParseJSRegexLiteral() {
518   FormatToken *RegexToken = Tokens.back();
519   if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
520     return;
521 
522   FormatToken *Prev = nullptr;
523   for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
524     // NB: Because previous pointers are not initialized yet, this cannot use
525     // Token.getPreviousNonComment.
526     if (FT->isNot(tok::comment)) {
527       Prev = FT;
528       break;
529     }
530   }
531 
532   if (!canPrecedeRegexLiteral(Prev))
533     return;
534 
535   // 'Manually' lex ahead in the current file buffer.
536   const char *Offset = Lex->getBufferLocation();
537   const char *RegexBegin = Offset - RegexToken->TokenText.size();
538   StringRef Buffer = Lex->getBuffer();
539   bool InCharacterClass = false;
540   bool HaveClosingSlash = false;
541   for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
542     // Regular expressions are terminated with a '/', which can only be
543     // escaped using '\' or a character class between '[' and ']'.
544     // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
545     switch (*Offset) {
546     case '\\':
547       // Skip the escaped character.
548       ++Offset;
549       break;
550     case '[':
551       InCharacterClass = true;
552       break;
553     case ']':
554       InCharacterClass = false;
555       break;
556     case '/':
557       if (!InCharacterClass)
558         HaveClosingSlash = true;
559       break;
560     }
561   }
562 
563   RegexToken->setType(TT_RegexLiteral);
564   // Treat regex literals like other string_literals.
565   RegexToken->Tok.setKind(tok::string_literal);
566   RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
567   RegexToken->ColumnWidth = RegexToken->TokenText.size();
568 
569   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
570 }
571 
572 void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
573   FormatToken *CSharpStringLiteral = Tokens.back();
574 
575   if (CSharpStringLiteral->getType() != TT_CSharpStringLiteral)
576     return;
577 
578   // Deal with multiline strings.
579   if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") ||
580         CSharpStringLiteral->TokenText.startswith(R"($@")")))
581     return;
582 
583   const char *StrBegin =
584       Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size();
585   const char *Offset = StrBegin;
586   if (CSharpStringLiteral->TokenText.startswith(R"(@")"))
587     Offset += 2;
588   else // CSharpStringLiteral->TokenText.startswith(R"($@")")
589     Offset += 3;
590 
591   // Look for a terminating '"' in the current file buffer.
592   // Make no effort to format code within an interpolated or verbatim string.
593   for (; Offset != Lex->getBuffer().end(); ++Offset) {
594     if (Offset[0] == '"') {
595       // "" within a verbatim string is an escaped double quote: skip it.
596       if (Offset + 1 < Lex->getBuffer().end() && Offset[1] == '"')
597         ++Offset;
598       else
599         break;
600     }
601   }
602 
603   // Make no attempt to format code properly if a verbatim string is
604   // unterminated.
605   if (Offset == Lex->getBuffer().end())
606     return;
607 
608   StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
609   CSharpStringLiteral->TokenText = LiteralText;
610 
611   // Adjust width for potentially multiline string literals.
612   size_t FirstBreak = LiteralText.find('\n');
613   StringRef FirstLineText = FirstBreak == StringRef::npos
614                                 ? LiteralText
615                                 : LiteralText.substr(0, FirstBreak);
616   CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
617       FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
618       Encoding);
619   size_t LastBreak = LiteralText.rfind('\n');
620   if (LastBreak != StringRef::npos) {
621     CSharpStringLiteral->IsMultiline = true;
622     unsigned StartColumn = 0;
623     CSharpStringLiteral->LastLineColumnWidth =
624         encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
625                                       StartColumn, Style.TabWidth, Encoding);
626   }
627 
628   SourceLocation loc = Offset < Lex->getBuffer().end()
629                            ? Lex->getSourceLocation(Offset + 1)
630                            : SourceMgr.getLocForEndOfFile(ID);
631   resetLexer(SourceMgr.getFileOffset(loc));
632 }
633 
634 void FormatTokenLexer::handleTemplateStrings() {
635   FormatToken *BacktickToken = Tokens.back();
636 
637   if (BacktickToken->is(tok::l_brace)) {
638     StateStack.push(LexerState::NORMAL);
639     return;
640   }
641   if (BacktickToken->is(tok::r_brace)) {
642     if (StateStack.size() == 1)
643       return;
644     StateStack.pop();
645     if (StateStack.top() != LexerState::TEMPLATE_STRING)
646       return;
647     // If back in TEMPLATE_STRING, fallthrough and continue parsing the
648   } else if (BacktickToken->is(tok::unknown) &&
649              BacktickToken->TokenText == "`") {
650     StateStack.push(LexerState::TEMPLATE_STRING);
651   } else {
652     return; // Not actually a template
653   }
654 
655   // 'Manually' lex ahead in the current file buffer.
656   const char *Offset = Lex->getBufferLocation();
657   const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
658   for (; Offset != Lex->getBuffer().end(); ++Offset) {
659     if (Offset[0] == '`') {
660       StateStack.pop();
661       break;
662     }
663     if (Offset[0] == '\\') {
664       ++Offset; // Skip the escaped character.
665     } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
666                Offset[1] == '{') {
667       // '${' introduces an expression interpolation in the template string.
668       StateStack.push(LexerState::NORMAL);
669       ++Offset;
670       break;
671     }
672   }
673 
674   StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
675   BacktickToken->setType(TT_TemplateString);
676   BacktickToken->Tok.setKind(tok::string_literal);
677   BacktickToken->TokenText = LiteralText;
678 
679   // Adjust width for potentially multiline string literals.
680   size_t FirstBreak = LiteralText.find('\n');
681   StringRef FirstLineText = FirstBreak == StringRef::npos
682                                 ? LiteralText
683                                 : LiteralText.substr(0, FirstBreak);
684   BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
685       FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
686   size_t LastBreak = LiteralText.rfind('\n');
687   if (LastBreak != StringRef::npos) {
688     BacktickToken->IsMultiline = true;
689     unsigned StartColumn = 0; // The template tail spans the entire line.
690     BacktickToken->LastLineColumnWidth =
691         encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
692                                       StartColumn, Style.TabWidth, Encoding);
693   }
694 
695   SourceLocation loc = Offset < Lex->getBuffer().end()
696                            ? Lex->getSourceLocation(Offset + 1)
697                            : SourceMgr.getLocForEndOfFile(ID);
698   resetLexer(SourceMgr.getFileOffset(loc));
699 }
700 
701 void FormatTokenLexer::tryParsePythonComment() {
702   FormatToken *HashToken = Tokens.back();
703   if (!HashToken->isOneOf(tok::hash, tok::hashhash))
704     return;
705   // Turn the remainder of this line into a comment.
706   const char *CommentBegin =
707       Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
708   size_t From = CommentBegin - Lex->getBuffer().begin();
709   size_t To = Lex->getBuffer().find_first_of('\n', From);
710   if (To == StringRef::npos)
711     To = Lex->getBuffer().size();
712   size_t Len = To - From;
713   HashToken->setType(TT_LineComment);
714   HashToken->Tok.setKind(tok::comment);
715   HashToken->TokenText = Lex->getBuffer().substr(From, Len);
716   SourceLocation Loc = To < Lex->getBuffer().size()
717                            ? Lex->getSourceLocation(CommentBegin + Len)
718                            : SourceMgr.getLocForEndOfFile(ID);
719   resetLexer(SourceMgr.getFileOffset(Loc));
720 }
721 
722 bool FormatTokenLexer::tryMerge_TMacro() {
723   if (Tokens.size() < 4)
724     return false;
725   FormatToken *Last = Tokens.back();
726   if (!Last->is(tok::r_paren))
727     return false;
728 
729   FormatToken *String = Tokens[Tokens.size() - 2];
730   if (!String->is(tok::string_literal) || String->IsMultiline)
731     return false;
732 
733   if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
734     return false;
735 
736   FormatToken *Macro = Tokens[Tokens.size() - 4];
737   if (Macro->TokenText != "_T")
738     return false;
739 
740   const char *Start = Macro->TokenText.data();
741   const char *End = Last->TokenText.data() + Last->TokenText.size();
742   String->TokenText = StringRef(Start, End - Start);
743   String->IsFirst = Macro->IsFirst;
744   String->LastNewlineOffset = Macro->LastNewlineOffset;
745   String->WhitespaceRange = Macro->WhitespaceRange;
746   String->OriginalColumn = Macro->OriginalColumn;
747   String->ColumnWidth = encoding::columnWidthWithTabs(
748       String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
749   String->NewlinesBefore = Macro->NewlinesBefore;
750   String->HasUnescapedNewline = Macro->HasUnescapedNewline;
751 
752   Tokens.pop_back();
753   Tokens.pop_back();
754   Tokens.pop_back();
755   Tokens.back() = String;
756   if (FirstInLineIndex >= Tokens.size())
757     FirstInLineIndex = Tokens.size() - 1;
758   return true;
759 }
760 
761 bool FormatTokenLexer::tryMergeConflictMarkers() {
762   if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
763     return false;
764 
765   // Conflict lines look like:
766   // <marker> <text from the vcs>
767   // For example:
768   // >>>>>>> /file/in/file/system at revision 1234
769   //
770   // We merge all tokens in a line that starts with a conflict marker
771   // into a single token with a special token type that the unwrapped line
772   // parser will use to correctly rebuild the underlying code.
773 
774   FileID ID;
775   // Get the position of the first token in the line.
776   unsigned FirstInLineOffset;
777   std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
778       Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
779   StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
780   // Calculate the offset of the start of the current line.
781   auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
782   if (LineOffset == StringRef::npos)
783     LineOffset = 0;
784   else
785     ++LineOffset;
786 
787   auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
788   StringRef LineStart;
789   if (FirstSpace == StringRef::npos)
790     LineStart = Buffer.substr(LineOffset);
791   else
792     LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
793 
794   TokenType Type = TT_Unknown;
795   if (LineStart == "<<<<<<<" || LineStart == ">>>>")
796     Type = TT_ConflictStart;
797   else if (LineStart == "|||||||" || LineStart == "=======" ||
798            LineStart == "====")
799     Type = TT_ConflictAlternative;
800   else if (LineStart == ">>>>>>>" || LineStart == "<<<<")
801     Type = TT_ConflictEnd;
802 
803   if (Type != TT_Unknown) {
804     FormatToken *Next = Tokens.back();
805 
806     Tokens.resize(FirstInLineIndex + 1);
807     // We do not need to build a complete token here, as we will skip it
808     // during parsing anyway (as we must not touch whitespace around conflict
809     // markers).
810     Tokens.back()->setType(Type);
811     Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
812 
813     Tokens.push_back(Next);
814     return true;
815   }
816 
817   return false;
818 }
819 
820 FormatToken *FormatTokenLexer::getStashedToken() {
821   // Create a synthesized second '>' or '<' token.
822   Token Tok = FormatTok->Tok;
823   StringRef TokenText = FormatTok->TokenText;
824 
825   unsigned OriginalColumn = FormatTok->OriginalColumn;
826   FormatTok = new (Allocator.Allocate()) FormatToken;
827   FormatTok->Tok = Tok;
828   SourceLocation TokLocation =
829       FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
830   FormatTok->Tok.setLocation(TokLocation);
831   FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
832   FormatTok->TokenText = TokenText;
833   FormatTok->ColumnWidth = 1;
834   FormatTok->OriginalColumn = OriginalColumn + 1;
835 
836   return FormatTok;
837 }
838 
839 FormatToken *FormatTokenLexer::getNextToken() {
840   if (StateStack.top() == LexerState::TOKEN_STASHED) {
841     StateStack.pop();
842     return getStashedToken();
843   }
844 
845   FormatTok = new (Allocator.Allocate()) FormatToken;
846   readRawToken(*FormatTok);
847   SourceLocation WhitespaceStart =
848       FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
849   FormatTok->IsFirst = IsFirstToken;
850   IsFirstToken = false;
851 
852   // Consume and record whitespace until we find a significant token.
853   unsigned WhitespaceLength = TrailingWhitespace;
854   while (FormatTok->is(tok::unknown)) {
855     StringRef Text = FormatTok->TokenText;
856     auto EscapesNewline = [&](int pos) {
857       // A '\r' here is just part of '\r\n'. Skip it.
858       if (pos >= 0 && Text[pos] == '\r')
859         --pos;
860       // See whether there is an odd number of '\' before this.
861       // FIXME: This is wrong. A '\' followed by a newline is always removed,
862       // regardless of whether there is another '\' before it.
863       // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
864       unsigned count = 0;
865       for (; pos >= 0; --pos, ++count)
866         if (Text[pos] != '\\')
867           break;
868       return count & 1;
869     };
870     // FIXME: This miscounts tok:unknown tokens that are not just
871     // whitespace, e.g. a '`' character.
872     for (int i = 0, e = Text.size(); i != e; ++i) {
873       switch (Text[i]) {
874       case '\n':
875         ++FormatTok->NewlinesBefore;
876         FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
877         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
878         Column = 0;
879         break;
880       case '\r':
881         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
882         Column = 0;
883         break;
884       case '\f':
885       case '\v':
886         Column = 0;
887         break;
888       case ' ':
889         ++Column;
890         break;
891       case '\t':
892         Column +=
893             Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
894         break;
895       case '\\':
896         if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
897           FormatTok->setType(TT_ImplicitStringLiteral);
898         break;
899       default:
900         FormatTok->setType(TT_ImplicitStringLiteral);
901         break;
902       }
903       if (FormatTok->getType() == TT_ImplicitStringLiteral)
904         break;
905     }
906 
907     if (FormatTok->is(TT_ImplicitStringLiteral))
908       break;
909     WhitespaceLength += FormatTok->Tok.getLength();
910 
911     readRawToken(*FormatTok);
912   }
913 
914   // JavaScript and Java do not allow to escape the end of the line with a
915   // backslash. Backslashes are syntax errors in plain source, but can occur in
916   // comments. When a single line comment ends with a \, it'll cause the next
917   // line of code to be lexed as a comment, breaking formatting. The code below
918   // finds comments that contain a backslash followed by a line break, truncates
919   // the comment token at the backslash, and resets the lexer to restart behind
920   // the backslash.
921   if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
922       FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
923     size_t BackslashPos = FormatTok->TokenText.find('\\');
924     while (BackslashPos != StringRef::npos) {
925       if (BackslashPos + 1 < FormatTok->TokenText.size() &&
926           FormatTok->TokenText[BackslashPos + 1] == '\n') {
927         const char *Offset = Lex->getBufferLocation();
928         Offset -= FormatTok->TokenText.size();
929         Offset += BackslashPos + 1;
930         resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
931         FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
932         FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
933             FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
934             Encoding);
935         break;
936       }
937       BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
938     }
939   }
940 
941   // In case the token starts with escaped newlines, we want to
942   // take them into account as whitespace - this pattern is quite frequent
943   // in macro definitions.
944   // FIXME: Add a more explicit test.
945   while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
946     unsigned SkippedWhitespace = 0;
947     if (FormatTok->TokenText.size() > 2 &&
948         (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
949       SkippedWhitespace = 3;
950     else if (FormatTok->TokenText[1] == '\n')
951       SkippedWhitespace = 2;
952     else
953       break;
954 
955     ++FormatTok->NewlinesBefore;
956     WhitespaceLength += SkippedWhitespace;
957     FormatTok->LastNewlineOffset = SkippedWhitespace;
958     Column = 0;
959     FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
960   }
961 
962   FormatTok->WhitespaceRange = SourceRange(
963       WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
964 
965   FormatTok->OriginalColumn = Column;
966 
967   TrailingWhitespace = 0;
968   if (FormatTok->is(tok::comment)) {
969     // FIXME: Add the trimmed whitespace to Column.
970     StringRef UntrimmedText = FormatTok->TokenText;
971     FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
972     TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
973   } else if (FormatTok->is(tok::raw_identifier)) {
974     IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
975     FormatTok->Tok.setIdentifierInfo(&Info);
976     FormatTok->Tok.setKind(Info.getTokenID());
977     if (Style.Language == FormatStyle::LK_Java &&
978         FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
979                            tok::kw_operator)) {
980       FormatTok->Tok.setKind(tok::identifier);
981       FormatTok->Tok.setIdentifierInfo(nullptr);
982     } else if (Style.isJavaScript() &&
983                FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
984                                   tok::kw_operator)) {
985       FormatTok->Tok.setKind(tok::identifier);
986       FormatTok->Tok.setIdentifierInfo(nullptr);
987     }
988   } else if (FormatTok->is(tok::greatergreater)) {
989     FormatTok->Tok.setKind(tok::greater);
990     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
991     ++Column;
992     StateStack.push(LexerState::TOKEN_STASHED);
993   } else if (FormatTok->is(tok::lessless)) {
994     FormatTok->Tok.setKind(tok::less);
995     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
996     ++Column;
997     StateStack.push(LexerState::TOKEN_STASHED);
998   }
999 
1000   // Now FormatTok is the next non-whitespace token.
1001 
1002   StringRef Text = FormatTok->TokenText;
1003   size_t FirstNewlinePos = Text.find('\n');
1004   if (FirstNewlinePos == StringRef::npos) {
1005     // FIXME: ColumnWidth actually depends on the start column, we need to
1006     // take this into account when the token is moved.
1007     FormatTok->ColumnWidth =
1008         encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1009     Column += FormatTok->ColumnWidth;
1010   } else {
1011     FormatTok->IsMultiline = true;
1012     // FIXME: ColumnWidth actually depends on the start column, we need to
1013     // take this into account when the token is moved.
1014     FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1015         Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1016 
1017     // The last line of the token always starts in column 0.
1018     // Thus, the length can be precomputed even in the presence of tabs.
1019     FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1020         Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
1021     Column = FormatTok->LastLineColumnWidth;
1022   }
1023 
1024   if (Style.isCpp()) {
1025     auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
1026     if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1027           Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1028               tok::pp_define) &&
1029         it != Macros.end()) {
1030       FormatTok->setType(it->second);
1031       if (it->second == TT_IfMacro) {
1032         // The lexer token currently has type tok::kw_unknown. However, for this
1033         // substitution to be treated correctly in the TokenAnnotator, faking
1034         // the tok value seems to be needed. Not sure if there's a more elegant
1035         // way.
1036         FormatTok->Tok.setKind(tok::kw_if);
1037       }
1038     } else if (FormatTok->is(tok::identifier)) {
1039       if (MacroBlockBeginRegex.match(Text))
1040         FormatTok->setType(TT_MacroBlockBegin);
1041       else if (MacroBlockEndRegex.match(Text))
1042         FormatTok->setType(TT_MacroBlockEnd);
1043     }
1044   }
1045 
1046   return FormatTok;
1047 }
1048 
1049 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
1050   Lex->LexFromRawLexer(Tok.Tok);
1051   Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1052                             Tok.Tok.getLength());
1053   // For formatting, treat unterminated string literals like normal string
1054   // literals.
1055   if (Tok.is(tok::unknown)) {
1056     if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1057       Tok.Tok.setKind(tok::string_literal);
1058       Tok.IsUnterminatedLiteral = true;
1059     } else if (Style.isJavaScript() && Tok.TokenText == "''") {
1060       Tok.Tok.setKind(tok::string_literal);
1061     }
1062   }
1063 
1064   if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto ||
1065        Style.Language == FormatStyle::LK_TextProto) &&
1066       Tok.is(tok::char_constant))
1067     Tok.Tok.setKind(tok::string_literal);
1068 
1069   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1070                                Tok.TokenText == "/* clang-format on */"))
1071     FormattingDisabled = false;
1072 
1073   Tok.Finalized = FormattingDisabled;
1074 
1075   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1076                                Tok.TokenText == "/* clang-format off */"))
1077     FormattingDisabled = true;
1078 }
1079 
1080 void FormatTokenLexer::resetLexer(unsigned Offset) {
1081   StringRef Buffer = SourceMgr.getBufferData(ID);
1082   LangOpts = getFormattingLangOpts(Style);
1083   Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1084                       Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
1085   Lex->SetKeepWhitespaceMode(true);
1086   TrailingWhitespace = 0;
1087 }
1088 
1089 } // namespace format
1090 } // namespace clang
1091