clang  16.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 "FormatToken.h"
20 #include "clang/Format/Format.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/Support/Regex.h"
23 #include <list>
24 #include <stack>
25 #include <vector>
26 
27 namespace clang {
28 namespace format {
29 
30 struct UnwrappedLineNode;
31 
32 /// An unwrapped line is a sequence of \c Token, that we would like to
33 /// put on a single line if there was no column limit.
34 ///
35 /// This is used as a main interface between the \c UnwrappedLineParser and the
36 /// \c UnwrappedLineFormatter. The key property is that changing the formatting
37 /// within an unwrapped line does not affect any other unwrapped lines.
38 struct UnwrappedLine {
39  UnwrappedLine();
40 
41  /// The \c Tokens comprising this \c UnwrappedLine.
42  std::list<UnwrappedLineNode> Tokens;
43 
44  /// The indent level of the \c UnwrappedLine.
45  unsigned Level;
46 
47  /// The \c PPBranchLevel (adjusted for header guards) if this line is a
48  /// \c InMacroBody line, and 0 otherwise.
49  unsigned PPLevel;
50 
51  /// Whether this \c UnwrappedLine is part of a preprocessor directive.
53  /// Whether this \c UnwrappedLine is part of a pramga directive.
55  /// Whether it is part of a macro body.
57 
59 
60  /// \c True if this line should be indented by ContinuationIndent in
61  /// addition to the normal indention level.
62  bool IsContinuation = false;
63 
64  /// If this \c UnwrappedLine closes a block in a sequence of lines,
65  /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding
66  /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be
67  /// \c kInvalidIndex.
69 
70  /// If this \c UnwrappedLine opens a block, stores the index of the
71  /// line with the corresponding closing brace.
73 
74  static const size_t kInvalidIndex = -1;
75 
76  unsigned FirstStartColumn = 0;
77 };
78 
80 public:
82  virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
83  virtual void finishRun() = 0;
84 };
85 
86 class FormatTokenSource;
87 
89 public:
90  UnwrappedLineParser(const FormatStyle &Style,
91  const AdditionalKeywords &Keywords,
92  unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens,
93  UnwrappedLineConsumer &Callback);
94 
95  void parse();
96 
97 private:
98  enum class IfStmtKind {
99  NotIf, // Not an if statement.
100  IfOnly, // An if statement without the else clause.
101  IfElse, // An if statement followed by else but not else if.
102  IfElseIf // An if statement followed by else if.
103  };
104 
105  void reset();
106  void parseFile();
107  bool precededByCommentOrPPDirective() const;
108  bool parseLevel(const FormatToken *OpeningBrace = nullptr,
109  bool CanContainBracedList = true,
110  TokenType NextLBracesType = TT_Unknown,
111  IfStmtKind *IfKind = nullptr,
112  FormatToken **IfLeftBrace = nullptr);
113  bool mightFitOnOneLine(UnwrappedLine &Line,
114  const FormatToken *OpeningBrace = nullptr) const;
115  FormatToken *parseBlock(bool MustBeDeclaration = false,
116  unsigned AddLevels = 1u, bool MunchSemi = true,
117  bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
118  bool UnindentWhitesmithsBraces = false,
119  bool CanContainBracedList = true,
120  TokenType NextLBracesType = TT_Unknown);
121  void parseChildBlock(bool CanContainBracedList = true,
122  TokenType NextLBracesType = TT_Unknown);
123  void parsePPDirective();
124  void parsePPDefine();
125  void parsePPIf(bool IfDef);
126  void parsePPElse();
127  void parsePPEndIf();
128  void parsePPPragma();
129  void parsePPUnknown();
130  void readTokenWithJavaScriptASI();
131  void parseStructuralElement(bool IsTopLevel = false,
132  TokenType NextLBracesType = TT_Unknown,
133  IfStmtKind *IfKind = nullptr,
134  FormatToken **IfLeftBrace = nullptr,
135  bool *HasDoWhile = nullptr,
136  bool *HasLabel = nullptr);
137  bool tryToParseBracedList();
138  bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
139  tok::TokenKind ClosingBraceKind = tok::r_brace);
140  void parseParens(TokenType AmpAmpTokenType = TT_Unknown);
141  void parseSquare(bool LambdaIntroducer = false);
142  void keepAncestorBraces();
143  void parseUnbracedBody(bool CheckEOF = false);
144  void handleAttributes();
145  bool handleCppAttributes();
146  FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
147  void parseTryCatch();
148  void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
149  void parseForOrWhileLoop();
150  void parseDoWhile();
151  void parseLabel(bool LeftAlignLabel = false);
152  void parseCaseLabel();
153  void parseSwitch();
154  void parseNamespace();
155  void parseModuleImport();
156  void parseNew();
157  void parseAccessSpecifier();
158  bool parseEnum();
159  bool parseStructLike();
160  void parseConcept();
161  bool parseRequires();
162  void parseRequiresClause(FormatToken *RequiresToken);
163  void parseRequiresExpression(FormatToken *RequiresToken);
164  void parseConstraintExpression();
165  void parseJavaEnumBody();
166  // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
167  // parses the record as a child block, i.e. if the class declaration is an
168  // expression.
169  void parseRecord(bool ParseAsExpr = false);
170  void parseObjCLightweightGenerics();
171  void parseObjCMethod();
172  void parseObjCProtocolList();
173  void parseObjCUntilAtEnd();
174  void parseObjCInterfaceOrImplementation();
175  bool parseObjCProtocol();
176  void parseJavaScriptEs6ImportExport();
177  void parseStatementMacro();
178  void parseCSharpAttribute();
179  // Parse a C# generic type constraint: `where T : IComparable<T>`.
180  // See:
181  // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
182  void parseCSharpGenericTypeConstraint();
183  bool tryToParseLambda();
184  bool tryToParseChildBlock();
185  bool tryToParseLambdaIntroducer();
186  bool tryToParsePropertyAccessor();
187  void tryToParseJSFunction();
188  bool tryToParseSimpleAttribute();
189  void parseVerilogHierarchyIdentifier();
190  void parseVerilogSensitivityList();
191  // Returns the number of levels of indentation in addition to the normal 1
192  // level for a block, used for indenting case labels.
193  unsigned parseVerilogHierarchyHeader();
194  void parseVerilogTable();
195  void parseVerilogCaseLabel();
196 
197  // Used by addUnwrappedLine to denote whether to keep or remove a level
198  // when resetting the line state.
199  enum class LineLevel { Remove, Keep };
200 
201  void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
202  bool eof() const;
203  // LevelDifference is the difference of levels after and before the current
204  // token. For example:
205  // - if the token is '{' and opens a block, LevelDifference is 1.
206  // - if the token is '}' and closes a block, LevelDifference is -1.
207  void nextToken(int LevelDifference = 0);
208  void readToken(int LevelDifference = 0);
209 
210  // Decides which comment tokens should be added to the current line and which
211  // should be added as comments before the next token.
212  //
213  // Comments specifies the sequence of comment tokens to analyze. They get
214  // either pushed to the current line or added to the comments before the next
215  // token.
216  //
217  // NextTok specifies the next token. A null pointer NextTok is supported, and
218  // signifies either the absence of a next token, or that the next token
219  // shouldn't be taken into account for the analysis.
220  void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
221  const FormatToken *NextTok);
222 
223  // Adds the comment preceding the next token to unwrapped lines.
224  void flushComments(bool NewlineBeforeNext);
225  void pushToken(FormatToken *Tok);
226  void calculateBraceTypes(bool ExpectClassBody = false);
227 
228  // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
229  // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
230  // this branch either cannot be taken (for example '#if false'), or should
231  // not be taken in this round.
232  void conditionalCompilationCondition(bool Unreachable);
233  void conditionalCompilationStart(bool Unreachable);
234  void conditionalCompilationAlternative();
235  void conditionalCompilationEnd();
236 
237  bool isOnNewLine(const FormatToken &FormatTok);
238 
239  // Compute hash of the current preprocessor branch.
240  // This is used to identify the different branches, and thus track if block
241  // open and close in the same branch.
242  size_t computePPHash() const;
243 
244  // FIXME: We are constantly running into bugs where Line.Level is incorrectly
245  // subtracted from beyond 0. Introduce a method to subtract from Line.Level
246  // and use that everywhere in the Parser.
247  std::unique_ptr<UnwrappedLine> Line;
248 
249  // Comments are sorted into unwrapped lines by whether they are in the same
250  // line as the previous token, or not. If not, they belong to the next token.
251  // Since the next token might already be in a new unwrapped line, we need to
252  // store the comments belonging to that token.
253  SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
254  FormatToken *FormatTok;
255  bool MustBreakBeforeNextToken;
256 
257  // The parsed lines. Only added to through \c CurrentLines.
259 
260  // Preprocessor directives are parsed out-of-order from other unwrapped lines.
261  // Thus, we need to keep a list of preprocessor directives to be reported
262  // after an unwrapped line that has been started was finished.
263  SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
264 
265  // New unwrapped lines are added via CurrentLines.
266  // Usually points to \c &Lines. While parsing a preprocessor directive when
267  // there is an unfinished previous unwrapped line, will point to
268  // \c &PreprocessorDirectives.
269  SmallVectorImpl<UnwrappedLine> *CurrentLines;
270 
271  // We store for each line whether it must be a declaration depending on
272  // whether we are in a compound statement or not.
273  llvm::BitVector DeclarationScopeStack;
274 
275  const FormatStyle &Style;
276  const AdditionalKeywords &Keywords;
277 
278  llvm::Regex CommentPragmasRegex;
279 
280  FormatTokenSource *Tokens;
281  UnwrappedLineConsumer &Callback;
282 
283  // FIXME: This is a temporary measure until we have reworked the ownership
284  // of the format tokens. The goal is to have the actual tokens created and
285  // owned outside of and handed into the UnwrappedLineParser.
286  ArrayRef<FormatToken *> AllTokens;
287 
288  // Keeps a stack of the states of nested control statements (true if the
289  // statement contains more than some predefined number of nested statements).
290  SmallVector<bool, 8> NestedTooDeep;
291 
292  // Represents preprocessor branch type, so we can find matching
293  // #if/#else/#endif directives.
294  enum PPBranchKind {
295  PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
296  PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
297  };
298 
299  struct PPBranch {
300  PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
301  PPBranchKind Kind;
302  size_t Line;
303  };
304 
305  // Keeps a stack of currently active preprocessor branching directives.
307 
308  // The \c UnwrappedLineParser re-parses the code for each combination
309  // of preprocessor branches that can be taken.
310  // To that end, we take the same branch (#if, #else, or one of the #elif
311  // branches) for each nesting level of preprocessor branches.
312  // \c PPBranchLevel stores the current nesting level of preprocessor
313  // branches during one pass over the code.
314  int PPBranchLevel;
315 
316  // Contains the current branch (#if, #else or one of the #elif branches)
317  // for each nesting level.
318  SmallVector<int, 8> PPLevelBranchIndex;
319 
320  // Contains the maximum number of branches at each nesting level.
321  SmallVector<int, 8> PPLevelBranchCount;
322 
323  // Contains the number of branches per nesting level we are currently
324  // in while parsing a preprocessor branch sequence.
325  // This is used to update PPLevelBranchCount at the end of a branch
326  // sequence.
327  std::stack<int> PPChainBranchIndex;
328 
329  // Include guard search state. Used to fixup preprocessor indent levels
330  // so that include guards do not participate in indentation.
331  enum IncludeGuardState {
332  IG_Inited, // Search started, looking for #ifndef.
333  IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
334  IG_Defined, // Matching #define found, checking other requirements.
335  IG_Found, // All requirements met, need to fix indents.
336  IG_Rejected, // Search failed or never started.
337  };
338 
339  // Current state of include guard search.
340  IncludeGuardState IncludeGuard;
341 
342  // Points to the #ifndef condition for a potential include guard. Null unless
343  // IncludeGuardState == IG_IfNdefed.
344  FormatToken *IncludeGuardToken;
345 
346  // Contains the first start column where the source begins. This is zero for
347  // normal source code and may be nonzero when formatting a code fragment that
348  // does not start at the beginning of the file.
349  unsigned FirstStartColumn;
350 
351  friend class ScopedLineState;
353 };
354 
356  UnwrappedLineNode() : Tok(nullptr) {}
358 
361 };
362 
364  : Level(0), PPLevel(0), InPPDirective(false), InPragmaDirective(false),
365  InMacroBody(false), MustBeDeclaration(false),
366  MatchingOpeningBlockLineIndex(kInvalidIndex) {}
367 
368 } // end namespace format
369 } // end namespace clang
370 
371 #endif
clang::format::CompoundStatementIndenter
Definition: UnwrappedLineParser.cpp:242
clang::format::ScopedLineState
Definition: UnwrappedLineParser.cpp:208
clang::format::UnwrappedLineNode::Children
SmallVector< UnwrappedLine, 0 > Children
Definition: UnwrappedLineParser.h:360
clang::LambdaIntroducer
Represents a complete lambda introducer.
Definition: DeclSpec.h:2739
llvm::SmallVector
Definition: LLVM.h:38
clang::format::UnwrappedLineParser::parse
void parse()
Definition: UnwrappedLineParser.cpp:362
clang::format::UnwrappedLineConsumer::~UnwrappedLineConsumer
virtual ~UnwrappedLineConsumer()
Definition: UnwrappedLineParser.h:81
clang::format::UnwrappedLine::kInvalidIndex
static const size_t kInvalidIndex
Definition: UnwrappedLineParser.h:74
clang::format::FormatStyle
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:54
clang::format::FormatToken
A wrapper around a Token storing information about the whitespace characters preceding it.
Definition: FormatToken.h:240
clang::format::AdditionalKeywords
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang's l...
Definition: FormatToken.h:917
clang::format::UnwrappedLine
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...
Definition: UnwrappedLineParser.h:38
Format.h
clang::format::UnwrappedLineParser
Definition: UnwrappedLineParser.h:88
clang::format::UnwrappedLineConsumer
Definition: UnwrappedLineParser.h:79
clang::format::UnwrappedLine::InPPDirective
bool InPPDirective
Whether this UnwrappedLine is part of a preprocessor directive.
Definition: UnwrappedLineParser.h:52
clang::format::UnwrappedLineNode::Tok
FormatToken * Tok
Definition: UnwrappedLineParser.h:359
IdentifierTable.h
clang::format::UnwrappedLine::IsContinuation
bool IsContinuation
True if this line should be indented by ContinuationIndent in addition to the normal indention level.
Definition: UnwrappedLineParser.h:62
Line
const AnnotatedLine * Line
Definition: UsingDeclarationsSorter.cpp:68
clang::format::UnwrappedLine::MustBeDeclaration
bool MustBeDeclaration
Definition: UnwrappedLineParser.h:58
clang::format::UnwrappedLine::MatchingClosingBlockLineIndex
size_t MatchingClosingBlockLineIndex
If this UnwrappedLine opens a block, stores the index of the line with the corresponding closing brac...
Definition: UnwrappedLineParser.h:72
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
false
#define false
Definition: stdbool.h:22
clang::format::UnwrappedLineNode::UnwrappedLineNode
UnwrappedLineNode(FormatToken *Tok)
Definition: UnwrappedLineParser.h:357
llvm::ArrayRef
Definition: LLVM.h:34
clang::format::UnwrappedLine::UnwrappedLine
UnwrappedLine()
Definition: UnwrappedLineParser.h:363
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::format::UnwrappedLineConsumer::consumeUnwrappedLine
virtual void consumeUnwrappedLine(const UnwrappedLine &Line)=0
clang::format::UnwrappedLineNode
Definition: UnwrappedLineParser.h:355
clang
Definition: CalledOnceCheck.h:17
clang::format::UnwrappedLineConsumer::finishRun
virtual void finishRun()=0
clang::format::UnwrappedLine::InMacroBody
bool InMacroBody
Whether it is part of a macro body.
Definition: UnwrappedLineParser.h:56
clang::prec::Level
Level
Definition: OperatorPrecedence.h:26
clang::format::UnwrappedLine::PPLevel
unsigned PPLevel
The PPBranchLevel (adjusted for header guards) if this line is a InMacroBody line,...
Definition: UnwrappedLineParser.h:49
clang::format::UnwrappedLineNode::UnwrappedLineNode
UnwrappedLineNode()
Definition: UnwrappedLineParser.h:356
FormatToken.h
clang::format::UnwrappedLine::Level
unsigned Level
The indent level of the UnwrappedLine.
Definition: UnwrappedLineParser.h:45
llvm::SmallVectorImpl
Definition: Randstruct.h:18
clang::format::UnwrappedLine::MatchingOpeningBlockLineIndex
size_t MatchingOpeningBlockLineIndex
If this UnwrappedLine closes a block in a sequence of lines, MatchingOpeningBlockLineIndex stores the...
Definition: UnwrappedLineParser.h:68
clang::NeverCalledReason::IfElse
@ IfElse
clang::format::TokenType
TokenType
Determines the semantic type of a syntactic token, e.g.
Definition: FormatToken.h:155
clang::format::UnwrappedLine::InPragmaDirective
bool InPragmaDirective
Whether this UnwrappedLine is part of a pramga directive.
Definition: UnwrappedLineParser.h:54
clang::format::UnwrappedLine::Tokens
std::list< UnwrappedLineNode > Tokens
The Tokens comprising this UnwrappedLine.
Definition: UnwrappedLineParser.h:42
clang::format::UnwrappedLine::FirstStartColumn
unsigned FirstStartColumn
Definition: UnwrappedLineParser.h:76
clang::format::UnwrappedLineParser::UnwrappedLineParser
UnwrappedLineParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, unsigned FirstStartColumn, ArrayRef< FormatToken * > Tokens, UnwrappedLineConsumer &Callback)
Definition: UnwrappedLineParser.cpp:330
clang::format::FormatTokenSource
Definition: UnwrappedLineParser.cpp:31