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