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