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