blob: e41af026dfcd0d908a6d625e0e170da072493993 [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;
Nico Weberc29f83b2018-01-23 16:30:56 +0000336 case tok::kw_default: {
337 unsigned StoredPosition = Tokens->getPosition();
338 FormatToken *Next = Tokens->getNextToken();
339 FormatTok = Tokens->setPosition(StoredPosition);
340 if (Next && Next->isNot(tok::colon)) {
341 // default not followed by ':' is not a case label; treat it like
342 // an identifier.
343 parseStructuralElement();
344 break;
345 }
346 // Else, if it is 'default:', fall through to the case handling.
347 }
Daniel Jasper516d7972013-07-25 11:31:57 +0000348 case tok::kw_case:
Manuel Klimek89628f62017-09-20 09:51:03 +0000349 if (Style.Language == FormatStyle::LK_JavaScript &&
350 Line->MustBeDeclaration) {
Martin Probstf785fd92017-08-04 17:07:15 +0000351 // A 'case: string' style field declaration.
352 parseStructuralElement();
353 break;
354 }
Daniel Jasper72407622013-09-02 08:26:29 +0000355 if (!SwitchLabelEncountered &&
356 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
357 ++Line->Level;
Daniel Jasper516d7972013-07-25 11:31:57 +0000358 SwitchLabelEncountered = true;
359 parseStructuralElement();
360 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000361 default:
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000362 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +0000363 break;
364 }
365 } while (!eof());
366}
367
Daniel Jasperadba2aa2015-05-18 12:52:00 +0000368void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
Manuel Klimekab419912013-05-23 09:41:43 +0000369 // We'll parse forward through the tokens until we hit
370 // a closing brace or eof - note that getNextToken() will
371 // parse macros, so this will magically work inside macro
372 // definitions, too.
373 unsigned StoredPosition = Tokens->getPosition();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000374 FormatToken *Tok = FormatTok;
Manuel Klimek89628f62017-09-20 09:51:03 +0000375 const FormatToken *PrevTok = Tok->Previous;
Manuel Klimekab419912013-05-23 09:41:43 +0000376 // Keep a stack of positions of lbrace tokens. We will
377 // update information about whether an lbrace starts a
378 // braced init list or a different block during the loop.
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000379 SmallVector<FormatToken *, 8> LBraceStack;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000380 assert(Tok->Tok.is(tok::l_brace));
Manuel Klimekab419912013-05-23 09:41:43 +0000381 do {
Daniel Jaspereb65e912015-12-21 18:31:15 +0000382 // Get next non-comment token.
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000383 FormatToken *NextTok;
Daniel Jasperca7bd722013-07-01 16:43:38 +0000384 unsigned ReadTokens = 0;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000385 do {
386 NextTok = Tokens->getNextToken();
Daniel Jasperca7bd722013-07-01 16:43:38 +0000387 ++ReadTokens;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000388 } while (NextTok->is(tok::comment));
389
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000390 switch (Tok->Tok.getKind()) {
Manuel Klimekab419912013-05-23 09:41:43 +0000391 case tok::l_brace:
Martin Probst95ed8e72017-05-31 09:29:40 +0000392 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
Martin Probste8e27ca2017-11-25 09:33:47 +0000393 if (PrevTok->isOneOf(tok::colon, tok::less))
394 // A ':' indicates this code is in a type, or a braced list
395 // following a label in an object literal ({a: {b: 1}}).
396 // A '<' could be an object used in a comparison, but that is nonsense
397 // code (can never return true), so more likely it is a generic type
398 // argument (`X<{a: string; b: number}>`).
399 // The code below could be confused by semicolons between the
400 // individual members in a type member list, which would normally
401 // trigger BK_Block. In both cases, this must be parsed as an inline
402 // braced init.
Martin Probst95ed8e72017-05-31 09:29:40 +0000403 Tok->BlockKind = BK_BracedInit;
404 else if (PrevTok->is(tok::r_paren))
405 // `) { }` can only occur in function or method declarations in JS.
406 Tok->BlockKind = BK_Block;
407 } else {
Daniel Jasperb9a49902016-01-09 15:56:28 +0000408 Tok->BlockKind = BK_Unknown;
Martin Probst95ed8e72017-05-31 09:29:40 +0000409 }
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000410 LBraceStack.push_back(Tok);
Manuel Klimekab419912013-05-23 09:41:43 +0000411 break;
412 case tok::r_brace:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000413 if (LBraceStack.empty())
414 break;
415 if (LBraceStack.back()->BlockKind == BK_Unknown) {
416 bool ProbablyBracedList = false;
417 if (Style.Language == FormatStyle::LK_Proto) {
418 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
419 } else {
420 // Using OriginalColumn to distinguish between ObjC methods and
421 // binary operators is a bit hacky.
422 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
423 NextTok->OriginalColumn == 0;
Daniel Jasper91b032a2014-05-22 12:46:38 +0000424
Daniel Jasperb9a49902016-01-09 15:56:28 +0000425 // If there is a comma, semicolon or right paren after the closing
426 // brace, we assume this is a braced initializer list. Note that
427 // regardless how we mark inner braces here, we will overwrite the
428 // BlockKind later if we parse a braced list (where all blocks
429 // inside are by default braced lists), or when we explicitly detect
430 // blocks (for example while parsing lambdas).
Martin Probst95ed8e72017-05-31 09:29:40 +0000431 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
432 // braced list in JS.
Daniel Jasperb9a49902016-01-09 15:56:28 +0000433 ProbablyBracedList =
Daniel Jasperacffeb82016-03-05 18:34:26 +0000434 (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probste1e12a72016-08-19 14:35:01 +0000435 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
436 Keywords.kw_as)) ||
Martin Probstb7fb2672017-05-10 13:53:29 +0000437 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000438 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
439 tok::r_paren, tok::r_square, tok::l_brace,
Martin Probstb7fb2672017-05-10 13:53:29 +0000440 tok::l_square, tok::ellipsis) ||
Daniel Jaspere4ada022016-12-13 10:05:03 +0000441 (NextTok->is(tok::identifier) &&
442 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000443 (NextTok->is(tok::semi) &&
444 (!ExpectClassBody || LBraceStack.size() != 1)) ||
445 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
Manuel Klimekab419912013-05-23 09:41:43 +0000446 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000447 if (ProbablyBracedList) {
448 Tok->BlockKind = BK_BracedInit;
449 LBraceStack.back()->BlockKind = BK_BracedInit;
450 } else {
451 Tok->BlockKind = BK_Block;
452 LBraceStack.back()->BlockKind = BK_Block;
453 }
Manuel Klimekab419912013-05-23 09:41:43 +0000454 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000455 LBraceStack.pop_back();
Manuel Klimekab419912013-05-23 09:41:43 +0000456 break;
Daniel Jasperac7e34e2014-03-13 10:11:17 +0000457 case tok::at:
Manuel Klimekab419912013-05-23 09:41:43 +0000458 case tok::semi:
459 case tok::kw_if:
460 case tok::kw_while:
461 case tok::kw_for:
462 case tok::kw_switch:
463 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +0000464 case tok::kw___try:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000465 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000466 LBraceStack.back()->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000467 break;
468 default:
469 break;
470 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000471 PrevTok = Tok;
Manuel Klimekab419912013-05-23 09:41:43 +0000472 Tok = NextTok;
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000473 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
Daniel Jasperb9a49902016-01-09 15:56:28 +0000474
Manuel Klimekab419912013-05-23 09:41:43 +0000475 // Assume other blocks for all unclosed opening braces.
476 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000477 if (LBraceStack[i]->BlockKind == BK_Unknown)
478 LBraceStack[i]->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000479 }
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000480
Manuel Klimekab419912013-05-23 09:41:43 +0000481 FormatTok = Tokens->setPosition(StoredPosition);
482}
483
Francois Ferranda98a95c2017-07-28 07:56:14 +0000484template <class T>
485static inline void hash_combine(std::size_t &seed, const T &v) {
486 std::hash<T> hasher;
487 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
488}
489
490size_t UnwrappedLineParser::computePPHash() const {
491 size_t h = 0;
492 for (const auto &i : PPStack) {
493 hash_combine(h, size_t(i.Kind));
494 hash_combine(h, i.Line);
495 }
496 return h;
497}
498
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000499void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
500 bool MunchSemi) {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000501 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
502 "'{' or macro block token expected");
503 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
Daniel Jaspereb65e912015-12-21 18:31:15 +0000504 FormatTok->BlockKind = BK_Block;
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000505
Francois Ferranda98a95c2017-07-28 07:56:14 +0000506 size_t PPStartHash = computePPHash();
507
Daniel Jasper516d7972013-07-25 11:31:57 +0000508 unsigned InitialLevel = Line->Level;
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000509 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
Daniel Jasperf7935112012-12-03 18:12:45 +0000510
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000511 if (MacroBlock && FormatTok->is(tok::l_paren))
512 parseParens();
513
Francois Ferranda98a95c2017-07-28 07:56:14 +0000514 size_t NbPreprocessorDirectives =
515 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000516 addUnwrappedLine();
Francois Ferranda98a95c2017-07-28 07:56:14 +0000517 size_t OpeningLineIndex =
518 CurrentLines->empty()
519 ? (UnwrappedLine::kInvalidIndex)
520 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
Daniel Jasperf7935112012-12-03 18:12:45 +0000521
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000522 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
523 MustBeDeclaration);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000524 if (AddLevel)
525 ++Line->Level;
Nico Weber9096fc02013-06-26 00:30:14 +0000526 parseLevel(/*HasOpeningBrace=*/true);
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000527
Marianne Mailhot-Sarrasin03137c62016-04-14 14:56:49 +0000528 if (eof())
529 return;
530
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000531 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
532 : !FormatTok->is(tok::r_brace)) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000533 Line->Level = InitialLevel;
Daniel Jaspereb65e912015-12-21 18:31:15 +0000534 FormatTok->BlockKind = BK_Block;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000535 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000536 }
Alexander Kornienko0ea8e102012-12-04 15:40:36 +0000537
Francois Ferranda98a95c2017-07-28 07:56:14 +0000538 size_t PPEndHash = computePPHash();
539
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000540 // Munch the closing brace.
541 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000542
543 if (MacroBlock && FormatTok->is(tok::l_paren))
544 parseParens();
545
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000546 if (MunchSemi && FormatTok->Tok.is(tok::semi))
547 nextToken();
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000548 Line->Level = InitialLevel;
Francois Ferranda98a95c2017-07-28 07:56:14 +0000549
550 if (PPStartHash == PPEndHash) {
551 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
552 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
553 // Update the opening line to add the forward reference as well
554 (*CurrentLines)[OpeningLineIndex].MatchingOpeningBlockLineIndex =
555 CurrentLines->size() - 1;
556 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000557 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000558}
559
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000560static bool isGoogScope(const UnwrappedLine &Line) {
Daniel Jasper616de8642014-11-23 16:46:28 +0000561 // FIXME: Closure-library specific stuff should not be hard-coded but be
562 // configurable.
Daniel Jasper4a39c842014-05-06 13:54:10 +0000563 if (Line.Tokens.size() < 4)
564 return false;
565 auto I = Line.Tokens.begin();
566 if (I->Tok->TokenText != "goog")
567 return false;
568 ++I;
569 if (I->Tok->isNot(tok::period))
570 return false;
571 ++I;
572 if (I->Tok->TokenText != "scope")
573 return false;
574 ++I;
575 return I->Tok->is(tok::l_paren);
576}
577
Martin Probst101ec892017-05-09 20:04:09 +0000578static bool isIIFE(const UnwrappedLine &Line,
579 const AdditionalKeywords &Keywords) {
580 // Look for the start of an immediately invoked anonymous function.
581 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
582 // This is commonly done in JavaScript to create a new, anonymous scope.
583 // Example: (function() { ... })()
584 if (Line.Tokens.size() < 3)
585 return false;
586 auto I = Line.Tokens.begin();
587 if (I->Tok->isNot(tok::l_paren))
588 return false;
589 ++I;
590 if (I->Tok->isNot(Keywords.kw_function))
591 return false;
592 ++I;
593 return I->Tok->is(tok::l_paren);
594}
595
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000596static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
597 const FormatToken &InitialToken) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000598 if (InitialToken.is(tok::kw_namespace))
599 return Style.BraceWrapping.AfterNamespace;
600 if (InitialToken.is(tok::kw_class))
601 return Style.BraceWrapping.AfterClass;
602 if (InitialToken.is(tok::kw_union))
603 return Style.BraceWrapping.AfterUnion;
604 if (InitialToken.is(tok::kw_struct))
605 return Style.BraceWrapping.AfterStruct;
606 return false;
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000607}
608
Manuel Klimek516e0542013-09-04 13:25:30 +0000609void UnwrappedLineParser::parseChildBlock() {
610 FormatTok->BlockKind = BK_Block;
611 nextToken();
612 {
Manuel Klimek89628f62017-09-20 09:51:03 +0000613 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
614 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
Manuel Klimek516e0542013-09-04 13:25:30 +0000615 ScopedLineState LineState(*this);
616 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
617 /*MustBeDeclaration=*/false);
Martin Probst101ec892017-05-09 20:04:09 +0000618 Line->Level += SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000619 parseLevel(/*HasOpeningBrace=*/true);
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000620 flushComments(isOnNewLine(*FormatTok));
Martin Probst101ec892017-05-09 20:04:09 +0000621 Line->Level -= SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000622 }
623 nextToken();
624}
625
Daniel Jasperf7935112012-12-03 18:12:45 +0000626void UnwrappedLineParser::parsePPDirective() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000627 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
Manuel Klimek20e0af62015-05-06 11:56:29 +0000628 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000629 nextToken();
630
Craig Topper2145bc02014-05-09 08:15:10 +0000631 if (!FormatTok->Tok.getIdentifierInfo()) {
Manuel Klimek591b5802013-01-31 15:58:48 +0000632 parsePPUnknown();
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000633 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000634 }
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000635
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000636 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000637 case tok::pp_define:
638 parsePPDefine();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000639 return;
640 case tok::pp_if:
Manuel Klimek71814b42013-10-11 21:25:45 +0000641 parsePPIf(/*IfDef=*/false);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000642 break;
643 case tok::pp_ifdef:
644 case tok::pp_ifndef:
Manuel Klimek71814b42013-10-11 21:25:45 +0000645 parsePPIf(/*IfDef=*/true);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000646 break;
647 case tok::pp_else:
648 parsePPElse();
649 break;
650 case tok::pp_elif:
651 parsePPElIf();
652 break;
653 case tok::pp_endif:
654 parsePPEndIf();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000655 break;
656 default:
657 parsePPUnknown();
658 break;
659 }
660}
661
Manuel Klimek68b03042014-04-14 09:14:11 +0000662void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
Francois Ferranda98a95c2017-07-28 07:56:14 +0000663 size_t Line = CurrentLines->size();
664 if (CurrentLines == &PreprocessorDirectives)
665 Line += Lines.size();
666
667 if (Unreachable ||
668 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
669 PPStack.push_back({PP_Unreachable, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000670 else
Francois Ferranda98a95c2017-07-28 07:56:14 +0000671 PPStack.push_back({PP_Conditional, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000672}
673
Manuel Klimek68b03042014-04-14 09:14:11 +0000674void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000675 ++PPBranchLevel;
676 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
677 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
678 PPLevelBranchIndex.push_back(0);
679 PPLevelBranchCount.push_back(0);
680 }
681 PPChainBranchIndex.push(0);
Manuel Klimek68b03042014-04-14 09:14:11 +0000682 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
683 conditionalCompilationCondition(Unreachable || Skip);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000684}
685
Manuel Klimek68b03042014-04-14 09:14:11 +0000686void UnwrappedLineParser::conditionalCompilationAlternative() {
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000687 if (!PPStack.empty())
688 PPStack.pop_back();
Manuel Klimek71814b42013-10-11 21:25:45 +0000689 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
690 if (!PPChainBranchIndex.empty())
691 ++PPChainBranchIndex.top();
Manuel Klimek68b03042014-04-14 09:14:11 +0000692 conditionalCompilationCondition(
693 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
694 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000695}
696
Manuel Klimek68b03042014-04-14 09:14:11 +0000697void UnwrappedLineParser::conditionalCompilationEnd() {
Manuel Klimek71814b42013-10-11 21:25:45 +0000698 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
699 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
700 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000701 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
702 }
703 }
Manuel Klimek14bd9172014-01-29 08:49:02 +0000704 // Guard against #endif's without #if.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000705 if (PPBranchLevel > -1)
Manuel Klimek14bd9172014-01-29 08:49:02 +0000706 --PPBranchLevel;
Manuel Klimek71814b42013-10-11 21:25:45 +0000707 if (!PPChainBranchIndex.empty())
708 PPChainBranchIndex.pop();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000709 if (!PPStack.empty())
710 PPStack.pop_back();
Manuel Klimek68b03042014-04-14 09:14:11 +0000711}
712
713void UnwrappedLineParser::parsePPIf(bool IfDef) {
Daniel Jasper62703eb2017-03-01 11:10:11 +0000714 bool IfNDef = FormatTok->is(tok::pp_ifndef);
Manuel Klimek68b03042014-04-14 09:14:11 +0000715 nextToken();
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000716 bool Unreachable = false;
717 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
718 Unreachable = true;
Daniel Jasper62703eb2017-03-01 11:10:11 +0000719 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000720 Unreachable = true;
721 conditionalCompilationStart(Unreachable);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000722 FormatToken *IfCondition = FormatTok;
723 // If there's a #ifndef on the first line, and the only lines before it are
724 // comments, it could be an include guard.
725 bool MaybeIncludeGuard = IfNDef;
726 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard) {
727 for (auto &Line : Lines) {
728 if (!Line.Tokens.front().Tok->is(tok::comment)) {
729 MaybeIncludeGuard = false;
730 IncludeGuardRejected = true;
731 break;
732 }
733 }
734 }
735 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000736 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000737 ++PPBranchLevel;
738 if (!IncludeGuardRejected && !FoundIncludeGuardStart && MaybeIncludeGuard)
739 IfNdefCondition = IfCondition;
Manuel Klimek68b03042014-04-14 09:14:11 +0000740}
741
742void UnwrappedLineParser::parsePPElse() {
Krasimir Georgievad47c902017-08-30 14:34:57 +0000743 // If a potential include guard has an #else, it's not an include guard.
744 if (FoundIncludeGuardStart && PPBranchLevel == 0)
745 FoundIncludeGuardStart = false;
Manuel Klimek68b03042014-04-14 09:14:11 +0000746 conditionalCompilationAlternative();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000747 if (PPBranchLevel > -1)
748 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000749 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000750 ++PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000751}
752
753void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
754
755void UnwrappedLineParser::parsePPEndIf() {
756 conditionalCompilationEnd();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000757 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000758 // If the #endif of a potential include guard is the last thing in the file,
759 // then we count it as a real include guard and subtract one from every
760 // preprocessor indent.
761 unsigned TokenPosition = Tokens->getPosition();
762 FormatToken *PeekNext = AllTokens[TokenPosition];
Daniel Jasper4df130f2017-09-04 13:33:52 +0000763 if (FoundIncludeGuardStart && PPBranchLevel == -1 && PeekNext->is(tok::eof) &&
764 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
765 for (auto &Line : Lines)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000766 if (Line.InPPDirective && Line.Level > 0)
767 --Line.Level;
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000768}
769
Manuel Klimek1abf7892013-01-04 23:34:14 +0000770void UnwrappedLineParser::parsePPDefine() {
771 nextToken();
772
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000773 if (FormatTok->Tok.getKind() != tok::identifier) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000774 parsePPUnknown();
775 return;
776 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000777 if (IfNdefCondition && IfNdefCondition->TokenText == FormatTok->TokenText) {
778 FoundIncludeGuardStart = true;
779 for (auto &Line : Lines) {
780 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
781 FoundIncludeGuardStart = false;
782 break;
783 }
784 }
785 }
786 IfNdefCondition = nullptr;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000787 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000788 if (FormatTok->Tok.getKind() == tok::l_paren &&
789 FormatTok->WhitespaceRange.getBegin() ==
790 FormatTok->WhitespaceRange.getEnd()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000791 parseParens();
792 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000793 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
794 Line->Level += PPBranchLevel + 1;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000795 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000796 ++Line->Level;
Manuel Klimek1b896292013-01-07 09:34:28 +0000797
798 // Errors during a preprocessor directive can only affect the layout of the
799 // preprocessor directive, and thus we ignore them. An alternative approach
800 // would be to use the same approach we use on the file level (no
801 // re-indentation if there was a structural error) within the macro
802 // definition.
Manuel Klimek1abf7892013-01-04 23:34:14 +0000803 parseFile();
804}
805
806void UnwrappedLineParser::parsePPUnknown() {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000807 do {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000808 nextToken();
809 } while (!eof());
Krasimir Georgievad47c902017-08-30 14:34:57 +0000810 if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
811 Line->Level += PPBranchLevel + 1;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000812 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000813 IfNdefCondition = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +0000814}
815
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000816// Here we blacklist certain tokens that are not usually the first token in an
817// unwrapped line. This is used in attempt to distinguish macro calls without
818// trailing semicolons from other constructs split to several lines.
Benjamin Kramer8407df72015-03-09 16:47:52 +0000819static bool tokenCanStartNewLine(const clang::Token &Tok) {
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000820 // Semicolon can be a null-statement, l_square can be a start of a macro or
821 // a C++11 attribute, but this doesn't seem to be common.
822 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
823 Tok.isNot(tok::l_square) &&
824 // Tokens that can only be used as binary operators and a part of
825 // overloaded operator names.
826 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
827 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
828 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
829 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
830 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
831 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
832 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
833 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
834 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
835 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
836 Tok.isNot(tok::lesslessequal) &&
837 // Colon is used in labels, base class lists, initializer lists,
838 // range-based for loops, ternary operator, but should never be the
839 // first token in an unwrapped line.
Daniel Jasper5ebb2f32014-05-21 13:08:17 +0000840 Tok.isNot(tok::colon) &&
841 // 'noexcept' is a trailing annotation.
842 Tok.isNot(tok::kw_noexcept);
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000843}
844
Martin Probst533965c2016-04-19 18:19:06 +0000845static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
846 const FormatToken *FormatTok) {
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000847 // FIXME: This returns true for C/C++ keywords like 'struct'.
848 return FormatTok->is(tok::identifier) &&
849 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
Martin Probst3dbbefa2016-11-10 16:21:02 +0000850 !FormatTok->isOneOf(
851 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
852 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
853 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
854 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
855 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
Manuel Klimek89628f62017-09-20 09:51:03 +0000856 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
857 Keywords.kw_from));
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000858}
859
Martin Probst533965c2016-04-19 18:19:06 +0000860static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
861 const FormatToken *FormatTok) {
Martin Probstb9316ff2016-09-18 17:21:52 +0000862 return FormatTok->Tok.isLiteral() ||
863 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
864 mustBeJSIdent(Keywords, FormatTok);
Martin Probst533965c2016-04-19 18:19:06 +0000865}
866
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000867// isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
868// when encountered after a value (see mustBeJSIdentOrValue).
869static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
870 const FormatToken *FormatTok) {
871 return FormatTok->isOneOf(
Martin Probst5f8445b2016-04-24 22:05:09 +0000872 tok::kw_return, Keywords.kw_yield,
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000873 // conditionals
874 tok::kw_if, tok::kw_else,
875 // loops
876 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
877 // switch/case
878 tok::kw_switch, tok::kw_case,
879 // exceptions
880 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
881 // declaration
882 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
Martin Probst5f8445b2016-04-24 22:05:09 +0000883 Keywords.kw_async, Keywords.kw_function,
884 // import/export
885 Keywords.kw_import, tok::kw_export);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000886}
887
888// readTokenWithJavaScriptASI reads the next token and terminates the current
889// line if JavaScript Automatic Semicolon Insertion must
890// happen between the current token and the next token.
891//
892// This method is conservative - it cannot cover all edge cases of JavaScript,
893// but only aims to correctly handle certain well known cases. It *must not*
894// return true in speculative cases.
895void UnwrappedLineParser::readTokenWithJavaScriptASI() {
896 FormatToken *Previous = FormatTok;
897 readToken();
898 FormatToken *Next = FormatTok;
899
900 bool IsOnSameLine =
901 CommentsBeforeNextToken.empty()
902 ? Next->NewlinesBefore == 0
903 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
904 if (IsOnSameLine)
905 return;
906
907 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
Martin Probst717f6dc2016-10-21 05:11:38 +0000908 bool PreviousStartsTemplateExpr =
909 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
Martin Probst7e0f25b2017-11-25 09:19:42 +0000910 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
911 // If the line contains an '@' sign, the previous token might be an
912 // annotation, which can precede another identifier/value.
913 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
914 [](UnwrappedLineNode &LineNode) {
915 return LineNode.Tok->is(tok::at);
916 }) != Line->Tokens.end();
917 if (HasAt)
Martin Probstbbffeac2016-04-11 07:35:57 +0000918 return;
919 }
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000920 if (Next->is(tok::exclaim) && PreviousMustBeValue)
Martin Probstd40bca42017-01-09 08:56:36 +0000921 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000922 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
Martin Probst717f6dc2016-10-21 05:11:38 +0000923 bool NextEndsTemplateExpr =
924 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
925 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
926 (PreviousMustBeValue ||
927 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
928 tok::minusminus)))
Martin Probstd40bca42017-01-09 08:56:36 +0000929 return addUnwrappedLine();
Martin Probst0a19d432017-08-09 15:19:16 +0000930 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
931 isJSDeclOrStmt(Keywords, Next))
Martin Probstd40bca42017-01-09 08:56:36 +0000932 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000933}
934
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000935void UnwrappedLineParser::parseStructuralElement() {
Daniel Jasper498f5582015-12-25 08:53:31 +0000936 assert(!FormatTok->is(tok::l_brace));
937 if (Style.Language == FormatStyle::LK_TableGen &&
938 FormatTok->is(tok::pp_include)) {
939 nextToken();
940 if (FormatTok->is(tok::string_literal))
941 nextToken();
942 addUnwrappedLine();
943 return;
944 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000945 switch (FormatTok->Tok.getKind()) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000946 case tok::kw_asm:
Daniel Jasper8f463652014-08-26 23:15:12 +0000947 nextToken();
948 if (FormatTok->is(tok::l_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000949 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper2337f282015-01-12 10:14:56 +0000950 nextToken();
Daniel Jasper4429f142014-08-27 17:16:46 +0000951 while (FormatTok && FormatTok->isNot(tok::eof)) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000952 if (FormatTok->is(tok::r_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000953 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper8f463652014-08-26 23:15:12 +0000954 nextToken();
Daniel Jasper790d4f92015-05-11 11:59:46 +0000955 addUnwrappedLine();
Daniel Jasper8f463652014-08-26 23:15:12 +0000956 break;
957 }
Daniel Jasper2337f282015-01-12 10:14:56 +0000958 FormatTok->Finalized = true;
Daniel Jasper8f463652014-08-26 23:15:12 +0000959 nextToken();
960 }
961 }
962 break;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000963 case tok::kw_namespace:
964 parseNamespace();
965 return;
Dmitri Gribenko58d64e22012-12-30 21:27:25 +0000966 case tok::kw_inline:
967 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000968 if (FormatTok->Tok.is(tok::kw_namespace)) {
Dmitri Gribenko58d64e22012-12-30 21:27:25 +0000969 parseNamespace();
970 return;
971 }
972 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +0000973 case tok::kw_public:
974 case tok::kw_protected:
975 case tok::kw_private:
Daniel Jasper83709082015-02-18 17:14:05 +0000976 if (Style.Language == FormatStyle::LK_Java ||
977 Style.Language == FormatStyle::LK_JavaScript)
Daniel Jasperc58c70e2014-09-15 11:21:46 +0000978 nextToken();
979 else
980 parseAccessSpecifier();
Daniel Jasperf7935112012-12-03 18:12:45 +0000981 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +0000982 case tok::kw_if:
983 parseIfThenElse();
Daniel Jasperf7935112012-12-03 18:12:45 +0000984 return;
Alexander Kornienko37d6c942012-12-05 15:06:06 +0000985 case tok::kw_for:
986 case tok::kw_while:
987 parseForOrWhileLoop();
988 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +0000989 case tok::kw_do:
990 parseDoWhile();
991 return;
992 case tok::kw_switch:
Martin Probstf785fd92017-08-04 17:07:15 +0000993 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
994 // 'switch: string' field declaration.
995 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +0000996 parseSwitch();
997 return;
998 case tok::kw_default:
Martin Probstf785fd92017-08-04 17:07:15 +0000999 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1000 // 'default: string' field declaration.
1001 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001002 nextToken();
Nico Weberc29f83b2018-01-23 16:30:56 +00001003 if (FormatTok->is(tok::colon)) {
1004 parseLabel();
1005 return;
1006 }
1007 // e.g. "default void f() {}" in a Java interface.
1008 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001009 case tok::kw_case:
Martin Probstf785fd92017-08-04 17:07:15 +00001010 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1011 // 'case: string' field declaration.
1012 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001013 parseCaseLabel();
1014 return;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001015 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +00001016 case tok::kw___try:
Daniel Jasper04a71a42014-05-08 11:58:24 +00001017 parseTryCatch();
1018 return;
Manuel Klimekae610d12013-01-21 14:32:05 +00001019 case tok::kw_extern:
1020 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001021 if (FormatTok->Tok.is(tok::string_literal)) {
Manuel Klimekae610d12013-01-21 14:32:05 +00001022 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001023 if (FormatTok->Tok.is(tok::l_brace)) {
Krasimir Georgievd6ce9372017-09-15 11:23:50 +00001024 if (Style.BraceWrapping.AfterExternBlock) {
1025 addUnwrappedLine();
1026 parseBlock(/*MustBeDeclaration=*/true);
1027 } else {
1028 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1029 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001030 addUnwrappedLine();
1031 return;
1032 }
1033 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001034 break;
Daniel Jasperfca735c2015-02-19 16:14:18 +00001035 case tok::kw_export:
1036 if (Style.Language == FormatStyle::LK_JavaScript) {
1037 parseJavaScriptEs6ImportExport();
1038 return;
1039 }
1040 break;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001041 case tok::identifier:
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001042 if (FormatTok->is(TT_ForEachMacro)) {
Daniel Jaspere1e43192014-04-01 12:55:11 +00001043 parseForOrWhileLoop();
1044 return;
1045 }
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001046 if (FormatTok->is(TT_MacroBlockBegin)) {
1047 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1048 /*MunchSemi=*/false);
1049 return;
1050 }
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001051 if (FormatTok->is(Keywords.kw_import)) {
1052 if (Style.Language == FormatStyle::LK_JavaScript) {
1053 parseJavaScriptEs6ImportExport();
1054 return;
1055 }
1056 if (Style.Language == FormatStyle::LK_Proto) {
1057 nextToken();
Daniel Jasper8b61d142016-06-20 20:39:53 +00001058 if (FormatTok->is(tok::kw_public))
1059 nextToken();
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001060 if (!FormatTok->is(tok::string_literal))
1061 return;
1062 nextToken();
1063 if (FormatTok->is(tok::semi))
1064 nextToken();
1065 addUnwrappedLine();
1066 return;
1067 }
Daniel Jasper354aa512015-02-19 16:07:32 +00001068 }
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001069 if (Style.isCpp() &&
Daniel Jasper72b33572017-03-31 12:04:37 +00001070 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
Daniel Jaspera00de632015-12-01 12:05:04 +00001071 Keywords.kw_slots, Keywords.kw_qslots)) {
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001072 nextToken();
1073 if (FormatTok->is(tok::colon)) {
1074 nextToken();
1075 addUnwrappedLine();
Daniel Jasper31343832016-07-27 10:13:24 +00001076 return;
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001077 }
Daniel Jasper53395402015-04-07 15:04:40 +00001078 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001079 // In all other cases, parse the declaration.
1080 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001081 default:
1082 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001083 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001084 do {
Manuel Klimeke411aa82017-09-20 09:29:37 +00001085 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001086 switch (FormatTok->Tok.getKind()) {
Nico Weber372d8dc2013-02-10 20:35:35 +00001087 case tok::at:
1088 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001089 if (FormatTok->Tok.is(tok::l_brace)) {
1090 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001091 parseBracedList();
Nico Weberc068ff72018-01-23 17:10:25 +00001092 break;
1093 }
1094 switch (FormatTok->Tok.getObjCKeywordID()) {
1095 case tok::objc_public:
1096 case tok::objc_protected:
1097 case tok::objc_package:
1098 case tok::objc_private:
1099 return parseAccessSpecifier();
1100 case tok::objc_interface:
1101 case tok::objc_implementation:
1102 return parseObjCInterfaceOrImplementation();
1103 case tok::objc_protocol:
1104 if (parseObjCProtocol())
1105 return;
1106 break;
1107 case tok::objc_end:
1108 return; // Handled by the caller.
1109 case tok::objc_optional:
1110 case tok::objc_required:
1111 nextToken();
1112 addUnwrappedLine();
1113 return;
1114 case tok::objc_autoreleasepool:
1115 nextToken();
1116 if (FormatTok->Tok.is(tok::l_brace)) {
1117 if (Style.BraceWrapping.AfterObjCDeclaration)
1118 addUnwrappedLine();
1119 parseBlock(/*MustBeDeclaration=*/false);
1120 }
1121 addUnwrappedLine();
1122 return;
1123 case tok::objc_try:
1124 // This branch isn't strictly necessary (the kw_try case below would
1125 // do this too after the tok::at is parsed above). But be explicit.
1126 parseTryCatch();
1127 return;
1128 default:
1129 break;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001130 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001131 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001132 case tok::kw_enum:
Daniel Jaspera7900ad2016-05-08 18:12:22 +00001133 // Ignore if this is part of "template <enum ...".
1134 if (Previous && Previous->is(tok::less)) {
1135 nextToken();
1136 break;
1137 }
1138
Daniel Jasper90cf3802015-06-17 09:44:02 +00001139 // parseEnum falls through and does not yet add an unwrapped line as an
1140 // enum definition can start a structural element.
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001141 if (!parseEnum())
1142 break;
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001143 // This only applies for C++.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001144 if (!Style.isCpp()) {
Daniel Jasper90cf3802015-06-17 09:44:02 +00001145 addUnwrappedLine();
1146 return;
1147 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001148 break;
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001149 case tok::kw_typedef:
1150 nextToken();
Daniel Jasper31f6c542014-12-05 10:42:21 +00001151 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1152 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001153 parseEnum();
1154 break;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001155 case tok::kw_struct:
1156 case tok::kw_union:
Manuel Klimek28cacc72013-01-07 18:10:23 +00001157 case tok::kw_class:
Daniel Jasper910807d2015-06-12 04:52:02 +00001158 // parseRecord falls through and does not yet add an unwrapped line as a
1159 // record declaration or definition can start a structural element.
Manuel Klimeke01bab52013-01-15 13:38:33 +00001160 parseRecord();
Daniel Jasper910807d2015-06-12 04:52:02 +00001161 // This does not apply for Java and JavaScript.
1162 if (Style.Language == FormatStyle::LK_Java ||
1163 Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperd5ec65b2016-01-08 07:06:07 +00001164 if (FormatTok->is(tok::semi))
1165 nextToken();
Daniel Jasper910807d2015-06-12 04:52:02 +00001166 addUnwrappedLine();
1167 return;
1168 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00001169 break;
Daniel Jaspere5d74862014-11-26 08:17:08 +00001170 case tok::period:
1171 nextToken();
1172 // In Java, classes have an implicit static member "class".
1173 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1174 FormatTok->is(tok::kw_class))
1175 nextToken();
Daniel Jasperba52fcb2015-09-28 14:29:45 +00001176 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1177 FormatTok->Tok.getIdentifierInfo())
1178 // JavaScript only has pseudo keywords, all keywords are allowed to
1179 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1180 nextToken();
Daniel Jaspere5d74862014-11-26 08:17:08 +00001181 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001182 case tok::semi:
1183 nextToken();
1184 addUnwrappedLine();
1185 return;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001186 case tok::r_brace:
1187 addUnwrappedLine();
1188 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001189 case tok::l_paren:
1190 parseParens();
1191 break;
Daniel Jasper5af04a42015-10-07 03:43:10 +00001192 case tok::kw_operator:
1193 nextToken();
1194 if (FormatTok->isBinaryOperator())
1195 nextToken();
1196 break;
Manuel Klimek516e0542013-09-04 13:25:30 +00001197 case tok::caret:
1198 nextToken();
Daniel Jasper395193c2014-03-28 07:48:59 +00001199 if (FormatTok->Tok.isAnyIdentifier() ||
1200 FormatTok->isSimpleTypeSpecifier())
1201 nextToken();
1202 if (FormatTok->is(tok::l_paren))
1203 parseParens();
1204 if (FormatTok->is(tok::l_brace))
Manuel Klimek516e0542013-09-04 13:25:30 +00001205 parseChildBlock();
Manuel Klimek516e0542013-09-04 13:25:30 +00001206 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001207 case tok::l_brace:
Manuel Klimekab419912013-05-23 09:41:43 +00001208 if (!tryToParseBracedList()) {
1209 // A block outside of parentheses must be the last part of a
1210 // structural element.
1211 // FIXME: Figure out cases where this is not true, and add projections
1212 // for them (the one we know is missing are lambdas).
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001213 if (Style.BraceWrapping.AfterFunction)
Manuel Klimekab419912013-05-23 09:41:43 +00001214 addUnwrappedLine();
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001215 FormatTok->Type = TT_FunctionLBrace;
Nico Weber9096fc02013-06-26 00:30:14 +00001216 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001217 addUnwrappedLine();
Manuel Klimekab419912013-05-23 09:41:43 +00001218 return;
1219 }
1220 // Otherwise this was a braced init list, and the structural
1221 // element continues.
1222 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001223 case tok::kw_try:
1224 // We arrive here when parsing function-try blocks.
1225 parseTryCatch();
1226 return;
Daniel Jasper40e19212013-05-29 13:16:10 +00001227 case tok::identifier: {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001228 if (FormatTok->is(TT_MacroBlockEnd)) {
1229 addUnwrappedLine();
1230 return;
1231 }
1232
Martin Probst973ff792017-04-27 13:07:24 +00001233 // Function declarations (as opposed to function expressions) are parsed
1234 // on their own unwrapped line by continuing this loop. Function
1235 // expressions (functions that are not on their own line) must not create
1236 // a new unwrapped line, so they are special cased below.
1237 size_t TokenCount = Line->Tokens.size();
Daniel Jasper9326f912015-05-05 08:40:32 +00001238 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst973ff792017-04-27 13:07:24 +00001239 FormatTok->is(Keywords.kw_function) &&
1240 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1241 Keywords.kw_async)))) {
Daniel Jasper069e5f42014-05-20 11:14:57 +00001242 tryToParseJSFunction();
1243 break;
1244 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001245 if ((Style.Language == FormatStyle::LK_JavaScript ||
1246 Style.Language == FormatStyle::LK_Java) &&
1247 FormatTok->is(Keywords.kw_interface)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001248 if (Style.Language == FormatStyle::LK_JavaScript) {
1249 // In JavaScript/TypeScript, "interface" can be used as a standalone
1250 // identifier, e.g. in `var interface = 1;`. If "interface" is
1251 // followed by another identifier, it is very like to be an actual
1252 // interface declaration.
1253 unsigned StoredPosition = Tokens->getPosition();
1254 FormatToken *Next = Tokens->getNextToken();
1255 FormatTok = Tokens->setPosition(StoredPosition);
Martin Probst533965c2016-04-19 18:19:06 +00001256 if (Next && !mustBeJSIdent(Keywords, Next)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001257 nextToken();
1258 break;
1259 }
1260 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001261 parseRecord();
Daniel Jasper259188b2015-06-12 04:56:34 +00001262 addUnwrappedLine();
Daniel Jasper5c235c02015-07-06 14:26:04 +00001263 return;
Daniel Jasper9326f912015-05-05 08:40:32 +00001264 }
1265
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00001266 // See if the following token should start a new unwrapped line.
Daniel Jasper9326f912015-05-05 08:40:32 +00001267 StringRef Text = FormatTok->TokenText;
Daniel Jasperf7935112012-12-03 18:12:45 +00001268 nextToken();
Daniel Jasper83709082015-02-18 17:14:05 +00001269 if (Line->Tokens.size() == 1 &&
1270 // JS doesn't have macros, and within classes colons indicate fields,
1271 // not labels.
Daniel Jasper676e5162015-04-07 14:36:33 +00001272 Style.Language != FormatStyle::LK_JavaScript) {
1273 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
Daniel Jasper40609472016-04-06 15:02:46 +00001274 Line->Tokens.begin()->Tok->MustBreakBefore = true;
Alexander Kornienkode644272013-04-08 22:16:06 +00001275 parseLabel();
1276 return;
1277 }
Daniel Jasper680b09b2014-11-05 10:48:04 +00001278 // Recognize function-like macro usages without trailing semicolon as
Daniel Jasper83709082015-02-18 17:14:05 +00001279 // well as free-standing macros like Q_OBJECT.
Daniel Jasper680b09b2014-11-05 10:48:04 +00001280 bool FunctionLike = FormatTok->is(tok::l_paren);
1281 if (FunctionLike)
Alexander Kornienkode644272013-04-08 22:16:06 +00001282 parseParens();
Daniel Jaspere60cba12015-05-13 11:35:53 +00001283
1284 bool FollowedByNewline =
1285 CommentsBeforeNextToken.empty()
1286 ? FormatTok->NewlinesBefore > 0
1287 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1288
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001289 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
Daniel Jasper680b09b2014-11-05 10:48:04 +00001290 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
Daniel Jasper40e19212013-05-29 13:16:10 +00001291 addUnwrappedLine();
Daniel Jasper41a0f782013-05-29 14:09:17 +00001292 return;
Alexander Kornienkode644272013-04-08 22:16:06 +00001293 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001294 }
1295 break;
Daniel Jasper40e19212013-05-29 13:16:10 +00001296 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001297 case tok::equal:
Manuel Klimek79e06082015-05-21 12:23:34 +00001298 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1299 // TT_JsFatArrow. The always start an expression or a child block if
1300 // followed by a curly.
1301 if (FormatTok->is(TT_JsFatArrow)) {
1302 nextToken();
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001303 if (FormatTok->is(tok::l_brace))
Manuel Klimek79e06082015-05-21 12:23:34 +00001304 parseChildBlock();
Manuel Klimek79e06082015-05-21 12:23:34 +00001305 break;
1306 }
1307
Daniel Jaspere25509f2012-12-17 11:29:41 +00001308 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001309 if (FormatTok->Tok.is(tok::l_brace)) {
1310 nextToken();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001311 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001312 } else if (Style.Language == FormatStyle::LK_Proto &&
Manuel Klimek89628f62017-09-20 09:51:03 +00001313 FormatTok->Tok.is(tok::less)) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001314 nextToken();
Krasimir Georgiev0b41fcb2017-06-27 13:58:41 +00001315 parseBracedList(/*ContinueOnSemicolons=*/false,
1316 /*ClosingBraceKind=*/tok::greater);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001317 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001318 break;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001319 case tok::l_square:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001320 parseSquare();
Manuel Klimekffdeb592013-09-03 15:10:01 +00001321 break;
Daniel Jasper6acf5132015-03-12 14:44:29 +00001322 case tok::kw_new:
1323 parseNew();
1324 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001325 default:
1326 nextToken();
1327 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001328 }
1329 } while (!eof());
1330}
1331
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001332bool UnwrappedLineParser::tryToParseLambda() {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001333 if (!Style.isCpp()) {
Daniel Jasper1feab0f2015-06-02 15:31:37 +00001334 nextToken();
1335 return false;
1336 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001337 assert(FormatTok->is(tok::l_square));
1338 FormatToken &LSquare = *FormatTok;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001339 if (!tryToParseLambdaIntroducer())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001340 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001341
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00001342 while (FormatTok->isNot(tok::l_brace)) {
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001343 if (FormatTok->isSimpleTypeSpecifier()) {
1344 nextToken();
1345 continue;
1346 }
Manuel Klimekffdeb592013-09-03 15:10:01 +00001347 switch (FormatTok->Tok.getKind()) {
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001348 case tok::l_brace:
1349 break;
1350 case tok::l_paren:
1351 parseParens();
1352 break;
Daniel Jasperbcb55ee2014-11-21 14:08:38 +00001353 case tok::amp:
1354 case tok::star:
1355 case tok::kw_const:
Daniel Jasper3431b752014-12-08 13:22:37 +00001356 case tok::comma:
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001357 case tok::less:
1358 case tok::greater:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001359 case tok::identifier:
Daniel Jasper5eaa0092015-08-13 13:37:08 +00001360 case tok::numeric_constant:
Daniel Jasper1067ab02014-02-11 10:16:55 +00001361 case tok::coloncolon:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001362 case tok::kw_mutable:
Daniel Jasper81a20782014-03-10 10:02:02 +00001363 nextToken();
1364 break;
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001365 case tok::arrow:
Daniel Jasper6f2b88a2015-06-05 13:18:09 +00001366 FormatTok->Type = TT_LambdaArrow;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001367 nextToken();
1368 break;
1369 default:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001370 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001371 }
1372 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001373 LSquare.Type = TT_LambdaLSquare;
Manuel Klimek516e0542013-09-04 13:25:30 +00001374 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001375 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001376}
1377
1378bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
Manuel Klimek89628f62017-09-20 09:51:03 +00001379 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001380 if (Previous &&
1381 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1382 tok::kw_delete) ||
Manuel Klimek89628f62017-09-20 09:51:03 +00001383 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1384 Previous->isSimpleTypeSpecifier())) {
Manuel Klimekffdeb592013-09-03 15:10:01 +00001385 nextToken();
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001386 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001387 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001388 nextToken();
1389 parseSquare(/*LambdaIntroducer=*/true);
1390 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001391}
1392
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001393void UnwrappedLineParser::tryToParseJSFunction() {
Martin Probst409697e2016-05-29 14:41:07 +00001394 assert(FormatTok->is(Keywords.kw_function) ||
1395 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
Martin Probst5f8445b2016-04-24 22:05:09 +00001396 if (FormatTok->is(Keywords.kw_async))
1397 nextToken();
1398 // Consume "function".
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001399 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001400
Daniel Jasper71e50af2016-11-01 06:22:59 +00001401 // Consume * (generator function). Treat it like C++'s overloaded operators.
1402 if (FormatTok->is(tok::star)) {
1403 FormatTok->Type = TT_OverloadedOperator;
Martin Probst5f8445b2016-04-24 22:05:09 +00001404 nextToken();
Daniel Jasper71e50af2016-11-01 06:22:59 +00001405 }
Martin Probst5f8445b2016-04-24 22:05:09 +00001406
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001407 // Consume function name.
1408 if (FormatTok->is(tok::identifier))
Daniel Jasperfca735c2015-02-19 16:14:18 +00001409 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001410
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001411 if (FormatTok->isNot(tok::l_paren))
1412 return;
Manuel Klimek79e06082015-05-21 12:23:34 +00001413
1414 // Parse formal parameter list.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001415 parseParens();
Manuel Klimek79e06082015-05-21 12:23:34 +00001416
1417 if (FormatTok->is(tok::colon)) {
1418 // Parse a type definition.
1419 nextToken();
1420
1421 // Eat the type declaration. For braced inline object types, balance braces,
1422 // otherwise just parse until finding an l_brace for the function body.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001423 if (FormatTok->is(tok::l_brace))
1424 tryToParseBracedList();
1425 else
Martin Probstaf16c502017-01-04 13:36:43 +00001426 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
Manuel Klimek79e06082015-05-21 12:23:34 +00001427 nextToken();
Manuel Klimek79e06082015-05-21 12:23:34 +00001428 }
1429
Martin Probstaf16c502017-01-04 13:36:43 +00001430 if (FormatTok->is(tok::semi))
1431 return;
1432
Manuel Klimek79e06082015-05-21 12:23:34 +00001433 parseChildBlock();
1434}
1435
Daniel Jasper3c883d12015-05-18 14:49:19 +00001436bool UnwrappedLineParser::tryToParseBracedList() {
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001437 if (FormatTok->BlockKind == BK_Unknown)
Daniel Jasper3c883d12015-05-18 14:49:19 +00001438 calculateBraceTypes();
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001439 assert(FormatTok->BlockKind != BK_Unknown);
1440 if (FormatTok->BlockKind == BK_Block)
Manuel Klimekab419912013-05-23 09:41:43 +00001441 return false;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001442 nextToken();
Manuel Klimekab419912013-05-23 09:41:43 +00001443 parseBracedList();
1444 return true;
1445}
1446
Krasimir Georgievff747be2017-06-27 13:43:07 +00001447bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1448 tok::TokenKind ClosingBraceKind) {
Daniel Jasper015ed022013-09-13 09:20:45 +00001449 bool HasError = false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001450
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001451 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1452 // replace this by using parseAssigmentExpression() inside.
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001453 do {
Manuel Klimek79e06082015-05-21 12:23:34 +00001454 if (Style.Language == FormatStyle::LK_JavaScript) {
Martin Probst409697e2016-05-29 14:41:07 +00001455 if (FormatTok->is(Keywords.kw_function) ||
1456 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001457 tryToParseJSFunction();
1458 continue;
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001459 }
1460 if (FormatTok->is(TT_JsFatArrow)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001461 nextToken();
1462 // Fat arrows can be followed by simple expressions or by child blocks
1463 // in curly braces.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001464 if (FormatTok->is(tok::l_brace)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001465 parseChildBlock();
1466 continue;
1467 }
1468 }
Martin Probst8e3eba02017-02-07 16:33:13 +00001469 if (FormatTok->is(tok::l_brace)) {
1470 // Could be a method inside of a braced list `{a() { return 1; }}`.
1471 if (tryToParseBracedList())
1472 continue;
1473 parseChildBlock();
1474 }
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001475 }
Krasimir Georgievff747be2017-06-27 13:43:07 +00001476 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1477 nextToken();
1478 return !HasError;
1479 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001480 switch (FormatTok->Tok.getKind()) {
Manuel Klimek516e0542013-09-04 13:25:30 +00001481 case tok::caret:
1482 nextToken();
1483 if (FormatTok->is(tok::l_brace)) {
1484 parseChildBlock();
1485 }
1486 break;
1487 case tok::l_square:
1488 tryToParseLambda();
1489 break;
Daniel Jaspera87af7a2015-06-30 11:32:22 +00001490 case tok::l_paren:
1491 parseParens();
Daniel Jasperf46dec82015-03-31 14:34:15 +00001492 // JavaScript can just have free standing methods and getters/setters in
1493 // object literals. Detect them by a "{" following ")".
1494 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf46dec82015-03-31 14:34:15 +00001495 if (FormatTok->is(tok::l_brace))
1496 parseChildBlock();
1497 break;
1498 }
Daniel Jasperf46dec82015-03-31 14:34:15 +00001499 break;
Martin Probst8e3eba02017-02-07 16:33:13 +00001500 case tok::l_brace:
1501 // Assume there are no blocks inside a braced init list apart
1502 // from the ones we explicitly parse out (like lambdas).
1503 FormatTok->BlockKind = BK_BracedInit;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001504 nextToken();
Martin Probst8e3eba02017-02-07 16:33:13 +00001505 parseBracedList();
1506 break;
Krasimir Georgievfa4dbb62017-08-03 13:43:45 +00001507 case tok::less:
1508 if (Style.Language == FormatStyle::LK_Proto) {
1509 nextToken();
1510 parseBracedList(/*ContinueOnSemicolons=*/false,
1511 /*ClosingBraceKind=*/tok::greater);
1512 } else {
1513 nextToken();
1514 }
1515 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001516 case tok::semi:
Daniel Jasperb9a49902016-01-09 15:56:28 +00001517 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1518 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1519 // used for error recovery if we have otherwise determined that this is
1520 // a braced list.
1521 if (Style.Language == FormatStyle::LK_JavaScript) {
1522 nextToken();
1523 break;
1524 }
Daniel Jasper015ed022013-09-13 09:20:45 +00001525 HasError = true;
1526 if (!ContinueOnSemicolons)
1527 return !HasError;
1528 nextToken();
1529 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001530 case tok::comma:
1531 nextToken();
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001532 break;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001533 default:
1534 nextToken();
1535 break;
1536 }
1537 } while (!eof());
Daniel Jasper015ed022013-09-13 09:20:45 +00001538 return false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001539}
1540
Daniel Jasperf7935112012-12-03 18:12:45 +00001541void UnwrappedLineParser::parseParens() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001542 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
Daniel Jasperf7935112012-12-03 18:12:45 +00001543 nextToken();
1544 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001545 switch (FormatTok->Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001546 case tok::l_paren:
1547 parseParens();
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001548 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1549 parseChildBlock();
Daniel Jasperf7935112012-12-03 18:12:45 +00001550 break;
1551 case tok::r_paren:
1552 nextToken();
1553 return;
Daniel Jasper393564f2013-05-31 14:56:29 +00001554 case tok::r_brace:
1555 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1556 return;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001557 case tok::l_square:
1558 tryToParseLambda();
1559 break;
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001560 case tok::l_brace:
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001561 if (!tryToParseBracedList())
Manuel Klimekf017dc02013-09-04 13:34:14 +00001562 parseChildBlock();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001563 break;
Nico Weber372d8dc2013-02-10 20:35:35 +00001564 case tok::at:
1565 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001566 if (FormatTok->Tok.is(tok::l_brace)) {
1567 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001568 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001569 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001570 break;
Martin Probst1027fb82017-02-07 14:05:30 +00001571 case tok::kw_class:
1572 if (Style.Language == FormatStyle::LK_JavaScript)
1573 parseRecord(/*ParseAsExpr=*/true);
1574 else
1575 nextToken();
1576 break;
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001577 case tok::identifier:
1578 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst409697e2016-05-29 14:41:07 +00001579 (FormatTok->is(Keywords.kw_function) ||
1580 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001581 tryToParseJSFunction();
1582 else
1583 nextToken();
1584 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001585 default:
1586 nextToken();
1587 break;
1588 }
1589 } while (!eof());
1590}
1591
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001592void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1593 if (!LambdaIntroducer) {
1594 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1595 if (tryToParseLambda())
1596 return;
1597 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001598 do {
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001599 switch (FormatTok->Tok.getKind()) {
1600 case tok::l_paren:
1601 parseParens();
1602 break;
1603 case tok::r_square:
1604 nextToken();
1605 return;
1606 case tok::r_brace:
1607 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1608 return;
1609 case tok::l_square:
1610 parseSquare();
1611 break;
1612 case tok::l_brace: {
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001613 if (!tryToParseBracedList())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001614 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001615 break;
1616 }
1617 case tok::at:
1618 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001619 if (FormatTok->Tok.is(tok::l_brace)) {
1620 nextToken();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001621 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001622 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001623 break;
1624 default:
1625 nextToken();
1626 break;
1627 }
1628 } while (!eof());
1629}
1630
Daniel Jasperf7935112012-12-03 18:12:45 +00001631void UnwrappedLineParser::parseIfThenElse() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001632 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001633 nextToken();
Daniel Jasper6a7d5a72017-06-19 07:40:49 +00001634 if (FormatTok->Tok.is(tok::kw_constexpr))
1635 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001636 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimekadededf2013-01-11 18:28:36 +00001637 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +00001638 bool NeedsUnwrappedLine = false;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001639 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001640 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001641 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001642 if (Style.BraceWrapping.BeforeElse)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001643 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001644 else
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001645 NeedsUnwrappedLine = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001646 } else {
1647 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001648 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001649 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001650 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001651 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001652 if (FormatTok->Tok.is(tok::kw_else)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001653 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001654 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001655 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001656 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001657 addUnwrappedLine();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001658 } else if (FormatTok->Tok.is(tok::kw_if)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001659 parseIfThenElse();
1660 } else {
1661 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001662 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001663 parseStructuralElement();
Daniel Jasper451544a2016-05-19 06:30:48 +00001664 if (FormatTok->is(tok::eof))
1665 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001666 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001667 }
1668 } else if (NeedsUnwrappedLine) {
1669 addUnwrappedLine();
1670 }
1671}
1672
Daniel Jasper04a71a42014-05-08 11:58:24 +00001673void UnwrappedLineParser::parseTryCatch() {
Nico Weberfac23712015-02-04 15:26:27 +00001674 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
Daniel Jasper04a71a42014-05-08 11:58:24 +00001675 nextToken();
1676 bool NeedsUnwrappedLine = false;
1677 if (FormatTok->is(tok::colon)) {
1678 // We are in a function try block, what comes is an initializer list.
1679 nextToken();
1680 while (FormatTok->is(tok::identifier)) {
1681 nextToken();
1682 if (FormatTok->is(tok::l_paren))
1683 parseParens();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001684 if (FormatTok->is(tok::comma))
1685 nextToken();
1686 }
1687 }
Daniel Jaspere189d462015-01-14 10:48:41 +00001688 // Parse try with resource.
1689 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1690 parseParens();
1691 }
Daniel Jasper04a71a42014-05-08 11:58:24 +00001692 if (FormatTok->is(tok::l_brace)) {
1693 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1694 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001695 if (Style.BraceWrapping.BeforeCatch) {
Daniel Jasper04a71a42014-05-08 11:58:24 +00001696 addUnwrappedLine();
1697 } else {
1698 NeedsUnwrappedLine = true;
1699 }
1700 } else if (!FormatTok->is(tok::kw_catch)) {
1701 // The C++ standard requires a compound-statement after a try.
1702 // If there's none, we try to assume there's a structuralElement
1703 // and try to continue.
Daniel Jasper04a71a42014-05-08 11:58:24 +00001704 addUnwrappedLine();
1705 ++Line->Level;
1706 parseStructuralElement();
1707 --Line->Level;
1708 }
Nico Weber33381f52015-02-07 01:57:32 +00001709 while (1) {
1710 if (FormatTok->is(tok::at))
1711 nextToken();
1712 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1713 tok::kw___finally) ||
1714 ((Style.Language == FormatStyle::LK_Java ||
1715 Style.Language == FormatStyle::LK_JavaScript) &&
1716 FormatTok->is(Keywords.kw_finally)) ||
1717 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1718 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1719 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001720 nextToken();
1721 while (FormatTok->isNot(tok::l_brace)) {
1722 if (FormatTok->is(tok::l_paren)) {
1723 parseParens();
1724 continue;
1725 }
Daniel Jasper2bd7a642015-01-19 10:50:51 +00001726 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
Daniel Jasper04a71a42014-05-08 11:58:24 +00001727 return;
1728 nextToken();
1729 }
1730 NeedsUnwrappedLine = false;
1731 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1732 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001733 if (Style.BraceWrapping.BeforeCatch)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001734 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001735 else
Daniel Jasper04a71a42014-05-08 11:58:24 +00001736 NeedsUnwrappedLine = true;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001737 }
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001738 if (NeedsUnwrappedLine)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001739 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001740}
1741
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001742void UnwrappedLineParser::parseNamespace() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001743 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001744
1745 const FormatToken &InitialToken = *FormatTok;
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001746 nextToken();
Saleem Abdulrasool328085f2015-10-30 05:07:56 +00001747 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001748 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001749 if (FormatTok->Tok.is(tok::l_brace)) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001750 if (ShouldBreakBeforeBrace(Style, InitialToken))
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001751 addUnwrappedLine();
1752
Daniel Jasper65ee3472013-07-31 23:16:02 +00001753 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1754 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1755 DeclarationScopeStack.size() > 1);
1756 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
Manuel Klimek046b9302013-02-06 16:08:09 +00001757 // Munch the semicolon after a namespace. This is more common than one would
1758 // think. Puttin the semicolon into its own line is very ugly.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001759 if (FormatTok->Tok.is(tok::semi))
Manuel Klimek046b9302013-02-06 16:08:09 +00001760 nextToken();
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001761 addUnwrappedLine();
1762 }
1763 // FIXME: Add error handling.
1764}
1765
Daniel Jasper6acf5132015-03-12 14:44:29 +00001766void UnwrappedLineParser::parseNew() {
1767 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1768 nextToken();
1769 if (Style.Language != FormatStyle::LK_Java)
1770 return;
1771
1772 // In Java, we can parse everything up to the parens, which aren't optional.
1773 do {
1774 // There should not be a ;, { or } before the new's open paren.
1775 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1776 return;
1777
1778 // Consume the parens.
1779 if (FormatTok->is(tok::l_paren)) {
1780 parseParens();
1781
1782 // If there is a class body of an anonymous class, consume that as child.
1783 if (FormatTok->is(tok::l_brace))
1784 parseChildBlock();
1785 return;
1786 }
1787 nextToken();
1788 } while (!eof());
1789}
1790
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001791void UnwrappedLineParser::parseForOrWhileLoop() {
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001792 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
Daniel Jaspere1e43192014-04-01 12:55:11 +00001793 "'for', 'while' or foreach macro expected");
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001794 nextToken();
Martin Probsta050f412017-05-18 21:19:29 +00001795 // JS' for await ( ...
Martin Probstbd49e322017-05-15 19:33:20 +00001796 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probsta050f412017-05-18 21:19:29 +00001797 FormatTok->is(Keywords.kw_await))
Martin Probstbd49e322017-05-15 19:33:20 +00001798 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001799 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001800 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001801 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001802 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001803 parseBlock(/*MustBeDeclaration=*/false);
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001804 addUnwrappedLine();
1805 } else {
1806 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001807 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001808 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001809 --Line->Level;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001810 }
1811}
1812
Daniel Jasperf7935112012-12-03 18:12:45 +00001813void UnwrappedLineParser::parseDoWhile() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001814 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001815 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001816 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001817 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001818 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001819 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001820 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001821 } else {
1822 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001823 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001824 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001825 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001826 }
1827
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001828 // FIXME: Add error handling.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001829 if (!FormatTok->Tok.is(tok::kw_while)) {
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001830 addUnwrappedLine();
1831 return;
1832 }
1833
Daniel Jasperf7935112012-12-03 18:12:45 +00001834 nextToken();
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001835 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +00001836}
1837
1838void UnwrappedLineParser::parseLabel() {
Daniel Jasperf7935112012-12-03 18:12:45 +00001839 nextToken();
Manuel Klimek52b15152013-01-09 15:25:02 +00001840 unsigned OldLineLevel = Line->Level;
Daniel Jaspera1275122013-03-20 10:23:53 +00001841 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
Manuel Klimek52b15152013-01-09 15:25:02 +00001842 --Line->Level;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001843 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001844 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001845 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001846 if (FormatTok->Tok.is(tok::kw_break)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001847 if (Style.BraceWrapping.AfterControlStatement)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001848 addUnwrappedLine();
1849 parseStructuralElement();
1850 }
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001851 addUnwrappedLine();
1852 } else {
Daniel Jasper1fe0d5c2015-05-06 15:19:47 +00001853 if (FormatTok->is(tok::semi))
1854 nextToken();
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001855 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001856 }
Manuel Klimek52b15152013-01-09 15:25:02 +00001857 Line->Level = OldLineLevel;
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001858 if (FormatTok->isNot(tok::l_brace)) {
Daniel Jasper40609472016-04-06 15:02:46 +00001859 parseStructuralElement();
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001860 addUnwrappedLine();
1861 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001862}
1863
1864void UnwrappedLineParser::parseCaseLabel() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001865 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001866 // FIXME: fix handling of complex expressions here.
1867 do {
1868 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001869 } while (!eof() && !FormatTok->Tok.is(tok::colon));
Daniel Jasperf7935112012-12-03 18:12:45 +00001870 parseLabel();
1871}
1872
1873void UnwrappedLineParser::parseSwitch() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001874 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001875 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001876 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001877 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001878 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001879 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Daniel Jasper65ee3472013-07-31 23:16:02 +00001880 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001881 addUnwrappedLine();
1882 } else {
1883 addUnwrappedLine();
Daniel Jasper516d7972013-07-25 11:31:57 +00001884 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001885 parseStructuralElement();
Daniel Jasper516d7972013-07-25 11:31:57 +00001886 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001887 }
1888}
1889
1890void UnwrappedLineParser::parseAccessSpecifier() {
1891 nextToken();
Daniel Jasper84c47a12013-11-23 17:53:41 +00001892 // Understand Qt's slots.
Daniel Jasper53395402015-04-07 15:04:40 +00001893 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
Daniel Jasper84c47a12013-11-23 17:53:41 +00001894 nextToken();
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00001895 // Otherwise, we don't know what it is, and we'd better keep the next token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001896 if (FormatTok->Tok.is(tok::colon))
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00001897 nextToken();
Daniel Jasperf7935112012-12-03 18:12:45 +00001898 addUnwrappedLine();
1899}
1900
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001901bool UnwrappedLineParser::parseEnum() {
Daniel Jasper6be0f552014-11-13 15:56:28 +00001902 // Won't be 'enum' for NS_ENUMs.
1903 if (FormatTok->Tok.is(tok::kw_enum))
Daniel Jasperccb68b42014-11-19 22:38:18 +00001904 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001905
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001906 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1907 // declarations. An "enum" keyword followed by a colon would be a syntax
1908 // error and thus assume it is just an identifier.
Daniel Jasper87379302016-02-03 05:33:44 +00001909 if (Style.Language == FormatStyle::LK_JavaScript &&
1910 FormatTok->isOneOf(tok::colon, tok::question))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001911 return false;
1912
Daniel Jasper2b41a822013-08-20 12:42:50 +00001913 // Eat up enum class ...
Daniel Jasperb05a81d2014-05-09 13:11:16 +00001914 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1915 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001916
Daniel Jasper786a5502013-09-06 21:32:35 +00001917 while (FormatTok->Tok.getIdentifierInfo() ||
Daniel Jasperccb68b42014-11-19 22:38:18 +00001918 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1919 tok::greater, tok::comma, tok::question)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00001920 nextToken();
1921 // We can have macros or attributes in between 'enum' and the enum name.
Daniel Jasperccb68b42014-11-19 22:38:18 +00001922 if (FormatTok->is(tok::l_paren))
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001923 parseParens();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001924 if (FormatTok->is(tok::identifier)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00001925 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001926 // If there are two identifiers in a row, this is likely an elaborate
1927 // return type. In Java, this can be "implements", etc.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001928 if (Style.isCpp() && FormatTok->is(tok::identifier))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001929 return false;
Daniel Jasperb5a0b852015-06-19 08:17:32 +00001930 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001931 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00001932
1933 // Just a declaration or something is wrong.
Daniel Jasperccb68b42014-11-19 22:38:18 +00001934 if (FormatTok->isNot(tok::l_brace))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001935 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00001936 FormatTok->BlockKind = BK_Block;
1937
1938 if (Style.Language == FormatStyle::LK_Java) {
1939 // Java enums are different.
1940 parseJavaEnumBody();
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001941 return true;
1942 }
1943 if (Style.Language == FormatStyle::LK_Proto) {
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001944 parseBlock(/*MustBeDeclaration=*/true);
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001945 return true;
Manuel Klimek2cec0192013-01-21 19:17:52 +00001946 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00001947
1948 // Parse enum body.
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001949 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001950 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1951 if (HasError) {
1952 if (FormatTok->is(tok::semi))
1953 nextToken();
1954 addUnwrappedLine();
1955 }
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001956 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00001957
Daniel Jasper90cf3802015-06-17 09:44:02 +00001958 // There is no addUnwrappedLine() here so that we fall through to parsing a
1959 // structural element afterwards. Thus, in "enum A {} n, m;",
Manuel Klimek2cec0192013-01-21 19:17:52 +00001960 // "} n, m;" will end up in one unwrapped line.
Daniel Jasper6be0f552014-11-13 15:56:28 +00001961}
1962
1963void UnwrappedLineParser::parseJavaEnumBody() {
1964 // Determine whether the enum is simple, i.e. does not have a semicolon or
1965 // constants with class bodies. Simple enums can be formatted like braced
1966 // lists, contracted to a single line, etc.
1967 unsigned StoredPosition = Tokens->getPosition();
1968 bool IsSimple = true;
1969 FormatToken *Tok = Tokens->getNextToken();
1970 while (Tok) {
1971 if (Tok->is(tok::r_brace))
1972 break;
1973 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1974 IsSimple = false;
1975 break;
1976 }
1977 // FIXME: This will also mark enums with braces in the arguments to enum
1978 // constants as "not simple". This is probably fine in practice, though.
1979 Tok = Tokens->getNextToken();
1980 }
1981 FormatTok = Tokens->setPosition(StoredPosition);
1982
1983 if (IsSimple) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001984 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001985 parseBracedList();
Daniel Jasperdf2ff002014-11-02 22:31:39 +00001986 addUnwrappedLine();
Daniel Jasper6be0f552014-11-13 15:56:28 +00001987 return;
1988 }
1989
1990 // Parse the body of a more complex enum.
1991 // First add a line for everything up to the "{".
1992 nextToken();
1993 addUnwrappedLine();
1994 ++Line->Level;
1995
1996 // Parse the enum constants.
1997 while (FormatTok) {
1998 if (FormatTok->is(tok::l_brace)) {
1999 // Parse the constant's class body.
2000 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2001 /*MunchSemi=*/false);
2002 } else if (FormatTok->is(tok::l_paren)) {
2003 parseParens();
2004 } else if (FormatTok->is(tok::comma)) {
2005 nextToken();
2006 addUnwrappedLine();
2007 } else if (FormatTok->is(tok::semi)) {
2008 nextToken();
2009 addUnwrappedLine();
2010 break;
2011 } else if (FormatTok->is(tok::r_brace)) {
2012 addUnwrappedLine();
2013 break;
2014 } else {
2015 nextToken();
2016 }
2017 }
2018
2019 // Parse the class body after the enum's ";" if any.
2020 parseLevel(/*HasOpeningBrace=*/true);
2021 nextToken();
2022 --Line->Level;
2023 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00002024}
2025
Martin Probst1027fb82017-02-07 14:05:30 +00002026void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00002027 const FormatToken &InitialToken = *FormatTok;
Manuel Klimek28cacc72013-01-07 18:10:23 +00002028 nextToken();
Daniel Jasper04785d02015-05-06 14:03:02 +00002029
Daniel Jasper04785d02015-05-06 14:03:02 +00002030 // The actual identifier can be a nested name specifier, and in macros
2031 // it is often token-pasted.
2032 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2033 tok::kw___attribute, tok::kw___declspec,
2034 tok::kw_alignas) ||
2035 ((Style.Language == FormatStyle::LK_Java ||
2036 Style.Language == FormatStyle::LK_JavaScript) &&
2037 FormatTok->isOneOf(tok::period, tok::comma))) {
Martin Probstcb870c52017-08-01 15:46:10 +00002038 if (Style.Language == FormatStyle::LK_JavaScript &&
2039 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2040 // JavaScript/TypeScript supports inline object types in
2041 // extends/implements positions:
2042 // class Foo implements {bar: number} { }
2043 nextToken();
2044 if (FormatTok->is(tok::l_brace)) {
2045 tryToParseBracedList();
2046 continue;
2047 }
2048 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002049 bool IsNonMacroIdentifier =
2050 FormatTok->is(tok::identifier) &&
2051 FormatTok->TokenText != FormatTok->TokenText.upper();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002052 nextToken();
2053 // We can have macros or attributes in between 'class' and the class name.
Daniel Jasper04785d02015-05-06 14:03:02 +00002054 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
Manuel Klimeke01bab52013-01-15 13:38:33 +00002055 parseParens();
Daniel Jasper04785d02015-05-06 14:03:02 +00002056 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00002057
Daniel Jasper04785d02015-05-06 14:03:02 +00002058 // Note that parsing away template declarations here leads to incorrectly
2059 // accepting function declarations as record declarations.
2060 // In general, we cannot solve this problem. Consider:
2061 // class A<int> B() {}
2062 // which can be a function definition or a class definition when B() is a
2063 // macro. If we find enough real-world cases where this is a problem, we
2064 // can parse for the 'template' keyword in the beginning of the statement,
2065 // and thus rule out the record production in case there is no template
2066 // (this would still leave us with an ambiguity between template function
2067 // and class declarations).
Daniel Jasperadba2aa2015-05-18 12:52:00 +00002068 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2069 while (!eof()) {
Daniel Jasper3c883d12015-05-18 14:49:19 +00002070 if (FormatTok->is(tok::l_brace)) {
2071 calculateBraceTypes(/*ExpectClassBody=*/true);
2072 if (!tryToParseBracedList())
2073 break;
2074 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002075 if (FormatTok->Tok.is(tok::semi))
2076 return;
2077 nextToken();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002078 }
2079 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002080 if (FormatTok->Tok.is(tok::l_brace)) {
Martin Probst1027fb82017-02-07 14:05:30 +00002081 if (ParseAsExpr) {
2082 parseChildBlock();
2083 } else {
2084 if (ShouldBreakBeforeBrace(Style, InitialToken))
2085 addUnwrappedLine();
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002086
Martin Probst1027fb82017-02-07 14:05:30 +00002087 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2088 /*MunchSemi=*/false);
2089 }
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002090 }
Daniel Jasper90cf3802015-06-17 09:44:02 +00002091 // There is no addUnwrappedLine() here so that we fall through to parsing a
2092 // structural element afterwards. Thus, in "class A {} n, m;",
2093 // "} n, m;" will end up in one unwrapped line.
Manuel Klimek28cacc72013-01-07 18:10:23 +00002094}
2095
Nico Weber8696a8d2013-01-09 21:15:03 +00002096void UnwrappedLineParser::parseObjCProtocolList() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002097 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
Nico Weber8696a8d2013-01-09 21:15:03 +00002098 do
2099 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002100 while (!eof() && FormatTok->Tok.isNot(tok::greater));
Nico Weber8696a8d2013-01-09 21:15:03 +00002101 nextToken(); // Skip '>'.
2102}
2103
2104void UnwrappedLineParser::parseObjCUntilAtEnd() {
2105 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002106 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002107 nextToken();
2108 addUnwrappedLine();
2109 break;
2110 }
Daniel Jaspera15da302013-08-28 08:04:23 +00002111 if (FormatTok->is(tok::l_brace)) {
2112 parseBlock(/*MustBeDeclaration=*/false);
2113 // In ObjC interfaces, nothing should be following the "}".
2114 addUnwrappedLine();
Benjamin Kramere21cb742014-01-08 15:59:42 +00002115 } else if (FormatTok->is(tok::r_brace)) {
2116 // Ignore stray "}". parseStructuralElement doesn't consume them.
2117 nextToken();
2118 addUnwrappedLine();
Daniel Jaspera15da302013-08-28 08:04:23 +00002119 } else {
2120 parseStructuralElement();
2121 }
Nico Weber8696a8d2013-01-09 21:15:03 +00002122 } while (!eof());
2123}
2124
Nico Weber2ce0ac52013-01-09 23:25:37 +00002125void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
Nico Weberc068ff72018-01-23 17:10:25 +00002126 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2127 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
Nico Weber7eecf4b2013-01-09 20:25:35 +00002128 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002129 nextToken(); // interface name
Nico Weber7eecf4b2013-01-09 20:25:35 +00002130
2131 // @interface can be followed by either a base class, or a category.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002132 if (FormatTok->Tok.is(tok::colon)) {
Nico Weber7eecf4b2013-01-09 20:25:35 +00002133 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002134 nextToken(); // base class name
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002135 } else if (FormatTok->Tok.is(tok::l_paren))
Nico Weber7eecf4b2013-01-09 20:25:35 +00002136 // Skip category, if present.
2137 parseParens();
2138
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002139 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002140 parseObjCProtocolList();
Nico Weber7eecf4b2013-01-09 20:25:35 +00002141
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002142 if (FormatTok->Tok.is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002143 if (Style.BraceWrapping.AfterObjCDeclaration)
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002144 addUnwrappedLine();
Nico Weber9096fc02013-06-26 00:30:14 +00002145 parseBlock(/*MustBeDeclaration=*/true);
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002146 }
Nico Weber7eecf4b2013-01-09 20:25:35 +00002147
2148 // With instance variables, this puts '}' on its own line. Without instance
2149 // variables, this ends the @interface line.
2150 addUnwrappedLine();
2151
Nico Weber8696a8d2013-01-09 21:15:03 +00002152 parseObjCUntilAtEnd();
2153}
Nico Weber7eecf4b2013-01-09 20:25:35 +00002154
Nico Weberc068ff72018-01-23 17:10:25 +00002155// Returns true for the declaration/definition form of @protocol,
2156// false for the expression form.
2157bool UnwrappedLineParser::parseObjCProtocol() {
2158 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
Nico Weber8696a8d2013-01-09 21:15:03 +00002159 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002160
2161 if (FormatTok->is(tok::l_paren))
2162 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2163 return false;
2164
2165 // The definition/declaration form,
2166 // @protocol Foo
2167 // - (int)someMethod;
2168 // @end
2169
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002170 nextToken(); // protocol name
Nico Weber8696a8d2013-01-09 21:15:03 +00002171
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002172 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002173 parseObjCProtocolList();
2174
2175 // Check for protocol declaration.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002176 if (FormatTok->Tok.is(tok::semi)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002177 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002178 addUnwrappedLine();
2179 return true;
Nico Weber8696a8d2013-01-09 21:15:03 +00002180 }
2181
2182 addUnwrappedLine();
2183 parseObjCUntilAtEnd();
Nico Weberc068ff72018-01-23 17:10:25 +00002184 return true;
Nico Weber7eecf4b2013-01-09 20:25:35 +00002185}
2186
Daniel Jasperfca735c2015-02-19 16:14:18 +00002187void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
Martin Probst053f1aa2016-04-19 14:55:37 +00002188 bool IsImport = FormatTok->is(Keywords.kw_import);
2189 assert(IsImport || FormatTok->is(tok::kw_export));
Daniel Jasper354aa512015-02-19 16:07:32 +00002190 nextToken();
Daniel Jasperfca735c2015-02-19 16:14:18 +00002191
Daniel Jasperec05fc72015-05-11 09:14:50 +00002192 // Consume the "default" in "export default class/function".
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002193 if (FormatTok->is(tok::kw_default))
2194 nextToken();
Daniel Jasperec05fc72015-05-11 09:14:50 +00002195
Martin Probst5f8445b2016-04-24 22:05:09 +00002196 // Consume "async function", "function" and "default function", so that these
2197 // get parsed as free-standing JS functions, i.e. do not require a trailing
2198 // semicolon.
2199 if (FormatTok->is(Keywords.kw_async))
2200 nextToken();
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002201 if (FormatTok->is(Keywords.kw_function)) {
2202 nextToken();
2203 return;
2204 }
2205
Martin Probst053f1aa2016-04-19 14:55:37 +00002206 // For imports, `export *`, `export {...}`, consume the rest of the line up
2207 // to the terminating `;`. For everything else, just return and continue
2208 // parsing the structural element, i.e. the declaration or expression for
2209 // `export default`.
2210 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2211 !FormatTok->isStringLiteral())
2212 return;
Daniel Jasperfca735c2015-02-19 16:14:18 +00002213
Martin Probstd40bca42017-01-09 08:56:36 +00002214 while (!eof()) {
2215 if (FormatTok->is(tok::semi))
2216 return;
Krasimir Georgiev112c2e92017-11-09 13:22:03 +00002217 if (Line->Tokens.empty()) {
Martin Probstd40bca42017-01-09 08:56:36 +00002218 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2219 // import statement should terminate.
2220 return;
2221 }
Daniel Jasperefc1a832016-01-07 08:53:35 +00002222 if (FormatTok->is(tok::l_brace)) {
2223 FormatTok->BlockKind = BK_Block;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002224 nextToken();
Daniel Jasperefc1a832016-01-07 08:53:35 +00002225 parseBracedList();
2226 } else {
2227 nextToken();
2228 }
Daniel Jasper354aa512015-02-19 16:07:32 +00002229 }
2230}
2231
Daniel Jasper3b203a62013-09-05 16:05:56 +00002232LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2233 StringRef Prefix = "") {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002234 llvm::dbgs() << Prefix << "Line(" << Line.Level
2235 << ", FSC=" << Line.FirstStartColumn << ")"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002236 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2237 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2238 E = Line.Tokens.end();
2239 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002240 llvm::dbgs() << I->Tok->Tok.getName() << "["
Manuel Klimek89628f62017-09-20 09:51:03 +00002241 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2242 << "] ";
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002243 }
2244 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2245 E = Line.Tokens.end();
2246 I != E; ++I) {
2247 const UnwrappedLineNode &Node = *I;
2248 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2249 I = Node.Children.begin(),
2250 E = Node.Children.end();
2251 I != E; ++I) {
2252 printDebugInfo(*I, "\nChild: ");
2253 }
2254 }
2255 llvm::dbgs() << "\n";
2256}
2257
Daniel Jasperf7935112012-12-03 18:12:45 +00002258void UnwrappedLineParser::addUnwrappedLine() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002259 if (Line->Tokens.empty())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00002260 return;
Manuel Klimekab3dc002013-01-16 12:31:12 +00002261 DEBUG({
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002262 if (CurrentLines == &Lines)
2263 printDebugInfo(*Line);
Manuel Klimekab3dc002013-01-16 12:31:12 +00002264 });
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002265 CurrentLines->push_back(std::move(*Line));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002266 Line->Tokens.clear();
Krasimir Georgiev85c37042017-03-01 16:38:08 +00002267 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002268 Line->FirstStartColumn = 0;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002269 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002270 CurrentLines->append(
2271 std::make_move_iterator(PreprocessorDirectives.begin()),
2272 std::make_move_iterator(PreprocessorDirectives.end()));
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002273 PreprocessorDirectives.clear();
2274 }
Manuel Klimeke411aa82017-09-20 09:29:37 +00002275 // Disconnect the current token from the last token on the previous line.
2276 FormatTok->Previous = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +00002277}
2278
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002279bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
Daniel Jasperf7935112012-12-03 18:12:45 +00002280
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002281bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002282 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2283 FormatTok.NewlinesBefore > 0;
2284}
2285
Krasimir Georgiev91834222017-01-25 13:58:58 +00002286// Checks if \p FormatTok is a line comment that continues the line comment
2287// section on \p Line.
Krasimir Georgievea222a72017-05-22 10:07:56 +00002288static bool continuesLineCommentSection(const FormatToken &FormatTok,
2289 const UnwrappedLine &Line,
2290 llvm::Regex &CommentPragmasRegex) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002291 if (Line.Tokens.empty())
2292 return false;
Krasimir Georgiev84321612017-01-30 19:18:55 +00002293
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002294 StringRef IndentContent = FormatTok.TokenText;
2295 if (FormatTok.TokenText.startswith("//") ||
2296 FormatTok.TokenText.startswith("/*"))
2297 IndentContent = FormatTok.TokenText.substr(2);
2298 if (CommentPragmasRegex.match(IndentContent))
2299 return false;
2300
Krasimir Georgiev91834222017-01-25 13:58:58 +00002301 // If Line starts with a line comment, then FormatTok continues the comment
Krasimir Georgiev84321612017-01-30 19:18:55 +00002302 // section if its original column is greater or equal to the original start
Krasimir Georgiev91834222017-01-25 13:58:58 +00002303 // column of the line.
2304 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002305 // Define the min column token of a line as follows: if a line ends in '{' or
2306 // contains a '{' followed by a line comment, then the min column token is
2307 // that '{'. Otherwise, the min column token of the line is the first token of
2308 // the line.
2309 //
2310 // If Line starts with a token other than a line comment, then FormatTok
2311 // continues the comment section if its original column is greater than the
2312 // original start column of the min column token of the line.
Krasimir Georgiev91834222017-01-25 13:58:58 +00002313 //
2314 // For example, the second line comment continues the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002315 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002316 // // first line
2317 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002318 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002319 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002320 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002321 // // first line
2322 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002323 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002324 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002325 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002326 // int i; // first line
2327 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002328 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002329 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002330 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002331 // do { // first line
2332 // // second line
2333 // int i;
2334 // } while (true);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002335 //
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002336 // and:
2337 //
2338 // enum {
2339 // a, // first line
2340 // // second line
2341 // b
2342 // };
2343 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002344 // The second line comment doesn't continue the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002345 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002346 // // first line
2347 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002348 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002349 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002350 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002351 // int i; // first line
2352 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002353 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002354 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002355 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002356 // do { // first line
2357 // // second line
2358 // int i;
2359 // } while (true);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002360 //
2361 // and:
2362 //
2363 // enum {
2364 // a, // first line
2365 // // second line
2366 // };
Krasimir Georgiev84321612017-01-30 19:18:55 +00002367 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2368
2369 // Scan for '{//'. If found, use the column of '{' as a min column for line
2370 // comment section continuation.
2371 const FormatToken *PreviousToken = nullptr;
Krasimir Georgievd86c25d2017-03-10 13:09:29 +00002372 for (const UnwrappedLineNode &Node : Line.Tokens) {
Krasimir Georgiev84321612017-01-30 19:18:55 +00002373 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2374 isLineComment(*Node.Tok)) {
2375 MinColumnToken = PreviousToken;
2376 break;
2377 }
2378 PreviousToken = Node.Tok;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002379
2380 // Grab the last newline preceding a token in this unwrapped line.
2381 if (Node.Tok->NewlinesBefore > 0) {
2382 MinColumnToken = Node.Tok;
2383 }
Krasimir Georgiev84321612017-01-30 19:18:55 +00002384 }
2385 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2386 MinColumnToken = PreviousToken;
2387 }
2388
Krasimir Georgievea222a72017-05-22 10:07:56 +00002389 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2390 MinColumnToken);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002391}
2392
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002393void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2394 bool JustComments = Line->Tokens.empty();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002395 for (SmallVectorImpl<FormatToken *>::const_iterator
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002396 I = CommentsBeforeNextToken.begin(),
2397 E = CommentsBeforeNextToken.end();
2398 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002399 // Line comments that belong to the same line comment section are put on the
2400 // same line since later we might want to reflow content between them.
Krasimir Georgiev753625b2017-01-31 13:32:38 +00002401 // Additional fine-grained breaking of line comment sections is controlled
2402 // by the class BreakableLineCommentSection in case it is desirable to keep
2403 // several line comment sections in the same unwrapped line.
2404 //
2405 // FIXME: Consider putting separate line comment sections as children to the
2406 // unwrapped line instead.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002407 (*I)->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002408 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002409 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002410 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002411 pushToken(*I);
2412 }
Daniel Jaspere60cba12015-05-13 11:35:53 +00002413 if (NewlineBeforeNext && JustComments)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002414 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002415 CommentsBeforeNextToken.clear();
2416}
2417
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002418void UnwrappedLineParser::nextToken(int LevelDifference) {
Daniel Jasperf7935112012-12-03 18:12:45 +00002419 if (eof())
2420 return;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002421 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002422 pushToken(FormatTok);
Manuel Klimek89628f62017-09-20 09:51:03 +00002423 FormatToken *Previous = FormatTok;
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002424 if (Style.Language != FormatStyle::LK_JavaScript)
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002425 readToken(LevelDifference);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002426 else
2427 readTokenWithJavaScriptASI();
Manuel Klimeke411aa82017-09-20 09:29:37 +00002428 FormatTok->Previous = Previous;
Daniel Jasperb9a49902016-01-09 15:56:28 +00002429}
2430
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002431void UnwrappedLineParser::distributeComments(
2432 const SmallVectorImpl<FormatToken *> &Comments,
2433 const FormatToken *NextTok) {
2434 // Whether or not a line comment token continues a line is controlled by
Krasimir Georgievea222a72017-05-22 10:07:56 +00002435 // the method continuesLineCommentSection, with the following caveat:
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002436 //
2437 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2438 // that each comment line from the trail is aligned with the next token, if
2439 // the next token exists. If a trail exists, the beginning of the maximal
2440 // trail is marked as a start of a new comment section.
2441 //
2442 // For example in this code:
2443 //
2444 // int a; // line about a
2445 // // line 1 about b
2446 // // line 2 about b
2447 // int b;
2448 //
2449 // the two lines about b form a maximal trail, so there are two sections, the
2450 // first one consisting of the single comment "// line about a" and the
2451 // second one consisting of the next two comments.
2452 if (Comments.empty())
2453 return;
2454 bool ShouldPushCommentsInCurrentLine = true;
2455 bool HasTrailAlignedWithNextToken = false;
2456 unsigned StartOfTrailAlignedWithNextToken = 0;
2457 if (NextTok) {
2458 // We are skipping the first element intentionally.
2459 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2460 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2461 HasTrailAlignedWithNextToken = true;
2462 StartOfTrailAlignedWithNextToken = i;
2463 }
2464 }
2465 }
2466 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2467 FormatToken *FormatTok = Comments[i];
Manuel Klimek89628f62017-09-20 09:51:03 +00002468 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002469 FormatTok->ContinuesLineCommentSection = false;
2470 } else {
2471 FormatTok->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002472 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002473 }
2474 if (!FormatTok->ContinuesLineCommentSection &&
2475 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2476 ShouldPushCommentsInCurrentLine = false;
2477 }
2478 if (ShouldPushCommentsInCurrentLine) {
2479 pushToken(FormatTok);
2480 } else {
2481 CommentsBeforeNextToken.push_back(FormatTok);
2482 }
2483 }
2484}
2485
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002486void UnwrappedLineParser::readToken(int LevelDifference) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002487 SmallVector<FormatToken *, 1> Comments;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002488 do {
2489 FormatTok = Tokens->getNextToken();
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00002490 assert(FormatTok);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002491 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2492 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002493 distributeComments(Comments, FormatTok);
2494 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002495 // If there is an unfinished unwrapped line, we flush the preprocessor
2496 // directives only after that unwrapped line was finished later.
Daniel Jasper29d39d52015-02-08 09:34:49 +00002497 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002498 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002499 assert((LevelDifference >= 0 ||
2500 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2501 "LevelDifference makes Line->Level negative");
2502 Line->Level += LevelDifference;
Alexander Kornienkob1be9d62013-04-03 12:38:53 +00002503 // Comments stored before the preprocessor directive need to be output
2504 // before the preprocessor directive, at the same level as the
2505 // preprocessor directive, as we consider them to apply to the directive.
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002506 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002507 parsePPDirective();
2508 }
Manuel Klimek68b03042014-04-14 09:14:11 +00002509 while (FormatTok->Type == TT_ConflictStart ||
2510 FormatTok->Type == TT_ConflictEnd ||
2511 FormatTok->Type == TT_ConflictAlternative) {
2512 if (FormatTok->Type == TT_ConflictStart) {
2513 conditionalCompilationStart(/*Unreachable=*/false);
2514 } else if (FormatTok->Type == TT_ConflictAlternative) {
2515 conditionalCompilationAlternative();
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002516 } else if (FormatTok->Type == TT_ConflictEnd) {
Manuel Klimek68b03042014-04-14 09:14:11 +00002517 conditionalCompilationEnd();
2518 }
2519 FormatTok = Tokens->getNextToken();
2520 FormatTok->MustBreakBefore = true;
2521 }
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002522
Francois Ferranda98a95c2017-07-28 07:56:14 +00002523 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002524 !Line->InPPDirective) {
2525 continue;
2526 }
2527
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002528 if (!FormatTok->Tok.is(tok::comment)) {
2529 distributeComments(Comments, FormatTok);
2530 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002531 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002532 }
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002533
2534 Comments.push_back(FormatTok);
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002535 } while (!eof());
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002536
2537 distributeComments(Comments, nullptr);
2538 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002539}
2540
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002541void UnwrappedLineParser::pushToken(FormatToken *Tok) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002542 Line->Tokens.push_back(UnwrappedLineNode(Tok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002543 if (MustBreakBeforeNextToken) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002544 Line->Tokens.back().Tok->MustBreakBefore = true;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002545 MustBreakBeforeNextToken = false;
Manuel Klimek1abf7892013-01-04 23:34:14 +00002546 }
Daniel Jasperf7935112012-12-03 18:12:45 +00002547}
2548
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002549} // end namespace format
2550} // end namespace clang