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