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