xref: /freebsd/contrib/llvm-project/clang/lib/Format/UnwrappedLineParser.h (revision 02e9120893770924227138ba49df1edb3896112a)
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 "Encoding.h"
19 #include "FormatToken.h"
20 #include "Macros.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"
27 #include <list>
28 #include <stack>
29 #include <vector>
30 
31 namespace clang {
32 namespace format {
33 
34 struct UnwrappedLineNode;
35 
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.
38 ///
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();
44 
45   /// The \c Tokens comprising this \c UnwrappedLine.
46   std::list<UnwrappedLineNode> Tokens;
47 
48   /// The indent level of the \c UnwrappedLine.
49   unsigned Level;
50 
51   /// The \c PPBranchLevel (adjusted for header guards) if this line is a
52   /// \c InMacroBody line, and 0 otherwise.
53   unsigned PPLevel;
54 
55   /// Whether this \c UnwrappedLine is part of a preprocessor directive.
56   bool InPPDirective;
57   /// Whether this \c UnwrappedLine is part of a pramga directive.
58   bool InPragmaDirective;
59   /// Whether it is part of a macro body.
60   bool InMacroBody;
61 
62   bool MustBeDeclaration;
63 
64   /// Whether the parser has seen \c decltype(auto) in this line.
65   bool SeenDecltypeAuto = false;
66 
67   /// \c True if this line should be indented by ContinuationIndent in
68   /// addition to the normal indention level.
69   bool IsContinuation = false;
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.
75   size_t MatchingOpeningBlockLineIndex = kInvalidIndex;
76 
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;
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.
99 class UnwrappedLineConsumer {
100 public:
101   virtual ~UnwrappedLineConsumer() {}
102   virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
103   virtual void finishRun() = 0;
104 };
105 
106 class FormatTokenSource;
107 
108 class UnwrappedLineParser {
109 public:
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 
119 private:
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                   bool CanContainBracedList = true,
132                   TokenType NextLBracesType = TT_Unknown,
133                   IfStmtKind *IfKind = nullptr,
134                   FormatToken **IfLeftBrace = nullptr);
135   bool mightFitOnOneLine(UnwrappedLine &Line,
136                          const FormatToken *OpeningBrace = nullptr) const;
137   FormatToken *parseBlock(bool MustBeDeclaration = false,
138                           unsigned AddLevels = 1u, bool MunchSemi = true,
139                           bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
140                           bool UnindentWhitesmithsBraces = false,
141                           bool CanContainBracedList = true,
142                           TokenType NextLBracesType = TT_Unknown);
143   void parseChildBlock(bool CanContainBracedList = true,
144                        TokenType NextLBracesType = TT_Unknown);
145   void parsePPDirective();
146   void parsePPDefine();
147   void parsePPIf(bool IfDef);
148   void parsePPElse();
149   void parsePPEndIf();
150   void parsePPPragma();
151   void parsePPUnknown();
152   void readTokenWithJavaScriptASI();
153   void parseStructuralElement(bool IsTopLevel = false,
154                               TokenType NextLBracesType = TT_Unknown,
155                               IfStmtKind *IfKind = nullptr,
156                               FormatToken **IfLeftBrace = nullptr,
157                               bool *HasDoWhile = nullptr,
158                               bool *HasLabel = nullptr);
159   bool tryToParseBracedList();
160   bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
161                        tok::TokenKind ClosingBraceKind = tok::r_brace);
162   bool parseParens(TokenType AmpAmpTokenType = TT_Unknown);
163   void parseSquare(bool LambdaIntroducer = false);
164   void keepAncestorBraces();
165   void parseUnbracedBody(bool CheckEOF = false);
166   void handleAttributes();
167   bool handleCppAttributes();
168   bool isBlockBegin(const FormatToken &Tok) const;
169   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false,
170                                bool IsVerilogAssert = false);
171   void parseTryCatch();
172   void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
173   void parseForOrWhileLoop(bool HasParens = true);
174   void parseDoWhile();
175   void parseLabel(bool LeftAlignLabel = false);
176   void parseCaseLabel();
177   void parseSwitch();
178   void parseNamespace();
179   bool parseModuleImport();
180   void parseNew();
181   void parseAccessSpecifier();
182   bool parseEnum();
183   bool parseStructLike();
184   bool parseRequires();
185   void parseRequiresClause(FormatToken *RequiresToken);
186   void parseRequiresExpression(FormatToken *RequiresToken);
187   void parseConstraintExpression();
188   void parseJavaEnumBody();
189   // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
190   // parses the record as a child block, i.e. if the class declaration is an
191   // expression.
192   void parseRecord(bool ParseAsExpr = false);
193   void parseObjCLightweightGenerics();
194   void parseObjCMethod();
195   void parseObjCProtocolList();
196   void parseObjCUntilAtEnd();
197   void parseObjCInterfaceOrImplementation();
198   bool parseObjCProtocol();
199   void parseJavaScriptEs6ImportExport();
200   void parseStatementMacro();
201   void parseCSharpAttribute();
202   // Parse a C# generic type constraint: `where T : IComparable<T>`.
203   // See:
204   // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
205   void parseCSharpGenericTypeConstraint();
206   bool tryToParseLambda();
207   bool tryToParseChildBlock();
208   bool tryToParseLambdaIntroducer();
209   bool tryToParsePropertyAccessor();
210   void tryToParseJSFunction();
211   bool tryToParseSimpleAttribute();
212   void parseVerilogHierarchyIdentifier();
213   void parseVerilogSensitivityList();
214   // Returns the number of levels of indentation in addition to the normal 1
215   // level for a block, used for indenting case labels.
216   unsigned parseVerilogHierarchyHeader();
217   void parseVerilogTable();
218   void parseVerilogCaseLabel();
219   std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
220   parseMacroCall();
221 
222   // Used by addUnwrappedLine to denote whether to keep or remove a level
223   // when resetting the line state.
224   enum class LineLevel { Remove, Keep };
225 
226   void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
227   bool eof() const;
228   // LevelDifference is the difference of levels after and before the current
229   // token. For example:
230   // - if the token is '{' and opens a block, LevelDifference is 1.
231   // - if the token is '}' and closes a block, LevelDifference is -1.
232   void nextToken(int LevelDifference = 0);
233   void readToken(int LevelDifference = 0);
234 
235   // Decides which comment tokens should be added to the current line and which
236   // should be added as comments before the next token.
237   //
238   // Comments specifies the sequence of comment tokens to analyze. They get
239   // either pushed to the current line or added to the comments before the next
240   // token.
241   //
242   // NextTok specifies the next token. A null pointer NextTok is supported, and
243   // signifies either the absence of a next token, or that the next token
244   // shouldn't be taken into account for the analysis.
245   void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
246                           const FormatToken *NextTok);
247 
248   // Adds the comment preceding the next token to unwrapped lines.
249   void flushComments(bool NewlineBeforeNext);
250   void pushToken(FormatToken *Tok);
251   void calculateBraceTypes(bool ExpectClassBody = false);
252 
253   // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
254   // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
255   // this branch either cannot be taken (for example '#if false'), or should
256   // not be taken in this round.
257   void conditionalCompilationCondition(bool Unreachable);
258   void conditionalCompilationStart(bool Unreachable);
259   void conditionalCompilationAlternative();
260   void conditionalCompilationEnd();
261 
262   bool isOnNewLine(const FormatToken &FormatTok);
263 
264   // Returns whether there is a macro expansion in the line, i.e. a token that
265   // was expanded from a macro call.
266   bool containsExpansion(const UnwrappedLine &Line) const;
267 
268   // Compute hash of the current preprocessor branch.
269   // This is used to identify the different branches, and thus track if block
270   // open and close in the same branch.
271   size_t computePPHash() const;
272 
273   bool parsingPPDirective() const { return CurrentLines != &Lines; }
274 
275   // FIXME: We are constantly running into bugs where Line.Level is incorrectly
276   // subtracted from beyond 0. Introduce a method to subtract from Line.Level
277   // and use that everywhere in the Parser.
278   std::unique_ptr<UnwrappedLine> Line;
279 
280   // Lines that are created by macro expansion.
281   // When formatting code containing macro calls, we first format the expanded
282   // lines to set the token types correctly. Afterwards, we format the
283   // reconstructed macro calls, re-using the token types determined in the first
284   // step.
285   // ExpandedLines will be reset every time we create a new LineAndExpansion
286   // instance once a line containing macro calls has been parsed.
287   SmallVector<UnwrappedLine, 8> CurrentExpandedLines;
288 
289   // Maps from the first token of a top-level UnwrappedLine that contains
290   // a macro call to the replacement UnwrappedLines expanded from the macro
291   // call.
292   llvm::DenseMap<FormatToken *, SmallVector<UnwrappedLine, 8>> ExpandedLines;
293 
294   // Map from the macro identifier to a line containing the full unexpanded
295   // macro call.
296   llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>> Unexpanded;
297 
298   // For recursive macro expansions, trigger reconstruction only on the
299   // outermost expansion.
300   bool InExpansion = false;
301 
302   // Set while we reconstruct a macro call.
303   // For reconstruction, we feed the expanded lines into the reconstructor
304   // until it is finished.
305   std::optional<MacroCallReconstructor> Reconstruct;
306 
307   // Comments are sorted into unwrapped lines by whether they are in the same
308   // line as the previous token, or not. If not, they belong to the next token.
309   // Since the next token might already be in a new unwrapped line, we need to
310   // store the comments belonging to that token.
311   SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
312   FormatToken *FormatTok = nullptr;
313   bool MustBreakBeforeNextToken;
314 
315   // The parsed lines. Only added to through \c CurrentLines.
316   SmallVector<UnwrappedLine, 8> Lines;
317 
318   // Preprocessor directives are parsed out-of-order from other unwrapped lines.
319   // Thus, we need to keep a list of preprocessor directives to be reported
320   // after an unwrapped line that has been started was finished.
321   SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
322 
323   // New unwrapped lines are added via CurrentLines.
324   // Usually points to \c &Lines. While parsing a preprocessor directive when
325   // there is an unfinished previous unwrapped line, will point to
326   // \c &PreprocessorDirectives.
327   SmallVectorImpl<UnwrappedLine> *CurrentLines;
328 
329   // We store for each line whether it must be a declaration depending on
330   // whether we are in a compound statement or not.
331   llvm::BitVector DeclarationScopeStack;
332 
333   const FormatStyle &Style;
334   const AdditionalKeywords &Keywords;
335 
336   llvm::Regex CommentPragmasRegex;
337 
338   FormatTokenSource *Tokens;
339   UnwrappedLineConsumer &Callback;
340 
341   ArrayRef<FormatToken *> AllTokens;
342 
343   // Keeps a stack of the states of nested control statements (true if the
344   // statement contains more than some predefined number of nested statements).
345   SmallVector<bool, 8> NestedTooDeep;
346 
347   // Keeps a stack of the states of nested lambdas (true if the return type of
348   // the lambda is `decltype(auto)`).
349   SmallVector<bool, 4> NestedLambdas;
350 
351   // Whether the parser is parsing the body of a function whose return type is
352   // `decltype(auto)`.
353   bool IsDecltypeAutoFunction = false;
354 
355   // Represents preprocessor branch type, so we can find matching
356   // #if/#else/#endif directives.
357   enum PPBranchKind {
358     PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
359     PP_Unreachable  // #if 0 or a conditional preprocessor block inside #if 0
360   };
361 
362   struct PPBranch {
363     PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
364     PPBranchKind Kind;
365     size_t Line;
366   };
367 
368   // Keeps a stack of currently active preprocessor branching directives.
369   SmallVector<PPBranch, 16> PPStack;
370 
371   // The \c UnwrappedLineParser re-parses the code for each combination
372   // of preprocessor branches that can be taken.
373   // To that end, we take the same branch (#if, #else, or one of the #elif
374   // branches) for each nesting level of preprocessor branches.
375   // \c PPBranchLevel stores the current nesting level of preprocessor
376   // branches during one pass over the code.
377   int PPBranchLevel;
378 
379   // Contains the current branch (#if, #else or one of the #elif branches)
380   // for each nesting level.
381   SmallVector<int, 8> PPLevelBranchIndex;
382 
383   // Contains the maximum number of branches at each nesting level.
384   SmallVector<int, 8> PPLevelBranchCount;
385 
386   // Contains the number of branches per nesting level we are currently
387   // in while parsing a preprocessor branch sequence.
388   // This is used to update PPLevelBranchCount at the end of a branch
389   // sequence.
390   std::stack<int> PPChainBranchIndex;
391 
392   // Include guard search state. Used to fixup preprocessor indent levels
393   // so that include guards do not participate in indentation.
394   enum IncludeGuardState {
395     IG_Inited,   // Search started, looking for #ifndef.
396     IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
397     IG_Defined,  // Matching #define found, checking other requirements.
398     IG_Found,    // All requirements met, need to fix indents.
399     IG_Rejected, // Search failed or never started.
400   };
401 
402   // Current state of include guard search.
403   IncludeGuardState IncludeGuard;
404 
405   // Points to the #ifndef condition for a potential include guard. Null unless
406   // IncludeGuardState == IG_IfNdefed.
407   FormatToken *IncludeGuardToken;
408 
409   // Contains the first start column where the source begins. This is zero for
410   // normal source code and may be nonzero when formatting a code fragment that
411   // does not start at the beginning of the file.
412   unsigned FirstStartColumn;
413 
414   MacroExpander Macros;
415 
416   friend class ScopedLineState;
417   friend class CompoundStatementIndenter;
418 };
419 
420 struct UnwrappedLineNode {
421   UnwrappedLineNode() : Tok(nullptr) {}
422   UnwrappedLineNode(FormatToken *Tok,
423                     llvm::ArrayRef<UnwrappedLine> Children = {})
424       : Tok(Tok), Children(Children.begin(), Children.end()) {}
425 
426   FormatToken *Tok;
427   SmallVector<UnwrappedLine, 0> Children;
428 };
429 
430 inline UnwrappedLine::UnwrappedLine()
431     : Level(0), PPLevel(0), InPPDirective(false), InPragmaDirective(false),
432       InMacroBody(false), MustBeDeclaration(false),
433       MatchingOpeningBlockLineIndex(kInvalidIndex) {}
434 
435 } // end namespace format
436 } // end namespace clang
437 
438 #endif
439