1 //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file implements FormatTokenLexer, which tokenizes a source file
11 /// into a FormatToken stream suitable for ClangFormat.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #include "FormatTokenLexer.h"
16 #include "FormatToken.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Format/Format.h"
20 #include "llvm/Support/Regex.h"
21
22 namespace clang {
23 namespace format {
24
FormatTokenLexer(const SourceManager & SourceMgr,FileID ID,unsigned Column,const FormatStyle & Style,encoding::Encoding Encoding,llvm::SpecificBumpPtrAllocator<FormatToken> & Allocator,IdentifierTable & IdentTable)25 FormatTokenLexer::FormatTokenLexer(
26 const SourceManager &SourceMgr, FileID ID, unsigned Column,
27 const FormatStyle &Style, encoding::Encoding Encoding,
28 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
29 IdentifierTable &IdentTable)
30 : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
31 Column(Column), TrailingWhitespace(0),
32 LangOpts(getFormattingLangOpts(Style)), SourceMgr(SourceMgr), ID(ID),
33 Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
34 Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
35 FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
36 MacroBlockEndRegex(Style.MacroBlockEnd) {
37 Lex.reset(new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr, LangOpts));
38 Lex->SetKeepWhitespaceMode(true);
39
40 for (const std::string &ForEachMacro : Style.ForEachMacros) {
41 auto Identifier = &IdentTable.get(ForEachMacro);
42 Macros.insert({Identifier, TT_ForEachMacro});
43 }
44 for (const std::string &IfMacro : Style.IfMacros) {
45 auto Identifier = &IdentTable.get(IfMacro);
46 Macros.insert({Identifier, TT_IfMacro});
47 }
48 for (const std::string &AttributeMacro : Style.AttributeMacros) {
49 auto Identifier = &IdentTable.get(AttributeMacro);
50 Macros.insert({Identifier, TT_AttributeMacro});
51 }
52 for (const std::string &StatementMacro : Style.StatementMacros) {
53 auto Identifier = &IdentTable.get(StatementMacro);
54 Macros.insert({Identifier, TT_StatementMacro});
55 }
56 for (const std::string &TypenameMacro : Style.TypenameMacros) {
57 auto Identifier = &IdentTable.get(TypenameMacro);
58 Macros.insert({Identifier, TT_TypenameMacro});
59 }
60 for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
61 auto Identifier = &IdentTable.get(NamespaceMacro);
62 Macros.insert({Identifier, TT_NamespaceMacro});
63 }
64 for (const std::string &WhitespaceSensitiveMacro :
65 Style.WhitespaceSensitiveMacros) {
66 auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
67 Macros.insert({Identifier, TT_UntouchableMacroFunc});
68 }
69 for (const std::string &StatementAttributeLikeMacro :
70 Style.StatementAttributeLikeMacros) {
71 auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
72 Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
73 }
74 }
75
lex()76 ArrayRef<FormatToken *> FormatTokenLexer::lex() {
77 assert(Tokens.empty());
78 assert(FirstInLineIndex == 0);
79 do {
80 Tokens.push_back(getNextToken());
81 if (Style.isJavaScript()) {
82 tryParseJSRegexLiteral();
83 handleTemplateStrings();
84 }
85 if (Style.Language == FormatStyle::LK_TextProto)
86 tryParsePythonComment();
87 tryMergePreviousTokens();
88 if (Style.isCSharp()) {
89 // This needs to come after tokens have been merged so that C#
90 // string literals are correctly identified.
91 handleCSharpVerbatimAndInterpolatedStrings();
92 }
93 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
94 FirstInLineIndex = Tokens.size() - 1;
95 } while (Tokens.back()->isNot(tok::eof));
96 return Tokens;
97 }
98
tryMergePreviousTokens()99 void FormatTokenLexer::tryMergePreviousTokens() {
100 if (tryMerge_TMacro())
101 return;
102 if (tryMergeConflictMarkers())
103 return;
104 if (tryMergeLessLess())
105 return;
106 if (tryMergeForEach())
107 return;
108 if (Style.isCpp() && tryTransformTryUsageForC())
109 return;
110
111 if (Style.isJavaScript() || Style.isCSharp()) {
112 static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
113 tok::question};
114 static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
115 tok::period};
116 static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
117
118 if (tryMergeTokens(FatArrow, TT_FatArrow))
119 return;
120 if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
121 // Treat like the "||" operator (as opposed to the ternary ?).
122 Tokens.back()->Tok.setKind(tok::pipepipe);
123 return;
124 }
125 if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
126 // Treat like a regular "." access.
127 Tokens.back()->Tok.setKind(tok::period);
128 return;
129 }
130 if (tryMergeNullishCoalescingEqual())
131 return;
132 }
133
134 if (Style.isCSharp()) {
135 static const tok::TokenKind CSharpNullConditionalLSquare[] = {
136 tok::question, tok::l_square};
137
138 if (tryMergeCSharpKeywordVariables())
139 return;
140 if (tryMergeCSharpStringLiteral())
141 return;
142 if (tryTransformCSharpForEach())
143 return;
144 if (tryMergeTokens(CSharpNullConditionalLSquare,
145 TT_CSharpNullConditionalLSquare)) {
146 // Treat like a regular "[" operator.
147 Tokens.back()->Tok.setKind(tok::l_square);
148 return;
149 }
150 }
151
152 if (tryMergeNSStringLiteral())
153 return;
154
155 if (Style.isJavaScript()) {
156 static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
157 static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
158 tok::equal};
159 static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
160 tok::greaterequal};
161 static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
162 static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
163 tok::starequal};
164 static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
165 static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
166
167 // FIXME: Investigate what token type gives the correct operator priority.
168 if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
169 return;
170 if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
171 return;
172 if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
173 return;
174 if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
175 return;
176 if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
177 Tokens.back()->Tok.setKind(tok::starequal);
178 return;
179 }
180 if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
181 tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
182 // Treat like the "=" assignment operator.
183 Tokens.back()->Tok.setKind(tok::equal);
184 return;
185 }
186 if (tryMergeJSPrivateIdentifier())
187 return;
188 }
189
190 if (Style.Language == FormatStyle::LK_Java) {
191 static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
192 tok::greater, tok::greater, tok::greaterequal};
193 if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
194 return;
195 }
196
197 if (Style.isVerilog()) {
198 // Merge the number following a base like `'h?a0`.
199 if (Tokens.size() >= 3 && Tokens.end()[-3]->is(TT_VerilogNumberBase) &&
200 Tokens.end()[-2]->is(tok::numeric_constant) &&
201 Tokens.back()->isOneOf(tok::numeric_constant, tok::identifier,
202 tok::question) &&
203 tryMergeTokens(2, TT_Unknown)) {
204 return;
205 }
206 // Part select.
207 if (tryMergeTokensAny({{tok::minus, tok::colon}, {tok::plus, tok::colon}},
208 TT_BitFieldColon)) {
209 return;
210 }
211 // Xnor. The combined token is treated as a caret which can also be either a
212 // unary or binary operator. The actual type is determined in
213 // TokenAnnotator. We also check the token length so we know it is not
214 // already a merged token.
215 if (Tokens.back()->TokenText.size() == 1 &&
216 tryMergeTokensAny({{tok::caret, tok::tilde}, {tok::tilde, tok::caret}},
217 TT_BinaryOperator)) {
218 Tokens.back()->Tok.setKind(tok::caret);
219 return;
220 }
221 // Signed shift and distribution weight.
222 if (tryMergeTokens({tok::less, tok::less}, TT_BinaryOperator)) {
223 Tokens.back()->Tok.setKind(tok::lessless);
224 return;
225 }
226 if (tryMergeTokens({tok::greater, tok::greater}, TT_BinaryOperator)) {
227 Tokens.back()->Tok.setKind(tok::greatergreater);
228 return;
229 }
230 if (tryMergeTokensAny({{tok::lessless, tok::equal},
231 {tok::lessless, tok::lessequal},
232 {tok::greatergreater, tok::equal},
233 {tok::greatergreater, tok::greaterequal},
234 {tok::colon, tok::equal},
235 {tok::colon, tok::slash}},
236 TT_BinaryOperator)) {
237 Tokens.back()->ForcedPrecedence = prec::Assignment;
238 return;
239 }
240 // Exponentiation, signed shift, case equality, and wildcard equality.
241 if (tryMergeTokensAny({{tok::star, tok::star},
242 {tok::lessless, tok::less},
243 {tok::greatergreater, tok::greater},
244 {tok::exclaimequal, tok::equal},
245 {tok::exclaimequal, tok::question},
246 {tok::equalequal, tok::equal},
247 {tok::equalequal, tok::question}},
248 TT_BinaryOperator)) {
249 return;
250 }
251 // Module paths in specify blocks and implications in properties.
252 if (tryMergeTokensAny({{tok::plusequal, tok::greater},
253 {tok::plus, tok::star, tok::greater},
254 {tok::minusequal, tok::greater},
255 {tok::minus, tok::star, tok::greater},
256 {tok::less, tok::arrow},
257 {tok::equal, tok::greater},
258 {tok::star, tok::greater},
259 {tok::pipeequal, tok::greater},
260 {tok::pipe, tok::arrow},
261 {tok::hash, tok::minus, tok::hash},
262 {tok::hash, tok::equal, tok::hash}},
263 TT_BinaryOperator)) {
264 Tokens.back()->ForcedPrecedence = prec::Comma;
265 return;
266 }
267 }
268 }
269
tryMergeNSStringLiteral()270 bool FormatTokenLexer::tryMergeNSStringLiteral() {
271 if (Tokens.size() < 2)
272 return false;
273 auto &At = *(Tokens.end() - 2);
274 auto &String = *(Tokens.end() - 1);
275 if (!At->is(tok::at) || !String->is(tok::string_literal))
276 return false;
277 At->Tok.setKind(tok::string_literal);
278 At->TokenText = StringRef(At->TokenText.begin(),
279 String->TokenText.end() - At->TokenText.begin());
280 At->ColumnWidth += String->ColumnWidth;
281 At->setType(TT_ObjCStringLiteral);
282 Tokens.erase(Tokens.end() - 1);
283 return true;
284 }
285
tryMergeJSPrivateIdentifier()286 bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
287 // Merges #idenfier into a single identifier with the text #identifier
288 // but the token tok::identifier.
289 if (Tokens.size() < 2)
290 return false;
291 auto &Hash = *(Tokens.end() - 2);
292 auto &Identifier = *(Tokens.end() - 1);
293 if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier))
294 return false;
295 Hash->Tok.setKind(tok::identifier);
296 Hash->TokenText =
297 StringRef(Hash->TokenText.begin(),
298 Identifier->TokenText.end() - Hash->TokenText.begin());
299 Hash->ColumnWidth += Identifier->ColumnWidth;
300 Hash->setType(TT_JsPrivateIdentifier);
301 Tokens.erase(Tokens.end() - 1);
302 return true;
303 }
304
305 // Search for verbatim or interpolated string literals @"ABC" or
306 // $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to
307 // prevent splitting of @, $ and ".
308 // Merging of multiline verbatim strings with embedded '"' is handled in
309 // handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
tryMergeCSharpStringLiteral()310 bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
311 if (Tokens.size() < 2)
312 return false;
313
314 // Look for @"aaaaaa" or $"aaaaaa".
315 const auto String = *(Tokens.end() - 1);
316 if (String->isNot(tok::string_literal))
317 return false;
318
319 auto Prefix = *(Tokens.end() - 2);
320 if (Prefix->isNot(tok::at) && Prefix->TokenText != "$")
321 return false;
322
323 if (Tokens.size() > 2) {
324 const auto Tok = *(Tokens.end() - 3);
325 if ((Tok->TokenText == "$" && Prefix->is(tok::at)) ||
326 (Tok->is(tok::at) && Prefix->TokenText == "$")) {
327 // This looks like $@"aaa" or @$"aaa" so we need to combine all 3 tokens.
328 Tok->ColumnWidth += Prefix->ColumnWidth;
329 Tokens.erase(Tokens.end() - 2);
330 Prefix = Tok;
331 }
332 }
333
334 // Convert back into just a string_literal.
335 Prefix->Tok.setKind(tok::string_literal);
336 Prefix->TokenText =
337 StringRef(Prefix->TokenText.begin(),
338 String->TokenText.end() - Prefix->TokenText.begin());
339 Prefix->ColumnWidth += String->ColumnWidth;
340 Prefix->setType(TT_CSharpStringLiteral);
341 Tokens.erase(Tokens.end() - 1);
342 return true;
343 }
344
345 // Valid C# attribute targets:
346 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
347 const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
348 "assembly", "module", "field", "event", "method",
349 "param", "property", "return", "type",
350 };
351
tryMergeNullishCoalescingEqual()352 bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
353 if (Tokens.size() < 2)
354 return false;
355 auto &NullishCoalescing = *(Tokens.end() - 2);
356 auto &Equal = *(Tokens.end() - 1);
357 if (NullishCoalescing->getType() != TT_NullCoalescingOperator ||
358 !Equal->is(tok::equal)) {
359 return false;
360 }
361 NullishCoalescing->Tok.setKind(tok::equal); // no '??=' in clang tokens.
362 NullishCoalescing->TokenText =
363 StringRef(NullishCoalescing->TokenText.begin(),
364 Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
365 NullishCoalescing->ColumnWidth += Equal->ColumnWidth;
366 NullishCoalescing->setType(TT_NullCoalescingEqual);
367 Tokens.erase(Tokens.end() - 1);
368 return true;
369 }
370
tryMergeCSharpKeywordVariables()371 bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
372 if (Tokens.size() < 2)
373 return false;
374 const auto At = *(Tokens.end() - 2);
375 if (At->isNot(tok::at))
376 return false;
377 const auto Keyword = *(Tokens.end() - 1);
378 if (Keyword->TokenText == "$")
379 return false;
380 if (!Keywords.isCSharpKeyword(*Keyword))
381 return false;
382
383 At->Tok.setKind(tok::identifier);
384 At->TokenText = StringRef(At->TokenText.begin(),
385 Keyword->TokenText.end() - At->TokenText.begin());
386 At->ColumnWidth += Keyword->ColumnWidth;
387 At->setType(Keyword->getType());
388 Tokens.erase(Tokens.end() - 1);
389 return true;
390 }
391
392 // In C# transform identifier foreach into kw_foreach
tryTransformCSharpForEach()393 bool FormatTokenLexer::tryTransformCSharpForEach() {
394 if (Tokens.size() < 1)
395 return false;
396 auto &Identifier = *(Tokens.end() - 1);
397 if (!Identifier->is(tok::identifier))
398 return false;
399 if (Identifier->TokenText != "foreach")
400 return false;
401
402 Identifier->setType(TT_ForEachMacro);
403 Identifier->Tok.setKind(tok::kw_for);
404 return true;
405 }
406
tryMergeForEach()407 bool FormatTokenLexer::tryMergeForEach() {
408 if (Tokens.size() < 2)
409 return false;
410 auto &For = *(Tokens.end() - 2);
411 auto &Each = *(Tokens.end() - 1);
412 if (!For->is(tok::kw_for))
413 return false;
414 if (!Each->is(tok::identifier))
415 return false;
416 if (Each->TokenText != "each")
417 return false;
418
419 For->setType(TT_ForEachMacro);
420 For->Tok.setKind(tok::kw_for);
421
422 For->TokenText = StringRef(For->TokenText.begin(),
423 Each->TokenText.end() - For->TokenText.begin());
424 For->ColumnWidth += Each->ColumnWidth;
425 Tokens.erase(Tokens.end() - 1);
426 return true;
427 }
428
tryTransformTryUsageForC()429 bool FormatTokenLexer::tryTransformTryUsageForC() {
430 if (Tokens.size() < 2)
431 return false;
432 auto &Try = *(Tokens.end() - 2);
433 if (!Try->is(tok::kw_try))
434 return false;
435 auto &Next = *(Tokens.end() - 1);
436 if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
437 return false;
438
439 if (Tokens.size() > 2) {
440 auto &At = *(Tokens.end() - 3);
441 if (At->is(tok::at))
442 return false;
443 }
444
445 Try->Tok.setKind(tok::identifier);
446 return true;
447 }
448
tryMergeLessLess()449 bool FormatTokenLexer::tryMergeLessLess() {
450 // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
451 if (Tokens.size() < 3)
452 return false;
453
454 auto First = Tokens.end() - 3;
455 if (First[0]->isNot(tok::less) || First[1]->isNot(tok::less))
456 return false;
457
458 // Only merge if there currently is no whitespace between the two "<".
459 if (First[1]->hasWhitespaceBefore())
460 return false;
461
462 auto X = Tokens.size() > 3 ? First[-1] : nullptr;
463 auto Y = First[2];
464 if ((X && X->is(tok::less)) || Y->is(tok::less))
465 return false;
466
467 // Do not remove a whitespace between the two "<" e.g. "operator< <>".
468 if (X && X->is(tok::kw_operator) && Y->is(tok::greater))
469 return false;
470
471 First[0]->Tok.setKind(tok::lessless);
472 First[0]->TokenText = "<<";
473 First[0]->ColumnWidth += 1;
474 Tokens.erase(Tokens.end() - 2);
475 return true;
476 }
477
tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,TokenType NewType)478 bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
479 TokenType NewType) {
480 if (Tokens.size() < Kinds.size())
481 return false;
482
483 SmallVectorImpl<FormatToken *>::const_iterator First =
484 Tokens.end() - Kinds.size();
485 for (unsigned i = 0; i < Kinds.size(); ++i)
486 if (!First[i]->is(Kinds[i]))
487 return false;
488
489 return tryMergeTokens(Kinds.size(), NewType);
490 }
491
tryMergeTokens(size_t Count,TokenType NewType)492 bool FormatTokenLexer::tryMergeTokens(size_t Count, TokenType NewType) {
493 if (Tokens.size() < Count)
494 return false;
495
496 SmallVectorImpl<FormatToken *>::const_iterator First = Tokens.end() - Count;
497 unsigned AddLength = 0;
498 for (size_t i = 1; i < Count; ++i) {
499 // If there is whitespace separating the token and the previous one,
500 // they should not be merged.
501 if (First[i]->hasWhitespaceBefore())
502 return false;
503 AddLength += First[i]->TokenText.size();
504 }
505
506 Tokens.resize(Tokens.size() - Count + 1);
507 First[0]->TokenText = StringRef(First[0]->TokenText.data(),
508 First[0]->TokenText.size() + AddLength);
509 First[0]->ColumnWidth += AddLength;
510 First[0]->setType(NewType);
511 return true;
512 }
513
tryMergeTokensAny(ArrayRef<ArrayRef<tok::TokenKind>> Kinds,TokenType NewType)514 bool FormatTokenLexer::tryMergeTokensAny(
515 ArrayRef<ArrayRef<tok::TokenKind>> Kinds, TokenType NewType) {
516 return llvm::any_of(Kinds, [this, NewType](ArrayRef<tok::TokenKind> Kinds) {
517 return tryMergeTokens(Kinds, NewType);
518 });
519 }
520
521 // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
precedesOperand(FormatToken * Tok)522 bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
523 // NB: This is not entirely correct, as an r_paren can introduce an operand
524 // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
525 // corner case to not matter in practice, though.
526 return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
527 tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
528 tok::colon, tok::question, tok::tilde) ||
529 Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
530 tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
531 tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
532 Tok->isBinaryOperator();
533 }
534
canPrecedeRegexLiteral(FormatToken * Prev)535 bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
536 if (!Prev)
537 return true;
538
539 // Regex literals can only follow after prefix unary operators, not after
540 // postfix unary operators. If the '++' is followed by a non-operand
541 // introducing token, the slash here is the operand and not the start of a
542 // regex.
543 // `!` is an unary prefix operator, but also a post-fix operator that casts
544 // away nullability, so the same check applies.
545 if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
546 return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
547
548 // The previous token must introduce an operand location where regex
549 // literals can occur.
550 if (!precedesOperand(Prev))
551 return false;
552
553 return true;
554 }
555
556 // Tries to parse a JavaScript Regex literal starting at the current token,
557 // if that begins with a slash and is in a location where JavaScript allows
558 // regex literals. Changes the current token to a regex literal and updates
559 // its text if successful.
tryParseJSRegexLiteral()560 void FormatTokenLexer::tryParseJSRegexLiteral() {
561 FormatToken *RegexToken = Tokens.back();
562 if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
563 return;
564
565 FormatToken *Prev = nullptr;
566 for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
567 // NB: Because previous pointers are not initialized yet, this cannot use
568 // Token.getPreviousNonComment.
569 if (FT->isNot(tok::comment)) {
570 Prev = FT;
571 break;
572 }
573 }
574
575 if (!canPrecedeRegexLiteral(Prev))
576 return;
577
578 // 'Manually' lex ahead in the current file buffer.
579 const char *Offset = Lex->getBufferLocation();
580 const char *RegexBegin = Offset - RegexToken->TokenText.size();
581 StringRef Buffer = Lex->getBuffer();
582 bool InCharacterClass = false;
583 bool HaveClosingSlash = false;
584 for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
585 // Regular expressions are terminated with a '/', which can only be
586 // escaped using '\' or a character class between '[' and ']'.
587 // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
588 switch (*Offset) {
589 case '\\':
590 // Skip the escaped character.
591 ++Offset;
592 break;
593 case '[':
594 InCharacterClass = true;
595 break;
596 case ']':
597 InCharacterClass = false;
598 break;
599 case '/':
600 if (!InCharacterClass)
601 HaveClosingSlash = true;
602 break;
603 }
604 }
605
606 RegexToken->setType(TT_RegexLiteral);
607 // Treat regex literals like other string_literals.
608 RegexToken->Tok.setKind(tok::string_literal);
609 RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
610 RegexToken->ColumnWidth = RegexToken->TokenText.size();
611
612 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
613 }
614
lexCSharpString(const char * Begin,const char * End,bool Verbatim,bool Interpolated)615 static auto lexCSharpString(const char *Begin, const char *End, bool Verbatim,
616 bool Interpolated) {
617 auto Repeated = [&Begin, End]() {
618 return Begin + 1 < End && Begin[1] == Begin[0];
619 };
620
621 // Look for a terminating '"' in the current file buffer.
622 // Make no effort to format code within an interpolated or verbatim string.
623 //
624 // Interpolated strings could contain { } with " characters inside.
625 // $"{x ?? "null"}"
626 // should not be split into $"{x ?? ", null, "}" but should be treated as a
627 // single string-literal.
628 //
629 // We opt not to try and format expressions inside {} within a C#
630 // interpolated string. Formatting expressions within an interpolated string
631 // would require similar work as that done for JavaScript template strings
632 // in `handleTemplateStrings()`.
633 for (int UnmatchedOpeningBraceCount = 0; Begin < End; ++Begin) {
634 switch (*Begin) {
635 case '\\':
636 if (!Verbatim)
637 ++Begin;
638 break;
639 case '{':
640 if (Interpolated) {
641 // {{ inside an interpolated string is escaped, so skip it.
642 if (Repeated())
643 ++Begin;
644 else
645 ++UnmatchedOpeningBraceCount;
646 }
647 break;
648 case '}':
649 if (Interpolated) {
650 // }} inside an interpolated string is escaped, so skip it.
651 if (Repeated())
652 ++Begin;
653 else if (UnmatchedOpeningBraceCount > 0)
654 --UnmatchedOpeningBraceCount;
655 else
656 return End;
657 }
658 break;
659 case '"':
660 if (UnmatchedOpeningBraceCount > 0)
661 break;
662 // "" within a verbatim string is an escaped double quote: skip it.
663 if (Verbatim && Repeated()) {
664 ++Begin;
665 break;
666 }
667 return Begin;
668 }
669 }
670
671 return End;
672 }
673
handleCSharpVerbatimAndInterpolatedStrings()674 void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
675 FormatToken *CSharpStringLiteral = Tokens.back();
676
677 if (CSharpStringLiteral->isNot(TT_CSharpStringLiteral))
678 return;
679
680 auto &TokenText = CSharpStringLiteral->TokenText;
681
682 bool Verbatim = false;
683 bool Interpolated = false;
684 if (TokenText.startswith(R"($@")") || TokenText.startswith(R"(@$")")) {
685 Verbatim = true;
686 Interpolated = true;
687 } else if (TokenText.startswith(R"(@")")) {
688 Verbatim = true;
689 } else if (TokenText.startswith(R"($")")) {
690 Interpolated = true;
691 }
692
693 // Deal with multiline strings.
694 if (!Verbatim && !Interpolated)
695 return;
696
697 const char *StrBegin = Lex->getBufferLocation() - TokenText.size();
698 const char *Offset = StrBegin;
699 if (Verbatim && Interpolated)
700 Offset += 3;
701 else
702 Offset += 2;
703
704 const auto End = Lex->getBuffer().end();
705 Offset = lexCSharpString(Offset, End, Verbatim, Interpolated);
706
707 // Make no attempt to format code properly if a verbatim string is
708 // unterminated.
709 if (Offset >= End)
710 return;
711
712 StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
713 TokenText = LiteralText;
714
715 // Adjust width for potentially multiline string literals.
716 size_t FirstBreak = LiteralText.find('\n');
717 StringRef FirstLineText = FirstBreak == StringRef::npos
718 ? LiteralText
719 : LiteralText.substr(0, FirstBreak);
720 CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
721 FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
722 Encoding);
723 size_t LastBreak = LiteralText.rfind('\n');
724 if (LastBreak != StringRef::npos) {
725 CSharpStringLiteral->IsMultiline = true;
726 unsigned StartColumn = 0;
727 CSharpStringLiteral->LastLineColumnWidth =
728 encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
729 StartColumn, Style.TabWidth, Encoding);
730 }
731
732 assert(Offset < End);
733 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
734 }
735
handleTemplateStrings()736 void FormatTokenLexer::handleTemplateStrings() {
737 FormatToken *BacktickToken = Tokens.back();
738
739 if (BacktickToken->is(tok::l_brace)) {
740 StateStack.push(LexerState::NORMAL);
741 return;
742 }
743 if (BacktickToken->is(tok::r_brace)) {
744 if (StateStack.size() == 1)
745 return;
746 StateStack.pop();
747 if (StateStack.top() != LexerState::TEMPLATE_STRING)
748 return;
749 // If back in TEMPLATE_STRING, fallthrough and continue parsing the
750 } else if (BacktickToken->is(tok::unknown) &&
751 BacktickToken->TokenText == "`") {
752 StateStack.push(LexerState::TEMPLATE_STRING);
753 } else {
754 return; // Not actually a template
755 }
756
757 // 'Manually' lex ahead in the current file buffer.
758 const char *Offset = Lex->getBufferLocation();
759 const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
760 for (; Offset != Lex->getBuffer().end(); ++Offset) {
761 if (Offset[0] == '`') {
762 StateStack.pop();
763 ++Offset;
764 break;
765 }
766 if (Offset[0] == '\\') {
767 ++Offset; // Skip the escaped character.
768 } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
769 Offset[1] == '{') {
770 // '${' introduces an expression interpolation in the template string.
771 StateStack.push(LexerState::NORMAL);
772 Offset += 2;
773 break;
774 }
775 }
776
777 StringRef LiteralText(TmplBegin, Offset - TmplBegin);
778 BacktickToken->setType(TT_TemplateString);
779 BacktickToken->Tok.setKind(tok::string_literal);
780 BacktickToken->TokenText = LiteralText;
781
782 // Adjust width for potentially multiline string literals.
783 size_t FirstBreak = LiteralText.find('\n');
784 StringRef FirstLineText = FirstBreak == StringRef::npos
785 ? LiteralText
786 : LiteralText.substr(0, FirstBreak);
787 BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
788 FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
789 size_t LastBreak = LiteralText.rfind('\n');
790 if (LastBreak != StringRef::npos) {
791 BacktickToken->IsMultiline = true;
792 unsigned StartColumn = 0; // The template tail spans the entire line.
793 BacktickToken->LastLineColumnWidth =
794 encoding::columnWidthWithTabs(LiteralText.substr(LastBreak + 1),
795 StartColumn, Style.TabWidth, Encoding);
796 }
797
798 SourceLocation loc = Lex->getSourceLocation(Offset);
799 resetLexer(SourceMgr.getFileOffset(loc));
800 }
801
tryParsePythonComment()802 void FormatTokenLexer::tryParsePythonComment() {
803 FormatToken *HashToken = Tokens.back();
804 if (!HashToken->isOneOf(tok::hash, tok::hashhash))
805 return;
806 // Turn the remainder of this line into a comment.
807 const char *CommentBegin =
808 Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
809 size_t From = CommentBegin - Lex->getBuffer().begin();
810 size_t To = Lex->getBuffer().find_first_of('\n', From);
811 if (To == StringRef::npos)
812 To = Lex->getBuffer().size();
813 size_t Len = To - From;
814 HashToken->setType(TT_LineComment);
815 HashToken->Tok.setKind(tok::comment);
816 HashToken->TokenText = Lex->getBuffer().substr(From, Len);
817 SourceLocation Loc = To < Lex->getBuffer().size()
818 ? Lex->getSourceLocation(CommentBegin + Len)
819 : SourceMgr.getLocForEndOfFile(ID);
820 resetLexer(SourceMgr.getFileOffset(Loc));
821 }
822
tryMerge_TMacro()823 bool FormatTokenLexer::tryMerge_TMacro() {
824 if (Tokens.size() < 4)
825 return false;
826 FormatToken *Last = Tokens.back();
827 if (!Last->is(tok::r_paren))
828 return false;
829
830 FormatToken *String = Tokens[Tokens.size() - 2];
831 if (!String->is(tok::string_literal) || String->IsMultiline)
832 return false;
833
834 if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
835 return false;
836
837 FormatToken *Macro = Tokens[Tokens.size() - 4];
838 if (Macro->TokenText != "_T")
839 return false;
840
841 const char *Start = Macro->TokenText.data();
842 const char *End = Last->TokenText.data() + Last->TokenText.size();
843 String->TokenText = StringRef(Start, End - Start);
844 String->IsFirst = Macro->IsFirst;
845 String->LastNewlineOffset = Macro->LastNewlineOffset;
846 String->WhitespaceRange = Macro->WhitespaceRange;
847 String->OriginalColumn = Macro->OriginalColumn;
848 String->ColumnWidth = encoding::columnWidthWithTabs(
849 String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
850 String->NewlinesBefore = Macro->NewlinesBefore;
851 String->HasUnescapedNewline = Macro->HasUnescapedNewline;
852
853 Tokens.pop_back();
854 Tokens.pop_back();
855 Tokens.pop_back();
856 Tokens.back() = String;
857 if (FirstInLineIndex >= Tokens.size())
858 FirstInLineIndex = Tokens.size() - 1;
859 return true;
860 }
861
tryMergeConflictMarkers()862 bool FormatTokenLexer::tryMergeConflictMarkers() {
863 if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
864 return false;
865
866 // Conflict lines look like:
867 // <marker> <text from the vcs>
868 // For example:
869 // >>>>>>> /file/in/file/system at revision 1234
870 //
871 // We merge all tokens in a line that starts with a conflict marker
872 // into a single token with a special token type that the unwrapped line
873 // parser will use to correctly rebuild the underlying code.
874
875 FileID ID;
876 // Get the position of the first token in the line.
877 unsigned FirstInLineOffset;
878 std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
879 Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
880 StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
881 // Calculate the offset of the start of the current line.
882 auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
883 if (LineOffset == StringRef::npos)
884 LineOffset = 0;
885 else
886 ++LineOffset;
887
888 auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
889 StringRef LineStart;
890 if (FirstSpace == StringRef::npos)
891 LineStart = Buffer.substr(LineOffset);
892 else
893 LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
894
895 TokenType Type = TT_Unknown;
896 if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
897 Type = TT_ConflictStart;
898 } else if (LineStart == "|||||||" || LineStart == "=======" ||
899 LineStart == "====") {
900 Type = TT_ConflictAlternative;
901 } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
902 Type = TT_ConflictEnd;
903 }
904
905 if (Type != TT_Unknown) {
906 FormatToken *Next = Tokens.back();
907
908 Tokens.resize(FirstInLineIndex + 1);
909 // We do not need to build a complete token here, as we will skip it
910 // during parsing anyway (as we must not touch whitespace around conflict
911 // markers).
912 Tokens.back()->setType(Type);
913 Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
914
915 Tokens.push_back(Next);
916 return true;
917 }
918
919 return false;
920 }
921
getStashedToken()922 FormatToken *FormatTokenLexer::getStashedToken() {
923 // Create a synthesized second '>' or '<' token.
924 Token Tok = FormatTok->Tok;
925 StringRef TokenText = FormatTok->TokenText;
926
927 unsigned OriginalColumn = FormatTok->OriginalColumn;
928 FormatTok = new (Allocator.Allocate()) FormatToken;
929 FormatTok->Tok = Tok;
930 SourceLocation TokLocation =
931 FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
932 FormatTok->Tok.setLocation(TokLocation);
933 FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
934 FormatTok->TokenText = TokenText;
935 FormatTok->ColumnWidth = 1;
936 FormatTok->OriginalColumn = OriginalColumn + 1;
937
938 return FormatTok;
939 }
940
941 /// Truncate the current token to the new length and make the lexer continue
942 /// from the end of the truncated token. Used for other languages that have
943 /// different token boundaries, like JavaScript in which a comment ends at a
944 /// line break regardless of whether the line break follows a backslash. Also
945 /// used to set the lexer to the end of whitespace if the lexer regards
946 /// whitespace and an unrecognized symbol as one token.
truncateToken(size_t NewLen)947 void FormatTokenLexer::truncateToken(size_t NewLen) {
948 assert(NewLen <= FormatTok->TokenText.size());
949 resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(
950 Lex->getBufferLocation() - FormatTok->TokenText.size() + NewLen)));
951 FormatTok->TokenText = FormatTok->TokenText.substr(0, NewLen);
952 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
953 FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
954 Encoding);
955 FormatTok->Tok.setLength(NewLen);
956 }
957
958 /// Count the length of leading whitespace in a token.
countLeadingWhitespace(StringRef Text)959 static size_t countLeadingWhitespace(StringRef Text) {
960 // Basically counting the length matched by this regex.
961 // "^([\n\r\f\v \t]|(\\\\|\\?\\?/)[\n\r])+"
962 // Directly using the regex turned out to be slow. With the regex
963 // version formatting all files in this directory took about 1.25
964 // seconds. This version took about 0.5 seconds.
965 const unsigned char *const Begin = Text.bytes_begin();
966 const unsigned char *const End = Text.bytes_end();
967 const unsigned char *Cur = Begin;
968 while (Cur < End) {
969 if (isspace(Cur[0])) {
970 ++Cur;
971 } else if (Cur[0] == '\\' && (Cur[1] == '\n' || Cur[1] == '\r')) {
972 // A '\' followed by a newline always escapes the newline, regardless
973 // of whether there is another '\' before it.
974 // The source has a null byte at the end. So the end of the entire input
975 // isn't reached yet. Also the lexer doesn't break apart an escaped
976 // newline.
977 assert(End - Cur >= 2);
978 Cur += 2;
979 } else if (Cur[0] == '?' && Cur[1] == '?' && Cur[2] == '/' &&
980 (Cur[3] == '\n' || Cur[3] == '\r')) {
981 // Newlines can also be escaped by a '?' '?' '/' trigraph. By the way, the
982 // characters are quoted individually in this comment because if we write
983 // them together some compilers warn that we have a trigraph in the code.
984 assert(End - Cur >= 4);
985 Cur += 4;
986 } else {
987 break;
988 }
989 }
990 return Cur - Begin;
991 }
992
getNextToken()993 FormatToken *FormatTokenLexer::getNextToken() {
994 if (StateStack.top() == LexerState::TOKEN_STASHED) {
995 StateStack.pop();
996 return getStashedToken();
997 }
998
999 FormatTok = new (Allocator.Allocate()) FormatToken;
1000 readRawToken(*FormatTok);
1001 SourceLocation WhitespaceStart =
1002 FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
1003 FormatTok->IsFirst = IsFirstToken;
1004 IsFirstToken = false;
1005
1006 // Consume and record whitespace until we find a significant token.
1007 // Some tok::unknown tokens are not just whitespace, e.g. whitespace
1008 // followed by a symbol such as backtick. Those symbols may be
1009 // significant in other languages.
1010 unsigned WhitespaceLength = TrailingWhitespace;
1011 while (FormatTok->isNot(tok::eof)) {
1012 auto LeadingWhitespace = countLeadingWhitespace(FormatTok->TokenText);
1013 if (LeadingWhitespace == 0)
1014 break;
1015 if (LeadingWhitespace < FormatTok->TokenText.size())
1016 truncateToken(LeadingWhitespace);
1017 StringRef Text = FormatTok->TokenText;
1018 bool InEscape = false;
1019 for (int i = 0, e = Text.size(); i != e; ++i) {
1020 switch (Text[i]) {
1021 case '\r':
1022 // If this is a CRLF sequence, break here and the LF will be handled on
1023 // the next loop iteration. Otherwise, this is a single Mac CR, treat it
1024 // the same as a single LF.
1025 if (i + 1 < e && Text[i + 1] == '\n')
1026 break;
1027 [[fallthrough]];
1028 case '\n':
1029 ++FormatTok->NewlinesBefore;
1030 if (!InEscape)
1031 FormatTok->HasUnescapedNewline = true;
1032 else
1033 InEscape = false;
1034 FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
1035 Column = 0;
1036 break;
1037 case '\f':
1038 case '\v':
1039 Column = 0;
1040 break;
1041 case ' ':
1042 ++Column;
1043 break;
1044 case '\t':
1045 Column +=
1046 Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
1047 break;
1048 case '\\':
1049 case '?':
1050 case '/':
1051 // The text was entirely whitespace when this loop was entered. Thus
1052 // this has to be an escape sequence.
1053 assert(Text.substr(i, 2) == "\\\r" || Text.substr(i, 2) == "\\\n" ||
1054 Text.substr(i, 4) == "\?\?/\r" ||
1055 Text.substr(i, 4) == "\?\?/\n" ||
1056 (i >= 1 && (Text.substr(i - 1, 4) == "\?\?/\r" ||
1057 Text.substr(i - 1, 4) == "\?\?/\n")) ||
1058 (i >= 2 && (Text.substr(i - 2, 4) == "\?\?/\r" ||
1059 Text.substr(i - 2, 4) == "\?\?/\n")));
1060 InEscape = true;
1061 break;
1062 default:
1063 // This shouldn't happen.
1064 assert(false);
1065 break;
1066 }
1067 }
1068 WhitespaceLength += Text.size();
1069 readRawToken(*FormatTok);
1070 }
1071
1072 if (FormatTok->is(tok::unknown))
1073 FormatTok->setType(TT_ImplicitStringLiteral);
1074
1075 // JavaScript and Java do not allow to escape the end of the line with a
1076 // backslash. Backslashes are syntax errors in plain source, but can occur in
1077 // comments. When a single line comment ends with a \, it'll cause the next
1078 // line of code to be lexed as a comment, breaking formatting. The code below
1079 // finds comments that contain a backslash followed by a line break, truncates
1080 // the comment token at the backslash, and resets the lexer to restart behind
1081 // the backslash.
1082 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
1083 FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
1084 size_t BackslashPos = FormatTok->TokenText.find('\\');
1085 while (BackslashPos != StringRef::npos) {
1086 if (BackslashPos + 1 < FormatTok->TokenText.size() &&
1087 FormatTok->TokenText[BackslashPos + 1] == '\n') {
1088 truncateToken(BackslashPos + 1);
1089 break;
1090 }
1091 BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
1092 }
1093 }
1094
1095 if (Style.isVerilog()) {
1096 static const llvm::Regex NumberBase("^s?[bdho]", llvm::Regex::IgnoreCase);
1097 SmallVector<StringRef, 1> Matches;
1098 // Verilog uses the backtick instead of the hash for preprocessor stuff.
1099 // And it uses the hash for delays and parameter lists. In order to continue
1100 // using `tok::hash` in other places, the backtick gets marked as the hash
1101 // here. And in order to tell the backtick and hash apart for
1102 // Verilog-specific stuff, the hash becomes an identifier.
1103 if (FormatTok->is(tok::numeric_constant)) {
1104 // In Verilog the quote is not part of a number.
1105 auto Quote = FormatTok->TokenText.find('\'');
1106 if (Quote != StringRef::npos)
1107 truncateToken(Quote);
1108 } else if (FormatTok->isOneOf(tok::hash, tok::hashhash)) {
1109 FormatTok->Tok.setKind(tok::raw_identifier);
1110 } else if (FormatTok->is(tok::raw_identifier)) {
1111 if (FormatTok->TokenText == "`") {
1112 FormatTok->Tok.setIdentifierInfo(nullptr);
1113 FormatTok->Tok.setKind(tok::hash);
1114 } else if (FormatTok->TokenText == "``") {
1115 FormatTok->Tok.setIdentifierInfo(nullptr);
1116 FormatTok->Tok.setKind(tok::hashhash);
1117 } else if (Tokens.size() > 0 &&
1118 Tokens.back()->is(Keywords.kw_apostrophe) &&
1119 NumberBase.match(FormatTok->TokenText, &Matches)) {
1120 // In Verilog in a based number literal like `'b10`, there may be
1121 // whitespace between `'b` and `10`. Therefore we handle the base and
1122 // the rest of the number literal as two tokens. But if there is no
1123 // space in the input code, we need to manually separate the two parts.
1124 truncateToken(Matches[0].size());
1125 FormatTok->setFinalizedType(TT_VerilogNumberBase);
1126 }
1127 }
1128 }
1129
1130 FormatTok->WhitespaceRange = SourceRange(
1131 WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
1132
1133 FormatTok->OriginalColumn = Column;
1134
1135 TrailingWhitespace = 0;
1136 if (FormatTok->is(tok::comment)) {
1137 // FIXME: Add the trimmed whitespace to Column.
1138 StringRef UntrimmedText = FormatTok->TokenText;
1139 FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
1140 TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
1141 } else if (FormatTok->is(tok::raw_identifier)) {
1142 IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
1143 FormatTok->Tok.setIdentifierInfo(&Info);
1144 FormatTok->Tok.setKind(Info.getTokenID());
1145 if (Style.Language == FormatStyle::LK_Java &&
1146 FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
1147 tok::kw_operator)) {
1148 FormatTok->Tok.setKind(tok::identifier);
1149 FormatTok->Tok.setIdentifierInfo(nullptr);
1150 } else if (Style.isJavaScript() &&
1151 FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
1152 tok::kw_operator)) {
1153 FormatTok->Tok.setKind(tok::identifier);
1154 FormatTok->Tok.setIdentifierInfo(nullptr);
1155 }
1156 } else if (FormatTok->is(tok::greatergreater)) {
1157 FormatTok->Tok.setKind(tok::greater);
1158 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1159 ++Column;
1160 StateStack.push(LexerState::TOKEN_STASHED);
1161 } else if (FormatTok->is(tok::lessless)) {
1162 FormatTok->Tok.setKind(tok::less);
1163 FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
1164 ++Column;
1165 StateStack.push(LexerState::TOKEN_STASHED);
1166 }
1167
1168 if (Style.isVerilog() && Tokens.size() > 0 &&
1169 Tokens.back()->is(TT_VerilogNumberBase) &&
1170 FormatTok->Tok.isOneOf(tok::identifier, tok::question)) {
1171 // Mark the number following a base like `'h?a0` as a number.
1172 FormatTok->Tok.setKind(tok::numeric_constant);
1173 }
1174
1175 // Now FormatTok is the next non-whitespace token.
1176
1177 StringRef Text = FormatTok->TokenText;
1178 size_t FirstNewlinePos = Text.find('\n');
1179 if (FirstNewlinePos == StringRef::npos) {
1180 // FIXME: ColumnWidth actually depends on the start column, we need to
1181 // take this into account when the token is moved.
1182 FormatTok->ColumnWidth =
1183 encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
1184 Column += FormatTok->ColumnWidth;
1185 } else {
1186 FormatTok->IsMultiline = true;
1187 // FIXME: ColumnWidth actually depends on the start column, we need to
1188 // take this into account when the token is moved.
1189 FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
1190 Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
1191
1192 // The last line of the token always starts in column 0.
1193 // Thus, the length can be precomputed even in the presence of tabs.
1194 FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
1195 Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
1196 Column = FormatTok->LastLineColumnWidth;
1197 }
1198
1199 if (Style.isCpp()) {
1200 auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
1201 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
1202 Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
1203 tok::pp_define) &&
1204 it != Macros.end()) {
1205 FormatTok->setType(it->second);
1206 if (it->second == TT_IfMacro) {
1207 // The lexer token currently has type tok::kw_unknown. However, for this
1208 // substitution to be treated correctly in the TokenAnnotator, faking
1209 // the tok value seems to be needed. Not sure if there's a more elegant
1210 // way.
1211 FormatTok->Tok.setKind(tok::kw_if);
1212 }
1213 } else if (FormatTok->is(tok::identifier)) {
1214 if (MacroBlockBeginRegex.match(Text))
1215 FormatTok->setType(TT_MacroBlockBegin);
1216 else if (MacroBlockEndRegex.match(Text))
1217 FormatTok->setType(TT_MacroBlockEnd);
1218 }
1219 }
1220
1221 return FormatTok;
1222 }
1223
readRawTokenVerilogSpecific(Token & Tok)1224 bool FormatTokenLexer::readRawTokenVerilogSpecific(Token &Tok) {
1225 // In Verilog the quote is not a character literal.
1226 //
1227 // Make the backtick and double backtick identifiers to match against them
1228 // more easily.
1229 //
1230 // In Verilog an escaped identifier starts with backslash and ends with
1231 // whitespace. Unless that whitespace is an escaped newline. A backslash can
1232 // also begin an escaped newline outside of an escaped identifier. We check
1233 // for that outside of the Regex since we can't use negative lookhead
1234 // assertions. Simply changing the '*' to '+' breaks stuff as the escaped
1235 // identifier may have a length of 0 according to Section A.9.3.
1236 // FIXME: If there is an escaped newline in the middle of an escaped
1237 // identifier, allow for pasting the two lines together, But escaped
1238 // identifiers usually occur only in generated code anyway.
1239 static const llvm::Regex VerilogToken(R"re(^('|``?|\\(\\)re"
1240 "(\r?\n|\r)|[^[:space:]])*)");
1241
1242 SmallVector<StringRef, 4> Matches;
1243 const char *Start = Lex->getBufferLocation();
1244 if (!VerilogToken.match(StringRef(Start, Lex->getBuffer().end() - Start),
1245 &Matches)) {
1246 return false;
1247 }
1248 // There is a null byte at the end of the buffer, so we don't have to check
1249 // Start[1] is within the buffer.
1250 if (Start[0] == '\\' && (Start[1] == '\r' || Start[1] == '\n'))
1251 return false;
1252 size_t Len = Matches[0].size();
1253
1254 // The kind has to be an identifier so we can match it against those defined
1255 // in Keywords. The kind has to be set before the length because the setLength
1256 // function checks that the kind is not an annotation.
1257 Tok.setKind(tok::raw_identifier);
1258 Tok.setLength(Len);
1259 Tok.setLocation(Lex->getSourceLocation(Start, Len));
1260 Tok.setRawIdentifierData(Start);
1261 Lex->seek(Lex->getCurrentBufferOffset() + Len, /*IsAtStartofline=*/false);
1262 return true;
1263 }
1264
readRawToken(FormatToken & Tok)1265 void FormatTokenLexer::readRawToken(FormatToken &Tok) {
1266 // For Verilog, first see if there is a special token, and fall back to the
1267 // normal lexer if there isn't one.
1268 if (!Style.isVerilog() || !readRawTokenVerilogSpecific(Tok.Tok))
1269 Lex->LexFromRawLexer(Tok.Tok);
1270 Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
1271 Tok.Tok.getLength());
1272 // For formatting, treat unterminated string literals like normal string
1273 // literals.
1274 if (Tok.is(tok::unknown)) {
1275 if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
1276 Tok.Tok.setKind(tok::string_literal);
1277 Tok.IsUnterminatedLiteral = true;
1278 } else if (Style.isJavaScript() && Tok.TokenText == "''") {
1279 Tok.Tok.setKind(tok::string_literal);
1280 }
1281 }
1282
1283 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto ||
1284 Style.Language == FormatStyle::LK_TextProto) &&
1285 Tok.is(tok::char_constant)) {
1286 Tok.Tok.setKind(tok::string_literal);
1287 }
1288
1289 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
1290 Tok.TokenText == "/* clang-format on */")) {
1291 FormattingDisabled = false;
1292 }
1293
1294 Tok.Finalized = FormattingDisabled;
1295
1296 if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
1297 Tok.TokenText == "/* clang-format off */")) {
1298 FormattingDisabled = true;
1299 }
1300 }
1301
resetLexer(unsigned Offset)1302 void FormatTokenLexer::resetLexer(unsigned Offset) {
1303 StringRef Buffer = SourceMgr.getBufferData(ID);
1304 LangOpts = getFormattingLangOpts(Style);
1305 Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID), LangOpts,
1306 Buffer.begin(), Buffer.begin() + Offset, Buffer.end()));
1307 Lex->SetKeepWhitespaceMode(true);
1308 TrailingWhitespace = 0;
1309 }
1310
1311 } // namespace format
1312 } // namespace clang
1313