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