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