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