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