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