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/ADT/BitVector.h"
22 #include "llvm/Support/Regex.h"
23 #include <list>
24 #include <stack>
25 #include <vector>
26
27 namespace clang {
28 namespace format {
29
30 struct UnwrappedLineNode;
31
32 /// An unwrapped line is a sequence of \c Token, that we would like to
33 /// put on a single line if there was no column limit.
34 ///
35 /// This is used as a main interface between the \c UnwrappedLineParser and the
36 /// \c UnwrappedLineFormatter. The key property is that changing the formatting
37 /// within an unwrapped line does not affect any other unwrapped lines.
38 struct UnwrappedLine {
39 UnwrappedLine();
40
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.
48 bool InPPDirective;
49
50 bool MustBeDeclaration;
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.
56 size_t MatchingOpeningBlockLineIndex = kInvalidIndex;
57
58 /// If this \c UnwrappedLine opens a block, stores the index of the
59 /// line with the corresponding closing brace.
60 size_t MatchingClosingBlockLineIndex = kInvalidIndex;
61
62 static const size_t kInvalidIndex = -1;
63
64 unsigned FirstStartColumn = 0;
65 };
66
67 class UnwrappedLineConsumer {
68 public:
~UnwrappedLineConsumer()69 virtual ~UnwrappedLineConsumer() {}
70 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
71 virtual void finishRun() = 0;
72 };
73
74 class FormatTokenSource;
75
76 class UnwrappedLineParser {
77 public:
78 UnwrappedLineParser(const FormatStyle &Style,
79 const AdditionalKeywords &Keywords,
80 unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens,
81 UnwrappedLineConsumer &Callback);
82
83 void parse();
84
85 private:
86 enum class IfStmtKind {
87 NotIf, // Not an if statement.
88 IfOnly, // An if statement without the else clause.
89 IfElse, // An if statement followed by else but not else if.
90 IfElseIf // An if statement followed by else if.
91 };
92
93 void reset();
94 void parseFile();
95 bool precededByCommentOrPPDirective() const;
96 bool parseLevel(const FormatToken *OpeningBrace = nullptr,
97 bool CanContainBracedList = true,
98 TokenType NextLBracesType = TT_Unknown,
99 IfStmtKind *IfKind = nullptr,
100 FormatToken **IfLeftBrace = nullptr);
101 bool mightFitOnOneLine(UnwrappedLine &Line,
102 const FormatToken *OpeningBrace = nullptr) const;
103 FormatToken *parseBlock(bool MustBeDeclaration = false,
104 unsigned AddLevels = 1u, bool MunchSemi = true,
105 bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
106 bool UnindentWhitesmithsBraces = false,
107 bool CanContainBracedList = true,
108 TokenType NextLBracesType = TT_Unknown);
109 void parseChildBlock(bool CanContainBracedList = true,
110 TokenType NextLBracesType = TT_Unknown);
111 void parsePPDirective();
112 void parsePPDefine();
113 void parsePPIf(bool IfDef);
114 void parsePPElIf();
115 void parsePPElse();
116 void parsePPEndIf();
117 void parsePPUnknown();
118 void readTokenWithJavaScriptASI();
119 void parseStructuralElement(bool IsTopLevel = false,
120 TokenType NextLBracesType = TT_Unknown,
121 IfStmtKind *IfKind = nullptr,
122 FormatToken **IfLeftBrace = nullptr,
123 bool *HasDoWhile = nullptr,
124 bool *HasLabel = nullptr);
125 bool tryToParseBracedList();
126 bool parseBracedList(bool ContinueOnSemicolons = false, bool IsEnum = false,
127 tok::TokenKind ClosingBraceKind = tok::r_brace);
128 void parseParens(TokenType AmpAmpTokenType = TT_Unknown);
129 void parseSquare(bool LambdaIntroducer = false);
130 void keepAncestorBraces();
131 void parseUnbracedBody(bool CheckEOF = false);
132 void handleAttributes();
133 bool handleCppAttributes();
134 FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
135 void parseTryCatch();
136 void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
137 void parseForOrWhileLoop();
138 void parseDoWhile();
139 void parseLabel(bool LeftAlignLabel = false);
140 void parseCaseLabel();
141 void parseSwitch();
142 void parseNamespace();
143 void parseModuleImport();
144 void parseNew();
145 void parseAccessSpecifier();
146 bool parseEnum();
147 bool parseStructLike();
148 void parseConcept();
149 bool parseRequires();
150 void parseRequiresClause(FormatToken *RequiresToken);
151 void parseRequiresExpression(FormatToken *RequiresToken);
152 void parseConstraintExpression();
153 void parseJavaEnumBody();
154 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
155 // parses the record as a child block, i.e. if the class declaration is an
156 // expression.
157 void parseRecord(bool ParseAsExpr = false);
158 void parseObjCLightweightGenerics();
159 void parseObjCMethod();
160 void parseObjCProtocolList();
161 void parseObjCUntilAtEnd();
162 void parseObjCInterfaceOrImplementation();
163 bool parseObjCProtocol();
164 void parseJavaScriptEs6ImportExport();
165 void parseStatementMacro();
166 void parseCSharpAttribute();
167 // Parse a C# generic type constraint: `where T : IComparable<T>`.
168 // See:
169 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
170 void parseCSharpGenericTypeConstraint();
171 bool tryToParseLambda();
172 bool tryToParseChildBlock();
173 bool tryToParseLambdaIntroducer();
174 bool tryToParsePropertyAccessor();
175 void tryToParseJSFunction();
176 bool tryToParseSimpleAttribute();
177
178 // Used by addUnwrappedLine to denote whether to keep or remove a level
179 // when resetting the line state.
180 enum class LineLevel { Remove, Keep };
181
182 void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
183 bool eof() const;
184 // LevelDifference is the difference of levels after and before the current
185 // token. For example:
186 // - if the token is '{' and opens a block, LevelDifference is 1.
187 // - if the token is '}' and closes a block, LevelDifference is -1.
188 void nextToken(int LevelDifference = 0);
189 void readToken(int LevelDifference = 0);
190
191 // Decides which comment tokens should be added to the current line and which
192 // should be added as comments before the next token.
193 //
194 // Comments specifies the sequence of comment tokens to analyze. They get
195 // either pushed to the current line or added to the comments before the next
196 // token.
197 //
198 // NextTok specifies the next token. A null pointer NextTok is supported, and
199 // signifies either the absence of a next token, or that the next token
200 // shouldn't be taken into accunt for the analysis.
201 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
202 const FormatToken *NextTok);
203
204 // Adds the comment preceding the next token to unwrapped lines.
205 void flushComments(bool NewlineBeforeNext);
206 void pushToken(FormatToken *Tok);
207 void calculateBraceTypes(bool ExpectClassBody = false);
208
209 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
210 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
211 // this branch either cannot be taken (for example '#if false'), or should
212 // not be taken in this round.
213 void conditionalCompilationCondition(bool Unreachable);
214 void conditionalCompilationStart(bool Unreachable);
215 void conditionalCompilationAlternative();
216 void conditionalCompilationEnd();
217
218 bool isOnNewLine(const FormatToken &FormatTok);
219
220 // Compute hash of the current preprocessor branch.
221 // This is used to identify the different branches, and thus track if block
222 // open and close in the same branch.
223 size_t computePPHash() const;
224
225 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
226 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
227 // and use that everywhere in the Parser.
228 std::unique_ptr<UnwrappedLine> Line;
229
230 // Comments are sorted into unwrapped lines by whether they are in the same
231 // line as the previous token, or not. If not, they belong to the next token.
232 // Since the next token might already be in a new unwrapped line, we need to
233 // store the comments belonging to that token.
234 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
235 FormatToken *FormatTok;
236 bool MustBreakBeforeNextToken;
237
238 // The parsed lines. Only added to through \c CurrentLines.
239 SmallVector<UnwrappedLine, 8> Lines;
240
241 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
242 // Thus, we need to keep a list of preprocessor directives to be reported
243 // after an unwrapped line that has been started was finished.
244 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
245
246 // New unwrapped lines are added via CurrentLines.
247 // Usually points to \c &Lines. While parsing a preprocessor directive when
248 // there is an unfinished previous unwrapped line, will point to
249 // \c &PreprocessorDirectives.
250 SmallVectorImpl<UnwrappedLine> *CurrentLines;
251
252 // We store for each line whether it must be a declaration depending on
253 // whether we are in a compound statement or not.
254 llvm::BitVector DeclarationScopeStack;
255
256 const FormatStyle &Style;
257 const AdditionalKeywords &Keywords;
258
259 llvm::Regex CommentPragmasRegex;
260
261 FormatTokenSource *Tokens;
262 UnwrappedLineConsumer &Callback;
263
264 // FIXME: This is a temporary measure until we have reworked the ownership
265 // of the format tokens. The goal is to have the actual tokens created and
266 // owned outside of and handed into the UnwrappedLineParser.
267 ArrayRef<FormatToken *> AllTokens;
268
269 // Keeps a stack of the states of nested control statements (true if the
270 // statement contains more than some predefined number of nested statements).
271 SmallVector<bool, 8> NestedTooDeep;
272
273 // Represents preprocessor branch type, so we can find matching
274 // #if/#else/#endif directives.
275 enum PPBranchKind {
276 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
277 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
278 };
279
280 struct PPBranch {
PPBranchPPBranch281 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
282 PPBranchKind Kind;
283 size_t Line;
284 };
285
286 // Keeps a stack of currently active preprocessor branching directives.
287 SmallVector<PPBranch, 16> PPStack;
288
289 // The \c UnwrappedLineParser re-parses the code for each combination
290 // of preprocessor branches that can be taken.
291 // To that end, we take the same branch (#if, #else, or one of the #elif
292 // branches) for each nesting level of preprocessor branches.
293 // \c PPBranchLevel stores the current nesting level of preprocessor
294 // branches during one pass over the code.
295 int PPBranchLevel;
296
297 // Contains the current branch (#if, #else or one of the #elif branches)
298 // for each nesting level.
299 SmallVector<int, 8> PPLevelBranchIndex;
300
301 // Contains the maximum number of branches at each nesting level.
302 SmallVector<int, 8> PPLevelBranchCount;
303
304 // Contains the number of branches per nesting level we are currently
305 // in while parsing a preprocessor branch sequence.
306 // This is used to update PPLevelBranchCount at the end of a branch
307 // sequence.
308 std::stack<int> PPChainBranchIndex;
309
310 // Include guard search state. Used to fixup preprocessor indent levels
311 // so that include guards do not participate in indentation.
312 enum IncludeGuardState {
313 IG_Inited, // Search started, looking for #ifndef.
314 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
315 IG_Defined, // Matching #define found, checking other requirements.
316 IG_Found, // All requirements met, need to fix indents.
317 IG_Rejected, // Search failed or never started.
318 };
319
320 // Current state of include guard search.
321 IncludeGuardState IncludeGuard;
322
323 // Points to the #ifndef condition for a potential include guard. Null unless
324 // IncludeGuardState == IG_IfNdefed.
325 FormatToken *IncludeGuardToken;
326
327 // Contains the first start column where the source begins. This is zero for
328 // normal source code and may be nonzero when formatting a code fragment that
329 // does not start at the beginning of the file.
330 unsigned FirstStartColumn;
331
332 friend class ScopedLineState;
333 friend class CompoundStatementIndenter;
334 };
335
336 struct UnwrappedLineNode {
UnwrappedLineNodeUnwrappedLineNode337 UnwrappedLineNode() : Tok(nullptr) {}
UnwrappedLineNodeUnwrappedLineNode338 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {}
339
340 FormatToken *Tok;
341 SmallVector<UnwrappedLine, 0> Children;
342 };
343
UnwrappedLine()344 inline UnwrappedLine::UnwrappedLine()
345 : Level(0), InPPDirective(false), MustBeDeclaration(false),
346 MatchingOpeningBlockLineIndex(kInvalidIndex) {}
347
348 } // end namespace format
349 } // end namespace clang
350
351 #endif
352