clang 24.0.0git
UnwrappedLineParser.h
Go to the documentation of this file.
1//===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
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 declaration of the UnwrappedLineParser,
11/// which turns a stream of tokens into UnwrappedLines.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
16#define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
17
18#include "Macros.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include <stack>
21
22namespace clang {
23namespace format {
24
26
27/// An unwrapped line is a sequence of \c Token, that we would like to
28/// put on a single line if there was no column limit.
29///
30/// This is used as a main interface between the \c UnwrappedLineParser and the
31/// \c UnwrappedLineFormatter. The key property is that changing the formatting
32/// within an unwrapped line does not affect any other unwrapped lines.
34 UnwrappedLine() = default;
35
36 /// The \c Tokens comprising this \c UnwrappedLine.
37 std::list<UnwrappedLineNode> Tokens;
38
39 /// The indent level of the \c UnwrappedLine.
40 unsigned Level = 0;
41
42 /// The \c PPState::BranchLevel (adjusted for header guards) if this line is a
43 /// \c InMacroBody line, and 0 otherwise.
44 unsigned PPLevel = 0;
45
46 /// Whether this \c UnwrappedLine is part of a preprocessor directive.
47 bool InPPDirective = false;
48 /// Whether this \c UnwrappedLine is part of a pramga directive.
49 bool InPragmaDirective = false;
50 /// Whether it is part of a macro body.
51 bool InMacroBody = false;
52 /// Whether this \c UnwrappedLine is part of the first pass of a multi-pass
53 /// macro expansion run.
54 bool InMacroExpansion = false;
55
56 /// Nesting level of unbraced body of a control statement.
57 unsigned UnbracedBodyLevel = 0;
58
59 bool MustBeDeclaration = false;
60
61 /// Whether the parser has seen \c decltype(auto) in this line.
62 bool SeenDecltypeAuto = false;
63
64 /// \c True if this line should be indented by ContinuationIndent in
65 /// addition to the normal indention level.
66 bool IsContinuation = false;
67
68 /// Whether it is a C++20 module/import declaration.
70
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
74 /// \c kInvalidIndex.
76
77 /// If this \c UnwrappedLine opens a block, stores the index of the
78 /// line with the corresponding closing brace.
80
81 static const size_t kInvalidIndex = -1;
82
83 unsigned FirstStartColumn = 0;
84};
85
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.
89///
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
93///
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.
100public:
102 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
103 virtual void finishRun() = 0;
104};
105
107
109public:
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);
116
117 void parse();
118
119private:
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.
125 };
126
127 void reset();
128 void parseFile();
129 bool precededByCommentOrPPDirective() const;
130 bool parseLevel(const FormatToken *OpeningBrace = nullptr,
131 IfStmtKind *IfKind = nullptr,
132 FormatToken **IfLeftBrace = nullptr,
133 bool *SeenExplicitAccessModifier = nullptr);
134 bool mightFitOnOneLine(UnwrappedLine &Line,
135 const FormatToken *OpeningBrace = nullptr) const;
136 FormatToken *parseBlock(bool MustBeDeclaration = false,
137 unsigned AddLevels = 1u, bool MunchSemi = true,
138 bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
139 bool UnindentWhitesmithsBraces = false,
140 bool IndentAfterExplicitAccessModifier = false);
141 void parseChildBlock();
142 void parsePPDirective();
143 void parsePPDefine();
144 void parsePPIf(bool IfDef);
145 void parsePPElse();
146 void parsePPEndIf();
147 void parsePPPragma();
148 void parsePPUnknown();
149 void readTokenWithJavaScriptASI();
150 void parseStructuralElement(const FormatToken *OpeningBrace = nullptr,
151 IfStmtKind *IfKind = nullptr,
152 FormatToken **IfLeftBrace = nullptr,
153 bool *HasDoWhile = nullptr,
154 bool *HasLabel = nullptr);
155 bool tryToParseBracedList();
156 bool parseBracedList(bool IsAngleBracket = false, bool IsEnum = false);
157 bool parseParens(TokenType StarAndAmpTokenType = TT_Unknown,
158 bool InMacroCall = false);
159 // SkipLambda means the square does not begin a lambda expression. The opening
160 // square bracket is assumed to be consumed when it is true.
161 void parseSquare(bool SkipLambda = false);
162 void keepAncestorBraces();
163 void parseUnbracedBody(bool CheckEOF = false);
164 bool isFollowedByConditionalElse() const;
165 bool canInsertBraces(const FormatToken &LBraceTok,
166 const FormatToken &RBraceTok) const;
167 void handleAttributes();
168 bool handleCppAttributes();
169 bool isBlockBegin(const FormatToken &Tok) const;
170 FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false,
171 bool IsVerilogAssert = false);
172 void parseTryCatch();
173 void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
174 void parseForOrWhileLoop(bool HasParens = true);
175 void parseDoWhile();
176 void parseLabel(bool IsGotoLabel = false);
177 void parseCaseLabel();
178 void parseSwitch(bool IsExpr);
179 void parseNamespace();
180 bool parseModuleDecl();
181 bool parseImportDecl();
182 void parseNew();
183 void parseAccessSpecifier();
184 bool parseEnum();
185 bool parseStructLike();
186 bool parseRequires(bool SeenEqual);
187 void parseRequiresClause();
188 void parseRequiresExpression();
189 void parseConstraintExpression();
190 void parseCppExportBlock();
191 void parseNamespaceOrExportBlock(unsigned AddLevels);
192 void parseJavaEnumBody();
193 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
194 // parses the record as a child block, i.e. if the class declaration is an
195 // expression.
196 void parseRecord(bool ParseAsExpr = false, bool IsJavaRecord = false);
197 void parseObjCLightweightGenerics();
198 void parseObjCMethod();
199 void parseObjCProtocolList();
200 void parseObjCUntilAtEnd();
201 void parseObjCInterfaceOrImplementation();
202 bool parseObjCProtocol();
203 void parseJavaScriptEs6ImportExport();
204 void parseStatementMacro();
205 void parseCSharpAttribute();
206 // Parse a C# generic type constraint: `where T : IComparable<T>`.
207 // See:
208 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
209 void parseCSharpGenericTypeConstraint();
210 bool tryToParseLambda();
211 bool tryToParseChildBlock();
212 bool tryToParseLambdaIntroducer();
213 bool tryToParsePropertyAccessor();
214 void tryToParseJSFunction();
215 bool tryToParseSimpleAttribute();
216 void parseVerilogHierarchyIdentifier();
217 void parseVerilogSensitivityList();
218 // Returns the number of levels of indentation in addition to the normal 1
219 // level for a block, used for indenting case labels.
220 unsigned parseVerilogHierarchyHeader();
221 void parseVerilogTable();
222 void parseVerilogCaseLabel();
223 // For import, export, and extern.
224 void parseVerilogExtern();
225 // Skip things that can precede the keywords like module.
226 void skipVerilogQualifiers();
227 struct PPState;
228 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
229 parseMacroCall(const PPState &SavedPPState);
230
231 // Used by addUnwrappedLine to denote whether to keep or remove a level
232 // when resetting the line state.
233 enum class LineLevel { Remove, Keep };
234
235 void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
236 bool eof() const;
237 // LevelDifference is the difference of levels after and before the current
238 // token. For example:
239 // - if the token is '{' and opens a block, LevelDifference is 1.
240 // - if the token is '}' and closes a block, LevelDifference is -1.
241 void nextToken(int LevelDifference = 0);
242 void readToken(int LevelDifference = 0);
243
244 // Decides which comment tokens should be added to the current line and which
245 // should be added as comments before the next token.
246 //
247 // Comments specifies the sequence of comment tokens to analyze. They get
248 // either pushed to the current line or added to the comments before the next
249 // token.
250 //
251 // NextTok specifies the next token. A null pointer NextTok is supported, and
252 // signifies either the absence of a next token, or that the next token
253 // shouldn't be taken into account for the analysis.
254 void distributeComments(const ArrayRef<FormatToken *> &Comments,
255 const FormatToken *NextTok);
256
257 // Adds the comment preceding the next token to unwrapped lines.
258 void flushComments(bool NewlineBeforeNext);
259 void pushToken(FormatToken *Tok);
260 void calculateBraceTypes(bool ExpectClassBody = false);
261 void setPreviousRBraceType(TokenType Type);
262
263 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
264 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
265 // this branch either cannot be taken (for example '#if false'), or should
266 // not be taken in this round.
267 void conditionalCompilationCondition(bool Unreachable);
268 void conditionalCompilationStart(bool Unreachable);
269 void conditionalCompilationAlternative();
270 void conditionalCompilationEnd();
271
272 bool isOnNewLine(const FormatToken &FormatTok);
273
274 // Returns whether there is a macro expansion in the line, i.e. a token that
275 // was expanded from a macro call.
276 bool containsExpansion(const UnwrappedLine &Line) const;
277
278 // Compute hash of the current preprocessor branch.
279 // This is used to identify the different branches, and thus track if block
280 // open and close in the same branch.
281 size_t computePPHash() const;
282
283 bool parsingPPDirective() const { return CurrentLines != &Lines; }
284
285 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
286 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
287 // and use that everywhere in the Parser.
288 std::unique_ptr<UnwrappedLine> Line;
289
290 // Lines that are created by macro expansion.
291 // When formatting code containing macro calls, we first format the expanded
292 // lines to set the token types correctly. Afterwards, we format the
293 // reconstructed macro calls, re-using the token types determined in the first
294 // step.
295 // ExpandedLines will be reset every time we create a new LineAndExpansion
296 // instance once a line containing macro calls has been parsed.
297 SmallVector<UnwrappedLine, 8> CurrentExpandedLines;
298
299 // Maps from the first token of a top-level UnwrappedLine that contains
300 // a macro call to the replacement UnwrappedLines expanded from the macro
301 // call.
302 llvm::DenseMap<FormatToken *, SmallVector<UnwrappedLine, 8>> ExpandedLines;
303
304 // Map from the macro identifier to a line containing the full unexpanded
305 // macro call.
306 llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>> Unexpanded;
307
308 // For recursive macro expansions, trigger reconstruction only on the
309 // outermost expansion.
310 bool InExpansion = false;
311
312 // Set while we reconstruct a macro call.
313 // For reconstruction, we feed the expanded lines into the reconstructor
314 // until it is finished.
315 std::optional<MacroCallReconstructor> Reconstruct;
316
317 // Comments are sorted into unwrapped lines by whether they are in the same
318 // line as the previous token, or not. If not, they belong to the next token.
319 // Since the next token might already be in a new unwrapped line, we need to
320 // store the comments belonging to that token.
321 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
322
323 FormatToken *FormatTok = nullptr;
324
325 // The parsed lines. Only added to through \c CurrentLines.
327
328 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
329 // Thus, we need to keep a list of preprocessor directives to be reported
330 // after an unwrapped line that has been started was finished.
331 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
332
333 // New unwrapped lines are added via CurrentLines.
334 // Usually points to \c &Lines. While parsing a preprocessor directive when
335 // there is an unfinished previous unwrapped line, will point to
336 // \c &PreprocessorDirectives.
337 SmallVectorImpl<UnwrappedLine> *CurrentLines;
338
339 // We store for each line whether it must be a declaration depending on
340 // whether we are in a compound statement or not.
341 llvm::BitVector DeclarationScopeStack;
342
343 const FormatStyle &Style;
344 bool IsCpp;
345 LangOptions LangOpts;
346 const AdditionalKeywords &Keywords;
347
348 llvm::Regex CommentPragmasRegex;
349
350 FormatTokenSource *Tokens;
351 UnwrappedLineConsumer &Callback;
352
353 ArrayRef<FormatToken *> AllTokens;
354
355 // Keeps a stack of the states of nested control statements (true if the
356 // statement contains more than some predefined number of nested statements).
357 SmallVector<bool, 8> NestedTooDeep;
358
359 // Keeps a stack of the states of nested lambdas (true if the return type of
360 // the lambda is `decltype(auto)`).
361 SmallVector<bool, 4> NestedLambdas;
362
363 // Whether the parser is parsing the body of a function whose return type is
364 // `decltype(auto)`.
365 bool IsDecltypeAutoFunction = false;
366
367 // Represents preprocessor branch type, so we can find matching
368 // #if/#else/#endif directives.
369 enum PPBranchKind {
370 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
371 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
372 };
373
374 struct PPBranch {
375 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
376 PPBranchKind Kind;
377 size_t Line;
378 };
379
380 // Include guard search state. Used to fixup preprocessor indent levels
381 // so that include guards do not participate in indentation.
382 enum IncludeGuardState {
383 IG_Inited, // Search started, looking for #ifndef.
384 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
385 IG_Defined, // Matching #define found, checking other requirements.
386 IG_Found, // All requirements met, need to fix indents.
387 IG_Rejected, // Search failed or never started.
388 };
389
390 IncludeGuardState
391 getIncludeGuardState(FormatStyle::PPDirectiveIndentStyle Style) const {
392 return Style == FormatStyle::PPDIS_None || Style == FormatStyle::PPDIS_Leave
393 ? IG_Rejected
394 : IG_Inited;
395 }
396
397 // The preprocessor bookkeeping that is rolled back when the token stream is
398 // rewound over preprocessor directives, which happens if the speculatively
399 // parsed arguments of a macro call are discarded. See readToken().
400 struct PPState {
401 explicit PPState(IncludeGuardState IncludeGuard)
402 : IncludeGuard(IncludeGuard) {}
403
404 // Keeps a stack of currently active preprocessor branching directives.
406
407 // The \c UnwrappedLineParser re-parses the code for each combination
408 // of preprocessor branches that can be taken.
409 // To that end, we take the same branch (#if, #else, or one of the #elif
410 // branches) for each nesting level of preprocessor branches.
411 // \c BranchLevel stores the current nesting level of preprocessor
412 // branches during one pass over the code.
413 int BranchLevel = -1;
414
415 // Contains the current branch (#if, #else or one of the #elif branches)
416 // for each nesting level.
417 SmallVector<int, 8> LevelBranchIndex;
418
419 // Contains the maximum number of branches at each nesting level.
420 SmallVector<int, 8> LevelBranchCount;
421
422 // Contains the number of branches per nesting level we are currently
423 // in while parsing a preprocessor branch sequence.
424 // This is used to update LevelBranchCount at the end of a branch
425 // sequence.
426 std::stack<int> ChainBranchIndex;
427
428 // Current state of include guard search.
429 IncludeGuardState IncludeGuard;
430
431 // Points to the #ifndef condition for a potential include guard. Null
432 // unless IncludeGuardState == IG_IfNdefed.
433 FormatToken *IncludeGuardToken = nullptr;
434
435 // Has just finished parsing a preprocessor line.
436 bool AtEndOfPPLine = false;
437 } PP;
438
439 // The hash tokens of the parsed preprocessor directives. The lines of a
440 // directive are kept when the token stream is rewound over it, so it is then
441 // parsed again only for its effect on the preprocessor bookkeeping. See
442 // readToken().
444
445 // Follows an if statement whose else may be in a skipped preprocessor branch.
446 const FormatToken *TokenAfterIfWithConditionalElse = nullptr;
447
448 // Contains the first start column where the source begins. This is zero for
449 // normal source code and may be nonzero when formatting a code fragment that
450 // does not start at the beginning of the file.
451 unsigned FirstStartColumn;
452
453 MacroExpander Macros;
454
455 friend class ScopedLineState;
457};
458
468
469std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line);
470
471} // end namespace format
472} // end namespace clang
473
474#endif
Token Tok
The Token.
SmallVector< AnnotatedLine *, 1 > Children
If this token starts a block, this contains all the unwrapped lines in it.
This file contains the main building blocks of macro support in clang-format.
Implements an efficient mapping from strings to IdentifierInfo nodes.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
This class handles loading and caching of source files into memory.
The base class of the type hierarchy.
Definition TypeBase.h:1879
Takes a set of macro definitions as strings and allows expanding calls to those macros.
Definition Macros.h:80
Interface for users of the UnwrappedLineParser to receive the parsed lines.
virtual void consumeUnwrappedLine(const UnwrappedLine &Line)=0
UnwrappedLineParser(SourceManager &SourceMgr, const FormatStyle &Style, const AdditionalKeywords &Keywords, unsigned FirstStartColumn, ArrayRef< FormatToken * > Tokens, UnwrappedLineConsumer &Callback, llvm::SpecificBumpPtrAllocator< FormatToken > &Allocator, IdentifierTable &IdentTable)
std::ostream & operator<<(std::ostream &Stream, const UnwrappedLine &Line)
TokenType
Determines the semantic type of a syntactic token, e.g.
Top level wrappers for InstallAPI frontend operations.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition Format.h:51
PPDirectiveIndentStyle
Options for indenting preprocessor directives.
Definition Format.h:3396
@ PPDIS_Leave
Leaves indentation of directives as-is.
Definition Format.h:3435
@ PPDIS_None
Does not indent any directives.
Definition Format.h:3405
A wrapper around a Token storing information about the whitespace characters preceding it.
SmallVector< UnwrappedLine, 0 > Children
UnwrappedLineNode(FormatToken *Tok, llvm::ArrayRef< UnwrappedLine > Children={})
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...
unsigned PPLevel
The PPState::BranchLevel (adjusted for header guards) if this line is a InMacroBody line,...
bool InMacroBody
Whether it is part of a macro body.
std::list< UnwrappedLineNode > Tokens
The Tokens comprising this UnwrappedLine.
bool IsContinuation
True if this line should be indented by ContinuationIndent in addition to the normal indention level.
unsigned Level
The indent level of the UnwrappedLine.
bool InMacroExpansion
Whether this UnwrappedLine is part of the first pass of a multi-pass macro expansion run.
unsigned UnbracedBodyLevel
Nesting level of unbraced body of a control statement.
bool InPragmaDirective
Whether this UnwrappedLine is part of a pramga directive.
bool IsModuleOrImportDecl
Whether it is a C++20 module/import declaration.
bool InPPDirective
Whether this UnwrappedLine is part of a preprocessor directive.
bool SeenDecltypeAuto
Whether the parser has seen decltype(auto) in this line.
size_t MatchingClosingBlockLineIndex
If this UnwrappedLine opens a block, stores the index of the line with the corresponding closing brac...
size_t MatchingOpeningBlockLineIndex
If this UnwrappedLine closes a block in a sequence of lines, MatchingOpeningBlockLineIndex stores the...