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 void handleAttributes();
166 bool handleCppAttributes();
167 bool isBlockBegin(const FormatToken &Tok) const;
168 FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false,
169 bool IsVerilogAssert = false);
170 void parseTryCatch();
171 void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
172 void parseForOrWhileLoop(bool HasParens = true);
173 void parseDoWhile();
174 void parseLabel(bool IsGotoLabel = false);
175 void parseCaseLabel();
176 void parseSwitch(bool IsExpr);
177 void parseNamespace();
178 bool parseModuleDecl();
179 bool parseImportDecl();
180 void parseNew();
181 void parseAccessSpecifier();
182 bool parseEnum();
183 bool parseStructLike();
184 bool parseRequires(bool SeenEqual);
185 void parseRequiresClause();
186 void parseRequiresExpression();
187 void parseConstraintExpression();
188 void parseCppExportBlock();
189 void parseNamespaceOrExportBlock(unsigned AddLevels);
190 void parseJavaEnumBody();
191 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
192 // parses the record as a child block, i.e. if the class declaration is an
193 // expression.
194 void parseRecord(bool ParseAsExpr = false, bool IsJavaRecord = false);
195 void parseObjCLightweightGenerics();
196 void parseObjCMethod();
197 void parseObjCProtocolList();
198 void parseObjCUntilAtEnd();
199 void parseObjCInterfaceOrImplementation();
200 bool parseObjCProtocol();
201 void parseJavaScriptEs6ImportExport();
202 void parseStatementMacro();
203 void parseCSharpAttribute();
204 // Parse a C# generic type constraint: `where T : IComparable<T>`.
205 // See:
206 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
207 void parseCSharpGenericTypeConstraint();
208 bool tryToParseLambda();
209 bool tryToParseChildBlock();
210 bool tryToParseLambdaIntroducer();
211 bool tryToParsePropertyAccessor();
212 void tryToParseJSFunction();
213 bool tryToParseSimpleAttribute();
214 void parseVerilogHierarchyIdentifier();
215 void parseVerilogSensitivityList();
216 // Returns the number of levels of indentation in addition to the normal 1
217 // level for a block, used for indenting case labels.
218 unsigned parseVerilogHierarchyHeader();
219 void parseVerilogTable();
220 void parseVerilogCaseLabel();
221 // For import, export, and extern.
222 void parseVerilogExtern();
223 // Skip things that can precede the keywords like module.
224 void skipVerilogQualifiers();
225 struct PPState;
226 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
227 parseMacroCall(const PPState &SavedPPState);
228
229 // Used by addUnwrappedLine to denote whether to keep or remove a level
230 // when resetting the line state.
231 enum class LineLevel { Remove, Keep };
232
233 void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
234 bool eof() const;
235 // LevelDifference is the difference of levels after and before the current
236 // token. For example:
237 // - if the token is '{' and opens a block, LevelDifference is 1.
238 // - if the token is '}' and closes a block, LevelDifference is -1.
239 void nextToken(int LevelDifference = 0);
240 void readToken(int LevelDifference = 0);
241
242 // Decides which comment tokens should be added to the current line and which
243 // should be added as comments before the next token.
244 //
245 // Comments specifies the sequence of comment tokens to analyze. They get
246 // either pushed to the current line or added to the comments before the next
247 // token.
248 //
249 // NextTok specifies the next token. A null pointer NextTok is supported, and
250 // signifies either the absence of a next token, or that the next token
251 // shouldn't be taken into account for the analysis.
252 void distributeComments(const ArrayRef<FormatToken *> &Comments,
253 const FormatToken *NextTok);
254
255 // Adds the comment preceding the next token to unwrapped lines.
256 void flushComments(bool NewlineBeforeNext);
257 void pushToken(FormatToken *Tok);
258 void calculateBraceTypes(bool ExpectClassBody = false);
259 void setPreviousRBraceType(TokenType Type);
260
261 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
262 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
263 // this branch either cannot be taken (for example '#if false'), or should
264 // not be taken in this round.
265 void conditionalCompilationCondition(bool Unreachable);
266 void conditionalCompilationStart(bool Unreachable);
267 void conditionalCompilationAlternative();
268 void conditionalCompilationEnd();
269
270 bool isOnNewLine(const FormatToken &FormatTok);
271
272 // Returns whether there is a macro expansion in the line, i.e. a token that
273 // was expanded from a macro call.
274 bool containsExpansion(const UnwrappedLine &Line) const;
275
276 // Compute hash of the current preprocessor branch.
277 // This is used to identify the different branches, and thus track if block
278 // open and close in the same branch.
279 size_t computePPHash() const;
280
281 bool parsingPPDirective() const { return CurrentLines != &Lines; }
282
283 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
284 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
285 // and use that everywhere in the Parser.
286 std::unique_ptr<UnwrappedLine> Line;
287
288 // Lines that are created by macro expansion.
289 // When formatting code containing macro calls, we first format the expanded
290 // lines to set the token types correctly. Afterwards, we format the
291 // reconstructed macro calls, re-using the token types determined in the first
292 // step.
293 // ExpandedLines will be reset every time we create a new LineAndExpansion
294 // instance once a line containing macro calls has been parsed.
295 SmallVector<UnwrappedLine, 8> CurrentExpandedLines;
296
297 // Maps from the first token of a top-level UnwrappedLine that contains
298 // a macro call to the replacement UnwrappedLines expanded from the macro
299 // call.
300 llvm::DenseMap<FormatToken *, SmallVector<UnwrappedLine, 8>> ExpandedLines;
301
302 // Map from the macro identifier to a line containing the full unexpanded
303 // macro call.
304 llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>> Unexpanded;
305
306 // For recursive macro expansions, trigger reconstruction only on the
307 // outermost expansion.
308 bool InExpansion = false;
309
310 // Set while we reconstruct a macro call.
311 // For reconstruction, we feed the expanded lines into the reconstructor
312 // until it is finished.
313 std::optional<MacroCallReconstructor> Reconstruct;
314
315 // Comments are sorted into unwrapped lines by whether they are in the same
316 // line as the previous token, or not. If not, they belong to the next token.
317 // Since the next token might already be in a new unwrapped line, we need to
318 // store the comments belonging to that token.
319 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
320
321 FormatToken *FormatTok = nullptr;
322
323 // The parsed lines. Only added to through \c CurrentLines.
325
326 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
327 // Thus, we need to keep a list of preprocessor directives to be reported
328 // after an unwrapped line that has been started was finished.
329 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
330
331 // New unwrapped lines are added via CurrentLines.
332 // Usually points to \c &Lines. While parsing a preprocessor directive when
333 // there is an unfinished previous unwrapped line, will point to
334 // \c &PreprocessorDirectives.
335 SmallVectorImpl<UnwrappedLine> *CurrentLines;
336
337 // We store for each line whether it must be a declaration depending on
338 // whether we are in a compound statement or not.
339 llvm::BitVector DeclarationScopeStack;
340
341 const FormatStyle &Style;
342 bool IsCpp;
343 LangOptions LangOpts;
344 const AdditionalKeywords &Keywords;
345
346 llvm::Regex CommentPragmasRegex;
347
348 FormatTokenSource *Tokens;
349 UnwrappedLineConsumer &Callback;
350
351 ArrayRef<FormatToken *> AllTokens;
352
353 // Keeps a stack of the states of nested control statements (true if the
354 // statement contains more than some predefined number of nested statements).
355 SmallVector<bool, 8> NestedTooDeep;
356
357 // Keeps a stack of the states of nested lambdas (true if the return type of
358 // the lambda is `decltype(auto)`).
359 SmallVector<bool, 4> NestedLambdas;
360
361 // Whether the parser is parsing the body of a function whose return type is
362 // `decltype(auto)`.
363 bool IsDecltypeAutoFunction = false;
364
365 // Represents preprocessor branch type, so we can find matching
366 // #if/#else/#endif directives.
367 enum PPBranchKind {
368 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
369 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
370 };
371
372 struct PPBranch {
373 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
374 PPBranchKind Kind;
375 size_t Line;
376 };
377
378 // Include guard search state. Used to fixup preprocessor indent levels
379 // so that include guards do not participate in indentation.
380 enum IncludeGuardState {
381 IG_Inited, // Search started, looking for #ifndef.
382 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
383 IG_Defined, // Matching #define found, checking other requirements.
384 IG_Found, // All requirements met, need to fix indents.
385 IG_Rejected, // Search failed or never started.
386 };
387
388 IncludeGuardState
389 getIncludeGuardState(FormatStyle::PPDirectiveIndentStyle Style) const {
390 return Style == FormatStyle::PPDIS_None || Style == FormatStyle::PPDIS_Leave
391 ? IG_Rejected
392 : IG_Inited;
393 }
394
395 // The preprocessor bookkeeping that is rolled back when the token stream is
396 // rewound over preprocessor directives, which happens if the speculatively
397 // parsed arguments of a macro call are discarded. See readToken().
398 struct PPState {
399 explicit PPState(IncludeGuardState IncludeGuard)
400 : IncludeGuard(IncludeGuard) {}
401
402 // Keeps a stack of currently active preprocessor branching directives.
404
405 // The \c UnwrappedLineParser re-parses the code for each combination
406 // of preprocessor branches that can be taken.
407 // To that end, we take the same branch (#if, #else, or one of the #elif
408 // branches) for each nesting level of preprocessor branches.
409 // \c BranchLevel stores the current nesting level of preprocessor
410 // branches during one pass over the code.
411 int BranchLevel = -1;
412
413 // Contains the current branch (#if, #else or one of the #elif branches)
414 // for each nesting level.
415 SmallVector<int, 8> LevelBranchIndex;
416
417 // Contains the maximum number of branches at each nesting level.
418 SmallVector<int, 8> LevelBranchCount;
419
420 // Contains the number of branches per nesting level we are currently
421 // in while parsing a preprocessor branch sequence.
422 // This is used to update LevelBranchCount at the end of a branch
423 // sequence.
424 std::stack<int> ChainBranchIndex;
425
426 // Current state of include guard search.
427 IncludeGuardState IncludeGuard;
428
429 // Points to the #ifndef condition for a potential include guard. Null
430 // unless IncludeGuardState == IG_IfNdefed.
431 FormatToken *IncludeGuardToken = nullptr;
432
433 // Has just finished parsing a preprocessor line.
434 bool AtEndOfPPLine = false;
435 } PP;
436
437 // The hash tokens of the parsed preprocessor directives. The lines of a
438 // directive are kept when the token stream is rewound over it, so it is then
439 // parsed again only for its effect on the preprocessor bookkeeping. See
440 // readToken().
442
443 // Follows an if statement whose else may be in a skipped preprocessor branch.
444 const FormatToken *TokenAfterIfWithConditionalElse = nullptr;
445
446 // Contains the first start column where the source begins. This is zero for
447 // normal source code and may be nonzero when formatting a code fragment that
448 // does not start at the beginning of the file.
449 unsigned FirstStartColumn;
450
451 MacroExpander Macros;
452
453 friend class ScopedLineState;
455};
456
466
467std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line);
468
469} // end namespace format
470} // end namespace clang
471
472#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...