blob: e1b35317c7c0eb8c9d173507c0317e4b2f13bc1e [file] [log] [blame]
Chandler Carruth3a022472012-12-04 09:13:33 +00001//===--- UnwrappedLineParser.h - Format C++ code ----------------*- C++ -*-===//
Daniel Jasperf7935112012-12-03 18:12:45 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Jasperf7935112012-12-03 18:12:45 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// This file contains the declaration of the UnwrappedLineParser,
Daniel Jasperf7935112012-12-03 18:12:45 +000011/// which turns a stream of tokens into UnwrappedLines.
12///
Daniel Jasperf7935112012-12-03 18:12:45 +000013//===----------------------------------------------------------------------===//
14
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +000015#ifndef LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
16#define LLVM_CLANG_LIB_FORMAT_UNWRAPPEDLINEPARSER_H
Daniel Jasperf7935112012-12-03 18:12:45 +000017
Chandler Carruth5553d0d2014-01-07 11:51:46 +000018#include "FormatToken.h"
Daniel Jasperf7935112012-12-03 18:12:45 +000019#include "clang/Basic/IdentifierTable.h"
Alexander Kornienko578fdd82012-12-06 18:03:27 +000020#include "clang/Format/Format.h"
Krasimir Georgiev00c5c722017-02-02 15:32:19 +000021#include "llvm/Support/Regex.h"
Daniel Jasperdaffc0d2013-01-16 09:10:19 +000022#include <list>
Hans Wennborg2f65f7f2014-10-29 22:49:58 +000023#include <stack>
Daniel Jasper7c85fde2013-01-08 14:56:18 +000024
Daniel Jasperf7935112012-12-03 18:12:45 +000025namespace clang {
26namespace format {
27
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000028struct UnwrappedLineNode;
29
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000030/// An unwrapped line is a sequence of \c Token, that we would like to
Daniel Jasperf7935112012-12-03 18:12:45 +000031/// put on a single line if there was no column limit.
32///
33/// This is used as a main interface between the \c UnwrappedLineParser and the
34/// \c UnwrappedLineFormatter. The key property is that changing the formatting
35/// within an unwrapped line does not affect any other unwrapped lines.
36struct UnwrappedLine {
Douglas Gregor7cfed212013-09-05 18:28:53 +000037 UnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +000038
Daniel Jaspera67a8f02013-01-16 10:41:46 +000039 // FIXME: Don't use std::list here.
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// The \c Tokens comprising this \c UnwrappedLine.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +000041 std::list<UnwrappedLineNode> Tokens;
Daniel Jasperf7935112012-12-03 18:12:45 +000042
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000043 /// The indent level of the \c UnwrappedLine.
Daniel Jasperf7935112012-12-03 18:12:45 +000044 unsigned Level;
Manuel Klimeka71e5d82013-01-02 16:30:12 +000045
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 /// Whether this \c UnwrappedLine is part of a preprocessor directive.
Manuel Klimeka71e5d82013-01-02 16:30:12 +000047 bool InPPDirective;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000048
49 bool MustBeDeclaration;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000051 /// If this \c UnwrappedLine closes a block in a sequence of lines,
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000052 /// \c MatchingOpeningBlockLineIndex stores the index of the corresponding
53 /// opening line. Otherwise, \c MatchingOpeningBlockLineIndex must be
54 /// \c kInvalidIndex.
Manuel Klimek0dddcf72018-04-23 09:34:26 +000055 size_t MatchingOpeningBlockLineIndex = kInvalidIndex;
56
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057 /// If this \c UnwrappedLine opens a block, stores the index of the
Manuel Klimek0dddcf72018-04-23 09:34:26 +000058 /// line with the corresponding closing brace.
59 size_t MatchingClosingBlockLineIndex = kInvalidIndex;
Krasimir Georgiev7cb267a2017-02-27 13:28:36 +000060
61 static const size_t kInvalidIndex = -1;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +000062
63 unsigned FirstStartColumn = 0;
Daniel Jasperf7935112012-12-03 18:12:45 +000064};
65
66class UnwrappedLineConsumer {
67public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000068 virtual ~UnwrappedLineConsumer() {}
Alexander Kornienkobc09a7e2012-12-05 13:56:52 +000069 virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0;
Manuel Klimek71814b42013-10-11 21:25:45 +000070 virtual void finishRun() = 0;
Daniel Jasperf7935112012-12-03 18:12:45 +000071};
72
Manuel Klimek15dfe7a2013-05-28 11:55:06 +000073class FormatTokenSource;
Alexander Kornienkoe3276842012-12-07 16:15:44 +000074
Daniel Jasperf7935112012-12-03 18:12:45 +000075class UnwrappedLineParser {
76public:
Daniel Jasperd0ec0d62014-11-04 12:41:02 +000077 UnwrappedLineParser(const FormatStyle &Style,
78 const AdditionalKeywords &Keywords,
Paul Hoad5bcf99b2019-03-01 09:09:54 +000079 unsigned FirstStartColumn, ArrayRef<FormatToken *> Tokens,
Daniel Jasperf7935112012-12-03 18:12:45 +000080 UnwrappedLineConsumer &Callback);
81
Manuel Klimek20e0af62015-05-06 11:56:29 +000082 void parse();
Daniel Jasperf7935112012-12-03 18:12:45 +000083
84private:
Manuel Klimek71814b42013-10-11 21:25:45 +000085 void reset();
Manuel Klimek1a18c402013-04-12 14:13:36 +000086 void parseFile();
87 void parseLevel(bool HasOpeningBrace);
Manuel Klimekb212f3b2013-10-12 22:46:56 +000088 void parseBlock(bool MustBeDeclaration, bool AddLevel = true,
89 bool MunchSemi = true);
Manuel Klimek516e0542013-09-04 13:25:30 +000090 void parseChildBlock();
Daniel Jasperf7935112012-12-03 18:12:45 +000091 void parsePPDirective();
Manuel Klimek1abf7892013-01-04 23:34:14 +000092 void parsePPDefine();
Manuel Klimek71814b42013-10-11 21:25:45 +000093 void parsePPIf(bool IfDef);
Alexander Kornienkof2e02122013-05-24 18:24:24 +000094 void parsePPElIf();
95 void parsePPElse();
96 void parsePPEndIf();
Manuel Klimek1abf7892013-01-04 23:34:14 +000097 void parsePPUnknown();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +000098 void readTokenWithJavaScriptASI();
Manuel Klimek6b9eeba2013-01-07 14:56:16 +000099 void parseStructuralElement();
Daniel Jasper3c883d12015-05-18 14:49:19 +0000100 bool tryToParseBracedList();
Krasimir Georgievff747be2017-06-27 13:43:07 +0000101 bool parseBracedList(bool ContinueOnSemicolons = false,
102 tok::TokenKind ClosingBraceKind = tok::r_brace);
Daniel Jasperf7935112012-12-03 18:12:45 +0000103 void parseParens();
Manuel Klimek9f0a4e52017-09-19 09:59:30 +0000104 void parseSquare(bool LambdaIntroducer = false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000105 void parseIfThenElse();
Daniel Jasper04a71a42014-05-08 11:58:24 +0000106 void parseTryCatch();
Alexander Kornienko37d6c942012-12-05 15:06:06 +0000107 void parseForOrWhileLoop();
Daniel Jasperf7935112012-12-03 18:12:45 +0000108 void parseDoWhile();
109 void parseLabel();
110 void parseCaseLabel();
111 void parseSwitch();
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000112 void parseNamespace();
Daniel Jasper6acf5132015-03-12 14:44:29 +0000113 void parseNew();
Daniel Jasperf7935112012-12-03 18:12:45 +0000114 void parseAccessSpecifier();
Daniel Jasper6f5a1932015-12-29 08:54:23 +0000115 bool parseEnum();
Daniel Jasper6be0f552014-11-13 15:56:28 +0000116 void parseJavaEnumBody();
Martin Probst1027fb82017-02-07 14:05:30 +0000117 // Parses a record (aka class) as a top level element. If ParseAsExpr is true,
118 // parses the record as a child block, i.e. if the class declaration is an
119 // expression.
120 void parseRecord(bool ParseAsExpr = false);
Ben Hamilton707e68f2018-05-30 15:21:38 +0000121 void parseObjCMethod();
Nico Weber8696a8d2013-01-09 21:15:03 +0000122 void parseObjCProtocolList();
123 void parseObjCUntilAtEnd();
Nico Weber2ce0ac52013-01-09 23:25:37 +0000124 void parseObjCInterfaceOrImplementation();
Nico Weberc068ff72018-01-23 17:10:25 +0000125 bool parseObjCProtocol();
Daniel Jasperfca735c2015-02-19 16:14:18 +0000126 void parseJavaScriptEs6ImportExport();
Francois Ferrand6f40e212018-10-02 16:37:51 +0000127 void parseStatementMacro();
Daniel Jasperb88b25f2013-12-23 07:29:06 +0000128 bool tryToParseLambda();
Manuel Klimekffdeb592013-09-03 15:10:01 +0000129 bool tryToParseLambdaIntroducer();
Daniel Jasperc03e16a2014-05-08 09:25:39 +0000130 void tryToParseJSFunction();
Daniel Jasperf7935112012-12-03 18:12:45 +0000131 void addUnwrappedLine();
132 bool eof() const;
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000133 // LevelDifference is the difference of levels after and before the current
134 // token. For example:
135 // - if the token is '{' and opens a block, LevelDifference is 1.
136 // - if the token is '}' and closes a block, LevelDifference is -1.
137 void nextToken(int LevelDifference = 0);
138 void readToken(int LevelDifference = 0);
Krasimir Georgievf62f9582017-02-08 10:30:44 +0000139
140 // Decides which comment tokens should be added to the current line and which
141 // should be added as comments before the next token.
142 //
143 // Comments specifies the sequence of comment tokens to analyze. They get
144 // either pushed to the current line or added to the comments before the next
145 // token.
146 //
147 // NextTok specifies the next token. A null pointer NextTok is supported, and
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000148 // signifies either the absence of a next token, or that the next token
Krasimir Georgievf62f9582017-02-08 10:30:44 +0000149 // shouldn't be taken into accunt for the analysis.
150 void distributeComments(const SmallVectorImpl<FormatToken *> &Comments,
151 const FormatToken *NextTok);
152
153 // Adds the comment preceding the next token to unwrapped lines.
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000154 void flushComments(bool NewlineBeforeNext);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000155 void pushToken(FormatToken *Tok);
Daniel Jasper3c883d12015-05-18 14:49:19 +0000156 void calculateBraceTypes(bool ExpectClassBody = false);
Manuel Klimek68b03042014-04-14 09:14:11 +0000157
158 // Marks a conditional compilation edge (for example, an '#if', '#ifdef',
159 // '#else' or merge conflict marker). If 'Unreachable' is true, assumes
160 // this branch either cannot be taken (for example '#if false'), or should
161 // not be taken in this round.
162 void conditionalCompilationCondition(bool Unreachable);
163 void conditionalCompilationStart(bool Unreachable);
164 void conditionalCompilationAlternative();
165 void conditionalCompilationEnd();
166
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000167 bool isOnNewLine(const FormatToken &FormatTok);
Manuel Klimekab419912013-05-23 09:41:43 +0000168
Francois Ferranda98a95c2017-07-28 07:56:14 +0000169 // Compute hash of the current preprocessor branch.
170 // This is used to identify the different branches, and thus track if block
171 // open and close in the same branch.
172 size_t computePPHash() const;
173
Manuel Klimekef2cfb12013-01-05 22:14:16 +0000174 // FIXME: We are constantly running into bugs where Line.Level is incorrectly
175 // subtracted from beyond 0. Introduce a method to subtract from Line.Level
176 // and use that everywhere in the Parser.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000177 std::unique_ptr<UnwrappedLine> Line;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000178
179 // Comments are sorted into unwrapped lines by whether they are in the same
180 // line as the previous token, or not. If not, they belong to the next token.
181 // Since the next token might already be in a new unwrapped line, we need to
182 // store the comments belonging to that token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000183 SmallVector<FormatToken *, 1> CommentsBeforeNextToken;
184 FormatToken *FormatTok;
Manuel Klimek52b15152013-01-09 15:25:02 +0000185 bool MustBreakBeforeNextToken;
Daniel Jasperf7935112012-12-03 18:12:45 +0000186
Manuel Klimek05d82b72013-01-18 18:24:28 +0000187 // The parsed lines. Only added to through \c CurrentLines.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000188 SmallVector<UnwrappedLine, 8> Lines;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000189
190 // Preprocessor directives are parsed out-of-order from other unwrapped lines.
191 // Thus, we need to keep a list of preprocessor directives to be reported
Francois Ferranda98a95c2017-07-28 07:56:14 +0000192 // after an unwrapped line that has been started was finished.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000193 SmallVector<UnwrappedLine, 4> PreprocessorDirectives;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000194
195 // New unwrapped lines are added via CurrentLines.
196 // Usually points to \c &Lines. While parsing a preprocessor directive when
197 // there is an unfinished previous unwrapped line, will point to
198 // \c &PreprocessorDirectives.
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000199 SmallVectorImpl<UnwrappedLine> *CurrentLines;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000200
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000201 // We store for each line whether it must be a declaration depending on
202 // whether we are in a compound statement or not.
203 std::vector<bool> DeclarationScopeStack;
204
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000205 const FormatStyle &Style;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000206 const AdditionalKeywords &Keywords;
Martin Probst1027fb82017-02-07 14:05:30 +0000207
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000208 llvm::Regex CommentPragmasRegex;
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000209
Manuel Klimek1abf7892013-01-04 23:34:14 +0000210 FormatTokenSource *Tokens;
Daniel Jasperf7935112012-12-03 18:12:45 +0000211 UnwrappedLineConsumer &Callback;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000212
Manuel Klimekab419912013-05-23 09:41:43 +0000213 // FIXME: This is a temporary measure until we have reworked the ownership
214 // of the format tokens. The goal is to have the actual tokens created and
215 // owned outside of and handed into the UnwrappedLineParser.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000216 ArrayRef<FormatToken *> AllTokens;
Manuel Klimekab419912013-05-23 09:41:43 +0000217
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000218 // Represents preprocessor branch type, so we can find matching
219 // #if/#else/#endif directives.
220 enum PPBranchKind {
Daniel Jasper3ac9b9e2013-07-08 14:34:09 +0000221 PP_Conditional, // Any #if, #ifdef, #ifndef, #elif, block outside #if 0
222 PP_Unreachable // #if 0 or a conditional preprocessor block inside #if 0
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000223 };
224
Francois Ferranda98a95c2017-07-28 07:56:14 +0000225 struct PPBranch {
226 PPBranch(PPBranchKind Kind, size_t Line) : Kind(Kind), Line(Line) {}
227 PPBranchKind Kind;
228 size_t Line;
229 };
230
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000231 // Keeps a stack of currently active preprocessor branching directives.
Francois Ferranda98a95c2017-07-28 07:56:14 +0000232 SmallVector<PPBranch, 16> PPStack;
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000233
Manuel Klimek71814b42013-10-11 21:25:45 +0000234 // The \c UnwrappedLineParser re-parses the code for each combination
235 // of preprocessor branches that can be taken.
236 // To that end, we take the same branch (#if, #else, or one of the #elif
237 // branches) for each nesting level of preprocessor branches.
238 // \c PPBranchLevel stores the current nesting level of preprocessor
239 // branches during one pass over the code.
240 int PPBranchLevel;
241
242 // Contains the current branch (#if, #else or one of the #elif branches)
243 // for each nesting level.
244 SmallVector<int, 8> PPLevelBranchIndex;
245
246 // Contains the maximum number of branches at each nesting level.
247 SmallVector<int, 8> PPLevelBranchCount;
248
249 // Contains the number of branches per nesting level we are currently
250 // in while parsing a preprocessor branch sequence.
251 // This is used to update PPLevelBranchCount at the end of a branch
252 // sequence.
253 std::stack<int> PPChainBranchIndex;
254
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000255 // Include guard search state. Used to fixup preprocessor indent levels
256 // so that include guards do not participate in indentation.
257 enum IncludeGuardState {
258 IG_Inited, // Search started, looking for #ifndef.
259 IG_IfNdefed, // #ifndef found, IncludeGuardToken points to condition.
260 IG_Defined, // Matching #define found, checking other requirements.
261 IG_Found, // All requirements met, need to fix indents.
262 IG_Rejected, // Search failed or never started.
263 };
264
265 // Current state of include guard search.
266 IncludeGuardState IncludeGuard;
267
268 // Points to the #ifndef condition for a potential include guard. Null unless
269 // IncludeGuardState == IG_IfNdefed.
270 FormatToken *IncludeGuardToken;
271
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000272 // Contains the first start column where the source begins. This is zero for
273 // normal source code and may be nonzero when formatting a code fragment that
274 // does not start at the beginning of the file.
275 unsigned FirstStartColumn;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000276
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000277 friend class ScopedLineState;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000278 friend class CompoundStatementIndenter;
Daniel Jasperf7935112012-12-03 18:12:45 +0000279};
280
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000281struct UnwrappedLineNode {
Craig Topper2145bc02014-05-09 08:15:10 +0000282 UnwrappedLineNode() : Tok(nullptr) {}
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000283 UnwrappedLineNode(FormatToken *Tok) : Tok(Tok) {}
284
285 FormatToken *Tok;
286 SmallVector<UnwrappedLine, 0> Children;
287};
288
Manuel Klimek89628f62017-09-20 09:51:03 +0000289inline UnwrappedLine::UnwrappedLine()
290 : Level(0), InPPDirective(false), MustBeDeclaration(false),
291 MatchingOpeningBlockLineIndex(kInvalidIndex) {}
Douglas Gregor7cfed212013-09-05 18:28:53 +0000292
Daniel Jasper8d1832e2013-01-07 13:26:07 +0000293} // end namespace format
294} // end namespace clang
Daniel Jasperf7935112012-12-03 18:12:45 +0000295
Benjamin Kramer2f5db8b2014-08-13 16:25:19 +0000296#endif