clang  7.0.0svn
UnwrappedLineParser.h
Go to the documentation of this file.
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 /// 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"
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 /// 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  /// The \c Tokens comprising this \c UnwrappedLine.
42  std::list<UnwrappedLineNode> Tokens;
43 
44  /// The indent level of the \c UnwrappedLine.
45  unsigned Level;
46 
47  /// Whether this \c UnwrappedLine is part of a preprocessor directive.
49 
51 
52  /// 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.
57 
58  /// If this \c UnwrappedLine opens a block, stores the index of the
59  /// line with the corresponding closing brace.
61 
62  static const size_t kInvalidIndex = -1;
63 
64  unsigned FirstStartColumn = 0;
65 };
66 
68 public:
70  virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
71  virtual void finishRun() = 0;
72 };
73 
74 class FormatTokenSource;
75 
77 public:
79  const AdditionalKeywords &Keywords,
80  unsigned FirstStartColumn,
82  UnwrappedLineConsumer &Callback);
83 
84  void parse();
85 
86 private:
87  void reset();
88  void parseFile();
89  void parseLevel(bool HasOpeningBrace);
90  void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
91  bool MunchSemi = true);
92  void parseChildBlock();
93  void parsePPDirective();
94  void parsePPDefine();
95  void parsePPIf(bool IfDef);
96  void parsePPElIf();
97  void parsePPElse();
98  void parsePPEndIf();
99  void parsePPUnknown();
100  void readTokenWithJavaScriptASI();
101  void parseStructuralElement();
102  bool tryToParseBracedList();
103  bool parseBracedList(bool ContinueOnSemicolons = false,
104  tok::TokenKind ClosingBraceKind = tok::r_brace);
105  void parseParens();
106  void parseSquare(bool LambdaIntroducer = false);
107  void parseIfThenElse();
108  void parseTryCatch();
109  void parseForOrWhileLoop();
110  void parseDoWhile();
111  void parseLabel();
112  void parseCaseLabel();
113  void parseSwitch();
114  void parseNamespace();
115  void parseNew();
116  void parseAccessSpecifier();
117  bool parseEnum();
118  void parseJavaEnumBody();
119  // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
120  // parses the record as a child block, i.e. if the class declaration is an
121  // expression.
122  void parseRecord(bool ParseAsExpr = false);
123  void parseObjCMethod();
124  void parseObjCProtocolList();
125  void parseObjCUntilAtEnd();
126  void parseObjCInterfaceOrImplementation();
127  bool parseObjCProtocol();
128  void parseJavaScriptEs6ImportExport();
129  bool tryToParseLambda();
130  bool tryToParseLambdaIntroducer();
131  void tryToParseJSFunction();
132  void addUnwrappedLine();
133  bool eof() const;
134  // LevelDifference is the difference of levels after and before the current
135  // token. For example:
136  // - if the token is '{' and opens a block, LevelDifference is 1.
137  // - if the token is '}' and closes a block, LevelDifference is -1.
138  void nextToken(int LevelDifference = 0);
139  void readToken(int LevelDifference = 0);
140 
141  // Decides which comment tokens should be added to the current line and which
142  // should be added as comments before the next token.
143  //
144  // Comments specifies the sequence of comment tokens to analyze. They get
145  // either pushed to the current line or added to the comments before the next
146  // token.
147  //
148  // NextTok specifies the next token. A null pointer NextTok is supported, and
149  // signifies either the absence of a next token, or that the next token
150  // shouldn't be taken into accunt for the analysis.
151  void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
152  const FormatToken *NextTok);
153 
154  // Adds the comment preceding the next token to unwrapped lines.
155  void flushComments(bool NewlineBeforeNext);
156  void pushToken(FormatToken *Tok);
157  void calculateBraceTypes(bool ExpectClassBody = false);
158 
159  // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
160  // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
161  // this branch either cannot be taken (for example '#if false'), or should
162  // not be taken in this round.
163  void conditionalCompilationCondition(bool Unreachable);
164  void conditionalCompilationStart(bool Unreachable);
165  void conditionalCompilationAlternative();
166  void conditionalCompilationEnd();
167 
168  bool isOnNewLine(const FormatToken &FormatTok);
169 
170  // Compute hash of the current preprocessor branch.
171  // This is used to identify the different branches, and thus track if block
172  // open and close in the same branch.
173  size_t computePPHash() const;
174 
175  // FIXME: We are constantly running into bugs where Line.Level is incorrectly
176  // subtracted from beyond 0. Introduce a method to subtract from Line.Level
177  // and use that everywhere in the Parser.
178  std::unique_ptr<UnwrappedLine> Line;
179 
180  // Comments are sorted into unwrapped lines by whether they are in the same
181  // line as the previous token, or not. If not, they belong to the next token.
182  // Since the next token might already be in a new unwrapped line, we need to
183  // store the comments belonging to that token.
184  SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
185  FormatToken *FormatTok;
186  bool MustBreakBeforeNextToken;
187 
188  // The parsed lines. Only added to through \c CurrentLines.
190 
191  // Preprocessor directives are parsed out-of-order from other unwrapped lines.
192  // Thus, we need to keep a list of preprocessor directives to be reported
193  // after an unwrapped line that has been started was finished.
194  SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
195 
196  // New unwrapped lines are added via CurrentLines.
197  // Usually points to \c &Lines. While parsing a preprocessor directive when
198  // there is an unfinished previous unwrapped line, will point to
199  // \c &PreprocessorDirectives.
200  SmallVectorImpl<UnwrappedLine> *CurrentLines;
201 
202  // We store for each line whether it must be a declaration depending on
203  // whether we are in a compound statement or not.
204  std::vector<bool> DeclarationScopeStack;
205 
206  const FormatStyle &Style;
207  const AdditionalKeywords &Keywords;
208 
209  llvm::Regex CommentPragmasRegex;
210 
212  UnwrappedLineConsumer &Callback;
213 
214  // FIXME: This is a temporary measure until we have reworked the ownership
215  // of the format tokens. The goal is to have the actual tokens created and
216  // owned outside of and handed into the UnwrappedLineParser.
217  ArrayRef<FormatToken *> AllTokens;
218 
219  // Represents preprocessor branch type, so we can find matching
220  // #if/#else/#endif directives.
221  enum PPBranchKind {
222  PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
223  PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
224  };
225 
226  struct PPBranch {
227  PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
228  PPBranchKind Kind;
229  size_t Line;
230  };
231 
232  // Keeps a stack of currently active preprocessor branching directives.
234 
235  // The \c UnwrappedLineParser re-parses the code for each combination
236  // of preprocessor branches that can be taken.
237  // To that end, we take the same branch (#if, #else, or one of the #elif
238  // branches) for each nesting level of preprocessor branches.
239  // \c PPBranchLevel stores the current nesting level of preprocessor
240  // branches during one pass over the code.
241  int PPBranchLevel;
242 
243  // Contains the current branch (#if, #else or one of the #elif branches)
244  // for each nesting level.
245  SmallVector<int, 8> PPLevelBranchIndex;
246 
247  // Contains the maximum number of branches at each nesting level.
248  SmallVector<int, 8> PPLevelBranchCount;
249 
250  // Contains the number of branches per nesting level we are currently
251  // in while parsing a preprocessor branch sequence.
252  // This is used to update PPLevelBranchCount at the end of a branch
253  // sequence.
254  std::stack<int> PPChainBranchIndex;
255 
256  // Include guard search state. Used to fixup preprocessor indent levels
257  // so that include guards do not participate in indentation.
258  enum IncludeGuardState {
259  IG_Inited, // Search started, looking for #ifndef.
260  IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
261  IG_Defined, // Matching #define found, checking other requirements.
262  IG_Found, // All requirements met, need to fix indents.
263  IG_Rejected, // Search failed or never started.
264  };
265 
266  // Current state of include guard search.
267  IncludeGuardState IncludeGuard;
268 
269  // Points to the #ifndef condition for a potential include guard. Null unless
270  // IncludeGuardState == IG_IfNdefed.
271  FormatToken *IncludeGuardToken;
272 
273  // Contains the first start column where the source begins. This is zero for
274  // normal source code and may be nonzero when formatting a code fragment that
275  // does not start at the beginning of the file.
276  unsigned FirstStartColumn;
277 
278  friend class ScopedLineState;
280 };
281 
283  UnwrappedLineNode() : Tok(nullptr) {}
285 
288 };
289 
293 
294 } // end namespace format
295 } // end namespace clang
296 
297 #endif
size_t MatchingClosingBlockLineIndex
If this UnwrappedLine opens a block, stores the index of the line with the corresponding closing brac...
SmallVector< UnwrappedLine, 0 > Children
unsigned Level
The indent level of the UnwrappedLine.
const FormatToken & Tok
An unwrapped line is a sequence of Token, that we would like to put on a single line if there was no ...
std::list< UnwrappedLineNode > Tokens
The Tokens comprising this UnwrappedLine.
const AnnotatedLine * Line
static const size_t kInvalidIndex
bool InPPDirective
Whether this UnwrappedLine is part of a preprocessor directive.
A wrapper around a Token storing information about the whitespace characters preceding it...
Definition: FormatToken.h:123
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
#define false
Definition: stdbool.h:33
Kind
Various functions to configurably format source code.
size_t MatchingOpeningBlockLineIndex
If this UnwrappedLine closes a block in a sequence of lines, MatchingOpeningBlockLineIndex stores the...
Encapsulates keywords that are context sensitive or for languages not properly supported by Clang&#39;s l...
Definition: FormatToken.h:649
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The FormatStyle is used to configure the formatting to follow specific guidelines.
Definition: Format.h:48
Dataflow Directional Tag Classes.
Represents a complete lambda introducer.
Definition: DeclSpec.h:2542
This file contains the declaration of the FormatToken, a wrapper around Token with additional informa...
const FormatStyle & Style