Coverage Report

Created: 2020-09-19 12:23

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