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 (tryMergeCSharpNullConditionals())
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);
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 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
333   if (Tokens.size() < 2)
334     return false;
335   auto &At = *(Tokens.end() - 2);
336   auto &Keyword = *(Tokens.end() - 1);
337   if (!At->is(tok::at))
338     return false;
339   if (!Keywords.isCSharpKeyword(*Keyword))
340     return false;
341 
342   At->Tok.setKind(tok::identifier);
343   At->TokenText = StringRef(At->TokenText.begin(),
344                             Keyword->TokenText.end() - At->TokenText.begin());
345   At->ColumnWidth += Keyword->ColumnWidth;
346   At->Type = Keyword->Type;
347   Tokens.erase(Tokens.end() - 1);
348   return true;
349 }
350 
351 // In C# merge the Identifier and the ? together e.g. arg?.
352 bool FormatTokenLexer::tryMergeCSharpNullConditionals() {
353   if (Tokens.size() < 2)
354     return false;
355   auto &Identifier = *(Tokens.end() - 2);
356   auto &Question = *(Tokens.end() - 1);
357   if (!Identifier->isOneOf(tok::r_square, tok::identifier) ||
358       !Question->is(tok::question))
359     return false;
360   Identifier->TokenText =
361       StringRef(Identifier->TokenText.begin(),
362                 Question->TokenText.end() - Identifier->TokenText.begin());
363   Identifier->ColumnWidth += Question->ColumnWidth;
364   Tokens.erase(Tokens.end() - 1);
365   return true;
366 }
367 
368 // In C# transform identifier foreach into kw_foreach
369 bool FormatTokenLexer::tryTransformCSharpForEach() {
370   if (Tokens.size() < 1)
371     return false;
372   auto &Identifier = *(Tokens.end() - 1);
373   if (!Identifier->is(tok::identifier))
374     return false;
375   if (Identifier->TokenText != "foreach")
376     return false;
377 
378   Identifier->Type = TT_ForEachMacro;
379   Identifier->Tok.setKind(tok::kw_for);
380   return true;
381 }
382 
383 bool FormatTokenLexer::tryMergeLessLess() {
384   // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
385   if (Tokens.size() < 3)
386     return false;
387 
388   bool FourthTokenIsLess = false;
389   if (Tokens.size() > 3)
390     FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
391 
392   auto First = Tokens.end() - 3;
393   if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
394       First[0]->isNot(tok::less) || FourthTokenIsLess)
395     return false;
396 
397   // Only merge if there currently is no whitespace between the two "<".
398   if (First[1]->WhitespaceRange.getBegin() !=
399       First[1]->WhitespaceRange.getEnd())
400     return false;
401 
402   First[0]->Tok.setKind(tok::lessless);
403   First[0]->TokenText = "<<";
404   First[0]->ColumnWidth += 1;
405   Tokens.erase(Tokens.end() - 2);
406   return true;
407 }
408 
409 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
410                                       TokenType NewType) {
411   if (Tokens.size() < Kinds.size())
412     return false;
413 
414   SmallVectorImpl<FormatToken *>::const_iterator First =
415       Tokens.end() - Kinds.size();
416   if (!First[0]->is(Kinds[0]))
417     return false;
418   unsigned AddLength = 0;
419   for (unsigned i = 1; i < Kinds.size(); ++i) {
420     if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
421                                        First[i]->WhitespaceRange.getEnd())
422       return false;
423     AddLength += First[i]->TokenText.size();
424   }
425   Tokens.resize(Tokens.size() - Kinds.size() + 1);
426   First[0]->TokenText = StringRef(First[0]->TokenText.data(),
427                                   First[0]->TokenText.size() + AddLength);
428   First[0]->ColumnWidth += AddLength;
429   First[0]->Type = NewType;
430   return true;
431 }
432 
433 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
434 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
435   // NB: This is not entirely correct, as an r_paren can introduce an operand
436   // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
437   // corner case to not matter in practice, though.
438   return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
439                       tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
440                       tok::colon, tok::question, tok::tilde) ||
441          Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
442                       tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
443                       tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
444          Tok->isBinaryOperator();
445 }
446 
447 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
448   if (!Prev)
449     return true;
450 
451   // Regex literals can only follow after prefix unary operators, not after
452   // postfix unary operators. If the '++' is followed by a non-operand
453   // introducing token, the slash here is the operand and not the start of a
454   // regex.
455   // `!` is an unary prefix operator, but also a post-fix operator that casts
456   // away nullability, so the same check applies.
457   if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
458     return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
459 
460   // The previous token must introduce an operand location where regex
461   // literals can occur.
462   if (!precedesOperand(Prev))
463     return false;
464 
465   return true;
466 }
467 
468 // Tries to parse a JavaScript Regex literal starting at the current token,
469 // if that begins with a slash and is in a location where JavaScript allows
470 // regex literals. Changes the current token to a regex literal and updates
471 // its text if successful.
472 void FormatTokenLexer::tryParseJSRegexLiteral() {
473   FormatToken *RegexToken = Tokens.back();
474   if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
475     return;
476 
477   FormatToken *Prev = nullptr;
478   for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
479     // NB: Because previous pointers are not initialized yet, this cannot use
480     // Token.getPreviousNonComment.
481     if ((*I)->isNot(tok::comment)) {
482       Prev = *I;
483       break;
484     }
485   }
486 
487   if (!canPrecedeRegexLiteral(Prev))
488     return;
489 
490   // 'Manually' lex ahead in the current file buffer.
491   const char *Offset = Lex->getBufferLocation();
492   const char *RegexBegin = Offset - RegexToken->TokenText.size();
493   StringRef Buffer = Lex->getBuffer();
494   bool InCharacterClass = false;
495   bool HaveClosingSlash = false;
496   for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
497     // Regular expressions are terminated with a '/', which can only be
498     // escaped using '\' or a character class between '[' and ']'.
499     // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
500     switch (*Offset) {
501     case '\\':
502       // Skip the escaped character.
503       ++Offset;
504       break;
505     case '[':
506       InCharacterClass = true;
507       break;
508     case ']':
509       InCharacterClass = false;
510       break;
511     case '/':
512       if (!InCharacterClass)
513         HaveClosingSlash = true;
514       break;
515     }
516   }
517 
518   RegexToken->Type = TT_RegexLiteral;
519   // Treat regex literals like other string_literals.
520   RegexToken->Tok.setKind(tok::string_literal);
521   RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
522   RegexToken->ColumnWidth = RegexToken->TokenText.size();
523 
524   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
525 }
526 
527 void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
528   FormatToken *CSharpStringLiteral = Tokens.back();
529 
530   if (CSharpStringLiteral->Type != TT_CSharpStringLiteral)
531     return;
532 
533   // Deal with multiline strings.
534   if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") ||
535         CSharpStringLiteral->TokenText.startswith(R"($@")")))
536     return;
537 
538   const char *StrBegin =
539       Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size();
540   const char *Offset = StrBegin;
541   if (CSharpStringLiteral->TokenText.startswith(R"(@")"))
542     Offset += 2;
543   else // CSharpStringLiteral->TokenText.startswith(R"($@")")
544     Offset += 3;
545 
546   // Look for a terminating '"' in the current file buffer.
547   // Make no effort to format code within an interpolated or verbatim string.
548   for (; Offset != Lex->getBuffer().end(); ++Offset) {
549     if (Offset[0] == '"') {
550       // "" within a verbatim string is an escaped double quote: skip it.
551       if (Offset + 1 < Lex->getBuffer().end() && Offset[1] == '"')
552         ++Offset;
553       else
554         break;
555     }
556   }
557 
558   // Make no attempt to format code properly if a verbatim string is
559   // unterminated.
560   if (Offset == Lex->getBuffer().end())
561     return;
562 
563   StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
564   CSharpStringLiteral->TokenText = LiteralText;
565 
566   // Adjust width for potentially multiline string literals.
567   size_t FirstBreak = LiteralText.find('\n');
568   StringRef FirstLineText = FirstBreak == StringRef::npos
569                                 ? LiteralText
570                                 : LiteralText.substr(0, FirstBreak);
571   CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
572       FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
573       Encoding);
574   size_t LastBreak = LiteralText.rfind('\n');
575   if (LastBreak != StringRef::npos) {
576     CSharpStringLiteral->IsMultiline = true;
577     unsigned StartColumn = 0; // The template tail spans the entire line.
578     CSharpStringLiteral->LastLineColumnWidth = encoding::columnWidthWithTabs(
579         LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
580         Style.TabWidth, Encoding);
581   }
582 
583   SourceLocation loc = Offset < Lex->getBuffer().end()
584                            ? Lex->getSourceLocation(Offset + 1)
585                            : SourceMgr.getLocForEndOfFile(ID);
586   resetLexer(SourceMgr.getFileOffset(loc));
587 }
588 
589 void FormatTokenLexer::handleTemplateStrings() {
590   FormatToken *BacktickToken = Tokens.back();
591 
592   if (BacktickToken->is(tok::l_brace)) {
593     StateStack.push(LexerState::NORMAL);
594     return;
595   }
596   if (BacktickToken->is(tok::r_brace)) {
597     if (StateStack.size() == 1)
598       return;
599     StateStack.pop();
600     if (StateStack.top() != LexerState::TEMPLATE_STRING)
601       return;
602     // If back in TEMPLATE_STRING, fallthrough and continue parsing the
603   } else if (BacktickToken->is(tok::unknown) &&
604              BacktickToken->TokenText == "`") {
605     StateStack.push(LexerState::TEMPLATE_STRING);
606   } else {
607     return; // Not actually a template
608   }
609 
610   // 'Manually' lex ahead in the current file buffer.
611   const char *Offset = Lex->getBufferLocation();
612   const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
613   for (; Offset != Lex->getBuffer().end(); ++Offset) {
614     if (Offset[0] == '`') {
615       StateStack.pop();
616       break;
617     }
618     if (Offset[0] == '\\') {
619       ++Offset; // Skip the escaped character.
620     } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
621                Offset[1] == '{') {
622       // '${' introduces an expression interpolation in the template string.
623       StateStack.push(LexerState::NORMAL);
624       ++Offset;
625       break;
626     }
627   }
628 
629   StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
630   BacktickToken->Type = TT_TemplateString;
631   BacktickToken->Tok.setKind(tok::string_literal);
632   BacktickToken->TokenText = LiteralText;
633 
634   // Adjust width for potentially multiline string literals.
635   size_t FirstBreak = LiteralText.find('\n');
636   StringRef FirstLineText = FirstBreak == StringRef::npos
637                                 ? LiteralText
638                                 : LiteralText.substr(0, FirstBreak);
639   BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
640       FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
641   size_t LastBreak = LiteralText.rfind('\n');
642   if (LastBreak != StringRef::npos) {
643     BacktickToken->IsMultiline = true;
644     unsigned StartColumn = 0; // The template tail spans the entire line.
645     BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
646         LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
647         Style.TabWidth, Encoding);
648   }
649 
650   SourceLocation loc = Offset < Lex->getBuffer().end()
651                            ? Lex->getSourceLocation(Offset + 1)
652                            : SourceMgr.getLocForEndOfFile(ID);
653   resetLexer(SourceMgr.getFileOffset(loc));
654 }
655 
656 void FormatTokenLexer::tryParsePythonComment() {
657   FormatToken *HashToken = Tokens.back();
658   if (!HashToken->isOneOf(tok::hash, tok::hashhash))
659     return;
660   // Turn the remainder of this line into a comment.
661   const char *CommentBegin =
662       Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
663   size_t From = CommentBegin - Lex->getBuffer().begin();
664   size_t To = Lex->getBuffer().find_first_of('\n', From);
665   if (To == StringRef::npos)
666     To = Lex->getBuffer().size();
667   size_t Len = To - From;
668   HashToken->Type = TT_LineComment;
669   HashToken->Tok.setKind(tok::comment);
670   HashToken->TokenText = Lex->getBuffer().substr(From, Len);
671   SourceLocation Loc = To < Lex->getBuffer().size()
672                            ? Lex->getSourceLocation(CommentBegin + Len)
673                            : SourceMgr.getLocForEndOfFile(ID);
674   resetLexer(SourceMgr.getFileOffset(Loc));
675 }
676 
677 bool FormatTokenLexer::tryMerge_TMacro() {
678   if (Tokens.size() < 4)
679     return false;
680   FormatToken *Last = Tokens.back();
681   if (!Last->is(tok::r_paren))
682     return false;
683 
684   FormatToken *String = Tokens[Tokens.size() - 2];
685   if (!String->is(tok::string_literal) || String->IsMultiline)
686     return false;
687 
688   if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
689     return false;
690 
691   FormatToken *Macro = Tokens[Tokens.size() - 4];
692   if (Macro->TokenText != "_T")
693     return false;
694 
695   const char *Start = Macro->TokenText.data();
696   const char *End = Last->TokenText.data() + Last->TokenText.size();
697   String->TokenText = StringRef(Start, End - Start);
698   String->IsFirst = Macro->IsFirst;
699   String->LastNewlineOffset = Macro->LastNewlineOffset;
700   String->WhitespaceRange = Macro->WhitespaceRange;
701   String->OriginalColumn = Macro->OriginalColumn;
702   String->ColumnWidth = encoding::columnWidthWithTabs(
703       String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
704   String->NewlinesBefore = Macro->NewlinesBefore;
705   String->HasUnescapedNewline = Macro->HasUnescapedNewline;
706 
707   Tokens.pop_back();
708   Tokens.pop_back();
709   Tokens.pop_back();
710   Tokens.back() = String;
711   return true;
712 }
713 
714 bool FormatTokenLexer::tryMergeConflictMarkers() {
715   if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
716     return false;
717 
718   // Conflict lines look like:
719   // <marker> <text from the vcs>
720   // For example:
721   // >>>>>>> /file/in/file/system at revision 1234
722   //
723   // We merge all tokens in a line that starts with a conflict marker
724   // into a single token with a special token type that the unwrapped line
725   // parser will use to correctly rebuild the underlying code.
726 
727   FileID ID;
728   // Get the position of the first token in the line.
729   unsigned FirstInLineOffset;
730   std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
731       Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
732   StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
733   // Calculate the offset of the start of the current line.
734   auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
735   if (LineOffset == StringRef::npos) {
736     LineOffset = 0;
737   } else {
738     ++LineOffset;
739   }
740 
741   auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
742   StringRef LineStart;
743   if (FirstSpace == StringRef::npos) {
744     LineStart = Buffer.substr(LineOffset);
745   } else {
746     LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
747   }
748 
749   TokenType Type = TT_Unknown;
750   if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
751     Type = TT_ConflictStart;
752   } else if (LineStart == "|||||||" || LineStart == "=======" ||
753              LineStart == "====") {
754     Type = TT_ConflictAlternative;
755   } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
756     Type = TT_ConflictEnd;
757   }
758 
759   if (Type != TT_Unknown) {
760     FormatToken *Next = Tokens.back();
761 
762     Tokens.resize(FirstInLineIndex + 1);
763     // We do not need to build a complete token here, as we will skip it
764     // during parsing anyway (as we must not touch whitespace around conflict
765     // markers).
766     Tokens.back()->Type = Type;
767     Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
768 
769     Tokens.push_back(Next);
770     return true;
771   }
772 
773   return false;
774 }
775 
776 FormatToken *FormatTokenLexer::getStashedToken() {
777   // Create a synthesized second '>' or '<' token.
778   Token Tok = FormatTok->Tok;
779   StringRef TokenText = FormatTok->TokenText;
780 
781   unsigned OriginalColumn = FormatTok->OriginalColumn;
782   FormatTok = new (Allocator.Allocate()) FormatToken;
783   FormatTok->Tok = Tok;
784   SourceLocation TokLocation =
785       FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
786   FormatTok->Tok.setLocation(TokLocation);
787   FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
788   FormatTok->TokenText = TokenText;
789   FormatTok->ColumnWidth = 1;
790   FormatTok->OriginalColumn = OriginalColumn + 1;
791 
792   return FormatTok;
793 }
794 
795 FormatToken *FormatTokenLexer::getNextToken() {
796   if (StateStack.top() == LexerState::TOKEN_STASHED) {
797     StateStack.pop();
798     return getStashedToken();
799   }
800 
801   FormatTok = new (Allocator.Allocate()) FormatToken;
802   readRawToken(*FormatTok);
803   SourceLocation WhitespaceStart =
804       FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
805   FormatTok->IsFirst = IsFirstToken;
806   IsFirstToken = false;
807 
808   // Consume and record whitespace until we find a significant token.
809   unsigned WhitespaceLength = TrailingWhitespace;
810   while (FormatTok->Tok.is(tok::unknown)) {
811     StringRef Text = FormatTok->TokenText;
812     auto EscapesNewline = [&](int pos) {
813       // A '\r' here is just part of '\r\n'. Skip it.
814       if (pos >= 0 && Text[pos] == '\r')
815         --pos;
816       // See whether there is an odd number of '\' before this.
817       // FIXME: This is wrong. A '\' followed by a newline is always removed,
818       // regardless of whether there is another '\' before it.
819       // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
820       unsigned count = 0;
821       for (; pos >= 0; --pos, ++count)
822         if (Text[pos] != '\\')
823           break;
824       return count & 1;
825     };
826     // FIXME: This miscounts tok:unknown tokens that are not just
827     // whitespace, e.g. a '`' character.
828     for (int i = 0, e = Text.size(); i != e; ++i) {
829       switch (Text[i]) {
830       case '\n':
831         ++FormatTok->NewlinesBefore;
832         FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
833         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
834         Column = 0;
835         break;
836       case '\r':
837         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
838         Column = 0;
839         break;
840       case '\f':
841       case '\v':
842         Column = 0;
843         break;
844       case ' ':
845         ++Column;
846         break;
847       case '\t':
848         Column +=
849             Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
850         break;
851       case '\\':
852         if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
853           FormatTok->Type = TT_ImplicitStringLiteral;
854         break;
855       default:
856         FormatTok->Type = TT_ImplicitStringLiteral;
857         break;
858       }
859       if (FormatTok->Type == TT_ImplicitStringLiteral)
860         break;
861     }
862 
863     if (FormatTok->is(TT_ImplicitStringLiteral))
864       break;
865     WhitespaceLength += FormatTok->Tok.getLength();
866 
867     readRawToken(*FormatTok);
868   }
869 
870   // JavaScript and Java do not allow to escape the end of the line with a
871   // backslash. Backslashes are syntax errors in plain source, but can occur in
872   // comments. When a single line comment ends with a \, it'll cause the next
873   // line of code to be lexed as a comment, breaking formatting. The code below
874   // finds comments that contain a backslash followed by a line break, truncates
875   // the comment token at the backslash, and resets the lexer to restart behind
876   // the backslash.
877   if ((Style.Language == FormatStyle::LK_JavaScript ||
878        Style.Language == FormatStyle::LK_Java) &&
879       FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
880     size_t BackslashPos = FormatTok->TokenText.find('\\');
881     while (BackslashPos != StringRef::npos) {
882       if (BackslashPos + 1 < FormatTok->TokenText.size() &&
883           FormatTok->TokenText[BackslashPos + 1] == '\n') {
884         const char *Offset = Lex->getBufferLocation();
885         Offset -= FormatTok->TokenText.size();
886         Offset += BackslashPos + 1;
887         resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
888         FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
889         FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
890             FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
891             Encoding);
892         break;
893       }
894       BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
895     }
896   }
897 
898   // In case the token starts with escaped newlines, we want to
899   // take them into account as whitespace - this pattern is quite frequent
900   // in macro definitions.
901   // FIXME: Add a more explicit test.
902   while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
903     unsigned SkippedWhitespace = 0;
904     if (FormatTok->TokenText.size() > 2 &&
905         (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
906       SkippedWhitespace = 3;
907     else if (FormatTok->TokenText[1] == '\n')
908       SkippedWhitespace = 2;
909     else
910       break;
911 
912     ++FormatTok->NewlinesBefore;
913     WhitespaceLength += SkippedWhitespace;
914     FormatTok->LastNewlineOffset = SkippedWhitespace;
915     Column = 0;
916     FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
917   }
918 
919   FormatTok->WhitespaceRange = SourceRange(
920       WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
921 
922   FormatTok->OriginalColumn = Column;
923 
924   TrailingWhitespace = 0;
925   if (FormatTok->Tok.is(tok::comment)) {
926     // FIXME: Add the trimmed whitespace to Column.
927     StringRef UntrimmedText = FormatTok->TokenText;
928     FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
929     TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
930   } else if (FormatTok->Tok.is(tok::raw_identifier)) {
931     IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
932     FormatTok->Tok.setIdentifierInfo(&Info);
933     FormatTok->Tok.setKind(Info.getTokenID());
934     if (Style.Language == FormatStyle::LK_Java &&
935         FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
936                            tok::kw_operator)) {
937       FormatTok->Tok.setKind(tok::identifier);
938       FormatTok->Tok.setIdentifierInfo(nullptr);
939     } else if (Style.Language == FormatStyle::LK_JavaScript &&
940                FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
941                                   tok::kw_operator)) {
942       FormatTok->Tok.setKind(tok::identifier);
943       FormatTok->Tok.setIdentifierInfo(nullptr);
944     }
945   } else if (FormatTok->Tok.is(tok::greatergreater)) {
946     FormatTok->Tok.setKind(tok::greater);
947     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
948     ++Column;
949     StateStack.push(LexerState::TOKEN_STASHED);
950   } else if (FormatTok->Tok.is(tok::lessless)) {
951     FormatTok->Tok.setKind(tok::less);
952     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
953     ++Column;
954     StateStack.push(LexerState::TOKEN_STASHED);
955   }
956 
957   // Now FormatTok is the next non-whitespace token.
958 
959   StringRef Text = FormatTok->TokenText;
960   size_t FirstNewlinePos = Text.find('\n');
961   if (FirstNewlinePos == StringRef::npos) {
962     // FIXME: ColumnWidth actually depends on the start column, we need to
963     // take this into account when the token is moved.
964     FormatTok->ColumnWidth =
965         encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
966     Column += FormatTok->ColumnWidth;
967   } else {
968     FormatTok->IsMultiline = true;
969     // FIXME: ColumnWidth actually depends on the start column, we need to
970     // take this into account when the token is moved.
971     FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
972         Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
973 
974     // The last line of the token always starts in column 0.
975     // Thus, the length can be precomputed even in the presence of tabs.
976     FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
977         Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
978     Column = FormatTok->LastLineColumnWidth;
979   }
980 
981   if (Style.isCpp()) {
982     auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
983     if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
984           Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
985               tok::pp_define) &&
986         it != Macros.end()) {
987       FormatTok->Type = it->second;
988     } else if (FormatTok->is(tok::identifier)) {
989       if (MacroBlockBeginRegex.match(Text)) {
990         FormatTok->Type = TT_MacroBlockBegin;
991       } else if (MacroBlockEndRegex.match(Text)) {
992         FormatTok->Type = TT_MacroBlockEnd;
993       }
994     }
995   }
996 
997   return FormatTok;
998 }
999 
1000 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
1001   Lex->LexFromRawLexer(Tok.Tok);
1002   Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1003                             Tok.Tok.getLength());
1004   // For formatting, treat unterminated string literals like normal string
1005   // literals.
1006   if (Tok.is(tok::unknown)) {
1007     if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1008       Tok.Tok.setKind(tok::string_literal);
1009       Tok.IsUnterminatedLiteral = true;
1010     } else if (Style.Language == FormatStyle::LK_JavaScript &&
1011                Tok.TokenText == "''") {
1012       Tok.Tok.setKind(tok::string_literal);
1013     }
1014   }
1015 
1016   if ((Style.Language == FormatStyle::LK_JavaScript ||
1017        Style.Language == FormatStyle::LK_Proto ||
1018        Style.Language == FormatStyle::LK_TextProto) &&
1019       Tok.is(tok::char_constant)) {
1020     Tok.Tok.setKind(tok::string_literal);
1021   }
1022 
1023   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1024                                Tok.TokenText == "/* clang-format on */")) {
1025     FormattingDisabled = false;
1026   }
1027 
1028   Tok.Finalized = FormattingDisabled;
1029 
1030   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1031                                Tok.TokenText == "/* clang-format off */")) {
1032     FormattingDisabled = true;
1033   }
1034 }
1035 
1036 void FormatTokenLexer::resetLexer(unsigned Offset) {
1037   StringRef Buffer = SourceMgr.getBufferData(ID);
1038   Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
1039                       getFormattingLangOpts(Style), Buffer.begin(),
1040                       Buffer.begin() + Offset, Buffer.end()));
1041   Lex->SetKeepWhitespaceMode(true);
1042   TrailingWhitespace = 0;
1043 }
1044 
1045 } // namespace format
1046 } // namespace clang
1047