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