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