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 /// \brief 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 /// \brief 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 /// \brief The \c Tokens comprising this \c UnwrappedLine.
42 std::list<UnwrappedLineNode> Tokens;
44 /// \brief The indent level of the \c UnwrappedLine.
47 /// \brief Whether this \c UnwrappedLine is part of a preprocessor directive.
50 bool MustBeDeclaration;
52 /// \brief 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;
58 static const size_t kInvalidIndex = -1;
60 unsigned FirstStartColumn = 0;
63 class UnwrappedLineConsumer {
65 virtual ~UnwrappedLineConsumer() {}
66 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
67 virtual void finishRun() = 0;
70 class FormatTokenSource;
72 class UnwrappedLineParser {
74 UnwrappedLineParser(const FormatStyle &Style,
75 const AdditionalKeywords &Keywords,
76 unsigned FirstStartColumn,
77 ArrayRef<FormatToken *> Tokens,
78 UnwrappedLineConsumer &Callback);
85 void parseLevel(bool HasOpeningBrace);
86 void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
87 bool MunchSemi = true);
88 void parseChildBlock();
89 void parsePPDirective();
91 void parsePPIf(bool IfDef);
95 void parsePPUnknown();
96 void readTokenWithJavaScriptASI();
97 void parseStructuralElement();
98 bool tryToParseBracedList();
99 bool parseBracedList(bool ContinueOnSemicolons = false,
100 tok::TokenKind ClosingBraceKind = tok::r_brace);
102 void parseSquare(bool LambdaIntroducer = false);
103 void parseIfThenElse();
104 void parseTryCatch();
105 void parseForOrWhileLoop();
108 void parseCaseLabel();
110 void parseNamespace();
112 void parseAccessSpecifier();
114 void parseJavaEnumBody();
115 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
116 // parses the record as a child block, i.e. if the class declaration is an
118 void parseRecord(bool ParseAsExpr = false);
119 void parseObjCProtocolList();
120 void parseObjCUntilAtEnd();
121 void parseObjCInterfaceOrImplementation();
122 void parseObjCProtocol();
123 void parseJavaScriptEs6ImportExport();
124 bool tryToParseLambda();
125 bool tryToParseLambdaIntroducer();
126 void tryToParseJSFunction();
127 void addUnwrappedLine();
129 // LevelDifference is the difference of levels after and before the current
130 // token. For example:
131 // - if the token is '{' and opens a block, LevelDifference is 1.
132 // - if the token is '}' and closes a block, LevelDifference is -1.
133 void nextToken(int LevelDifference = 0);
134 void readToken(int LevelDifference = 0);
136 // Decides which comment tokens should be added to the current line and which
137 // should be added as comments before the next token.
139 // Comments specifies the sequence of comment tokens to analyze. They get
140 // either pushed to the current line or added to the comments before the next
143 // NextTok specifies the next token. A null pointer NextTok is supported, and
144 // signifies either the absense of a next token, or that the next token
145 // shouldn't be taken into accunt for the analysis.
146 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
147 const FormatToken *NextTok);
149 // Adds the comment preceding the next token to unwrapped lines.
150 void flushComments(bool NewlineBeforeNext);
151 void pushToken(FormatToken *Tok);
152 void calculateBraceTypes(bool ExpectClassBody = false);
154 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
155 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
156 // this branch either cannot be taken (for example '#if false'), or should
157 // not be taken in this round.
158 void conditionalCompilationCondition(bool Unreachable);
159 void conditionalCompilationStart(bool Unreachable);
160 void conditionalCompilationAlternative();
161 void conditionalCompilationEnd();
163 bool isOnNewLine(const FormatToken &FormatTok);
165 // Compute hash of the current preprocessor branch.
166 // This is used to identify the different branches, and thus track if block
167 // open and close in the same branch.
168 size_t computePPHash() const;
170 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
171 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
172 // and use that everywhere in the Parser.
173 std::unique_ptr<UnwrappedLine> Line;
175 // Comments are sorted into unwrapped lines by whether they are in the same
176 // line as the previous token, or not. If not, they belong to the next token.
177 // Since the next token might already be in a new unwrapped line, we need to
178 // store the comments belonging to that token.
179 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
180 FormatToken *FormatTok;
181 bool MustBreakBeforeNextToken;
183 // The parsed lines. Only added to through \c CurrentLines.
184 SmallVector<UnwrappedLine, 8> Lines;
186 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
187 // Thus, we need to keep a list of preprocessor directives to be reported
188 // after an unwrapped line that has been started was finished.
189 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
191 // New unwrapped lines are added via CurrentLines.
192 // Usually points to \c &Lines. While parsing a preprocessor directive when
193 // there is an unfinished previous unwrapped line, will point to
194 // \c &PreprocessorDirectives.
195 SmallVectorImpl<UnwrappedLine> *CurrentLines;
197 // We store for each line whether it must be a declaration depending on
198 // whether we are in a compound statement or not.
199 std::vector<bool> DeclarationScopeStack;
201 const FormatStyle &Style;
202 const AdditionalKeywords &Keywords;
204 llvm::Regex CommentPragmasRegex;
206 FormatTokenSource *Tokens;
207 UnwrappedLineConsumer &Callback;
209 // FIXME: This is a temporary measure until we have reworked the ownership
210 // of the format tokens. The goal is to have the actual tokens created and
211 // owned outside of and handed into the UnwrappedLineParser.
212 ArrayRef<FormatToken *> AllTokens;
214 // Represents preprocessor branch type, so we can find matching
215 // #if/#else/#endif directives.
217 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
218 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
222 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
227 // Keeps a stack of currently active preprocessor branching directives.
228 SmallVector<PPBranch, 16> PPStack;
230 // The \c UnwrappedLineParser re-parses the code for each combination
231 // of preprocessor branches that can be taken.
232 // To that end, we take the same branch (#if, #else, or one of the #elif
233 // branches) for each nesting level of preprocessor branches.
234 // \c PPBranchLevel stores the current nesting level of preprocessor
235 // branches during one pass over the code.
238 // Contains the current branch (#if, #else or one of the #elif branches)
239 // for each nesting level.
240 SmallVector<int, 8> PPLevelBranchIndex;
242 // Contains the maximum number of branches at each nesting level.
243 SmallVector<int, 8> PPLevelBranchCount;
245 // Contains the number of branches per nesting level we are currently
246 // in while parsing a preprocessor branch sequence.
247 // This is used to update PPLevelBranchCount at the end of a branch
249 std::stack<int> PPChainBranchIndex;
251 // Contains the #ifndef condition for a potential include guard.
252 FormatToken *IfNdefCondition;
253 bool FoundIncludeGuardStart;
254 bool IncludeGuardRejected;
255 // Contains the first start column where the source begins. This is zero for
256 // normal source code and may be nonzero when formatting a code fragment that
257 // does not start at the beginning of the file.
258 unsigned FirstStartColumn;
260 friend class ScopedLineState;
261 friend class CompoundStatementIndenter;
264 struct UnwrappedLineNode {
265 UnwrappedLineNode() : Tok(nullptr) {}
266 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {}
269 SmallVector<UnwrappedLine, 0> Children;
272 inline UnwrappedLine::UnwrappedLine()
273 : Level(0), InPPDirective(false), MustBeDeclaration(false),
274 MatchingOpeningBlockLineIndex(kInvalidIndex) {}
276 } // end namespace format
277 } // end namespace clang