1 //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file implements FormatTokenLexer, which tokenizes a source file
12 /// into a FormatToken stream suitable for ClangFormat.
14 //===----------------------------------------------------------------------===//
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"
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);
39 for (const std::string &ForEachMacro : Style.ForEachMacros)
40 Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro});
41 for (const std::string &StatementMacro : Style.StatementMacros)
42 Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro});
45 ArrayRef<FormatToken *> FormatTokenLexer::lex() {
46 assert(Tokens.empty());
47 assert(FirstInLineIndex == 0);
49 Tokens.push_back(getNextToken());
50 if (Style.Language == FormatStyle::LK_JavaScript) {
51 tryParseJSRegexLiteral();
52 handleTemplateStrings();
54 if (Style.Language == FormatStyle::LK_TextProto)
55 tryParsePythonComment();
56 tryMergePreviousTokens();
57 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
58 FirstInLineIndex = Tokens.size() - 1;
59 } while (Tokens.back()->Tok.isNot(tok::eof));
63 void FormatTokenLexer::tryMergePreviousTokens() {
64 if (tryMerge_TMacro())
66 if (tryMergeConflictMarkers())
68 if (tryMergeLessLess())
70 if (tryMergeNSStringLiteral())
73 if (Style.Language == FormatStyle::LK_JavaScript) {
74 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
75 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
77 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
79 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
80 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
81 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
84 // FIXME: Investigate what token type gives the correct operator priority.
85 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
87 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
89 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
91 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
93 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
95 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
96 Tokens.back()->Tok.setKind(tok::starequal);
101 if (Style.Language == FormatStyle::LK_Java) {
102 static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
103 tok::greater, tok::greater, tok::greaterequal};
104 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
109 bool FormatTokenLexer::tryMergeNSStringLiteral() {
110 if (Tokens.size() < 2)
112 auto &At = *(Tokens.end() - 2);
113 auto &String = *(Tokens.end() - 1);
114 if (!At->is(tok::at) || !String->is(tok::string_literal))
116 At->Tok.setKind(tok::string_literal);
117 At->TokenText = StringRef(At->TokenText.begin(),
118 String->TokenText.end() - At->TokenText.begin());
119 At->ColumnWidth += String->ColumnWidth;
120 At->Type = TT_ObjCStringLiteral;
121 Tokens.erase(Tokens.end() - 1);
125 bool FormatTokenLexer::tryMergeLessLess() {
126 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
127 if (Tokens.size() < 3)
130 bool FourthTokenIsLess = false;
131 if (Tokens.size() > 3)
132 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
134 auto First = Tokens.end() - 3;
135 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
136 First[0]->isNot(tok::less) || FourthTokenIsLess)
139 // Only merge if there currently is no whitespace between the two "<".
140 if (First[1]->WhitespaceRange.getBegin() !=
141 First[1]->WhitespaceRange.getEnd())
144 First[0]->Tok.setKind(tok::lessless);
145 First[0]->TokenText = "<<";
146 First[0]->ColumnWidth += 1;
147 Tokens.erase(Tokens.end() - 2);
151 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
153 if (Tokens.size() < Kinds.size())
156 SmallVectorImpl<FormatToken *>::const_iterator First =
157 Tokens.end() - Kinds.size();
158 if (!First[0]->is(Kinds[0]))
160 unsigned AddLength = 0;
161 for (unsigned i = 1; i < Kinds.size(); ++i) {
162 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
163 First[i]->WhitespaceRange.getEnd())
165 AddLength += First[i]->TokenText.size();
167 Tokens.resize(Tokens.size() - Kinds.size() + 1);
168 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
169 First[0]->TokenText.size() + AddLength);
170 First[0]->ColumnWidth += AddLength;
171 First[0]->Type = NewType;
175 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
176 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
177 // NB: This is not entirely correct, as an r_paren can introduce an operand
178 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
179 // corner case to not matter in practice, though.
180 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
181 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
182 tok::colon, tok::question, tok::tilde) ||
183 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
184 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
185 tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
186 Tok->isBinaryOperator();
189 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
193 // Regex literals can only follow after prefix unary operators, not after
194 // postfix unary operators. If the '++' is followed by a non-operand
195 // introducing token, the slash here is the operand and not the start of a
197 // `!` is an unary prefix operator, but also a post-fix operator that casts
198 // away nullability, so the same check applies.
199 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
200 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
202 // The previous token must introduce an operand location where regex
203 // literals can occur.
204 if (!precedesOperand(Prev))
210 // Tries to parse a JavaScript Regex literal starting at the current token,
211 // if that begins with a slash and is in a location where JavaScript allows
212 // regex literals. Changes the current token to a regex literal and updates
213 // its text if successful.
214 void FormatTokenLexer::tryParseJSRegexLiteral() {
215 FormatToken *RegexToken = Tokens.back();
216 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
219 FormatToken *Prev = nullptr;
220 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
221 // NB: Because previous pointers are not initialized yet, this cannot use
222 // Token.getPreviousNonComment.
223 if ((*I)->isNot(tok::comment)) {
229 if (!canPrecedeRegexLiteral(Prev))
232 // 'Manually' lex ahead in the current file buffer.
233 const char *Offset = Lex->getBufferLocation();
234 const char *RegexBegin = Offset - RegexToken->TokenText.size();
235 StringRef Buffer = Lex->getBuffer();
236 bool InCharacterClass = false;
237 bool HaveClosingSlash = false;
238 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
239 // Regular expressions are terminated with a '/', which can only be
240 // escaped using '\' or a character class between '[' and ']'.
241 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
244 // Skip the escaped character.
248 InCharacterClass = true;
251 InCharacterClass = false;
254 if (!InCharacterClass)
255 HaveClosingSlash = true;
260 RegexToken->Type = TT_RegexLiteral;
261 // Treat regex literals like other string_literals.
262 RegexToken->Tok.setKind(tok::string_literal);
263 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
264 RegexToken->ColumnWidth = RegexToken->TokenText.size();
266 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
269 void FormatTokenLexer::handleTemplateStrings() {
270 FormatToken *BacktickToken = Tokens.back();
272 if (BacktickToken->is(tok::l_brace)) {
273 StateStack.push(LexerState::NORMAL);
276 if (BacktickToken->is(tok::r_brace)) {
277 if (StateStack.size() == 1)
280 if (StateStack.top() != LexerState::TEMPLATE_STRING)
282 // If back in TEMPLATE_STRING, fallthrough and continue parsing the
283 } else if (BacktickToken->is(tok::unknown) &&
284 BacktickToken->TokenText == "`") {
285 StateStack.push(LexerState::TEMPLATE_STRING);
287 return; // Not actually a template
290 // 'Manually' lex ahead in the current file buffer.
291 const char *Offset = Lex->getBufferLocation();
292 const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
293 for (; Offset != Lex->getBuffer().end(); ++Offset) {
294 if (Offset[0] == '`') {
298 if (Offset[0] == '\\') {
299 ++Offset; // Skip the escaped character.
300 } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
302 // '${' introduces an expression interpolation in the template string.
303 StateStack.push(LexerState::NORMAL);
309 StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
310 BacktickToken->Type = TT_TemplateString;
311 BacktickToken->Tok.setKind(tok::string_literal);
312 BacktickToken->TokenText = LiteralText;
314 // Adjust width for potentially multiline string literals.
315 size_t FirstBreak = LiteralText.find('\n');
316 StringRef FirstLineText = FirstBreak == StringRef::npos
318 : LiteralText.substr(0, FirstBreak);
319 BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
320 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
321 size_t LastBreak = LiteralText.rfind('\n');
322 if (LastBreak != StringRef::npos) {
323 BacktickToken->IsMultiline = true;
324 unsigned StartColumn = 0; // The template tail spans the entire line.
325 BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
326 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
327 Style.TabWidth, Encoding);
330 SourceLocation loc = Offset < Lex->getBuffer().end()
331 ? Lex->getSourceLocation(Offset + 1)
332 : SourceMgr.getLocForEndOfFile(ID);
333 resetLexer(SourceMgr.getFileOffset(loc));
336 void FormatTokenLexer::tryParsePythonComment() {
337 FormatToken *HashToken = Tokens.back();
338 if (!HashToken->isOneOf(tok::hash, tok::hashhash))
340 // Turn the remainder of this line into a comment.
341 const char *CommentBegin =
342 Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
343 size_t From = CommentBegin - Lex->getBuffer().begin();
344 size_t To = Lex->getBuffer().find_first_of('\n', From);
345 if (To == StringRef::npos)
346 To = Lex->getBuffer().size();
347 size_t Len = To - From;
348 HashToken->Type = TT_LineComment;
349 HashToken->Tok.setKind(tok::comment);
350 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
351 SourceLocation Loc = To < Lex->getBuffer().size()
352 ? Lex->getSourceLocation(CommentBegin + Len)
353 : SourceMgr.getLocForEndOfFile(ID);
354 resetLexer(SourceMgr.getFileOffset(Loc));
357 bool FormatTokenLexer::tryMerge_TMacro() {
358 if (Tokens.size() < 4)
360 FormatToken *Last = Tokens.back();
361 if (!Last->is(tok::r_paren))
364 FormatToken *String = Tokens[Tokens.size() - 2];
365 if (!String->is(tok::string_literal) || String->IsMultiline)
368 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
371 FormatToken *Macro = Tokens[Tokens.size() - 4];
372 if (Macro->TokenText != "_T")
375 const char *Start = Macro->TokenText.data();
376 const char *End = Last->TokenText.data() + Last->TokenText.size();
377 String->TokenText = StringRef(Start, End - Start);
378 String->IsFirst = Macro->IsFirst;
379 String->LastNewlineOffset = Macro->LastNewlineOffset;
380 String->WhitespaceRange = Macro->WhitespaceRange;
381 String->OriginalColumn = Macro->OriginalColumn;
382 String->ColumnWidth = encoding::columnWidthWithTabs(
383 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
384 String->NewlinesBefore = Macro->NewlinesBefore;
385 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
390 Tokens.back() = String;
394 bool FormatTokenLexer::tryMergeConflictMarkers() {
395 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
398 // Conflict lines look like:
399 // <marker> <text from the vcs>
401 // >>>>>>> /file/in/file/system at revision 1234
403 // We merge all tokens in a line that starts with a conflict marker
404 // into a single token with a special token type that the unwrapped line
405 // parser will use to correctly rebuild the underlying code.
408 // Get the position of the first token in the line.
409 unsigned FirstInLineOffset;
410 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
411 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
412 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
413 // Calculate the offset of the start of the current line.
414 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
415 if (LineOffset == StringRef::npos) {
421 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
423 if (FirstSpace == StringRef::npos) {
424 LineStart = Buffer.substr(LineOffset);
426 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
429 TokenType Type = TT_Unknown;
430 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
431 Type = TT_ConflictStart;
432 } else if (LineStart == "|||||||" || LineStart == "=======" ||
433 LineStart == "====") {
434 Type = TT_ConflictAlternative;
435 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
436 Type = TT_ConflictEnd;
439 if (Type != TT_Unknown) {
440 FormatToken *Next = Tokens.back();
442 Tokens.resize(FirstInLineIndex + 1);
443 // We do not need to build a complete token here, as we will skip it
444 // during parsing anyway (as we must not touch whitespace around conflict
446 Tokens.back()->Type = Type;
447 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
449 Tokens.push_back(Next);
456 FormatToken *FormatTokenLexer::getStashedToken() {
457 // Create a synthesized second '>' or '<' token.
458 Token Tok = FormatTok->Tok;
459 StringRef TokenText = FormatTok->TokenText;
461 unsigned OriginalColumn = FormatTok->OriginalColumn;
462 FormatTok = new (Allocator.Allocate()) FormatToken;
463 FormatTok->Tok = Tok;
464 SourceLocation TokLocation =
465 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
466 FormatTok->Tok.setLocation(TokLocation);
467 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
468 FormatTok->TokenText = TokenText;
469 FormatTok->ColumnWidth = 1;
470 FormatTok->OriginalColumn = OriginalColumn + 1;
475 FormatToken *FormatTokenLexer::getNextToken() {
476 if (StateStack.top() == LexerState::TOKEN_STASHED) {
478 return getStashedToken();
481 FormatTok = new (Allocator.Allocate()) FormatToken;
482 readRawToken(*FormatTok);
483 SourceLocation WhitespaceStart =
484 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
485 FormatTok->IsFirst = IsFirstToken;
486 IsFirstToken = false;
488 // Consume and record whitespace until we find a significant token.
489 unsigned WhitespaceLength = TrailingWhitespace;
490 while (FormatTok->Tok.is(tok::unknown)) {
491 StringRef Text = FormatTok->TokenText;
492 auto EscapesNewline = [&](int pos) {
493 // A '\r' here is just part of '\r\n'. Skip it.
494 if (pos >= 0 && Text[pos] == '\r')
496 // See whether there is an odd number of '\' before this.
497 // FIXME: This is wrong. A '\' followed by a newline is always removed,
498 // regardless of whether there is another '\' before it.
499 // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
501 for (; pos >= 0; --pos, ++count)
502 if (Text[pos] != '\\')
506 // FIXME: This miscounts tok:unknown tokens that are not just
507 // whitespace, e.g. a '`' character.
508 for (int i = 0, e = Text.size(); i != e; ++i) {
511 ++FormatTok->NewlinesBefore;
512 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
513 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
517 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
528 Column += Style.TabWidth - Column % Style.TabWidth;
531 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
532 FormatTok->Type = TT_ImplicitStringLiteral;
535 FormatTok->Type = TT_ImplicitStringLiteral;
538 if (FormatTok->Type == TT_ImplicitStringLiteral)
542 if (FormatTok->is(TT_ImplicitStringLiteral))
544 WhitespaceLength += FormatTok->Tok.getLength();
546 readRawToken(*FormatTok);
549 // JavaScript and Java do not allow to escape the end of the line with a
550 // backslash. Backslashes are syntax errors in plain source, but can occur in
551 // comments. When a single line comment ends with a \, it'll cause the next
552 // line of code to be lexed as a comment, breaking formatting. The code below
553 // finds comments that contain a backslash followed by a line break, truncates
554 // the comment token at the backslash, and resets the lexer to restart behind
556 if ((Style.Language == FormatStyle::LK_JavaScript ||
557 Style.Language == FormatStyle::LK_Java) &&
558 FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
559 size_t BackslashPos = FormatTok->TokenText.find('\\');
560 while (BackslashPos != StringRef::npos) {
561 if (BackslashPos + 1 < FormatTok->TokenText.size() &&
562 FormatTok->TokenText[BackslashPos + 1] == '\n') {
563 const char *Offset = Lex->getBufferLocation();
564 Offset -= FormatTok->TokenText.size();
565 Offset += BackslashPos + 1;
566 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
567 FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
568 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
569 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
573 BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
577 // In case the token starts with escaped newlines, we want to
578 // take them into account as whitespace - this pattern is quite frequent
579 // in macro definitions.
580 // FIXME: Add a more explicit test.
581 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
582 unsigned SkippedWhitespace = 0;
583 if (FormatTok->TokenText.size() > 2 &&
584 (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
585 SkippedWhitespace = 3;
586 else if (FormatTok->TokenText[1] == '\n')
587 SkippedWhitespace = 2;
591 ++FormatTok->NewlinesBefore;
592 WhitespaceLength += SkippedWhitespace;
593 FormatTok->LastNewlineOffset = SkippedWhitespace;
595 FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
598 FormatTok->WhitespaceRange = SourceRange(
599 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
601 FormatTok->OriginalColumn = Column;
603 TrailingWhitespace = 0;
604 if (FormatTok->Tok.is(tok::comment)) {
605 // FIXME: Add the trimmed whitespace to Column.
606 StringRef UntrimmedText = FormatTok->TokenText;
607 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
608 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
609 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
610 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
611 FormatTok->Tok.setIdentifierInfo(&Info);
612 FormatTok->Tok.setKind(Info.getTokenID());
613 if (Style.Language == FormatStyle::LK_Java &&
614 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
616 FormatTok->Tok.setKind(tok::identifier);
617 FormatTok->Tok.setIdentifierInfo(nullptr);
618 } else if (Style.Language == FormatStyle::LK_JavaScript &&
619 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
621 FormatTok->Tok.setKind(tok::identifier);
622 FormatTok->Tok.setIdentifierInfo(nullptr);
624 } else if (FormatTok->Tok.is(tok::greatergreater)) {
625 FormatTok->Tok.setKind(tok::greater);
626 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
628 StateStack.push(LexerState::TOKEN_STASHED);
629 } else if (FormatTok->Tok.is(tok::lessless)) {
630 FormatTok->Tok.setKind(tok::less);
631 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
633 StateStack.push(LexerState::TOKEN_STASHED);
636 // Now FormatTok is the next non-whitespace token.
638 StringRef Text = FormatTok->TokenText;
639 size_t FirstNewlinePos = Text.find('\n');
640 if (FirstNewlinePos == StringRef::npos) {
641 // FIXME: ColumnWidth actually depends on the start column, we need to
642 // take this into account when the token is moved.
643 FormatTok->ColumnWidth =
644 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
645 Column += FormatTok->ColumnWidth;
647 FormatTok->IsMultiline = true;
648 // FIXME: ColumnWidth actually depends on the start column, we need to
649 // take this into account when the token is moved.
650 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
651 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
653 // The last line of the token always starts in column 0.
654 // Thus, the length can be precomputed even in the presence of tabs.
655 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
656 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
657 Column = FormatTok->LastLineColumnWidth;
661 auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
662 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
663 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
665 it != Macros.end()) {
666 FormatTok->Type = it->second;
667 } else if (FormatTok->is(tok::identifier)) {
668 if (MacroBlockBeginRegex.match(Text)) {
669 FormatTok->Type = TT_MacroBlockBegin;
670 } else if (MacroBlockEndRegex.match(Text)) {
671 FormatTok->Type = TT_MacroBlockEnd;
679 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
680 Lex->LexFromRawLexer(Tok.Tok);
681 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
682 Tok.Tok.getLength());
683 // For formatting, treat unterminated string literals like normal string
685 if (Tok.is(tok::unknown)) {
686 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
687 Tok.Tok.setKind(tok::string_literal);
688 Tok.IsUnterminatedLiteral = true;
689 } else if (Style.Language == FormatStyle::LK_JavaScript &&
690 Tok.TokenText == "''") {
691 Tok.Tok.setKind(tok::string_literal);
695 if ((Style.Language == FormatStyle::LK_JavaScript ||
696 Style.Language == FormatStyle::LK_Proto ||
697 Style.Language == FormatStyle::LK_TextProto) &&
698 Tok.is(tok::char_constant)) {
699 Tok.Tok.setKind(tok::string_literal);
702 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
703 Tok.TokenText == "/* clang-format on */")) {
704 FormattingDisabled = false;
707 Tok.Finalized = FormattingDisabled;
709 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
710 Tok.TokenText == "/* clang-format off */")) {
711 FormattingDisabled = true;
715 void FormatTokenLexer::resetLexer(unsigned Offset) {
716 StringRef Buffer = SourceMgr.getBufferData(ID);
717 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
718 getFormattingLangOpts(Style), Buffer.begin(),
719 Buffer.begin() + Offset, Buffer.end()));
720 Lex->SetKeepWhitespaceMode(true);
721 TrailingWhitespace = 0;
724 } // namespace format