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