1 //===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file contains the declaration of the UnwrappedLineParser,
12 /// which turns a stream of tokens into UnwrappedLines.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
17 #define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
18 
19 #include "FormatToken.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Format/Format.h"
22 #include "llvm/Support/Regex.h"
23 #include <list>
24 #include <stack>
25 
26 namespace clang {
27 namespace format {
28 
29 struct UnwrappedLineNode;
30 
31 /// \brief 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   // FIXME: Don't use std::list here.
41   /// \brief The \c Tokens comprising this \c UnwrappedLine.
42   std::list<UnwrappedLineNode> Tokens;
43 
44   /// \brief The indent level of the \c UnwrappedLine.
45   unsigned Level;
46 
47   /// \brief Whether this \c UnwrappedLine is part of a preprocessor directive.
48   bool InPPDirective;
49 
50   bool MustBeDeclaration;
51 
52   /// \brief If this \c UnwrappedLine closes a block in a sequence of lines,
53   /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding
54   /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be
55   /// \c kInvalidIndex.
56   size_t MatchingOpeningBlockLineIndex;
57 
58   static const size_t kInvalidIndex = -1;
59 };
60 
61 class UnwrappedLineConsumer {
62 public:
63   virtual ~UnwrappedLineConsumer() {}
64   virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
65   virtual void finishRun() = 0;
66 };
67 
68 class FormatTokenSource;
69 
70 class UnwrappedLineParser {
71 public:
72   UnwrappedLineParser(const FormatStyle &Style,
73                       const AdditionalKeywords &Keywords,
74                       ArrayRef<FormatToken *> Tokens,
75                       UnwrappedLineConsumer &Callback);
76 
77   void parse();
78 
79 private:
80   void reset();
81   void parseFile();
82   void parseLevel(bool HasOpeningBrace);
83   void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
84                   bool MunchSemi = true);
85   void parseChildBlock();
86   void parsePPDirective();
87   void parsePPDefine();
88   void parsePPIf(bool IfDef);
89   void parsePPElIf();
90   void parsePPElse();
91   void parsePPEndIf();
92   void parsePPUnknown();
93   void readTokenWithJavaScriptASI();
94   void parseStructuralElement();
95   bool tryToParseBracedList();
96   bool parseBracedList(bool ContinueOnSemicolons = false,
97                        tok::TokenKind ClosingBraceKind = tok::r_brace);
98   void parseParens();
99   void parseSquare(bool LambdaIntroducer = false);
100   void parseIfThenElse();
101   void parseTryCatch();
102   void parseForOrWhileLoop();
103   void parseDoWhile();
104   void parseLabel();
105   void parseCaseLabel();
106   void parseSwitch();
107   void parseNamespace();
108   void parseNew();
109   void parseAccessSpecifier();
110   bool parseEnum();
111   void parseJavaEnumBody();
112   // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
113   // parses the record as a child block, i.e. if the class declaration is an
114   // expression.
115   void parseRecord(bool ParseAsExpr = false);
116   void parseObjCProtocolList();
117   void parseObjCUntilAtEnd();
118   void parseObjCInterfaceOrImplementation();
119   void parseObjCProtocol();
120   void parseJavaScriptEs6ImportExport();
121   bool tryToParseLambda();
122   bool tryToParseLambdaIntroducer();
123   void tryToParseJSFunction();
124   void addUnwrappedLine();
125   bool eof() const;
126   // LevelDifference is the difference of levels after and before the current
127   // token. For example:
128   // - if the token is '{' and opens a block, LevelDifference is 1.
129   // - if the token is '}' and closes a block, LevelDifference is -1.
130   void nextToken(int LevelDifference = 0);
131   void readToken(int LevelDifference = 0);
132 
133   // Decides which comment tokens should be added to the current line and which
134   // should be added as comments before the next token.
135   //
136   // Comments specifies the sequence of comment tokens to analyze. They get
137   // either pushed to the current line or added to the comments before the next
138   // token.
139   //
140   // NextTok specifies the next token. A null pointer NextTok is supported, and
141   // signifies either the absense of a next token, or that the next token
142   // shouldn't be taken into accunt for the analysis.
143   void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
144                           const FormatToken *NextTok);
145 
146   // Adds the comment preceding the next token to unwrapped lines.
147   void flushComments(bool NewlineBeforeNext);
148   void pushToken(FormatToken *Tok);
149   void calculateBraceTypes(bool ExpectClassBody = false);
150 
151   // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
152   // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
153   // this branch either cannot be taken (for example '#if false'), or should
154   // not be taken in this round.
155   void conditionalCompilationCondition(bool Unreachable);
156   void conditionalCompilationStart(bool Unreachable);
157   void conditionalCompilationAlternative();
158   void conditionalCompilationEnd();
159 
160   bool isOnNewLine(const FormatToken &FormatTok);
161 
162   // Compute hash of the current preprocessor branch.
163   // This is used to identify the different branches, and thus track if block
164   // open and close in the same branch.
165   size_t computePPHash() const;
166 
167   // FIXME: We are constantly running into bugs where Line.Level is incorrectly
168   // subtracted from beyond 0. Introduce a method to subtract from Line.Level
169   // and use that everywhere in the Parser.
170   std::unique_ptr<UnwrappedLine> Line;
171 
172   // Comments are sorted into unwrapped lines by whether they are in the same
173   // line as the previous token, or not. If not, they belong to the next token.
174   // Since the next token might already be in a new unwrapped line, we need to
175   // store the comments belonging to that token.
176   SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
177   FormatToken *FormatTok;
178   bool MustBreakBeforeNextToken;
179 
180   // The parsed lines. Only added to through \c CurrentLines.
181   SmallVector<UnwrappedLine, 8> Lines;
182 
183   // Preprocessor directives are parsed out-of-order from other unwrapped lines.
184   // Thus, we need to keep a list of preprocessor directives to be reported
185   // after an unwrapped line that has been started was finished.
186   SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
187 
188   // New unwrapped lines are added via CurrentLines.
189   // Usually points to \c &Lines. While parsing a preprocessor directive when
190   // there is an unfinished previous unwrapped line, will point to
191   // \c &PreprocessorDirectives.
192   SmallVectorImpl<UnwrappedLine> *CurrentLines;
193 
194   // We store for each line whether it must be a declaration depending on
195   // whether we are in a compound statement or not.
196   std::vector<bool> DeclarationScopeStack;
197 
198   const FormatStyle &Style;
199   const AdditionalKeywords &Keywords;
200 
201   llvm::Regex CommentPragmasRegex;
202 
203   FormatTokenSource *Tokens;
204   UnwrappedLineConsumer &Callback;
205 
206   // FIXME: This is a temporary measure until we have reworked the ownership
207   // of the format tokens. The goal is to have the actual tokens created and
208   // owned outside of and handed into the UnwrappedLineParser.
209   ArrayRef<FormatToken *> AllTokens;
210 
211   // Represents preprocessor branch type, so we can find matching
212   // #if/#else/#endif directives.
213   enum PPBranchKind {
214     PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
215     PP_Unreachable  // #if 0 or a conditional preprocessor block inside #if 0
216   };
217 
218   struct PPBranch {
219     PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
220     PPBranchKind Kind;
221     size_t Line;
222   };
223 
224   // Keeps a stack of currently active preprocessor branching directives.
225   SmallVector<PPBranch, 16> PPStack;
226 
227   // The \c UnwrappedLineParser re-parses the code for each combination
228   // of preprocessor branches that can be taken.
229   // To that end, we take the same branch (#if, #else, or one of the #elif
230   // branches) for each nesting level of preprocessor branches.
231   // \c PPBranchLevel stores the current nesting level of preprocessor
232   // branches during one pass over the code.
233   int PPBranchLevel;
234 
235   // Contains the current branch (#if, #else or one of the #elif branches)
236   // for each nesting level.
237   SmallVector<int, 8> PPLevelBranchIndex;
238 
239   // Contains the maximum number of branches at each nesting level.
240   SmallVector<int, 8> PPLevelBranchCount;
241 
242   // Contains the number of branches per nesting level we are currently
243   // in while parsing a preprocessor branch sequence.
244   // This is used to update PPLevelBranchCount at the end of a branch
245   // sequence.
246   std::stack<int> PPChainBranchIndex;
247 
248   // Contains the #ifndef condition for a potential include guard.
249   FormatToken *IfNdefCondition;
250   bool FoundIncludeGuardStart;
251   bool IncludeGuardRejected;
252 
253   friend class ScopedLineState;
254   friend class CompoundStatementIndenter;
255 };
256 
257 struct UnwrappedLineNode {
258   UnwrappedLineNode() : Tok(nullptr) {}
259   UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {}
260 
261   FormatToken *Tok;
262   SmallVector<UnwrappedLine, 0> Children;
263 };
264 
265 inline UnwrappedLine::UnwrappedLine()
266     : Level(0), InPPDirective(false), MustBeDeclaration(false),
267       MatchingOpeningBlockLineIndex(kInvalidIndex) {}
268 
269 } // end namespace format
270 } // end namespace clang
271 
272 #endif
273