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