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

source code of clang/lib/Format/FormatTokenLexer.cpp