blob: b8608dcac9c7ec093168d8275cb50c112ddfc075 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// \brief This file contains the implementation of the UnwrappedLineParser,
12/// which turns a stream of tokens into UnwrappedLines.
13///
Daniel Jasperf7935112012-12-03 18:12:45 +000014//===----------------------------------------------------------------------===//
15
Chandler Carruth4b417452013-01-19 08:09:44 +000016#include "UnwrappedLineParser.h"
Benjamin Kramer33335df2015-03-01 21:36:40 +000017#include "llvm/ADT/STLExtras.h"
Manuel Klimekab3dc002013-01-16 12:31:12 +000018#include "llvm/Support/Debug.h"
Benjamin Kramer53f5e892015-03-23 18:05:43 +000019#include "llvm/Support/raw_ostream.h"
Manuel Klimekab3dc002013-01-16 12:31:12 +000020
Martin Probst7e0f25b2017-11-25 09:19:42 +000021#include <algorithm>
22
Chandler Carruth10346662014-04-22 03:17:02 +000023#define DEBUG_TYPE "format-parser"
24
Daniel Jasperf7935112012-12-03 18:12:45 +000025namespace clang {
26namespace format {
27
Manuel Klimek15dfe7a2013-05-28 11:55:06 +000028class FormatTokenSource {
29public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000030 virtual ~FormatTokenSource() {}
Manuel Klimek15dfe7a2013-05-28 11:55:06 +000031 virtual FormatToken *getNextToken() = 0;
32
33 virtual unsigned getPosition() = 0;
34 virtual FormatToken *setPosition(unsigned Position) = 0;
35};
36
Craig Topper69665e12013-07-01 04:21:54 +000037namespace {
38
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000039class ScopedDeclarationState {
40public:
41 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
42 bool MustBeDeclaration)
43 : Line(Line), Stack(Stack) {
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000044 Line.MustBeDeclaration = MustBeDeclaration;
Manuel Klimek39080572013-01-23 11:03:04 +000045 Stack.push_back(MustBeDeclaration);
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000046 }
47 ~ScopedDeclarationState() {
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000048 Stack.pop_back();
Manuel Klimekc1237a82013-01-23 14:08:21 +000049 if (!Stack.empty())
50 Line.MustBeDeclaration = Stack.back();
51 else
52 Line.MustBeDeclaration = true;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000053 }
Daniel Jasper393564f2013-05-31 14:56:29 +000054
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000055private:
56 UnwrappedLine &Line;
57 std::vector<bool> &Stack;
58};
59
Krasimir Georgieva1c30932017-05-19 10:34:57 +000060static bool isLineComment(const FormatToken &FormatTok) {
Krasimir Georgiev410ed242017-11-10 12:50:09 +000061 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
Krasimir Georgieva1c30932017-05-19 10:34:57 +000062}
63
Krasimir Georgievea222a72017-05-22 10:07:56 +000064// Checks if \p FormatTok is a line comment that continues the line comment
65// \p Previous. The original column of \p MinColumnToken is used to determine
66// whether \p FormatTok is indented enough to the right to continue \p Previous.
67static bool continuesLineComment(const FormatToken &FormatTok,
68 const FormatToken *Previous,
69 const FormatToken *MinColumnToken) {
70 if (!Previous || !MinColumnToken)
71 return false;
72 unsigned MinContinueColumn =
73 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
74 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
75 isLineComment(*Previous) &&
76 FormatTok.OriginalColumn >= MinContinueColumn;
77}
78
Manuel Klimek1abf7892013-01-04 23:34:14 +000079class ScopedMacroState : public FormatTokenSource {
80public:
81 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
Manuel Klimek20e0af62015-05-06 11:56:29 +000082 FormatToken *&ResetToken)
Manuel Klimek1abf7892013-01-04 23:34:14 +000083 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
Manuel Klimek1a18c402013-04-12 14:13:36 +000084 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
Krasimir Georgieva1c30932017-05-19 10:34:57 +000085 Token(nullptr), PreviousToken(nullptr) {
Manuel Klimek1abf7892013-01-04 23:34:14 +000086 TokenSource = this;
Manuel Klimekef2cfb12013-01-05 22:14:16 +000087 Line.Level = 0;
Manuel Klimek1abf7892013-01-04 23:34:14 +000088 Line.InPPDirective = true;
89 }
90
Alexander Kornienko34eb2072015-04-11 02:00:23 +000091 ~ScopedMacroState() override {
Manuel Klimek1abf7892013-01-04 23:34:14 +000092 TokenSource = PreviousTokenSource;
93 ResetToken = Token;
94 Line.InPPDirective = false;
Manuel Klimekef2cfb12013-01-05 22:14:16 +000095 Line.Level = PreviousLineLevel;
Manuel Klimek1abf7892013-01-04 23:34:14 +000096 }
97
Craig Topperfb6b25b2014-03-15 04:29:04 +000098 FormatToken *getNextToken() override {
Manuel Klimek78725712013-01-07 10:03:37 +000099 // The \c UnwrappedLineParser guards against this by never calling
100 // \c getNextToken() after it has encountered the first eof token.
101 assert(!eof());
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000102 PreviousToken = Token;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000103 Token = PreviousTokenSource->getNextToken();
104 if (eof())
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000105 return getFakeEOF();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000106 return Token;
107 }
108
Craig Topperfb6b25b2014-03-15 04:29:04 +0000109 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
Manuel Klimekab419912013-05-23 09:41:43 +0000110
Craig Topperfb6b25b2014-03-15 04:29:04 +0000111 FormatToken *setPosition(unsigned Position) override {
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000112 PreviousToken = nullptr;
Manuel Klimekab419912013-05-23 09:41:43 +0000113 Token = PreviousTokenSource->setPosition(Position);
114 return Token;
115 }
116
Manuel Klimek1abf7892013-01-04 23:34:14 +0000117private:
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000118 bool eof() {
119 return Token && Token->HasUnescapedNewline &&
Krasimir Georgievea222a72017-05-22 10:07:56 +0000120 !continuesLineComment(*Token, PreviousToken,
121 /*MinColumnToken=*/PreviousToken);
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000122 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000123
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000124 FormatToken *getFakeEOF() {
125 static bool EOFInitialized = false;
126 static FormatToken FormatTok;
127 if (!EOFInitialized) {
128 FormatTok.Tok.startToken();
129 FormatTok.Tok.setKind(tok::eof);
130 EOFInitialized = true;
131 }
132 return &FormatTok;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000133 }
134
135 UnwrappedLine &Line;
136 FormatTokenSource *&TokenSource;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000137 FormatToken *&ResetToken;
Manuel Klimekef2cfb12013-01-05 22:14:16 +0000138 unsigned PreviousLineLevel;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000139 FormatTokenSource *PreviousTokenSource;
140
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000141 FormatToken *Token;
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000142 FormatToken *PreviousToken;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000143};
144
Craig Topper69665e12013-07-01 04:21:54 +0000145} // end anonymous namespace
146
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000147class ScopedLineState {
148public:
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000149 ScopedLineState(UnwrappedLineParser &Parser,
150 bool SwitchToPreprocessorLines = false)
David Blaikieefb6eb22014-08-09 20:02:07 +0000151 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000152 if (SwitchToPreprocessorLines)
153 Parser.CurrentLines = &Parser.PreprocessorDirectives;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000154 else if (!Parser.Line->Tokens.empty())
155 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
David Blaikieefb6eb22014-08-09 20:02:07 +0000156 PreBlockLine = std::move(Parser.Line);
157 Parser.Line = llvm::make_unique<UnwrappedLine>();
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000158 Parser.Line->Level = PreBlockLine->Level;
159 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000160 }
161
162 ~ScopedLineState() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000163 if (!Parser.Line->Tokens.empty()) {
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000164 Parser.addUnwrappedLine();
165 }
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000166 assert(Parser.Line->Tokens.empty());
David Blaikieefb6eb22014-08-09 20:02:07 +0000167 Parser.Line = std::move(PreBlockLine);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000168 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
169 Parser.MustBreakBeforeNextToken = true;
170 Parser.CurrentLines = OriginalLines;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000171 }
172
173private:
174 UnwrappedLineParser &Parser;
175
David Blaikieefb6eb22014-08-09 20:02:07 +0000176 std::unique_ptr<UnwrappedLine> PreBlockLine;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000177 SmallVectorImpl<UnwrappedLine> *OriginalLines;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000178};
179
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000180class CompoundStatementIndenter {
181public:
182 CompoundStatementIndenter(UnwrappedLineParser *Parser,
183 const FormatStyle &Style, unsigned &LineLevel)
184 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000185 if (Style.BraceWrapping.AfterControlStatement)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000186 Parser->addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000187 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000188 ++LineLevel;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000189 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000190 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000191
192private:
193 unsigned &LineLevel;
194 unsigned OldLineLevel;
195};
196
Craig Topper69665e12013-07-01 04:21:54 +0000197namespace {
198
Manuel Klimekab419912013-05-23 09:41:43 +0000199class IndexedTokenSource : public FormatTokenSource {
200public:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000201 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
Manuel Klimekab419912013-05-23 09:41:43 +0000202 : Tokens(Tokens), Position(-1) {}
203
Craig Topperfb6b25b2014-03-15 04:29:04 +0000204 FormatToken *getNextToken() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000205 ++Position;
206 return Tokens[Position];
207 }
208
Craig Topperfb6b25b2014-03-15 04:29:04 +0000209 unsigned getPosition() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000210 assert(Position >= 0);
211 return Position;
212 }
213
Craig Topperfb6b25b2014-03-15 04:29:04 +0000214 FormatToken *setPosition(unsigned P) override {
Manuel Klimekab419912013-05-23 09:41:43 +0000215 Position = P;
216 return Tokens[Position];
217 }
218
Manuel Klimek71814b42013-10-11 21:25:45 +0000219 void reset() { Position = -1; }
220
Manuel Klimekab419912013-05-23 09:41:43 +0000221private:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000222 ArrayRef<FormatToken *> Tokens;
Manuel Klimekab419912013-05-23 09:41:43 +0000223 int Position;
224};
225
Craig Topper69665e12013-07-01 04:21:54 +0000226} // end anonymous namespace
227
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000228UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000229 const AdditionalKeywords &Keywords,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000230 unsigned FirstStartColumn,
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000231 ArrayRef<FormatToken *> Tokens,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000232 UnwrappedLineConsumer &Callback)
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000233 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000234 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
235 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
Krasimir Georgievad47c902017-08-30 14:34:57 +0000236 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
237 IfNdefCondition(nullptr), FoundIncludeGuardStart(false),
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000238 IncludeGuardRejected(false), FirstStartColumn(FirstStartColumn) {}
Manuel Klimek71814b42013-10-11 21:25:45 +0000239
240void UnwrappedLineParser::reset() {
241 PPBranchLevel = -1;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000242 IfNdefCondition = nullptr;
243 FoundIncludeGuardStart = false;
244 IncludeGuardRejected = false;
Manuel Klimek71814b42013-10-11 21:25:45 +0000245 Line.reset(new UnwrappedLine);
246 CommentsBeforeNextToken.clear();
Craig Topper2145bc02014-05-09 08:15:10 +0000247 FormatTok = nullptr;
Manuel Klimek71814b42013-10-11 21:25:45 +0000248 MustBreakBeforeNextToken = false;
249 PreprocessorDirectives.clear();
250 CurrentLines = &Lines;
251 DeclarationScopeStack.clear();
Manuel Klimek71814b42013-10-11 21:25:45 +0000252 PPStack.clear();
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000253 Line->FirstStartColumn = FirstStartColumn;
Manuel Klimek71814b42013-10-11 21:25:45 +0000254}
Daniel Jasperf7935112012-12-03 18:12:45 +0000255
Manuel Klimek20e0af62015-05-06 11:56:29 +0000256void UnwrappedLineParser::parse() {
Manuel Klimekab419912013-05-23 09:41:43 +0000257 IndexedTokenSource TokenSource(AllTokens);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000258 Line->FirstStartColumn = FirstStartColumn;
Manuel Klimek71814b42013-10-11 21:25:45 +0000259 do {
260 DEBUG(llvm::dbgs() << "----\n");
261 reset();
262 Tokens = &TokenSource;
263 TokenSource.reset();
Daniel Jaspera79064a2013-03-01 18:11:39 +0000264
Manuel Klimek71814b42013-10-11 21:25:45 +0000265 readToken();
266 parseFile();
267 // Create line with eof token.
268 pushToken(FormatTok);
269 addUnwrappedLine();
270
271 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
272 E = Lines.end();
273 I != E; ++I) {
274 Callback.consumeUnwrappedLine(*I);
275 }
276 Callback.finishRun();
277 Lines.clear();
278 while (!PPLevelBranchIndex.empty() &&
Daniel Jasper53bd1672013-10-12 13:32:56 +0000279 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000280 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
281 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
282 }
283 if (!PPLevelBranchIndex.empty()) {
284 ++PPLevelBranchIndex.back();
285 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
286 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
287 }
288 } while (!PPLevelBranchIndex.empty());
Manuel Klimek1abf7892013-01-04 23:34:14 +0000289}
290
Manuel Klimek1a18c402013-04-12 14:13:36 +0000291void UnwrappedLineParser::parseFile() {
Daniel Jasper9326f912015-05-05 08:40:32 +0000292 // The top-level context in a file always has declarations, except for pre-
293 // processor directives and JavaScript files.
294 bool MustBeDeclaration =
295 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
296 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
297 MustBeDeclaration);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000298 if (Style.Language == FormatStyle::LK_TextProto)
299 parseBracedList();
300 else
301 parseLevel(/*HasOpeningBrace=*/false);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000302 // Make sure to format the remaining tokens.
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000303 flushComments(true);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000304 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000305}
306
Manuel Klimek1a18c402013-04-12 14:13:36 +0000307void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000308 bool SwitchLabelEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000309 do {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000310 tok::TokenKind kind = FormatTok->Tok.getKind();
311 if (FormatTok->Type == TT_MacroBlockBegin) {
312 kind = tok::l_brace;
313 } else if (FormatTok->Type == TT_MacroBlockEnd) {
314 kind = tok::r_brace;
315 }
316
317 switch (kind) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000318 case tok::comment:
Daniel Jaspere25509f2012-12-17 11:29:41 +0000319 nextToken();
320 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000321 break;
322 case tok::l_brace:
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000323 // FIXME: Add parameter whether this can happen - if this happens, we must
324 // be in a non-declaration context.
Daniel Jasperb86e2722015-08-24 13:23:37 +0000325 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
326 continue;
Nico Weber9096fc02013-06-26 00:30:14 +0000327 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000328 addUnwrappedLine();
329 break;
330 case tok::r_brace:
Manuel Klimek1a18c402013-04-12 14:13:36 +0000331 if (HasOpeningBrace)
332 return;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000333 nextToken();
334 addUnwrappedLine();
Manuel Klimek1058d982013-01-06 20:07:31 +0000335 break;
Daniel Jasper516d7972013-07-25 11:31:57 +0000336 case tok::kw_default:
337 case tok::kw_case:
Manuel Klimek89628f62017-09-20 09:51:03 +0000338 if (Style.Language == FormatStyle::LK_JavaScript &&
339 Line->MustBeDeclaration) {
Martin Probstf785fd92017-08-04 17:07:15 +0000340 // A 'case: string' style field declaration.
341 parseStructuralElement();
342 break;
343 }
Daniel Jasper72407622013-09-02 08:26:29 +0000344 if (!SwitchLabelEncountered &&
345 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
346 ++Line->Level;
Daniel Jasper516d7972013-07-25 11:31:57 +0000347 SwitchLabelEncountered = true;
348 parseStructuralElement();
349 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000350 default:
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000351 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +0000352 break;
353 }
354 } while (!eof());
355}
356
Daniel Jasperadba2aa2015-05-18 12:52:00 +0000357void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
Manuel Klimekab419912013-05-23 09:41:43 +0000358 // We'll parse forward through the tokens until we hit
359 // a closing brace or eof - note that getNextToken() will
360 // parse macros, so this will magically work inside macro
361 // definitions, too.
362 unsigned StoredPosition = Tokens->getPosition();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000363 FormatToken *Tok = FormatTok;
Manuel Klimek89628f62017-09-20 09:51:03 +0000364 const FormatToken *PrevTok = Tok->Previous;
Manuel Klimekab419912013-05-23 09:41:43 +0000365 // Keep a stack of positions of lbrace tokens. We will
366 // update information about whether an lbrace starts a
367 // braced init list or a different block during the loop.
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000368 SmallVector<FormatToken *, 8> LBraceStack;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000369 assert(Tok->Tok.is(tok::l_brace));
Manuel Klimekab419912013-05-23 09:41:43 +0000370 do {
Daniel Jaspereb65e912015-12-21 18:31:15 +0000371 // Get next non-comment token.
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000372 FormatToken *NextTok;
Daniel Jasperca7bd722013-07-01 16:43:38 +0000373 unsigned ReadTokens = 0;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000374 do {
375 NextTok = Tokens->getNextToken();
Daniel Jasperca7bd722013-07-01 16:43:38 +0000376 ++ReadTokens;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000377 } while (NextTok->is(tok::comment));
378
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000379 switch (Tok->Tok.getKind()) {
Manuel Klimekab419912013-05-23 09:41:43 +0000380 case tok::l_brace:
Martin Probst95ed8e72017-05-31 09:29:40 +0000381 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
Martin Probste8e27ca2017-11-25 09:33:47 +0000382 if (PrevTok->isOneOf(tok::colon, tok::less))
383 // A ':' indicates this code is in a type, or a braced list
384 // following a label in an object literal ({a: {b: 1}}).
385 // A '<' could be an object used in a comparison, but that is nonsense
386 // code (can never return true), so more likely it is a generic type
387 // argument (`X<{a: string; b: number}>`).
388 // The code below could be confused by semicolons between the
389 // individual members in a type member list, which would normally
390 // trigger BK_Block. In both cases, this must be parsed as an inline
391 // braced init.
Martin Probst95ed8e72017-05-31 09:29:40 +0000392 Tok->BlockKind = BK_BracedInit;
393 else if (PrevTok->is(tok::r_paren))
394 // `) { }` can only occur in function or method declarations in JS.
395 Tok->BlockKind = BK_Block;
396 } else {
Daniel Jasperb9a49902016-01-09 15:56:28 +0000397 Tok->BlockKind = BK_Unknown;
Martin Probst95ed8e72017-05-31 09:29:40 +0000398 }
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000399 LBraceStack.push_back(Tok);
Manuel Klimekab419912013-05-23 09:41:43 +0000400 break;
401 case tok::r_brace:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000402 if (LBraceStack.empty())
403 break;
404 if (LBraceStack.back()->BlockKind == BK_Unknown) {
405 bool ProbablyBracedList = false;
406 if (Style.Language == FormatStyle::LK_Proto) {
407 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
408 } else {
409 // Using OriginalColumn to distinguish between ObjC methods and
410 // binary operators is a bit hacky.
411 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
412 NextTok->OriginalColumn == 0;
Daniel Jasper91b032a2014-05-22 12:46:38 +0000413
Daniel Jasperb9a49902016-01-09 15:56:28 +0000414 // If there is a comma, semicolon or right paren after the closing
415 // brace, we assume this is a braced initializer list. Note that
416 // regardless how we mark inner braces here, we will overwrite the
417 // BlockKind later if we parse a braced list (where all blocks
418 // inside are by default braced lists), or when we explicitly detect
419 // blocks (for example while parsing lambdas).
Martin Probst95ed8e72017-05-31 09:29:40 +0000420 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
421 // braced list in JS.
Daniel Jasperb9a49902016-01-09 15:56:28 +0000422 ProbablyBracedList =
Daniel Jasperacffeb82016-03-05 18:34:26 +0000423 (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probste1e12a72016-08-19 14:35:01 +0000424 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
425 Keywords.kw_as)) ||
Martin Probstb7fb2672017-05-10 13:53:29 +0000426 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000427 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
428 tok::r_paren, tok::r_square, tok::l_brace,
Martin Probstb7fb2672017-05-10 13:53:29 +0000429 tok::l_square, tok::ellipsis) ||
Daniel Jaspere4ada022016-12-13 10:05:03 +0000430 (NextTok->is(tok::identifier) &&
431 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000432 (NextTok->is(tok::semi) &&
433 (!ExpectClassBody || LBraceStack.size() != 1)) ||
434 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
Manuel Klimekab419912013-05-23 09:41:43 +0000435 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000436 if (ProbablyBracedList) {
437 Tok->BlockKind = BK_BracedInit;
438 LBraceStack.back()->BlockKind = BK_BracedInit;
439 } else {
440 Tok->BlockKind = BK_Block;
441 LBraceStack.back()->BlockKind = BK_Block;
442 }
Manuel Klimekab419912013-05-23 09:41:43 +0000443 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000444 LBraceStack.pop_back();
Manuel Klimekab419912013-05-23 09:41:43 +0000445 break;
Daniel Jasperac7e34e2014-03-13 10:11:17 +0000446 case tok::at:
Manuel Klimekab419912013-05-23 09:41:43 +0000447 case tok::semi:
448 case tok::kw_if:
449 case tok::kw_while:
450 case tok::kw_for:
451 case tok::kw_switch:
452 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +0000453 case tok::kw___try:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000454 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000455 LBraceStack.back()->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000456 break;
457 default:
458 break;
459 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000460 PrevTok = Tok;
Manuel Klimekab419912013-05-23 09:41:43 +0000461 Tok = NextTok;
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000462 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
Daniel Jasperb9a49902016-01-09 15:56:28 +0000463
Manuel Klimekab419912013-05-23 09:41:43 +0000464 // Assume other blocks for all unclosed opening braces.
465 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000466 if (LBraceStack[i]->BlockKind == BK_Unknown)
467 LBraceStack[i]->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000468 }
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000469
Manuel Klimekab419912013-05-23 09:41:43 +0000470 FormatTok = Tokens->setPosition(StoredPosition);
471}
472
Francois Ferranda98a95c2017-07-28 07:56:14 +0000473template <class T>
474static inline void hash_combine(std::size_t &seed, const T &v) {
475 std::hash<T> hasher;
476 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
477}
478
479size_t UnwrappedLineParser::computePPHash() const {
480 size_t h = 0;
481 for (const auto &i : PPStack) {
482 hash_combine(h, size_t(i.Kind));
483 hash_combine(h, i.Line);
484 }
485 return h;
486}
487
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000488void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
489 bool MunchSemi) {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000490 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
491 "'{' or macro block token expected");
492 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
Daniel Jaspereb65e912015-12-21 18:31:15 +0000493 FormatTok->BlockKind = BK_Block;
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000494
Francois Ferranda98a95c2017-07-28 07:56:14 +0000495 size_t PPStartHash = computePPHash();
496
Daniel Jasper516d7972013-07-25 11:31:57 +0000497 unsigned InitialLevel = Line->Level;
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000498 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
Daniel Jasperf7935112012-12-03 18:12:45 +0000499
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000500 if (MacroBlock && FormatTok->is(tok::l_paren))
501 parseParens();
502
Francois Ferranda98a95c2017-07-28 07:56:14 +0000503 size_t NbPreprocessorDirectives =
504 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000505 addUnwrappedLine();
Francois Ferranda98a95c2017-07-28 07:56:14 +0000506 size_t OpeningLineIndex =
507 CurrentLines->empty()
508 ? (UnwrappedLine::kInvalidIndex)
509 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
Daniel Jasperf7935112012-12-03 18:12:45 +0000510
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000511 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
512 MustBeDeclaration);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000513 if (AddLevel)
514 ++Line->Level;
Nico Weber9096fc02013-06-26 00:30:14 +0000515 parseLevel(/*HasOpeningBrace=*/true);
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000516
Marianne Mailhot-Sarrasin03137c62016-04-14 14:56:49 +0000517 if (eof())
518 return;
519
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000520 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
521 : !FormatTok->is(tok::r_brace)) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000522 Line->Level = InitialLevel;
Daniel Jaspereb65e912015-12-21 18:31:15 +0000523 FormatTok->BlockKind = BK_Block;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000524 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000525 }
Alexander Kornienko0ea8e102012-12-04 15:40:36 +0000526
Francois Ferranda98a95c2017-07-28 07:56:14 +0000527 size_t PPEndHash = computePPHash();
528
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000529 // Munch the closing brace.
530 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000531
532 if (MacroBlock && FormatTok->is(tok::l_paren))
533 parseParens();
534
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000535 if (MunchSemi && FormatTok->Tok.is(tok::semi))
536 nextToken();
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000537 Line->Level = InitialLevel;
Francois Ferranda98a95c2017-07-28 07:56:14 +0000538
539 if (PPStartHash == PPEndHash) {
540 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
541 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
542 // Update the opening line to add the forward reference as well
543 (*CurrentLines)[OpeningLineIndex].MatchingOpeningBlockLineIndex =
544 CurrentLines->size() - 1;
545 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000546 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000547}
548
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000549static bool isGoogScope(const UnwrappedLine &Line) {
Daniel Jasper616de8642014-11-23 16:46:28 +0000550 // FIXME: Closure-library specific stuff should not be hard-coded but be
551 // configurable.
Daniel Jasper4a39c842014-05-06 13:54:10 +0000552 if (Line.Tokens.size() < 4)
553 return false;
554 auto I = Line.Tokens.begin();
555 if (I->Tok->TokenText != "goog")
556 return false;
557 ++I;
558 if (I->Tok->isNot(tok::period))
559 return false;
560 ++I;
561 if (I->Tok->TokenText != "scope")
562 return false;
563 ++I;
564 return I->Tok->is(tok::l_paren);
565}
566
Martin Probst101ec892017-05-09 20:04:09 +0000567static bool isIIFE(const UnwrappedLine &Line,
568 const AdditionalKeywords &Keywords) {
569 // Look for the start of an immediately invoked anonymous function.
570 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
571 // This is commonly done in JavaScript to create a new, anonymous scope.
572 // Example: (function() { ... })()
573 if (Line.Tokens.size() < 3)
574 return false;
575 auto I = Line.Tokens.begin();
576 if (I->Tok->isNot(tok::l_paren))
577 return false;
578 ++I;
579 if (I->Tok->isNot(Keywords.kw_function))
580 return false;
581 ++I;
582 return I->Tok->is(tok::l_paren);
583}
584
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000585static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
586 const FormatToken &InitialToken) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000587 if (InitialToken.is(tok::kw_namespace))
588 return Style.BraceWrapping.AfterNamespace;
589 if (InitialToken.is(tok::kw_class))
590 return Style.BraceWrapping.AfterClass;
591 if (InitialToken.is(tok::kw_union))
592 return Style.BraceWrapping.AfterUnion;
593 if (InitialToken.is(tok::kw_struct))
594 return Style.BraceWrapping.AfterStruct;
595 return false;
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000596}
597
Manuel Klimek516e0542013-09-04 13:25:30 +0000598void UnwrappedLineParser::parseChildBlock() {
599 FormatTok->BlockKind = BK_Block;
600 nextToken();
601 {
Manuel Klimek89628f62017-09-20 09:51:03 +0000602 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
603 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
Manuel Klimek516e0542013-09-04 13:25:30 +0000604 ScopedLineState LineState(*this);
605 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
606 /*MustBeDeclaration=*/false);
Martin Probst101ec892017-05-09 20:04:09 +0000607 Line->Level += SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000608 parseLevel(/*HasOpeningBrace=*/true);
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000609 flushComments(isOnNewLine(*FormatTok));
Martin Probst101ec892017-05-09 20:04:09 +0000610 Line->Level -= SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000611 }
612 nextToken();
613}
614
Daniel Jasperf7935112012-12-03 18:12:45 +0000615void UnwrappedLineParser::parsePPDirective() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000616 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
Manuel Klimek20e0af62015-05-06 11:56:29 +0000617 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000618 nextToken();
619
Craig Topper2145bc02014-05-09 08:15:10 +0000620 if (!FormatTok->Tok.getIdentifierInfo()) {
Manuel Klimek591b5802013-01-31 15:58:48 +0000621 parsePPUnknown();
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000622 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000623 }
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000624
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000625 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000626 case tok::pp_define:
627 parsePPDefine();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000628 return;
629 case tok::pp_if:
Manuel Klimek71814b42013-10-11 21:25:45 +0000630 parsePPIf(/*IfDef=*/false);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000631 break;
632 case tok::pp_ifdef:
633 case tok::pp_ifndef:
Manuel Klimek71814b42013-10-11 21:25:45 +0000634 parsePPIf(/*IfDef=*/true);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000635 break;
636 case tok::pp_else:
637 parsePPElse();
638 break;
639 case tok::pp_elif:
640 parsePPElIf();
641 break;
642 case tok::pp_endif:
643 parsePPEndIf();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000644 break;
645 default:
646 parsePPUnknown();
647 break;
648 }
649}
650
Manuel Klimek68b03042014-04-14 09:14:11 +0000651void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
Francois Ferranda98a95c2017-07-28 07:56:14 +0000652 size_t Line = CurrentLines->size();
653 if (CurrentLines == &PreprocessorDirectives)
654 Line += Lines.size();
655
656 if (Unreachable ||
657 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
658 PPStack.push_back({PP_Unreachable, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000659 else
Francois Ferranda98a95c2017-07-28 07:56:14 +0000660 PPStack.push_back({PP_Conditional, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000661}
662
Manuel Klimek68b03042014-04-14 09:14:11 +0000663void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000664 ++PPBranchLevel;
665 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
666 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
667 PPLevelBranchIndex.push_back(0);
668 PPLevelBranchCount.push_back(0);
669 }
670 PPChainBranchIndex.push(0);
Manuel Klimek68b03042014-04-14 09:14:11 +0000671 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
672 conditionalCompilationCondition(Unreachable || Skip);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000673}
674
Manuel Klimek68b03042014-04-14 09:14:11 +0000675void UnwrappedLineParser::conditionalCompilationAlternative() {
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000676 if (!PPStack.empty())
677 PPStack.pop_back();
Manuel Klimek71814b42013-10-11 21:25:45 +0000678 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
679 if (!PPChainBranchIndex.empty())
680 ++PPChainBranchIndex.top();
Manuel Klimek68b03042014-04-14 09:14:11 +0000681 conditionalCompilationCondition(
682 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
683 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000684}
685
Manuel Klimek68b03042014-04-14 09:14:11 +0000686void UnwrappedLineParser::conditionalCompilationEnd() {
Manuel Klimek71814b42013-10-11 21:25:45 +0000687 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
688 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
689 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000690 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
691 }
692 }
Manuel Klimek14bd9172014-01-29 08:49:02 +0000693 // Guard against #endif's without #if.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000694 if (PPBranchLevel > -1)
Manuel Klimek14bd9172014-01-29 08:49:02 +0000695 --PPBranchLevel;
Manuel Klimek71814b42013-10-11 21:25:45 +0000696 if (!PPChainBranchIndex.empty())
697 PPChainBranchIndex.pop();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000698 if (!PPStack.empty())
699 PPStack.pop_back();
Manuel Klimek68b03042014-04-14 09:14:11 +0000700}
701
702void UnwrappedLineParser::parsePPIf(bool IfDef) {
Daniel Jasper62703eb2017-03-01 11:10:11 +0000703 bool IfNDef = FormatTok->is(tok::pp_ifndef);
Manuel Klimek68b03042014-04-14 09:14:11 +0000704 nextToken();
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000705 bool Unreachable = false;
706 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
707 Unreachable = true;
Daniel Jasper62703eb2017-03-01 11:10:11 +0000708 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000709 Unreachable = true;
710 conditionalCompilationStart(Unreachable);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000711 FormatToken *IfCondition = FormatTok;
712 // If there's a #ifndef on the first line, and the only lines before it are
713 // comments, it could be an include guard.
714 bool MaybeIncludeGuard = IfNDef;
715 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
716 for (auto &Line : Lines) {
717 if (!Line.Tokens.front().Tok->is(tok::comment)) {
718 MaybeIncludeGuard = false;
719 IncludeGuardRejected = true;
720 break;
721 }
722 }
723 }
724 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000725 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000726 ++PPBranchLevel;
727 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
728 IfNdefCondition = IfCondition;
Manuel Klimek68b03042014-04-14 09:14:11 +0000729}
730
731void UnwrappedLineParser::parsePPElse() {
Krasimir Georgievad47c902017-08-30 14:34:57 +0000732 // If a potential include guard has an #else, it's not an include guard.
733 if (FoundIncludeGuardStart && PPBranchLevel == 0)
734 FoundIncludeGuardStart = false;
Manuel Klimek68b03042014-04-14 09:14:11 +0000735 conditionalCompilationAlternative();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000736 if (PPBranchLevel > -1)
737 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000738 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000739 ++PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000740}
741
742void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
743
744void UnwrappedLineParser::parsePPEndIf() {
745 conditionalCompilationEnd();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000746 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000747 // If the #endif of a potential include guard is the last thing in the file,
748 // then we count it as a real include guard and subtract one from every
749 // preprocessor indent.
750 unsigned TokenPosition = Tokens->getPosition();
751 FormatToken *PeekNext = AllTokens[TokenPosition];
Daniel Jasper4df130f2017-09-04 13:33:52 +0000752 if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) &&
753 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
754 for (auto &Line : Lines)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000755 if (Line.InPPDirective && Line.Level > 0)
756 --Line.Level;
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000757}
758
Manuel Klimek1abf7892013-01-04 23:34:14 +0000759void UnwrappedLineParser::parsePPDefine() {
760 nextToken();
761
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000762 if (FormatTok->Tok.getKind() != tok::identifier) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000763 parsePPUnknown();
764 return;
765 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000766 if (IfNdefCondition && IfNdefCondition->TokenText == FormatTok->TokenText) {
767 FoundIncludeGuardStart = true;
768 for (auto &Line : Lines) {
769 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
770 FoundIncludeGuardStart = false;
771 break;
772 }
773 }
774 }
775 IfNdefCondition = nullptr;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000776 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000777 if (FormatTok->Tok.getKind() == tok::l_paren &&
778 FormatTok->WhitespaceRange.getBegin() ==
779 FormatTok->WhitespaceRange.getEnd()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000780 parseParens();
781 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000782 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
783 Line->Level += PPBranchLevel + 1;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000784 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000785 ++Line->Level;
Manuel Klimek1b896292013-01-07 09:34:28 +0000786
787 // Errors during a preprocessor directive can only affect the layout of the
788 // preprocessor directive, and thus we ignore them. An alternative approach
789 // would be to use the same approach we use on the file level (no
790 // re-indentation if there was a structural error) within the macro
791 // definition.
Manuel Klimek1abf7892013-01-04 23:34:14 +0000792 parseFile();
793}
794
795void UnwrappedLineParser::parsePPUnknown() {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000796 do {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000797 nextToken();
798 } while (!eof());
Krasimir Georgievad47c902017-08-30 14:34:57 +0000799 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
800 Line->Level += PPBranchLevel + 1;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000801 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000802 IfNdefCondition = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000803}
804
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000805// Here we blacklist certain tokens that are not usually the first token in an
806// unwrapped line. This is used in attempt to distinguish macro calls without
807// trailing semicolons from other constructs split to several lines.
Benjamin Kramer8407df72015-03-09 16:47:52 +0000808static bool tokenCanStartNewLine(const clang::Token &Tok) {
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000809 // Semicolon can be a null-statement, l_square can be a start of a macro or
810 // a C++11 attribute, but this doesn't seem to be common.
811 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
812 Tok.isNot(tok::l_square) &&
813 // Tokens that can only be used as binary operators and a part of
814 // overloaded operator names.
815 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
816 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
817 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
818 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
819 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
820 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
821 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
822 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
823 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
824 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
825 Tok.isNot(tok::lesslessequal) &&
826 // Colon is used in labels, base class lists, initializer lists,
827 // range-based for loops, ternary operator, but should never be the
828 // first token in an unwrapped line.
Daniel Jasper5ebb2f32014-05-21 13:08:17 +0000829 Tok.isNot(tok::colon) &&
830 // 'noexcept' is a trailing annotation.
831 Tok.isNot(tok::kw_noexcept);
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000832}
833
Martin Probst533965c2016-04-19 18:19:06 +0000834static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
835 const FormatToken *FormatTok) {
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000836 // FIXME: This returns true for C/C++ keywords like 'struct'.
837 return FormatTok->is(tok::identifier) &&
838 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
Martin Probst3dbbefa2016-11-10 16:21:02 +0000839 !FormatTok->isOneOf(
840 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
841 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
842 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
843 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
844 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
Manuel Klimek89628f62017-09-20 09:51:03 +0000845 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
846 Keywords.kw_from));
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000847}
848
Martin Probst533965c2016-04-19 18:19:06 +0000849static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
850 const FormatToken *FormatTok) {
Martin Probstb9316ff2016-09-18 17:21:52 +0000851 return FormatTok->Tok.isLiteral() ||
852 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
853 mustBeJSIdent(Keywords, FormatTok);
Martin Probst533965c2016-04-19 18:19:06 +0000854}
855
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000856// isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
857// when encountered after a value (see mustBeJSIdentOrValue).
858static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
859 const FormatToken *FormatTok) {
860 return FormatTok->isOneOf(
Martin Probst5f8445b2016-04-24 22:05:09 +0000861 tok::kw_return, Keywords.kw_yield,
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000862 // conditionals
863 tok::kw_if, tok::kw_else,
864 // loops
865 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
866 // switch/case
867 tok::kw_switch, tok::kw_case,
868 // exceptions
869 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
870 // declaration
871 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
Martin Probst5f8445b2016-04-24 22:05:09 +0000872 Keywords.kw_async, Keywords.kw_function,
873 // import/export
874 Keywords.kw_import, tok::kw_export);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000875}
876
877// readTokenWithJavaScriptASI reads the next token and terminates the current
878// line if JavaScript Automatic Semicolon Insertion must
879// happen between the current token and the next token.
880//
881// This method is conservative - it cannot cover all edge cases of JavaScript,
882// but only aims to correctly handle certain well known cases. It *must not*
883// return true in speculative cases.
884void UnwrappedLineParser::readTokenWithJavaScriptASI() {
885 FormatToken *Previous = FormatTok;
886 readToken();
887 FormatToken *Next = FormatTok;
888
889 bool IsOnSameLine =
890 CommentsBeforeNextToken.empty()
891 ? Next->NewlinesBefore == 0
892 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
893 if (IsOnSameLine)
894 return;
895
896 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
Martin Probst717f6dc2016-10-21 05:11:38 +0000897 bool PreviousStartsTemplateExpr =
898 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
Martin Probst7e0f25b2017-11-25 09:19:42 +0000899 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
900 // If the line contains an '@' sign, the previous token might be an
901 // annotation, which can precede another identifier/value.
902 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
903 [](UnwrappedLineNode &LineNode) {
904 return LineNode.Tok->is(tok::at);
905 }) != Line->Tokens.end();
906 if (HasAt)
Martin Probstbbffeac2016-04-11 07:35:57 +0000907 return;
908 }
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000909 if (Next->is(tok::exclaim) && PreviousMustBeValue)
Martin Probstd40bca42017-01-09 08:56:36 +0000910 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000911 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
Martin Probst717f6dc2016-10-21 05:11:38 +0000912 bool NextEndsTemplateExpr =
913 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
914 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
915 (PreviousMustBeValue ||
916 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
917 tok::minusminus)))
Martin Probstd40bca42017-01-09 08:56:36 +0000918 return addUnwrappedLine();
Martin Probst0a19d432017-08-09 15:19:16 +0000919 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
920 isJSDeclOrStmt(Keywords, Next))
Martin Probstd40bca42017-01-09 08:56:36 +0000921 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000922}
923
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000924void UnwrappedLineParser::parseStructuralElement() {
Daniel Jasper498f5582015-12-25 08:53:31 +0000925 assert(!FormatTok->is(tok::l_brace));
926 if (Style.Language == FormatStyle::LK_TableGen &&
927 FormatTok->is(tok::pp_include)) {
928 nextToken();
929 if (FormatTok->is(tok::string_literal))
930 nextToken();
931 addUnwrappedLine();
932 return;
933 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000934 switch (FormatTok->Tok.getKind()) {
Nico Weber04e9f1a2013-01-07 19:05:19 +0000935 case tok::at:
936 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000937 if (FormatTok->Tok.is(tok::l_brace)) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000938 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +0000939 parseBracedList();
940 break;
941 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000942 switch (FormatTok->Tok.getObjCKeywordID()) {
Nico Weber04e9f1a2013-01-07 19:05:19 +0000943 case tok::objc_public:
944 case tok::objc_protected:
945 case tok::objc_package:
946 case tok::objc_private:
947 return parseAccessSpecifier();
Nico Weber7eecf4b2013-01-09 20:25:35 +0000948 case tok::objc_interface:
Nico Weber2ce0ac52013-01-09 23:25:37 +0000949 case tok::objc_implementation:
950 return parseObjCInterfaceOrImplementation();
Nico Weber8696a8d2013-01-09 21:15:03 +0000951 case tok::objc_protocol:
952 return parseObjCProtocol();
Nico Weberd8ffe752013-01-09 21:42:32 +0000953 case tok::objc_end:
954 return; // Handled by the caller.
Nico Weber51306d22013-01-10 00:25:19 +0000955 case tok::objc_optional:
956 case tok::objc_required:
957 nextToken();
958 addUnwrappedLine();
959 return;
Nico Weber45c48122015-06-28 01:06:16 +0000960 case tok::objc_autoreleasepool:
961 nextToken();
962 if (FormatTok->Tok.is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000963 if (Style.BraceWrapping.AfterObjCDeclaration)
Nico Weber45c48122015-06-28 01:06:16 +0000964 addUnwrappedLine();
965 parseBlock(/*MustBeDeclaration=*/false);
966 }
967 addUnwrappedLine();
968 return;
Nico Weber33381f52015-02-07 01:57:32 +0000969 case tok::objc_try:
970 // This branch isn't strictly necessary (the kw_try case below would
971 // do this too after the tok::at is parsed above). But be explicit.
972 parseTryCatch();
973 return;
Nico Weber04e9f1a2013-01-07 19:05:19 +0000974 default:
975 break;
976 }
977 break;
Daniel Jasper8f463652014-08-26 23:15:12 +0000978 case tok::kw_asm:
Daniel Jasper8f463652014-08-26 23:15:12 +0000979 nextToken();
980 if (FormatTok->is(tok::l_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000981 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper2337f282015-01-12 10:14:56 +0000982 nextToken();
Daniel Jasper4429f142014-08-27 17:16:46 +0000983 while (FormatTok && FormatTok->isNot(tok::eof)) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000984 if (FormatTok->is(tok::r_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000985 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper8f463652014-08-26 23:15:12 +0000986 nextToken();
Daniel Jasper790d4f92015-05-11 11:59:46 +0000987 addUnwrappedLine();
Daniel Jasper8f463652014-08-26 23:15:12 +0000988 break;
989 }
Daniel Jasper2337f282015-01-12 10:14:56 +0000990 FormatTok->Finalized = true;
Daniel Jasper8f463652014-08-26 23:15:12 +0000991 nextToken();
992 }
993 }
994 break;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000995 case tok::kw_namespace:
996 parseNamespace();
997 return;
Dmitri Gribenko58d64e22012-12-30 21:27:25 +0000998 case tok::kw_inline:
999 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001000 if (FormatTok->Tok.is(tok::kw_namespace)) {
Dmitri Gribenko58d64e22012-12-30 21:27:25 +00001001 parseNamespace();
1002 return;
1003 }
1004 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001005 case tok::kw_public:
1006 case tok::kw_protected:
1007 case tok::kw_private:
Daniel Jasper83709082015-02-18 17:14:05 +00001008 if (Style.Language == FormatStyle::LK_Java ||
1009 Style.Language == FormatStyle::LK_JavaScript)
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001010 nextToken();
1011 else
1012 parseAccessSpecifier();
Daniel Jasperf7935112012-12-03 18:12:45 +00001013 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001014 case tok::kw_if:
1015 parseIfThenElse();
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 return;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001017 case tok::kw_for:
1018 case tok::kw_while:
1019 parseForOrWhileLoop();
1020 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001021 case tok::kw_do:
1022 parseDoWhile();
1023 return;
1024 case tok::kw_switch:
Martin Probstf785fd92017-08-04 17:07:15 +00001025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1026 // 'switch: string' field declaration.
1027 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001028 parseSwitch();
1029 return;
1030 case tok::kw_default:
Martin Probstf785fd92017-08-04 17:07:15 +00001031 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1032 // 'default: string' field declaration.
1033 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001034 nextToken();
1035 parseLabel();
1036 return;
1037 case tok::kw_case:
Martin Probstf785fd92017-08-04 17:07:15 +00001038 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1039 // 'case: string' field declaration.
1040 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001041 parseCaseLabel();
1042 return;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001043 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +00001044 case tok::kw___try:
Daniel Jasper04a71a42014-05-08 11:58:24 +00001045 parseTryCatch();
1046 return;
Manuel Klimekae610d12013-01-21 14:32:05 +00001047 case tok::kw_extern:
1048 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001049 if (FormatTok->Tok.is(tok::string_literal)) {
Manuel Klimekae610d12013-01-21 14:32:05 +00001050 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001051 if (FormatTok->Tok.is(tok::l_brace)) {
Krasimir Georgievd6ce9372017-09-15 11:23:50 +00001052 if (Style.BraceWrapping.AfterExternBlock) {
1053 addUnwrappedLine();
1054 parseBlock(/*MustBeDeclaration=*/true);
1055 } else {
1056 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1057 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001058 addUnwrappedLine();
1059 return;
1060 }
1061 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001062 break;
Daniel Jasperfca735c2015-02-19 16:14:18 +00001063 case tok::kw_export:
1064 if (Style.Language == FormatStyle::LK_JavaScript) {
1065 parseJavaScriptEs6ImportExport();
1066 return;
1067 }
1068 break;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001069 case tok::identifier:
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001070 if (FormatTok->is(TT_ForEachMacro)) {
Daniel Jaspere1e43192014-04-01 12:55:11 +00001071 parseForOrWhileLoop();
1072 return;
1073 }
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001074 if (FormatTok->is(TT_MacroBlockBegin)) {
1075 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1076 /*MunchSemi=*/false);
1077 return;
1078 }
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001079 if (FormatTok->is(Keywords.kw_import)) {
1080 if (Style.Language == FormatStyle::LK_JavaScript) {
1081 parseJavaScriptEs6ImportExport();
1082 return;
1083 }
1084 if (Style.Language == FormatStyle::LK_Proto) {
1085 nextToken();
Daniel Jasper8b61d142016-06-20 20:39:53 +00001086 if (FormatTok->is(tok::kw_public))
1087 nextToken();
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001088 if (!FormatTok->is(tok::string_literal))
1089 return;
1090 nextToken();
1091 if (FormatTok->is(tok::semi))
1092 nextToken();
1093 addUnwrappedLine();
1094 return;
1095 }
Daniel Jasper354aa512015-02-19 16:07:32 +00001096 }
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001097 if (Style.isCpp() &&
Daniel Jasper72b33572017-03-31 12:04:37 +00001098 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
Daniel Jaspera00de632015-12-01 12:05:04 +00001099 Keywords.kw_slots, Keywords.kw_qslots)) {
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001100 nextToken();
1101 if (FormatTok->is(tok::colon)) {
1102 nextToken();
1103 addUnwrappedLine();
Daniel Jasper31343832016-07-27 10:13:24 +00001104 return;
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001105 }
Daniel Jasper53395402015-04-07 15:04:40 +00001106 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001107 // In all other cases, parse the declaration.
1108 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001109 default:
1110 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001111 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001112 do {
Manuel Klimeke411aa82017-09-20 09:29:37 +00001113 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001114 switch (FormatTok->Tok.getKind()) {
Nico Weber372d8dc2013-02-10 20:35:35 +00001115 case tok::at:
1116 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001117 if (FormatTok->Tok.is(tok::l_brace)) {
1118 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001119 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001120 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001121 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001122 case tok::kw_enum:
Daniel Jaspera7900ad2016-05-08 18:12:22 +00001123 // Ignore if this is part of "template <enum ...".
1124 if (Previous && Previous->is(tok::less)) {
1125 nextToken();
1126 break;
1127 }
1128
Daniel Jasper90cf3802015-06-17 09:44:02 +00001129 // parseEnum falls through and does not yet add an unwrapped line as an
1130 // enum definition can start a structural element.
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001131 if (!parseEnum())
1132 break;
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001133 // This only applies for C++.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001134 if (!Style.isCpp()) {
Daniel Jasper90cf3802015-06-17 09:44:02 +00001135 addUnwrappedLine();
1136 return;
1137 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001138 break;
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001139 case tok::kw_typedef:
1140 nextToken();
Daniel Jasper31f6c542014-12-05 10:42:21 +00001141 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1142 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001143 parseEnum();
1144 break;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001145 case tok::kw_struct:
1146 case tok::kw_union:
Manuel Klimek28cacc72013-01-07 18:10:23 +00001147 case tok::kw_class:
Daniel Jasper910807d2015-06-12 04:52:02 +00001148 // parseRecord falls through and does not yet add an unwrapped line as a
1149 // record declaration or definition can start a structural element.
Manuel Klimeke01bab52013-01-15 13:38:33 +00001150 parseRecord();
Daniel Jasper910807d2015-06-12 04:52:02 +00001151 // This does not apply for Java and JavaScript.
1152 if (Style.Language == FormatStyle::LK_Java ||
1153 Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperd5ec65b2016-01-08 07:06:07 +00001154 if (FormatTok->is(tok::semi))
1155 nextToken();
Daniel Jasper910807d2015-06-12 04:52:02 +00001156 addUnwrappedLine();
1157 return;
1158 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00001159 break;
Daniel Jaspere5d74862014-11-26 08:17:08 +00001160 case tok::period:
1161 nextToken();
1162 // In Java, classes have an implicit static member "class".
1163 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1164 FormatTok->is(tok::kw_class))
1165 nextToken();
Daniel Jasperba52fcb2015-09-28 14:29:45 +00001166 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1167 FormatTok->Tok.getIdentifierInfo())
1168 // JavaScript only has pseudo keywords, all keywords are allowed to
1169 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1170 nextToken();
Daniel Jaspere5d74862014-11-26 08:17:08 +00001171 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001172 case tok::semi:
1173 nextToken();
1174 addUnwrappedLine();
1175 return;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001176 case tok::r_brace:
1177 addUnwrappedLine();
1178 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001179 case tok::l_paren:
1180 parseParens();
1181 break;
Daniel Jasper5af04a42015-10-07 03:43:10 +00001182 case tok::kw_operator:
1183 nextToken();
1184 if (FormatTok->isBinaryOperator())
1185 nextToken();
1186 break;
Manuel Klimek516e0542013-09-04 13:25:30 +00001187 case tok::caret:
1188 nextToken();
Daniel Jasper395193c2014-03-28 07:48:59 +00001189 if (FormatTok->Tok.isAnyIdentifier() ||
1190 FormatTok->isSimpleTypeSpecifier())
1191 nextToken();
1192 if (FormatTok->is(tok::l_paren))
1193 parseParens();
1194 if (FormatTok->is(tok::l_brace))
Manuel Klimek516e0542013-09-04 13:25:30 +00001195 parseChildBlock();
Manuel Klimek516e0542013-09-04 13:25:30 +00001196 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001197 case tok::l_brace:
Manuel Klimekab419912013-05-23 09:41:43 +00001198 if (!tryToParseBracedList()) {
1199 // A block outside of parentheses must be the last part of a
1200 // structural element.
1201 // FIXME: Figure out cases where this is not true, and add projections
1202 // for them (the one we know is missing are lambdas).
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001203 if (Style.BraceWrapping.AfterFunction)
Manuel Klimekab419912013-05-23 09:41:43 +00001204 addUnwrappedLine();
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001205 FormatTok->Type = TT_FunctionLBrace;
Nico Weber9096fc02013-06-26 00:30:14 +00001206 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001207 addUnwrappedLine();
Manuel Klimekab419912013-05-23 09:41:43 +00001208 return;
1209 }
1210 // Otherwise this was a braced init list, and the structural
1211 // element continues.
1212 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001213 case tok::kw_try:
1214 // We arrive here when parsing function-try blocks.
1215 parseTryCatch();
1216 return;
Daniel Jasper40e19212013-05-29 13:16:10 +00001217 case tok::identifier: {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001218 if (FormatTok->is(TT_MacroBlockEnd)) {
1219 addUnwrappedLine();
1220 return;
1221 }
1222
Martin Probst973ff792017-04-27 13:07:24 +00001223 // Function declarations (as opposed to function expressions) are parsed
1224 // on their own unwrapped line by continuing this loop. Function
1225 // expressions (functions that are not on their own line) must not create
1226 // a new unwrapped line, so they are special cased below.
1227 size_t TokenCount = Line->Tokens.size();
Daniel Jasper9326f912015-05-05 08:40:32 +00001228 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst973ff792017-04-27 13:07:24 +00001229 FormatTok->is(Keywords.kw_function) &&
1230 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1231 Keywords.kw_async)))) {
Daniel Jasper069e5f42014-05-20 11:14:57 +00001232 tryToParseJSFunction();
1233 break;
1234 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001235 if ((Style.Language == FormatStyle::LK_JavaScript ||
1236 Style.Language == FormatStyle::LK_Java) &&
1237 FormatTok->is(Keywords.kw_interface)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001238 if (Style.Language == FormatStyle::LK_JavaScript) {
1239 // In JavaScript/TypeScript, "interface" can be used as a standalone
1240 // identifier, e.g. in `var interface = 1;`. If "interface" is
1241 // followed by another identifier, it is very like to be an actual
1242 // interface declaration.
1243 unsigned StoredPosition = Tokens->getPosition();
1244 FormatToken *Next = Tokens->getNextToken();
1245 FormatTok = Tokens->setPosition(StoredPosition);
Martin Probst533965c2016-04-19 18:19:06 +00001246 if (Next && !mustBeJSIdent(Keywords, Next)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001247 nextToken();
1248 break;
1249 }
1250 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001251 parseRecord();
Daniel Jasper259188b2015-06-12 04:56:34 +00001252 addUnwrappedLine();
Daniel Jasper5c235c02015-07-06 14:26:04 +00001253 return;
Daniel Jasper9326f912015-05-05 08:40:32 +00001254 }
1255
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00001256 // See if the following token should start a new unwrapped line.
Daniel Jasper9326f912015-05-05 08:40:32 +00001257 StringRef Text = FormatTok->TokenText;
Daniel Jasperf7935112012-12-03 18:12:45 +00001258 nextToken();
Daniel Jasper83709082015-02-18 17:14:05 +00001259 if (Line->Tokens.size() == 1 &&
1260 // JS doesn't have macros, and within classes colons indicate fields,
1261 // not labels.
Daniel Jasper676e5162015-04-07 14:36:33 +00001262 Style.Language != FormatStyle::LK_JavaScript) {
1263 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
Daniel Jasper40609472016-04-06 15:02:46 +00001264 Line->Tokens.begin()->Tok->MustBreakBefore = true;
Alexander Kornienkode644272013-04-08 22:16:06 +00001265 parseLabel();
1266 return;
1267 }
Daniel Jasper680b09b2014-11-05 10:48:04 +00001268 // Recognize function-like macro usages without trailing semicolon as
Daniel Jasper83709082015-02-18 17:14:05 +00001269 // well as free-standing macros like Q_OBJECT.
Daniel Jasper680b09b2014-11-05 10:48:04 +00001270 bool FunctionLike = FormatTok->is(tok::l_paren);
1271 if (FunctionLike)
Alexander Kornienkode644272013-04-08 22:16:06 +00001272 parseParens();
Daniel Jaspere60cba12015-05-13 11:35:53 +00001273
1274 bool FollowedByNewline =
1275 CommentsBeforeNextToken.empty()
1276 ? FormatTok->NewlinesBefore > 0
1277 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1278
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001279 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
Daniel Jasper680b09b2014-11-05 10:48:04 +00001280 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
Daniel Jasper40e19212013-05-29 13:16:10 +00001281 addUnwrappedLine();
Daniel Jasper41a0f782013-05-29 14:09:17 +00001282 return;
Alexander Kornienkode644272013-04-08 22:16:06 +00001283 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001284 }
1285 break;
Daniel Jasper40e19212013-05-29 13:16:10 +00001286 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001287 case tok::equal:
Manuel Klimek79e06082015-05-21 12:23:34 +00001288 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1289 // TT_JsFatArrow. The always start an expression or a child block if
1290 // followed by a curly.
1291 if (FormatTok->is(TT_JsFatArrow)) {
1292 nextToken();
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001293 if (FormatTok->is(tok::l_brace))
Manuel Klimek79e06082015-05-21 12:23:34 +00001294 parseChildBlock();
Manuel Klimek79e06082015-05-21 12:23:34 +00001295 break;
1296 }
1297
Daniel Jaspere25509f2012-12-17 11:29:41 +00001298 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001299 if (FormatTok->Tok.is(tok::l_brace)) {
1300 nextToken();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001301 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001302 } else if (Style.Language == FormatStyle::LK_Proto &&
Manuel Klimek89628f62017-09-20 09:51:03 +00001303 FormatTok->Tok.is(tok::less)) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001304 nextToken();
Krasimir Georgiev0b41fcb2017-06-27 13:58:41 +00001305 parseBracedList(/*ContinueOnSemicolons=*/false,
1306 /*ClosingBraceKind=*/tok::greater);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001307 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001308 break;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001309 case tok::l_square:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001310 parseSquare();
Manuel Klimekffdeb592013-09-03 15:10:01 +00001311 break;
Daniel Jasper6acf5132015-03-12 14:44:29 +00001312 case tok::kw_new:
1313 parseNew();
1314 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001315 default:
1316 nextToken();
1317 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001318 }
1319 } while (!eof());
1320}
1321
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001322bool UnwrappedLineParser::tryToParseLambda() {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001323 if (!Style.isCpp()) {
Daniel Jasper1feab0f2015-06-02 15:31:37 +00001324 nextToken();
1325 return false;
1326 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001327 assert(FormatTok->is(tok::l_square));
1328 FormatToken &LSquare = *FormatTok;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001329 if (!tryToParseLambdaIntroducer())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001330 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001331
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00001332 while (FormatTok->isNot(tok::l_brace)) {
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001333 if (FormatTok->isSimpleTypeSpecifier()) {
1334 nextToken();
1335 continue;
1336 }
Manuel Klimekffdeb592013-09-03 15:10:01 +00001337 switch (FormatTok->Tok.getKind()) {
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001338 case tok::l_brace:
1339 break;
1340 case tok::l_paren:
1341 parseParens();
1342 break;
Daniel Jasperbcb55ee2014-11-21 14:08:38 +00001343 case tok::amp:
1344 case tok::star:
1345 case tok::kw_const:
Daniel Jasper3431b752014-12-08 13:22:37 +00001346 case tok::comma:
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001347 case tok::less:
1348 case tok::greater:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001349 case tok::identifier:
Daniel Jasper5eaa0092015-08-13 13:37:08 +00001350 case tok::numeric_constant:
Daniel Jasper1067ab02014-02-11 10:16:55 +00001351 case tok::coloncolon:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001352 case tok::kw_mutable:
Daniel Jasper81a20782014-03-10 10:02:02 +00001353 nextToken();
1354 break;
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001355 case tok::arrow:
Daniel Jasper6f2b88a2015-06-05 13:18:09 +00001356 FormatTok->Type = TT_LambdaArrow;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001357 nextToken();
1358 break;
1359 default:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001360 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001361 }
1362 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001363 LSquare.Type = TT_LambdaLSquare;
Manuel Klimek516e0542013-09-04 13:25:30 +00001364 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001365 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001366}
1367
1368bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
Manuel Klimek89628f62017-09-20 09:51:03 +00001369 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001370 if (Previous &&
1371 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1372 tok::kw_delete) ||
Manuel Klimek89628f62017-09-20 09:51:03 +00001373 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1374 Previous->isSimpleTypeSpecifier())) {
Manuel Klimekffdeb592013-09-03 15:10:01 +00001375 nextToken();
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001376 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001377 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001378 nextToken();
1379 parseSquare(/*LambdaIntroducer=*/true);
1380 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001381}
1382
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001383void UnwrappedLineParser::tryToParseJSFunction() {
Martin Probst409697e2016-05-29 14:41:07 +00001384 assert(FormatTok->is(Keywords.kw_function) ||
1385 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
Martin Probst5f8445b2016-04-24 22:05:09 +00001386 if (FormatTok->is(Keywords.kw_async))
1387 nextToken();
1388 // Consume "function".
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001389 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001390
Daniel Jasper71e50af2016-11-01 06:22:59 +00001391 // Consume * (generator function). Treat it like C++'s overloaded operators.
1392 if (FormatTok->is(tok::star)) {
1393 FormatTok->Type = TT_OverloadedOperator;
Martin Probst5f8445b2016-04-24 22:05:09 +00001394 nextToken();
Daniel Jasper71e50af2016-11-01 06:22:59 +00001395 }
Martin Probst5f8445b2016-04-24 22:05:09 +00001396
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001397 // Consume function name.
1398 if (FormatTok->is(tok::identifier))
Daniel Jasperfca735c2015-02-19 16:14:18 +00001399 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001400
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001401 if (FormatTok->isNot(tok::l_paren))
1402 return;
Manuel Klimek79e06082015-05-21 12:23:34 +00001403
1404 // Parse formal parameter list.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001405 parseParens();
Manuel Klimek79e06082015-05-21 12:23:34 +00001406
1407 if (FormatTok->is(tok::colon)) {
1408 // Parse a type definition.
1409 nextToken();
1410
1411 // Eat the type declaration. For braced inline object types, balance braces,
1412 // otherwise just parse until finding an l_brace for the function body.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001413 if (FormatTok->is(tok::l_brace))
1414 tryToParseBracedList();
1415 else
Martin Probstaf16c502017-01-04 13:36:43 +00001416 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
Manuel Klimek79e06082015-05-21 12:23:34 +00001417 nextToken();
Manuel Klimek79e06082015-05-21 12:23:34 +00001418 }
1419
Martin Probstaf16c502017-01-04 13:36:43 +00001420 if (FormatTok->is(tok::semi))
1421 return;
1422
Manuel Klimek79e06082015-05-21 12:23:34 +00001423 parseChildBlock();
1424}
1425
Daniel Jasper3c883d12015-05-18 14:49:19 +00001426bool UnwrappedLineParser::tryToParseBracedList() {
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001427 if (FormatTok->BlockKind == BK_Unknown)
Daniel Jasper3c883d12015-05-18 14:49:19 +00001428 calculateBraceTypes();
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001429 assert(FormatTok->BlockKind != BK_Unknown);
1430 if (FormatTok->BlockKind == BK_Block)
Manuel Klimekab419912013-05-23 09:41:43 +00001431 return false;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001432 nextToken();
Manuel Klimekab419912013-05-23 09:41:43 +00001433 parseBracedList();
1434 return true;
1435}
1436
Krasimir Georgievff747be2017-06-27 13:43:07 +00001437bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1438 tok::TokenKind ClosingBraceKind) {
Daniel Jasper015ed022013-09-13 09:20:45 +00001439 bool HasError = false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001440
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001441 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1442 // replace this by using parseAssigmentExpression() inside.
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001443 do {
Manuel Klimek79e06082015-05-21 12:23:34 +00001444 if (Style.Language == FormatStyle::LK_JavaScript) {
Martin Probst409697e2016-05-29 14:41:07 +00001445 if (FormatTok->is(Keywords.kw_function) ||
1446 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001447 tryToParseJSFunction();
1448 continue;
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001449 }
1450 if (FormatTok->is(TT_JsFatArrow)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001451 nextToken();
1452 // Fat arrows can be followed by simple expressions or by child blocks
1453 // in curly braces.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001454 if (FormatTok->is(tok::l_brace)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001455 parseChildBlock();
1456 continue;
1457 }
1458 }
Martin Probst8e3eba02017-02-07 16:33:13 +00001459 if (FormatTok->is(tok::l_brace)) {
1460 // Could be a method inside of a braced list `{a() { return 1; }}`.
1461 if (tryToParseBracedList())
1462 continue;
1463 parseChildBlock();
1464 }
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001465 }
Krasimir Georgievff747be2017-06-27 13:43:07 +00001466 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1467 nextToken();
1468 return !HasError;
1469 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001470 switch (FormatTok->Tok.getKind()) {
Manuel Klimek516e0542013-09-04 13:25:30 +00001471 case tok::caret:
1472 nextToken();
1473 if (FormatTok->is(tok::l_brace)) {
1474 parseChildBlock();
1475 }
1476 break;
1477 case tok::l_square:
1478 tryToParseLambda();
1479 break;
Daniel Jaspera87af7a2015-06-30 11:32:22 +00001480 case tok::l_paren:
1481 parseParens();
Daniel Jasperf46dec82015-03-31 14:34:15 +00001482 // JavaScript can just have free standing methods and getters/setters in
1483 // object literals. Detect them by a "{" following ")".
1484 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf46dec82015-03-31 14:34:15 +00001485 if (FormatTok->is(tok::l_brace))
1486 parseChildBlock();
1487 break;
1488 }
Daniel Jasperf46dec82015-03-31 14:34:15 +00001489 break;
Martin Probst8e3eba02017-02-07 16:33:13 +00001490 case tok::l_brace:
1491 // Assume there are no blocks inside a braced init list apart
1492 // from the ones we explicitly parse out (like lambdas).
1493 FormatTok->BlockKind = BK_BracedInit;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001494 nextToken();
Martin Probst8e3eba02017-02-07 16:33:13 +00001495 parseBracedList();
1496 break;
Krasimir Georgievfa4dbb62017-08-03 13:43:45 +00001497 case tok::less:
1498 if (Style.Language == FormatStyle::LK_Proto) {
1499 nextToken();
1500 parseBracedList(/*ContinueOnSemicolons=*/false,
1501 /*ClosingBraceKind=*/tok::greater);
1502 } else {
1503 nextToken();
1504 }
1505 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001506 case tok::semi:
Daniel Jasperb9a49902016-01-09 15:56:28 +00001507 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1508 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1509 // used for error recovery if we have otherwise determined that this is
1510 // a braced list.
1511 if (Style.Language == FormatStyle::LK_JavaScript) {
1512 nextToken();
1513 break;
1514 }
Daniel Jasper015ed022013-09-13 09:20:45 +00001515 HasError = true;
1516 if (!ContinueOnSemicolons)
1517 return !HasError;
1518 nextToken();
1519 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001520 case tok::comma:
1521 nextToken();
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001522 break;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001523 default:
1524 nextToken();
1525 break;
1526 }
1527 } while (!eof());
Daniel Jasper015ed022013-09-13 09:20:45 +00001528 return false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001529}
1530
Daniel Jasperf7935112012-12-03 18:12:45 +00001531void UnwrappedLineParser::parseParens() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001532 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
Daniel Jasperf7935112012-12-03 18:12:45 +00001533 nextToken();
1534 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001535 switch (FormatTok->Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001536 case tok::l_paren:
1537 parseParens();
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001538 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1539 parseChildBlock();
Daniel Jasperf7935112012-12-03 18:12:45 +00001540 break;
1541 case tok::r_paren:
1542 nextToken();
1543 return;
Daniel Jasper393564f2013-05-31 14:56:29 +00001544 case tok::r_brace:
1545 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1546 return;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001547 case tok::l_square:
1548 tryToParseLambda();
1549 break;
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001550 case tok::l_brace:
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001551 if (!tryToParseBracedList())
Manuel Klimekf017dc02013-09-04 13:34:14 +00001552 parseChildBlock();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001553 break;
Nico Weber372d8dc2013-02-10 20:35:35 +00001554 case tok::at:
1555 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001556 if (FormatTok->Tok.is(tok::l_brace)) {
1557 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001558 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001559 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001560 break;
Martin Probst1027fb82017-02-07 14:05:30 +00001561 case tok::kw_class:
1562 if (Style.Language == FormatStyle::LK_JavaScript)
1563 parseRecord(/*ParseAsExpr=*/true);
1564 else
1565 nextToken();
1566 break;
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001567 case tok::identifier:
1568 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst409697e2016-05-29 14:41:07 +00001569 (FormatTok->is(Keywords.kw_function) ||
1570 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001571 tryToParseJSFunction();
1572 else
1573 nextToken();
1574 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001575 default:
1576 nextToken();
1577 break;
1578 }
1579 } while (!eof());
1580}
1581
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001582void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1583 if (!LambdaIntroducer) {
1584 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1585 if (tryToParseLambda())
1586 return;
1587 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001588 do {
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001589 switch (FormatTok->Tok.getKind()) {
1590 case tok::l_paren:
1591 parseParens();
1592 break;
1593 case tok::r_square:
1594 nextToken();
1595 return;
1596 case tok::r_brace:
1597 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1598 return;
1599 case tok::l_square:
1600 parseSquare();
1601 break;
1602 case tok::l_brace: {
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001603 if (!tryToParseBracedList())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001604 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001605 break;
1606 }
1607 case tok::at:
1608 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001609 if (FormatTok->Tok.is(tok::l_brace)) {
1610 nextToken();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001611 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001612 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001613 break;
1614 default:
1615 nextToken();
1616 break;
1617 }
1618 } while (!eof());
1619}
1620
Daniel Jasperf7935112012-12-03 18:12:45 +00001621void UnwrappedLineParser::parseIfThenElse() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001622 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001623 nextToken();
Daniel Jasper6a7d5a72017-06-19 07:40:49 +00001624 if (FormatTok->Tok.is(tok::kw_constexpr))
1625 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001626 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimekadededf2013-01-11 18:28:36 +00001627 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +00001628 bool NeedsUnwrappedLine = false;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001629 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001630 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001631 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001632 if (Style.BraceWrapping.BeforeElse)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001633 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001634 else
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001635 NeedsUnwrappedLine = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001636 } else {
1637 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001638 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001639 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001640 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001641 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001642 if (FormatTok->Tok.is(tok::kw_else)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001643 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001644 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001645 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001646 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001647 addUnwrappedLine();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001648 } else if (FormatTok->Tok.is(tok::kw_if)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001649 parseIfThenElse();
1650 } else {
1651 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001652 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001653 parseStructuralElement();
Daniel Jasper451544a2016-05-19 06:30:48 +00001654 if (FormatTok->is(tok::eof))
1655 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001656 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001657 }
1658 } else if (NeedsUnwrappedLine) {
1659 addUnwrappedLine();
1660 }
1661}
1662
Daniel Jasper04a71a42014-05-08 11:58:24 +00001663void UnwrappedLineParser::parseTryCatch() {
Nico Weberfac23712015-02-04 15:26:27 +00001664 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
Daniel Jasper04a71a42014-05-08 11:58:24 +00001665 nextToken();
1666 bool NeedsUnwrappedLine = false;
1667 if (FormatTok->is(tok::colon)) {
1668 // We are in a function try block, what comes is an initializer list.
1669 nextToken();
1670 while (FormatTok->is(tok::identifier)) {
1671 nextToken();
1672 if (FormatTok->is(tok::l_paren))
1673 parseParens();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001674 if (FormatTok->is(tok::comma))
1675 nextToken();
1676 }
1677 }
Daniel Jaspere189d462015-01-14 10:48:41 +00001678 // Parse try with resource.
1679 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1680 parseParens();
1681 }
Daniel Jasper04a71a42014-05-08 11:58:24 +00001682 if (FormatTok->is(tok::l_brace)) {
1683 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1684 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001685 if (Style.BraceWrapping.BeforeCatch) {
Daniel Jasper04a71a42014-05-08 11:58:24 +00001686 addUnwrappedLine();
1687 } else {
1688 NeedsUnwrappedLine = true;
1689 }
1690 } else if (!FormatTok->is(tok::kw_catch)) {
1691 // The C++ standard requires a compound-statement after a try.
1692 // If there's none, we try to assume there's a structuralElement
1693 // and try to continue.
Daniel Jasper04a71a42014-05-08 11:58:24 +00001694 addUnwrappedLine();
1695 ++Line->Level;
1696 parseStructuralElement();
1697 --Line->Level;
1698 }
Nico Weber33381f52015-02-07 01:57:32 +00001699 while (1) {
1700 if (FormatTok->is(tok::at))
1701 nextToken();
1702 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1703 tok::kw___finally) ||
1704 ((Style.Language == FormatStyle::LK_Java ||
1705 Style.Language == FormatStyle::LK_JavaScript) &&
1706 FormatTok->is(Keywords.kw_finally)) ||
1707 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1708 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1709 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001710 nextToken();
1711 while (FormatTok->isNot(tok::l_brace)) {
1712 if (FormatTok->is(tok::l_paren)) {
1713 parseParens();
1714 continue;
1715 }
Daniel Jasper2bd7a642015-01-19 10:50:51 +00001716 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
Daniel Jasper04a71a42014-05-08 11:58:24 +00001717 return;
1718 nextToken();
1719 }
1720 NeedsUnwrappedLine = false;
1721 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1722 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001723 if (Style.BraceWrapping.BeforeCatch)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001724 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001725 else
Daniel Jasper04a71a42014-05-08 11:58:24 +00001726 NeedsUnwrappedLine = true;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001727 }
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001728 if (NeedsUnwrappedLine)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001729 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001730}
1731
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001732void UnwrappedLineParser::parseNamespace() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001733 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001734
1735 const FormatToken &InitialToken = *FormatTok;
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001736 nextToken();
Saleem Abdulrasool328085f2015-10-30 05:07:56 +00001737 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001738 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001739 if (FormatTok->Tok.is(tok::l_brace)) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001740 if (ShouldBreakBeforeBrace(Style, InitialToken))
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001741 addUnwrappedLine();
1742
Daniel Jasper65ee3472013-07-31 23:16:02 +00001743 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1744 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1745 DeclarationScopeStack.size() > 1);
1746 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
Manuel Klimek046b9302013-02-06 16:08:09 +00001747 // Munch the semicolon after a namespace. This is more common than one would
1748 // think. Puttin the semicolon into its own line is very ugly.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001749 if (FormatTok->Tok.is(tok::semi))
Manuel Klimek046b9302013-02-06 16:08:09 +00001750 nextToken();
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001751 addUnwrappedLine();
1752 }
1753 // FIXME: Add error handling.
1754}
1755
Daniel Jasper6acf5132015-03-12 14:44:29 +00001756void UnwrappedLineParser::parseNew() {
1757 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1758 nextToken();
1759 if (Style.Language != FormatStyle::LK_Java)
1760 return;
1761
1762 // In Java, we can parse everything up to the parens, which aren't optional.
1763 do {
1764 // There should not be a ;, { or } before the new's open paren.
1765 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1766 return;
1767
1768 // Consume the parens.
1769 if (FormatTok->is(tok::l_paren)) {
1770 parseParens();
1771
1772 // If there is a class body of an anonymous class, consume that as child.
1773 if (FormatTok->is(tok::l_brace))
1774 parseChildBlock();
1775 return;
1776 }
1777 nextToken();
1778 } while (!eof());
1779}
1780
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001781void UnwrappedLineParser::parseForOrWhileLoop() {
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001782 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
Daniel Jaspere1e43192014-04-01 12:55:11 +00001783 "'for', 'while' or foreach macro expected");
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001784 nextToken();
Martin Probsta050f412017-05-18 21:19:29 +00001785 // JS' for await ( ...
Martin Probstbd49e322017-05-15 19:33:20 +00001786 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probsta050f412017-05-18 21:19:29 +00001787 FormatTok->is(Keywords.kw_await))
Martin Probstbd49e322017-05-15 19:33:20 +00001788 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001789 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001790 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001791 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001792 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001793 parseBlock(/*MustBeDeclaration=*/false);
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001794 addUnwrappedLine();
1795 } else {
1796 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001797 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001798 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001799 --Line->Level;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001800 }
1801}
1802
Daniel Jasperf7935112012-12-03 18:12:45 +00001803void UnwrappedLineParser::parseDoWhile() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001804 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001805 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001806 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001807 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001808 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001809 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001810 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001811 } else {
1812 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001813 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001814 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001815 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001816 }
1817
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001818 // FIXME: Add error handling.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001819 if (!FormatTok->Tok.is(tok::kw_while)) {
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001820 addUnwrappedLine();
1821 return;
1822 }
1823
Daniel Jasperf7935112012-12-03 18:12:45 +00001824 nextToken();
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001825 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +00001826}
1827
1828void UnwrappedLineParser::parseLabel() {
Daniel Jasperf7935112012-12-03 18:12:45 +00001829 nextToken();
Manuel Klimek52b15152013-01-09 15:25:02 +00001830 unsigned OldLineLevel = Line->Level;
Daniel Jaspera1275122013-03-20 10:23:53 +00001831 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
Manuel Klimek52b15152013-01-09 15:25:02 +00001832 --Line->Level;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001833 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001834 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001835 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001836 if (FormatTok->Tok.is(tok::kw_break)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001837 if (Style.BraceWrapping.AfterControlStatement)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001838 addUnwrappedLine();
1839 parseStructuralElement();
1840 }
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001841 addUnwrappedLine();
1842 } else {
Daniel Jasper1fe0d5c2015-05-06 15:19:47 +00001843 if (FormatTok->is(tok::semi))
1844 nextToken();
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001845 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001846 }
Manuel Klimek52b15152013-01-09 15:25:02 +00001847 Line->Level = OldLineLevel;
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001848 if (FormatTok->isNot(tok::l_brace)) {
Daniel Jasper40609472016-04-06 15:02:46 +00001849 parseStructuralElement();
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001850 addUnwrappedLine();
1851 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001852}
1853
1854void UnwrappedLineParser::parseCaseLabel() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001855 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001856 // FIXME: fix handling of complex expressions here.
1857 do {
1858 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001859 } while (!eof() && !FormatTok->Tok.is(tok::colon));
Daniel Jasperf7935112012-12-03 18:12:45 +00001860 parseLabel();
1861}
1862
1863void UnwrappedLineParser::parseSwitch() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001864 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001865 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001866 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001867 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001868 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001869 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Daniel Jasper65ee3472013-07-31 23:16:02 +00001870 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001871 addUnwrappedLine();
1872 } else {
1873 addUnwrappedLine();
Daniel Jasper516d7972013-07-25 11:31:57 +00001874 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001875 parseStructuralElement();
Daniel Jasper516d7972013-07-25 11:31:57 +00001876 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001877 }
1878}
1879
1880void UnwrappedLineParser::parseAccessSpecifier() {
1881 nextToken();
Daniel Jasper84c47a12013-11-23 17:53:41 +00001882 // Understand Qt's slots.
Daniel Jasper53395402015-04-07 15:04:40 +00001883 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
Daniel Jasper84c47a12013-11-23 17:53:41 +00001884 nextToken();
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00001885 // Otherwise, we don't know what it is, and we'd better keep the next token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001886 if (FormatTok->Tok.is(tok::colon))
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00001887 nextToken();
Daniel Jasperf7935112012-12-03 18:12:45 +00001888 addUnwrappedLine();
1889}
1890
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001891bool UnwrappedLineParser::parseEnum() {
Daniel Jasper6be0f552014-11-13 15:56:28 +00001892 // Won't be 'enum' for NS_ENUMs.
1893 if (FormatTok->Tok.is(tok::kw_enum))
Daniel Jasperccb68b42014-11-19 22:38:18 +00001894 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001895
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001896 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1897 // declarations. An "enum" keyword followed by a colon would be a syntax
1898 // error and thus assume it is just an identifier.
Daniel Jasper87379302016-02-03 05:33:44 +00001899 if (Style.Language == FormatStyle::LK_JavaScript &&
1900 FormatTok->isOneOf(tok::colon, tok::question))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001901 return false;
1902
Daniel Jasper2b41a822013-08-20 12:42:50 +00001903 // Eat up enum class ...
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001904 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1905 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001906
Daniel Jasper786a5502013-09-06 21:32:35 +00001907 while (FormatTok->Tok.getIdentifierInfo() ||
Daniel Jasperccb68b42014-11-19 22:38:18 +00001908 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1909 tok::greater, tok::comma, tok::question)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00001910 nextToken();
1911 // We can have macros or attributes in between 'enum' and the enum name.
Daniel Jasperccb68b42014-11-19 22:38:18 +00001912 if (FormatTok->is(tok::l_paren))
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001913 parseParens();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001914 if (FormatTok->is(tok::identifier)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00001915 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001916 // If there are two identifiers in a row, this is likely an elaborate
1917 // return type. In Java, this can be "implements", etc.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001918 if (Style.isCpp() && FormatTok->is(tok::identifier))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001919 return false;
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001920 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001921 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00001922
1923 // Just a declaration or something is wrong.
Daniel Jasperccb68b42014-11-19 22:38:18 +00001924 if (FormatTok->isNot(tok::l_brace))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001925 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00001926 FormatTok->BlockKind = BK_Block;
1927
1928 if (Style.Language == FormatStyle::LK_Java) {
1929 // Java enums are different.
1930 parseJavaEnumBody();
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001931 return true;
1932 }
1933 if (Style.Language == FormatStyle::LK_Proto) {
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001934 parseBlock(/*MustBeDeclaration=*/true);
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001935 return true;
Manuel Klimek2cec0192013-01-21 19:17:52 +00001936 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00001937
1938 // Parse enum body.
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001939 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001940 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1941 if (HasError) {
1942 if (FormatTok->is(tok::semi))
1943 nextToken();
1944 addUnwrappedLine();
1945 }
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001946 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00001947
Daniel Jasper90cf3802015-06-17 09:44:02 +00001948 // There is no addUnwrappedLine() here so that we fall through to parsing a
1949 // structural element afterwards. Thus, in "enum A {} n, m;",
Manuel Klimek2cec0192013-01-21 19:17:52 +00001950 // "} n, m;" will end up in one unwrapped line.
Daniel Jasper6be0f552014-11-13 15:56:28 +00001951}
1952
1953void UnwrappedLineParser::parseJavaEnumBody() {
1954 // Determine whether the enum is simple, i.e. does not have a semicolon or
1955 // constants with class bodies. Simple enums can be formatted like braced
1956 // lists, contracted to a single line, etc.
1957 unsigned StoredPosition = Tokens->getPosition();
1958 bool IsSimple = true;
1959 FormatToken *Tok = Tokens->getNextToken();
1960 while (Tok) {
1961 if (Tok->is(tok::r_brace))
1962 break;
1963 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1964 IsSimple = false;
1965 break;
1966 }
1967 // FIXME: This will also mark enums with braces in the arguments to enum
1968 // constants as "not simple". This is probably fine in practice, though.
1969 Tok = Tokens->getNextToken();
1970 }
1971 FormatTok = Tokens->setPosition(StoredPosition);
1972
1973 if (IsSimple) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001974 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001975 parseBracedList();
Daniel Jasperdf2ff002014-11-02 22:31:39 +00001976 addUnwrappedLine();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001977 return;
1978 }
1979
1980 // Parse the body of a more complex enum.
1981 // First add a line for everything up to the "{".
1982 nextToken();
1983 addUnwrappedLine();
1984 ++Line->Level;
1985
1986 // Parse the enum constants.
1987 while (FormatTok) {
1988 if (FormatTok->is(tok::l_brace)) {
1989 // Parse the constant's class body.
1990 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1991 /*MunchSemi=*/false);
1992 } else if (FormatTok->is(tok::l_paren)) {
1993 parseParens();
1994 } else if (FormatTok->is(tok::comma)) {
1995 nextToken();
1996 addUnwrappedLine();
1997 } else if (FormatTok->is(tok::semi)) {
1998 nextToken();
1999 addUnwrappedLine();
2000 break;
2001 } else if (FormatTok->is(tok::r_brace)) {
2002 addUnwrappedLine();
2003 break;
2004 } else {
2005 nextToken();
2006 }
2007 }
2008
2009 // Parse the class body after the enum's ";" if any.
2010 parseLevel(/*HasOpeningBrace=*/true);
2011 nextToken();
2012 --Line->Level;
2013 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00002014}
2015
Martin Probst1027fb82017-02-07 14:05:30 +00002016void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00002017 const FormatToken &InitialToken = *FormatTok;
Manuel Klimek28cacc72013-01-07 18:10:23 +00002018 nextToken();
Daniel Jasper04785d02015-05-06 14:03:02 +00002019
Daniel Jasper04785d02015-05-06 14:03:02 +00002020 // The actual identifier can be a nested name specifier, and in macros
2021 // it is often token-pasted.
2022 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2023 tok::kw___attribute, tok::kw___declspec,
2024 tok::kw_alignas) ||
2025 ((Style.Language == FormatStyle::LK_Java ||
2026 Style.Language == FormatStyle::LK_JavaScript) &&
2027 FormatTok->isOneOf(tok::period, tok::comma))) {
Martin Probstcb870c52017-08-01 15:46:10 +00002028 if (Style.Language == FormatStyle::LK_JavaScript &&
2029 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2030 // JavaScript/TypeScript supports inline object types in
2031 // extends/implements positions:
2032 // class Foo implements {bar: number} { }
2033 nextToken();
2034 if (FormatTok->is(tok::l_brace)) {
2035 tryToParseBracedList();
2036 continue;
2037 }
2038 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002039 bool IsNonMacroIdentifier =
2040 FormatTok->is(tok::identifier) &&
2041 FormatTok->TokenText != FormatTok->TokenText.upper();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002042 nextToken();
2043 // We can have macros or attributes in between 'class' and the class name.
Daniel Jasper04785d02015-05-06 14:03:02 +00002044 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
Manuel Klimeke01bab52013-01-15 13:38:33 +00002045 parseParens();
Daniel Jasper04785d02015-05-06 14:03:02 +00002046 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00002047
Daniel Jasper04785d02015-05-06 14:03:02 +00002048 // Note that parsing away template declarations here leads to incorrectly
2049 // accepting function declarations as record declarations.
2050 // In general, we cannot solve this problem. Consider:
2051 // class A<int> B() {}
2052 // which can be a function definition or a class definition when B() is a
2053 // macro. If we find enough real-world cases where this is a problem, we
2054 // can parse for the 'template' keyword in the beginning of the statement,
2055 // and thus rule out the record production in case there is no template
2056 // (this would still leave us with an ambiguity between template function
2057 // and class declarations).
Daniel Jasperadba2aa2015-05-18 12:52:00 +00002058 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2059 while (!eof()) {
Daniel Jasper3c883d12015-05-18 14:49:19 +00002060 if (FormatTok->is(tok::l_brace)) {
2061 calculateBraceTypes(/*ExpectClassBody=*/true);
2062 if (!tryToParseBracedList())
2063 break;
2064 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002065 if (FormatTok->Tok.is(tok::semi))
2066 return;
2067 nextToken();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002068 }
2069 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002070 if (FormatTok->Tok.is(tok::l_brace)) {
Martin Probst1027fb82017-02-07 14:05:30 +00002071 if (ParseAsExpr) {
2072 parseChildBlock();
2073 } else {
2074 if (ShouldBreakBeforeBrace(Style, InitialToken))
2075 addUnwrappedLine();
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002076
Martin Probst1027fb82017-02-07 14:05:30 +00002077 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2078 /*MunchSemi=*/false);
2079 }
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002080 }
Daniel Jasper90cf3802015-06-17 09:44:02 +00002081 // There is no addUnwrappedLine() here so that we fall through to parsing a
2082 // structural element afterwards. Thus, in "class A {} n, m;",
2083 // "} n, m;" will end up in one unwrapped line.
Manuel Klimek28cacc72013-01-07 18:10:23 +00002084}
2085
Nico Weber8696a8d2013-01-09 21:15:03 +00002086void UnwrappedLineParser::parseObjCProtocolList() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002087 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
Nico Weber8696a8d2013-01-09 21:15:03 +00002088 do
2089 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002090 while (!eof() && FormatTok->Tok.isNot(tok::greater));
Nico Weber8696a8d2013-01-09 21:15:03 +00002091 nextToken(); // Skip '>'.
2092}
2093
2094void UnwrappedLineParser::parseObjCUntilAtEnd() {
2095 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002096 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002097 nextToken();
2098 addUnwrappedLine();
2099 break;
2100 }
Daniel Jaspera15da302013-08-28 08:04:23 +00002101 if (FormatTok->is(tok::l_brace)) {
2102 parseBlock(/*MustBeDeclaration=*/false);
2103 // In ObjC interfaces, nothing should be following the "}".
2104 addUnwrappedLine();
Benjamin Kramere21cb742014-01-08 15:59:42 +00002105 } else if (FormatTok->is(tok::r_brace)) {
2106 // Ignore stray "}". parseStructuralElement doesn't consume them.
2107 nextToken();
2108 addUnwrappedLine();
Daniel Jaspera15da302013-08-28 08:04:23 +00002109 } else {
2110 parseStructuralElement();
2111 }
Nico Weber8696a8d2013-01-09 21:15:03 +00002112 } while (!eof());
2113}
2114
Nico Weber2ce0ac52013-01-09 23:25:37 +00002115void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
Nico Weber7eecf4b2013-01-09 20:25:35 +00002116 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002117 nextToken(); // interface name
Nico Weber7eecf4b2013-01-09 20:25:35 +00002118
2119 // @interface can be followed by either a base class, or a category.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002120 if (FormatTok->Tok.is(tok::colon)) {
Nico Weber7eecf4b2013-01-09 20:25:35 +00002121 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002122 nextToken(); // base class name
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002123 } else if (FormatTok->Tok.is(tok::l_paren))
Nico Weber7eecf4b2013-01-09 20:25:35 +00002124 // Skip category, if present.
2125 parseParens();
2126
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002127 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002128 parseObjCProtocolList();
Nico Weber7eecf4b2013-01-09 20:25:35 +00002129
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002130 if (FormatTok->Tok.is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002131 if (Style.BraceWrapping.AfterObjCDeclaration)
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002132 addUnwrappedLine();
Nico Weber9096fc02013-06-26 00:30:14 +00002133 parseBlock(/*MustBeDeclaration=*/true);
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002134 }
Nico Weber7eecf4b2013-01-09 20:25:35 +00002135
2136 // With instance variables, this puts '}' on its own line. Without instance
2137 // variables, this ends the @interface line.
2138 addUnwrappedLine();
2139
Nico Weber8696a8d2013-01-09 21:15:03 +00002140 parseObjCUntilAtEnd();
2141}
Nico Weber7eecf4b2013-01-09 20:25:35 +00002142
Nico Weber8696a8d2013-01-09 21:15:03 +00002143void UnwrappedLineParser::parseObjCProtocol() {
2144 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002145 nextToken(); // protocol name
Nico Weber8696a8d2013-01-09 21:15:03 +00002146
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002147 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002148 parseObjCProtocolList();
2149
2150 // Check for protocol declaration.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002151 if (FormatTok->Tok.is(tok::semi)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002152 nextToken();
2153 return addUnwrappedLine();
2154 }
2155
2156 addUnwrappedLine();
2157 parseObjCUntilAtEnd();
Nico Weber7eecf4b2013-01-09 20:25:35 +00002158}
2159
Daniel Jasperfca735c2015-02-19 16:14:18 +00002160void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
Martin Probst053f1aa2016-04-19 14:55:37 +00002161 bool IsImport = FormatTok->is(Keywords.kw_import);
2162 assert(IsImport || FormatTok->is(tok::kw_export));
Daniel Jasper354aa512015-02-19 16:07:32 +00002163 nextToken();
Daniel Jasperfca735c2015-02-19 16:14:18 +00002164
Daniel Jasperec05fc72015-05-11 09:14:50 +00002165 // Consume the "default" in "export default class/function".
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002166 if (FormatTok->is(tok::kw_default))
2167 nextToken();
Daniel Jasperec05fc72015-05-11 09:14:50 +00002168
Martin Probst5f8445b2016-04-24 22:05:09 +00002169 // Consume "async function", "function" and "default function", so that these
2170 // get parsed as free-standing JS functions, i.e. do not require a trailing
2171 // semicolon.
2172 if (FormatTok->is(Keywords.kw_async))
2173 nextToken();
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002174 if (FormatTok->is(Keywords.kw_function)) {
2175 nextToken();
2176 return;
2177 }
2178
Martin Probst053f1aa2016-04-19 14:55:37 +00002179 // For imports, `export *`, `export {...}`, consume the rest of the line up
2180 // to the terminating `;`. For everything else, just return and continue
2181 // parsing the structural element, i.e. the declaration or expression for
2182 // `export default`.
2183 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2184 !FormatTok->isStringLiteral())
2185 return;
Daniel Jasperfca735c2015-02-19 16:14:18 +00002186
Martin Probstd40bca42017-01-09 08:56:36 +00002187 while (!eof()) {
2188 if (FormatTok->is(tok::semi))
2189 return;
Krasimir Georgiev112c2e92017-11-09 13:22:03 +00002190 if (Line->Tokens.empty()) {
Martin Probstd40bca42017-01-09 08:56:36 +00002191 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2192 // import statement should terminate.
2193 return;
2194 }
Daniel Jasperefc1a832016-01-07 08:53:35 +00002195 if (FormatTok->is(tok::l_brace)) {
2196 FormatTok->BlockKind = BK_Block;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002197 nextToken();
Daniel Jasperefc1a832016-01-07 08:53:35 +00002198 parseBracedList();
2199 } else {
2200 nextToken();
2201 }
Daniel Jasper354aa512015-02-19 16:07:32 +00002202 }
2203}
2204
Daniel Jasper3b203a62013-09-05 16:05:56 +00002205LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2206 StringRef Prefix = "") {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002207 llvm::dbgs() << Prefix << "Line(" << Line.Level
2208 << ", FSC=" << Line.FirstStartColumn << ")"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002209 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2210 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2211 E = Line.Tokens.end();
2212 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002213 llvm::dbgs() << I->Tok->Tok.getName() << "["
Manuel Klimek89628f62017-09-20 09:51:03 +00002214 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2215 << "] ";
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002216 }
2217 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2218 E = Line.Tokens.end();
2219 I != E; ++I) {
2220 const UnwrappedLineNode &Node = *I;
2221 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2222 I = Node.Children.begin(),
2223 E = Node.Children.end();
2224 I != E; ++I) {
2225 printDebugInfo(*I, "\nChild: ");
2226 }
2227 }
2228 llvm::dbgs() << "\n";
2229}
2230
Daniel Jasperf7935112012-12-03 18:12:45 +00002231void UnwrappedLineParser::addUnwrappedLine() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002232 if (Line->Tokens.empty())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00002233 return;
Manuel Klimekab3dc002013-01-16 12:31:12 +00002234 DEBUG({
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002235 if (CurrentLines == &Lines)
2236 printDebugInfo(*Line);
Manuel Klimekab3dc002013-01-16 12:31:12 +00002237 });
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002238 CurrentLines->push_back(std::move(*Line));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002239 Line->Tokens.clear();
Krasimir Georgiev85c37042017-03-01 16:38:08 +00002240 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002241 Line->FirstStartColumn = 0;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002242 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002243 CurrentLines->append(
2244 std::make_move_iterator(PreprocessorDirectives.begin()),
2245 std::make_move_iterator(PreprocessorDirectives.end()));
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002246 PreprocessorDirectives.clear();
2247 }
Manuel Klimeke411aa82017-09-20 09:29:37 +00002248 // Disconnect the current token from the last token on the previous line.
2249 FormatTok->Previous = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +00002250}
2251
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002252bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
Daniel Jasperf7935112012-12-03 18:12:45 +00002253
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002254bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002255 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2256 FormatTok.NewlinesBefore > 0;
2257}
2258
Krasimir Georgiev91834222017-01-25 13:58:58 +00002259// Checks if \p FormatTok is a line comment that continues the line comment
2260// section on \p Line.
Krasimir Georgievea222a72017-05-22 10:07:56 +00002261static bool continuesLineCommentSection(const FormatToken &FormatTok,
2262 const UnwrappedLine &Line,
2263 llvm::Regex &CommentPragmasRegex) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002264 if (Line.Tokens.empty())
2265 return false;
Krasimir Georgiev84321612017-01-30 19:18:55 +00002266
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002267 StringRef IndentContent = FormatTok.TokenText;
2268 if (FormatTok.TokenText.startswith("//") ||
2269 FormatTok.TokenText.startswith("/*"))
2270 IndentContent = FormatTok.TokenText.substr(2);
2271 if (CommentPragmasRegex.match(IndentContent))
2272 return false;
2273
Krasimir Georgiev91834222017-01-25 13:58:58 +00002274 // If Line starts with a line comment, then FormatTok continues the comment
Krasimir Georgiev84321612017-01-30 19:18:55 +00002275 // section if its original column is greater or equal to the original start
Krasimir Georgiev91834222017-01-25 13:58:58 +00002276 // column of the line.
2277 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002278 // Define the min column token of a line as follows: if a line ends in '{' or
2279 // contains a '{' followed by a line comment, then the min column token is
2280 // that '{'. Otherwise, the min column token of the line is the first token of
2281 // the line.
2282 //
2283 // If Line starts with a token other than a line comment, then FormatTok
2284 // continues the comment section if its original column is greater than the
2285 // original start column of the min column token of the line.
Krasimir Georgiev91834222017-01-25 13:58:58 +00002286 //
2287 // For example, the second line comment continues the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002288 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002289 // // first line
2290 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002291 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002292 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002293 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002294 // // first line
2295 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002296 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002297 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002298 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002299 // int i; // first line
2300 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002301 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002302 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002303 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002304 // do { // first line
2305 // // second line
2306 // int i;
2307 // } while (true);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002308 //
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002309 // and:
2310 //
2311 // enum {
2312 // a, // first line
2313 // // second line
2314 // b
2315 // };
2316 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002317 // The second line comment doesn't continue the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002318 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002319 // // first line
2320 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002321 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002322 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002323 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002324 // int i; // first line
2325 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002326 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002327 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002328 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002329 // do { // first line
2330 // // second line
2331 // int i;
2332 // } while (true);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002333 //
2334 // and:
2335 //
2336 // enum {
2337 // a, // first line
2338 // // second line
2339 // };
Krasimir Georgiev84321612017-01-30 19:18:55 +00002340 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2341
2342 // Scan for '{//'. If found, use the column of '{' as a min column for line
2343 // comment section continuation.
2344 const FormatToken *PreviousToken = nullptr;
Krasimir Georgievd86c25d2017-03-10 13:09:29 +00002345 for (const UnwrappedLineNode &Node : Line.Tokens) {
Krasimir Georgiev84321612017-01-30 19:18:55 +00002346 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2347 isLineComment(*Node.Tok)) {
2348 MinColumnToken = PreviousToken;
2349 break;
2350 }
2351 PreviousToken = Node.Tok;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002352
2353 // Grab the last newline preceding a token in this unwrapped line.
2354 if (Node.Tok->NewlinesBefore > 0) {
2355 MinColumnToken = Node.Tok;
2356 }
Krasimir Georgiev84321612017-01-30 19:18:55 +00002357 }
2358 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2359 MinColumnToken = PreviousToken;
2360 }
2361
Krasimir Georgievea222a72017-05-22 10:07:56 +00002362 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2363 MinColumnToken);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002364}
2365
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002366void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2367 bool JustComments = Line->Tokens.empty();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002368 for (SmallVectorImpl<FormatToken *>::const_iterator
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002369 I = CommentsBeforeNextToken.begin(),
2370 E = CommentsBeforeNextToken.end();
2371 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002372 // Line comments that belong to the same line comment section are put on the
2373 // same line since later we might want to reflow content between them.
Krasimir Georgiev753625b2017-01-31 13:32:38 +00002374 // Additional fine-grained breaking of line comment sections is controlled
2375 // by the class BreakableLineCommentSection in case it is desirable to keep
2376 // several line comment sections in the same unwrapped line.
2377 //
2378 // FIXME: Consider putting separate line comment sections as children to the
2379 // unwrapped line instead.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002380 (*I)->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002381 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002382 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002383 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002384 pushToken(*I);
2385 }
Daniel Jaspere60cba12015-05-13 11:35:53 +00002386 if (NewlineBeforeNext && JustComments)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002387 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002388 CommentsBeforeNextToken.clear();
2389}
2390
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002391void UnwrappedLineParser::nextToken(int LevelDifference) {
Daniel Jasperf7935112012-12-03 18:12:45 +00002392 if (eof())
2393 return;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002394 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002395 pushToken(FormatTok);
Manuel Klimek89628f62017-09-20 09:51:03 +00002396 FormatToken *Previous = FormatTok;
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002397 if (Style.Language != FormatStyle::LK_JavaScript)
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002398 readToken(LevelDifference);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002399 else
2400 readTokenWithJavaScriptASI();
Manuel Klimeke411aa82017-09-20 09:29:37 +00002401 FormatTok->Previous = Previous;
Daniel Jasperb9a49902016-01-09 15:56:28 +00002402}
2403
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002404void UnwrappedLineParser::distributeComments(
2405 const SmallVectorImpl<FormatToken *> &Comments,
2406 const FormatToken *NextTok) {
2407 // Whether or not a line comment token continues a line is controlled by
Krasimir Georgievea222a72017-05-22 10:07:56 +00002408 // the method continuesLineCommentSection, with the following caveat:
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002409 //
2410 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2411 // that each comment line from the trail is aligned with the next token, if
2412 // the next token exists. If a trail exists, the beginning of the maximal
2413 // trail is marked as a start of a new comment section.
2414 //
2415 // For example in this code:
2416 //
2417 // int a; // line about a
2418 // // line 1 about b
2419 // // line 2 about b
2420 // int b;
2421 //
2422 // the two lines about b form a maximal trail, so there are two sections, the
2423 // first one consisting of the single comment "// line about a" and the
2424 // second one consisting of the next two comments.
2425 if (Comments.empty())
2426 return;
2427 bool ShouldPushCommentsInCurrentLine = true;
2428 bool HasTrailAlignedWithNextToken = false;
2429 unsigned StartOfTrailAlignedWithNextToken = 0;
2430 if (NextTok) {
2431 // We are skipping the first element intentionally.
2432 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2433 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2434 HasTrailAlignedWithNextToken = true;
2435 StartOfTrailAlignedWithNextToken = i;
2436 }
2437 }
2438 }
2439 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2440 FormatToken *FormatTok = Comments[i];
Manuel Klimek89628f62017-09-20 09:51:03 +00002441 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002442 FormatTok->ContinuesLineCommentSection = false;
2443 } else {
2444 FormatTok->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002445 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002446 }
2447 if (!FormatTok->ContinuesLineCommentSection &&
2448 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2449 ShouldPushCommentsInCurrentLine = false;
2450 }
2451 if (ShouldPushCommentsInCurrentLine) {
2452 pushToken(FormatTok);
2453 } else {
2454 CommentsBeforeNextToken.push_back(FormatTok);
2455 }
2456 }
2457}
2458
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002459void UnwrappedLineParser::readToken(int LevelDifference) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002460 SmallVector<FormatToken *, 1> Comments;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002461 do {
2462 FormatTok = Tokens->getNextToken();
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00002463 assert(FormatTok);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002464 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2465 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002466 distributeComments(Comments, FormatTok);
2467 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002468 // If there is an unfinished unwrapped line, we flush the preprocessor
2469 // directives only after that unwrapped line was finished later.
Daniel Jasper29d39d52015-02-08 09:34:49 +00002470 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002471 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002472 assert((LevelDifference >= 0 ||
2473 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2474 "LevelDifference makes Line->Level negative");
2475 Line->Level += LevelDifference;
Alexander Kornienkob1be9d62013-04-03 12:38:53 +00002476 // Comments stored before the preprocessor directive need to be output
2477 // before the preprocessor directive, at the same level as the
2478 // preprocessor directive, as we consider them to apply to the directive.
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002479 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002480 parsePPDirective();
2481 }
Manuel Klimek68b03042014-04-14 09:14:11 +00002482 while (FormatTok->Type == TT_ConflictStart ||
2483 FormatTok->Type == TT_ConflictEnd ||
2484 FormatTok->Type == TT_ConflictAlternative) {
2485 if (FormatTok->Type == TT_ConflictStart) {
2486 conditionalCompilationStart(/*Unreachable=*/false);
2487 } else if (FormatTok->Type == TT_ConflictAlternative) {
2488 conditionalCompilationAlternative();
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002489 } else if (FormatTok->Type == TT_ConflictEnd) {
Manuel Klimek68b03042014-04-14 09:14:11 +00002490 conditionalCompilationEnd();
2491 }
2492 FormatTok = Tokens->getNextToken();
2493 FormatTok->MustBreakBefore = true;
2494 }
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002495
Francois Ferranda98a95c2017-07-28 07:56:14 +00002496 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002497 !Line->InPPDirective) {
2498 continue;
2499 }
2500
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002501 if (!FormatTok->Tok.is(tok::comment)) {
2502 distributeComments(Comments, FormatTok);
2503 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002504 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002505 }
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002506
2507 Comments.push_back(FormatTok);
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002508 } while (!eof());
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002509
2510 distributeComments(Comments, nullptr);
2511 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002512}
2513
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002514void UnwrappedLineParser::pushToken(FormatToken *Tok) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002515 Line->Tokens.push_back(UnwrappedLineNode(Tok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002516 if (MustBreakBeforeNextToken) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002517 Line->Tokens.back().Tok->MustBreakBefore = true;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002518 MustBreakBeforeNextToken = false;
Manuel Klimek1abf7892013-01-04 23:34:14 +00002519 }
Daniel Jasperf7935112012-12-03 18:12:45 +00002520}
2521
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002522} // end namespace format
2523} // end namespace clang