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