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