1 //===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// This file contains the declaration of the UnwrappedLineParser,
12 /// which turns a stream of tokens into UnwrappedLines.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
17 #define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
19 #include "FormatToken.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Format/Format.h"
22 #include "llvm/Support/Regex.h"
29 struct UnwrappedLineNode;
31 /// An unwrapped line is a sequence of \c Token, that we would like to
32 /// put on a single line if there was no column limit.
34 /// This is used as a main interface between the \c UnwrappedLineParser and the
35 /// \c UnwrappedLineFormatter. The key property is that changing the formatting
36 /// within an unwrapped line does not affect any other unwrapped lines.
37 struct UnwrappedLine {
40 // FIXME: Don't use std::list here.
41 /// The \c Tokens comprising this \c UnwrappedLine.
42 std::list<UnwrappedLineNode> Tokens;
44 /// The indent level of the \c UnwrappedLine.
47 /// Whether this \c UnwrappedLine is part of a preprocessor directive.
50 bool MustBeDeclaration;
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
56 size_t MatchingOpeningBlockLineIndex = kInvalidIndex;
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;
62 static const size_t kInvalidIndex = -1;
64 unsigned FirstStartColumn = 0;
67 class UnwrappedLineConsumer {
69 virtual ~UnwrappedLineConsumer() {}
70 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
71 virtual void finishRun() = 0;
74 class FormatTokenSource;
76 class UnwrappedLineParser {
78 UnwrappedLineParser(const FormatStyle &Style,
79 const AdditionalKeywords &Keywords,
80 unsigned FirstStartColumn,
81 ArrayRef<FormatToken *> Tokens,
82 UnwrappedLineConsumer &Callback);
89 void parseLevel(bool HasOpeningBrace);
90 void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
91 bool MunchSemi = true);
92 void parseChildBlock();
93 void parsePPDirective();
95 void parsePPIf(bool IfDef);
99 void parsePPUnknown();
100 void readTokenWithJavaScriptASI();
101 void parseStructuralElement();
102 bool tryToParseBracedList();
103 bool parseBracedList(bool ContinueOnSemicolons = false,
104 tok::TokenKind ClosingBraceKind = tok::r_brace);
106 void parseSquare(bool LambdaIntroducer = false);
107 void parseIfThenElse();
108 void parseTryCatch();
109 void parseForOrWhileLoop();
112 void parseCaseLabel();
114 void parseNamespace();
116 void parseAccessSpecifier();
118 void parseJavaEnumBody();
119 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
120 // parses the record as a child block, i.e. if the class declaration is an
122 void parseRecord(bool ParseAsExpr = false);
123 void parseObjCMethod();
124 void parseObjCProtocolList();
125 void parseObjCUntilAtEnd();
126 void parseObjCInterfaceOrImplementation();
127 bool parseObjCProtocol();
128 void parseJavaScriptEs6ImportExport();
129 void parseStatementMacro();
130 bool tryToParseLambda();
131 bool tryToParseLambdaIntroducer();
132 void tryToParseJSFunction();
133 void addUnwrappedLine();
135 // LevelDifference is the difference of levels after and before the current
136 // token. For example:
137 // - if the token is '{' and opens a block, LevelDifference is 1.
138 // - if the token is '}' and closes a block, LevelDifference is -1.
139 void nextToken(int LevelDifference = 0);
140 void readToken(int LevelDifference = 0);
142 // Decides which comment tokens should be added to the current line and which
143 // should be added as comments before the next token.
145 // Comments specifies the sequence of comment tokens to analyze. They get
146 // either pushed to the current line or added to the comments before the next
149 // NextTok specifies the next token. A null pointer NextTok is supported, and
150 // signifies either the absence of a next token, or that the next token
151 // shouldn't be taken into accunt for the analysis.
152 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
153 const FormatToken *NextTok);
155 // Adds the comment preceding the next token to unwrapped lines.
156 void flushComments(bool NewlineBeforeNext);
157 void pushToken(FormatToken *Tok);
158 void calculateBraceTypes(bool ExpectClassBody = false);
160 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
161 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
162 // this branch either cannot be taken (for example '#if false'), or should
163 // not be taken in this round.
164 void conditionalCompilationCondition(bool Unreachable);
165 void conditionalCompilationStart(bool Unreachable);
166 void conditionalCompilationAlternative();
167 void conditionalCompilationEnd();
169 bool isOnNewLine(const FormatToken &FormatTok);
171 // Compute hash of the current preprocessor branch.
172 // This is used to identify the different branches, and thus track if block
173 // open and close in the same branch.
174 size_t computePPHash() const;
176 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
177 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
178 // and use that everywhere in the Parser.
179 std::unique_ptr<UnwrappedLine> Line;
181 // Comments are sorted into unwrapped lines by whether they are in the same
182 // line as the previous token, or not. If not, they belong to the next token.
183 // Since the next token might already be in a new unwrapped line, we need to
184 // store the comments belonging to that token.
185 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
186 FormatToken *FormatTok;
187 bool MustBreakBeforeNextToken;
189 // The parsed lines. Only added to through \c CurrentLines.
190 SmallVector<UnwrappedLine, 8> Lines;
192 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
193 // Thus, we need to keep a list of preprocessor directives to be reported
194 // after an unwrapped line that has been started was finished.
195 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
197 // New unwrapped lines are added via CurrentLines.
198 // Usually points to \c &Lines. While parsing a preprocessor directive when
199 // there is an unfinished previous unwrapped line, will point to
200 // \c &PreprocessorDirectives.
201 SmallVectorImpl<UnwrappedLine> *CurrentLines;
203 // We store for each line whether it must be a declaration depending on
204 // whether we are in a compound statement or not.
205 std::vector<bool> DeclarationScopeStack;
207 const FormatStyle &Style;
208 const AdditionalKeywords &Keywords;
210 llvm::Regex CommentPragmasRegex;
212 FormatTokenSource *Tokens;
213 UnwrappedLineConsumer &Callback;
215 // FIXME: This is a temporary measure until we have reworked the ownership
216 // of the format tokens. The goal is to have the actual tokens created and
217 // owned outside of and handed into the UnwrappedLineParser.
218 ArrayRef<FormatToken *> AllTokens;
220 // Represents preprocessor branch type, so we can find matching
221 // #if/#else/#endif directives.
223 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
224 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
228 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
233 // Keeps a stack of currently active preprocessor branching directives.
234 SmallVector<PPBranch, 16> PPStack;
236 // The \c UnwrappedLineParser re-parses the code for each combination
237 // of preprocessor branches that can be taken.
238 // To that end, we take the same branch (#if, #else, or one of the #elif
239 // branches) for each nesting level of preprocessor branches.
240 // \c PPBranchLevel stores the current nesting level of preprocessor
241 // branches during one pass over the code.
244 // Contains the current branch (#if, #else or one of the #elif branches)
245 // for each nesting level.
246 SmallVector<int, 8> PPLevelBranchIndex;
248 // Contains the maximum number of branches at each nesting level.
249 SmallVector<int, 8> PPLevelBranchCount;
251 // Contains the number of branches per nesting level we are currently
252 // in while parsing a preprocessor branch sequence.
253 // This is used to update PPLevelBranchCount at the end of a branch
255 std::stack<int> PPChainBranchIndex;
257 // Include guard search state. Used to fixup preprocessor indent levels
258 // so that include guards do not participate in indentation.
259 enum IncludeGuardState {
260 IG_Inited, // Search started, looking for #ifndef.
261 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
262 IG_Defined, // Matching #define found, checking other requirements.
263 IG_Found, // All requirements met, need to fix indents.
264 IG_Rejected, // Search failed or never started.
267 // Current state of include guard search.
268 IncludeGuardState IncludeGuard;
270 // Points to the #ifndef condition for a potential include guard. Null unless
271 // IncludeGuardState == IG_IfNdefed.
272 FormatToken *IncludeGuardToken;
274 // Contains the first start column where the source begins. This is zero for
275 // normal source code and may be nonzero when formatting a code fragment that
276 // does not start at the beginning of the file.
277 unsigned FirstStartColumn;
279 friend class ScopedLineState;
280 friend class CompoundStatementIndenter;
283 struct UnwrappedLineNode {
284 UnwrappedLineNode() : Tok(nullptr) {}
285 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {}
288 SmallVector<UnwrappedLine, 0> Children;
291 inline UnwrappedLine::UnwrappedLine()
292 : Level(0), InPPDirective(false), MustBeDeclaration(false),
293 MatchingOpeningBlockLineIndex(kInvalidIndex) {}
295 } // end namespace format
296 } // end namespace clang