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