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 ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
41 llvm::sort(ForEachMacros.begin(), ForEachMacros.end());
44 ArrayRef<FormatToken *> FormatTokenLexer::lex() {
45 assert(Tokens.empty());
46 assert(FirstInLineIndex == 0);
48 Tokens.push_back(getNextToken());
49 if (Style.Language == FormatStyle::LK_JavaScript) {
50 tryParseJSRegexLiteral();
51 handleTemplateStrings();
53 if (Style.Language == FormatStyle::LK_TextProto)
54 tryParsePythonComment();
55 tryMergePreviousTokens();
56 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
57 FirstInLineIndex = Tokens.size() - 1;
58 } while (Tokens.back()->Tok.isNot(tok::eof));
62 void FormatTokenLexer::tryMergePreviousTokens() {
63 if (tryMerge_TMacro())
65 if (tryMergeConflictMarkers())
67 if (tryMergeLessLess())
69 if (tryMergeNSStringLiteral())
72 if (Style.Language == FormatStyle::LK_JavaScript) {
73 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
74 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
76 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
78 static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
79 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
80 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
83 // FIXME: Investigate what token type gives the correct operator priority.
84 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
86 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
88 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
90 if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
92 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
94 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
95 Tokens.back()->Tok.setKind(tok::starequal);
100 if (Style.Language == FormatStyle::LK_Java) {
101 static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
102 tok::greater, tok::greater, tok::greaterequal};
103 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
108 bool FormatTokenLexer::tryMergeNSStringLiteral() {
109 if (Tokens.size() < 2)
111 auto &At = *(Tokens.end() - 2);
112 auto &String = *(Tokens.end() - 1);
113 if (!At->is(tok::at) || !String->is(tok::string_literal))
115 At->Tok.setKind(tok::string_literal);
116 At->TokenText = StringRef(At->TokenText.begin(),
117 String->TokenText.end() - At->TokenText.begin());
118 At->ColumnWidth += String->ColumnWidth;
119 At->Type = TT_ObjCStringLiteral;
120 Tokens.erase(Tokens.end() - 1);
124 bool FormatTokenLexer::tryMergeLessLess() {
125 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
126 if (Tokens.size() < 3)
129 bool FourthTokenIsLess = false;
130 if (Tokens.size() > 3)
131 FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
133 auto First = Tokens.end() - 3;
134 if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
135 First[0]->isNot(tok::less) || FourthTokenIsLess)
138 // Only merge if there currently is no whitespace between the two "<".
139 if (First[1]->WhitespaceRange.getBegin() !=
140 First[1]->WhitespaceRange.getEnd())
143 First[0]->Tok.setKind(tok::lessless);
144 First[0]->TokenText = "<<";
145 First[0]->ColumnWidth += 1;
146 Tokens.erase(Tokens.end() - 2);
150 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
152 if (Tokens.size() < Kinds.size())
155 SmallVectorImpl<FormatToken *>::const_iterator First =
156 Tokens.end() - Kinds.size();
157 if (!First[0]->is(Kinds[0]))
159 unsigned AddLength = 0;
160 for (unsigned i = 1; i < Kinds.size(); ++i) {
161 if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
162 First[i]->WhitespaceRange.getEnd())
164 AddLength += First[i]->TokenText.size();
166 Tokens.resize(Tokens.size() - Kinds.size() + 1);
167 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
168 First[0]->TokenText.size() + AddLength);
169 First[0]->ColumnWidth += AddLength;
170 First[0]->Type = NewType;
174 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
175 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
176 // NB: This is not entirely correct, as an r_paren can introduce an operand
177 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
178 // corner case to not matter in practice, though.
179 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
180 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
181 tok::colon, tok::question, tok::tilde) ||
182 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
183 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
184 tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
185 Tok->isBinaryOperator();
188 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
192 // Regex literals can only follow after prefix unary operators, not after
193 // postfix unary operators. If the '++' is followed by a non-operand
194 // introducing token, the slash here is the operand and not the start of a
196 // `!` is an unary prefix operator, but also a post-fix operator that casts
197 // away nullability, so the same check applies.
198 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
199 return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
201 // The previous token must introduce an operand location where regex
202 // literals can occur.
203 if (!precedesOperand(Prev))
209 // Tries to parse a JavaScript Regex literal starting at the current token,
210 // if that begins with a slash and is in a location where JavaScript allows
211 // regex literals. Changes the current token to a regex literal and updates
212 // its text if successful.
213 void FormatTokenLexer::tryParseJSRegexLiteral() {
214 FormatToken *RegexToken = Tokens.back();
215 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
218 FormatToken *Prev = nullptr;
219 for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
220 // NB: Because previous pointers are not initialized yet, this cannot use
221 // Token.getPreviousNonComment.
222 if ((*I)->isNot(tok::comment)) {
228 if (!canPrecedeRegexLiteral(Prev))
231 // 'Manually' lex ahead in the current file buffer.
232 const char *Offset = Lex->getBufferLocation();
233 const char *RegexBegin = Offset - RegexToken->TokenText.size();
234 StringRef Buffer = Lex->getBuffer();
235 bool InCharacterClass = false;
236 bool HaveClosingSlash = false;
237 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
238 // Regular expressions are terminated with a '/', which can only be
239 // escaped using '\' or a character class between '[' and ']'.
240 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
243 // Skip the escaped character.
247 InCharacterClass = true;
250 InCharacterClass = false;
253 if (!InCharacterClass)
254 HaveClosingSlash = true;
259 RegexToken->Type = TT_RegexLiteral;
260 // Treat regex literals like other string_literals.
261 RegexToken->Tok.setKind(tok::string_literal);
262 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
263 RegexToken->ColumnWidth = RegexToken->TokenText.size();
265 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
268 void FormatTokenLexer::handleTemplateStrings() {
269 FormatToken *BacktickToken = Tokens.back();
271 if (BacktickToken->is(tok::l_brace)) {
272 StateStack.push(LexerState::NORMAL);
275 if (BacktickToken->is(tok::r_brace)) {
276 if (StateStack.size() == 1)
279 if (StateStack.top() != LexerState::TEMPLATE_STRING)
281 // If back in TEMPLATE_STRING, fallthrough and continue parsing the
282 } else if (BacktickToken->is(tok::unknown) &&
283 BacktickToken->TokenText == "`") {
284 StateStack.push(LexerState::TEMPLATE_STRING);
286 return; // Not actually a template
289 // 'Manually' lex ahead in the current file buffer.
290 const char *Offset = Lex->getBufferLocation();
291 const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
292 for (; Offset != Lex->getBuffer().end(); ++Offset) {
293 if (Offset[0] == '`') {
297 if (Offset[0] == '\\') {
298 ++Offset; // Skip the escaped character.
299 } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
301 // '${' introduces an expression interpolation in the template string.
302 StateStack.push(LexerState::NORMAL);
308 StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
309 BacktickToken->Type = TT_TemplateString;
310 BacktickToken->Tok.setKind(tok::string_literal);
311 BacktickToken->TokenText = LiteralText;
313 // Adjust width for potentially multiline string literals.
314 size_t FirstBreak = LiteralText.find('\n');
315 StringRef FirstLineText = FirstBreak == StringRef::npos
317 : LiteralText.substr(0, FirstBreak);
318 BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
319 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
320 size_t LastBreak = LiteralText.rfind('\n');
321 if (LastBreak != StringRef::npos) {
322 BacktickToken->IsMultiline = true;
323 unsigned StartColumn = 0; // The template tail spans the entire line.
324 BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
325 LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
326 Style.TabWidth, Encoding);
329 SourceLocation loc = Offset < Lex->getBuffer().end()
330 ? Lex->getSourceLocation(Offset + 1)
331 : SourceMgr.getLocForEndOfFile(ID);
332 resetLexer(SourceMgr.getFileOffset(loc));
335 void FormatTokenLexer::tryParsePythonComment() {
336 FormatToken *HashToken = Tokens.back();
337 if (!HashToken->isOneOf(tok::hash, tok::hashhash))
339 // Turn the remainder of this line into a comment.
340 const char *CommentBegin =
341 Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
342 size_t From = CommentBegin - Lex->getBuffer().begin();
343 size_t To = Lex->getBuffer().find_first_of('\n', From);
344 if (To == StringRef::npos)
345 To = Lex->getBuffer().size();
346 size_t Len = To - From;
347 HashToken->Type = TT_LineComment;
348 HashToken->Tok.setKind(tok::comment);
349 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
350 SourceLocation Loc = To < Lex->getBuffer().size()
351 ? Lex->getSourceLocation(CommentBegin + Len)
352 : SourceMgr.getLocForEndOfFile(ID);
353 resetLexer(SourceMgr.getFileOffset(Loc));
356 bool FormatTokenLexer::tryMerge_TMacro() {
357 if (Tokens.size() < 4)
359 FormatToken *Last = Tokens.back();
360 if (!Last->is(tok::r_paren))
363 FormatToken *String = Tokens[Tokens.size() - 2];
364 if (!String->is(tok::string_literal) || String->IsMultiline)
367 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
370 FormatToken *Macro = Tokens[Tokens.size() - 4];
371 if (Macro->TokenText != "_T")
374 const char *Start = Macro->TokenText.data();
375 const char *End = Last->TokenText.data() + Last->TokenText.size();
376 String->TokenText = StringRef(Start, End - Start);
377 String->IsFirst = Macro->IsFirst;
378 String->LastNewlineOffset = Macro->LastNewlineOffset;
379 String->WhitespaceRange = Macro->WhitespaceRange;
380 String->OriginalColumn = Macro->OriginalColumn;
381 String->ColumnWidth = encoding::columnWidthWithTabs(
382 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
383 String->NewlinesBefore = Macro->NewlinesBefore;
384 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
389 Tokens.back() = String;
393 bool FormatTokenLexer::tryMergeConflictMarkers() {
394 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
397 // Conflict lines look like:
398 // <marker> <text from the vcs>
400 // >>>>>>> /file/in/file/system at revision 1234
402 // We merge all tokens in a line that starts with a conflict marker
403 // into a single token with a special token type that the unwrapped line
404 // parser will use to correctly rebuild the underlying code.
407 // Get the position of the first token in the line.
408 unsigned FirstInLineOffset;
409 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
410 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
411 StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
412 // Calculate the offset of the start of the current line.
413 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
414 if (LineOffset == StringRef::npos) {
420 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
422 if (FirstSpace == StringRef::npos) {
423 LineStart = Buffer.substr(LineOffset);
425 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
428 TokenType Type = TT_Unknown;
429 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
430 Type = TT_ConflictStart;
431 } else if (LineStart == "|||||||" || LineStart == "=======" ||
432 LineStart == "====") {
433 Type = TT_ConflictAlternative;
434 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
435 Type = TT_ConflictEnd;
438 if (Type != TT_Unknown) {
439 FormatToken *Next = Tokens.back();
441 Tokens.resize(FirstInLineIndex + 1);
442 // We do not need to build a complete token here, as we will skip it
443 // during parsing anyway (as we must not touch whitespace around conflict
445 Tokens.back()->Type = Type;
446 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
448 Tokens.push_back(Next);
455 FormatToken *FormatTokenLexer::getStashedToken() {
456 // Create a synthesized second '>' or '<' token.
457 Token Tok = FormatTok->Tok;
458 StringRef TokenText = FormatTok->TokenText;
460 unsigned OriginalColumn = FormatTok->OriginalColumn;
461 FormatTok = new (Allocator.Allocate()) FormatToken;
462 FormatTok->Tok = Tok;
463 SourceLocation TokLocation =
464 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
465 FormatTok->Tok.setLocation(TokLocation);
466 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
467 FormatTok->TokenText = TokenText;
468 FormatTok->ColumnWidth = 1;
469 FormatTok->OriginalColumn = OriginalColumn + 1;
474 FormatToken *FormatTokenLexer::getNextToken() {
475 if (StateStack.top() == LexerState::TOKEN_STASHED) {
477 return getStashedToken();
480 FormatTok = new (Allocator.Allocate()) FormatToken;
481 readRawToken(*FormatTok);
482 SourceLocation WhitespaceStart =
483 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
484 FormatTok->IsFirst = IsFirstToken;
485 IsFirstToken = false;
487 // Consume and record whitespace until we find a significant token.
488 unsigned WhitespaceLength = TrailingWhitespace;
489 while (FormatTok->Tok.is(tok::unknown)) {
490 StringRef Text = FormatTok->TokenText;
491 auto EscapesNewline = [&](int pos) {
492 // A '\r' here is just part of '\r\n'. Skip it.
493 if (pos >= 0 && Text[pos] == '\r')
495 // See whether there is an odd number of '\' before this.
496 // FIXME: This is wrong. A '\' followed by a newline is always removed,
497 // regardless of whether there is another '\' before it.
498 // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
500 for (; pos >= 0; --pos, ++count)
501 if (Text[pos] != '\\')
505 // FIXME: This miscounts tok:unknown tokens that are not just
506 // whitespace, e.g. a '`' character.
507 for (int i = 0, e = Text.size(); i != e; ++i) {
510 ++FormatTok->NewlinesBefore;
511 FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
512 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
516 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
527 Column += Style.TabWidth - Column % Style.TabWidth;
530 if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
531 FormatTok->Type = TT_ImplicitStringLiteral;
534 FormatTok->Type = TT_ImplicitStringLiteral;
537 if (FormatTok->Type == TT_ImplicitStringLiteral)
541 if (FormatTok->is(TT_ImplicitStringLiteral))
543 WhitespaceLength += FormatTok->Tok.getLength();
545 readRawToken(*FormatTok);
548 // JavaScript and Java do not allow to escape the end of the line with a
549 // backslash. Backslashes are syntax errors in plain source, but can occur in
550 // comments. When a single line comment ends with a \, it'll cause the next
551 // line of code to be lexed as a comment, breaking formatting. The code below
552 // finds comments that contain a backslash followed by a line break, truncates
553 // the comment token at the backslash, and resets the lexer to restart behind
555 if ((Style.Language == FormatStyle::LK_JavaScript ||
556 Style.Language == FormatStyle::LK_Java) &&
557 FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
558 size_t BackslashPos = FormatTok->TokenText.find('\\');
559 while (BackslashPos != StringRef::npos) {
560 if (BackslashPos + 1 < FormatTok->TokenText.size() &&
561 FormatTok->TokenText[BackslashPos + 1] == '\n') {
562 const char *Offset = Lex->getBufferLocation();
563 Offset -= FormatTok->TokenText.size();
564 Offset += BackslashPos + 1;
565 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
566 FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
567 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
568 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
572 BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
576 // In case the token starts with escaped newlines, we want to
577 // take them into account as whitespace - this pattern is quite frequent
578 // in macro definitions.
579 // FIXME: Add a more explicit test.
580 while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
581 unsigned SkippedWhitespace = 0;
582 if (FormatTok->TokenText.size() > 2 &&
583 (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
584 SkippedWhitespace = 3;
585 else if (FormatTok->TokenText[1] == '\n')
586 SkippedWhitespace = 2;
590 ++FormatTok->NewlinesBefore;
591 WhitespaceLength += SkippedWhitespace;
592 FormatTok->LastNewlineOffset = SkippedWhitespace;
594 FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
597 FormatTok->WhitespaceRange = SourceRange(
598 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
600 FormatTok->OriginalColumn = Column;
602 TrailingWhitespace = 0;
603 if (FormatTok->Tok.is(tok::comment)) {
604 // FIXME: Add the trimmed whitespace to Column.
605 StringRef UntrimmedText = FormatTok->TokenText;
606 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
607 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
608 } else if (FormatTok->Tok.is(tok::raw_identifier)) {
609 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
610 FormatTok->Tok.setIdentifierInfo(&Info);
611 FormatTok->Tok.setKind(Info.getTokenID());
612 if (Style.Language == FormatStyle::LK_Java &&
613 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
615 FormatTok->Tok.setKind(tok::identifier);
616 FormatTok->Tok.setIdentifierInfo(nullptr);
617 } else if (Style.Language == FormatStyle::LK_JavaScript &&
618 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
620 FormatTok->Tok.setKind(tok::identifier);
621 FormatTok->Tok.setIdentifierInfo(nullptr);
623 } else if (FormatTok->Tok.is(tok::greatergreater)) {
624 FormatTok->Tok.setKind(tok::greater);
625 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
627 StateStack.push(LexerState::TOKEN_STASHED);
628 } else if (FormatTok->Tok.is(tok::lessless)) {
629 FormatTok->Tok.setKind(tok::less);
630 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
632 StateStack.push(LexerState::TOKEN_STASHED);
635 // Now FormatTok is the next non-whitespace token.
637 StringRef Text = FormatTok->TokenText;
638 size_t FirstNewlinePos = Text.find('\n');
639 if (FirstNewlinePos == StringRef::npos) {
640 // FIXME: ColumnWidth actually depends on the start column, we need to
641 // take this into account when the token is moved.
642 FormatTok->ColumnWidth =
643 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
644 Column += FormatTok->ColumnWidth;
646 FormatTok->IsMultiline = true;
647 // FIXME: ColumnWidth actually depends on the start column, we need to
648 // take this into account when the token is moved.
649 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
650 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
652 // The last line of the token always starts in column 0.
653 // Thus, the length can be precomputed even in the presence of tabs.
654 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
655 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
656 Column = FormatTok->LastLineColumnWidth;
660 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
661 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
663 std::find(ForEachMacros.begin(), ForEachMacros.end(),
664 FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
665 FormatTok->Type = TT_ForEachMacro;
666 } else if (FormatTok->is(tok::identifier)) {
667 if (MacroBlockBeginRegex.match(Text)) {
668 FormatTok->Type = TT_MacroBlockBegin;
669 } else if (MacroBlockEndRegex.match(Text)) {
670 FormatTok->Type = TT_MacroBlockEnd;
678 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
679 Lex->LexFromRawLexer(Tok.Tok);
680 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
681 Tok.Tok.getLength());
682 // For formatting, treat unterminated string literals like normal string
684 if (Tok.is(tok::unknown)) {
685 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
686 Tok.Tok.setKind(tok::string_literal);
687 Tok.IsUnterminatedLiteral = true;
688 } else if (Style.Language == FormatStyle::LK_JavaScript &&
689 Tok.TokenText == "''") {
690 Tok.Tok.setKind(tok::string_literal);
694 if ((Style.Language == FormatStyle::LK_JavaScript ||
695 Style.Language == FormatStyle::LK_Proto ||
696 Style.Language == FormatStyle::LK_TextProto) &&
697 Tok.is(tok::char_constant)) {
698 Tok.Tok.setKind(tok::string_literal);
701 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
702 Tok.TokenText == "/* clang-format on */")) {
703 FormattingDisabled = false;
706 Tok.Finalized = FormattingDisabled;
708 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
709 Tok.TokenText == "/* clang-format off */")) {
710 FormattingDisabled = true;
714 void FormatTokenLexer::resetLexer(unsigned Offset) {
715 StringRef Buffer = SourceMgr.getBufferData(ID);
716 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
717 getFormattingLangOpts(Style), Buffer.begin(),
718 Buffer.begin() + Offset, Buffer.end()));
719 Lex->SetKeepWhitespaceMode(true);
720 TrailingWhitespace = 0;
723 } // namespace format