clang 24.0.0git
UnwrappedLineParser.cpp
Go to the documentation of this file.
1//===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
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 contains the implementation of the UnwrappedLineParser,
11/// which turns a stream of tokens into UnwrappedLines.
12///
13//===----------------------------------------------------------------------===//
14
15#include "UnwrappedLineParser.h"
16#include "FormatToken.h"
17#include "FormatTokenSource.h"
18#include "Macros.h"
19#include "TokenAnnotator.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_os_ostream.h"
25#include "llvm/Support/raw_ostream.h"
26
27#include <utility>
28
29#define DEBUG_TYPE "format-parser"
30
31namespace clang {
32namespace format {
33
34namespace {
35
36void printLine(llvm::raw_ostream &OS, const UnwrappedLine &Line,
37 StringRef Prefix = "", bool PrintText = false) {
38 OS << Prefix << "Line(" << Line.Level << ", FSC=" << Line.FirstStartColumn
39 << ")" << (Line.InPPDirective ? " MACRO" : "") << ": ";
40 bool NewLine = false;
41 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
42 E = Line.Tokens.end();
43 I != E; ++I) {
44 if (NewLine) {
45 OS << Prefix;
46 NewLine = false;
47 }
48 OS << I->Tok->Tok.getName() << "["
49 << "T=" << (unsigned)I->Tok->getType()
50 << ", OC=" << I->Tok->OriginalColumn << ", \"" << I->Tok->TokenText
51 << "\"] ";
52 for (const auto *CI = I->Children.begin(), *CE = I->Children.end();
53 CI != CE; ++CI) {
54 OS << "\n";
55 printLine(OS, *CI, (Prefix + " ").str());
56 NewLine = true;
57 }
58 }
59 if (!NewLine)
60 OS << "\n";
61}
62
63[[maybe_unused]] static void printDebugInfo(const UnwrappedLine &Line) {
64 printLine(llvm::dbgs(), Line);
65}
66
67class ScopedDeclarationState {
68public:
69 ScopedDeclarationState(UnwrappedLine &Line, llvm::BitVector &Stack,
70 bool MustBeDeclaration)
71 : Line(Line), Stack(Stack) {
72 Line.MustBeDeclaration = MustBeDeclaration;
73 Stack.push_back(MustBeDeclaration);
74 }
75 ~ScopedDeclarationState() {
76 Stack.pop_back();
77 if (!Stack.empty())
78 Line.MustBeDeclaration = Stack.back();
79 else
80 Line.MustBeDeclaration = true;
81 }
82
83private:
84 UnwrappedLine &Line;
85 llvm::BitVector &Stack;
86};
87
88} // end anonymous namespace
89
90std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line) {
91 llvm::raw_os_ostream OS(Stream);
92 printLine(OS, Line);
93 return Stream;
94}
95
97public:
98 // With \c DiscardLines, the lines added while in scope are discarded.
100 bool SwitchToPreprocessorLines = false,
101 bool DiscardLines = false)
102 : Parser(Parser), OriginalLines(Parser.CurrentLines),
103 DiscardLines(DiscardLines) {
104 if (SwitchToPreprocessorLines)
105 Parser.CurrentLines = &Parser.PreprocessorDirectives;
106 else if (!Parser.Line->Tokens.empty())
107 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
108 OriginalNumLines = Parser.CurrentLines->size();
109 PreBlockLine = std::move(Parser.Line);
110 Parser.Line = std::make_unique<UnwrappedLine>();
111 Parser.Line->Level = PreBlockLine->Level;
112 Parser.Line->PPLevel = PreBlockLine->PPLevel;
113 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
114 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
115 Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
116 }
117
119 if (!Parser.Line->Tokens.empty())
120 Parser.addUnwrappedLine();
121 assert(Parser.Line->Tokens.empty());
122 if (DiscardLines)
123 Parser.CurrentLines->truncate(OriginalNumLines);
124 Parser.Line = std::move(PreBlockLine);
125 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
126 Parser.PP.AtEndOfPPLine = true;
127 Parser.CurrentLines = OriginalLines;
128 }
129
130private:
132
133 std::unique_ptr<UnwrappedLine> PreBlockLine;
134 SmallVectorImpl<UnwrappedLine> *OriginalLines;
135 size_t OriginalNumLines;
136 bool DiscardLines;
137};
138
140public:
142 const FormatStyle &Style, unsigned &LineLevel)
144 Style.BraceWrapping.AfterControlStatement ==
145 FormatStyle::BWACS_Always,
146 Style.BraceWrapping.IndentBraces) {}
148 bool WrapBrace, bool IndentBrace)
149 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
150 if (WrapBrace)
151 Parser->addUnwrappedLine();
152 if (IndentBrace)
153 ++LineLevel;
154 }
155 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
156
157private:
158 unsigned &LineLevel;
159 unsigned OldLineLevel;
160};
161
163 SourceManager &SourceMgr, const FormatStyle &Style,
164 const AdditionalKeywords &Keywords, unsigned FirstStartColumn,
166 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
167 IdentifierTable &IdentTable)
168 : Line(new UnwrappedLine), CurrentLines(&Lines), Style(Style),
169 IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
170 Keywords(Keywords), CommentPragmasRegex(Style.CommentPragmas),
171 Tokens(nullptr), Callback(Callback), AllTokens(Tokens),
172 PP(getIncludeGuardState(Style.IndentPPDirectives)),
173 FirstStartColumn(FirstStartColumn),
174 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
175
176void UnwrappedLineParser::reset() {
177 PP.BranchLevel = -1;
178 PP.IncludeGuard = getIncludeGuardState(Style.IndentPPDirectives);
179 PP.IncludeGuardToken = nullptr;
180 ParsedPPDirectives.clear();
181 Line.reset(new UnwrappedLine);
182 CommentsBeforeNextToken.clear();
183 FormatTok = nullptr;
184 PP.AtEndOfPPLine = false;
185 IsDecltypeAutoFunction = false;
186 PreprocessorDirectives.clear();
187 CurrentLines = &Lines;
188 DeclarationScopeStack.clear();
189 NestedTooDeep.clear();
190 NestedLambdas.clear();
191 PP.Stack.clear();
192 Line->FirstStartColumn = FirstStartColumn;
193
194 if (!Unexpanded.empty())
195 for (FormatToken *Token : AllTokens)
196 Token->MacroCtx.reset();
197 CurrentExpandedLines.clear();
198 ExpandedLines.clear();
199 Unexpanded.clear();
200 InExpansion = false;
201 Reconstruct.reset();
202}
203
205 IndexedTokenSource TokenSource(AllTokens);
206 Line->FirstStartColumn = FirstStartColumn;
207 do {
208 LLVM_DEBUG(llvm::dbgs() << "----\n");
209 reset();
210 Tokens = &TokenSource;
211 TokenSource.reset();
212
213 readToken();
214 parseFile();
215
216 // If we found an include guard then all preprocessor directives (other than
217 // the guard) are over-indented by one.
218 if (PP.IncludeGuard == IG_Found) {
219 for (auto &Line : Lines)
220 if (Line.InPPDirective && Line.Level > 0)
221 --Line.Level;
222 }
223
224 // Create line with eof token.
225 assert(eof());
226 pushToken(FormatTok);
227 addUnwrappedLine();
228
229 // In a first run, format everything with the lines containing macro calls
230 // replaced by the expansion.
231 if (!ExpandedLines.empty()) {
232 LLVM_DEBUG(llvm::dbgs() << "Expanded lines:\n");
233 for (auto &Line : Lines) {
234 if (!Line.Tokens.empty()) {
235 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
236 if (it != ExpandedLines.end()) {
237 for (auto &Expanded : it->second) {
238 Expanded.InMacroExpansion = true;
239 LLVM_DEBUG(printDebugInfo(Expanded));
240 Callback.consumeUnwrappedLine(Expanded);
241 }
242 continue;
243 }
244 }
245 Line.InMacroExpansion = true;
246 LLVM_DEBUG(printDebugInfo(Line));
247 Callback.consumeUnwrappedLine(Line);
248 Line.InMacroExpansion = false;
249 }
250 Callback.finishRun();
251 }
252
253 LLVM_DEBUG(llvm::dbgs() << "Unwrapped lines:\n");
254 for (const UnwrappedLine &Line : Lines) {
255 LLVM_DEBUG(printDebugInfo(Line));
256 Callback.consumeUnwrappedLine(Line);
257 }
258 Callback.finishRun();
259 Lines.clear();
260 while (!PP.LevelBranchIndex.empty() &&
261 PP.LevelBranchIndex.back() + 1 >= PP.LevelBranchCount.back()) {
262 PP.LevelBranchIndex.resize(PP.LevelBranchIndex.size() - 1);
263 PP.LevelBranchCount.resize(PP.LevelBranchCount.size() - 1);
264 }
265 if (!PP.LevelBranchIndex.empty()) {
266 ++PP.LevelBranchIndex.back();
267 assert(PP.LevelBranchIndex.size() == PP.LevelBranchCount.size());
268 assert(PP.LevelBranchIndex.back() <= PP.LevelBranchCount.back());
269 }
270 } while (!PP.LevelBranchIndex.empty());
271}
272
273void UnwrappedLineParser::parseFile() {
274 // The top-level context in a file always has declarations, except for pre-
275 // processor directives and JavaScript files.
276 bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript();
277 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
278 MustBeDeclaration);
279 if (Style.isTextProto() || (Style.isJson() && FormatTok->IsFirst))
280 while (!eof())
281 parseBracedList();
282 else
283 parseLevel();
284 // Make sure to format the remaining tokens.
285 //
286 // LK_TextProto is special since its top-level is parsed as the body of a
287 // braced list, which does not necessarily have natural line separators such
288 // as a semicolon. Comments after the last entry that have been determined to
289 // not belong to that line, as in:
290 // key: value
291 // // endfile comment
292 // do not have a chance to be put on a line of their own until this point.
293 // Here we add this newline before end-of-file comments.
294 if (Style.isTextProto() && !CommentsBeforeNextToken.empty())
295 addUnwrappedLine();
296 flushComments(true);
297 addUnwrappedLine();
298}
299
300void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
301 do {
302 switch (FormatTok->Tok.getKind()) {
303 case tok::l_brace:
304 case tok::semi:
305 return;
306 default:
307 if (FormatTok->is(Keywords.kw_where)) {
308 addUnwrappedLine();
309 nextToken();
310 parseCSharpGenericTypeConstraint();
311 break;
312 }
313 nextToken();
314 break;
315 }
316 } while (!eof());
317}
318
319void UnwrappedLineParser::parseCSharpAttribute() {
320 int UnpairedSquareBrackets = 1;
321 do {
322 switch (FormatTok->Tok.getKind()) {
323 case tok::r_square:
324 nextToken();
325 --UnpairedSquareBrackets;
326 if (UnpairedSquareBrackets == 0) {
327 addUnwrappedLine();
328 return;
329 }
330 break;
331 case tok::l_square:
332 ++UnpairedSquareBrackets;
333 nextToken();
334 break;
335 default:
336 nextToken();
337 break;
338 }
339 } while (!eof());
340}
341
342bool UnwrappedLineParser::precededByCommentOrPPDirective() const {
343 if (!Lines.empty() && Lines.back().InPPDirective)
344 return true;
345
346 const FormatToken *Previous = Tokens->getPreviousToken();
347 return Previous && Previous->is(tok::comment) &&
348 (Previous->IsMultiline || Previous->NewlinesBefore > 0);
349}
350
351/// Parses a level, that is ???.
352/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level.
353/// \param IfKind The \p if statement kind in the level.
354/// \param IfLeftBrace The left brace of the \p if block in the level.
355/// \returns true if a simple block of if/else/for/while, or false otherwise.
356/// (A simple block has a single statement.)
357bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
358 IfStmtKind *IfKind,
359 FormatToken **IfLeftBrace,
360 bool *SeenExplicitAccessModifier) {
361 const bool InRequiresExpression =
362 OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
363 const bool IsPrecededByCommentOrPPDirective =
364 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
365 FormatToken *IfLBrace = nullptr;
366 bool HasDoWhile = false;
367 bool HasLabel = false;
368 unsigned StatementCount = 0;
369 bool SwitchLabelEncountered = false;
370
371 do {
372 if (FormatTok->isAttribute()) {
373 nextToken();
374 if (FormatTok->is(tok::l_paren))
375 parseParens();
376 continue;
377 }
378 tok::TokenKind Kind = FormatTok->Tok.getKind();
379 if (FormatTok->is(TT_MacroBlockBegin))
380 Kind = tok::l_brace;
381 else if (FormatTok->is(TT_MacroBlockEnd))
382 Kind = tok::r_brace;
383
384 auto ParseDefault = [this, OpeningBrace, IfKind, &IfLBrace, &HasDoWhile,
385 &HasLabel, &StatementCount,
386 SeenExplicitAccessModifier] {
387 if (SeenExplicitAccessModifier && !*SeenExplicitAccessModifier) {
388 const bool IsQtAccessLabel =
389 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
390 Keywords.kw_slots, Keywords.kw_qslots) &&
391 Tokens->peekNextToken(/*SkipComment=*/true)->is(tok::colon);
392 if (FormatTok->isAccessSpecifierKeyword() || IsQtAccessLabel) {
393 ++Line->Level;
394 *SeenExplicitAccessModifier = true;
395 }
396 }
397 parseStructuralElement(OpeningBrace, IfKind, &IfLBrace,
398 HasDoWhile ? nullptr : &HasDoWhile,
399 HasLabel ? nullptr : &HasLabel);
400 ++StatementCount;
401 assert(StatementCount > 0 && "StatementCount overflow!");
402 };
403
404 switch (Kind) {
405 case tok::comment:
406 nextToken();
407 addUnwrappedLine();
408 break;
409 case tok::l_brace:
410 if (InRequiresExpression) {
411 FormatTok->setFinalizedType(TT_CompoundRequirementLBrace);
412 } else if (FormatTok->Previous &&
413 FormatTok->Previous->ClosesRequiresClause) {
414 // We need the 'default' case here to correctly parse a function
415 // l_brace.
416 ParseDefault();
417 continue;
418 }
419 if (!InRequiresExpression && FormatTok->isNot(TT_MacroBlockBegin)) {
420 if (tryToParseBracedList())
421 continue;
422 FormatTok->setFinalizedType(TT_BlockLBrace);
423 }
424 parseBlock();
425 ++StatementCount;
426 assert(StatementCount > 0 && "StatementCount overflow!");
427 addUnwrappedLine();
428 break;
429 case tok::r_brace:
430 if (OpeningBrace) {
431 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
432 OpeningBrace->isNoneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
433 return false;
434 }
435 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
436 HasDoWhile || IsPrecededByCommentOrPPDirective ||
437 precededByCommentOrPPDirective()) {
438 return false;
439 }
440 const FormatToken *Next = Tokens->peekNextToken();
441 if (Next->is(tok::comment) && Next->NewlinesBefore == 0)
442 return false;
443 if (IfLeftBrace)
444 *IfLeftBrace = IfLBrace;
445 return true;
446 }
447 nextToken();
448 addUnwrappedLine();
449 break;
450 case tok::kw_default: {
451 unsigned StoredPosition = Tokens->getPosition();
452 auto *Next = Tokens->getNextNonComment();
453 FormatTok = Tokens->setPosition(StoredPosition);
454 if (Next->isNoneOf(tok::colon, tok::arrow)) {
455 // default not followed by `:` or `->` is not a case label; treat it
456 // like an identifier.
457 parseStructuralElement();
458 break;
459 }
460 // Else, if it is 'default:', fall through to the case handling.
461 [[fallthrough]];
462 }
463 case tok::kw_case:
464 if (Style.Language == FormatStyle::LK_Proto || Style.isVerilog() ||
465 (Style.isJavaScript() && Line->MustBeDeclaration)) {
466 // Proto: there are no switch/case statements
467 // Verilog: Case labels don't have this word. We handle case
468 // labels including default in TokenAnnotator.
469 // JavaScript: A 'case: string' style field declaration.
470 ParseDefault();
471 break;
472 }
473 if (!SwitchLabelEncountered &&
474 (Style.IndentCaseLabels ||
475 (OpeningBrace && OpeningBrace->is(TT_SwitchExpressionLBrace)) ||
476 (Line->InPPDirective && Line->Level == 1))) {
477 ++Line->Level;
478 }
479 SwitchLabelEncountered = true;
480 parseStructuralElement();
481 break;
482 case tok::l_square:
483 if (Style.isCSharp()) {
484 nextToken();
485 parseCSharpAttribute();
486 break;
487 }
488 if (handleCppAttributes())
489 break;
490 [[fallthrough]];
491 default:
492 ParseDefault();
493 break;
494 }
495 } while (!eof());
496
497 return false;
498}
499
500void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
501 // We'll parse forward through the tokens until we hit
502 // a closing brace or eof - note that getNextToken() will
503 // parse macros, so this will magically work inside macro
504 // definitions, too.
505 unsigned StoredPosition = Tokens->getPosition();
506 FormatToken *Tok = FormatTok;
507 const FormatToken *PrevTok = Tok->Previous;
508 // Keep a stack of positions of lbrace tokens. We will
509 // update information about whether an lbrace starts a
510 // braced init list or a different block during the loop.
511 struct StackEntry {
513 const FormatToken *PrevTok;
514 };
515 SmallVector<StackEntry, 8> LBraceStack;
516 assert(Tok->is(tok::l_brace));
517
518 do {
519 auto *NextTok = Tokens->getNextNonComment();
520
521 if (!Line->InMacroBody && !Style.isTableGen()) {
522 // Skip PPDirective lines (except macro definitions) and comments.
523 while (NextTok->is(tok::hash)) {
524 NextTok = Tokens->getNextToken();
525 if (NextTok->isOneOf(tok::pp_not_keyword, tok::pp_define))
526 break;
527 do {
528 NextTok = Tokens->getNextToken();
529 } while (!NextTok->HasUnescapedNewline && NextTok->isNot(tok::eof));
530
531 while (NextTok->is(tok::comment))
532 NextTok = Tokens->getNextToken();
533 }
534 }
535
536 switch (Tok->Tok.getKind()) {
537 case tok::l_brace:
538 if (Style.isJavaScript() && PrevTok) {
539 if (PrevTok->isOneOf(tok::colon, tok::less)) {
540 // A ':' indicates this code is in a type, or a braced list
541 // following a label in an object literal ({a: {b: 1}}).
542 // A '<' could be an object used in a comparison, but that is nonsense
543 // code (can never return true), so more likely it is a generic type
544 // argument (`X<{a: string; b: number}>`).
545 // The code below could be confused by semicolons between the
546 // individual members in a type member list, which would normally
547 // trigger BK_Block. In both cases, this must be parsed as an inline
548 // braced init.
549 Tok->setBlockKind(BK_BracedInit);
550 } else if (PrevTok->is(tok::r_paren)) {
551 // `) { }` can only occur in function or method declarations in JS.
552 Tok->setBlockKind(BK_Block);
553 }
554 } else if (Style.isJava() && PrevTok && PrevTok->is(tok::arrow)) {
555 Tok->setBlockKind(BK_Block);
556 } else {
557 Tok->setBlockKind(BK_Unknown);
558 }
559 LBraceStack.push_back({Tok, PrevTok});
560 break;
561 case tok::r_brace:
562 if (LBraceStack.empty())
563 break;
564 if (auto *LBrace = LBraceStack.back().Tok; LBrace->is(BK_Unknown)) {
565 bool ProbablyBracedList = false;
566 if (Style.Language == FormatStyle::LK_Proto) {
567 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
568 } else if (LBrace->isNot(TT_EnumLBrace)) {
569 // Using OriginalColumn to distinguish between ObjC methods and
570 // binary operators is a bit hacky.
571 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
572 NextTok->OriginalColumn == 0;
573
574 // Try to detect a braced list. Note that regardless how we mark inner
575 // braces here, we will overwrite the BlockKind later if we parse a
576 // braced list (where all blocks inside are by default braced lists),
577 // or when we explicitly detect blocks (for example while parsing
578 // lambdas).
579
580 // If we already marked the opening brace as braced list, the closing
581 // must also be part of it.
582 ProbablyBracedList = LBrace->is(TT_BracedListLBrace);
583
584 ProbablyBracedList = ProbablyBracedList ||
585 (Style.isJavaScript() &&
586 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
587 Keywords.kw_as));
588 ProbablyBracedList =
589 ProbablyBracedList ||
590 (IsCpp && (PrevTok->Tok.isLiteral() ||
591 NextTok->isOneOf(tok::l_paren, tok::arrow)));
592
593 // If there is a comma, or right paren after the closing brace, we
594 // assume this is a braced initializer list.
595 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
596 // braced list in JS.
597 ProbablyBracedList =
598 ProbablyBracedList ||
599 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
600 tok::r_paren, tok::r_square, tok::ellipsis);
601
602 // Distinguish between braced list in a constructor initializer list
603 // followed by constructor body, or just adjacent blocks.
604 ProbablyBracedList =
605 ProbablyBracedList ||
606 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
607 LBraceStack.back().PrevTok->isOneOf(tok::identifier,
608 tok::greater));
609
610 ProbablyBracedList =
611 ProbablyBracedList ||
612 (NextTok->is(tok::identifier) &&
613 PrevTok->isNoneOf(tok::semi, tok::r_brace, tok::l_brace));
614
615 ProbablyBracedList = ProbablyBracedList ||
616 (NextTok->is(tok::semi) &&
617 (!ExpectClassBody || LBraceStack.size() != 1));
618
619 ProbablyBracedList =
620 ProbablyBracedList ||
621 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
622
623 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
624 // We can have an array subscript after a braced init
625 // list, but C++11 attributes are expected after blocks.
626 NextTok = Tokens->getNextToken();
627 ProbablyBracedList = NextTok->isNot(tok::l_square);
628 }
629
630 // Cpp macro definition body that is a nonempty braced list or block:
631 if (IsCpp && Line->InMacroBody && PrevTok != FormatTok &&
632 !FormatTok->Previous && NextTok->is(tok::eof) &&
633 // A statement can end with only `;` (simple statement), a block
634 // closing brace (compound statement), or `:` (label statement).
635 // If PrevTok is a block opening brace, Tok ends an empty block.
636 PrevTok->isNoneOf(tok::semi, BK_Block, tok::colon)) {
637 ProbablyBracedList = true;
638 }
639 }
640 const auto BlockKind = ProbablyBracedList ? BK_BracedInit : BK_Block;
641 Tok->setBlockKind(BlockKind);
642 LBrace->setBlockKind(BlockKind);
643 }
644 LBraceStack.pop_back();
645 break;
646 case tok::identifier:
647 if (Tok->isNot(TT_StatementMacro))
648 break;
649 [[fallthrough]];
650 case tok::at:
651 case tok::semi:
652 case tok::kw_if:
653 case tok::kw_while:
654 case tok::kw_for:
655 case tok::kw_switch:
656 case tok::kw_try:
657 case tok::kw___try:
658 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(BK_Unknown))
659 LBraceStack.back().Tok->setBlockKind(BK_Block);
660 break;
661 default:
662 break;
663 }
664
665 PrevTok = Tok;
666 Tok = NextTok;
667 } while (Tok->isNot(tok::eof) && !LBraceStack.empty());
668
669 // Assume other blocks for all unclosed opening braces.
670 for (const auto &Entry : LBraceStack)
671 if (Entry.Tok->is(BK_Unknown))
672 Entry.Tok->setBlockKind(BK_Block);
673
674 FormatTok = Tokens->setPosition(StoredPosition);
675}
676
677// Sets the token type of the directly previous right brace.
678void UnwrappedLineParser::setPreviousRBraceType(TokenType Type) {
679 if (auto Prev = FormatTok->getPreviousNonComment();
680 Prev && Prev->is(tok::r_brace)) {
681 Prev->setFinalizedType(Type);
682 }
683}
684
685template <class T>
686static inline void hash_combine(std::size_t &seed, const T &v) {
687 std::hash<T> hasher;
688 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
689}
690
691size_t UnwrappedLineParser::computePPHash() const {
692 size_t h = 0;
693 for (const auto &i : PP.Stack) {
694 hash_combine(h, size_t(i.Kind));
695 hash_combine(h, i.Line);
696 }
697 return h;
698}
699
700// Checks whether \p ParsedLine might fit on a single line. If \p OpeningBrace
701// is not null, subtracts its length (plus the preceding space) when computing
702// the length of \p ParsedLine. We must clone the tokens of \p ParsedLine before
703// running the token annotator on it so that we can restore them afterward.
704bool UnwrappedLineParser::mightFitOnOneLine(
705 UnwrappedLine &ParsedLine, const FormatToken *OpeningBrace) const {
706 const auto ColumnLimit = Style.ColumnLimit;
707 if (ColumnLimit == 0)
708 return true;
709
710 auto &Tokens = ParsedLine.Tokens;
711 assert(!Tokens.empty());
712
713 const auto *LastToken = Tokens.back().Tok;
714 assert(LastToken);
715
716 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
717
718 int Index = 0;
719 for (const auto &Token : Tokens) {
720 assert(Token.Tok);
721 auto &SavedToken = SavedTokens[Index++];
722 SavedToken.Tok = new FormatToken;
723 SavedToken.Tok->copyFrom(*Token.Tok);
724 SavedToken.Children = std::move(Token.Children);
725 }
726
727 AnnotatedLine Line(ParsedLine);
728 assert(Line.Last == LastToken);
729
730 TokenAnnotator Annotator(Style, Keywords);
731 Annotator.annotate(Line);
732 Annotator.calculateFormattingInformation(Line);
733
734 auto Length = LastToken->TotalLength;
735 if (OpeningBrace) {
736 assert(OpeningBrace != Tokens.front().Tok);
737 if (auto Prev = OpeningBrace->Previous;
738 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
739 Length -= ColumnLimit;
740 }
741 Length -= OpeningBrace->TokenText.size() + 1;
742 }
743
744 if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
745 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
746 Length -= FirstToken->TokenText.size() + 1;
747 }
748
749 Index = 0;
750 for (auto &Token : Tokens) {
751 const auto &SavedToken = SavedTokens[Index++];
752 Token.Tok->copyFrom(*SavedToken.Tok);
753 Token.Children = std::move(SavedToken.Children);
754 delete SavedToken.Tok;
755 }
756
757 // If these change PPLevel needs to be used for get correct indentation.
758 assert(!Line.InMacroBody);
759 assert(!Line.InPPDirective);
760 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
761}
762
763FormatToken *UnwrappedLineParser::parseBlock(
764 bool MustBeDeclaration, unsigned AddLevels, bool MunchSemi, bool KeepBraces,
765 IfStmtKind *IfKind, bool UnindentWhitesmithsBraces,
766 bool IndentAfterExplicitAccessModifier) {
767 auto HandleVerilogBlockLabel = [this]() {
768 // ":" name
769 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
770 nextToken();
771 if (Keywords.isVerilogIdentifier(*FormatTok))
772 nextToken();
773 }
774 };
775
776 // Whether this is a Verilog-specific block that has a special header like a
777 // module.
778 const bool VerilogHierarchy =
779 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
780 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
781 (Style.isVerilog() &&
782 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
783 "'{' or macro block token expected");
784 FormatToken *Tok = FormatTok;
785 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
786 auto Index = CurrentLines->size();
787 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
788 FormatTok->setBlockKind(BK_Block);
789
790 const bool IsWhitesmiths =
791 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
792
793 // For Whitesmiths mode, jump to the next level prior to skipping over the
794 // braces.
795 if (!VerilogHierarchy && AddLevels > 0 && IsWhitesmiths)
796 ++Line->Level;
797
798 size_t PPStartHash = computePPHash();
799
800 const unsigned InitialLevel = Line->Level;
801 if (VerilogHierarchy) {
802 AddLevels += parseVerilogHierarchyHeader();
803 } else {
804 nextToken(/*LevelDifference=*/AddLevels);
805 HandleVerilogBlockLabel();
806 }
807
808 // Bail out if there are too many levels. Otherwise, the stack might overflow.
809 if (Line->Level > 300)
810 return nullptr;
811
812 if (MacroBlock && FormatTok->is(tok::l_paren))
813 parseParens();
814
815 size_t NbPreprocessorDirectives =
816 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
817 addUnwrappedLine();
818 size_t OpeningLineIndex =
819 CurrentLines->empty() || !CurrentExpandedLines.empty()
821 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
822
823 // Whitesmiths is weird here. The brace needs to be indented for the namespace
824 // block, but the block itself may not be indented depending on the style
825 // settings. This allows the format to back up one level in those cases.
826 if (UnindentWhitesmithsBraces)
827 --Line->Level;
828
829 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
830 MustBeDeclaration);
831
832 // Whitesmiths logic has already added a level by this point, so avoid
833 // adding it twice.
834 if (AddLevels > 0u)
835 Line->Level += AddLevels - (IsWhitesmiths ? 1 : 0);
836
837 FormatToken *IfLBrace = nullptr;
838 bool SeenExplicitAccessModifier = false;
839 const bool SimpleBlock =
840 parseLevel(Tok, IfKind, &IfLBrace,
841 IndentAfterExplicitAccessModifier ? &SeenExplicitAccessModifier
842 : nullptr);
843
844 if (eof())
845 return IfLBrace;
846
847 if (MacroBlock ? FormatTok->isNot(TT_MacroBlockEnd)
848 : FormatTok->isNot(tok::r_brace)) {
849 Line->Level = InitialLevel;
850 FormatTok->setBlockKind(BK_Block);
851 return IfLBrace;
852 }
853
854 if (FormatTok->is(tok::r_brace)) {
855 FormatTok->setBlockKind(BK_Block);
856 if (Tok->is(TT_NamespaceLBrace))
857 FormatTok->setFinalizedType(TT_NamespaceRBrace);
858 }
859
860 const bool IsFunctionRBrace =
861 FormatTok->is(tok::r_brace) && Tok->is(TT_FunctionLBrace);
862
863 auto RemoveBraces = [=]() mutable {
864 if (!SimpleBlock)
865 return false;
866 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
867 assert(FormatTok->is(tok::r_brace));
868 const bool WrappedOpeningBrace = !Tok->Previous;
869 if (WrappedOpeningBrace && FollowedByComment)
870 return false;
871 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
872 if (KeepBraces && !HasRequiredIfBraces)
873 return false;
874 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
875 const FormatToken *Previous = Tokens->getPreviousToken();
876 assert(Previous);
877 if (Previous->is(tok::r_brace) && !Previous->Optional)
878 return false;
879 }
880 if (OpeningLineIndex == UnwrappedLine::kInvalidIndex)
881 return false;
882 assert(!CurrentLines->empty());
883 auto &LastLine = CurrentLines->back();
884 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
885 return false;
886 if (Tok->is(TT_ElseLBrace))
887 return true;
888 if (WrappedOpeningBrace) {
889 assert(Index > 0);
890 --Index; // The line above the wrapped l_brace.
891 Tok = nullptr;
892 }
893 return mightFitOnOneLine((*CurrentLines)[Index], Tok);
894 };
895 if (RemoveBraces()) {
896 Tok->MatchingParen = FormatTok;
897 FormatTok->MatchingParen = Tok;
898 }
899
900 size_t PPEndHash = computePPHash();
901
902 if (SeenExplicitAccessModifier)
903 ++AddLevels;
904 // Munch the closing brace.
905 nextToken(/*LevelDifference=*/-AddLevels);
906
907 // When this is a function block and there is an unnecessary semicolon
908 // afterwards then mark it as optional (so the RemoveSemi pass can get rid of
909 // it later).
910 if (Style.RemoveSemicolon && IsFunctionRBrace) {
911 while (FormatTok->is(tok::semi)) {
912 FormatTok->Optional = true;
913 nextToken();
914 }
915 }
916
917 HandleVerilogBlockLabel();
918
919 if (MacroBlock && FormatTok->is(tok::l_paren))
920 parseParens();
921
922 Line->Level = InitialLevel;
923
924 if (FormatTok->is(tok::kw_noexcept)) {
925 // A noexcept in a requires expression.
926 nextToken();
927 }
928
929 if (FormatTok->is(tok::arrow)) {
930 // Following the } or noexcept we can find a trailing return type arrow
931 // as part of an implicit conversion constraint.
932 nextToken();
933 parseStructuralElement();
934 }
935
936 if (MunchSemi && FormatTok->is(tok::semi))
937 nextToken();
938
939 if (PPStartHash == PPEndHash && CurrentExpandedLines.empty() &&
940 !containsExpansion(*Line)) {
941 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
942 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
943 // Update the opening line to add the forward reference as well
944 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
945 CurrentLines->size() - 1;
946 }
947 }
948
949 return IfLBrace;
950}
951
952static bool isGoogScope(const UnwrappedLine &Line) {
953 // FIXME: Closure-library specific stuff should not be hard-coded but be
954 // configurable.
955 if (Line.Tokens.size() < 4)
956 return false;
957 auto I = Line.Tokens.begin();
958 if (I->Tok->TokenText != "goog")
959 return false;
960 ++I;
961 if (I->Tok->isNot(tok::period))
962 return false;
963 ++I;
964 if (I->Tok->TokenText != "scope")
965 return false;
966 ++I;
967 return I->Tok->is(tok::l_paren);
968}
969
970static bool isIIFE(const UnwrappedLine &Line,
971 const AdditionalKeywords &Keywords) {
972 // Look for the start of an immediately invoked anonymous function.
973 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
974 // This is commonly done in JavaScript to create a new, anonymous scope.
975 // Example: (function() { ... })()
976 if (Line.Tokens.size() < 3)
977 return false;
978 auto I = Line.Tokens.begin();
979 if (I->Tok->isNot(tok::l_paren))
980 return false;
981 ++I;
982 if (I->Tok->isNot(Keywords.kw_function))
983 return false;
984 ++I;
985 return I->Tok->is(tok::l_paren);
986}
987
988static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
989 const FormatToken &InitialToken,
990 bool IsEmptyBlock,
991 bool IsJavaRecord = false) {
992 if (IsJavaRecord)
993 return Style.BraceWrapping.AfterClass;
994
995 tok::TokenKind Kind = InitialToken.Tok.getKind();
996 if (InitialToken.is(TT_NamespaceMacro))
997 Kind = tok::kw_namespace;
998
999 const bool WrapRecordAllowed =
1000 !IsEmptyBlock ||
1001 Style.AllowShortRecordOnASingleLine < FormatStyle::SRS_Empty ||
1002 Style.BraceWrapping.SplitEmptyRecord;
1003
1004 switch (Kind) {
1005 case tok::kw_namespace:
1006 return Style.BraceWrapping.AfterNamespace;
1007 case tok::kw_class:
1008 return Style.BraceWrapping.AfterClass && WrapRecordAllowed;
1009 case tok::kw_union:
1010 return Style.BraceWrapping.AfterUnion && WrapRecordAllowed;
1011 case tok::kw_struct:
1012 return Style.BraceWrapping.AfterStruct && WrapRecordAllowed;
1013 case tok::kw_enum:
1014 return Style.BraceWrapping.AfterEnum;
1015 default:
1016 return false;
1017 }
1018}
1019
1020void UnwrappedLineParser::parseChildBlock() {
1021 assert(FormatTok->is(tok::l_brace));
1022 FormatTok->setBlockKind(BK_Block);
1023 const FormatToken *OpeningBrace = FormatTok;
1024 nextToken();
1025 {
1026 bool SkipIndent = (Style.isJavaScript() &&
1027 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
1028 ScopedLineState LineState(*this);
1029 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
1030 /*MustBeDeclaration=*/false);
1031 Line->Level += SkipIndent ? 0 : 1;
1032 parseLevel(OpeningBrace);
1033 flushComments(isOnNewLine(*FormatTok));
1034 Line->Level -= SkipIndent ? 0 : 1;
1035 }
1036 nextToken();
1037}
1038
1039void UnwrappedLineParser::parsePPDirective() {
1040 assert(FormatTok->is(tok::hash) && "'#' expected");
1041 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
1042
1043 nextToken();
1044
1045 if (!FormatTok->Tok.getIdentifierInfo()) {
1046 parsePPUnknown();
1047 return;
1048 }
1049
1050 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
1051 case tok::pp_define:
1052 parsePPDefine();
1053 return;
1054 case tok::pp_if:
1055 parsePPIf(/*IfDef=*/false);
1056 break;
1057 case tok::pp_ifdef:
1058 case tok::pp_ifndef:
1059 parsePPIf(/*IfDef=*/true);
1060 break;
1061 case tok::pp_else:
1062 case tok::pp_elifdef:
1063 case tok::pp_elifndef:
1064 case tok::pp_elif:
1065 parsePPElse();
1066 break;
1067 case tok::pp_endif:
1068 parsePPEndIf();
1069 break;
1070 case tok::pp_pragma:
1071 parsePPPragma();
1072 break;
1073 case tok::pp_error:
1074 case tok::pp_warning:
1075 nextToken();
1076 if (!eof() && Style.isCpp())
1077 FormatTok->setFinalizedType(TT_AfterPPDirective);
1078 [[fallthrough]];
1079 default:
1080 parsePPUnknown();
1081 break;
1082 }
1083}
1084
1085void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
1086 size_t Line = CurrentLines->size();
1087 if (CurrentLines == &PreprocessorDirectives)
1088 Line += Lines.size();
1089
1090 if (Unreachable ||
1091 (!PP.Stack.empty() && PP.Stack.back().Kind == PP_Unreachable)) {
1092 PP.Stack.push_back({PP_Unreachable, Line});
1093 } else {
1094 PP.Stack.push_back({PP_Conditional, Line});
1095 }
1096}
1097
1098void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
1099 ++PP.BranchLevel;
1100 assert(PP.BranchLevel >= 0 &&
1101 PP.BranchLevel <= (int)PP.LevelBranchIndex.size());
1102 if (PP.BranchLevel == (int)PP.LevelBranchIndex.size()) {
1103 PP.LevelBranchIndex.push_back(0);
1104 PP.LevelBranchCount.push_back(0);
1105 }
1106 PP.ChainBranchIndex.push(Unreachable ? -1 : 0);
1107 bool Skip = PP.LevelBranchIndex[PP.BranchLevel] > 0;
1108 conditionalCompilationCondition(Unreachable || Skip);
1109}
1110
1111void UnwrappedLineParser::conditionalCompilationAlternative() {
1112 if (!PP.Stack.empty())
1113 PP.Stack.pop_back();
1114 assert(PP.BranchLevel < (int)PP.LevelBranchIndex.size());
1115 if (!PP.ChainBranchIndex.empty())
1116 ++PP.ChainBranchIndex.top();
1117 conditionalCompilationCondition(
1118 PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty() &&
1119 PP.LevelBranchIndex[PP.BranchLevel] != PP.ChainBranchIndex.top());
1120}
1121
1122void UnwrappedLineParser::conditionalCompilationEnd() {
1123 assert(PP.BranchLevel < (int)PP.LevelBranchIndex.size());
1124 if (PP.BranchLevel >= 0 && !PP.ChainBranchIndex.empty()) {
1125 if (PP.ChainBranchIndex.top() + 1 > PP.LevelBranchCount[PP.BranchLevel])
1126 PP.LevelBranchCount[PP.BranchLevel] = PP.ChainBranchIndex.top() + 1;
1127 }
1128 // Guard against #endif's without #if.
1129 if (PP.BranchLevel > -1)
1130 --PP.BranchLevel;
1131 if (!PP.ChainBranchIndex.empty())
1132 PP.ChainBranchIndex.pop();
1133 if (!PP.Stack.empty())
1134 PP.Stack.pop_back();
1135}
1136
1137void UnwrappedLineParser::parsePPIf(bool IfDef) {
1138 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1139 nextToken();
1140 bool Unreachable = false;
1141 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
1142 Unreachable = true;
1143 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
1144 Unreachable = true;
1145 conditionalCompilationStart(Unreachable);
1146 FormatToken *IfCondition = FormatTok;
1147 // If there's a #ifndef on the first line, and the only lines before it are
1148 // comments, it could be an include guard.
1149 bool MaybeIncludeGuard = IfNDef;
1150 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1151 for (auto &Line : Lines) {
1152 if (Line.Tokens.front().Tok->isNot(tok::comment)) {
1153 MaybeIncludeGuard = false;
1154 PP.IncludeGuard = IG_Rejected;
1155 break;
1156 }
1157 }
1158 }
1159 --PP.BranchLevel;
1160 parsePPUnknown();
1161 ++PP.BranchLevel;
1162 if (PP.IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1163 PP.IncludeGuard = IG_IfNdefed;
1164 PP.IncludeGuardToken = IfCondition;
1165 }
1166}
1167
1168void UnwrappedLineParser::parsePPElse() {
1169 // If a potential include guard has an #else, it's not an include guard.
1170 if (PP.IncludeGuard == IG_Defined && PP.BranchLevel == 0)
1171 PP.IncludeGuard = IG_Rejected;
1172 // Don't crash when there is an #else without an #if.
1173 assert(PP.BranchLevel >= -1);
1174 if (PP.BranchLevel == -1)
1175 conditionalCompilationStart(/*Unreachable=*/true);
1176 conditionalCompilationAlternative();
1177 --PP.BranchLevel;
1178 parsePPUnknown();
1179 ++PP.BranchLevel;
1180}
1181
1182void UnwrappedLineParser::parsePPEndIf() {
1183 conditionalCompilationEnd();
1184 parsePPUnknown();
1185}
1186
1187void UnwrappedLineParser::parsePPDefine() {
1188 nextToken();
1189
1190 if (!FormatTok->Tok.getIdentifierInfo()) {
1191 PP.IncludeGuard = IG_Rejected;
1192 PP.IncludeGuardToken = nullptr;
1193 parsePPUnknown();
1194 return;
1195 }
1196
1197 bool MaybeIncludeGuard = false;
1198 if (PP.IncludeGuard == IG_IfNdefed &&
1199 PP.IncludeGuardToken->TokenText == FormatTok->TokenText) {
1200 PP.IncludeGuard = IG_Defined;
1201 PP.IncludeGuardToken = nullptr;
1202 for (auto &Line : Lines) {
1203 if (Line.Tokens.front().Tok->isNoneOf(tok::comment, tok::hash)) {
1204 PP.IncludeGuard = IG_Rejected;
1205 break;
1206 }
1207 }
1208 MaybeIncludeGuard = PP.IncludeGuard == IG_Defined;
1209 }
1210
1211 // In the context of a define, even keywords should be treated as normal
1212 // identifiers. Setting the kind to identifier is not enough, because we need
1213 // to treat additional keywords like __except as well, which are already
1214 // identifiers. Setting the identifier info to null interferes with include
1215 // guard processing above, and changes preprocessing nesting.
1216 FormatTok->Tok.setKind(tok::identifier);
1217 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1218 nextToken();
1219
1220 // IncludeGuard can't have a non-empty macro definition.
1221 if (MaybeIncludeGuard && !eof())
1222 PP.IncludeGuard = IG_Rejected;
1223
1224 if (FormatTok->is(tok::l_paren) && !FormatTok->hasWhitespaceBefore())
1225 parseParens();
1226 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1227 Line->Level += PP.BranchLevel + 1;
1228 addUnwrappedLine();
1229 ++Line->Level;
1230
1231 Line->PPLevel = PP.BranchLevel + (PP.IncludeGuard == IG_Defined ? 0 : 1);
1232 assert((int)Line->PPLevel >= 0);
1233
1234 if (eof())
1235 return;
1236
1237 Line->InMacroBody = true;
1238
1239 if (!Style.SkipMacroDefinitionBody) {
1240 // Errors during a preprocessor directive can only affect the layout of the
1241 // preprocessor directive, and thus we ignore them. An alternative approach
1242 // would be to use the same approach we use on the file level (no
1243 // re-indentation if there was a structural error) within the macro
1244 // definition.
1245 parseFile();
1246 return;
1247 }
1248
1249 for (auto *Comment : CommentsBeforeNextToken)
1250 Comment->Finalized = true;
1251
1252 do {
1253 FormatTok->Finalized = true;
1254 FormatTok = Tokens->getNextToken();
1255 } while (!eof());
1256
1257 addUnwrappedLine();
1258}
1259
1260void UnwrappedLineParser::parsePPPragma() {
1261 Line->InPragmaDirective = true;
1262 parsePPUnknown();
1263}
1264
1265void UnwrappedLineParser::parsePPUnknown() {
1266 while (!eof())
1267 nextToken();
1268 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1269 Line->Level += PP.BranchLevel + 1;
1270 addUnwrappedLine();
1271}
1272
1273// Here we exclude certain tokens that are not usually the first token in an
1274// unwrapped line. This is used in attempt to distinguish macro calls without
1275// trailing semicolons from other constructs split to several lines.
1277 // Semicolon can be a null-statement, l_square can be a start of a macro or
1278 // a C++11 attribute, but this doesn't seem to be common.
1279 return Tok.isNoneOf(tok::semi, tok::l_brace,
1280 // Tokens that can only be used as binary operators and a
1281 // part of overloaded operator names.
1282 tok::period, tok::periodstar, tok::arrow, tok::arrowstar,
1283 tok::less, tok::greater, tok::slash, tok::percent,
1284 tok::lessless, tok::greatergreater, tok::equal,
1285 tok::plusequal, tok::minusequal, tok::starequal,
1286 tok::slashequal, tok::percentequal, tok::ampequal,
1287 tok::pipeequal, tok::caretequal, tok::greatergreaterequal,
1288 tok::lesslessequal,
1289 // Colon is used in labels, base class lists, initializer
1290 // lists, range-based for loops, ternary operator, but
1291 // should never be the first token in an unwrapped line.
1292 tok::colon,
1293 // 'noexcept' is a trailing annotation.
1294 tok::kw_noexcept);
1295}
1296
1297static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
1298 const FormatToken *FormatTok) {
1299 // FIXME: This returns true for C/C++ keywords like 'struct'.
1300 return FormatTok->is(tok::identifier) &&
1301 (!FormatTok->Tok.getIdentifierInfo() ||
1302 FormatTok->isNoneOf(
1303 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
1304 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
1305 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
1306 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
1307 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
1308 Keywords.kw_instanceof, Keywords.kw_interface,
1309 Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from));
1310}
1311
1312static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
1313 const FormatToken *FormatTok) {
1314 return FormatTok->Tok.isLiteral() ||
1315 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
1316 mustBeJSIdent(Keywords, FormatTok);
1317}
1318
1319// isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
1320// when encountered after a value (see mustBeJSIdentOrValue).
1321static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
1322 const FormatToken *FormatTok) {
1323 return FormatTok->isOneOf(
1324 tok::kw_return, Keywords.kw_yield,
1325 // conditionals
1326 tok::kw_if, tok::kw_else,
1327 // loops
1328 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1329 // switch/case
1330 tok::kw_switch, tok::kw_case,
1331 // exceptions
1332 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
1333 // declaration
1334 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
1335 Keywords.kw_async, Keywords.kw_function,
1336 // import/export
1337 Keywords.kw_import, tok::kw_export);
1338}
1339
1340// Checks whether a token is a type in K&R C (aka C78).
1341static bool isC78Type(const FormatToken &Tok) {
1342 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1343 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1344 tok::identifier);
1345}
1346
1347// This function checks whether a token starts the first parameter declaration
1348// in a K&R C (aka C78) function definition, e.g.:
1349// int f(a, b)
1350// short a, b;
1351// {
1352// return a + b;
1353// }
1355 const FormatToken *FuncName) {
1356 assert(Tok);
1357 assert(Next);
1358 assert(FuncName);
1359
1360 if (FuncName->isNot(tok::identifier))
1361 return false;
1362
1363 const FormatToken *Prev = FuncName->Previous;
1364 if (!Prev || (Prev->isNot(tok::star) && !isC78Type(*Prev)))
1365 return false;
1366
1367 if (!isC78Type(*Tok) &&
1368 Tok->isNoneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1369 return false;
1370 }
1371
1372 if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo())
1373 return false;
1374
1375 Tok = Tok->Previous;
1376 if (!Tok || Tok->isNot(tok::r_paren))
1377 return false;
1378
1379 Tok = Tok->Previous;
1380 if (!Tok || Tok->isNot(tok::identifier))
1381 return false;
1382
1383 return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1384}
1385
1386bool UnwrappedLineParser::parseModuleDecl() {
1387 assert(IsCpp);
1388 assert(FormatTok->is(Keywords.kw_module));
1389
1390 if (Style.Language == FormatStyle::LK_C ||
1391 Style.Standard < FormatStyle::LS_Cpp20) {
1392 return false;
1393 }
1394
1395 nextToken();
1396 if (FormatTok->isNot(tok::identifier))
1397 return false;
1398
1399 for (nextToken(); FormatTok->isNoneOf(tok::semi, tok::eof); nextToken())
1400 if (FormatTok->is(tok::colon))
1401 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1402
1403 nextToken();
1404 Line->IsModuleOrImportDecl = true;
1405 addUnwrappedLine();
1406 return true;
1407}
1408
1409bool UnwrappedLineParser::parseImportDecl() {
1410 assert(IsCpp);
1411 assert(FormatTok->is(Keywords.kw_import) && "'import' expected");
1412
1413 if (Style.Language == FormatStyle::LK_C ||
1414 Style.Standard < FormatStyle::LS_Cpp20) {
1415 return false;
1416 }
1417
1418 nextToken();
1419 if (FormatTok->is(tok::colon)) {
1420 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1421 nextToken();
1422 }
1423 if (FormatTok->isNoneOf(tok::identifier, tok::less, tok::string_literal))
1424 return false;
1425
1426 for (; FormatTok->isNoneOf(tok::semi, tok::eof); nextToken()) {
1427 // Handle import <foo/bar.h> as we would an include statement.
1428 if (FormatTok->is(tok::less)) {
1429 for (nextToken(); FormatTok->isNoneOf(tok::greater, tok::semi, tok::eof);
1430 nextToken()) {
1431 // Mark tokens as implicit string literals, so that import <A/Foo> will
1432 // neither be broken nor have a space added.
1433 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1434 }
1435 }
1436 }
1437
1438 nextToken();
1439 Line->IsModuleOrImportDecl = true;
1440 addUnwrappedLine();
1441 return true;
1442}
1443
1444// readTokenWithJavaScriptASI reads the next token and terminates the current
1445// line if JavaScript Automatic Semicolon Insertion must
1446// happen between the current token and the next token.
1447//
1448// This method is conservative - it cannot cover all edge cases of JavaScript,
1449// but only aims to correctly handle certain well known cases. It *must not*
1450// return true in speculative cases.
1451void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1452 FormatToken *Previous = FormatTok;
1453 readToken();
1454 FormatToken *Next = FormatTok;
1455
1456 bool IsOnSameLine =
1457 CommentsBeforeNextToken.empty()
1458 ? Next->NewlinesBefore == 0
1459 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1460 if (IsOnSameLine)
1461 return;
1462
1463 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
1464 bool PreviousStartsTemplateExpr =
1465 Previous->is(TT_TemplateString) && Previous->TokenText.ends_with("${");
1466 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
1467 // If the line contains an '@' sign, the previous token might be an
1468 // annotation, which can precede another identifier/value.
1469 bool HasAt = llvm::any_of(Line->Tokens, [](UnwrappedLineNode &LineNode) {
1470 return LineNode.Tok->is(tok::at);
1471 });
1472 if (HasAt)
1473 return;
1474 }
1475 if (Next->is(tok::exclaim) && PreviousMustBeValue)
1476 return addUnwrappedLine();
1477 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
1478 bool NextEndsTemplateExpr =
1479 Next->is(TT_TemplateString) && Next->TokenText.starts_with("}");
1480 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1481 (PreviousMustBeValue ||
1482 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1483 tok::minusminus))) {
1484 return addUnwrappedLine();
1485 }
1486 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
1487 isJSDeclOrStmt(Keywords, Next)) {
1488 return addUnwrappedLine();
1489 }
1490}
1491
1492void UnwrappedLineParser::parseStructuralElement(
1493 const FormatToken *OpeningBrace, IfStmtKind *IfKind,
1494 FormatToken **IfLeftBrace, bool *HasDoWhile, bool *HasLabel) {
1495 if (Style.isTableGen() && FormatTok->is(tok::pp_include)) {
1496 nextToken();
1497 if (FormatTok->is(tok::string_literal))
1498 nextToken();
1499 addUnwrappedLine();
1500 return;
1501 }
1502
1503 if (IsCpp) {
1504 while (FormatTok->is(tok::l_square) && handleCppAttributes()) {
1505 }
1506 } else if (Style.isVerilog()) {
1507 // Skip attributes.
1508 while (FormatTok->is(tok::l_paren) &&
1509 Tokens->peekNextToken()->is(tok::star)) {
1510 parseParens();
1511 }
1512 skipVerilogQualifiers();
1513 // Skip things that can exist before keywords like 'if' and 'case'.
1514 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1515 Keywords.kw_unique0)) {
1516 nextToken();
1517 }
1518
1519 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1520 parseForOrWhileLoop(/*HasParens=*/false);
1521 return;
1522 }
1523 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1524 parseForOrWhileLoop();
1525 return;
1526 }
1527 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1528 Keywords.kw_assume, Keywords.kw_cover)) {
1529 parseIfThenElse(IfKind, /*KeepBraces=*/false, /*IsVerilogAssert=*/true);
1530 return;
1531 }
1532 }
1533
1534 // Tokens that only make sense at the beginning of a line.
1535 if (FormatTok->isAccessSpecifierKeyword()) {
1536 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp())
1537 nextToken();
1538 else
1539 parseAccessSpecifier();
1540 return;
1541 }
1542 switch (FormatTok->Tok.getKind()) {
1543 case tok::kw_asm: {
1544 // Track whether to skip formatting inline asm by finalizing the tokens
1545 // in the block. Formatting is skipped inside of braces by default.
1546 // A style option could be added to also skip formatting inside parens.
1547 bool DoNotFormat = false;
1548 tok::TokenKind OpenType;
1549 tok::TokenKind CloseType;
1550 nextToken();
1551 while (FormatTok &&
1552 FormatTok->isOneOf(tok::kw_volatile, tok::kw_inline, tok::kw_goto)) {
1553 nextToken();
1554 }
1555 if (!FormatTok)
1556 break;
1557 if (FormatTok->is(tok::l_brace)) {
1558 FormatTok->setFinalizedType(TT_InlineASMBrace);
1559 OpenType = tok::l_brace;
1560 CloseType = tok::r_brace;
1561 DoNotFormat = true;
1562 } else if (FormatTok->is(tok::l_paren)) {
1563 OpenType = tok::l_paren;
1564 CloseType = tok::r_paren;
1565 FormatTok->setFinalizedType(TT_InlineASMParen);
1566 } else {
1567 break;
1568 }
1569 if (DoNotFormat) {
1570 FormatToken *OpenTok = FormatTok;
1571 int NestLevel = 0;
1572 nextToken();
1573 while (FormatTok && !eof()) {
1574 if (FormatTok->is(OpenType)) {
1575 ++NestLevel;
1576 } else if (FormatTok->is(CloseType)) {
1577 --NestLevel;
1578 if (NestLevel < 1) {
1579 FormatTok->setFinalizedType(OpenTok->getType());
1580 nextToken();
1581 addUnwrappedLine();
1582 break;
1583 }
1584 }
1585 FormatTok->Finalized = true;
1586 nextToken();
1587 }
1588 }
1589 break;
1590 }
1591 case tok::kw_namespace:
1592 parseNamespace();
1593 return;
1594 case tok::kw_if: {
1595 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1596 // field/method declaration.
1597 break;
1598 }
1599 FormatToken *Tok = parseIfThenElse(IfKind);
1600 if (IfLeftBrace)
1601 *IfLeftBrace = Tok;
1602 return;
1603 }
1604 case tok::kw_for:
1605 case tok::kw_while:
1606 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1607 // field/method declaration.
1608 break;
1609 }
1610 parseForOrWhileLoop();
1611 return;
1612 case tok::kw_do:
1613 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1614 // field/method declaration.
1615 break;
1616 }
1617 parseDoWhile();
1618 if (HasDoWhile)
1619 *HasDoWhile = true;
1620 return;
1621 case tok::kw_switch:
1622 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1623 // 'switch: string' field declaration.
1624 break;
1625 }
1626 parseSwitch(/*IsExpr=*/false);
1627 return;
1628 case tok::kw_default: {
1629 // In Verilog default along with other labels are handled in the next loop.
1630 if (Style.isVerilog())
1631 break;
1632 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1633 // 'default: string' field declaration.
1634 break;
1635 }
1636 auto *Default = FormatTok;
1637 nextToken();
1638 if (FormatTok->is(tok::colon)) {
1639 FormatTok->setFinalizedType(TT_CaseLabelColon);
1640 parseLabel();
1641 return;
1642 }
1643 if (FormatTok->is(tok::arrow)) {
1644 FormatTok->setFinalizedType(TT_CaseLabelArrow);
1645 Default->setFinalizedType(TT_SwitchExpressionLabel);
1646 parseLabel();
1647 return;
1648 }
1649 // e.g. "default void f() {}" in a Java interface.
1650 break;
1651 }
1652 case tok::kw_case:
1653 // Proto: there are no switch/case statements.
1654 if (Style.Language == FormatStyle::LK_Proto) {
1655 nextToken();
1656 return;
1657 }
1658 if (Style.isVerilog()) {
1659 parseBlock();
1660 addUnwrappedLine();
1661 return;
1662 }
1663 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1664 // 'case: string' field declaration.
1665 nextToken();
1666 break;
1667 }
1668 parseCaseLabel();
1669 return;
1670 case tok::kw_goto:
1671 nextToken();
1672 if (FormatTok->is(tok::kw_case))
1673 nextToken();
1674 break;
1675 case tok::kw_try:
1676 case tok::kw___try:
1677 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1678 // field/method declaration.
1679 break;
1680 }
1681 parseTryCatch();
1682 return;
1683 case tok::kw_extern:
1684 if (Style.isVerilog()) {
1685 // In Verilog an extern module declaration looks like a start of module.
1686 // But there is no body and endmodule. So we handle it separately.
1687 parseVerilogExtern();
1688 return;
1689 }
1690 nextToken();
1691 if (FormatTok->is(tok::string_literal)) {
1692 nextToken();
1693 if (FormatTok->is(tok::l_brace)) {
1694 if (Style.BraceWrapping.AfterExternBlock)
1695 addUnwrappedLine();
1696 // Either we indent or for backwards compatibility we follow the
1697 // AfterExternBlock style.
1698 unsigned AddLevels =
1699 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1700 (Style.BraceWrapping.AfterExternBlock &&
1701 Style.IndentExternBlock ==
1703 ? 1u
1704 : 0u;
1705 parseBlock(/*MustBeDeclaration=*/true, AddLevels);
1706 addUnwrappedLine();
1707 return;
1708 }
1709 }
1710 break;
1711 case tok::kw_export:
1712 if (IsCpp) {
1713 nextToken();
1714 if (FormatTok->is(tok::kw_namespace)) {
1715 parseNamespace();
1716 return;
1717 }
1718 if (FormatTok->is(tok::l_brace)) {
1719 parseCppExportBlock();
1720 return;
1721 }
1722 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1723 return;
1724 if (FormatTok->is(Keywords.kw_import) && parseImportDecl())
1725 return;
1726 break;
1727 }
1728 if (Style.isJavaScript()) {
1729 parseJavaScriptEs6ImportExport();
1730 return;
1731 }
1732 if (Style.isVerilog()) {
1733 parseVerilogExtern();
1734 return;
1735 }
1736 break;
1737 case tok::kw_inline:
1738 nextToken();
1739 if (FormatTok->is(tok::kw_namespace)) {
1740 parseNamespace();
1741 return;
1742 }
1743 break;
1744 case tok::identifier:
1745 if (FormatTok->is(TT_ForEachMacro)) {
1746 parseForOrWhileLoop();
1747 return;
1748 }
1749 if (FormatTok->is(TT_MacroBlockBegin)) {
1750 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
1751 /*MunchSemi=*/false);
1752 return;
1753 }
1754 if (FormatTok->is(Keywords.kw_import)) {
1755 if (IsCpp && parseImportDecl())
1756 return;
1757 if (Style.isJavaScript()) {
1758 parseJavaScriptEs6ImportExport();
1759 return;
1760 }
1761 if (Style.Language == FormatStyle::LK_Proto) {
1762 nextToken();
1763 if (FormatTok->is(tok::kw_public))
1764 nextToken();
1765 if (FormatTok->isNot(tok::string_literal))
1766 return;
1767 nextToken();
1768 if (FormatTok->is(tok::semi))
1769 nextToken();
1770 addUnwrappedLine();
1771 return;
1772 }
1773 if (Style.isVerilog()) {
1774 parseVerilogExtern();
1775 return;
1776 }
1777 }
1778 if (IsCpp) {
1779 if (FormatTok->is(Keywords.kw_module) && parseModuleDecl())
1780 return;
1781 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1782 Keywords.kw_slots, Keywords.kw_qslots)) {
1783 nextToken();
1784 if (FormatTok->is(tok::colon)) {
1785 nextToken();
1786 addUnwrappedLine();
1787 return;
1788 }
1789 }
1790 if (FormatTok->is(TT_StatementMacro)) {
1791 parseStatementMacro();
1792 return;
1793 }
1794 if (FormatTok->is(TT_NamespaceMacro)) {
1795 parseNamespace();
1796 return;
1797 }
1798 }
1799 // In Verilog labels can be any expression, so we don't do them here.
1800 // JS doesn't have macros, and within classes colons indicate fields, not
1801 // labels.
1802 // TableGen doesn't have labels.
1803 if (!Style.isJavaScript() && !Style.isVerilog() && !Style.isTableGen() &&
1804 Tokens->peekNextToken()->is(tok::colon) && !Line->MustBeDeclaration) {
1805 nextToken();
1806 if (!Line->InMacroBody || CurrentLines->size() > 1)
1807 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1808 FormatTok->setFinalizedType(TT_GotoLabelColon);
1809 parseLabel(/*IsGotoLabel=*/true);
1810 if (HasLabel)
1811 *HasLabel = true;
1812 return;
1813 }
1814 if (Style.isJava() && FormatTok->is(Keywords.kw_record)) {
1815 parseRecord(/*ParseAsExpr=*/false, /*IsJavaRecord=*/true);
1816 addUnwrappedLine();
1817 return;
1818 }
1819 // In all other cases, parse the declaration.
1820 break;
1821 default:
1822 break;
1823 }
1824
1825 bool SeenEqual = false;
1826 for (const bool InRequiresExpression =
1827 OpeningBrace && OpeningBrace->isOneOf(TT_RequiresExpressionLBrace,
1828 TT_CompoundRequirementLBrace);
1829 !eof();) {
1830 const FormatToken *Previous = FormatTok->Previous;
1831 switch (FormatTok->Tok.getKind()) {
1832 case tok::at:
1833 nextToken();
1834 if (FormatTok->is(tok::l_brace)) {
1835 nextToken();
1836 parseBracedList();
1837 break;
1838 }
1839 if (Style.isJava() && FormatTok->is(Keywords.kw_interface)) {
1840 nextToken();
1841 break;
1842 }
1843 switch (bool IsAutoRelease = false; FormatTok->Tok.getObjCKeywordID()) {
1844 case tok::objc_public:
1845 case tok::objc_protected:
1846 case tok::objc_package:
1847 case tok::objc_private:
1848 return parseAccessSpecifier();
1849 case tok::objc_interface:
1850 case tok::objc_implementation:
1851 return parseObjCInterfaceOrImplementation();
1852 case tok::objc_protocol:
1853 if (parseObjCProtocol())
1854 return;
1855 break;
1856 case tok::objc_end:
1857 return; // Handled by the caller.
1858 case tok::objc_optional:
1859 case tok::objc_required:
1860 nextToken();
1861 addUnwrappedLine();
1862 return;
1863 case tok::objc_autoreleasepool:
1864 IsAutoRelease = true;
1865 [[fallthrough]];
1866 case tok::objc_synchronized:
1867 nextToken();
1868 if (!IsAutoRelease && FormatTok->is(tok::l_paren)) {
1869 // Skip synchronization object
1870 parseParens();
1871 }
1872 if (FormatTok->is(tok::l_brace)) {
1873 if (Style.BraceWrapping.AfterControlStatement ==
1875 addUnwrappedLine();
1876 }
1877 parseBlock();
1878 }
1879 addUnwrappedLine();
1880 return;
1881 case tok::objc_try:
1882 // This branch isn't strictly necessary (the kw_try case below would
1883 // do this too after the tok::at is parsed above). But be explicit.
1884 parseTryCatch();
1885 return;
1886 default:
1887 break;
1888 }
1889 break;
1890 case tok::kw_requires: {
1891 if (IsCpp) {
1892 bool ParsedClause = parseRequires(SeenEqual);
1893 if (ParsedClause)
1894 return;
1895 } else {
1896 nextToken();
1897 }
1898 break;
1899 }
1900 case tok::kw_enum:
1901 // Ignore if this is part of "template <enum ..." or "... -> enum" or
1902 // "template <..., enum ...>".
1903 if (Previous && Previous->isOneOf(tok::less, tok::arrow, tok::comma)) {
1904 nextToken();
1905 break;
1906 }
1907
1908 // parseEnum falls through and does not yet add an unwrapped line as an
1909 // enum definition can start a structural element.
1910 if (!parseEnum())
1911 break;
1912 // This only applies to C++ and Verilog.
1913 if (!IsCpp && !Style.isVerilog()) {
1914 addUnwrappedLine();
1915 return;
1916 }
1917 break;
1918 case tok::kw_typedef:
1919 nextToken();
1920 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1921 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1922 Keywords.kw_CF_CLOSED_ENUM,
1923 Keywords.kw_NS_CLOSED_ENUM)) {
1924 parseEnum();
1925 }
1926 break;
1927 case tok::kw_class:
1928 if (Style.isVerilog()) {
1929 parseBlock();
1930 addUnwrappedLine();
1931 return;
1932 }
1933 if (Style.isTableGen()) {
1934 // Do nothing special. In this case the l_brace becomes FunctionLBrace.
1935 // This is same as def and so on.
1936 nextToken();
1937 break;
1938 }
1939 [[fallthrough]];
1940 case tok::kw_struct:
1941 case tok::kw_union:
1942 if (parseStructLike())
1943 return;
1944 break;
1945 case tok::kw_decltype:
1946 nextToken();
1947 if (FormatTok->is(tok::l_paren)) {
1948 parseParens();
1949 if (FormatTok->Previous &&
1950 FormatTok->Previous->endsSequence(tok::r_paren, tok::kw_auto,
1951 tok::l_paren)) {
1952 Line->SeenDecltypeAuto = true;
1953 }
1954 }
1955 break;
1956 case tok::period:
1957 nextToken();
1958 // In Java, classes have an implicit static member "class".
1959 if (Style.isJava() && FormatTok && FormatTok->is(tok::kw_class))
1960 nextToken();
1961 if (Style.isJavaScript() && FormatTok &&
1962 FormatTok->Tok.getIdentifierInfo()) {
1963 // JavaScript only has pseudo keywords, all keywords are allowed to
1964 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1965 nextToken();
1966 }
1967 break;
1968 case tok::semi:
1969 nextToken();
1970 addUnwrappedLine();
1971 return;
1972 case tok::r_brace:
1973 addUnwrappedLine();
1974 return;
1975 case tok::string_literal:
1976 if (Style.isVerilog() && FormatTok->is(TT_VerilogProtected)) {
1977 FormatTok->Finalized = true;
1978 nextToken();
1979 addUnwrappedLine();
1980 return;
1981 }
1982 nextToken();
1983 break;
1984 case tok::l_paren: {
1985 parseParens();
1986 // Break the unwrapped line if a K&R C function definition has a parameter
1987 // declaration.
1988 if (OpeningBrace || !IsCpp || !Previous || eof())
1989 break;
1990 if (isC78ParameterDecl(FormatTok,
1991 Tokens->peekNextToken(/*SkipComment=*/true),
1992 Previous)) {
1993 addUnwrappedLine();
1994 return;
1995 }
1996 break;
1997 }
1998 case tok::kw_operator:
1999 nextToken();
2000 if (FormatTok->isBinaryOperator())
2001 nextToken();
2002 break;
2003 case tok::caret: {
2004 const auto *Prev = FormatTok->getPreviousNonComment();
2005 nextToken();
2006 if (Prev && Prev->is(tok::identifier))
2007 break;
2008 // Block return type.
2009 if (FormatTok->Tok.isAnyIdentifier() || FormatTok->isTypeName(LangOpts)) {
2010 nextToken();
2011 // Return types: ObjC generics and protocol qualifiers are ok too.
2012 if (FormatTok->is(tok::less)) {
2013 nextToken();
2014 parseBracedList(/*IsAngleBracket=*/true);
2015 }
2016 // Return types: pointers are ok too.
2017 while (FormatTok->is(tok::star))
2018 nextToken();
2019 }
2020 // Block argument list.
2021 if (FormatTok->is(tok::l_paren))
2022 parseParens();
2023 // Block body.
2024 if (FormatTok->is(tok::l_brace))
2025 parseChildBlock();
2026 break;
2027 }
2028 case tok::l_brace:
2029 if (InRequiresExpression)
2030 FormatTok->setFinalizedType(TT_BracedListLBrace);
2031 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
2032 IsDecltypeAutoFunction = Line->SeenDecltypeAuto;
2033 // A block outside of parentheses must be the last part of a
2034 // structural element.
2035 // FIXME: Figure out cases where this is not true, and add projections
2036 // for them (the one we know is missing are lambdas).
2037 if (Style.isJava() &&
2038 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
2039 // If necessary, we could set the type to something different than
2040 // TT_FunctionLBrace.
2041 if (Style.BraceWrapping.AfterControlStatement ==
2043 addUnwrappedLine();
2044 }
2045 } else if (Style.BraceWrapping.AfterFunction) {
2046 addUnwrappedLine();
2047 }
2048 if (!Previous || Previous->isNot(TT_TypeDeclarationParen))
2049 FormatTok->setFinalizedType(TT_FunctionLBrace);
2050 parseBlock();
2051 IsDecltypeAutoFunction = false;
2052 addUnwrappedLine();
2053 return;
2054 }
2055 // Otherwise this was a braced init list, and the structural
2056 // element continues.
2057 break;
2058 case tok::kw_try:
2059 if (Style.isJavaScript() && Line->MustBeDeclaration) {
2060 // field/method declaration.
2061 nextToken();
2062 break;
2063 }
2064 // We arrive here when parsing function-try blocks.
2065 if (Style.BraceWrapping.AfterFunction)
2066 addUnwrappedLine();
2067 parseTryCatch();
2068 return;
2069 case tok::identifier: {
2070 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
2071 Line->MustBeDeclaration) {
2072 addUnwrappedLine();
2073 parseCSharpGenericTypeConstraint();
2074 break;
2075 }
2076 if (FormatTok->is(TT_MacroBlockEnd)) {
2077 addUnwrappedLine();
2078 return;
2079 }
2080
2081 // Function declarations (as opposed to function expressions) are parsed
2082 // on their own unwrapped line by continuing this loop. Function
2083 // expressions (functions that are not on their own line) must not create
2084 // a new unwrapped line, so they are special cased below.
2085 size_t TokenCount = Line->Tokens.size();
2086 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
2087 (TokenCount > 1 ||
2088 (TokenCount == 1 &&
2089 Line->Tokens.front().Tok->isNot(Keywords.kw_async)))) {
2090 tryToParseJSFunction();
2091 break;
2092 }
2093 if ((Style.isJavaScript() || Style.isJava()) &&
2094 FormatTok->is(Keywords.kw_interface)) {
2095 if (Style.isJavaScript()) {
2096 // In JavaScript/TypeScript, "interface" can be used as a standalone
2097 // identifier, e.g. in `var interface = 1;`. If "interface" is
2098 // followed by another identifier, it is very like to be an actual
2099 // interface declaration.
2100 unsigned StoredPosition = Tokens->getPosition();
2101 FormatToken *Next = Tokens->getNextToken();
2102 FormatTok = Tokens->setPosition(StoredPosition);
2103 if (!mustBeJSIdent(Keywords, Next)) {
2104 nextToken();
2105 break;
2106 }
2107 }
2108 parseRecord();
2109 addUnwrappedLine();
2110 return;
2111 }
2112
2113 if (Style.isVerilog()) {
2114 if (FormatTok->is(Keywords.kw_table)) {
2115 parseVerilogTable();
2116 return;
2117 }
2118 if (Keywords.isVerilogBegin(*FormatTok) ||
2119 Keywords.isVerilogHierarchy(*FormatTok)) {
2120 parseBlock();
2121 addUnwrappedLine();
2122 return;
2123 }
2124 }
2125
2126 if (!IsCpp && FormatTok->is(Keywords.kw_interface)) {
2127 if (parseStructLike())
2128 return;
2129 break;
2130 }
2131
2132 if (IsCpp && FormatTok->is(TT_StatementMacro)) {
2133 parseStatementMacro();
2134 return;
2135 }
2136
2137 // See if the following token should start a new unwrapped line.
2138 StringRef Text = FormatTok->TokenText;
2139
2140 FormatToken *PreviousToken = FormatTok;
2141 nextToken();
2142
2143 // JS doesn't have macros, and within classes colons indicate fields, not
2144 // labels.
2145 if (Style.isJavaScript())
2146 break;
2147
2148 auto OneTokenSoFar = [&]() {
2149 auto I = Line->Tokens.begin(), E = Line->Tokens.end();
2150 while (I != E && I->Tok->is(tok::comment))
2151 ++I;
2152 if (Style.isVerilog())
2153 while (I != E && I->Tok->is(tok::hash))
2154 ++I;
2155 return I != E && (++I == E);
2156 };
2157 if (OneTokenSoFar()) {
2158 // Recognize function-like macro usages without trailing semicolon as
2159 // well as free-standing macros like Q_OBJECT.
2160 bool FunctionLike = FormatTok->is(tok::l_paren);
2161 if (FunctionLike)
2162 parseParens();
2163
2164 bool FollowedByNewline =
2165 CommentsBeforeNextToken.empty()
2166 ? FormatTok->NewlinesBefore > 0
2167 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
2168
2169 if (FollowedByNewline &&
2170 (Text.size() >= 5 ||
2171 (FunctionLike && FormatTok->isNot(tok::l_paren))) &&
2172 tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
2173 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
2174 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
2175 addUnwrappedLine();
2176 return;
2177 }
2178 }
2179 break;
2180 }
2181 case tok::equal:
2182 if ((Style.isJavaScript() || Style.isCSharp()) &&
2183 FormatTok->is(TT_FatArrow)) {
2184 tryToParseChildBlock();
2185 break;
2186 }
2187
2188 SeenEqual = true;
2189 nextToken();
2190 if (FormatTok->is(tok::l_brace)) {
2191 // C# needs this change to ensure that array initialisers and object
2192 // initialisers are indented the same way. In TypeScript, the brace
2193 // can also be an object type definition.
2194 if (!Style.isJavaScript())
2195 FormatTok->setBlockKind(BK_BracedInit);
2196 // TableGen's defset statement has syntax of the form,
2197 // `defset <type> <name> = { <statement>... }`
2198 if (Style.isTableGen() &&
2199 Line->Tokens.begin()->Tok->is(Keywords.kw_defset)) {
2200 FormatTok->setFinalizedType(TT_FunctionLBrace);
2201 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
2202 /*MunchSemi=*/false);
2203 addUnwrappedLine();
2204 break;
2205 }
2206 nextToken();
2207 parseBracedList();
2208 } else if (Style.Language == FormatStyle::LK_Proto &&
2209 FormatTok->is(tok::less)) {
2210 nextToken();
2211 parseBracedList(/*IsAngleBracket=*/true);
2212 }
2213 break;
2214 case tok::l_square:
2215 parseSquare();
2216 break;
2217 case tok::kw_new:
2218 if ((Style.isCSharp() &&
2219 (Tokens->peekNextToken()->isAccessSpecifierKeyword() ||
2220 (Previous && Previous->isAccessSpecifierKeyword()))) ||
2221 FormatTok->endsSequence(tok::kw_new, tok::kw_operator)) {
2222 nextToken();
2223 } else {
2224 parseNew();
2225 }
2226 break;
2227 case tok::kw_switch:
2228 if (Style.isJava())
2229 parseSwitch(/*IsExpr=*/true);
2230 else
2231 nextToken();
2232 break;
2233 case tok::kw_case:
2234 // Proto: there are no switch/case statements.
2235 if (Style.Language == FormatStyle::LK_Proto) {
2236 nextToken();
2237 return;
2238 }
2239 // In Verilog switch is called case.
2240 if (Style.isVerilog()) {
2241 parseBlock();
2242 addUnwrappedLine();
2243 return;
2244 }
2245 if (Style.isJavaScript() && Line->MustBeDeclaration) {
2246 // 'case: string' field declaration.
2247 nextToken();
2248 break;
2249 }
2250 parseCaseLabel();
2251 break;
2252 case tok::kw_default:
2253 nextToken();
2254 if (Style.isVerilog()) {
2255 if (FormatTok->is(tok::colon)) {
2256 // The label will be handled in the next iteration.
2257 break;
2258 }
2259 if (FormatTok->is(Keywords.kw_clocking)) {
2260 // A default clocking block.
2261 parseBlock();
2262 addUnwrappedLine();
2263 return;
2264 }
2265 parseVerilogCaseLabel();
2266 return;
2267 }
2268 break;
2269 case tok::colon:
2270 nextToken();
2271 if (Style.isVerilog()) {
2272 parseVerilogCaseLabel();
2273 return;
2274 }
2275 break;
2276 case tok::greater:
2277 nextToken();
2278 if (FormatTok->is(tok::l_brace))
2279 FormatTok->Previous->setFinalizedType(TT_TemplateCloser);
2280 break;
2281 default:
2282 nextToken();
2283 break;
2284 }
2285 }
2286}
2287
2288bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2289 assert(FormatTok->is(tok::l_brace));
2290 if (!Style.isCSharp())
2291 return false;
2292 // See if it's a property accessor.
2293 if (!FormatTok->Previous || FormatTok->Previous->isNot(tok::identifier))
2294 return false;
2295
2296 // See if we are inside a property accessor.
2297 //
2298 // Record the current tokenPosition so that we can advance and
2299 // reset the current token. `Next` is not set yet so we need
2300 // another way to advance along the token stream.
2301 unsigned int StoredPosition = Tokens->getPosition();
2302 FormatToken *Tok = Tokens->getNextToken();
2303
2304 // A trivial property accessor is of the form:
2305 // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set|init] }
2306 // Track these as they do not require line breaks to be introduced.
2307 bool HasSpecialAccessor = false;
2308 bool IsTrivialPropertyAccessor = true;
2309 bool HasAttribute = false;
2310 while (!eof()) {
2311 if (const bool IsAccessorKeyword =
2312 Tok->isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set);
2313 IsAccessorKeyword || Tok->isAccessSpecifierKeyword() ||
2314 Tok->isOneOf(tok::l_square, tok::semi, Keywords.kw_internal)) {
2315 if (IsAccessorKeyword)
2316 HasSpecialAccessor = true;
2317 else if (Tok->is(tok::l_square))
2318 HasAttribute = true;
2319 Tok = Tokens->getNextToken();
2320 continue;
2321 }
2322 if (Tok->isNot(tok::r_brace))
2323 IsTrivialPropertyAccessor = false;
2324 break;
2325 }
2326
2327 if (!HasSpecialAccessor || HasAttribute) {
2328 Tokens->setPosition(StoredPosition);
2329 return false;
2330 }
2331
2332 // Try to parse the property accessor:
2333 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
2334 Tokens->setPosition(StoredPosition);
2335 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2336 addUnwrappedLine();
2337 nextToken();
2338 do {
2339 switch (FormatTok->Tok.getKind()) {
2340 case tok::r_brace:
2341 nextToken();
2342 if (FormatTok->is(tok::equal)) {
2343 while (!eof() && FormatTok->isNot(tok::semi))
2344 nextToken();
2345 nextToken();
2346 }
2347 addUnwrappedLine();
2348 return true;
2349 case tok::l_brace:
2350 ++Line->Level;
2351 parseBlock(/*MustBeDeclaration=*/true);
2352 addUnwrappedLine();
2353 --Line->Level;
2354 break;
2355 case tok::equal:
2356 if (FormatTok->is(TT_FatArrow)) {
2357 ++Line->Level;
2358 do {
2359 nextToken();
2360 } while (!eof() && FormatTok->isNot(tok::semi));
2361 nextToken();
2362 addUnwrappedLine();
2363 --Line->Level;
2364 break;
2365 }
2366 nextToken();
2367 break;
2368 default:
2369 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2370 Keywords.kw_set) &&
2371 !IsTrivialPropertyAccessor) {
2372 // Non-trivial get/set needs to be on its own line.
2373 addUnwrappedLine();
2374 }
2375 nextToken();
2376 }
2377 } while (!eof());
2378
2379 // Unreachable for well-formed code (paired '{' and '}').
2380 return true;
2381}
2382
2383bool UnwrappedLineParser::tryToParseLambda() {
2384 assert(FormatTok->is(tok::l_square));
2385 if (!IsCpp) {
2386 nextToken();
2387 return false;
2388 }
2389 FormatToken &LSquare = *FormatTok;
2390 if (!tryToParseLambdaIntroducer())
2391 return false;
2392
2393 FormatToken *Arrow = nullptr;
2394 bool InTemplateParameterList = false;
2395
2396 while (FormatTok->isNot(tok::l_brace)) {
2397 if (FormatTok->isTypeName(LangOpts) || FormatTok->isAttribute()) {
2398 nextToken();
2399 continue;
2400 }
2401 switch (FormatTok->Tok.getKind()) {
2402 case tok::l_brace:
2403 break;
2404 case tok::l_paren:
2405 parseParens(/*AmpAmpTokenType=*/TT_PointerOrReference);
2406 break;
2407 case tok::l_square:
2408 parseSquare();
2409 break;
2410 case tok::less:
2411 assert(FormatTok->Previous);
2412 if (FormatTok->Previous->is(tok::r_square))
2413 InTemplateParameterList = true;
2414 nextToken();
2415 break;
2416 case tok::kw_auto:
2417 case tok::kw_class:
2418 case tok::kw_struct:
2419 case tok::kw_union:
2420 case tok::kw_template:
2421 case tok::kw_typename:
2422 case tok::amp:
2423 case tok::star:
2424 case tok::kw_const:
2425 case tok::kw_constexpr:
2426 case tok::kw_consteval:
2427 case tok::comma:
2428 case tok::greater:
2429 case tok::identifier:
2430 case tok::numeric_constant:
2431 case tok::coloncolon:
2432 case tok::kw_mutable:
2433 case tok::kw_noexcept:
2434 case tok::kw_static:
2435 nextToken();
2436 break;
2437 // Specialization of a template with an integer parameter can contain
2438 // arithmetic, logical, comparison and ternary operators.
2439 //
2440 // FIXME: This also accepts sequences of operators that are not in the scope
2441 // of a template argument list.
2442 //
2443 // In a C++ lambda a template type can only occur after an arrow. We use
2444 // this as an heuristic to distinguish between Objective-C expressions
2445 // followed by an `a->b` expression, such as:
2446 // ([obj func:arg] + a->b)
2447 // Otherwise the code below would parse as a lambda.
2448 case tok::plus:
2449 case tok::minus:
2450 case tok::exclaim:
2451 case tok::tilde:
2452 case tok::slash:
2453 case tok::percent:
2454 case tok::lessless:
2455 case tok::pipe:
2456 case tok::pipepipe:
2457 case tok::ampamp:
2458 case tok::caret:
2459 case tok::equalequal:
2460 case tok::exclaimequal:
2461 case tok::greaterequal:
2462 case tok::lessequal:
2463 case tok::question:
2464 case tok::colon:
2465 case tok::ellipsis:
2466 case tok::kw_true:
2467 case tok::kw_false:
2468 if (Arrow || InTemplateParameterList) {
2469 nextToken();
2470 break;
2471 }
2472 return true;
2473 case tok::arrow:
2474 Arrow = FormatTok;
2475 nextToken();
2476 break;
2477 case tok::kw_requires:
2478 parseRequiresClause();
2479 break;
2480 case tok::equal:
2481 if (!InTemplateParameterList)
2482 return true;
2483 nextToken();
2484 break;
2485 default:
2486 return true;
2487 }
2488 }
2489
2490 FormatTok->setFinalizedType(TT_LambdaLBrace);
2491 LSquare.setFinalizedType(TT_LambdaLSquare);
2492
2493 if (Arrow)
2494 Arrow->setFinalizedType(TT_LambdaArrow);
2495
2496 NestedLambdas.push_back(Line->SeenDecltypeAuto);
2497 parseChildBlock();
2498 assert(!NestedLambdas.empty());
2499 NestedLambdas.pop_back();
2500
2501 return true;
2502}
2503
2504bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2505 const FormatToken *Previous = FormatTok->Previous;
2506 const FormatToken *LeftSquare = FormatTok;
2507 nextToken();
2508 if (Previous) {
2509 const auto *PrevPrev = Previous->getPreviousNonComment();
2510 if (Previous->is(tok::star) && PrevPrev && PrevPrev->isTypeName(LangOpts))
2511 return false;
2512 if (Previous->closesScope()) {
2513 // Not a potential C-style cast.
2514 if (Previous->isNot(tok::r_paren))
2515 return false;
2516 // Lambdas can be cast to function types only, e.g. `std::function<int()>`
2517 // and `int (*)()`.
2518 if (!PrevPrev || PrevPrev->isNoneOf(tok::greater, tok::r_paren))
2519 return false;
2520 }
2521 if (Previous && Previous->Tok.getIdentifierInfo() &&
2522 Previous->isNoneOf(tok::kw_return, tok::kw_co_await, tok::kw_co_yield,
2523 tok::kw_co_return)) {
2524 return false;
2525 }
2526 }
2527 if (LeftSquare->isCppStructuredBinding(IsCpp))
2528 return false;
2529 if (FormatTok->is(tok::l_square) || tok::isLiteral(FormatTok->Tok.getKind()))
2530 return false;
2531 if (FormatTok->is(tok::r_square)) {
2532 const FormatToken *Next = Tokens->peekNextToken(/*SkipComment=*/true);
2533 if (Next->is(tok::greater))
2534 return false;
2535 }
2536 parseSquare(/*SkipLambda=*/true);
2537 return true;
2538}
2539
2540void UnwrappedLineParser::tryToParseJSFunction() {
2541 assert(FormatTok->is(Keywords.kw_function));
2542 if (FormatTok->is(Keywords.kw_async))
2543 nextToken();
2544 // Consume "function".
2545 nextToken();
2546
2547 // Consume * (generator function). Treat it like C++'s overloaded operators.
2548 if (FormatTok->is(tok::star)) {
2549 FormatTok->setFinalizedType(TT_OverloadedOperator);
2550 nextToken();
2551 }
2552
2553 // Consume function name.
2554 if (FormatTok->is(tok::identifier))
2555 nextToken();
2556
2557 if (FormatTok->isNot(tok::l_paren))
2558 return;
2559
2560 // Parse formal parameter list.
2561 parseParens();
2562
2563 if (FormatTok->is(tok::colon)) {
2564 // Parse a type definition.
2565 nextToken();
2566
2567 // Eat the type declaration. For braced inline object types, balance braces,
2568 // otherwise just parse until finding an l_brace for the function body.
2569 if (FormatTok->is(tok::l_brace))
2570 tryToParseBracedList();
2571 else
2572 while (FormatTok->isNoneOf(tok::l_brace, tok::semi) && !eof())
2573 nextToken();
2574 }
2575
2576 if (FormatTok->is(tok::semi))
2577 return;
2578
2579 parseChildBlock();
2580}
2581
2582bool UnwrappedLineParser::tryToParseBracedList() {
2583 if (FormatTok->is(BK_Unknown))
2584 calculateBraceTypes();
2585 assert(FormatTok->isNot(BK_Unknown));
2586 if (FormatTok->is(BK_Block))
2587 return false;
2588 nextToken();
2589 parseBracedList();
2590 return true;
2591}
2592
2593bool UnwrappedLineParser::tryToParseChildBlock() {
2594 assert(Style.isJavaScript() || Style.isCSharp());
2595 assert(FormatTok->is(TT_FatArrow));
2596 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow.
2597 // They always start an expression or a child block if followed by a curly
2598 // brace.
2599 nextToken();
2600 if (FormatTok->isNot(tok::l_brace))
2601 return false;
2602 parseChildBlock();
2603 return true;
2604}
2605
2606bool UnwrappedLineParser::parseBracedList(bool IsAngleBracket, bool IsEnum) {
2607 assert(!IsAngleBracket || !IsEnum);
2608 bool HasError = false;
2609
2610 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
2611 // replace this by using parseAssignmentExpression() inside.
2612 do {
2613 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2614 tryToParseChildBlock()) {
2615 continue;
2616 }
2617 if (Style.isJavaScript()) {
2618 if (FormatTok->is(Keywords.kw_function)) {
2619 tryToParseJSFunction();
2620 continue;
2621 }
2622 if (FormatTok->is(tok::l_brace)) {
2623 // Could be a method inside of a braced list `{a() { return 1; }}`.
2624 if (tryToParseBracedList())
2625 continue;
2626 parseChildBlock();
2627 }
2628 }
2629 if (FormatTok->is(IsAngleBracket ? tok::greater : tok::r_brace)) {
2630 if (IsEnum) {
2631 FormatTok->setBlockKind(BK_Block);
2632 if (!Style.AllowShortEnumsOnASingleLine)
2633 addUnwrappedLine();
2634 }
2635 nextToken();
2636 return !HasError;
2637 }
2638 switch (FormatTok->Tok.getKind()) {
2639 case tok::l_square:
2640 if (Style.isCSharp())
2641 parseSquare();
2642 else
2643 tryToParseLambda();
2644 break;
2645 case tok::l_paren:
2646 parseParens();
2647 // JavaScript can just have free standing methods and getters/setters in
2648 // object literals. Detect them by a "{" following ")".
2649 if (Style.isJavaScript()) {
2650 if (FormatTok->is(tok::l_brace))
2651 parseChildBlock();
2652 break;
2653 }
2654 break;
2655 case tok::l_brace:
2656 // Assume there are no blocks inside a braced init list apart
2657 // from the ones we explicitly parse out (like lambdas).
2658 FormatTok->setBlockKind(BK_BracedInit);
2659 if (!IsAngleBracket) {
2660 auto *Prev = FormatTok->Previous;
2661 if (Prev && Prev->is(tok::greater))
2662 Prev->setFinalizedType(TT_TemplateCloser);
2663 }
2664 nextToken();
2665 parseBracedList();
2666 break;
2667 case tok::less:
2668 nextToken();
2669 if (IsAngleBracket)
2670 parseBracedList(/*IsAngleBracket=*/true);
2671 break;
2672 case tok::semi:
2673 // JavaScript (or more precisely TypeScript) can have semicolons in braced
2674 // lists (in so-called TypeMemberLists). TextProto and Proto options also
2675 // allow semicolons as field separators. Thus, the semicolon cannot be
2676 // used for error recovery if we have otherwise determined that this is
2677 // a braced list.
2678 if (Style.isJavaScript() || Style.isProto() || Style.isJson()) {
2679 nextToken();
2680 break;
2681 }
2682 HasError = true;
2683 if (!IsEnum)
2684 return false;
2685 nextToken();
2686 break;
2687 case tok::comma:
2688 nextToken();
2689 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2690 addUnwrappedLine();
2691 break;
2692 case tok::kw_requires:
2693 parseRequiresExpression();
2694 break;
2695 default:
2696 nextToken();
2697 break;
2698 }
2699 } while (!eof());
2700 return false;
2701}
2702
2703/// Parses a pair of parentheses (and everything between them).
2704/// \param StarAndAmpTokenType If different than TT_Unknown sets this type for
2705/// all (double) ampersands and stars. This applies for all nested scopes as
2706/// well, this is disabled within a (potential) template argument <>, and thus
2707/// also if we find only a <.
2708///
2709/// Returns whether there is a `=` token between the parentheses.
2710bool UnwrappedLineParser::parseParens(TokenType StarAndAmpTokenType,
2711 bool InMacroCall) {
2712 assert(FormatTok->is(tok::l_paren) && "'(' expected.");
2713 auto *LParen = FormatTok;
2714 auto *Prev = FormatTok->Previous;
2715 bool SeenComma = false;
2716 bool SeenEqual = false;
2717 bool MightBeFoldExpr = false;
2718 unsigned ExcessLess = 0;
2719 nextToken();
2720 const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
2721 if (!InMacroCall && Prev && Prev->is(TT_FunctionLikeMacro))
2722 InMacroCall = true;
2723 do {
2724 switch (FormatTok->Tok.getKind()) {
2725 case tok::l_paren:
2726 if (parseParens(ExcessLess == 0 ? StarAndAmpTokenType : TT_Unknown,
2727 InMacroCall)) {
2728 SeenEqual = true;
2729 }
2730 if (Style.isJava() && FormatTok->is(tok::l_brace))
2731 parseChildBlock();
2732 break;
2733 case tok::r_paren: {
2734 auto *RParen = FormatTok;
2735 nextToken();
2736 if (Prev) {
2737 auto OptionalParens = [&] {
2738 if (Style.RemoveParentheses == FormatStyle::RPS_Leave ||
2739 MightBeStmtExpr || MightBeFoldExpr || SeenComma || InMacroCall ||
2740 Line->InMacroBody || RParen->getPreviousNonComment() == LParen) {
2741 return false;
2742 }
2743 const bool DoubleParens =
2744 Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
2745 if (DoubleParens) {
2746 const auto *PrevPrev = Prev->getPreviousNonComment();
2747 const bool Excluded =
2748 PrevPrev &&
2749 (PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
2750 (SeenEqual &&
2751 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2752 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2753 if (!Excluded)
2754 return true;
2755 } else {
2756 const bool CommaSeparated =
2757 Prev->isOneOf(tok::l_paren, tok::comma) &&
2758 FormatTok->isOneOf(tok::comma, tok::r_paren);
2759 if (CommaSeparated &&
2760 // LParen is not preceded by ellipsis, comma.
2761 !Prev->endsSequence(tok::comma, tok::ellipsis) &&
2762 // RParen is not followed by comma, ellipsis.
2763 !(FormatTok->is(tok::comma) &&
2764 Tokens->peekNextToken()->is(tok::ellipsis))) {
2765 return true;
2766 }
2767 const bool ReturnParens =
2768 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2769 ((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
2770 (!NestedLambdas.empty() && !NestedLambdas.back())) &&
2771 Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
2772 FormatTok->is(tok::semi);
2773 if (ReturnParens)
2774 return true;
2775 }
2776 return false;
2777 };
2778 if (OptionalParens()) {
2779 LParen->Optional = true;
2780 RParen->Optional = true;
2781 } else if (Prev->is(TT_TypenameMacro)) {
2782 LParen->setFinalizedType(TT_TypeDeclarationParen);
2783 RParen->setFinalizedType(TT_TypeDeclarationParen);
2784 } else if (Prev->is(tok::greater) && RParen->Previous == LParen) {
2785 Prev->setFinalizedType(TT_TemplateCloser);
2786 } else if (FormatTok->is(tok::l_brace) && Prev->is(tok::amp) &&
2787 !Prev->Previous) {
2788 FormatTok->setBlockKind(BK_BracedInit);
2789 }
2790 }
2791 return SeenEqual;
2792 }
2793 case tok::r_brace:
2794 // A "}" inside parenthesis is an error if there wasn't a matching "{".
2795 return SeenEqual;
2796 case tok::l_square:
2797 tryToParseLambda();
2798 break;
2799 case tok::l_brace:
2800 if (!tryToParseBracedList())
2801 parseChildBlock();
2802 break;
2803 case tok::at:
2804 nextToken();
2805 if (FormatTok->is(tok::l_brace)) {
2806 nextToken();
2807 parseBracedList();
2808 }
2809 break;
2810 case tok::comma:
2811 SeenComma = true;
2812 nextToken();
2813 break;
2814 case tok::ellipsis:
2815 MightBeFoldExpr = true;
2816 nextToken();
2817 break;
2818 case tok::equal:
2819 SeenEqual = true;
2820 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2821 tryToParseChildBlock();
2822 else
2823 nextToken();
2824 break;
2825 case tok::kw_class:
2826 if (Style.isJavaScript())
2827 parseRecord(/*ParseAsExpr=*/true);
2828 else
2829 nextToken();
2830 break;
2831 case tok::identifier:
2832 if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function)))
2833 tryToParseJSFunction();
2834 else
2835 nextToken();
2836 break;
2837 case tok::kw_switch:
2838 if (Style.isJava())
2839 parseSwitch(/*IsExpr=*/true);
2840 else
2841 nextToken();
2842 break;
2843 case tok::kw_requires:
2844 parseRequiresExpression();
2845 break;
2846 case tok::less:
2847 // We have here no clue whether this is a less, or a template opener, opt
2848 // out of the predefined StarAndAmpTokenType.
2849 ++ExcessLess;
2850 nextToken();
2851 break;
2852 case tok::greater:
2853 if (ExcessLess > 0)
2854 --ExcessLess;
2855 nextToken();
2856 break;
2857 case tok::star:
2858 case tok::amp:
2859 case tok::ampamp:
2860 if (StarAndAmpTokenType != TT_Unknown && ExcessLess == 0)
2861 FormatTok->setFinalizedType(StarAndAmpTokenType);
2862 [[fallthrough]];
2863 default:
2864 nextToken();
2865 break;
2866 }
2867 } while (!eof());
2868 return SeenEqual;
2869}
2870
2871void UnwrappedLineParser::parseSquare(bool SkipLambda) {
2872 if (!SkipLambda) {
2873 assert(FormatTok->is(tok::l_square) && "'[' expected.");
2874 if (tryToParseLambda())
2875 return;
2876 }
2877 do {
2878 switch (FormatTok->Tok.getKind()) {
2879 case tok::l_paren:
2880 parseParens();
2881 break;
2882 case tok::r_square:
2883 nextToken();
2884 return;
2885 case tok::r_brace:
2886 // A "}" inside parenthesis is an error if there wasn't a matching "{".
2887 return;
2888 case tok::l_square:
2889 parseSquare();
2890 break;
2891 case tok::l_brace: {
2892 if (!tryToParseBracedList())
2893 parseChildBlock();
2894 break;
2895 }
2896 case tok::at:
2897 case tok::colon:
2898 nextToken();
2899 if (FormatTok->is(tok::l_brace)) {
2900 nextToken();
2901 parseBracedList();
2902 }
2903 break;
2904 default:
2905 nextToken();
2906 break;
2907 }
2908 } while (!eof());
2909}
2910
2911void UnwrappedLineParser::keepAncestorBraces() {
2912 if (!Style.RemoveBracesLLVM)
2913 return;
2914
2915 const int MaxNestingLevels = 2;
2916 const int Size = NestedTooDeep.size();
2917 if (Size >= MaxNestingLevels)
2918 NestedTooDeep[Size - MaxNestingLevels] = true;
2919 NestedTooDeep.push_back(false);
2920}
2921
2923 for (const auto &Token : llvm::reverse(Line.Tokens))
2924 if (Token.Tok->isNot(tok::comment))
2925 return Token.Tok;
2926
2927 return nullptr;
2928}
2929
2931 return llvm::any_of(
2932 llvm::drop_begin(Line.Tokens),
2933 [](const UnwrappedLineNode &Node) { return Node.Tok->FirstAfterPPLine; });
2934}
2935
2936void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
2937 FormatToken *Tok = nullptr;
2938
2939 if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() &&
2940 !containsPPDirective(*Line) && FormatTok->isNot(tok::semi)) {
2941 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2942 ? getLastNonComment(*Line)
2943 : Line->Tokens.back().Tok;
2944 assert(Tok);
2945 if (Tok->BraceCount < 0) {
2946 assert(Tok->BraceCount == -1);
2947 Tok = nullptr;
2948 } else {
2949 Tok->BraceCount = -1;
2950 }
2951 }
2952
2953 addUnwrappedLine();
2954 const auto BodyStart = CurrentLines->size();
2955 ++Line->Level;
2956 ++Line->UnbracedBodyLevel;
2957 parseStructuralElement();
2958 --Line->UnbracedBodyLevel;
2959
2960 if (Tok) {
2961 assert(!Line->InPPDirective);
2962 FormatToken *const LBraceTok = Tok;
2963 Tok = nullptr;
2964 auto BodyEnd = CurrentLines->size();
2965 while (BodyEnd > 0) {
2966 const auto &L = (*CurrentLines)[--BodyEnd];
2967 if (!L.InPPDirective && getLastNonComment(L)) {
2968 Tok = L.Tokens.back().Tok;
2969 break;
2970 }
2971 }
2972 assert(Tok);
2973 // Don't insert the braces if they would enclose preprocessor directives.
2974 bool EnclosesPPDirective = false;
2975 for (size_t I = BodyStart; I <= BodyEnd && !EnclosesPPDirective; ++I) {
2976 const auto &BodyLine = (*CurrentLines)[I];
2977 EnclosesPPDirective =
2978 BodyLine.InPPDirective ||
2979 llvm::any_of(BodyLine.Tokens, [](const UnwrappedLineNode &Node) {
2980 return Node.Tok->FirstAfterPPLine;
2981 });
2982 }
2983 if (EnclosesPPDirective)
2984 LBraceTok->BraceCount = 0;
2985 else
2986 ++Tok->BraceCount;
2987 }
2988
2989 if (CheckEOF && eof())
2990 addUnwrappedLine();
2991
2992 --Line->Level;
2993}
2994
2995static void markOptionalBraces(FormatToken *LeftBrace) {
2996 if (!LeftBrace)
2997 return;
2998
2999 assert(LeftBrace->is(tok::l_brace));
3000
3001 FormatToken *RightBrace = LeftBrace->MatchingParen;
3002 if (!RightBrace) {
3003 assert(!LeftBrace->Optional);
3004 return;
3005 }
3006
3007 assert(RightBrace->is(tok::r_brace));
3008 assert(RightBrace->MatchingParen == LeftBrace);
3009 assert(LeftBrace->Optional == RightBrace->Optional);
3010
3011 LeftBrace->Optional = true;
3012 RightBrace->Optional = true;
3013}
3014
3015void UnwrappedLineParser::handleAttributes() {
3016 // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
3017 if (FormatTok->isAttribute())
3018 nextToken();
3019 else if (FormatTok->is(tok::l_square))
3020 handleCppAttributes();
3021}
3022
3023bool UnwrappedLineParser::handleCppAttributes() {
3024 // Handle [[likely]] / [[unlikely]] attributes.
3025 assert(FormatTok->is(tok::l_square));
3026 if (!tryToParseSimpleAttribute())
3027 return false;
3028 parseSquare();
3029 return true;
3030}
3031
3032/// Returns whether \c Tok begins a block.
3033bool UnwrappedLineParser::isBlockBegin(const FormatToken &Tok) const {
3034 // FIXME: rename the function or make
3035 // Tok.isOneOf(tok::l_brace, TT_MacroBlockBegin) work.
3036 return Style.isVerilog() ? Keywords.isVerilogBegin(Tok)
3037 : Tok.is(tok::l_brace);
3038}
3039
3040FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
3041 bool KeepBraces,
3042 bool IsVerilogAssert) {
3043 assert((FormatTok->is(tok::kw_if) ||
3044 (Style.isVerilog() &&
3045 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
3046 Keywords.kw_assume, Keywords.kw_cover))) &&
3047 "'if' expected");
3048 nextToken();
3049
3050 if (IsVerilogAssert) {
3051 // Handle `assert #0` and `assert final`.
3052 if (FormatTok->is(Keywords.kw_verilogHash)) {
3053 nextToken();
3054 if (FormatTok->is(tok::numeric_constant))
3055 nextToken();
3056 } else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
3057 Keywords.kw_sequence)) {
3058 nextToken();
3059 }
3060 }
3061
3062 // TableGen's if statement has the form of `if <cond> then { ... }`.
3063 if (Style.isTableGen()) {
3064 while (!eof() && FormatTok->isNot(Keywords.kw_then)) {
3065 // Simply skip until then. This range only contains a value.
3066 nextToken();
3067 }
3068 }
3069
3070 // Handle `if !consteval`.
3071 if (FormatTok->is(tok::exclaim))
3072 nextToken();
3073
3074 bool KeepIfBraces = true;
3075 if (FormatTok->is(tok::kw_consteval)) {
3076 nextToken();
3077 } else {
3078 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
3079 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
3080 nextToken();
3081 if (FormatTok->is(tok::l_paren)) {
3082 FormatTok->setFinalizedType(TT_ConditionLParen);
3083 parseParens();
3084 }
3085 }
3086 handleAttributes();
3087 // The then action is optional in Verilog assert statements.
3088 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
3089 nextToken();
3090 addUnwrappedLine();
3091 return nullptr;
3092 }
3093
3094 bool NeedsUnwrappedLine = false;
3095 keepAncestorBraces();
3096
3097 FormatToken *IfLeftBrace = nullptr;
3098 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
3099
3100 if (isBlockBegin(*FormatTok)) {
3101 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3102 IfLeftBrace = FormatTok;
3103 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3104 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
3105 /*MunchSemi=*/true, KeepIfBraces, &IfBlockKind);
3106 setPreviousRBraceType(TT_ControlStatementRBrace);
3107 if (Style.BraceWrapping.BeforeElse)
3108 addUnwrappedLine();
3109 else
3110 NeedsUnwrappedLine = true;
3111 } else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
3112 addUnwrappedLine();
3113 } else {
3114 parseUnbracedBody();
3115 }
3116
3117 if (Style.RemoveBracesLLVM) {
3118 assert(!NestedTooDeep.empty());
3119 KeepIfBraces = KeepIfBraces ||
3120 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
3121 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
3122 IfBlockKind == IfStmtKind::IfElseIf;
3123 }
3124
3125 bool KeepElseBraces = KeepIfBraces;
3126 FormatToken *ElseLeftBrace = nullptr;
3127 IfStmtKind Kind = IfStmtKind::IfOnly;
3128
3129 if (FormatTok->is(tok::kw_else)) {
3130 if (Style.RemoveBracesLLVM) {
3131 NestedTooDeep.back() = false;
3132 Kind = IfStmtKind::IfElse;
3133 }
3134 nextToken();
3135 handleAttributes();
3136 if (isBlockBegin(*FormatTok)) {
3137 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
3138 FormatTok->setFinalizedType(TT_ElseLBrace);
3139 ElseLeftBrace = FormatTok;
3140 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3141 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
3142 FormatToken *IfLBrace =
3143 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
3144 /*MunchSemi=*/true, KeepElseBraces, &ElseBlockKind);
3145 setPreviousRBraceType(TT_ElseRBrace);
3146 if (FormatTok->is(tok::kw_else)) {
3147 KeepElseBraces = KeepElseBraces ||
3148 ElseBlockKind == IfStmtKind::IfOnly ||
3149 ElseBlockKind == IfStmtKind::IfElseIf;
3150 } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
3151 KeepElseBraces = true;
3152 assert(ElseLeftBrace->MatchingParen);
3153 markOptionalBraces(ElseLeftBrace);
3154 }
3155 addUnwrappedLine();
3156 } else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
3157 const FormatToken *Previous = Tokens->getPreviousToken();
3158 assert(Previous);
3159 const bool IsPrecededByComment = Previous->is(tok::comment);
3160 if (IsPrecededByComment) {
3161 addUnwrappedLine();
3162 ++Line->Level;
3163 }
3164 bool TooDeep = true;
3165 if (Style.RemoveBracesLLVM) {
3166 Kind = IfStmtKind::IfElseIf;
3167 TooDeep = NestedTooDeep.pop_back_val();
3168 }
3169 ElseLeftBrace = parseIfThenElse(/*IfKind=*/nullptr, KeepIfBraces);
3170 if (Style.RemoveBracesLLVM)
3171 NestedTooDeep.push_back(TooDeep);
3172 if (IsPrecededByComment)
3173 --Line->Level;
3174 } else {
3175 parseUnbracedBody(/*CheckEOF=*/true);
3176 }
3177 } else {
3178 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
3179 if (NeedsUnwrappedLine)
3180 addUnwrappedLine();
3181 }
3182
3183 if (!Style.RemoveBracesLLVM)
3184 return nullptr;
3185
3186 assert(!NestedTooDeep.empty());
3187 KeepElseBraces = KeepElseBraces ||
3188 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
3189 NestedTooDeep.back();
3190
3191 NestedTooDeep.pop_back();
3192
3193 if (!KeepIfBraces && !KeepElseBraces) {
3194 markOptionalBraces(IfLeftBrace);
3195 markOptionalBraces(ElseLeftBrace);
3196 } else if (IfLeftBrace) {
3197 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
3198 if (IfRightBrace) {
3199 assert(IfRightBrace->MatchingParen == IfLeftBrace);
3200 assert(!IfLeftBrace->Optional);
3201 assert(!IfRightBrace->Optional);
3202 IfLeftBrace->MatchingParen = nullptr;
3203 IfRightBrace->MatchingParen = nullptr;
3204 }
3205 }
3206
3207 if (IfKind)
3208 *IfKind = Kind;
3209
3210 return IfLeftBrace;
3211}
3212
3213void UnwrappedLineParser::parseTryCatch() {
3214 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
3215 nextToken();
3216 bool NeedsUnwrappedLine = false;
3217 bool HasCtorInitializer = false;
3218 if (FormatTok->is(tok::colon)) {
3219 auto *Colon = FormatTok;
3220 // We are in a function try block, what comes is an initializer list.
3221 nextToken();
3222 if (FormatTok->is(tok::identifier)) {
3223 HasCtorInitializer = true;
3224 Colon->setFinalizedType(TT_CtorInitializerColon);
3225 }
3226
3227 // In case identifiers were removed by clang-tidy, what might follow is
3228 // multiple commas in sequence - before the first identifier.
3229 while (FormatTok->is(tok::comma))
3230 nextToken();
3231
3232 while (FormatTok->is(tok::identifier)) {
3233 nextToken();
3234 if (FormatTok->is(tok::l_paren)) {
3235 parseParens();
3236 } else if (FormatTok->is(tok::l_brace)) {
3237 nextToken();
3238 parseBracedList();
3239 }
3240
3241 // In case identifiers were removed by clang-tidy, what might follow is
3242 // multiple commas in sequence - after the first identifier.
3243 while (FormatTok->is(tok::comma))
3244 nextToken();
3245 }
3246 }
3247 // Parse try with resource.
3248 if (Style.isJava() && FormatTok->is(tok::l_paren))
3249 parseParens();
3250
3251 keepAncestorBraces();
3252
3253 if (FormatTok->is(tok::l_brace)) {
3254 if (HasCtorInitializer)
3255 FormatTok->setFinalizedType(TT_FunctionLBrace);
3256 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3257 parseBlock();
3258 if (Style.BraceWrapping.BeforeCatch)
3259 addUnwrappedLine();
3260 else
3261 NeedsUnwrappedLine = true;
3262 } else if (FormatTok->isNot(tok::kw_catch)) {
3263 // The C++ standard requires a compound-statement after a try.
3264 // If there's none, we try to assume there's a structuralElement
3265 // and try to continue.
3266 addUnwrappedLine();
3267 ++Line->Level;
3268 parseStructuralElement();
3269 --Line->Level;
3270 }
3271 for (bool SeenCatch = false;;) {
3272 if (FormatTok->is(tok::at))
3273 nextToken();
3274 if (FormatTok->isNoneOf(tok::kw_catch, Keywords.kw___except,
3275 tok::kw___finally, tok::objc_catch,
3276 tok::objc_finally) &&
3277 !((Style.isJava() || Style.isJavaScript()) &&
3278 FormatTok->is(Keywords.kw_finally))) {
3279 break;
3280 }
3281 if (FormatTok->is(tok::kw_catch))
3282 SeenCatch = true;
3283 nextToken();
3284 while (FormatTok->isNot(tok::l_brace)) {
3285 if (FormatTok->is(tok::l_paren)) {
3286 parseParens();
3287 continue;
3288 }
3289 if (FormatTok->isOneOf(tok::semi, tok::r_brace) || eof()) {
3290 if (Style.RemoveBracesLLVM)
3291 NestedTooDeep.pop_back();
3292 return;
3293 }
3294 nextToken();
3295 }
3296 if (SeenCatch) {
3297 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3298 SeenCatch = false;
3299 }
3300 NeedsUnwrappedLine = false;
3301 Line->MustBeDeclaration = false;
3302 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3303 parseBlock();
3304 if (Style.BraceWrapping.BeforeCatch)
3305 addUnwrappedLine();
3306 else
3307 NeedsUnwrappedLine = true;
3308 }
3309
3310 if (Style.RemoveBracesLLVM)
3311 NestedTooDeep.pop_back();
3312
3313 if (NeedsUnwrappedLine)
3314 addUnwrappedLine();
3315}
3316
3317void UnwrappedLineParser::parseNamespaceOrExportBlock(unsigned AddLevels) {
3318 bool ManageWhitesmithsBraces =
3319 AddLevels == 0u && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3320
3321 // If we're in Whitesmiths mode, indent the brace if we're not indenting
3322 // the whole block.
3323 if (ManageWhitesmithsBraces)
3324 ++Line->Level;
3325
3326 // Munch the semicolon after the block. This is more common than one would
3327 // think. Putting the semicolon into its own line is very ugly.
3328 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/true,
3329 /*KeepBraces=*/true, /*IfKind=*/nullptr, ManageWhitesmithsBraces);
3330
3331 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
3332
3333 if (ManageWhitesmithsBraces)
3334 --Line->Level;
3335}
3336
3337void UnwrappedLineParser::parseNamespace() {
3338 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
3339 "'namespace' expected");
3340
3341 const FormatToken &InitialToken = *FormatTok;
3342 nextToken();
3343 if (InitialToken.is(TT_NamespaceMacro)) {
3344 parseParens();
3345 } else {
3346 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
3347 tok::l_square, tok::period, tok::l_paren) ||
3348 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
3349 if (FormatTok->is(tok::l_square))
3350 parseSquare();
3351 else if (FormatTok->is(tok::l_paren))
3352 parseParens();
3353 else
3354 nextToken();
3355 }
3356 }
3357 if (FormatTok->is(tok::l_brace)) {
3358 FormatTok->setFinalizedType(TT_NamespaceLBrace);
3359
3360 if (ShouldBreakBeforeBrace(Style, InitialToken,
3361 Tokens->peekNextToken()->is(tok::r_brace))) {
3362 addUnwrappedLine();
3363 }
3364
3365 unsigned AddLevels =
3366 Style.NamespaceIndentation == FormatStyle::NI_All ||
3367 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
3368 DeclarationScopeStack.size() > 1)
3369 ? 1u
3370 : 0u;
3371 parseNamespaceOrExportBlock(AddLevels);
3372 }
3373 // FIXME: Add error handling.
3374}
3375
3376void UnwrappedLineParser::parseCppExportBlock() {
3377 if (FormatTok->is(tok::l_brace)) {
3378 FormatTok->setFinalizedType(TT_ExportLBrace);
3379 if (Style.BraceWrapping.AfterExportBlock)
3380 addUnwrappedLine();
3381 }
3382 parseNamespaceOrExportBlock(/*AddLevels=*/Style.IndentExportBlock ? 1 : 0);
3383}
3384
3385void UnwrappedLineParser::parseNew() {
3386 assert(FormatTok->is(tok::kw_new) && "'new' expected");
3387 nextToken();
3388
3389 if (Style.isCSharp()) {
3390 do {
3391 // Handle constructor invocation, e.g. `new(field: value)`.
3392 if (FormatTok->is(tok::l_paren))
3393 parseParens();
3394
3395 // Handle array initialization syntax, e.g. `new[] {10, 20, 30}`.
3396 if (FormatTok->is(tok::l_brace))
3397 parseBracedList();
3398
3399 if (FormatTok->isOneOf(tok::semi, tok::comma))
3400 return;
3401
3402 nextToken();
3403 } while (!eof());
3404 } else if (Style.isJava()) {
3405 // In Java, we can parse everything up to the parens, which aren't optional.
3406 do {
3407 // There should not be a ;, { or } before the new's open paren.
3408 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3409 return;
3410
3411 // Consume the parens.
3412 if (FormatTok->is(tok::l_paren)) {
3413 parseParens();
3414
3415 // If there is a class body of an anonymous class, consume that as
3416 // child.
3417 if (FormatTok->is(tok::l_brace))
3418 parseChildBlock();
3419 return;
3420 }
3421 nextToken();
3422 } while (!eof());
3423 } else if (Style.isCpp()) {
3424 // The brace should not appear here in a new expression. It likely means
3425 // that the line is incomplete or that new is not a keyword such as in
3426 // Objective-C.
3427 if (FormatTok->is(tok::l_brace))
3428 return;
3429 if (FormatTok->is(tok::l_paren))
3430 parseParens();
3431 if (FormatTok->is(tok::l_paren)) {
3432 parseParens();
3433 } else {
3434 // When there are 2 pairs of parentheses, the second will be the type.
3435 // Otherwise, the type may be outside parentheses. It is handled here.
3436 while (!eof()) {
3437 if (FormatTok->isOneOf(tok::kw_alignas, tok::kw_decltype)) {
3438 nextToken();
3439 if (FormatTok->is(tok::l_paren))
3440 parseParens();
3441 } else if (FormatTok->is(tok::l_square)) {
3442 nextToken();
3443 parseSquare(/*SkipLambda=*/true);
3444 } else if (FormatTok->is(tok::less)) {
3445 nextToken();
3446 parseBracedList(/*IsAngleBracket=*/true);
3447 } else if (FormatTok->Tok.getIdentifierInfo() ||
3448 FormatTok->isOneOf(tok::coloncolon, tok::star)) {
3449 nextToken();
3450 } else {
3451 break;
3452 }
3453 }
3454 }
3455 if (FormatTok->is(tok::l_brace))
3456 parseBracedList();
3457 else if (FormatTok->is(tok::l_paren))
3458 parseParens();
3459 }
3460}
3461
3462void UnwrappedLineParser::parseLoopBody(bool KeepBraces, bool WrapRightBrace) {
3463 keepAncestorBraces();
3464
3465 if (isBlockBegin(*FormatTok)) {
3466 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3467 FormatToken *LeftBrace = FormatTok;
3468 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3469 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
3470 /*MunchSemi=*/true, KeepBraces);
3471 setPreviousRBraceType(TT_ControlStatementRBrace);
3472 if (!KeepBraces) {
3473 assert(!NestedTooDeep.empty());
3474 if (!NestedTooDeep.back())
3475 markOptionalBraces(LeftBrace);
3476 }
3477 if (WrapRightBrace)
3478 addUnwrappedLine();
3479 } else {
3480 parseUnbracedBody();
3481 }
3482
3483 if (!KeepBraces)
3484 NestedTooDeep.pop_back();
3485}
3486
3487void UnwrappedLineParser::parseForOrWhileLoop(bool HasParens) {
3488 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3489 (Style.isVerilog() &&
3490 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3491 Keywords.kw_always_ff, Keywords.kw_always_latch,
3492 Keywords.kw_final, Keywords.kw_initial,
3493 Keywords.kw_foreach, Keywords.kw_forever,
3494 Keywords.kw_repeat))) &&
3495 "'for', 'while' or foreach macro expected");
3496 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3497 FormatTok->isNoneOf(tok::kw_for, tok::kw_while);
3498
3499 nextToken();
3500 // JS' for await ( ...
3501 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3502 nextToken();
3503 if (IsCpp && FormatTok->is(tok::kw_co_await))
3504 nextToken();
3505 if (HasParens && FormatTok->is(tok::l_paren)) {
3506 // The type is only set for Verilog basically because we were afraid to
3507 // change the existing behavior for loops. See the discussion on D121756 for
3508 // details.
3509 if (Style.isVerilog())
3510 FormatTok->setFinalizedType(TT_ConditionLParen);
3511 parseParens();
3512 }
3513
3514 if (Style.isVerilog()) {
3515 // Event control.
3516 parseVerilogSensitivityList();
3517 } else if (Style.AllowShortLoopsOnASingleLine && FormatTok->is(tok::semi) &&
3518 Tokens->getPreviousToken()->is(tok::r_paren)) {
3519 nextToken();
3520 addUnwrappedLine();
3521 return;
3522 }
3523
3524 handleAttributes();
3525 parseLoopBody(KeepBraces, /*WrapRightBrace=*/true);
3526}
3527
3528void UnwrappedLineParser::parseDoWhile() {
3529 assert(FormatTok->is(tok::kw_do) && "'do' expected");
3530 nextToken();
3531
3532 parseLoopBody(/*KeepBraces=*/true, Style.BraceWrapping.BeforeWhile);
3533
3534 // FIXME: Add error handling.
3535 if (FormatTok->isNot(tok::kw_while)) {
3536 addUnwrappedLine();
3537 return;
3538 }
3539
3540 FormatTok->setFinalizedType(TT_DoWhile);
3541
3542 // If in Whitesmiths mode, the line with the while() needs to be indented
3543 // to the same level as the block.
3544 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3545 ++Line->Level;
3546
3547 nextToken();
3548 parseStructuralElement();
3549}
3550
3551void UnwrappedLineParser::parseLabel(bool IsGotoLabel) {
3552 nextToken();
3553
3554 const auto IndentGotoLabel = Style.IndentGotoLabels;
3555 const auto OldLineLevel = Line->Level;
3556 auto &Level = Line->Level;
3557
3558 if (IsGotoLabel && IndentGotoLabel == FormatStyle::IGLS_NoIndent)
3559 Level = 0;
3560
3561 if (!IsGotoLabel || IndentGotoLabel == FormatStyle::IGLS_OuterIndent) {
3562 if (OldLineLevel > 1 || (!Line->InPPDirective && OldLineLevel > 0))
3563 --Level;
3564 }
3565
3566 if (!IsGotoLabel && !Style.IndentCaseBlocks &&
3567 CommentsBeforeNextToken.empty() && FormatTok->is(tok::l_brace)) {
3568 CompoundStatementIndenter Indenter(this, Level,
3569 Style.BraceWrapping.AfterCaseLabel,
3570 Style.BraceWrapping.IndentBraces);
3571 parseBlock();
3572 if (FormatTok->is(tok::kw_break)) {
3573 if (Style.BraceWrapping.AfterControlStatement ==
3575 Style.CompactCaseLabels) {
3576 addUnwrappedLine();
3577 if (!Style.IndentCaseBlocks &&
3578 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3579 ++Level;
3580 }
3581 }
3582 parseStructuralElement();
3583 }
3584 addUnwrappedLine();
3585 } else {
3586 if (FormatTok->is(tok::semi))
3587 nextToken();
3588 addUnwrappedLine();
3589 }
3590
3591 Level = OldLineLevel;
3592
3593 if (FormatTok->isNot(tok::l_brace)) {
3594 parseStructuralElement();
3595 addUnwrappedLine();
3596 }
3597}
3598
3599void UnwrappedLineParser::parseCaseLabel() {
3600 assert(FormatTok->is(tok::kw_case) && "'case' expected");
3601 auto *Case = FormatTok;
3602
3603 // FIXME: fix handling of complex expressions here.
3604 do {
3605 nextToken();
3606 if (FormatTok->is(tok::colon)) {
3607 FormatTok->setFinalizedType(TT_CaseLabelColon);
3608 break;
3609 }
3610 if (Style.isJava() && FormatTok->is(tok::arrow)) {
3611 FormatTok->setFinalizedType(TT_CaseLabelArrow);
3612 Case->setFinalizedType(TT_SwitchExpressionLabel);
3613 break;
3614 }
3615 } while (!eof());
3616 parseLabel();
3617}
3618
3619void UnwrappedLineParser::parseSwitch(bool IsExpr) {
3620 assert(FormatTok->is(tok::kw_switch) && "'switch' expected");
3621 nextToken();
3622 if (FormatTok->is(tok::l_paren))
3623 parseParens();
3624
3625 keepAncestorBraces();
3626
3627 if (FormatTok->is(tok::l_brace)) {
3628 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3629 FormatTok->setFinalizedType(IsExpr ? TT_SwitchExpressionLBrace
3630 : TT_ControlStatementLBrace);
3631 if (IsExpr)
3632 parseChildBlock();
3633 else
3634 parseBlock();
3635 setPreviousRBraceType(TT_ControlStatementRBrace);
3636 if (!IsExpr)
3637 addUnwrappedLine();
3638 } else {
3639 addUnwrappedLine();
3640 ++Line->Level;
3641 parseStructuralElement();
3642 --Line->Level;
3643 }
3644
3645 if (Style.RemoveBracesLLVM)
3646 NestedTooDeep.pop_back();
3647}
3648
3649void UnwrappedLineParser::parseAccessSpecifier() {
3650 nextToken();
3651 // Understand Qt's slots.
3652 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3653 nextToken();
3654 // Otherwise, we don't know what it is, and we'd better keep the next token.
3655 if (FormatTok->is(tok::colon))
3656 nextToken();
3657 addUnwrappedLine();
3658}
3659
3660/// Parses a requires, decides if it is a clause or an expression.
3661/// \pre The current token has to be the requires keyword.
3662/// \returns true if it parsed a clause.
3663bool UnwrappedLineParser::parseRequires(bool SeenEqual) {
3664 assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
3665
3666 // We try to guess if it is a requires clause, or a requires expression. For
3667 // that we first check the next token.
3668 switch (Tokens->peekNextToken(/*SkipComment=*/true)->Tok.getKind()) {
3669 case tok::l_brace:
3670 // This can only be an expression, never a clause.
3671 parseRequiresExpression();
3672 return false;
3673 case tok::l_paren:
3674 // Clauses and expression can start with a paren, it's unclear what we have.
3675 break;
3676 default:
3677 // All other tokens can only be a clause.
3678 parseRequiresClause();
3679 return true;
3680 }
3681
3682 // Looking forward we would have to decide if there are function declaration
3683 // like arguments to the requires expression:
3684 // requires (T t) {
3685 // Or there is a constraint expression for the requires clause:
3686 // requires (C<T> && ...
3687
3688 // But first let's look behind.
3689 auto *PreviousNonComment = FormatTok->getPreviousNonComment();
3690
3691 if (!PreviousNonComment ||
3692 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3693 // If there is no token, or an expression left brace, we are a requires
3694 // clause within a requires expression.
3695 parseRequiresClause();
3696 return true;
3697 }
3698
3699 switch (PreviousNonComment->Tok.getKind()) {
3700 case tok::greater:
3701 case tok::r_paren:
3702 case tok::kw_noexcept:
3703 case tok::kw_const:
3704 case tok::star:
3705 case tok::amp:
3706 // This is a requires clause.
3707 parseRequiresClause();
3708 return true;
3709 case tok::ampamp: {
3710 // This can be either:
3711 // if (... && requires (T t) ...)
3712 // Or
3713 // void member(...) && requires (C<T> ...
3714 // We check the one token before that for a const:
3715 // void member(...) const && requires (C<T> ...
3716 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3717 if ((PrevPrev && PrevPrev->is(tok::kw_const)) || !SeenEqual) {
3718 parseRequiresClause();
3719 return true;
3720 }
3721 break;
3722 }
3723 default:
3724 if (PreviousNonComment->isTypeOrIdentifier(LangOpts)) {
3725 // This is a requires clause.
3726 parseRequiresClause();
3727 return true;
3728 }
3729 // It's an expression.
3730 parseRequiresExpression();
3731 return false;
3732 }
3733
3734 // Now we look forward and try to check if the paren content is a parameter
3735 // list. The parameters can be cv-qualified and contain references or
3736 // pointers.
3737 // So we want basically to check for TYPE NAME, but TYPE can contain all kinds
3738 // of stuff: typename, const, *, &, &&, ::, identifiers.
3739
3740 unsigned StoredPosition = Tokens->getPosition();
3741 FormatToken *NextToken = Tokens->getNextToken();
3742 int Lookahead = 0;
3743 auto PeekNext = [&Lookahead, &NextToken, this] {
3744 ++Lookahead;
3745 NextToken = Tokens->getNextToken();
3746 };
3747
3748 bool FoundType = false;
3749 bool LastWasColonColon = false;
3750 int OpenAngles = 0;
3751
3752 for (; Lookahead < 50; PeekNext()) {
3753 switch (NextToken->Tok.getKind()) {
3754 case tok::kw_volatile:
3755 case tok::kw_const:
3756 case tok::comma:
3757 if (OpenAngles == 0) {
3758 FormatTok = Tokens->setPosition(StoredPosition);
3759 parseRequiresExpression();
3760 return false;
3761 }
3762 break;
3763 case tok::eof:
3764 // Break out of the loop.
3765 Lookahead = 50;
3766 break;
3767 case tok::coloncolon:
3768 LastWasColonColon = true;
3769 break;
3770 case tok::kw_decltype:
3771 case tok::identifier:
3772 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3773 FormatTok = Tokens->setPosition(StoredPosition);
3774 parseRequiresExpression();
3775 return false;
3776 }
3777 FoundType = true;
3778 LastWasColonColon = false;
3779 break;
3780 case tok::less:
3781 ++OpenAngles;
3782 break;
3783 case tok::greater:
3784 --OpenAngles;
3785 break;
3786 default:
3787 if (NextToken->isTypeName(LangOpts)) {
3788 FormatTok = Tokens->setPosition(StoredPosition);
3789 parseRequiresExpression();
3790 return false;
3791 }
3792 break;
3793 }
3794 }
3795 // This seems to be a complicated expression, just assume it's a clause.
3796 FormatTok = Tokens->setPosition(StoredPosition);
3797 parseRequiresClause();
3798 return true;
3799}
3800
3801/// Parses a requires clause.
3802/// \sa parseRequiresExpression
3803///
3804/// Returns if it either has finished parsing the clause, or it detects, that
3805/// the clause is incorrect.
3806void UnwrappedLineParser::parseRequiresClause() {
3807 assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
3808
3809 // If there is no previous token, we are within a requires expression,
3810 // otherwise we will always have the template or function declaration in front
3811 // of it.
3812 bool InRequiresExpression =
3813 !FormatTok->Previous ||
3814 FormatTok->Previous->is(TT_RequiresExpressionLBrace);
3815
3816 FormatTok->setFinalizedType(InRequiresExpression
3817 ? TT_RequiresClauseInARequiresExpression
3818 : TT_RequiresClause);
3819 nextToken();
3820
3821 // NOTE: parseConstraintExpression is only ever called from this function.
3822 // It could be inlined into here.
3823 parseConstraintExpression();
3824
3825 if (!InRequiresExpression && FormatTok->Previous)
3826 FormatTok->Previous->ClosesRequiresClause = true;
3827}
3828
3829/// Parses a requires expression.
3830/// \sa parseRequiresClause
3831///
3832/// Returns if it either has finished parsing the expression, or it detects,
3833/// that the expression is incorrect.
3834void UnwrappedLineParser::parseRequiresExpression() {
3835 assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
3836
3837 FormatTok->setFinalizedType(TT_RequiresExpression);
3838 nextToken();
3839
3840 if (FormatTok->is(tok::l_paren)) {
3841 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3842 parseParens();
3843 }
3844
3845 if (FormatTok->is(tok::l_brace)) {
3846 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3847 parseChildBlock();
3848 }
3849}
3850
3851/// Parses a constraint expression.
3852///
3853/// This is the body of a requires clause. It returns, when the parsing is
3854/// complete, or the expression is incorrect.
3855void UnwrappedLineParser::parseConstraintExpression() {
3856 // The special handling for lambdas is needed since tryToParseLambda() eats a
3857 // token and if a requires expression is the last part of a requires clause
3858 // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is
3859 // not set on the correct token. Thus we need to be aware if we even expect a
3860 // lambda to be possible.
3861 // template <typename T> requires requires { ... } [[nodiscard]] ...;
3862 bool LambdaNextTimeAllowed = true;
3863
3864 // Within lambda declarations, it is permitted to put a requires clause after
3865 // its template parameter list, which would place the requires clause right
3866 // before the parentheses of the parameters of the lambda declaration. Thus,
3867 // we track if we expect to see grouping parentheses at all.
3868 // Without this check, `requires foo<T> (T t)` in the below example would be
3869 // seen as the whole requires clause, accidentally eating the parameters of
3870 // the lambda.
3871 // [&]<typename T> requires foo<T> (T t) { ... };
3872 bool TopLevelParensAllowed = true;
3873
3874 do {
3875 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false);
3876
3877 switch (FormatTok->Tok.getKind()) {
3878 case tok::kw_requires:
3879 parseRequiresExpression();
3880 break;
3881
3882 case tok::l_paren:
3883 if (!TopLevelParensAllowed)
3884 return;
3885 parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator);
3886 TopLevelParensAllowed = false;
3887 break;
3888
3889 case tok::l_square:
3890 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3891 return;
3892 break;
3893
3894 case tok::kw_const:
3895 case tok::semi:
3896 case tok::kw_class:
3897 case tok::kw_struct:
3898 case tok::kw_union:
3899 return;
3900
3901 case tok::l_brace:
3902 // Potential function body.
3903 return;
3904
3905 case tok::ampamp:
3906 case tok::pipepipe:
3907 FormatTok->setFinalizedType(TT_BinaryOperator);
3908 nextToken();
3909 LambdaNextTimeAllowed = true;
3910 TopLevelParensAllowed = true;
3911 break;
3912
3913 case tok::comma:
3914 case tok::comment:
3915 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3916 nextToken();
3917 break;
3918
3919 case tok::kw_sizeof:
3920 case tok::greater:
3921 case tok::greaterequal:
3922 case tok::greatergreater:
3923 case tok::less:
3924 case tok::lessequal:
3925 case tok::lessless:
3926 case tok::equalequal:
3927 case tok::exclaim:
3928 case tok::exclaimequal:
3929 case tok::plus:
3930 case tok::minus:
3931 case tok::star:
3932 case tok::slash:
3933 LambdaNextTimeAllowed = true;
3934 TopLevelParensAllowed = true;
3935 // Just eat them.
3936 nextToken();
3937 break;
3938
3939 case tok::numeric_constant:
3940 case tok::coloncolon:
3941 case tok::kw_true:
3942 case tok::kw_false:
3943 TopLevelParensAllowed = false;
3944 // Just eat them.
3945 nextToken();
3946 break;
3947
3948 case tok::kw_static_cast:
3949 case tok::kw_const_cast:
3950 case tok::kw_reinterpret_cast:
3951 case tok::kw_dynamic_cast:
3952 nextToken();
3953 if (FormatTok->isNot(tok::less))
3954 return;
3955
3956 nextToken();
3957 parseBracedList(/*IsAngleBracket=*/true);
3958 break;
3959
3960 default:
3961 if (!FormatTok->Tok.getIdentifierInfo()) {
3962 // Identifiers are part of the default case, we check for more then
3963 // tok::identifier to handle builtin type traits.
3964 return;
3965 }
3966
3967 // We need to differentiate identifiers for a template deduction guide,
3968 // variables, or function return types (the constraint expression has
3969 // ended before that), and basically all other cases. But it's easier to
3970 // check the other way around.
3971 assert(FormatTok->Previous);
3972 switch (FormatTok->Previous->Tok.getKind()) {
3973 case tok::coloncolon: // Nested identifier.
3974 case tok::ampamp: // Start of a function or variable for the
3975 case tok::pipepipe: // constraint expression. (binary)
3976 case tok::exclaim: // The same as above, but unary.
3977 case tok::kw_requires: // Initial identifier of a requires clause.
3978 case tok::equal: // Initial identifier of a concept declaration.
3979 case tok::kw_template: // A dependent template.
3980 break;
3981 default:
3982 return;
3983 }
3984
3985 // Read identifier with optional template declaration.
3986 nextToken();
3987 if (FormatTok->is(tok::less)) {
3988 nextToken();
3989 parseBracedList(/*IsAngleBracket=*/true);
3990 }
3991 TopLevelParensAllowed = false;
3992 break;
3993 }
3994 } while (!eof());
3995}
3996
3997bool UnwrappedLineParser::parseEnum() {
3998 const FormatToken &InitialToken = *FormatTok;
3999
4000 // Won't be 'enum' for NS_ENUMs.
4001 if (FormatTok->is(tok::kw_enum))
4002 nextToken();
4003
4004 // In TypeScript, "enum" can also be used as property name, e.g. in interface
4005 // declarations. An "enum" keyword followed by a colon would be a syntax
4006 // error and thus assume it is just an identifier.
4007 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
4008 return false;
4009
4010 // In protobuf, "enum" can be used as a field name.
4011 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
4012 return false;
4013
4014 if (IsCpp) {
4015 // Eat up enum class ...
4016 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
4017 nextToken();
4018 while (FormatTok->is(tok::l_square))
4019 if (!handleCppAttributes())
4020 return false;
4021 }
4022
4023 while (FormatTok->Tok.getIdentifierInfo() ||
4024 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
4025 tok::greater, tok::comma, tok::question,
4026 tok::l_square)) {
4027 if (FormatTok->is(tok::colon))
4028 FormatTok->setFinalizedType(TT_EnumUnderlyingTypeColon);
4029 if (Style.isVerilog()) {
4030 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
4031 nextToken();
4032 // In Verilog the base type can have dimensions.
4033 while (FormatTok->is(tok::l_square))
4034 parseSquare();
4035 } else {
4036 nextToken();
4037 }
4038 // We can have macros or attributes in between 'enum' and the enum name.
4039 if (FormatTok->is(tok::l_paren))
4040 parseParens();
4041 if (FormatTok->is(tok::identifier)) {
4042 nextToken();
4043 // If there are two identifiers in a row, this is likely an elaborate
4044 // return type. In Java, this can be "implements", etc.
4045 if (IsCpp && FormatTok->is(tok::identifier))
4046 return false;
4047 }
4048 }
4049
4050 // Just a declaration or something is wrong.
4051 if (FormatTok->isNot(tok::l_brace))
4052 return true;
4053 FormatTok->setFinalizedType(TT_EnumLBrace);
4054 FormatTok->setBlockKind(BK_Block);
4055
4056 if (Style.isJava()) {
4057 // Java enums are different.
4058 parseJavaEnumBody();
4059 return true;
4060 }
4061 if (Style.Language == FormatStyle::LK_Proto) {
4062 parseBlock(/*MustBeDeclaration=*/true);
4063 return true;
4064 }
4065
4066 const bool ManageWhitesmithsBraces =
4067 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4068
4069 if (!Style.AllowShortEnumsOnASingleLine &&
4070 ShouldBreakBeforeBrace(Style, InitialToken,
4071 Tokens->peekNextToken()->is(tok::r_brace))) {
4072 addUnwrappedLine();
4073
4074 // If we're in Whitesmiths mode, indent the brace if we're not indenting
4075 // the whole block.
4076 if (ManageWhitesmithsBraces)
4077 ++Line->Level;
4078 }
4079 // Parse enum body.
4080 nextToken();
4081 if (!Style.AllowShortEnumsOnASingleLine) {
4082 addUnwrappedLine();
4083 if (!ManageWhitesmithsBraces)
4084 ++Line->Level;
4085 }
4086 const auto OpeningLineIndex =
4087 CurrentLines->empty() || !CurrentExpandedLines.empty()
4088 ? UnwrappedLine::kInvalidIndex
4089 : CurrentLines->size() - 1;
4090 bool HasError = !parseBracedList(/*IsAngleBracket=*/false, /*IsEnum=*/true);
4091 if (!Style.AllowShortEnumsOnASingleLine && !ManageWhitesmithsBraces)
4092 --Line->Level;
4093 if (HasError) {
4094 if (FormatTok->is(tok::semi))
4095 nextToken();
4096 addUnwrappedLine();
4097 }
4098 setPreviousRBraceType(TT_EnumRBrace);
4099 if (ManageWhitesmithsBraces && CurrentExpandedLines.empty() &&
4100 !containsExpansion(*Line)) {
4101 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
4102 }
4103 return true;
4104
4105 // There is no addUnwrappedLine() here so that we fall through to parsing a
4106 // structural element afterwards. Thus, in "enum A {} n, m;",
4107 // "} n, m;" will end up in one unwrapped line.
4108}
4109
4110bool UnwrappedLineParser::parseStructLike() {
4111 // parseRecord falls through and does not yet add an unwrapped line as a
4112 // record declaration or definition can start a structural element.
4113 parseRecord();
4114 // This does not apply to Java, JavaScript and C#.
4115 if (Style.isJava() || Style.isJavaScript() || Style.isCSharp()) {
4116 if (FormatTok->is(tok::semi))
4117 nextToken();
4118 addUnwrappedLine();
4119 return true;
4120 }
4121 return false;
4122}
4123
4124namespace {
4125// A class used to set and restore the Token position when peeking
4126// ahead in the token source.
4127class ScopedTokenPosition {
4128 unsigned StoredPosition;
4129 FormatTokenSource *Tokens;
4130
4131public:
4132 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
4133 assert(Tokens && "Tokens expected to not be null");
4134 StoredPosition = Tokens->getPosition();
4135 }
4136
4137 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
4138};
4139} // namespace
4140
4141// Look to see if we have [[ by looking ahead, if
4142// its not then rewind to the original position.
4143bool UnwrappedLineParser::tryToParseSimpleAttribute() {
4144 ScopedTokenPosition AutoPosition(Tokens);
4145 FormatToken *Tok = Tokens->getNextToken();
4146 // We already read the first [ check for the second.
4147 if (Tok->isNot(tok::l_square))
4148 return false;
4149 // Double check that the attribute is just something
4150 // fairly simple.
4151 while (Tok->isNot(tok::eof)) {
4152 if (Tok->is(tok::r_square))
4153 break;
4154 Tok = Tokens->getNextToken();
4155 }
4156 if (Tok->is(tok::eof))
4157 return false;
4158 Tok = Tokens->getNextToken();
4159 if (Tok->isNot(tok::r_square))
4160 return false;
4161 Tok = Tokens->getNextToken();
4162 if (Tok->is(tok::semi))
4163 return false;
4164 return true;
4165}
4166
4167void UnwrappedLineParser::parseJavaEnumBody() {
4168 assert(FormatTok->is(tok::l_brace));
4169 const FormatToken *OpeningBrace = FormatTok;
4170
4171 // Determine whether the enum is simple, i.e. does not have a semicolon or
4172 // constants with class bodies. Simple enums can be formatted like braced
4173 // lists, contracted to a single line, etc.
4174 unsigned StoredPosition = Tokens->getPosition();
4175 bool IsSimple = true;
4176 FormatToken *Tok = Tokens->getNextToken();
4177 while (Tok->isNot(tok::eof)) {
4178 if (Tok->is(tok::r_brace))
4179 break;
4180 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
4181 IsSimple = false;
4182 break;
4183 }
4184 // FIXME: This will also mark enums with braces in the arguments to enum
4185 // constants as "not simple". This is probably fine in practice, though.
4186 Tok = Tokens->getNextToken();
4187 }
4188 FormatTok = Tokens->setPosition(StoredPosition);
4189
4190 if (IsSimple) {
4191 nextToken();
4192 parseBracedList();
4193 addUnwrappedLine();
4194 return;
4195 }
4196
4197 // Parse the body of a more complex enum.
4198 // First add a line for everything up to the "{".
4199 nextToken();
4200 addUnwrappedLine();
4201 ++Line->Level;
4202
4203 // Parse the enum constants.
4204 while (!eof()) {
4205 if (FormatTok->is(tok::l_brace)) {
4206 // Parse the constant's class body.
4207 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,
4208 /*MunchSemi=*/false);
4209 } else if (FormatTok->is(tok::l_paren)) {
4210 parseParens();
4211 } else if (FormatTok->is(tok::comma)) {
4212 nextToken();
4213 addUnwrappedLine();
4214 } else if (FormatTok->is(tok::semi)) {
4215 nextToken();
4216 addUnwrappedLine();
4217 break;
4218 } else if (FormatTok->is(tok::r_brace)) {
4219 addUnwrappedLine();
4220 break;
4221 } else {
4222 nextToken();
4223 }
4224 }
4225
4226 // Parse the class body after the enum's ";" if any.
4227 parseLevel(OpeningBrace);
4228 nextToken();
4229 --Line->Level;
4230 addUnwrappedLine();
4231}
4232
4233void UnwrappedLineParser::parseRecord(bool ParseAsExpr, bool IsJavaRecord) {
4234 assert(!IsJavaRecord || FormatTok->is(Keywords.kw_record));
4235 const FormatToken &InitialToken = *FormatTok;
4236 nextToken();
4237
4238 FormatToken *ClassName =
4239 IsJavaRecord && FormatTok->is(tok::identifier) ? FormatTok : nullptr;
4240 bool IsDerived = false;
4241 auto IsNonMacroIdentifier = [](const FormatToken *Tok) {
4242 return Tok->is(tok::identifier) && Tok->TokenText != Tok->TokenText.upper();
4243 };
4244 // JavaScript/TypeScript supports anonymous classes like:
4245 // a = class extends foo { }
4246 bool JSPastExtendsOrImplements = false;
4247 // The actual identifier can be a nested name specifier, and in macros
4248 // it is often token-pasted.
4249 // An [[attribute]] can be before the identifier.
4250 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
4251 tok::kw_alignas, tok::l_square) ||
4252 FormatTok->isAttribute() ||
4253 ((Style.isJava() || Style.isJavaScript()) &&
4254 FormatTok->isOneOf(tok::period, tok::comma)) ||
4255 (Style.isVerilog() &&
4256 FormatTok->isOneOf(tok::kw_signed, tok::kw_unsigned))) {
4257 if (Style.isJavaScript() &&
4258 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
4259 JSPastExtendsOrImplements = true;
4260 // JavaScript/TypeScript supports inline object types in
4261 // extends/implements positions:
4262 // class Foo implements {bar: number} { }
4263 nextToken();
4264 if (FormatTok->is(tok::l_brace)) {
4265 tryToParseBracedList();
4266 continue;
4267 }
4268 }
4269 if (FormatTok->is(tok::l_square) && handleCppAttributes())
4270 continue;
4271 auto *Previous = FormatTok;
4272 nextToken();
4273 switch (FormatTok->Tok.getKind()) {
4274 case tok::l_paren:
4275 // We can have macros in between 'class' and the class name.
4276 if (IsJavaRecord || !IsNonMacroIdentifier(Previous) ||
4277 // e.g. `struct macro(a) S { int i; };`
4278 Previous->Previous == &InitialToken) {
4279 parseParens();
4280 }
4281 break;
4282 case tok::coloncolon:
4283 case tok::hashhash:
4284 break;
4285 default:
4286 if (JSPastExtendsOrImplements || ClassName ||
4287 Previous->isNot(tok::identifier) || Previous->is(TT_AttributeMacro)) {
4288 break;
4289 }
4290 if (const auto Text = Previous->TokenText;
4291 Text.size() == 1 || Text != Text.upper()) {
4292 ClassName = Previous;
4293 }
4294 }
4295 }
4296
4297 auto IsListInitialization = [&] {
4298 if (!ClassName || IsDerived || JSPastExtendsOrImplements)
4299 return false;
4300 assert(FormatTok->is(tok::l_brace));
4301 const auto *Prev = FormatTok->getPreviousNonComment();
4302 assert(Prev);
4303 return Prev != ClassName && Prev->is(tok::identifier) &&
4304 Prev->isNot(Keywords.kw_final) && tryToParseBracedList();
4305 };
4306
4307 if (FormatTok->isOneOf(tok::colon, tok::less)) {
4308 int AngleNestingLevel = 0;
4309 do {
4310 if (FormatTok->is(tok::less))
4311 ++AngleNestingLevel;
4312 else if (FormatTok->is(tok::greater))
4313 --AngleNestingLevel;
4314
4315 if (AngleNestingLevel == 0) {
4316 if (FormatTok->is(tok::colon)) {
4317 IsDerived = true;
4318 } else if (!IsDerived && FormatTok->is(tok::identifier) &&
4319 FormatTok->Previous->is(tok::coloncolon)) {
4320 ClassName = FormatTok;
4321 } else if (FormatTok->is(tok::l_paren) &&
4322 IsNonMacroIdentifier(FormatTok->Previous)) {
4323 break;
4324 }
4325 }
4326 if (FormatTok->is(tok::l_brace)) {
4327 if (AngleNestingLevel == 0 && IsListInitialization())
4328 return;
4329 calculateBraceTypes(/*ExpectClassBody=*/true);
4330 if (!tryToParseBracedList())
4331 break;
4332 }
4333 if (FormatTok->is(tok::l_square)) {
4334 FormatToken *Previous = FormatTok->Previous;
4335 if (!Previous || (Previous->isNot(tok::r_paren) &&
4336 !Previous->isTypeOrIdentifier(LangOpts))) {
4337 // Don't try parsing a lambda if we had a closing parenthesis before,
4338 // it was probably a pointer to an array: int (*)[].
4339 if (!tryToParseLambda())
4340 continue;
4341 } else {
4342 parseSquare();
4343 continue;
4344 }
4345 }
4346 if (FormatTok->is(tok::semi))
4347 return;
4348 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
4349 addUnwrappedLine();
4350 nextToken();
4351 parseCSharpGenericTypeConstraint();
4352 break;
4353 }
4354 nextToken();
4355 } while (!eof());
4356 }
4357
4358 auto GetBraceTypes =
4359 [](const FormatToken &RecordTok) -> std::pair<TokenType, TokenType> {
4360 switch (RecordTok.Tok.getKind()) {
4361 case tok::kw_class:
4362 return {TT_ClassLBrace, TT_ClassRBrace};
4363 case tok::kw_struct:
4364 return {TT_StructLBrace, TT_StructRBrace};
4365 case tok::kw_union:
4366 return {TT_UnionLBrace, TT_UnionRBrace};
4367 default:
4368 // Useful for e.g. interface.
4369 return {TT_RecordLBrace, TT_RecordRBrace};
4370 }
4371 };
4372 if (FormatTok->is(tok::l_brace)) {
4373 if (IsListInitialization())
4374 return;
4375 if (ClassName)
4376 ClassName->setFinalizedType(TT_ClassHeadName);
4377 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
4378 FormatTok->setFinalizedType(OpenBraceType);
4379 if (ParseAsExpr) {
4380 parseChildBlock();
4381 } else {
4382 if (ShouldBreakBeforeBrace(Style, InitialToken,
4383 Tokens->peekNextToken()->is(tok::r_brace),
4384 IsJavaRecord)) {
4385 addUnwrappedLine();
4386 }
4387
4388 bool IndentAfterExplicitAccessModifier = false;
4389 unsigned AddLevels = 1u;
4390 switch (Style.IndentAccessModifiers) {
4392 break;
4394 if (Style.isCpp()) {
4395 IndentAfterExplicitAccessModifier = true;
4396 break;
4397 }
4398 // Other languages use the same indentation as IAMS_Always.
4399 [[fallthrough]];
4401 AddLevels = 2u;
4402 break;
4403 }
4404 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false,
4405 /*KeepBraces=*/true, /*IfKind=*/nullptr,
4406 /*UnindentWhitesmithsBraces=*/false,
4407 IndentAfterExplicitAccessModifier);
4408 }
4409 setPreviousRBraceType(ClosingBraceType);
4410 }
4411 // There is no addUnwrappedLine() here so that we fall through to parsing a
4412 // structural element afterwards. Thus, in "class A {} n, m;",
4413 // "} n, m;" will end up in one unwrapped line.
4414}
4415
4416void UnwrappedLineParser::parseObjCMethod() {
4417 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
4418 "'(' or identifier expected.");
4419 do {
4420 if (FormatTok->is(tok::semi)) {
4421 nextToken();
4422 addUnwrappedLine();
4423 return;
4424 } else if (FormatTok->is(tok::l_brace)) {
4425 if (Style.BraceWrapping.AfterFunction)
4426 addUnwrappedLine();
4427 parseBlock();
4428 addUnwrappedLine();
4429 return;
4430 } else {
4431 nextToken();
4432 }
4433 } while (!eof());
4434}
4435
4436void UnwrappedLineParser::parseObjCProtocolList() {
4437 assert(FormatTok->is(tok::less) && "'<' expected.");
4438 do {
4439 nextToken();
4440 // Early exit in case someone forgot a close angle.
4441 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4442 return;
4443 } while (!eof() && FormatTok->isNot(tok::greater));
4444 nextToken(); // Skip '>'.
4445}
4446
4447void UnwrappedLineParser::parseObjCUntilAtEnd() {
4448 do {
4449 if (FormatTok->is(tok::objc_end)) {
4450 nextToken();
4451 addUnwrappedLine();
4452 break;
4453 }
4454 if (FormatTok->is(tok::l_brace)) {
4455 parseBlock();
4456 // In ObjC interfaces, nothing should be following the "}".
4457 addUnwrappedLine();
4458 } else if (FormatTok->is(tok::r_brace)) {
4459 // Ignore stray "}". parseStructuralElement doesn't consume them.
4460 nextToken();
4461 addUnwrappedLine();
4462 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
4463 nextToken();
4464 if (FormatTok->isOneOf(tok::l_paren, tok::identifier))
4465 parseObjCMethod();
4466 } else {
4467 parseStructuralElement();
4468 }
4469 } while (!eof());
4470}
4471
4472void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
4473 assert(FormatTok->isOneOf(tok::objc_interface, tok::objc_implementation));
4474 nextToken();
4475 nextToken(); // interface name
4476
4477 // @interface can be followed by a lightweight generic
4478 // specialization list, then either a base class or a category.
4479 if (FormatTok->is(tok::less))
4480 parseObjCLightweightGenerics();
4481 if (FormatTok->is(tok::colon)) {
4482 nextToken();
4483 nextToken(); // base class name
4484 // The base class can also have lightweight generics applied to it.
4485 if (FormatTok->is(tok::less))
4486 parseObjCLightweightGenerics();
4487 } else if (FormatTok->is(tok::l_paren)) {
4488 // Skip category, if present.
4489 parseParens();
4490 }
4491
4492 if (FormatTok->is(tok::less))
4493 parseObjCProtocolList();
4494
4495 if (FormatTok->is(tok::l_brace)) {
4496 if (Style.BraceWrapping.AfterObjCDeclaration)
4497 addUnwrappedLine();
4498 parseBlock(/*MustBeDeclaration=*/true);
4499 }
4500
4501 // With instance variables, this puts '}' on its own line. Without instance
4502 // variables, this ends the @interface line.
4503 addUnwrappedLine();
4504
4505 parseObjCUntilAtEnd();
4506}
4507
4508void UnwrappedLineParser::parseObjCLightweightGenerics() {
4509 assert(FormatTok->is(tok::less));
4510 // Unlike protocol lists, generic parameterizations support
4511 // nested angles:
4512 //
4513 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
4514 // NSObject <NSCopying, NSSecureCoding>
4515 //
4516 // so we need to count how many open angles we have left.
4517 unsigned NumOpenAngles = 1;
4518 do {
4519 nextToken();
4520 // Early exit in case someone forgot a close angle.
4521 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::objc_end))
4522 break;
4523 if (FormatTok->is(tok::less)) {
4524 ++NumOpenAngles;
4525 } else if (FormatTok->is(tok::greater)) {
4526 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
4527 --NumOpenAngles;
4528 }
4529 } while (!eof() && NumOpenAngles != 0);
4530 nextToken(); // Skip '>'.
4531}
4532
4533// Returns true for the declaration/definition form of @protocol,
4534// false for the expression form.
4535bool UnwrappedLineParser::parseObjCProtocol() {
4536 assert(FormatTok->is(tok::objc_protocol));
4537 nextToken();
4538
4539 if (FormatTok->is(tok::l_paren)) {
4540 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
4541 return false;
4542 }
4543
4544 // The definition/declaration form,
4545 // @protocol Foo
4546 // - (int)someMethod;
4547 // @end
4548
4549 nextToken(); // protocol name
4550
4551 if (FormatTok->is(tok::less))
4552 parseObjCProtocolList();
4553
4554 // Check for protocol declaration.
4555 if (FormatTok->is(tok::semi)) {
4556 nextToken();
4557 addUnwrappedLine();
4558 return true;
4559 }
4560
4561 addUnwrappedLine();
4562 parseObjCUntilAtEnd();
4563 return true;
4564}
4565
4566void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4567 bool IsImport = FormatTok->is(Keywords.kw_import);
4568 assert(IsImport || FormatTok->is(tok::kw_export));
4569 nextToken();
4570
4571 // Consume the "default" in "export default class/function".
4572 if (FormatTok->is(tok::kw_default))
4573 nextToken();
4574
4575 // Consume "async function", "function" and "default function", so that these
4576 // get parsed as free-standing JS functions, i.e. do not require a trailing
4577 // semicolon.
4578 if (FormatTok->is(Keywords.kw_async))
4579 nextToken();
4580 if (FormatTok->is(Keywords.kw_function)) {
4581 nextToken();
4582 return;
4583 }
4584
4585 // For imports, `export *`, `export {...}`, consume the rest of the line up
4586 // to the terminating `;`. For everything else, just return and continue
4587 // parsing the structural element, i.e. the declaration or expression for
4588 // `export default`.
4589 if (!IsImport && FormatTok->isNoneOf(tok::l_brace, tok::star) &&
4590 !FormatTok->isStringLiteral() &&
4591 !(FormatTok->is(Keywords.kw_type) &&
4592 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4593 return;
4594 }
4595
4596 while (!eof()) {
4597 if (FormatTok->is(tok::semi))
4598 return;
4599 if (Line->Tokens.empty()) {
4600 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
4601 // import statement should terminate.
4602 return;
4603 }
4604 if (FormatTok->is(tok::l_brace)) {
4605 FormatTok->setBlockKind(BK_Block);
4606 nextToken();
4607 parseBracedList();
4608 } else {
4609 nextToken();
4610 }
4611 }
4612}
4613
4614void UnwrappedLineParser::parseStatementMacro() {
4615 nextToken();
4616 if (FormatTok->is(tok::l_paren))
4617 parseParens();
4618 if (FormatTok->is(tok::semi))
4619 nextToken();
4620 addUnwrappedLine();
4621}
4622
4623void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4624 // consume things like a::`b.c[d:e] or a::*
4625 while (true) {
4626 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4627 tok::coloncolon, tok::hash) ||
4628 Keywords.isVerilogIdentifier(*FormatTok)) {
4629 nextToken();
4630 } else if (FormatTok->is(tok::l_square)) {
4631 parseSquare();
4632 } else {
4633 break;
4634 }
4635 }
4636}
4637
4638void UnwrappedLineParser::parseVerilogSensitivityList() {
4639 if (FormatTok->isNot(tok::at))
4640 return;
4641 nextToken();
4642 // A block event expression has 2 at signs.
4643 if (FormatTok->is(tok::at))
4644 nextToken();
4645 switch (FormatTok->Tok.getKind()) {
4646 case tok::star:
4647 nextToken();
4648 break;
4649 case tok::l_paren:
4650 parseParens();
4651 break;
4652 default:
4653 parseVerilogHierarchyIdentifier();
4654 break;
4655 }
4656}
4657
4658unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4659 unsigned AddLevels = 0;
4660
4661 if (FormatTok->is(Keywords.kw_clocking)) {
4662 nextToken();
4663 if (Keywords.isVerilogIdentifier(*FormatTok))
4664 nextToken();
4665 parseVerilogSensitivityList();
4666 if (FormatTok->is(tok::semi))
4667 nextToken();
4668 } else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4669 Keywords.kw_casez, Keywords.kw_randcase,
4670 Keywords.kw_randsequence)) {
4671 if (Style.IndentCaseLabels)
4672 AddLevels++;
4673 nextToken();
4674 if (FormatTok->is(tok::l_paren)) {
4675 FormatTok->setFinalizedType(TT_ConditionLParen);
4676 parseParens();
4677 }
4678 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4679 nextToken();
4680 // The case header has no semicolon.
4681 } else {
4682 // "module" etc.
4683 nextToken();
4684 // all the words like the name of the module and specifiers like
4685 // "automatic" and the width of function return type
4686 while (true) {
4687 if (FormatTok->is(tok::l_square)) {
4688 auto Prev = FormatTok->getPreviousNonComment();
4689 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4690 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4691 parseSquare();
4692 } else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4693 FormatTok->isOneOf(tok::hash, tok::hashhash, tok::coloncolon,
4694 Keywords.kw_automatic, tok::kw_static)) {
4695 nextToken();
4696 } else {
4697 break;
4698 }
4699 }
4700
4701 auto NewLine = [this]() {
4702 addUnwrappedLine();
4703 Line->IsContinuation = true;
4704 };
4705
4706 // package imports
4707 while (FormatTok->is(Keywords.kw_import)) {
4708 NewLine();
4709 nextToken();
4710 parseVerilogHierarchyIdentifier();
4711 if (FormatTok->is(tok::semi))
4712 nextToken();
4713 }
4714
4715 // parameters and ports
4716 if (FormatTok->is(Keywords.kw_verilogHash)) {
4717 NewLine();
4718 nextToken();
4719 if (FormatTok->is(tok::l_paren)) {
4720 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4721 parseParens();
4722 }
4723 }
4724 if (FormatTok->is(tok::l_paren)) {
4725 NewLine();
4726 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4727 parseParens();
4728 }
4729
4730 // extends and implements
4731 if (FormatTok->is(Keywords.kw_extends)) {
4732 NewLine();
4733 nextToken();
4734 parseVerilogHierarchyIdentifier();
4735 if (FormatTok->is(tok::l_paren))
4736 parseParens();
4737 }
4738 if (FormatTok->is(Keywords.kw_implements)) {
4739 NewLine();
4740 do {
4741 nextToken();
4742 parseVerilogHierarchyIdentifier();
4743 } while (FormatTok->is(tok::comma));
4744 }
4745
4746 // Coverage event for cover groups.
4747 if (FormatTok->is(tok::at)) {
4748 NewLine();
4749 parseVerilogSensitivityList();
4750 }
4751
4752 if (FormatTok->is(tok::semi))
4753 nextToken(/*LevelDifference=*/1);
4754 addUnwrappedLine();
4755 }
4756
4757 return AddLevels;
4758}
4759
4760void UnwrappedLineParser::parseVerilogTable() {
4761 assert(FormatTok->is(Keywords.kw_table));
4762 nextToken(/*LevelDifference=*/1);
4763 addUnwrappedLine();
4764
4765 auto InitialLevel = Line->Level++;
4766 while (!eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4767 FormatToken *Tok = FormatTok;
4768 nextToken();
4769 if (Tok->is(tok::semi))
4770 addUnwrappedLine();
4771 else if (Tok->isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4772 Tok->setFinalizedType(TT_VerilogTableItem);
4773 }
4774 Line->Level = InitialLevel;
4775 nextToken(/*LevelDifference=*/-1);
4776 addUnwrappedLine();
4777}
4778
4779void UnwrappedLineParser::parseVerilogCaseLabel() {
4780 // The label will get unindented in AnnotatingParser. If there are no leading
4781 // spaces, indent the rest here so that things inside the block will be
4782 // indented relative to things outside. We don't use parseLabel because we
4783 // don't know whether this colon is a label or a ternary expression at this
4784 // point.
4785 auto OrigLevel = Line->Level;
4786 auto FirstLine = CurrentLines->size();
4787 if (Line->Level == 0 || (Line->InPPDirective && Line->Level <= 1))
4788 ++Line->Level;
4789 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4790 --Line->Level;
4791 parseStructuralElement();
4792 // Restore the indentation in both the new line and the line that has the
4793 // label.
4794 if (CurrentLines->size() > FirstLine)
4795 (*CurrentLines)[FirstLine].Level = OrigLevel;
4796 Line->Level = OrigLevel;
4797}
4798
4799void UnwrappedLineParser::parseVerilogExtern() {
4800 assert(
4801 FormatTok->isOneOf(tok::kw_extern, tok::kw_export, Keywords.kw_import));
4802 nextToken();
4803 // "DPI-C"
4804 if (FormatTok->is(tok::string_literal))
4805 nextToken();
4806 skipVerilogQualifiers();
4807 if (Keywords.isVerilogIdentifier(*FormatTok))
4808 nextToken();
4809 if (FormatTok->is(tok::equal))
4810 nextToken();
4811 if (Keywords.isVerilogHierarchy(*FormatTok))
4812 parseVerilogHierarchyHeader();
4813}
4814
4815void UnwrappedLineParser::skipVerilogQualifiers() {
4816 while (FormatTok->isOneOf(tok::kw_protected, tok::kw_virtual, tok::kw_static,
4817 Keywords.kw_rand, Keywords.kw_context,
4818 Keywords.kw_pure, Keywords.kw_randc,
4819 Keywords.kw_local)) {
4820 nextToken();
4821 }
4822}
4823
4824bool UnwrappedLineParser::containsExpansion(const UnwrappedLine &Line) const {
4825 for (const auto &N : Line.Tokens) {
4826 if (N.Tok->MacroCtx)
4827 return true;
4828 for (const UnwrappedLine &Child : N.Children)
4829 if (containsExpansion(Child))
4830 return true;
4831 }
4832 return false;
4833}
4834
4835void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4836 if (Line->Tokens.empty())
4837 return;
4838 LLVM_DEBUG({
4839 if (!parsingPPDirective()) {
4840 llvm::dbgs() << "Adding unwrapped line:\n";
4841 printDebugInfo(*Line);
4842 }
4843 });
4844
4845 // If this line closes a block when in Whitesmiths mode, remember that
4846 // information so that the level can be decreased after the line is added.
4847 // This has to happen after the addition of the line since the line itself
4848 // needs to be indented.
4849 bool ClosesWhitesmithsBlock =
4850 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4851 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4852
4853 // If the current line was expanded from a macro call, we use it to
4854 // reconstruct an unwrapped line from the structure of the expanded unwrapped
4855 // line and the unexpanded token stream.
4856 if (!parsingPPDirective() && !InExpansion && containsExpansion(*Line)) {
4857 if (!Reconstruct)
4858 Reconstruct.emplace(Line->Level, Unexpanded);
4859 Reconstruct->addLine(*Line);
4860
4861 // While the reconstructed unexpanded lines are stored in the normal
4862 // flow of lines, the expanded lines are stored on the side to be analyzed
4863 // in an extra step.
4864 CurrentExpandedLines.push_back(std::move(*Line));
4865
4866 if (Reconstruct->finished()) {
4867 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4868 assert(!Reconstructed.Tokens.empty() &&
4869 "Reconstructed must at least contain the macro identifier.");
4870 assert(!parsingPPDirective());
4871 LLVM_DEBUG({
4872 llvm::dbgs() << "Adding unexpanded line:\n";
4873 printDebugInfo(Reconstructed);
4874 });
4875 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4876 Lines.push_back(std::move(Reconstructed));
4877 CurrentExpandedLines.clear();
4878 Reconstruct.reset();
4879 }
4880 } else {
4881 // At the top level we only get here when no unexpansion is going on, or
4882 // when conditional formatting led to unfinished macro reconstructions.
4883 assert(!Reconstruct || (CurrentLines != &Lines) || !PP.Stack.empty());
4884 CurrentLines->push_back(std::move(*Line));
4885 }
4886 Line->Tokens.clear();
4887 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4888 Line->FirstStartColumn = 0;
4889 Line->IsContinuation = false;
4890 Line->SeenDecltypeAuto = false;
4891 Line->IsModuleOrImportDecl = false;
4892
4893 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4894 --Line->Level;
4895 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4896 CurrentLines->append(
4897 std::make_move_iterator(PreprocessorDirectives.begin()),
4898 std::make_move_iterator(PreprocessorDirectives.end()));
4899 PreprocessorDirectives.clear();
4900 }
4901 // Disconnect the current token from the last token on the previous line.
4902 FormatTok->Previous = nullptr;
4903}
4904
4905bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); }
4906
4907bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
4908 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4909 FormatTok.NewlinesBefore > 0;
4910}
4911
4912// Checks if \p FormatTok is a line comment that continues the line comment
4913// section on \p Line.
4914static bool
4916 const UnwrappedLine &Line, const FormatStyle &Style,
4917 const llvm::Regex &CommentPragmasRegex) {
4918 if (Line.Tokens.empty() || Style.ReflowComments != FormatStyle::RCS_Always)
4919 return false;
4920
4921 StringRef IndentContent = FormatTok.TokenText;
4922 if (FormatTok.TokenText.starts_with("//") ||
4923 FormatTok.TokenText.starts_with("/*")) {
4924 IndentContent = FormatTok.TokenText.substr(2);
4925 }
4926 if (CommentPragmasRegex.match(IndentContent))
4927 return false;
4928
4929 // If Line starts with a line comment, then FormatTok continues the comment
4930 // section if its original column is greater or equal to the original start
4931 // column of the line.
4932 //
4933 // Define the min column token of a line as follows: if a line ends in '{' or
4934 // contains a '{' followed by a line comment, then the min column token is
4935 // that '{'. Otherwise, the min column token of the line is the first token of
4936 // the line.
4937 //
4938 // If Line starts with a token other than a line comment, then FormatTok
4939 // continues the comment section if its original column is greater than the
4940 // original start column of the min column token of the line.
4941 //
4942 // For example, the second line comment continues the first in these cases:
4943 //
4944 // // first line
4945 // // second line
4946 //
4947 // and:
4948 //
4949 // // first line
4950 // // second line
4951 //
4952 // and:
4953 //
4954 // int i; // first line
4955 // // second line
4956 //
4957 // and:
4958 //
4959 // do { // first line
4960 // // second line
4961 // int i;
4962 // } while (true);
4963 //
4964 // and:
4965 //
4966 // enum {
4967 // a, // first line
4968 // // second line
4969 // b
4970 // };
4971 //
4972 // The second line comment doesn't continue the first in these cases:
4973 //
4974 // // first line
4975 // // second line
4976 //
4977 // and:
4978 //
4979 // int i; // first line
4980 // // second line
4981 //
4982 // and:
4983 //
4984 // do { // first line
4985 // // second line
4986 // int i;
4987 // } while (true);
4988 //
4989 // and:
4990 //
4991 // enum {
4992 // a, // first line
4993 // // second line
4994 // };
4995 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
4996
4997 // Scan for '{//'. If found, use the column of '{' as a min column for line
4998 // comment section continuation.
4999 const FormatToken *PreviousToken = nullptr;
5000 for (const UnwrappedLineNode &Node : Line.Tokens) {
5001 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
5002 isLineComment(*Node.Tok)) {
5003 MinColumnToken = PreviousToken;
5004 break;
5005 }
5006 PreviousToken = Node.Tok;
5007
5008 // Grab the last newline preceding a token in this unwrapped line.
5009 if (Node.Tok->NewlinesBefore > 0)
5010 MinColumnToken = Node.Tok;
5011 }
5012 if (PreviousToken && PreviousToken->is(tok::l_brace))
5013 MinColumnToken = PreviousToken;
5014
5015 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
5016 MinColumnToken);
5017}
5018
5019void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
5020 bool JustComments = Line->Tokens.empty();
5021 for (FormatToken *Tok : CommentsBeforeNextToken) {
5022 // Line comments that belong to the same line comment section are put on the
5023 // same line since later we might want to reflow content between them.
5024 // Additional fine-grained breaking of line comment sections is controlled
5025 // by the class BreakableLineCommentSection in case it is desirable to keep
5026 // several line comment sections in the same unwrapped line.
5027 //
5028 // FIXME: Consider putting separate line comment sections as children to the
5029 // unwrapped line instead.
5030 Tok->ContinuesLineCommentSection =
5031 continuesLineCommentSection(*Tok, *Line, Style, CommentPragmasRegex);
5032 if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection)
5033 addUnwrappedLine();
5034 pushToken(Tok);
5035 }
5036 if (NewlineBeforeNext && JustComments)
5037 addUnwrappedLine();
5038 CommentsBeforeNextToken.clear();
5039}
5040
5041void UnwrappedLineParser::nextToken(int LevelDifference) {
5042 if (eof())
5043 return;
5044 flushComments(isOnNewLine(*FormatTok));
5045 pushToken(FormatTok);
5046 FormatToken *Previous = FormatTok;
5047 if (!Style.isJavaScript())
5048 readToken(LevelDifference);
5049 else
5050 readTokenWithJavaScriptASI();
5051 FormatTok->Previous = Previous;
5052 if (Style.isVerilog()) {
5053 // Blocks in Verilog can have `begin` and `end` instead of braces. For
5054 // keywords like `begin`, we can't treat them the same as left braces
5055 // because some contexts require one of them. For example structs use
5056 // braces and if blocks use keywords, and a left brace can occur in an if
5057 // statement, but it is not a block. For keywords like `end`, we simply
5058 // treat them the same as right braces.
5059 if (Keywords.isVerilogEnd(*FormatTok))
5060 FormatTok->Tok.setKind(tok::r_brace);
5061 }
5062}
5063
5064void UnwrappedLineParser::distributeComments(
5065 const ArrayRef<FormatToken *> &Comments, const FormatToken *NextTok) {
5066 // Whether or not a line comment token continues a line is controlled by
5067 // the method continuesLineCommentSection, with the following caveat:
5068 //
5069 // Define a trail of Comments to be a nonempty proper postfix of Comments such
5070 // that each comment line from the trail is aligned with the next token, if
5071 // the next token exists. If a trail exists, the beginning of the maximal
5072 // trail is marked as a start of a new comment section.
5073 //
5074 // For example in this code:
5075 //
5076 // int a; // line about a
5077 // // line 1 about b
5078 // // line 2 about b
5079 // int b;
5080 //
5081 // the two lines about b form a maximal trail, so there are two sections, the
5082 // first one consisting of the single comment "// line about a" and the
5083 // second one consisting of the next two comments.
5084 if (Comments.empty())
5085 return;
5086 bool ShouldPushCommentsInCurrentLine = true;
5087 bool HasTrailAlignedWithNextToken = false;
5088 unsigned StartOfTrailAlignedWithNextToken = 0;
5089 if (NextTok) {
5090 // We are skipping the first element intentionally.
5091 for (unsigned i = Comments.size() - 1; i > 0; --i) {
5092 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
5093 HasTrailAlignedWithNextToken = true;
5094 StartOfTrailAlignedWithNextToken = i;
5095 }
5096 }
5097 }
5098 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
5099 FormatToken *FormatTok = Comments[i];
5100 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
5101 FormatTok->ContinuesLineCommentSection = false;
5102 } else {
5103 FormatTok->ContinuesLineCommentSection = continuesLineCommentSection(
5104 *FormatTok, *Line, Style, CommentPragmasRegex);
5105 }
5106 if (!FormatTok->ContinuesLineCommentSection &&
5107 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
5108 ShouldPushCommentsInCurrentLine = false;
5109 }
5110 if (ShouldPushCommentsInCurrentLine)
5111 pushToken(FormatTok);
5112 else
5113 CommentsBeforeNextToken.push_back(FormatTok);
5114 }
5115}
5116
5117void UnwrappedLineParser::readToken(int LevelDifference) {
5119 bool PreviousWasComment = false;
5120 bool FirstNonCommentOnLine = false;
5121 do {
5122 FormatTok = Tokens->getNextToken();
5123 assert(FormatTok);
5124 while (FormatTok->isOneOf(TT_ConflictStart, TT_ConflictEnd,
5125 TT_ConflictAlternative)) {
5126 if (FormatTok->is(TT_ConflictStart))
5127 conditionalCompilationStart(/*Unreachable=*/false);
5128 else if (FormatTok->is(TT_ConflictAlternative))
5129 conditionalCompilationAlternative();
5130 else if (FormatTok->is(TT_ConflictEnd))
5131 conditionalCompilationEnd();
5132 FormatTok = Tokens->getNextToken();
5133 FormatTok->MustBreakBefore = true;
5134 FormatTok->MustBreakBeforeFinalized = true;
5135 }
5136
5137 auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
5138 const FormatToken &Tok,
5139 bool PreviousWasComment) {
5140 auto IsFirstOnLine = [](const FormatToken &Tok) {
5141 return Tok.HasUnescapedNewline || Tok.IsFirst;
5142 };
5143
5144 // Consider preprocessor directives preceded by block comments as first
5145 // on line.
5146 if (PreviousWasComment)
5147 return FirstNonCommentOnLine || IsFirstOnLine(Tok);
5148 return IsFirstOnLine(Tok);
5149 };
5150
5151 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5152 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5153 PreviousWasComment = FormatTok->is(tok::comment);
5154
5155 while (!Line->InPPDirective && FormatTok->is(tok::hash) &&
5156 FirstNonCommentOnLine) {
5157 // In Verilog, the backtick is used for macro invocations. In TableGen,
5158 // the single hash is used for the paste operator.
5159 const auto *Next = Tokens->peekNextToken();
5160 if ((Style.isVerilog() && !Keywords.isVerilogPPDirective(*Next)) ||
5161 (Style.isTableGen() &&
5162 Next->isNoneOf(tok::kw_else, tok::pp_define, tok::pp_ifdef,
5163 tok::pp_ifndef, tok::pp_endif))) {
5164 break;
5165 }
5166 distributeComments(Comments, FormatTok);
5167 Comments.clear();
5168 // If the directive was parsed before the token stream was rewound (see
5169 // parseMacroCall()), its lines were kept. Parse it again only for its
5170 // effect on the preprocessor bookkeeping and discard the new lines.
5171 const bool ParsedBefore = !ParsedPPDirectives.insert(FormatTok).second;
5172 // If there is an unfinished unwrapped line, we flush the preprocessor
5173 // directives only after that unwrapped line was finished later.
5174 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
5175 ScopedLineState BlockState(*this, SwitchToPreprocessorLines,
5176 /*DiscardLines=*/ParsedBefore);
5177 assert((LevelDifference >= 0 ||
5178 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
5179 "LevelDifference makes Line->Level negative");
5180 Line->Level += LevelDifference;
5181 // Comments stored before the preprocessor directive need to be output
5182 // before the preprocessor directive, at the same level as the
5183 // preprocessor directive, as we consider them to apply to the directive.
5184 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
5185 PP.BranchLevel > 0) {
5186 Line->Level += PP.BranchLevel;
5187 }
5188 assert(Line->Level >= Line->UnbracedBodyLevel);
5189 Line->Level -= Line->UnbracedBodyLevel;
5190 flushComments(isOnNewLine(*FormatTok));
5191 const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif);
5192 parsePPDirective();
5193 PreviousWasComment = FormatTok->is(tok::comment);
5194 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
5195 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
5196 // If the #endif of a potential include guard is the last thing in the
5197 // file, then we found an include guard.
5198 if (IsEndIf && PP.IncludeGuard == IG_Defined && PP.BranchLevel == -1 &&
5199 getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited &&
5200 (eof() ||
5201 (PreviousWasComment &&
5202 Tokens->peekNextToken(/*SkipComment=*/true)->is(tok::eof)))) {
5203 PP.IncludeGuard = IG_Found;
5204 }
5205 }
5206
5207 if (!PP.Stack.empty() && (PP.Stack.back().Kind == PP_Unreachable) &&
5208 !Line->InPPDirective) {
5209 continue;
5210 }
5211
5212 if (FormatTok->is(tok::identifier) &&
5213 Macros.defined(FormatTok->TokenText) &&
5214 // FIXME: Allow expanding macros in preprocessor directives.
5215 !Line->InPPDirective) {
5216 FormatToken *ID = FormatTok;
5217 unsigned Position = Tokens->getPosition();
5218 // Parsing the arguments of the call may parse preprocessor directives,
5219 // which are parsed again if the token stream is rewound because the
5220 // arguments are discarded. The preprocessor bookkeeping is restored
5221 // whenever that happens.
5222 const auto SavedPPState = PP;
5223
5224 // To correctly parse the code, we need to replace the tokens of the macro
5225 // call with its expansion.
5226 auto PreCall = std::move(Line);
5227 Line.reset(new UnwrappedLine);
5228 bool OldInExpansion = InExpansion;
5229 InExpansion = true;
5230 // We parse the macro call into a new line.
5231 auto Args = parseMacroCall(SavedPPState);
5232 InExpansion = OldInExpansion;
5233 assert(Line->Tokens.front().Tok == ID);
5234 // And remember the unexpanded macro call tokens.
5235 auto UnexpandedLine = std::move(Line);
5236 // Reset to the old line.
5237 Line = std::move(PreCall);
5238
5239 LLVM_DEBUG({
5240 llvm::dbgs() << "Macro call: " << ID->TokenText << "(";
5241 if (Args) {
5242 llvm::dbgs() << "(";
5243 for (const auto &Arg : Args.value())
5244 for (const auto &T : Arg)
5245 llvm::dbgs() << T->TokenText << " ";
5246 llvm::dbgs() << ")";
5247 }
5248 llvm::dbgs() << "\n";
5249 });
5250 if (Macros.objectLike(ID->TokenText) && Args &&
5251 !Macros.hasArity(ID->TokenText, Args->size())) {
5252 // The macro is either
5253 // - object-like, but we got argumnets, or
5254 // - overloaded to be both object-like and function-like, but none of
5255 // the function-like arities match the number of arguments.
5256 // Thus, expand as object-like macro.
5257 LLVM_DEBUG(llvm::dbgs()
5258 << "Macro \"" << ID->TokenText
5259 << "\" not overloaded for arity " << Args->size()
5260 << "or not function-like, using object-like overload.");
5261 Args.reset();
5262 UnexpandedLine->Tokens.resize(1);
5263 Tokens->setPosition(Position);
5264 // Not nextToken(), which would push the stale FormatTok onto the line.
5265 FormatTok = Tokens->getNextToken();
5266 PP = SavedPPState;
5267 assert(!Args && Macros.objectLike(ID->TokenText));
5268 }
5269 if ((!Args && Macros.objectLike(ID->TokenText)) ||
5270 (Args && Macros.hasArity(ID->TokenText, Args->size()))) {
5271 // Next, we insert the expanded tokens in the token stream at the
5272 // current position, and continue parsing.
5273 Unexpanded[ID] = std::move(UnexpandedLine);
5275 Macros.expand(ID, std::move(Args));
5276 if (!Expansion.empty())
5277 FormatTok = Tokens->insertTokens(Expansion);
5278
5279 LLVM_DEBUG({
5280 llvm::dbgs() << "Expanded: ";
5281 for (const auto &T : Expansion)
5282 llvm::dbgs() << T->TokenText << " ";
5283 llvm::dbgs() << "\n";
5284 });
5285 } else {
5286 LLVM_DEBUG({
5287 llvm::dbgs() << "Did not expand macro \"" << ID->TokenText
5288 << "\", because it was used ";
5289 if (Args)
5290 llvm::dbgs() << "with " << Args->size();
5291 else
5292 llvm::dbgs() << "without";
5293 llvm::dbgs() << " arguments, which doesn't match any definition.\n";
5294 });
5295 Tokens->setPosition(Position);
5296 FormatTok = ID;
5297 PP = SavedPPState;
5298 }
5299 }
5300
5301 if (FormatTok->isNot(tok::comment)) {
5302 distributeComments(Comments, FormatTok);
5303 Comments.clear();
5304 return;
5305 }
5306
5307 Comments.push_back(FormatTok);
5308 } while (!eof());
5309
5310 distributeComments(Comments, nullptr);
5311 Comments.clear();
5312}
5313
5314namespace {
5315template <typename Iterator>
5316void pushTokens(Iterator Begin, Iterator End,
5318 for (auto I = Begin; I != End; ++I) {
5319 Into.push_back(I->Tok);
5320 for (const auto &Child : I->Children)
5321 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
5322 }
5323}
5324} // namespace
5325
5326std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
5327UnwrappedLineParser::parseMacroCall(const PPState &SavedPPState) {
5328 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
5329 assert(Line->Tokens.empty());
5330 // Not nextToken(), which would already expand a directly following macro
5331 // call before the expansion of this one is inserted.
5332 auto ConsumeLastTokenOfCall = [this] {
5333 flushComments(isOnNewLine(*FormatTok));
5334 pushToken(FormatTok);
5335 FormatTok = Tokens->getNextToken();
5336 };
5337 if (Tokens->peekNextToken(/*SkipComment=*/true)->isNot(tok::l_paren)) {
5338 ConsumeLastTokenOfCall();
5339 return Args;
5340 }
5341 nextToken();
5342 assert(FormatTok->is(tok::l_paren));
5343 unsigned Position = Tokens->getPosition();
5344 FormatToken *Tok = FormatTok;
5345 nextToken();
5346 Args.emplace();
5347 auto ArgStart = std::prev(Line->Tokens.end());
5348
5349 int Parens = 0;
5350 do {
5351 switch (FormatTok->Tok.getKind()) {
5352 case tok::l_paren:
5353 ++Parens;
5354 nextToken();
5355 break;
5356 case tok::r_paren: {
5357 if (Parens > 0) {
5358 --Parens;
5359 nextToken();
5360 break;
5361 }
5362 Args->push_back({});
5363 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back());
5364 ConsumeLastTokenOfCall();
5365 return Args;
5366 }
5367 case tok::comma: {
5368 if (Parens > 0) {
5369 nextToken();
5370 break;
5371 }
5372 Args->push_back({});
5373 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back());
5374 nextToken();
5375 ArgStart = std::prev(Line->Tokens.end());
5376 break;
5377 }
5378 default:
5379 nextToken();
5380 break;
5381 }
5382 } while (!eof());
5383 Line->Tokens.resize(1);
5384 Tokens->setPosition(Position);
5385 FormatTok = Tok;
5386 PP = SavedPPState;
5387 return {};
5388}
5389
5390void UnwrappedLineParser::pushToken(FormatToken *Tok) {
5391 Line->Tokens.push_back(UnwrappedLineNode(Tok));
5392 if (PP.AtEndOfPPLine) {
5393 auto &Tok = *Line->Tokens.back().Tok;
5394 Tok.MustBreakBefore = true;
5395 Tok.MustBreakBeforeFinalized = true;
5396 Tok.FirstAfterPPLine = true;
5397 PP.AtEndOfPPLine = false;
5398 }
5399}
5400
5401} // end namespace format
5402} // end namespace clang
This file defines the FormatTokenSource interface, which provides a token stream as well as the abili...
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
FormatToken()
Token Tok
The Token.
unsigned OriginalColumn
The original 0-based column of this token, including expanded tabs.
FormatToken * Previous
The previous token in the unwrapped line.
FormatToken * Next
The next token in the unwrapped line.
This file contains the main building blocks of macro support in clang-format.
static bool HasAttribute(const QualType &T)
This file implements a token annotator, i.e.
Defines the clang::TokenKind enum and support functions.
This file contains the declaration of the UnwrappedLineParser, which turns a stream of tokens into Un...
Implements an efficient mapping from strings to IdentifierInfo nodes.
Parser - This implements a parser for the C family of languages.
Definition Parser.h:264
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:225
bool isLiteral() const
Return true if this is a "literal", like a numeric constant, string, etc.
Definition Token.h:126
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
tok::TokenKind getKind() const
Definition Token.h:99
bool isOneOf(Ts... Ks) const
Definition Token.h:105
bool isNot(tok::TokenKind K) const
Definition Token.h:111
CompoundStatementIndenter(UnwrappedLineParser *Parser, const FormatStyle &Style, unsigned &LineLevel)
CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel, bool WrapBrace, bool IndentBrace)
ScopedLineState(UnwrappedLineParser &Parser, bool SwitchToPreprocessorLines=false, bool DiscardLines=false)
Interface for users of the UnwrappedLineParser to receive the parsed lines.
UnwrappedLineParser(SourceManager &SourceMgr, const FormatStyle &Style, const AdditionalKeywords &Keywords, unsigned FirstStartColumn, ArrayRef< FormatToken * > Tokens, UnwrappedLineConsumer &Callback, llvm::SpecificBumpPtrAllocator< FormatToken > &Allocator, IdentifierTable &IdentTable)
static bool containsPPDirective(const UnwrappedLine &Line)
static void hash_combine(std::size_t &seed, const T &v)
static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, const FormatToken *FormatTok)
std::ostream & operator<<(std::ostream &Stream, const UnwrappedLine &Line)
static bool tokenCanStartNewLine(const FormatToken &Tok)
static bool continuesLineCommentSection(const FormatToken &FormatTok, const UnwrappedLine &Line, const FormatStyle &Style, const llvm::Regex &CommentPragmasRegex)
static bool isC78Type(const FormatToken &Tok)
static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, const FormatToken *FormatTok)
LangOptions getFormattingLangOpts(const FormatStyle &Style=getLLVMStyle())
Returns the LangOpts that the formatter expects you to set.
Definition Format.cpp:4605
static void markOptionalBraces(FormatToken *LeftBrace)
static bool mustBeJSIdent(const AdditionalKeywords &Keywords, const FormatToken *FormatTok)
static bool isIIFE(const UnwrappedLine &Line, const AdditionalKeywords &Keywords)
static bool isC78ParameterDecl(const FormatToken *Tok, const FormatToken *Next, const FormatToken *FuncName)
static bool isGoogScope(const UnwrappedLine &Line)
static FormatToken * getLastNonComment(const UnwrappedLine &Line)
TokenType
Determines the semantic type of a syntactic token, e.g.
static bool ShouldBreakBeforeBrace(const FormatStyle &Style, const FormatToken &InitialToken, bool IsEmptyBlock, bool IsJavaRecord=false)
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
bool isLiteral(TokenKind K)
Return true if this is a "literal" kind, like a numeric constant, string, etc.
Definition TokenKinds.h:109
Top level wrappers for InstallAPI frontend operations.
bool isLineComment(const FormatToken &FormatTok)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Default
Set to the current date and time.
const FunctionProtoType * T
bool continuesLineComment(const FormatToken &FormatTok, const FormatToken *Previous, const FormatToken *MinColumnToken)
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2250
@ LK_C
Should be used for C.
Definition Format.h:3878
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ IEBS_AfterExternBlock
Backwards compatible with AfterExternBlock's indenting.
Definition Format.h:3316
@ IEBS_Indent
Indents extern blocks.
Definition Format.h:3330
@ PPDIS_BeforeHash
Indents directives before the hash.
Definition Format.h:3423
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
@ LS_Cpp20
Parse and format as C++20.
Definition Format.h:5938
@ BWACS_Always
Always wrap braces after a control statement.
Definition Format.h:1415
@ BWACS_Never
Never wrap braces after a control statement.
Definition Format.h:1394
@ IAMS_Never
Use AccessModifierOffset for access modifiers and indent members one level below the record.
Definition Format.h:3211
@ IAMS_AfterFirstAccessModifier
In C, C++, and Objective-C, indent members one level until the first explicit access modifier,...
Definition Format.h:3235
@ IAMS_Always
Give access modifiers their own indentation level and indent all members two levels below the record.
Definition Format.h:3223
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
@ RPS_Leave
Do not remove parentheses.
Definition Format.h:4863
@ RPS_ReturnStatement
Also remove parentheses enclosing the expression in a return/co_return statement.
Definition Format.h:4878
@ NI_All
Indent in all namespaces.
Definition Format.h:4060
@ NI_Inner
Indent only in inner namespaces (nested in other namespaces).
Definition Format.h:4050
@ IGLS_OuterIndent
Indent goto labels to the enclosing block (previous indenting level).
Definition Format.h:3362
@ IGLS_NoIndent
Do not indent goto labels.
Definition Format.h:3350
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
IdentifierInfo * kw_instanceof
IdentifierInfo * kw_implements
IdentifierInfo * kw_override
IdentifierInfo * kw_await
IdentifierInfo * kw_extends
IdentifierInfo * kw_async
IdentifierInfo * kw_from
IdentifierInfo * kw_abstract
IdentifierInfo * kw_var
IdentifierInfo * kw_interface
IdentifierInfo * kw_function
IdentifierInfo * kw_yield
IdentifierInfo * kw_where
IdentifierInfo * kw_throws
IdentifierInfo * kw_let
IdentifierInfo * kw_import
IdentifierInfo * kw_finally
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
@ LK_Proto
Should be used for Protocol Buffers
Definition Format.h:3892
@ RCS_Always
Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit.
Definition Format.h:4770
@ SRS_Empty
Only merge empty records.
Definition Format.h:1083
@ BS_Whitesmiths
Like Allman but always indent braces and line up code with braces.
Definition Format.h:2250
A wrapper around a Token storing information about the whitespace characters preceding it.
bool Optional
Is optional and can be removed.
bool isNot(T Kind) const
StringRef TokenText
The raw text of the token.
bool isNoneOf(Ts... Ks) const
unsigned NewlinesBefore
The number of newlines immediately before the Token.
bool is(tok::TokenKind Kind) const
bool isOneOf(A K1, B K2) const
unsigned IsFirst
Indicates that this is the first token of the file.
FormatToken * MatchingParen
If this is a bracket, this points to the matching one.
FormatToken * Previous
The previous token in the unwrapped line.
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...