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