1 //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements FormatTokenLexer, which tokenizes a source file
12 /// into a FormatToken stream suitable for ClangFormat.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "FormatTokenLexer.h"
17 #include "FormatToken.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Format/Format.h"
21 #include "llvm/Support/Regex.h"
22 
23 namespace clang {
24 namespace format {
25 
26 FormatTokenLexer::FormatTokenLexer(const SourceManager &SourceMgr, FileID ID,
27                                    unsigned Column, const FormatStyle &Style,
28                                    encoding::Encoding Encoding)
29     : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
30       Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
31       Style(Style), IdentTable(getFormattingLangOpts(Style)),
32       Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
33       FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
34       MacroBlockEndRegex(Style.MacroBlockEnd) {
35   Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
36                       getFormattingLangOpts(Style)));
37   Lex->SetKeepWhitespaceMode(true);
38 
39   for (const std::string &ForEachMacro : Style.ForEachMacros)
40     ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
41   std::sort(ForEachMacros.begin(), ForEachMacros.end());
42 }
43 
44 ArrayRef<FormatToken *> FormatTokenLexer::lex() {
45   assert(Tokens.empty());
46   assert(FirstInLineIndex == 0);
47   do {
48     Tokens.push_back(getNextToken());
49     if (Style.Language == FormatStyle::LK_JavaScript) {
50       tryParseJSRegexLiteral();
51       handleTemplateStrings();
52     }
53     tryMergePreviousTokens();
54     if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
55       FirstInLineIndex = Tokens.size() - 1;
56   } while (Tokens.back()->Tok.isNot(tok::eof));
57   return Tokens;
58 }
59 
60 void FormatTokenLexer::tryMergePreviousTokens() {
61   if (tryMerge_TMacro())
62     return;
63   if (tryMergeConflictMarkers())
64     return;
65   if (tryMergeLessLess())
66     return;
67   if (tryMergeNSStringLiteral())
68     return;
69 
70   if (Style.Language == FormatStyle::LK_JavaScript) {
71     static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
72     static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
73                                                    tok::equal};
74     static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
75                                                   tok::greaterequal};
76     static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
77     static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
78     static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
79                                                            tok::starequal};
80 
81     // FIXME: Investigate what token type gives the correct operator priority.
82     if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
83       return;
84     if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
85       return;
86     if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
87       return;
88     if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
89       return;
90     if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
91       return;
92     if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
93       Tokens.back()->Tok.setKind(tok::starequal);
94       return;
95     }
96   }
97 
98   if (Style.Language == FormatStyle::LK_Java) {
99     static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
100         tok::greater, tok::greater, tok::greaterequal};
101     if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
102       return;
103   }
104 }
105 
106 bool FormatTokenLexer::tryMergeNSStringLiteral() {
107   if (Tokens.size() < 2)
108     return false;
109   auto &At = *(Tokens.end() - 2);
110   auto &String = *(Tokens.end() - 1);
111   if (!At->is(tok::at) || !String->is(tok::string_literal))
112     return false;
113   At->Tok.setKind(tok::string_literal);
114   At->TokenText = StringRef(At->TokenText.begin(),
115                             String->TokenText.end() - At->TokenText.begin());
116   At->ColumnWidth += String->ColumnWidth;
117   At->Type = TT_ObjCStringLiteral;
118   Tokens.erase(Tokens.end() - 1);
119   return true;
120 }
121 
122 bool FormatTokenLexer::tryMergeLessLess() {
123   // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
124   if (Tokens.size() < 3)
125     return false;
126 
127   bool FourthTokenIsLess = false;
128   if (Tokens.size() > 3)
129     FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
130 
131   auto First = Tokens.end() - 3;
132   if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
133       First[0]->isNot(tok::less) || FourthTokenIsLess)
134     return false;
135 
136   // Only merge if there currently is no whitespace between the two "<".
137   if (First[1]->WhitespaceRange.getBegin() !=
138       First[1]->WhitespaceRange.getEnd())
139     return false;
140 
141   First[0]->Tok.setKind(tok::lessless);
142   First[0]->TokenText = "<<";
143   First[0]->ColumnWidth += 1;
144   Tokens.erase(Tokens.end() - 2);
145   return true;
146 }
147 
148 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
149                                       TokenType NewType) {
150   if (Tokens.size() < Kinds.size())
151     return false;
152 
153   SmallVectorImpl<FormatToken *>::const_iterator First =
154       Tokens.end() - Kinds.size();
155   if (!First[0]->is(Kinds[0]))
156     return false;
157   unsigned AddLength = 0;
158   for (unsigned i = 1; i < Kinds.size(); ++i) {
159     if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
160                                        First[i]->WhitespaceRange.getEnd())
161       return false;
162     AddLength += First[i]->TokenText.size();
163   }
164   Tokens.resize(Tokens.size() - Kinds.size() + 1);
165   First[0]->TokenText = StringRef(First[0]->TokenText.data(),
166                                   First[0]->TokenText.size() + AddLength);
167   First[0]->ColumnWidth += AddLength;
168   First[0]->Type = NewType;
169   return true;
170 }
171 
172 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
173 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
174   // NB: This is not entirely correct, as an r_paren can introduce an operand
175   // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
176   // corner case to not matter in practice, though.
177   return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
178                       tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
179                       tok::colon, tok::question, tok::tilde) ||
180          Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
181                       tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
182                       tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
183          Tok->isBinaryOperator();
184 }
185 
186 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
187   if (!Prev)
188     return true;
189 
190   // Regex literals can only follow after prefix unary operators, not after
191   // postfix unary operators. If the '++' is followed by a non-operand
192   // introducing token, the slash here is the operand and not the start of a
193   // regex.
194   // `!` is an unary prefix operator, but also a post-fix operator that casts
195   // away nullability, so the same check applies.
196   if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
197     return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
198 
199   // The previous token must introduce an operand location where regex
200   // literals can occur.
201   if (!precedesOperand(Prev))
202     return false;
203 
204   return true;
205 }
206 
207 // Tries to parse a JavaScript Regex literal starting at the current token,
208 // if that begins with a slash and is in a location where JavaScript allows
209 // regex literals. Changes the current token to a regex literal and updates
210 // its text if successful.
211 void FormatTokenLexer::tryParseJSRegexLiteral() {
212   FormatToken *RegexToken = Tokens.back();
213   if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
214     return;
215 
216   FormatToken *Prev = nullptr;
217   for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
218     // NB: Because previous pointers are not initialized yet, this cannot use
219     // Token.getPreviousNonComment.
220     if ((*I)->isNot(tok::comment)) {
221       Prev = *I;
222       break;
223     }
224   }
225 
226   if (!canPrecedeRegexLiteral(Prev))
227     return;
228 
229   // 'Manually' lex ahead in the current file buffer.
230   const char *Offset = Lex->getBufferLocation();
231   const char *RegexBegin = Offset - RegexToken->TokenText.size();
232   StringRef Buffer = Lex->getBuffer();
233   bool InCharacterClass = false;
234   bool HaveClosingSlash = false;
235   for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
236     // Regular expressions are terminated with a '/', which can only be
237     // escaped using '\' or a character class between '[' and ']'.
238     // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
239     switch (*Offset) {
240     case '\\':
241       // Skip the escaped character.
242       ++Offset;
243       break;
244     case '[':
245       InCharacterClass = true;
246       break;
247     case ']':
248       InCharacterClass = false;
249       break;
250     case '/':
251       if (!InCharacterClass)
252         HaveClosingSlash = true;
253       break;
254     }
255   }
256 
257   RegexToken->Type = TT_RegexLiteral;
258   // Treat regex literals like other string_literals.
259   RegexToken->Tok.setKind(tok::string_literal);
260   RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
261   RegexToken->ColumnWidth = RegexToken->TokenText.size();
262 
263   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
264 }
265 
266 void FormatTokenLexer::handleTemplateStrings() {
267   FormatToken *BacktickToken = Tokens.back();
268 
269   if (BacktickToken->is(tok::l_brace)) {
270     StateStack.push(LexerState::NORMAL);
271     return;
272   }
273   if (BacktickToken->is(tok::r_brace)) {
274     if (StateStack.size() == 1)
275       return;
276     StateStack.pop();
277     if (StateStack.top() != LexerState::TEMPLATE_STRING)
278       return;
279     // If back in TEMPLATE_STRING, fallthrough and continue parsing the
280   } else if (BacktickToken->is(tok::unknown) &&
281              BacktickToken->TokenText == "`") {
282     StateStack.push(LexerState::TEMPLATE_STRING);
283   } else {
284     return; // Not actually a template
285   }
286 
287   // 'Manually' lex ahead in the current file buffer.
288   const char *Offset = Lex->getBufferLocation();
289   const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
290   for (; Offset != Lex->getBuffer().end(); ++Offset) {
291     if (Offset[0] == '`') {
292       StateStack.pop();
293       break;
294     }
295     if (Offset[0] == '\\') {
296       ++Offset; // Skip the escaped character.
297     } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
298                Offset[1] == '{') {
299       // '${' introduces an expression interpolation in the template string.
300       StateStack.push(LexerState::NORMAL);
301       ++Offset;
302       break;
303     }
304   }
305 
306   StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
307   BacktickToken->Type = TT_TemplateString;
308   BacktickToken->Tok.setKind(tok::string_literal);
309   BacktickToken->TokenText = LiteralText;
310 
311   // Adjust width for potentially multiline string literals.
312   size_t FirstBreak = LiteralText.find('\n');
313   StringRef FirstLineText = FirstBreak == StringRef::npos
314                                 ? LiteralText
315                                 : LiteralText.substr(0, FirstBreak);
316   BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
317       FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
318   size_t LastBreak = LiteralText.rfind('\n');
319   if (LastBreak != StringRef::npos) {
320     BacktickToken->IsMultiline = true;
321     unsigned StartColumn = 0; // The template tail spans the entire line.
322     BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
323         LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
324         Style.TabWidth, Encoding);
325   }
326 
327   SourceLocation loc = Offset < Lex->getBuffer().end()
328                            ? Lex->getSourceLocation(Offset + 1)
329                            : SourceMgr.getLocForEndOfFile(ID);
330   resetLexer(SourceMgr.getFileOffset(loc));
331 }
332 
333 bool FormatTokenLexer::tryMerge_TMacro() {
334   if (Tokens.size() < 4)
335     return false;
336   FormatToken *Last = Tokens.back();
337   if (!Last->is(tok::r_paren))
338     return false;
339 
340   FormatToken *String = Tokens[Tokens.size() - 2];
341   if (!String->is(tok::string_literal) || String->IsMultiline)
342     return false;
343 
344   if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
345     return false;
346 
347   FormatToken *Macro = Tokens[Tokens.size() - 4];
348   if (Macro->TokenText != "_T")
349     return false;
350 
351   const char *Start = Macro->TokenText.data();
352   const char *End = Last->TokenText.data() + Last->TokenText.size();
353   String->TokenText = StringRef(Start, End - Start);
354   String->IsFirst = Macro->IsFirst;
355   String->LastNewlineOffset = Macro->LastNewlineOffset;
356   String->WhitespaceRange = Macro->WhitespaceRange;
357   String->OriginalColumn = Macro->OriginalColumn;
358   String->ColumnWidth = encoding::columnWidthWithTabs(
359       String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
360   String->NewlinesBefore = Macro->NewlinesBefore;
361   String->HasUnescapedNewline = Macro->HasUnescapedNewline;
362 
363   Tokens.pop_back();
364   Tokens.pop_back();
365   Tokens.pop_back();
366   Tokens.back() = String;
367   return true;
368 }
369 
370 bool FormatTokenLexer::tryMergeConflictMarkers() {
371   if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
372     return false;
373 
374   // Conflict lines look like:
375   // <marker> <text from the vcs>
376   // For example:
377   // >>>>>>> /file/in/file/system at revision 1234
378   //
379   // We merge all tokens in a line that starts with a conflict marker
380   // into a single token with a special token type that the unwrapped line
381   // parser will use to correctly rebuild the underlying code.
382 
383   FileID ID;
384   // Get the position of the first token in the line.
385   unsigned FirstInLineOffset;
386   std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
387       Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
388   StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
389   // Calculate the offset of the start of the current line.
390   auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
391   if (LineOffset == StringRef::npos) {
392     LineOffset = 0;
393   } else {
394     ++LineOffset;
395   }
396 
397   auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
398   StringRef LineStart;
399   if (FirstSpace == StringRef::npos) {
400     LineStart = Buffer.substr(LineOffset);
401   } else {
402     LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
403   }
404 
405   TokenType Type = TT_Unknown;
406   if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
407     Type = TT_ConflictStart;
408   } else if (LineStart == "|||||||" || LineStart == "=======" ||
409              LineStart == "====") {
410     Type = TT_ConflictAlternative;
411   } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
412     Type = TT_ConflictEnd;
413   }
414 
415   if (Type != TT_Unknown) {
416     FormatToken *Next = Tokens.back();
417 
418     Tokens.resize(FirstInLineIndex + 1);
419     // We do not need to build a complete token here, as we will skip it
420     // during parsing anyway (as we must not touch whitespace around conflict
421     // markers).
422     Tokens.back()->Type = Type;
423     Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
424 
425     Tokens.push_back(Next);
426     return true;
427   }
428 
429   return false;
430 }
431 
432 FormatToken *FormatTokenLexer::getStashedToken() {
433   // Create a synthesized second '>' or '<' token.
434   Token Tok = FormatTok->Tok;
435   StringRef TokenText = FormatTok->TokenText;
436 
437   unsigned OriginalColumn = FormatTok->OriginalColumn;
438   FormatTok = new (Allocator.Allocate()) FormatToken;
439   FormatTok->Tok = Tok;
440   SourceLocation TokLocation =
441       FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
442   FormatTok->Tok.setLocation(TokLocation);
443   FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
444   FormatTok->TokenText = TokenText;
445   FormatTok->ColumnWidth = 1;
446   FormatTok->OriginalColumn = OriginalColumn + 1;
447 
448   return FormatTok;
449 }
450 
451 FormatToken *FormatTokenLexer::getNextToken() {
452   if (StateStack.top() == LexerState::TOKEN_STASHED) {
453     StateStack.pop();
454     return getStashedToken();
455   }
456 
457   FormatTok = new (Allocator.Allocate()) FormatToken;
458   readRawToken(*FormatTok);
459   SourceLocation WhitespaceStart =
460       FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
461   FormatTok->IsFirst = IsFirstToken;
462   IsFirstToken = false;
463 
464   // Consume and record whitespace until we find a significant token.
465   unsigned WhitespaceLength = TrailingWhitespace;
466   while (FormatTok->Tok.is(tok::unknown)) {
467     StringRef Text = FormatTok->TokenText;
468     auto EscapesNewline = [&](int pos) {
469       // A '\r' here is just part of '\r\n'. Skip it.
470       if (pos >= 0 && Text[pos] == '\r')
471         --pos;
472       // See whether there is an odd number of '\' before this.
473       // FIXME: This is wrong. A '\' followed by a newline is always removed,
474       // regardless of whether there is another '\' before it.
475       // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
476       unsigned count = 0;
477       for (; pos >= 0; --pos, ++count)
478         if (Text[pos] != '\\')
479           break;
480       return count & 1;
481     };
482     // FIXME: This miscounts tok:unknown tokens that are not just
483     // whitespace, e.g. a '`' character.
484     for (int i = 0, e = Text.size(); i != e; ++i) {
485       switch (Text[i]) {
486       case '\n':
487         ++FormatTok->NewlinesBefore;
488         FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
489         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
490         Column = 0;
491         break;
492       case '\r':
493         FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
494         Column = 0;
495         break;
496       case '\f':
497       case '\v':
498         Column = 0;
499         break;
500       case ' ':
501         ++Column;
502         break;
503       case '\t':
504         Column += Style.TabWidth - Column % Style.TabWidth;
505         break;
506       case '\\':
507         if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
508           FormatTok->Type = TT_ImplicitStringLiteral;
509         break;
510       default:
511         FormatTok->Type = TT_ImplicitStringLiteral;
512         break;
513       }
514       if (FormatTok->Type == TT_ImplicitStringLiteral)
515         break;
516     }
517 
518     if (FormatTok->is(TT_ImplicitStringLiteral))
519       break;
520     WhitespaceLength += FormatTok->Tok.getLength();
521 
522     readRawToken(*FormatTok);
523   }
524 
525   // JavaScript and Java do not allow to escape the end of the line with a
526   // backslash. Backslashes are syntax errors in plain source, but can occur in
527   // comments. When a single line comment ends with a \, it'll cause the next
528   // line of code to be lexed as a comment, breaking formatting. The code below
529   // finds comments that contain a backslash followed by a line break, truncates
530   // the comment token at the backslash, and resets the lexer to restart behind
531   // the backslash.
532   if ((Style.Language == FormatStyle::LK_JavaScript ||
533        Style.Language == FormatStyle::LK_Java) &&
534       FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
535     size_t BackslashPos = FormatTok->TokenText.find('\\');
536     while (BackslashPos != StringRef::npos) {
537       if (BackslashPos + 1 < FormatTok->TokenText.size() &&
538           FormatTok->TokenText[BackslashPos + 1] == '\n') {
539         const char *Offset = Lex->getBufferLocation();
540         Offset -= FormatTok->TokenText.size();
541         Offset += BackslashPos + 1;
542         resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
543         FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
544         FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
545             FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
546             Encoding);
547         break;
548       }
549       BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
550     }
551   }
552 
553   // In case the token starts with escaped newlines, we want to
554   // take them into account as whitespace - this pattern is quite frequent
555   // in macro definitions.
556   // FIXME: Add a more explicit test.
557   while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
558     unsigned SkippedWhitespace = 0;
559     if (FormatTok->TokenText.size() > 2 &&
560         (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
561       SkippedWhitespace = 3;
562     else if (FormatTok->TokenText[1] == '\n')
563       SkippedWhitespace = 2;
564     else
565       break;
566 
567     ++FormatTok->NewlinesBefore;
568     WhitespaceLength += SkippedWhitespace;
569     FormatTok->LastNewlineOffset = SkippedWhitespace;
570     Column = 0;
571     FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
572   }
573 
574   FormatTok->WhitespaceRange = SourceRange(
575       WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
576 
577   FormatTok->OriginalColumn = Column;
578 
579   TrailingWhitespace = 0;
580   if (FormatTok->Tok.is(tok::comment)) {
581     // FIXME: Add the trimmed whitespace to Column.
582     StringRef UntrimmedText = FormatTok->TokenText;
583     FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
584     TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
585   } else if (FormatTok->Tok.is(tok::raw_identifier)) {
586     IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
587     FormatTok->Tok.setIdentifierInfo(&Info);
588     FormatTok->Tok.setKind(Info.getTokenID());
589     if (Style.Language == FormatStyle::LK_Java &&
590         FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
591                            tok::kw_operator)) {
592       FormatTok->Tok.setKind(tok::identifier);
593       FormatTok->Tok.setIdentifierInfo(nullptr);
594     } else if (Style.Language == FormatStyle::LK_JavaScript &&
595                FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
596                                   tok::kw_operator)) {
597       FormatTok->Tok.setKind(tok::identifier);
598       FormatTok->Tok.setIdentifierInfo(nullptr);
599     }
600   } else if (FormatTok->Tok.is(tok::greatergreater)) {
601     FormatTok->Tok.setKind(tok::greater);
602     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
603     ++Column;
604     StateStack.push(LexerState::TOKEN_STASHED);
605   } else if (FormatTok->Tok.is(tok::lessless)) {
606     FormatTok->Tok.setKind(tok::less);
607     FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
608     ++Column;
609     StateStack.push(LexerState::TOKEN_STASHED);
610   }
611 
612   // Now FormatTok is the next non-whitespace token.
613 
614   StringRef Text = FormatTok->TokenText;
615   size_t FirstNewlinePos = Text.find('\n');
616   if (FirstNewlinePos == StringRef::npos) {
617     // FIXME: ColumnWidth actually depends on the start column, we need to
618     // take this into account when the token is moved.
619     FormatTok->ColumnWidth =
620         encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
621     Column += FormatTok->ColumnWidth;
622   } else {
623     FormatTok->IsMultiline = true;
624     // FIXME: ColumnWidth actually depends on the start column, we need to
625     // take this into account when the token is moved.
626     FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
627         Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
628 
629     // The last line of the token always starts in column 0.
630     // Thus, the length can be precomputed even in the presence of tabs.
631     FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
632         Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
633     Column = FormatTok->LastLineColumnWidth;
634   }
635 
636   if (Style.isCpp()) {
637     if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
638           Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
639               tok::pp_define) &&
640         std::find(ForEachMacros.begin(), ForEachMacros.end(),
641                   FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
642       FormatTok->Type = TT_ForEachMacro;
643     } else if (FormatTok->is(tok::identifier)) {
644       if (MacroBlockBeginRegex.match(Text)) {
645         FormatTok->Type = TT_MacroBlockBegin;
646       } else if (MacroBlockEndRegex.match(Text)) {
647         FormatTok->Type = TT_MacroBlockEnd;
648       }
649     }
650   }
651 
652   return FormatTok;
653 }
654 
655 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
656   Lex->LexFromRawLexer(Tok.Tok);
657   Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
658                             Tok.Tok.getLength());
659   // For formatting, treat unterminated string literals like normal string
660   // literals.
661   if (Tok.is(tok::unknown)) {
662     if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
663       Tok.Tok.setKind(tok::string_literal);
664       Tok.IsUnterminatedLiteral = true;
665     } else if (Style.Language == FormatStyle::LK_JavaScript &&
666                Tok.TokenText == "''") {
667       Tok.Tok.setKind(tok::string_literal);
668     }
669   }
670 
671   if (Style.Language == FormatStyle::LK_JavaScript &&
672       Tok.is(tok::char_constant)) {
673     Tok.Tok.setKind(tok::string_literal);
674   }
675 
676   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
677                                Tok.TokenText == "/* clang-format on */")) {
678     FormattingDisabled = false;
679   }
680 
681   Tok.Finalized = FormattingDisabled;
682 
683   if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
684                                Tok.TokenText == "/* clang-format off */")) {
685     FormattingDisabled = true;
686   }
687 }
688 
689 void FormatTokenLexer::resetLexer(unsigned Offset) {
690   StringRef Buffer = SourceMgr.getBufferData(ID);
691   Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
692                       getFormattingLangOpts(Style), Buffer.begin(),
693                       Buffer.begin() + Offset, Buffer.end()));
694   Lex->SetKeepWhitespaceMode(true);
695   TrailingWhitespace = 0;
696 }
697 
698 } // namespace format
699 } // namespace clang
700