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