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