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