1 //===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// This file contains the declaration of the UnwrappedLineParser,
11 /// which turns a stream of tokens into UnwrappedLines.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
16 #define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
19 #include "FormatToken.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Format/Format.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/Support/Regex.h"
34 struct UnwrappedLineNode
;
36 /// An unwrapped line is a sequence of \c Token, that we would like to
37 /// put on a single line if there was no column limit.
39 /// This is used as a main interface between the \c UnwrappedLineParser and the
40 /// \c UnwrappedLineFormatter. The key property is that changing the formatting
41 /// within an unwrapped line does not affect any other unwrapped lines.
42 struct UnwrappedLine
{
43 UnwrappedLine() = default;
45 /// The \c Tokens comprising this \c UnwrappedLine.
46 std::list
<UnwrappedLineNode
> Tokens
;
48 /// The indent level of the \c UnwrappedLine.
51 /// The \c PPBranchLevel (adjusted for header guards) if this line is a
52 /// \c InMacroBody line, and 0 otherwise.
55 /// Whether this \c UnwrappedLine is part of a preprocessor directive.
56 bool InPPDirective
= false;
57 /// Whether this \c UnwrappedLine is part of a pramga directive.
58 bool InPragmaDirective
= false;
59 /// Whether it is part of a macro body.
60 bool InMacroBody
= false;
62 bool MustBeDeclaration
= false;
64 /// Whether the parser has seen \c decltype(auto) in this line.
65 bool SeenDecltypeAuto
= false;
67 /// \c True if this line should be indented by ContinuationIndent in
68 /// addition to the normal indention level.
69 bool IsContinuation
= false;
71 /// If this \c UnwrappedLine closes a block in a sequence of lines,
72 /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding
73 /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be
75 size_t MatchingOpeningBlockLineIndex
= kInvalidIndex
;
77 /// If this \c UnwrappedLine opens a block, stores the index of the
78 /// line with the corresponding closing brace.
79 size_t MatchingClosingBlockLineIndex
= kInvalidIndex
;
81 static const size_t kInvalidIndex
= -1;
83 unsigned FirstStartColumn
= 0;
86 /// Interface for users of the UnwrappedLineParser to receive the parsed lines.
87 /// Parsing a single snippet of code can lead to multiple runs, where each
88 /// run is a coherent view of the file.
90 /// For example, different runs are generated:
91 /// - for different combinations of #if blocks
92 /// - when macros are involved, for the expanded code and the as-written code
94 /// Some tokens will only be visible in a subset of the runs.
95 /// For each run, \c UnwrappedLineParser will call \c consumeUnwrappedLine
96 /// for each parsed unwrapped line, and then \c finishRun to indicate
97 /// that the set of unwrapped lines before is one coherent view of the
98 /// code snippet to be formatted.
99 class UnwrappedLineConsumer
{
101 virtual ~UnwrappedLineConsumer() {}
102 virtual void consumeUnwrappedLine(const UnwrappedLine
&Line
) = 0;
103 virtual void finishRun() = 0;
106 class FormatTokenSource
;
108 class UnwrappedLineParser
{
110 UnwrappedLineParser(SourceManager
&SourceMgr
, const FormatStyle
&Style
,
111 const AdditionalKeywords
&Keywords
,
112 unsigned FirstStartColumn
, ArrayRef
<FormatToken
*> Tokens
,
113 UnwrappedLineConsumer
&Callback
,
114 llvm::SpecificBumpPtrAllocator
<FormatToken
> &Allocator
,
115 IdentifierTable
&IdentTable
);
120 enum class IfStmtKind
{
121 NotIf
, // Not an if statement.
122 IfOnly
, // An if statement without the else clause.
123 IfElse
, // An if statement followed by else but not else if.
124 IfElseIf
// An if statement followed by else if.
129 bool precededByCommentOrPPDirective() const;
130 bool parseLevel(const FormatToken
*OpeningBrace
= nullptr,
131 IfStmtKind
*IfKind
= nullptr,
132 FormatToken
**IfLeftBrace
= nullptr);
133 bool mightFitOnOneLine(UnwrappedLine
&Line
,
134 const FormatToken
*OpeningBrace
= nullptr) const;
135 FormatToken
*parseBlock(bool MustBeDeclaration
= false,
136 unsigned AddLevels
= 1u, bool MunchSemi
= true,
137 bool KeepBraces
= true, IfStmtKind
*IfKind
= nullptr,
138 bool UnindentWhitesmithsBraces
= false);
139 void parseChildBlock();
140 void parsePPDirective();
141 void parsePPDefine();
142 void parsePPIf(bool IfDef
);
145 void parsePPPragma();
146 void parsePPUnknown();
147 void readTokenWithJavaScriptASI();
148 void parseStructuralElement(const FormatToken
*OpeningBrace
= nullptr,
149 IfStmtKind
*IfKind
= nullptr,
150 FormatToken
**IfLeftBrace
= nullptr,
151 bool *HasDoWhile
= nullptr,
152 bool *HasLabel
= nullptr);
153 bool tryToParseBracedList();
154 bool parseBracedList(bool ContinueOnSemicolons
= false, bool IsEnum
= false,
155 tok::TokenKind ClosingBraceKind
= tok::r_brace
);
156 bool parseParens(TokenType AmpAmpTokenType
= TT_Unknown
);
157 void parseSquare(bool LambdaIntroducer
= false);
158 void keepAncestorBraces();
159 void parseUnbracedBody(bool CheckEOF
= false);
160 void handleAttributes();
161 bool handleCppAttributes();
162 bool isBlockBegin(const FormatToken
&Tok
) const;
163 FormatToken
*parseIfThenElse(IfStmtKind
*IfKind
, bool KeepBraces
= false,
164 bool IsVerilogAssert
= false);
165 void parseTryCatch();
166 void parseLoopBody(bool KeepBraces
, bool WrapRightBrace
);
167 void parseForOrWhileLoop(bool HasParens
= true);
169 void parseLabel(bool LeftAlignLabel
= false);
170 void parseCaseLabel();
172 void parseNamespace();
173 bool parseModuleImport();
175 void parseAccessSpecifier();
177 bool parseStructLike();
178 bool parseRequires();
179 void parseRequiresClause(FormatToken
*RequiresToken
);
180 void parseRequiresExpression(FormatToken
*RequiresToken
);
181 void parseConstraintExpression();
182 void parseJavaEnumBody();
183 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
184 // parses the record as a child block, i.e. if the class declaration is an
186 void parseRecord(bool ParseAsExpr
= false);
187 void parseObjCLightweightGenerics();
188 void parseObjCMethod();
189 void parseObjCProtocolList();
190 void parseObjCUntilAtEnd();
191 void parseObjCInterfaceOrImplementation();
192 bool parseObjCProtocol();
193 void parseJavaScriptEs6ImportExport();
194 void parseStatementMacro();
195 void parseCSharpAttribute();
196 // Parse a C# generic type constraint: `where T : IComparable<T>`.
198 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
199 void parseCSharpGenericTypeConstraint();
200 bool tryToParseLambda();
201 bool tryToParseChildBlock();
202 bool tryToParseLambdaIntroducer();
203 bool tryToParsePropertyAccessor();
204 void tryToParseJSFunction();
205 bool tryToParseSimpleAttribute();
206 void parseVerilogHierarchyIdentifier();
207 void parseVerilogSensitivityList();
208 // Returns the number of levels of indentation in addition to the normal 1
209 // level for a block, used for indenting case labels.
210 unsigned parseVerilogHierarchyHeader();
211 void parseVerilogTable();
212 void parseVerilogCaseLabel();
213 std::optional
<llvm::SmallVector
<llvm::SmallVector
<FormatToken
*, 8>, 1>>
216 // Used by addUnwrappedLine to denote whether to keep or remove a level
217 // when resetting the line state.
218 enum class LineLevel
{ Remove
, Keep
};
220 void addUnwrappedLine(LineLevel AdjustLevel
= LineLevel::Remove
);
222 // LevelDifference is the difference of levels after and before the current
223 // token. For example:
224 // - if the token is '{' and opens a block, LevelDifference is 1.
225 // - if the token is '}' and closes a block, LevelDifference is -1.
226 void nextToken(int LevelDifference
= 0);
227 void readToken(int LevelDifference
= 0);
229 // Decides which comment tokens should be added to the current line and which
230 // should be added as comments before the next token.
232 // Comments specifies the sequence of comment tokens to analyze. They get
233 // either pushed to the current line or added to the comments before the next
236 // NextTok specifies the next token. A null pointer NextTok is supported, and
237 // signifies either the absence of a next token, or that the next token
238 // shouldn't be taken into account for the analysis.
239 void distributeComments(const SmallVectorImpl
<FormatToken
*> &Comments
,
240 const FormatToken
*NextTok
);
242 // Adds the comment preceding the next token to unwrapped lines.
243 void flushComments(bool NewlineBeforeNext
);
244 void pushToken(FormatToken
*Tok
);
245 void calculateBraceTypes(bool ExpectClassBody
= false);
246 void setPreviousRBraceType(TokenType Type
);
248 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
249 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
250 // this branch either cannot be taken (for example '#if false'), or should
251 // not be taken in this round.
252 void conditionalCompilationCondition(bool Unreachable
);
253 void conditionalCompilationStart(bool Unreachable
);
254 void conditionalCompilationAlternative();
255 void conditionalCompilationEnd();
257 bool isOnNewLine(const FormatToken
&FormatTok
);
259 // Returns whether there is a macro expansion in the line, i.e. a token that
260 // was expanded from a macro call.
261 bool containsExpansion(const UnwrappedLine
&Line
) const;
263 // Compute hash of the current preprocessor branch.
264 // This is used to identify the different branches, and thus track if block
265 // open and close in the same branch.
266 size_t computePPHash() const;
268 bool parsingPPDirective() const { return CurrentLines
!= &Lines
; }
270 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
271 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
272 // and use that everywhere in the Parser.
273 std::unique_ptr
<UnwrappedLine
> Line
;
275 // Lines that are created by macro expansion.
276 // When formatting code containing macro calls, we first format the expanded
277 // lines to set the token types correctly. Afterwards, we format the
278 // reconstructed macro calls, re-using the token types determined in the first
280 // ExpandedLines will be reset every time we create a new LineAndExpansion
281 // instance once a line containing macro calls has been parsed.
282 SmallVector
<UnwrappedLine
, 8> CurrentExpandedLines
;
284 // Maps from the first token of a top-level UnwrappedLine that contains
285 // a macro call to the replacement UnwrappedLines expanded from the macro
287 llvm::DenseMap
<FormatToken
*, SmallVector
<UnwrappedLine
, 8>> ExpandedLines
;
289 // Map from the macro identifier to a line containing the full unexpanded
291 llvm::DenseMap
<FormatToken
*, std::unique_ptr
<UnwrappedLine
>> Unexpanded
;
293 // For recursive macro expansions, trigger reconstruction only on the
294 // outermost expansion.
295 bool InExpansion
= false;
297 // Set while we reconstruct a macro call.
298 // For reconstruction, we feed the expanded lines into the reconstructor
299 // until it is finished.
300 std::optional
<MacroCallReconstructor
> Reconstruct
;
302 // Comments are sorted into unwrapped lines by whether they are in the same
303 // line as the previous token, or not. If not, they belong to the next token.
304 // Since the next token might already be in a new unwrapped line, we need to
305 // store the comments belonging to that token.
306 SmallVector
<FormatToken
*, 1> CommentsBeforeNextToken
;
307 FormatToken
*FormatTok
= nullptr;
308 bool MustBreakBeforeNextToken
;
310 // The parsed lines. Only added to through \c CurrentLines.
311 SmallVector
<UnwrappedLine
, 8> Lines
;
313 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
314 // Thus, we need to keep a list of preprocessor directives to be reported
315 // after an unwrapped line that has been started was finished.
316 SmallVector
<UnwrappedLine
, 4> PreprocessorDirectives
;
318 // New unwrapped lines are added via CurrentLines.
319 // Usually points to \c &Lines. While parsing a preprocessor directive when
320 // there is an unfinished previous unwrapped line, will point to
321 // \c &PreprocessorDirectives.
322 SmallVectorImpl
<UnwrappedLine
> *CurrentLines
;
324 // We store for each line whether it must be a declaration depending on
325 // whether we are in a compound statement or not.
326 llvm::BitVector DeclarationScopeStack
;
328 const FormatStyle
&Style
;
329 const AdditionalKeywords
&Keywords
;
331 llvm::Regex CommentPragmasRegex
;
333 FormatTokenSource
*Tokens
;
334 UnwrappedLineConsumer
&Callback
;
336 ArrayRef
<FormatToken
*> AllTokens
;
338 // Keeps a stack of the states of nested control statements (true if the
339 // statement contains more than some predefined number of nested statements).
340 SmallVector
<bool, 8> NestedTooDeep
;
342 // Keeps a stack of the states of nested lambdas (true if the return type of
343 // the lambda is `decltype(auto)`).
344 SmallVector
<bool, 4> NestedLambdas
;
346 // Whether the parser is parsing the body of a function whose return type is
348 bool IsDecltypeAutoFunction
= false;
350 // Represents preprocessor branch type, so we can find matching
351 // #if/#else/#endif directives.
353 PP_Conditional
, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
354 PP_Unreachable
// #if 0 or a conditional preprocessor block inside #if 0
358 PPBranch(PPBranchKind Kind
, size_t Line
) : Kind(Kind
), Line(Line
) {}
363 // Keeps a stack of currently active preprocessor branching directives.
364 SmallVector
<PPBranch
, 16> PPStack
;
366 // The \c UnwrappedLineParser re-parses the code for each combination
367 // of preprocessor branches that can be taken.
368 // To that end, we take the same branch (#if, #else, or one of the #elif
369 // branches) for each nesting level of preprocessor branches.
370 // \c PPBranchLevel stores the current nesting level of preprocessor
371 // branches during one pass over the code.
374 // Contains the current branch (#if, #else or one of the #elif branches)
375 // for each nesting level.
376 SmallVector
<int, 8> PPLevelBranchIndex
;
378 // Contains the maximum number of branches at each nesting level.
379 SmallVector
<int, 8> PPLevelBranchCount
;
381 // Contains the number of branches per nesting level we are currently
382 // in while parsing a preprocessor branch sequence.
383 // This is used to update PPLevelBranchCount at the end of a branch
385 std::stack
<int> PPChainBranchIndex
;
387 // Include guard search state. Used to fixup preprocessor indent levels
388 // so that include guards do not participate in indentation.
389 enum IncludeGuardState
{
390 IG_Inited
, // Search started, looking for #ifndef.
391 IG_IfNdefed
, // #ifndef found, IncludeGuardToken points to condition.
392 IG_Defined
, // Matching #define found, checking other requirements.
393 IG_Found
, // All requirements met, need to fix indents.
394 IG_Rejected
, // Search failed or never started.
397 // Current state of include guard search.
398 IncludeGuardState IncludeGuard
;
400 // Points to the #ifndef condition for a potential include guard. Null unless
401 // IncludeGuardState == IG_IfNdefed.
402 FormatToken
*IncludeGuardToken
;
404 // Contains the first start column where the source begins. This is zero for
405 // normal source code and may be nonzero when formatting a code fragment that
406 // does not start at the beginning of the file.
407 unsigned FirstStartColumn
;
409 MacroExpander Macros
;
411 friend class ScopedLineState
;
412 friend class CompoundStatementIndenter
;
415 struct UnwrappedLineNode
{
416 UnwrappedLineNode() : Tok(nullptr) {}
417 UnwrappedLineNode(FormatToken
*Tok
,
418 llvm::ArrayRef
<UnwrappedLine
> Children
= {})
419 : Tok(Tok
), Children(Children
.begin(), Children
.end()) {}
422 SmallVector
<UnwrappedLine
, 0> Children
;
425 } // end namespace format
426 } // end namespace clang