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 "Macros.h"
19#include <stack>
20
21namespace clang {
22namespace format {
23
24struct UnwrappedLineNode;
25
26/// An unwrapped line is a sequence of \c Token, that we would like to
27/// put on a single line if there was no column limit.
28///
29/// This is used as a main interface between the \c UnwrappedLineParser and the
30/// \c UnwrappedLineFormatter. The key property is that changing the formatting
31/// within an unwrapped line does not affect any other unwrapped lines.
32struct UnwrappedLine {
33 UnwrappedLine() = default;
34
35 /// The \c Tokens comprising this \c UnwrappedLine.
36 std::list<UnwrappedLineNode> Tokens;
37
38 /// The indent level of the \c UnwrappedLine.
39 unsigned Level = 0;
40
41 /// The \c PPBranchLevel (adjusted for header guards) if this line is a
42 /// \c InMacroBody line, and 0 otherwise.
43 unsigned PPLevel = 0;
44
45 /// Whether this \c UnwrappedLine is part of a preprocessor directive.
46 bool InPPDirective = false;
47 /// Whether this \c UnwrappedLine is part of a pramga directive.
48 bool InPragmaDirective = false;
49 /// Whether it is part of a macro body.
50 bool InMacroBody = false;
51
52 /// Nesting level of unbraced body of a control statement.
53 unsigned UnbracedBodyLevel = 0;
54
55 bool MustBeDeclaration = false;
56
57 /// Whether the parser has seen \c decltype(auto) in this line.
58 bool SeenDecltypeAuto = false;
59
60 /// \c True if this line should be indented by ContinuationIndent in
61 /// addition to the normal indention level.
62 bool IsContinuation = false;
63
64 /// If this \c UnwrappedLine closes a block in a sequence of lines,
65 /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding
66 /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be
67 /// \c kInvalidIndex.
68 size_t MatchingOpeningBlockLineIndex = kInvalidIndex;
69
70 /// If this \c UnwrappedLine opens a block, stores the index of the
71 /// line with the corresponding closing brace.
72 size_t MatchingClosingBlockLineIndex = kInvalidIndex;
73
74 static const size_t kInvalidIndex = -1;
75
76 unsigned FirstStartColumn = 0;
77};
78
79/// Interface for users of the UnwrappedLineParser to receive the parsed lines.
80/// Parsing a single snippet of code can lead to multiple runs, where each
81/// run is a coherent view of the file.
82///
83/// For example, different runs are generated:
84/// - for different combinations of #if blocks
85/// - when macros are involved, for the expanded code and the as-written code
86///
87/// Some tokens will only be visible in a subset of the runs.
88/// For each run, \c UnwrappedLineParser will call \c consumeUnwrappedLine
89/// for each parsed unwrapped line, and then \c finishRun to indicate
90/// that the set of unwrapped lines before is one coherent view of the
91/// code snippet to be formatted.
92class UnwrappedLineConsumer {
93public:
94 virtual ~UnwrappedLineConsumer() {}
95 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
96 virtual void finishRun() = 0;
97};
98
99class FormatTokenSource;
100
101class UnwrappedLineParser {
102public:
103 UnwrappedLineParser(SourceManager &SourceMgr, const FormatStyle &Style,
104 const AdditionalKeywords &Keywords,
105 unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens,
106 UnwrappedLineConsumer &Callback,
107 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
108 IdentifierTable &IdentTable);
109
110 void parse();
111
112private:
113 enum class IfStmtKind {
114 NotIf, // Not an if statement.
115 IfOnly, // An if statement without the else clause.
116 IfElse, // An if statement followed by else but not else if.
117 IfElseIf // An if statement followed by else if.
118 };
119
120 void reset();
121 void parseFile();
122 bool precededByCommentOrPPDirective() const;
123 bool parseLevel(const FormatToken *OpeningBrace = nullptr,
124 IfStmtKind *IfKind = nullptr,
125 FormatToken **IfLeftBrace = nullptr);
126 bool mightFitOnOneLine(UnwrappedLine &Line,
127 const FormatToken *OpeningBrace = nullptr) const;
128 FormatToken *parseBlock(bool MustBeDeclaration = false,
129 unsigned AddLevels = 1u, bool MunchSemi = true,
130 bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
131 bool UnindentWhitesmithsBraces = false);
132 void parseChildBlock();
133 void parsePPDirective();
134 void parsePPDefine();
135 void parsePPIf(bool IfDef);
136 void parsePPElse();
137 void parsePPEndIf();
138 void parsePPPragma();
139 void parsePPUnknown();
140 void readTokenWithJavaScriptASI();
141 void parseStructuralElement(const FormatToken *OpeningBrace = nullptr,
142 IfStmtKind *IfKind = nullptr,
143 FormatToken **IfLeftBrace = nullptr,
144 bool *HasDoWhile = nullptr,
145 bool *HasLabel = nullptr);
146 bool tryToParseBracedList();
147 bool parseBracedList(bool IsAngleBracket = false, bool IsEnum = false);
148 bool parseParens(TokenType AmpAmpTokenType = TT_Unknown,
149 bool InMacroCall = false);
150 void parseSquare(bool LambdaIntroducer = false);
151 void keepAncestorBraces();
152 void parseUnbracedBody(bool CheckEOF = false);
153 void handleAttributes();
154 bool handleCppAttributes();
155 bool isBlockBegin(const FormatToken &Tok) const;
156 FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false,
157 bool IsVerilogAssert = false);
158 void parseTryCatch();
159 void parseLoopBody(bool KeepBraces, bool WrapRightBrace);
160 void parseForOrWhileLoop(bool HasParens = true);
161 void parseDoWhile();
162 void parseLabel(FormatStyle::IndentGotoLabelStyle IndentGotoLabels =
163 FormatStyle::IGLS_OuterIndent);
164 void parseCaseLabel();
165 void parseSwitch(bool IsExpr);
166 void parseNamespace();
167 bool parseModuleImport();
168 void parseNew();
169 void parseAccessSpecifier();
170 bool parseEnum();
171 bool parseStructLike();
172 bool parseRequires(bool SeenEqual);
173 void parseRequiresClause();
174 void parseRequiresExpression();
175 void parseConstraintExpression();
176 void parseCppExportBlock();
177 void parseNamespaceOrExportBlock(unsigned AddLevels);
178 void parseJavaEnumBody();
179 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
180 // parses the record as a child block, i.e. if the class declaration is an
181 // expression.
182 void parseRecord(bool ParseAsExpr = false, bool IsJavaRecord = false);
183 void parseObjCLightweightGenerics();
184 void parseObjCMethod();
185 void parseObjCProtocolList();
186 void parseObjCUntilAtEnd();
187 void parseObjCInterfaceOrImplementation();
188 bool parseObjCProtocol();
189 void parseJavaScriptEs6ImportExport();
190 void parseStatementMacro();
191 void parseCSharpAttribute();
192 // Parse a C# generic type constraint: `where T : IComparable<T>`.
193 // See:
194 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
195 void parseCSharpGenericTypeConstraint();
196 bool tryToParseLambda();
197 bool tryToParseChildBlock();
198 bool tryToParseLambdaIntroducer();
199 bool tryToParsePropertyAccessor();
200 void tryToParseJSFunction();
201 bool tryToParseSimpleAttribute();
202 void parseVerilogHierarchyIdentifier();
203 void parseVerilogSensitivityList();
204 // Returns the number of levels of indentation in addition to the normal 1
205 // level for a block, used for indenting case labels.
206 unsigned parseVerilogHierarchyHeader();
207 void parseVerilogTable();
208 void parseVerilogCaseLabel();
209 // For import, export, and extern.
210 void parseVerilogExtern();
211 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
212 parseMacroCall();
213
214 // Used by addUnwrappedLine to denote whether to keep or remove a level
215 // when resetting the line state.
216 enum class LineLevel { Remove, Keep };
217
218 void addUnwrappedLine(LineLevel AdjustLevel = LineLevel::Remove);
219 bool eof() const;
220 // LevelDifference is the difference of levels after and before the current
221 // token. For example:
222 // - if the token is '{' and opens a block, LevelDifference is 1.
223 // - if the token is '}' and closes a block, LevelDifference is -1.
224 void nextToken(int LevelDifference = 0);
225 void readToken(int LevelDifference = 0);
226
227 // Decides which comment tokens should be added to the current line and which
228 // should be added as comments before the next token.
229 //
230 // Comments specifies the sequence of comment tokens to analyze. They get
231 // either pushed to the current line or added to the comments before the next
232 // token.
233 //
234 // NextTok specifies the next token. A null pointer NextTok is supported, and
235 // signifies either the absence of a next token, or that the next token
236 // shouldn't be taken into account for the analysis.
237 void distributeComments(const ArrayRef<FormatToken *> &Comments,
238 const FormatToken *NextTok);
239
240 // Adds the comment preceding the next token to unwrapped lines.
241 void flushComments(bool NewlineBeforeNext);
242 void pushToken(FormatToken *Tok);
243 void calculateBraceTypes(bool ExpectClassBody = false);
244 void setPreviousRBraceType(TokenType Type);
245
246 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
247 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
248 // this branch either cannot be taken (for example '#if false'), or should
249 // not be taken in this round.
250 void conditionalCompilationCondition(bool Unreachable);
251 void conditionalCompilationStart(bool Unreachable);
252 void conditionalCompilationAlternative();
253 void conditionalCompilationEnd();
254
255 bool isOnNewLine(const FormatToken &FormatTok);
256
257 // Returns whether there is a macro expansion in the line, i.e. a token that
258 // was expanded from a macro call.
259 bool containsExpansion(const UnwrappedLine &Line) const;
260
261 // Compute hash of the current preprocessor branch.
262 // This is used to identify the different branches, and thus track if block
263 // open and close in the same branch.
264 size_t computePPHash() const;
265
266 bool parsingPPDirective() const { return CurrentLines != &Lines; }
267
268 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
269 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
270 // and use that everywhere in the Parser.
271 std::unique_ptr<UnwrappedLine> Line;
272
273 // Lines that are created by macro expansion.
274 // When formatting code containing macro calls, we first format the expanded
275 // lines to set the token types correctly. Afterwards, we format the
276 // reconstructed macro calls, re-using the token types determined in the first
277 // step.
278 // ExpandedLines will be reset every time we create a new LineAndExpansion
279 // instance once a line containing macro calls has been parsed.
280 SmallVector<UnwrappedLine, 8> CurrentExpandedLines;
281
282 // Maps from the first token of a top-level UnwrappedLine that contains
283 // a macro call to the replacement UnwrappedLines expanded from the macro
284 // call.
285 llvm::DenseMap<FormatToken *, SmallVector<UnwrappedLine, 8>> ExpandedLines;
286
287 // Map from the macro identifier to a line containing the full unexpanded
288 // macro call.
289 llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>> Unexpanded;
290
291 // For recursive macro expansions, trigger reconstruction only on the
292 // outermost expansion.
293 bool InExpansion = false;
294
295 // Set while we reconstruct a macro call.
296 // For reconstruction, we feed the expanded lines into the reconstructor
297 // until it is finished.
298 std::optional<MacroCallReconstructor> Reconstruct;
299
300 // Comments are sorted into unwrapped lines by whether they are in the same
301 // line as the previous token, or not. If not, they belong to the next token.
302 // Since the next token might already be in a new unwrapped line, we need to
303 // store the comments belonging to that token.
304 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
305
306 FormatToken *FormatTok = nullptr;
307
308 // Has just finished parsing a preprocessor line.
309 bool AtEndOfPPLine;
310
311 // The parsed lines. Only added to through \c CurrentLines.
312 SmallVector<UnwrappedLine, 8> Lines;
313
314 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
315 // Thus, we need to keep a list of preprocessor directives to be reported
316 // after an unwrapped line that has been started was finished.
317 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
318
319 // New unwrapped lines are added via CurrentLines.
320 // Usually points to \c &Lines. While parsing a preprocessor directive when
321 // there is an unfinished previous unwrapped line, will point to
322 // \c &PreprocessorDirectives.
323 SmallVectorImpl<UnwrappedLine> *CurrentLines;
324
325 // We store for each line whether it must be a declaration depending on
326 // whether we are in a compound statement or not.
327 llvm::BitVector DeclarationScopeStack;
328
329 const FormatStyle &Style;
330 bool IsCpp;
331 LangOptions LangOpts;
332 const AdditionalKeywords &Keywords;
333
334 llvm::Regex CommentPragmasRegex;
335
336 FormatTokenSource *Tokens;
337 UnwrappedLineConsumer &Callback;
338
339 ArrayRef<FormatToken *> AllTokens;
340
341 // Keeps a stack of the states of nested control statements (true if the
342 // statement contains more than some predefined number of nested statements).
343 SmallVector<bool, 8> NestedTooDeep;
344
345 // Keeps a stack of the states of nested lambdas (true if the return type of
346 // the lambda is `decltype(auto)`).
347 SmallVector<bool, 4> NestedLambdas;
348
349 // Whether the parser is parsing the body of a function whose return type is
350 // `decltype(auto)`.
351 bool IsDecltypeAutoFunction = false;
352
353 // Represents preprocessor branch type, so we can find matching
354 // #if/#else/#endif directives.
355 enum PPBranchKind {
356 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
357 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
358 };
359
360 struct PPBranch {
361 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
362 PPBranchKind Kind;
363 size_t Line;
364 };
365
366 // Keeps a stack of currently active preprocessor branching directives.
367 SmallVector<PPBranch, 16> PPStack;
368
369 // The \c UnwrappedLineParser re-parses the code for each combination
370 // of preprocessor branches that can be taken.
371 // To that end, we take the same branch (#if, #else, or one of the #elif
372 // branches) for each nesting level of preprocessor branches.
373 // \c PPBranchLevel stores the current nesting level of preprocessor
374 // branches during one pass over the code.
375 int PPBranchLevel;
376
377 // Contains the current branch (#if, #else or one of the #elif branches)
378 // for each nesting level.
379 SmallVector<int, 8> PPLevelBranchIndex;
380
381 // Contains the maximum number of branches at each nesting level.
382 SmallVector<int, 8> PPLevelBranchCount;
383
384 // Contains the number of branches per nesting level we are currently
385 // in while parsing a preprocessor branch sequence.
386 // This is used to update PPLevelBranchCount at the end of a branch
387 // sequence.
388 std::stack<int> PPChainBranchIndex;
389
390 // Include guard search state. Used to fixup preprocessor indent levels
391 // so that include guards do not participate in indentation.
392 enum IncludeGuardState {
393 IG_Inited, // Search started, looking for #ifndef.
394 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
395 IG_Defined, // Matching #define found, checking other requirements.
396 IG_Found, // All requirements met, need to fix indents.
397 IG_Rejected, // Search failed or never started.
398 };
399
400 // Current state of include guard search.
401 IncludeGuardState IncludeGuard;
402
403 IncludeGuardState
404 getIncludeGuardState(FormatStyle::PPDirectiveIndentStyle Style) const {
405 return Style == FormatStyle::PPDIS_None || Style == FormatStyle::PPDIS_Leave
406 ? IG_Rejected
407 : IG_Inited;
408 }
409
410 // Points to the #ifndef condition for a potential include guard. Null unless
411 // IncludeGuardState == IG_IfNdefed.
412 FormatToken *IncludeGuardToken;
413
414 // Contains the first start column where the source begins. This is zero for
415 // normal source code and may be nonzero when formatting a code fragment that
416 // does not start at the beginning of the file.
417 unsigned FirstStartColumn;
418
419 MacroExpander Macros;
420
421 friend class ScopedLineState;
422 friend class CompoundStatementIndenter;
423};
424
425struct UnwrappedLineNode {
426 UnwrappedLineNode() : Tok(nullptr) {}
427 UnwrappedLineNode(FormatToken *Tok,
428 llvm::ArrayRef<UnwrappedLine> Children = {})
429 : Tok(Tok), Children(Children) {}
430
431 FormatToken *Tok;
432 SmallVector<UnwrappedLine, 0> Children;
433};
434
435std::ostream &operator<<(std::ostream &Stream, const UnwrappedLine &Line);
436
437} // end namespace format
438} // end namespace clang
439
440#endif
441