blob: 8a3a9bd580921a3065673b2292550d037e20ada3 [file] [log] [blame]
Daniel Jasperf7935112012-12-03 18:12:45 +00001//===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Jasperf7935112012-12-03 18:12:45 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// This file contains the implementation of the UnwrappedLineParser,
Daniel Jasperf7935112012-12-03 18:12:45 +000011/// which turns a stream of tokens into UnwrappedLines.
12///
Daniel Jasperf7935112012-12-03 18:12:45 +000013//===----------------------------------------------------------------------===//
14
Chandler Carruth4b417452013-01-19 08:09:44 +000015#include "UnwrappedLineParser.h"
Benjamin Kramer33335df2015-03-01 21:36:40 +000016#include "llvm/ADT/STLExtras.h"
Manuel Klimekab3dc002013-01-16 12:31:12 +000017#include "llvm/Support/Debug.h"
Benjamin Kramer53f5e892015-03-23 18:05:43 +000018#include "llvm/Support/raw_ostream.h"
Manuel Klimekab3dc002013-01-16 12:31:12 +000019
Martin Probst7e0f25b2017-11-25 09:19:42 +000020#include <algorithm>
21
Chandler Carruth10346662014-04-22 03:17:02 +000022#define DEBUG_TYPE "format-parser"
23
Daniel Jasperf7935112012-12-03 18:12:45 +000024namespace clang {
25namespace format {
26
Manuel Klimek15dfe7a2013-05-28 11:55:06 +000027class FormatTokenSource {
28public:
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000029 virtual ~FormatTokenSource() {}
Manuel Klimek15dfe7a2013-05-28 11:55:06 +000030 virtual FormatToken *getNextToken() = 0;
31
32 virtual unsigned getPosition() = 0;
33 virtual FormatToken *setPosition(unsigned Position) = 0;
34};
35
Craig Topper69665e12013-07-01 04:21:54 +000036namespace {
37
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000038class ScopedDeclarationState {
39public:
40 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
41 bool MustBeDeclaration)
42 : Line(Line), Stack(Stack) {
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000043 Line.MustBeDeclaration = MustBeDeclaration;
Manuel Klimek39080572013-01-23 11:03:04 +000044 Stack.push_back(MustBeDeclaration);
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000045 }
46 ~ScopedDeclarationState() {
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000047 Stack.pop_back();
Manuel Klimekc1237a82013-01-23 14:08:21 +000048 if (!Stack.empty())
49 Line.MustBeDeclaration = Stack.back();
50 else
51 Line.MustBeDeclaration = true;
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000052 }
Daniel Jasper393564f2013-05-31 14:56:29 +000053
Manuel Klimek0a3a3c92013-01-23 09:32:48 +000054private:
55 UnwrappedLine &Line;
56 std::vector<bool> &Stack;
57};
58
Krasimir Georgieva1c30932017-05-19 10:34:57 +000059static bool isLineComment(const FormatToken &FormatTok) {
Krasimir Georgiev410ed242017-11-10 12:50:09 +000060 return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
Krasimir Georgieva1c30932017-05-19 10:34:57 +000061}
62
Krasimir Georgievea222a72017-05-22 10:07:56 +000063// Checks if \p FormatTok is a line comment that continues the line comment
64// \p Previous. The original column of \p MinColumnToken is used to determine
65// whether \p FormatTok is indented enough to the right to continue \p Previous.
66static bool continuesLineComment(const FormatToken &FormatTok,
67 const FormatToken *Previous,
68 const FormatToken *MinColumnToken) {
69 if (!Previous || !MinColumnToken)
70 return false;
71 unsigned MinContinueColumn =
72 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
73 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
74 isLineComment(*Previous) &&
75 FormatTok.OriginalColumn >= MinContinueColumn;
76}
77
Manuel Klimek1abf7892013-01-04 23:34:14 +000078class ScopedMacroState : public FormatTokenSource {
79public:
80 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
Manuel Klimek20e0af62015-05-06 11:56:29 +000081 FormatToken *&ResetToken)
Manuel Klimek1abf7892013-01-04 23:34:14 +000082 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
Manuel Klimek1a18c402013-04-12 14:13:36 +000083 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
Krasimir Georgieva1c30932017-05-19 10:34:57 +000084 Token(nullptr), PreviousToken(nullptr) {
David L. Jones5de22722018-06-15 06:08:54 +000085 FakeEOF.Tok.startToken();
86 FakeEOF.Tok.setKind(tok::eof);
Manuel Klimek1abf7892013-01-04 23:34:14 +000087 TokenSource = this;
Manuel Klimekef2cfb12013-01-05 22:14:16 +000088 Line.Level = 0;
Manuel Klimek1abf7892013-01-04 23:34:14 +000089 Line.InPPDirective = true;
90 }
91
Alexander Kornienko34eb2072015-04-11 02:00:23 +000092 ~ScopedMacroState() override {
Manuel Klimek1abf7892013-01-04 23:34:14 +000093 TokenSource = PreviousTokenSource;
94 ResetToken = Token;
95 Line.InPPDirective = false;
Manuel Klimekef2cfb12013-01-05 22:14:16 +000096 Line.Level = PreviousLineLevel;
Manuel Klimek1abf7892013-01-04 23:34:14 +000097 }
98
Craig Topperfb6b25b2014-03-15 04:29:04 +000099 FormatToken *getNextToken() override {
Manuel Klimek78725712013-01-07 10:03:37 +0000100 // The \c UnwrappedLineParser guards against this by never calling
101 // \c getNextToken() after it has encountered the first eof token.
102 assert(!eof());
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000103 PreviousToken = Token;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000104 Token = PreviousTokenSource->getNextToken();
105 if (eof())
David L. Jones5de22722018-06-15 06:08:54 +0000106 return &FakeEOF;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000107 return Token;
108 }
109
Craig Topperfb6b25b2014-03-15 04:29:04 +0000110 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
Manuel Klimekab419912013-05-23 09:41:43 +0000111
Craig Topperfb6b25b2014-03-15 04:29:04 +0000112 FormatToken *setPosition(unsigned Position) override {
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000113 PreviousToken = nullptr;
Manuel Klimekab419912013-05-23 09:41:43 +0000114 Token = PreviousTokenSource->setPosition(Position);
115 return Token;
116 }
117
Manuel Klimek1abf7892013-01-04 23:34:14 +0000118private:
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000119 bool eof() {
120 return Token && Token->HasUnescapedNewline &&
Krasimir Georgievea222a72017-05-22 10:07:56 +0000121 !continuesLineComment(*Token, PreviousToken,
122 /*MinColumnToken=*/PreviousToken);
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000123 }
Manuel Klimek1abf7892013-01-04 23:34:14 +0000124
David L. Jones5de22722018-06-15 06:08:54 +0000125 FormatToken FakeEOF;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000126 UnwrappedLine &Line;
127 FormatTokenSource *&TokenSource;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000128 FormatToken *&ResetToken;
Manuel Klimekef2cfb12013-01-05 22:14:16 +0000129 unsigned PreviousLineLevel;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000130 FormatTokenSource *PreviousTokenSource;
131
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000132 FormatToken *Token;
Krasimir Georgieva1c30932017-05-19 10:34:57 +0000133 FormatToken *PreviousToken;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000134};
135
Craig Topper69665e12013-07-01 04:21:54 +0000136} // end anonymous namespace
137
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000138class ScopedLineState {
139public:
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000140 ScopedLineState(UnwrappedLineParser &Parser,
141 bool SwitchToPreprocessorLines = false)
David Blaikieefb6eb22014-08-09 20:02:07 +0000142 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
Manuel Klimekd3b92fa2013-01-18 14:04:34 +0000143 if (SwitchToPreprocessorLines)
144 Parser.CurrentLines = &Parser.PreprocessorDirectives;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000145 else if (!Parser.Line->Tokens.empty())
146 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
David Blaikieefb6eb22014-08-09 20:02:07 +0000147 PreBlockLine = std::move(Parser.Line);
148 Parser.Line = llvm::make_unique<UnwrappedLine>();
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000149 Parser.Line->Level = PreBlockLine->Level;
150 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000151 }
152
153 ~ScopedLineState() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000154 if (!Parser.Line->Tokens.empty()) {
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000155 Parser.addUnwrappedLine();
156 }
Daniel Jasperdaffc0d2013-01-16 09:10:19 +0000157 assert(Parser.Line->Tokens.empty());
David Blaikieefb6eb22014-08-09 20:02:07 +0000158 Parser.Line = std::move(PreBlockLine);
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000159 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
160 Parser.MustBreakBeforeNextToken = true;
161 Parser.CurrentLines = OriginalLines;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000162 }
163
164private:
165 UnwrappedLineParser &Parser;
166
David Blaikieefb6eb22014-08-09 20:02:07 +0000167 std::unique_ptr<UnwrappedLine> PreBlockLine;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +0000168 SmallVectorImpl<UnwrappedLine> *OriginalLines;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +0000169};
170
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000171class CompoundStatementIndenter {
172public:
173 CompoundStatementIndenter(UnwrappedLineParser *Parser,
174 const FormatStyle &Style, unsigned &LineLevel)
Owen Pan806d5742019-04-08 23:36:25 +0000175 : CompoundStatementIndenter(Parser, LineLevel,
176 Style.BraceWrapping.AfterControlStatement,
177 Style.BraceWrapping.IndentBraces) {
178 }
179 CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel,
180 bool WrapBrace, bool IndentBrace)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000181 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
Owen Pan806d5742019-04-08 23:36:25 +0000182 if (WrapBrace)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000183 Parser->addUnwrappedLine();
Owen Pan806d5742019-04-08 23:36:25 +0000184 if (IndentBrace)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000185 ++LineLevel;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000186 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000187 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000188
189private:
190 unsigned &LineLevel;
191 unsigned OldLineLevel;
192};
193
Craig Topper69665e12013-07-01 04:21:54 +0000194namespace {
195
Manuel Klimekab419912013-05-23 09:41:43 +0000196class IndexedTokenSource : public FormatTokenSource {
197public:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000198 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
Manuel Klimekab419912013-05-23 09:41:43 +0000199 : Tokens(Tokens), Position(-1) {}
200
Craig Topperfb6b25b2014-03-15 04:29:04 +0000201 FormatToken *getNextToken() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000202 ++Position;
203 return Tokens[Position];
204 }
205
Craig Topperfb6b25b2014-03-15 04:29:04 +0000206 unsigned getPosition() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000207 assert(Position >= 0);
208 return Position;
209 }
210
Craig Topperfb6b25b2014-03-15 04:29:04 +0000211 FormatToken *setPosition(unsigned P) override {
Manuel Klimekab419912013-05-23 09:41:43 +0000212 Position = P;
213 return Tokens[Position];
214 }
215
Manuel Klimek71814b42013-10-11 21:25:45 +0000216 void reset() { Position = -1; }
217
Manuel Klimekab419912013-05-23 09:41:43 +0000218private:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000219 ArrayRef<FormatToken *> Tokens;
Manuel Klimekab419912013-05-23 09:41:43 +0000220 int Position;
221};
222
Craig Topper69665e12013-07-01 04:21:54 +0000223} // end anonymous namespace
224
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000225UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000226 const AdditionalKeywords &Keywords,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000227 unsigned FirstStartColumn,
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000228 ArrayRef<FormatToken *> Tokens,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000229 UnwrappedLineConsumer &Callback)
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000230 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000231 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
232 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
Krasimir Georgievad47c902017-08-30 14:34:57 +0000233 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000234 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
235 ? IG_Rejected
236 : IG_Inited),
237 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
Manuel Klimek71814b42013-10-11 21:25:45 +0000238
239void UnwrappedLineParser::reset() {
240 PPBranchLevel = -1;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000241 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
242 ? IG_Rejected
243 : IG_Inited;
244 IncludeGuardToken = nullptr;
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 {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000260 LLVM_DEBUG(llvm::dbgs() << "----\n");
Manuel Klimek71814b42013-10-11 21:25:45 +0000261 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();
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000267
268 // If we found an include guard then all preprocessor directives (other than
269 // the guard) are over-indented by one.
270 if (IncludeGuard == IG_Found)
271 for (auto &Line : Lines)
272 if (Line.InPPDirective && Line.Level > 0)
273 --Line.Level;
274
Manuel Klimek71814b42013-10-11 21:25:45 +0000275 // Create line with eof token.
276 pushToken(FormatTok);
277 addUnwrappedLine();
278
279 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
280 E = Lines.end();
281 I != E; ++I) {
282 Callback.consumeUnwrappedLine(*I);
283 }
284 Callback.finishRun();
285 Lines.clear();
286 while (!PPLevelBranchIndex.empty() &&
Daniel Jasper53bd1672013-10-12 13:32:56 +0000287 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000288 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
289 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
290 }
291 if (!PPLevelBranchIndex.empty()) {
292 ++PPLevelBranchIndex.back();
293 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
294 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
295 }
296 } while (!PPLevelBranchIndex.empty());
Manuel Klimek1abf7892013-01-04 23:34:14 +0000297}
298
Manuel Klimek1a18c402013-04-12 14:13:36 +0000299void UnwrappedLineParser::parseFile() {
Daniel Jasper9326f912015-05-05 08:40:32 +0000300 // The top-level context in a file always has declarations, except for pre-
301 // processor directives and JavaScript files.
302 bool MustBeDeclaration =
303 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
304 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
305 MustBeDeclaration);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000306 if (Style.Language == FormatStyle::LK_TextProto)
307 parseBracedList();
308 else
309 parseLevel(/*HasOpeningBrace=*/false);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000310 // Make sure to format the remaining tokens.
Krasimir Georgiev0895f5e2018-06-25 11:08:24 +0000311 //
312 // LK_TextProto is special since its top-level is parsed as the body of a
313 // braced list, which does not necessarily have natural line separators such
314 // as a semicolon. Comments after the last entry that have been determined to
315 // not belong to that line, as in:
316 // key: value
317 // // endfile comment
318 // do not have a chance to be put on a line of their own until this point.
319 // Here we add this newline before end-of-file comments.
320 if (Style.Language == FormatStyle::LK_TextProto &&
321 !CommentsBeforeNextToken.empty())
322 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000323 flushComments(true);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000324 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000325}
326
Manuel Klimek1a18c402013-04-12 14:13:36 +0000327void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000328 bool SwitchLabelEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000329 do {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000330 tok::TokenKind kind = FormatTok->Tok.getKind();
331 if (FormatTok->Type == TT_MacroBlockBegin) {
332 kind = tok::l_brace;
333 } else if (FormatTok->Type == TT_MacroBlockEnd) {
334 kind = tok::r_brace;
335 }
336
337 switch (kind) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000338 case tok::comment:
Daniel Jaspere25509f2012-12-17 11:29:41 +0000339 nextToken();
340 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000341 break;
342 case tok::l_brace:
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000343 // FIXME: Add parameter whether this can happen - if this happens, we must
344 // be in a non-declaration context.
Daniel Jasperb86e2722015-08-24 13:23:37 +0000345 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
346 continue;
Nico Weber9096fc02013-06-26 00:30:14 +0000347 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000348 addUnwrappedLine();
349 break;
350 case tok::r_brace:
Manuel Klimek1a18c402013-04-12 14:13:36 +0000351 if (HasOpeningBrace)
352 return;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000353 nextToken();
354 addUnwrappedLine();
Manuel Klimek1058d982013-01-06 20:07:31 +0000355 break;
Nico Weberc29f83b2018-01-23 16:30:56 +0000356 case tok::kw_default: {
357 unsigned StoredPosition = Tokens->getPosition();
Jonas Toth90d2aa22018-08-24 17:25:06 +0000358 FormatToken *Next;
359 do {
360 Next = Tokens->getNextToken();
361 } while (Next && Next->is(tok::comment));
Nico Weberc29f83b2018-01-23 16:30:56 +0000362 FormatTok = Tokens->setPosition(StoredPosition);
363 if (Next && Next->isNot(tok::colon)) {
364 // default not followed by ':' is not a case label; treat it like
365 // an identifier.
366 parseStructuralElement();
367 break;
368 }
369 // Else, if it is 'default:', fall through to the case handling.
Nico Weberf1add5e2018-01-24 01:47:22 +0000370 LLVM_FALLTHROUGH;
Nico Weberc29f83b2018-01-23 16:30:56 +0000371 }
Daniel Jasper516d7972013-07-25 11:31:57 +0000372 case tok::kw_case:
Manuel Klimek89628f62017-09-20 09:51:03 +0000373 if (Style.Language == FormatStyle::LK_JavaScript &&
374 Line->MustBeDeclaration) {
Martin Probstf785fd92017-08-04 17:07:15 +0000375 // A 'case: string' style field declaration.
376 parseStructuralElement();
377 break;
378 }
Daniel Jasper72407622013-09-02 08:26:29 +0000379 if (!SwitchLabelEncountered &&
380 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
381 ++Line->Level;
Daniel Jasper516d7972013-07-25 11:31:57 +0000382 SwitchLabelEncountered = true;
383 parseStructuralElement();
384 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000385 default:
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000386 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +0000387 break;
388 }
389 } while (!eof());
390}
391
Daniel Jasperadba2aa2015-05-18 12:52:00 +0000392void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
Manuel Klimekab419912013-05-23 09:41:43 +0000393 // We'll parse forward through the tokens until we hit
394 // a closing brace or eof - note that getNextToken() will
395 // parse macros, so this will magically work inside macro
396 // definitions, too.
397 unsigned StoredPosition = Tokens->getPosition();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000398 FormatToken *Tok = FormatTok;
Manuel Klimek89628f62017-09-20 09:51:03 +0000399 const FormatToken *PrevTok = Tok->Previous;
Manuel Klimekab419912013-05-23 09:41:43 +0000400 // Keep a stack of positions of lbrace tokens. We will
401 // update information about whether an lbrace starts a
402 // braced init list or a different block during the loop.
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000403 SmallVector<FormatToken *, 8> LBraceStack;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000404 assert(Tok->Tok.is(tok::l_brace));
Manuel Klimekab419912013-05-23 09:41:43 +0000405 do {
Daniel Jaspereb65e912015-12-21 18:31:15 +0000406 // Get next non-comment token.
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000407 FormatToken *NextTok;
Daniel Jasperca7bd722013-07-01 16:43:38 +0000408 unsigned ReadTokens = 0;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000409 do {
410 NextTok = Tokens->getNextToken();
Daniel Jasperca7bd722013-07-01 16:43:38 +0000411 ++ReadTokens;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000412 } while (NextTok->is(tok::comment));
413
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000414 switch (Tok->Tok.getKind()) {
Manuel Klimekab419912013-05-23 09:41:43 +0000415 case tok::l_brace:
Martin Probst95ed8e72017-05-31 09:29:40 +0000416 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
Martin Probste8e27ca2017-11-25 09:33:47 +0000417 if (PrevTok->isOneOf(tok::colon, tok::less))
418 // A ':' indicates this code is in a type, or a braced list
419 // following a label in an object literal ({a: {b: 1}}).
420 // A '<' could be an object used in a comparison, but that is nonsense
421 // code (can never return true), so more likely it is a generic type
422 // argument (`X<{a: string; b: number}>`).
423 // The code below could be confused by semicolons between the
424 // individual members in a type member list, which would normally
425 // trigger BK_Block. In both cases, this must be parsed as an inline
426 // braced init.
Martin Probst95ed8e72017-05-31 09:29:40 +0000427 Tok->BlockKind = BK_BracedInit;
428 else if (PrevTok->is(tok::r_paren))
429 // `) { }` can only occur in function or method declarations in JS.
430 Tok->BlockKind = BK_Block;
431 } else {
Daniel Jasperb9a49902016-01-09 15:56:28 +0000432 Tok->BlockKind = BK_Unknown;
Martin Probst95ed8e72017-05-31 09:29:40 +0000433 }
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000434 LBraceStack.push_back(Tok);
Manuel Klimekab419912013-05-23 09:41:43 +0000435 break;
436 case tok::r_brace:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000437 if (LBraceStack.empty())
438 break;
439 if (LBraceStack.back()->BlockKind == BK_Unknown) {
440 bool ProbablyBracedList = false;
441 if (Style.Language == FormatStyle::LK_Proto) {
442 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
443 } else {
444 // Using OriginalColumn to distinguish between ObjC methods and
445 // binary operators is a bit hacky.
446 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
447 NextTok->OriginalColumn == 0;
Daniel Jasper91b032a2014-05-22 12:46:38 +0000448
Daniel Jasperb9a49902016-01-09 15:56:28 +0000449 // If there is a comma, semicolon or right paren after the closing
450 // brace, we assume this is a braced initializer list. Note that
451 // regardless how we mark inner braces here, we will overwrite the
452 // BlockKind later if we parse a braced list (where all blocks
453 // inside are by default braced lists), or when we explicitly detect
454 // blocks (for example while parsing lambdas).
Martin Probst95ed8e72017-05-31 09:29:40 +0000455 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
456 // braced list in JS.
Daniel Jasperb9a49902016-01-09 15:56:28 +0000457 ProbablyBracedList =
Daniel Jasperacffeb82016-03-05 18:34:26 +0000458 (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probste1e12a72016-08-19 14:35:01 +0000459 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
460 Keywords.kw_as)) ||
Martin Probstb7fb2672017-05-10 13:53:29 +0000461 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000462 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
463 tok::r_paren, tok::r_square, tok::l_brace,
Manuel Klimekd0f3fe52018-04-11 14:51:54 +0000464 tok::ellipsis) ||
Daniel Jaspere4ada022016-12-13 10:05:03 +0000465 (NextTok->is(tok::identifier) &&
466 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000467 (NextTok->is(tok::semi) &&
468 (!ExpectClassBody || LBraceStack.size() != 1)) ||
469 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
Manuel Klimekd0f3fe52018-04-11 14:51:54 +0000470 if (NextTok->is(tok::l_square)) {
471 // We can have an array subscript after a braced init
472 // list, but C++11 attributes are expected after blocks.
473 NextTok = Tokens->getNextToken();
474 ++ReadTokens;
475 ProbablyBracedList = NextTok->isNot(tok::l_square);
476 }
Manuel Klimekab419912013-05-23 09:41:43 +0000477 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000478 if (ProbablyBracedList) {
479 Tok->BlockKind = BK_BracedInit;
480 LBraceStack.back()->BlockKind = BK_BracedInit;
481 } else {
482 Tok->BlockKind = BK_Block;
483 LBraceStack.back()->BlockKind = BK_Block;
484 }
Manuel Klimekab419912013-05-23 09:41:43 +0000485 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000486 LBraceStack.pop_back();
Manuel Klimekab419912013-05-23 09:41:43 +0000487 break;
Francois Ferrand6f40e212018-10-02 16:37:51 +0000488 case tok::identifier:
489 if (!Tok->is(TT_StatementMacro))
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000490 break;
Francois Ferrand6f40e212018-10-02 16:37:51 +0000491 LLVM_FALLTHROUGH;
Daniel Jasperac7e34e2014-03-13 10:11:17 +0000492 case tok::at:
Manuel Klimekab419912013-05-23 09:41:43 +0000493 case tok::semi:
494 case tok::kw_if:
495 case tok::kw_while:
496 case tok::kw_for:
497 case tok::kw_switch:
498 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +0000499 case tok::kw___try:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000500 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000501 LBraceStack.back()->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000502 break;
503 default:
504 break;
505 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000506 PrevTok = Tok;
Manuel Klimekab419912013-05-23 09:41:43 +0000507 Tok = NextTok;
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000508 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
Daniel Jasperb9a49902016-01-09 15:56:28 +0000509
Manuel Klimekab419912013-05-23 09:41:43 +0000510 // Assume other blocks for all unclosed opening braces.
511 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000512 if (LBraceStack[i]->BlockKind == BK_Unknown)
513 LBraceStack[i]->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000514 }
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000515
Manuel Klimekab419912013-05-23 09:41:43 +0000516 FormatTok = Tokens->setPosition(StoredPosition);
517}
518
Francois Ferranda98a95c2017-07-28 07:56:14 +0000519template <class T>
520static inline void hash_combine(std::size_t &seed, const T &v) {
521 std::hash<T> hasher;
522 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
523}
524
525size_t UnwrappedLineParser::computePPHash() const {
526 size_t h = 0;
527 for (const auto &i : PPStack) {
528 hash_combine(h, size_t(i.Kind));
529 hash_combine(h, i.Line);
530 }
531 return h;
532}
533
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000534void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
535 bool MunchSemi) {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000536 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
537 "'{' or macro block token expected");
538 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
Daniel Jaspereb65e912015-12-21 18:31:15 +0000539 FormatTok->BlockKind = BK_Block;
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000540
Francois Ferranda98a95c2017-07-28 07:56:14 +0000541 size_t PPStartHash = computePPHash();
542
Daniel Jasper516d7972013-07-25 11:31:57 +0000543 unsigned InitialLevel = Line->Level;
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000544 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
Daniel Jasperf7935112012-12-03 18:12:45 +0000545
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000546 if (MacroBlock && FormatTok->is(tok::l_paren))
547 parseParens();
548
Francois Ferranda98a95c2017-07-28 07:56:14 +0000549 size_t NbPreprocessorDirectives =
550 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000551 addUnwrappedLine();
Francois Ferranda98a95c2017-07-28 07:56:14 +0000552 size_t OpeningLineIndex =
553 CurrentLines->empty()
554 ? (UnwrappedLine::kInvalidIndex)
555 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
Daniel Jasperf7935112012-12-03 18:12:45 +0000556
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000557 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
558 MustBeDeclaration);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000559 if (AddLevel)
560 ++Line->Level;
Nico Weber9096fc02013-06-26 00:30:14 +0000561 parseLevel(/*HasOpeningBrace=*/true);
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000562
Marianne Mailhot-Sarrasin03137c62016-04-14 14:56:49 +0000563 if (eof())
564 return;
565
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000566 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
567 : !FormatTok->is(tok::r_brace)) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000568 Line->Level = InitialLevel;
Daniel Jaspereb65e912015-12-21 18:31:15 +0000569 FormatTok->BlockKind = BK_Block;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000570 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000571 }
Alexander Kornienko0ea8e102012-12-04 15:40:36 +0000572
Francois Ferranda98a95c2017-07-28 07:56:14 +0000573 size_t PPEndHash = computePPHash();
574
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000575 // Munch the closing brace.
576 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000577
578 if (MacroBlock && FormatTok->is(tok::l_paren))
579 parseParens();
580
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000581 if (MunchSemi && FormatTok->Tok.is(tok::semi))
582 nextToken();
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000583 Line->Level = InitialLevel;
Francois Ferranda98a95c2017-07-28 07:56:14 +0000584
585 if (PPStartHash == PPEndHash) {
586 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
587 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
588 // Update the opening line to add the forward reference as well
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000589 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
Francois Ferranda98a95c2017-07-28 07:56:14 +0000590 CurrentLines->size() - 1;
591 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000592 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000593}
594
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000595static bool isGoogScope(const UnwrappedLine &Line) {
Daniel Jasper616de8642014-11-23 16:46:28 +0000596 // FIXME: Closure-library specific stuff should not be hard-coded but be
597 // configurable.
Daniel Jasper4a39c842014-05-06 13:54:10 +0000598 if (Line.Tokens.size() < 4)
599 return false;
600 auto I = Line.Tokens.begin();
601 if (I->Tok->TokenText != "goog")
602 return false;
603 ++I;
604 if (I->Tok->isNot(tok::period))
605 return false;
606 ++I;
607 if (I->Tok->TokenText != "scope")
608 return false;
609 ++I;
610 return I->Tok->is(tok::l_paren);
611}
612
Martin Probst101ec892017-05-09 20:04:09 +0000613static bool isIIFE(const UnwrappedLine &Line,
614 const AdditionalKeywords &Keywords) {
615 // Look for the start of an immediately invoked anonymous function.
616 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
617 // This is commonly done in JavaScript to create a new, anonymous scope.
618 // Example: (function() { ... })()
619 if (Line.Tokens.size() < 3)
620 return false;
621 auto I = Line.Tokens.begin();
622 if (I->Tok->isNot(tok::l_paren))
623 return false;
624 ++I;
625 if (I->Tok->isNot(Keywords.kw_function))
626 return false;
627 ++I;
628 return I->Tok->is(tok::l_paren);
629}
630
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000631static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
632 const FormatToken &InitialToken) {
Francois Ferrande8a301f2019-06-06 20:06:23 +0000633 if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro))
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000634 return Style.BraceWrapping.AfterNamespace;
635 if (InitialToken.is(tok::kw_class))
636 return Style.BraceWrapping.AfterClass;
637 if (InitialToken.is(tok::kw_union))
638 return Style.BraceWrapping.AfterUnion;
639 if (InitialToken.is(tok::kw_struct))
640 return Style.BraceWrapping.AfterStruct;
641 return false;
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000642}
643
Manuel Klimek516e0542013-09-04 13:25:30 +0000644void UnwrappedLineParser::parseChildBlock() {
645 FormatTok->BlockKind = BK_Block;
646 nextToken();
647 {
Manuel Klimek89628f62017-09-20 09:51:03 +0000648 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
649 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
Manuel Klimek516e0542013-09-04 13:25:30 +0000650 ScopedLineState LineState(*this);
651 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
652 /*MustBeDeclaration=*/false);
Martin Probst101ec892017-05-09 20:04:09 +0000653 Line->Level += SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000654 parseLevel(/*HasOpeningBrace=*/true);
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000655 flushComments(isOnNewLine(*FormatTok));
Martin Probst101ec892017-05-09 20:04:09 +0000656 Line->Level -= SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000657 }
658 nextToken();
659}
660
Daniel Jasperf7935112012-12-03 18:12:45 +0000661void UnwrappedLineParser::parsePPDirective() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000662 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
Manuel Klimek20e0af62015-05-06 11:56:29 +0000663 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
Paul Hoad701a0d72019-03-20 20:49:43 +0000664
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000665 nextToken();
666
Craig Topper2145bc02014-05-09 08:15:10 +0000667 if (!FormatTok->Tok.getIdentifierInfo()) {
Manuel Klimek591b5802013-01-31 15:58:48 +0000668 parsePPUnknown();
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000669 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000670 }
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000671
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000672 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000673 case tok::pp_define:
674 parsePPDefine();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000675 return;
676 case tok::pp_if:
Manuel Klimek71814b42013-10-11 21:25:45 +0000677 parsePPIf(/*IfDef=*/false);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000678 break;
679 case tok::pp_ifdef:
680 case tok::pp_ifndef:
Manuel Klimek71814b42013-10-11 21:25:45 +0000681 parsePPIf(/*IfDef=*/true);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000682 break;
683 case tok::pp_else:
684 parsePPElse();
685 break;
686 case tok::pp_elif:
687 parsePPElIf();
688 break;
689 case tok::pp_endif:
690 parsePPEndIf();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000691 break;
692 default:
693 parsePPUnknown();
694 break;
695 }
696}
697
Manuel Klimek68b03042014-04-14 09:14:11 +0000698void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
Francois Ferranda98a95c2017-07-28 07:56:14 +0000699 size_t Line = CurrentLines->size();
700 if (CurrentLines == &PreprocessorDirectives)
701 Line += Lines.size();
702
703 if (Unreachable ||
704 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
705 PPStack.push_back({PP_Unreachable, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000706 else
Francois Ferranda98a95c2017-07-28 07:56:14 +0000707 PPStack.push_back({PP_Conditional, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000708}
709
Manuel Klimek68b03042014-04-14 09:14:11 +0000710void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000711 ++PPBranchLevel;
712 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
713 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
714 PPLevelBranchIndex.push_back(0);
715 PPLevelBranchCount.push_back(0);
716 }
717 PPChainBranchIndex.push(0);
Manuel Klimek68b03042014-04-14 09:14:11 +0000718 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
719 conditionalCompilationCondition(Unreachable || Skip);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000720}
721
Manuel Klimek68b03042014-04-14 09:14:11 +0000722void UnwrappedLineParser::conditionalCompilationAlternative() {
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000723 if (!PPStack.empty())
724 PPStack.pop_back();
Manuel Klimek71814b42013-10-11 21:25:45 +0000725 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
726 if (!PPChainBranchIndex.empty())
727 ++PPChainBranchIndex.top();
Manuel Klimek68b03042014-04-14 09:14:11 +0000728 conditionalCompilationCondition(
729 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
730 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000731}
732
Manuel Klimek68b03042014-04-14 09:14:11 +0000733void UnwrappedLineParser::conditionalCompilationEnd() {
Manuel Klimek71814b42013-10-11 21:25:45 +0000734 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
735 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
736 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000737 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
738 }
739 }
Manuel Klimek14bd9172014-01-29 08:49:02 +0000740 // Guard against #endif's without #if.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000741 if (PPBranchLevel > -1)
Manuel Klimek14bd9172014-01-29 08:49:02 +0000742 --PPBranchLevel;
Manuel Klimek71814b42013-10-11 21:25:45 +0000743 if (!PPChainBranchIndex.empty())
744 PPChainBranchIndex.pop();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000745 if (!PPStack.empty())
746 PPStack.pop_back();
Manuel Klimek68b03042014-04-14 09:14:11 +0000747}
748
749void UnwrappedLineParser::parsePPIf(bool IfDef) {
Daniel Jasper62703eb2017-03-01 11:10:11 +0000750 bool IfNDef = FormatTok->is(tok::pp_ifndef);
Manuel Klimek68b03042014-04-14 09:14:11 +0000751 nextToken();
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000752 bool Unreachable = false;
753 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
754 Unreachable = true;
Daniel Jasper62703eb2017-03-01 11:10:11 +0000755 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000756 Unreachable = true;
757 conditionalCompilationStart(Unreachable);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000758 FormatToken *IfCondition = FormatTok;
759 // If there's a #ifndef on the first line, and the only lines before it are
760 // comments, it could be an include guard.
761 bool MaybeIncludeGuard = IfNDef;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000762 if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000763 for (auto &Line : Lines) {
764 if (!Line.Tokens.front().Tok->is(tok::comment)) {
765 MaybeIncludeGuard = false;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000766 IncludeGuard = IG_Rejected;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000767 break;
768 }
769 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000770 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000771 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000772 ++PPBranchLevel;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000773 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
774 IncludeGuard = IG_IfNdefed;
775 IncludeGuardToken = IfCondition;
776 }
Manuel Klimek68b03042014-04-14 09:14:11 +0000777}
778
779void UnwrappedLineParser::parsePPElse() {
Krasimir Georgievad47c902017-08-30 14:34:57 +0000780 // If a potential include guard has an #else, it's not an include guard.
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000781 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
782 IncludeGuard = IG_Rejected;
Manuel Klimek68b03042014-04-14 09:14:11 +0000783 conditionalCompilationAlternative();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000784 if (PPBranchLevel > -1)
785 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000786 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000787 ++PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000788}
789
790void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
791
792void UnwrappedLineParser::parsePPEndIf() {
793 conditionalCompilationEnd();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000794 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000795 // If the #endif of a potential include guard is the last thing in the file,
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000796 // then we found an include guard.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000797 unsigned TokenPosition = Tokens->getPosition();
798 FormatToken *PeekNext = AllTokens[TokenPosition];
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000799 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
800 PeekNext->is(tok::eof) &&
Daniel Jasper4df130f2017-09-04 13:33:52 +0000801 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000802 IncludeGuard = IG_Found;
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000803}
804
Manuel Klimek1abf7892013-01-04 23:34:14 +0000805void UnwrappedLineParser::parsePPDefine() {
806 nextToken();
807
Owen Panfb73b79a2019-04-18 20:17:08 +0000808 if (!FormatTok->Tok.getIdentifierInfo()) {
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000809 IncludeGuard = IG_Rejected;
810 IncludeGuardToken = nullptr;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000811 parsePPUnknown();
812 return;
813 }
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000814
815 if (IncludeGuard == IG_IfNdefed &&
816 IncludeGuardToken->TokenText == FormatTok->TokenText) {
817 IncludeGuard = IG_Defined;
818 IncludeGuardToken = nullptr;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000819 for (auto &Line : Lines) {
820 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000821 IncludeGuard = IG_Rejected;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000822 break;
823 }
824 }
825 }
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000826
Manuel Klimek1abf7892013-01-04 23:34:14 +0000827 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000828 if (FormatTok->Tok.getKind() == tok::l_paren &&
829 FormatTok->WhitespaceRange.getBegin() ==
830 FormatTok->WhitespaceRange.getEnd()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000831 parseParens();
832 }
Paul Hoad701a0d72019-03-20 20:49:43 +0000833 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000834 Line->Level += PPBranchLevel + 1;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000835 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000836 ++Line->Level;
Manuel Klimek1b896292013-01-07 09:34:28 +0000837
838 // Errors during a preprocessor directive can only affect the layout of the
839 // preprocessor directive, and thus we ignore them. An alternative approach
840 // would be to use the same approach we use on the file level (no
841 // re-indentation if there was a structural error) within the macro
842 // definition.
Manuel Klimek1abf7892013-01-04 23:34:14 +0000843 parseFile();
844}
845
846void UnwrappedLineParser::parsePPUnknown() {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000847 do {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000848 nextToken();
849 } while (!eof());
Paul Hoad701a0d72019-03-20 20:49:43 +0000850 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000851 Line->Level += PPBranchLevel + 1;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000852 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000853}
854
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000855// Here we blacklist certain tokens that are not usually the first token in an
856// unwrapped line. This is used in attempt to distinguish macro calls without
857// trailing semicolons from other constructs split to several lines.
Benjamin Kramer8407df72015-03-09 16:47:52 +0000858static bool tokenCanStartNewLine(const clang::Token &Tok) {
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000859 // Semicolon can be a null-statement, l_square can be a start of a macro or
860 // a C++11 attribute, but this doesn't seem to be common.
861 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
862 Tok.isNot(tok::l_square) &&
863 // Tokens that can only be used as binary operators and a part of
864 // overloaded operator names.
865 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
866 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
867 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
868 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
869 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
870 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
871 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
872 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
873 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
874 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
875 Tok.isNot(tok::lesslessequal) &&
876 // Colon is used in labels, base class lists, initializer lists,
877 // range-based for loops, ternary operator, but should never be the
878 // first token in an unwrapped line.
Daniel Jasper5ebb2f32014-05-21 13:08:17 +0000879 Tok.isNot(tok::colon) &&
880 // 'noexcept' is a trailing annotation.
881 Tok.isNot(tok::kw_noexcept);
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000882}
883
Martin Probst533965c2016-04-19 18:19:06 +0000884static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
885 const FormatToken *FormatTok) {
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000886 // FIXME: This returns true for C/C++ keywords like 'struct'.
887 return FormatTok->is(tok::identifier) &&
888 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
Martin Probst3dbbefa2016-11-10 16:21:02 +0000889 !FormatTok->isOneOf(
890 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
891 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
892 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
893 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
894 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
Manuel Klimek89628f62017-09-20 09:51:03 +0000895 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
896 Keywords.kw_from));
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000897}
898
Martin Probst533965c2016-04-19 18:19:06 +0000899static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
900 const FormatToken *FormatTok) {
Martin Probstb9316ff2016-09-18 17:21:52 +0000901 return FormatTok->Tok.isLiteral() ||
902 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
903 mustBeJSIdent(Keywords, FormatTok);
Martin Probst533965c2016-04-19 18:19:06 +0000904}
905
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000906// isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
907// when encountered after a value (see mustBeJSIdentOrValue).
908static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
909 const FormatToken *FormatTok) {
910 return FormatTok->isOneOf(
Martin Probst5f8445b2016-04-24 22:05:09 +0000911 tok::kw_return, Keywords.kw_yield,
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000912 // conditionals
913 tok::kw_if, tok::kw_else,
914 // loops
915 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
916 // switch/case
917 tok::kw_switch, tok::kw_case,
918 // exceptions
919 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
920 // declaration
921 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
Martin Probst5f8445b2016-04-24 22:05:09 +0000922 Keywords.kw_async, Keywords.kw_function,
923 // import/export
924 Keywords.kw_import, tok::kw_export);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000925}
926
927// readTokenWithJavaScriptASI reads the next token and terminates the current
928// line if JavaScript Automatic Semicolon Insertion must
929// happen between the current token and the next token.
930//
931// This method is conservative - it cannot cover all edge cases of JavaScript,
932// but only aims to correctly handle certain well known cases. It *must not*
933// return true in speculative cases.
934void UnwrappedLineParser::readTokenWithJavaScriptASI() {
935 FormatToken *Previous = FormatTok;
936 readToken();
937 FormatToken *Next = FormatTok;
938
939 bool IsOnSameLine =
940 CommentsBeforeNextToken.empty()
941 ? Next->NewlinesBefore == 0
942 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
943 if (IsOnSameLine)
944 return;
945
946 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
Martin Probst717f6dc2016-10-21 05:11:38 +0000947 bool PreviousStartsTemplateExpr =
948 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
Martin Probst7e0f25b2017-11-25 09:19:42 +0000949 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
950 // If the line contains an '@' sign, the previous token might be an
951 // annotation, which can precede another identifier/value.
952 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
953 [](UnwrappedLineNode &LineNode) {
954 return LineNode.Tok->is(tok::at);
955 }) != Line->Tokens.end();
956 if (HasAt)
Martin Probstbbffeac2016-04-11 07:35:57 +0000957 return;
958 }
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000959 if (Next->is(tok::exclaim) && PreviousMustBeValue)
Martin Probstd40bca42017-01-09 08:56:36 +0000960 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000961 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
Martin Probst717f6dc2016-10-21 05:11:38 +0000962 bool NextEndsTemplateExpr =
963 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
964 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
965 (PreviousMustBeValue ||
966 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
967 tok::minusminus)))
Martin Probstd40bca42017-01-09 08:56:36 +0000968 return addUnwrappedLine();
Martin Probst0a19d432017-08-09 15:19:16 +0000969 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
970 isJSDeclOrStmt(Keywords, Next))
Martin Probstd40bca42017-01-09 08:56:36 +0000971 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000972}
973
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000974void UnwrappedLineParser::parseStructuralElement() {
Daniel Jasper498f5582015-12-25 08:53:31 +0000975 assert(!FormatTok->is(tok::l_brace));
976 if (Style.Language == FormatStyle::LK_TableGen &&
977 FormatTok->is(tok::pp_include)) {
978 nextToken();
979 if (FormatTok->is(tok::string_literal))
980 nextToken();
981 addUnwrappedLine();
982 return;
983 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000984 switch (FormatTok->Tok.getKind()) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000985 case tok::kw_asm:
Daniel Jasper8f463652014-08-26 23:15:12 +0000986 nextToken();
987 if (FormatTok->is(tok::l_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000988 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper2337f282015-01-12 10:14:56 +0000989 nextToken();
Daniel Jasper4429f142014-08-27 17:16:46 +0000990 while (FormatTok && FormatTok->isNot(tok::eof)) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000991 if (FormatTok->is(tok::r_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000992 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper8f463652014-08-26 23:15:12 +0000993 nextToken();
Daniel Jasper790d4f92015-05-11 11:59:46 +0000994 addUnwrappedLine();
Daniel Jasper8f463652014-08-26 23:15:12 +0000995 break;
996 }
Daniel Jasper2337f282015-01-12 10:14:56 +0000997 FormatTok->Finalized = true;
Daniel Jasper8f463652014-08-26 23:15:12 +0000998 nextToken();
999 }
1000 }
1001 break;
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001002 case tok::kw_namespace:
1003 parseNamespace();
1004 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001005 case tok::kw_public:
1006 case tok::kw_protected:
1007 case tok::kw_private:
Daniel Jasper83709082015-02-18 17:14:05 +00001008 if (Style.Language == FormatStyle::LK_Java ||
Paul Hoadcbb726d2019-03-21 13:09:22 +00001009 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001010 nextToken();
1011 else
1012 parseAccessSpecifier();
Daniel Jasperf7935112012-12-03 18:12:45 +00001013 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001014 case tok::kw_if:
1015 parseIfThenElse();
Daniel Jasperf7935112012-12-03 18:12:45 +00001016 return;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001017 case tok::kw_for:
1018 case tok::kw_while:
1019 parseForOrWhileLoop();
1020 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001021 case tok::kw_do:
1022 parseDoWhile();
1023 return;
1024 case tok::kw_switch:
Martin Probstf785fd92017-08-04 17:07:15 +00001025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1026 // 'switch: string' field declaration.
1027 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001028 parseSwitch();
1029 return;
1030 case tok::kw_default:
Martin Probstf785fd92017-08-04 17:07:15 +00001031 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1032 // 'default: string' field declaration.
1033 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001034 nextToken();
Nico Weberc29f83b2018-01-23 16:30:56 +00001035 if (FormatTok->is(tok::colon)) {
1036 parseLabel();
1037 return;
1038 }
1039 // e.g. "default void f() {}" in a Java interface.
1040 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001041 case tok::kw_case:
Martin Probstf785fd92017-08-04 17:07:15 +00001042 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1043 // 'case: string' field declaration.
1044 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001045 parseCaseLabel();
1046 return;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001047 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +00001048 case tok::kw___try:
Daniel Jasper04a71a42014-05-08 11:58:24 +00001049 parseTryCatch();
1050 return;
Manuel Klimekae610d12013-01-21 14:32:05 +00001051 case tok::kw_extern:
1052 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001053 if (FormatTok->Tok.is(tok::string_literal)) {
Manuel Klimekae610d12013-01-21 14:32:05 +00001054 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001055 if (FormatTok->Tok.is(tok::l_brace)) {
Krasimir Georgievd6ce9372017-09-15 11:23:50 +00001056 if (Style.BraceWrapping.AfterExternBlock) {
1057 addUnwrappedLine();
1058 parseBlock(/*MustBeDeclaration=*/true);
1059 } else {
1060 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1061 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001062 addUnwrappedLine();
1063 return;
1064 }
1065 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001066 break;
Daniel Jasperfca735c2015-02-19 16:14:18 +00001067 case tok::kw_export:
1068 if (Style.Language == FormatStyle::LK_JavaScript) {
1069 parseJavaScriptEs6ImportExport();
1070 return;
1071 }
Sam McCall6f3778c2018-09-05 07:44:02 +00001072 if (!Style.isCpp())
1073 break;
1074 // Handle C++ "(inline|export) namespace".
1075 LLVM_FALLTHROUGH;
1076 case tok::kw_inline:
1077 nextToken();
1078 if (FormatTok->Tok.is(tok::kw_namespace)) {
1079 parseNamespace();
1080 return;
1081 }
Daniel Jasperfca735c2015-02-19 16:14:18 +00001082 break;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001083 case tok::identifier:
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001084 if (FormatTok->is(TT_ForEachMacro)) {
Daniel Jaspere1e43192014-04-01 12:55:11 +00001085 parseForOrWhileLoop();
1086 return;
1087 }
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001088 if (FormatTok->is(TT_MacroBlockBegin)) {
1089 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1090 /*MunchSemi=*/false);
1091 return;
1092 }
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001093 if (FormatTok->is(Keywords.kw_import)) {
1094 if (Style.Language == FormatStyle::LK_JavaScript) {
1095 parseJavaScriptEs6ImportExport();
1096 return;
1097 }
1098 if (Style.Language == FormatStyle::LK_Proto) {
1099 nextToken();
Daniel Jasper8b61d142016-06-20 20:39:53 +00001100 if (FormatTok->is(tok::kw_public))
1101 nextToken();
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001102 if (!FormatTok->is(tok::string_literal))
1103 return;
1104 nextToken();
1105 if (FormatTok->is(tok::semi))
1106 nextToken();
1107 addUnwrappedLine();
1108 return;
1109 }
Daniel Jasper354aa512015-02-19 16:07:32 +00001110 }
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001111 if (Style.isCpp() &&
Daniel Jasper72b33572017-03-31 12:04:37 +00001112 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
Daniel Jaspera00de632015-12-01 12:05:04 +00001113 Keywords.kw_slots, Keywords.kw_qslots)) {
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001114 nextToken();
1115 if (FormatTok->is(tok::colon)) {
1116 nextToken();
1117 addUnwrappedLine();
Daniel Jasper31343832016-07-27 10:13:24 +00001118 return;
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001119 }
Daniel Jasper53395402015-04-07 15:04:40 +00001120 }
Francois Ferrand6f40e212018-10-02 16:37:51 +00001121 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1122 parseStatementMacro();
1123 return;
1124 }
Francois Ferrande8a301f2019-06-06 20:06:23 +00001125 if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) {
1126 parseNamespace();
1127 return;
1128 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001129 // In all other cases, parse the declaration.
1130 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001131 default:
1132 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001133 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001134 do {
Manuel Klimeke411aa82017-09-20 09:29:37 +00001135 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001136 switch (FormatTok->Tok.getKind()) {
Nico Weber372d8dc2013-02-10 20:35:35 +00001137 case tok::at:
1138 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001139 if (FormatTok->Tok.is(tok::l_brace)) {
1140 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001141 parseBracedList();
Nico Weberc068ff72018-01-23 17:10:25 +00001142 break;
Hans Wennborg749c1b52018-10-19 16:19:52 +00001143 } else if (Style.Language == FormatStyle::LK_Java &&
1144 FormatTok->is(Keywords.kw_interface)) {
1145 nextToken();
1146 break;
Nico Weberc068ff72018-01-23 17:10:25 +00001147 }
1148 switch (FormatTok->Tok.getObjCKeywordID()) {
1149 case tok::objc_public:
1150 case tok::objc_protected:
1151 case tok::objc_package:
1152 case tok::objc_private:
1153 return parseAccessSpecifier();
1154 case tok::objc_interface:
1155 case tok::objc_implementation:
1156 return parseObjCInterfaceOrImplementation();
1157 case tok::objc_protocol:
1158 if (parseObjCProtocol())
1159 return;
1160 break;
1161 case tok::objc_end:
1162 return; // Handled by the caller.
1163 case tok::objc_optional:
1164 case tok::objc_required:
1165 nextToken();
1166 addUnwrappedLine();
1167 return;
1168 case tok::objc_autoreleasepool:
1169 nextToken();
1170 if (FormatTok->Tok.is(tok::l_brace)) {
Francois Ferranda2484b22018-02-27 13:48:27 +00001171 if (Style.BraceWrapping.AfterControlStatement)
Nico Weberc068ff72018-01-23 17:10:25 +00001172 addUnwrappedLine();
1173 parseBlock(/*MustBeDeclaration=*/false);
1174 }
1175 addUnwrappedLine();
1176 return;
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001177 case tok::objc_synchronized:
1178 nextToken();
1179 if (FormatTok->Tok.is(tok::l_paren))
Paul Hoad5bcf99b2019-03-01 09:09:54 +00001180 // Skip synchronization object
1181 parseParens();
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001182 if (FormatTok->Tok.is(tok::l_brace)) {
Francois Ferranda2484b22018-02-27 13:48:27 +00001183 if (Style.BraceWrapping.AfterControlStatement)
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001184 addUnwrappedLine();
1185 parseBlock(/*MustBeDeclaration=*/false);
1186 }
1187 addUnwrappedLine();
1188 return;
Nico Weberc068ff72018-01-23 17:10:25 +00001189 case tok::objc_try:
1190 // This branch isn't strictly necessary (the kw_try case below would
1191 // do this too after the tok::at is parsed above). But be explicit.
1192 parseTryCatch();
1193 return;
1194 default:
1195 break;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001196 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001197 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001198 case tok::kw_enum:
Daniel Jaspera7900ad2016-05-08 18:12:22 +00001199 // Ignore if this is part of "template <enum ...".
1200 if (Previous && Previous->is(tok::less)) {
1201 nextToken();
1202 break;
1203 }
1204
Daniel Jasper90cf3802015-06-17 09:44:02 +00001205 // parseEnum falls through and does not yet add an unwrapped line as an
1206 // enum definition can start a structural element.
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001207 if (!parseEnum())
1208 break;
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001209 // This only applies for C++.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001210 if (!Style.isCpp()) {
Daniel Jasper90cf3802015-06-17 09:44:02 +00001211 addUnwrappedLine();
1212 return;
1213 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001214 break;
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001215 case tok::kw_typedef:
1216 nextToken();
Daniel Jasper31f6c542014-12-05 10:42:21 +00001217 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
Ben Hamiltond9212ef2019-07-22 18:20:01 +00001218 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1219 Keywords.kw_CF_CLOSED_ENUM, Keywords.kw_NS_CLOSED_ENUM))
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001220 parseEnum();
1221 break;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001222 case tok::kw_struct:
1223 case tok::kw_union:
Manuel Klimek28cacc72013-01-07 18:10:23 +00001224 case tok::kw_class:
Daniel Jasper910807d2015-06-12 04:52:02 +00001225 // parseRecord falls through and does not yet add an unwrapped line as a
1226 // record declaration or definition can start a structural element.
Manuel Klimeke01bab52013-01-15 13:38:33 +00001227 parseRecord();
Paul Hoadcbb726d2019-03-21 13:09:22 +00001228 // This does not apply for Java, JavaScript and C#.
Daniel Jasper910807d2015-06-12 04:52:02 +00001229 if (Style.Language == FormatStyle::LK_Java ||
Paul Hoadcbb726d2019-03-21 13:09:22 +00001230 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
Daniel Jasperd5ec65b2016-01-08 07:06:07 +00001231 if (FormatTok->is(tok::semi))
1232 nextToken();
Daniel Jasper910807d2015-06-12 04:52:02 +00001233 addUnwrappedLine();
1234 return;
1235 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00001236 break;
Daniel Jaspere5d74862014-11-26 08:17:08 +00001237 case tok::period:
1238 nextToken();
1239 // In Java, classes have an implicit static member "class".
1240 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1241 FormatTok->is(tok::kw_class))
1242 nextToken();
Daniel Jasperba52fcb2015-09-28 14:29:45 +00001243 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1244 FormatTok->Tok.getIdentifierInfo())
1245 // JavaScript only has pseudo keywords, all keywords are allowed to
1246 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1247 nextToken();
Daniel Jaspere5d74862014-11-26 08:17:08 +00001248 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001249 case tok::semi:
1250 nextToken();
1251 addUnwrappedLine();
1252 return;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001253 case tok::r_brace:
1254 addUnwrappedLine();
1255 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001256 case tok::l_paren:
1257 parseParens();
1258 break;
Daniel Jasper5af04a42015-10-07 03:43:10 +00001259 case tok::kw_operator:
1260 nextToken();
1261 if (FormatTok->isBinaryOperator())
1262 nextToken();
1263 break;
Manuel Klimek516e0542013-09-04 13:25:30 +00001264 case tok::caret:
1265 nextToken();
Daniel Jasper395193c2014-03-28 07:48:59 +00001266 if (FormatTok->Tok.isAnyIdentifier() ||
1267 FormatTok->isSimpleTypeSpecifier())
1268 nextToken();
1269 if (FormatTok->is(tok::l_paren))
1270 parseParens();
1271 if (FormatTok->is(tok::l_brace))
Manuel Klimek516e0542013-09-04 13:25:30 +00001272 parseChildBlock();
Manuel Klimek516e0542013-09-04 13:25:30 +00001273 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001274 case tok::l_brace:
Manuel Klimekab419912013-05-23 09:41:43 +00001275 if (!tryToParseBracedList()) {
1276 // A block outside of parentheses must be the last part of a
1277 // structural element.
1278 // FIXME: Figure out cases where this is not true, and add projections
1279 // for them (the one we know is missing are lambdas).
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001280 if (Style.BraceWrapping.AfterFunction)
Manuel Klimekab419912013-05-23 09:41:43 +00001281 addUnwrappedLine();
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001282 FormatTok->Type = TT_FunctionLBrace;
Nico Weber9096fc02013-06-26 00:30:14 +00001283 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001284 addUnwrappedLine();
Manuel Klimekab419912013-05-23 09:41:43 +00001285 return;
1286 }
1287 // Otherwise this was a braced init list, and the structural
1288 // element continues.
1289 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001290 case tok::kw_try:
1291 // We arrive here when parsing function-try blocks.
Owen Pancb5ffbe2018-09-28 09:17:00 +00001292 if (Style.BraceWrapping.AfterFunction)
1293 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001294 parseTryCatch();
1295 return;
Daniel Jasper40e19212013-05-29 13:16:10 +00001296 case tok::identifier: {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001297 if (FormatTok->is(TT_MacroBlockEnd)) {
1298 addUnwrappedLine();
1299 return;
1300 }
1301
Martin Probst973ff792017-04-27 13:07:24 +00001302 // Function declarations (as opposed to function expressions) are parsed
1303 // on their own unwrapped line by continuing this loop. Function
1304 // expressions (functions that are not on their own line) must not create
1305 // a new unwrapped line, so they are special cased below.
1306 size_t TokenCount = Line->Tokens.size();
Daniel Jasper9326f912015-05-05 08:40:32 +00001307 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst973ff792017-04-27 13:07:24 +00001308 FormatTok->is(Keywords.kw_function) &&
1309 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1310 Keywords.kw_async)))) {
Daniel Jasper069e5f42014-05-20 11:14:57 +00001311 tryToParseJSFunction();
1312 break;
1313 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001314 if ((Style.Language == FormatStyle::LK_JavaScript ||
1315 Style.Language == FormatStyle::LK_Java) &&
1316 FormatTok->is(Keywords.kw_interface)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001317 if (Style.Language == FormatStyle::LK_JavaScript) {
1318 // In JavaScript/TypeScript, "interface" can be used as a standalone
1319 // identifier, e.g. in `var interface = 1;`. If "interface" is
1320 // followed by another identifier, it is very like to be an actual
1321 // interface declaration.
1322 unsigned StoredPosition = Tokens->getPosition();
1323 FormatToken *Next = Tokens->getNextToken();
1324 FormatTok = Tokens->setPosition(StoredPosition);
Martin Probst533965c2016-04-19 18:19:06 +00001325 if (Next && !mustBeJSIdent(Keywords, Next)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001326 nextToken();
1327 break;
1328 }
1329 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001330 parseRecord();
Daniel Jasper259188b2015-06-12 04:56:34 +00001331 addUnwrappedLine();
Daniel Jasper5c235c02015-07-06 14:26:04 +00001332 return;
Daniel Jasper9326f912015-05-05 08:40:32 +00001333 }
1334
Francois Ferrand6f40e212018-10-02 16:37:51 +00001335 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1336 parseStatementMacro();
1337 return;
1338 }
1339
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00001340 // See if the following token should start a new unwrapped line.
Daniel Jasper9326f912015-05-05 08:40:32 +00001341 StringRef Text = FormatTok->TokenText;
Daniel Jasperf7935112012-12-03 18:12:45 +00001342 nextToken();
Owen Pan945890a2019-05-01 15:03:41 +00001343
1344 // JS doesn't have macros, and within classes colons indicate fields, not
1345 // labels.
1346 if (Style.Language == FormatStyle::LK_JavaScript)
1347 break;
1348
1349 TokenCount = Line->Tokens.size();
1350 if (TokenCount == 1 ||
1351 (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) {
Daniel Jasper676e5162015-04-07 14:36:33 +00001352 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
Daniel Jasper40609472016-04-06 15:02:46 +00001353 Line->Tokens.begin()->Tok->MustBreakBefore = true;
Alexander Kornienkode644272013-04-08 22:16:06 +00001354 parseLabel();
1355 return;
1356 }
Daniel Jasper680b09b2014-11-05 10:48:04 +00001357 // Recognize function-like macro usages without trailing semicolon as
Daniel Jasper83709082015-02-18 17:14:05 +00001358 // well as free-standing macros like Q_OBJECT.
Daniel Jasper680b09b2014-11-05 10:48:04 +00001359 bool FunctionLike = FormatTok->is(tok::l_paren);
1360 if (FunctionLike)
Alexander Kornienkode644272013-04-08 22:16:06 +00001361 parseParens();
Daniel Jaspere60cba12015-05-13 11:35:53 +00001362
1363 bool FollowedByNewline =
1364 CommentsBeforeNextToken.empty()
1365 ? FormatTok->NewlinesBefore > 0
1366 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1367
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001368 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
Daniel Jasper680b09b2014-11-05 10:48:04 +00001369 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
Daniel Jasper40e19212013-05-29 13:16:10 +00001370 addUnwrappedLine();
Daniel Jasper41a0f782013-05-29 14:09:17 +00001371 return;
Alexander Kornienkode644272013-04-08 22:16:06 +00001372 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001373 }
1374 break;
Daniel Jasper40e19212013-05-29 13:16:10 +00001375 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001376 case tok::equal:
Manuel Klimek79e06082015-05-21 12:23:34 +00001377 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1378 // TT_JsFatArrow. The always start an expression or a child block if
1379 // followed by a curly.
1380 if (FormatTok->is(TT_JsFatArrow)) {
1381 nextToken();
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001382 if (FormatTok->is(tok::l_brace))
Manuel Klimek79e06082015-05-21 12:23:34 +00001383 parseChildBlock();
Manuel Klimek79e06082015-05-21 12:23:34 +00001384 break;
1385 }
1386
Daniel Jaspere25509f2012-12-17 11:29:41 +00001387 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001388 if (FormatTok->Tok.is(tok::l_brace)) {
1389 nextToken();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001390 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001391 } else if (Style.Language == FormatStyle::LK_Proto &&
Manuel Klimek89628f62017-09-20 09:51:03 +00001392 FormatTok->Tok.is(tok::less)) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001393 nextToken();
Krasimir Georgiev0b41fcb2017-06-27 13:58:41 +00001394 parseBracedList(/*ContinueOnSemicolons=*/false,
1395 /*ClosingBraceKind=*/tok::greater);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001396 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001397 break;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001398 case tok::l_square:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001399 parseSquare();
Manuel Klimekffdeb592013-09-03 15:10:01 +00001400 break;
Daniel Jasper6acf5132015-03-12 14:44:29 +00001401 case tok::kw_new:
1402 parseNew();
1403 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001404 default:
1405 nextToken();
1406 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001407 }
1408 } while (!eof());
1409}
1410
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001411bool UnwrappedLineParser::tryToParseLambda() {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001412 if (!Style.isCpp()) {
Daniel Jasper1feab0f2015-06-02 15:31:37 +00001413 nextToken();
1414 return false;
1415 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001416 assert(FormatTok->is(tok::l_square));
1417 FormatToken &LSquare = *FormatTok;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001418 if (!tryToParseLambdaIntroducer())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001419 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001420
Krasimir Georgievc416c522019-03-11 16:02:52 +00001421 bool SeenArrow = false;
1422
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00001423 while (FormatTok->isNot(tok::l_brace)) {
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001424 if (FormatTok->isSimpleTypeSpecifier()) {
1425 nextToken();
1426 continue;
1427 }
Manuel Klimekffdeb592013-09-03 15:10:01 +00001428 switch (FormatTok->Tok.getKind()) {
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001429 case tok::l_brace:
1430 break;
1431 case tok::l_paren:
1432 parseParens();
1433 break;
Daniel Jasperbcb55ee2014-11-21 14:08:38 +00001434 case tok::amp:
1435 case tok::star:
1436 case tok::kw_const:
Daniel Jasper3431b752014-12-08 13:22:37 +00001437 case tok::comma:
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001438 case tok::less:
1439 case tok::greater:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001440 case tok::identifier:
Daniel Jasper5eaa0092015-08-13 13:37:08 +00001441 case tok::numeric_constant:
Daniel Jasper1067ab02014-02-11 10:16:55 +00001442 case tok::coloncolon:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001443 case tok::kw_mutable:
Ben Hamilton4e442bb2019-01-30 13:54:32 +00001444 case tok::kw_noexcept:
Krasimir Georgievc416c522019-03-11 16:02:52 +00001445 nextToken();
1446 break;
Jan Korous88e15142019-03-05 19:27:24 +00001447 // Specialization of a template with an integer parameter can contain
1448 // arithmetic, logical, comparison and ternary operators.
Krasimir Georgievc416c522019-03-11 16:02:52 +00001449 //
1450 // FIXME: This also accepts sequences of operators that are not in the scope
1451 // of a template argument list.
1452 //
1453 // In a C++ lambda a template type can only occur after an arrow. We use
1454 // this as an heuristic to distinguish between Objective-C expressions
1455 // followed by an `a->b` expression, such as:
1456 // ([obj func:arg] + a->b)
1457 // Otherwise the code below would parse as a lambda.
Jan Korous88e15142019-03-05 19:27:24 +00001458 case tok::plus:
1459 case tok::minus:
1460 case tok::exclaim:
1461 case tok::tilde:
1462 case tok::slash:
1463 case tok::percent:
1464 case tok::lessless:
1465 case tok::pipe:
1466 case tok::pipepipe:
1467 case tok::ampamp:
1468 case tok::caret:
1469 case tok::equalequal:
1470 case tok::exclaimequal:
1471 case tok::greaterequal:
1472 case tok::lessequal:
1473 case tok::question:
1474 case tok::colon:
Paul Hoad10de3952019-03-05 22:20:25 +00001475 case tok::kw_true:
1476 case tok::kw_false:
Krasimir Georgievc416c522019-03-11 16:02:52 +00001477 if (SeenArrow) {
1478 nextToken();
1479 break;
1480 }
1481 return true;
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001482 case tok::arrow:
Ben Hamilton30b7d092019-02-08 15:55:18 +00001483 // This might or might not actually be a lambda arrow (this could be an
1484 // ObjC method invocation followed by a dereferencing arrow). We might
1485 // reset this back to TT_Unknown in TokenAnnotator.
Daniel Jasper6f2b88a2015-06-05 13:18:09 +00001486 FormatTok->Type = TT_LambdaArrow;
Krasimir Georgievc416c522019-03-11 16:02:52 +00001487 SeenArrow = true;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001488 nextToken();
1489 break;
1490 default:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001491 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001492 }
1493 }
Ronald Wamplera83e2db2019-03-26 20:18:14 +00001494 FormatTok->Type = TT_LambdaLBrace;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001495 LSquare.Type = TT_LambdaLSquare;
Manuel Klimek516e0542013-09-04 13:25:30 +00001496 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001497 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001498}
1499
1500bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
Manuel Klimek89628f62017-09-20 09:51:03 +00001501 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001502 if (Previous &&
1503 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
Manuel Klimekd0f3fe52018-04-11 14:51:54 +00001504 tok::kw_delete, tok::l_square) ||
Manuel Klimek89628f62017-09-20 09:51:03 +00001505 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1506 Previous->isSimpleTypeSpecifier())) {
Manuel Klimekffdeb592013-09-03 15:10:01 +00001507 nextToken();
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001508 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001509 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001510 nextToken();
Manuel Klimekd0f3fe52018-04-11 14:51:54 +00001511 if (FormatTok->is(tok::l_square)) {
1512 return false;
1513 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001514 parseSquare(/*LambdaIntroducer=*/true);
1515 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001516}
1517
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001518void UnwrappedLineParser::tryToParseJSFunction() {
Martin Probst409697e2016-05-29 14:41:07 +00001519 assert(FormatTok->is(Keywords.kw_function) ||
1520 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
Martin Probst5f8445b2016-04-24 22:05:09 +00001521 if (FormatTok->is(Keywords.kw_async))
1522 nextToken();
1523 // Consume "function".
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001524 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001525
Daniel Jasper71e50af2016-11-01 06:22:59 +00001526 // Consume * (generator function). Treat it like C++'s overloaded operators.
1527 if (FormatTok->is(tok::star)) {
1528 FormatTok->Type = TT_OverloadedOperator;
Martin Probst5f8445b2016-04-24 22:05:09 +00001529 nextToken();
Daniel Jasper71e50af2016-11-01 06:22:59 +00001530 }
Martin Probst5f8445b2016-04-24 22:05:09 +00001531
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001532 // Consume function name.
1533 if (FormatTok->is(tok::identifier))
Daniel Jasperfca735c2015-02-19 16:14:18 +00001534 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001535
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001536 if (FormatTok->isNot(tok::l_paren))
1537 return;
Manuel Klimek79e06082015-05-21 12:23:34 +00001538
1539 // Parse formal parameter list.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001540 parseParens();
Manuel Klimek79e06082015-05-21 12:23:34 +00001541
1542 if (FormatTok->is(tok::colon)) {
1543 // Parse a type definition.
1544 nextToken();
1545
1546 // Eat the type declaration. For braced inline object types, balance braces,
1547 // otherwise just parse until finding an l_brace for the function body.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001548 if (FormatTok->is(tok::l_brace))
1549 tryToParseBracedList();
1550 else
Martin Probstaf16c502017-01-04 13:36:43 +00001551 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
Manuel Klimek79e06082015-05-21 12:23:34 +00001552 nextToken();
Manuel Klimek79e06082015-05-21 12:23:34 +00001553 }
1554
Martin Probstaf16c502017-01-04 13:36:43 +00001555 if (FormatTok->is(tok::semi))
1556 return;
1557
Manuel Klimek79e06082015-05-21 12:23:34 +00001558 parseChildBlock();
1559}
1560
Daniel Jasper3c883d12015-05-18 14:49:19 +00001561bool UnwrappedLineParser::tryToParseBracedList() {
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001562 if (FormatTok->BlockKind == BK_Unknown)
Daniel Jasper3c883d12015-05-18 14:49:19 +00001563 calculateBraceTypes();
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001564 assert(FormatTok->BlockKind != BK_Unknown);
1565 if (FormatTok->BlockKind == BK_Block)
Manuel Klimekab419912013-05-23 09:41:43 +00001566 return false;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001567 nextToken();
Manuel Klimekab419912013-05-23 09:41:43 +00001568 parseBracedList();
1569 return true;
1570}
1571
Krasimir Georgievff747be2017-06-27 13:43:07 +00001572bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1573 tok::TokenKind ClosingBraceKind) {
Daniel Jasper015ed022013-09-13 09:20:45 +00001574 bool HasError = false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001575
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001576 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1577 // replace this by using parseAssigmentExpression() inside.
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001578 do {
Manuel Klimek79e06082015-05-21 12:23:34 +00001579 if (Style.Language == FormatStyle::LK_JavaScript) {
Martin Probst409697e2016-05-29 14:41:07 +00001580 if (FormatTok->is(Keywords.kw_function) ||
1581 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001582 tryToParseJSFunction();
1583 continue;
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001584 }
1585 if (FormatTok->is(TT_JsFatArrow)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001586 nextToken();
1587 // Fat arrows can be followed by simple expressions or by child blocks
1588 // in curly braces.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001589 if (FormatTok->is(tok::l_brace)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001590 parseChildBlock();
1591 continue;
1592 }
1593 }
Martin Probst8e3eba02017-02-07 16:33:13 +00001594 if (FormatTok->is(tok::l_brace)) {
1595 // Could be a method inside of a braced list `{a() { return 1; }}`.
1596 if (tryToParseBracedList())
1597 continue;
1598 parseChildBlock();
1599 }
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001600 }
Krasimir Georgievff747be2017-06-27 13:43:07 +00001601 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1602 nextToken();
1603 return !HasError;
1604 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001605 switch (FormatTok->Tok.getKind()) {
Manuel Klimek516e0542013-09-04 13:25:30 +00001606 case tok::caret:
1607 nextToken();
1608 if (FormatTok->is(tok::l_brace)) {
1609 parseChildBlock();
1610 }
1611 break;
1612 case tok::l_square:
1613 tryToParseLambda();
1614 break;
Daniel Jaspera87af7a2015-06-30 11:32:22 +00001615 case tok::l_paren:
1616 parseParens();
Daniel Jasperf46dec82015-03-31 14:34:15 +00001617 // JavaScript can just have free standing methods and getters/setters in
1618 // object literals. Detect them by a "{" following ")".
1619 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf46dec82015-03-31 14:34:15 +00001620 if (FormatTok->is(tok::l_brace))
1621 parseChildBlock();
1622 break;
1623 }
Daniel Jasperf46dec82015-03-31 14:34:15 +00001624 break;
Martin Probst8e3eba02017-02-07 16:33:13 +00001625 case tok::l_brace:
1626 // Assume there are no blocks inside a braced init list apart
1627 // from the ones we explicitly parse out (like lambdas).
1628 FormatTok->BlockKind = BK_BracedInit;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001629 nextToken();
Martin Probst8e3eba02017-02-07 16:33:13 +00001630 parseBracedList();
1631 break;
Krasimir Georgievfa4dbb62017-08-03 13:43:45 +00001632 case tok::less:
1633 if (Style.Language == FormatStyle::LK_Proto) {
1634 nextToken();
1635 parseBracedList(/*ContinueOnSemicolons=*/false,
1636 /*ClosingBraceKind=*/tok::greater);
1637 } else {
1638 nextToken();
1639 }
1640 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001641 case tok::semi:
Daniel Jasperb9a49902016-01-09 15:56:28 +00001642 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1643 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1644 // used for error recovery if we have otherwise determined that this is
1645 // a braced list.
1646 if (Style.Language == FormatStyle::LK_JavaScript) {
1647 nextToken();
1648 break;
1649 }
Daniel Jasper015ed022013-09-13 09:20:45 +00001650 HasError = true;
1651 if (!ContinueOnSemicolons)
1652 return !HasError;
1653 nextToken();
1654 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001655 case tok::comma:
1656 nextToken();
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001657 break;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001658 default:
1659 nextToken();
1660 break;
1661 }
1662 } while (!eof());
Daniel Jasper015ed022013-09-13 09:20:45 +00001663 return false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001664}
1665
Daniel Jasperf7935112012-12-03 18:12:45 +00001666void UnwrappedLineParser::parseParens() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001667 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
Daniel Jasperf7935112012-12-03 18:12:45 +00001668 nextToken();
1669 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001670 switch (FormatTok->Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001671 case tok::l_paren:
1672 parseParens();
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001673 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1674 parseChildBlock();
Daniel Jasperf7935112012-12-03 18:12:45 +00001675 break;
1676 case tok::r_paren:
1677 nextToken();
1678 return;
Daniel Jasper393564f2013-05-31 14:56:29 +00001679 case tok::r_brace:
1680 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1681 return;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001682 case tok::l_square:
1683 tryToParseLambda();
1684 break;
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001685 case tok::l_brace:
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001686 if (!tryToParseBracedList())
Manuel Klimekf017dc02013-09-04 13:34:14 +00001687 parseChildBlock();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001688 break;
Nico Weber372d8dc2013-02-10 20:35:35 +00001689 case tok::at:
1690 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001691 if (FormatTok->Tok.is(tok::l_brace)) {
1692 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001693 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001694 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001695 break;
Martin Probst1027fb82017-02-07 14:05:30 +00001696 case tok::kw_class:
1697 if (Style.Language == FormatStyle::LK_JavaScript)
1698 parseRecord(/*ParseAsExpr=*/true);
1699 else
1700 nextToken();
1701 break;
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001702 case tok::identifier:
1703 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst409697e2016-05-29 14:41:07 +00001704 (FormatTok->is(Keywords.kw_function) ||
1705 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001706 tryToParseJSFunction();
1707 else
1708 nextToken();
1709 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001710 default:
1711 nextToken();
1712 break;
1713 }
1714 } while (!eof());
1715}
1716
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001717void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1718 if (!LambdaIntroducer) {
1719 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1720 if (tryToParseLambda())
1721 return;
1722 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001723 do {
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001724 switch (FormatTok->Tok.getKind()) {
1725 case tok::l_paren:
1726 parseParens();
1727 break;
1728 case tok::r_square:
1729 nextToken();
1730 return;
1731 case tok::r_brace:
1732 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1733 return;
1734 case tok::l_square:
1735 parseSquare();
1736 break;
1737 case tok::l_brace: {
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001738 if (!tryToParseBracedList())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001739 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001740 break;
1741 }
1742 case tok::at:
1743 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001744 if (FormatTok->Tok.is(tok::l_brace)) {
1745 nextToken();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001746 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001747 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001748 break;
1749 default:
1750 nextToken();
1751 break;
1752 }
1753 } while (!eof());
1754}
1755
Daniel Jasperf7935112012-12-03 18:12:45 +00001756void UnwrappedLineParser::parseIfThenElse() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001757 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001758 nextToken();
Nico Weber1361a4c2019-07-27 02:41:40 +00001759 if (FormatTok->Tok.isOneOf(tok::kw_constexpr, tok::identifier))
Daniel Jasper6a7d5a72017-06-19 07:40:49 +00001760 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001761 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimekadededf2013-01-11 18:28:36 +00001762 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +00001763 bool NeedsUnwrappedLine = false;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001764 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001765 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001766 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001767 if (Style.BraceWrapping.BeforeElse)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001768 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001769 else
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001770 NeedsUnwrappedLine = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001771 } else {
1772 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001773 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001774 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001775 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001776 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001777 if (FormatTok->Tok.is(tok::kw_else)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001778 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001779 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001780 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001781 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001782 addUnwrappedLine();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001783 } else if (FormatTok->Tok.is(tok::kw_if)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001784 parseIfThenElse();
1785 } else {
1786 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001787 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001788 parseStructuralElement();
Daniel Jasper451544a2016-05-19 06:30:48 +00001789 if (FormatTok->is(tok::eof))
1790 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001791 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001792 }
1793 } else if (NeedsUnwrappedLine) {
1794 addUnwrappedLine();
1795 }
1796}
1797
Daniel Jasper04a71a42014-05-08 11:58:24 +00001798void UnwrappedLineParser::parseTryCatch() {
Nico Weberfac23712015-02-04 15:26:27 +00001799 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
Daniel Jasper04a71a42014-05-08 11:58:24 +00001800 nextToken();
1801 bool NeedsUnwrappedLine = false;
1802 if (FormatTok->is(tok::colon)) {
1803 // We are in a function try block, what comes is an initializer list.
1804 nextToken();
1805 while (FormatTok->is(tok::identifier)) {
1806 nextToken();
1807 if (FormatTok->is(tok::l_paren))
1808 parseParens();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001809 if (FormatTok->is(tok::comma))
1810 nextToken();
1811 }
1812 }
Daniel Jaspere189d462015-01-14 10:48:41 +00001813 // Parse try with resource.
1814 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1815 parseParens();
1816 }
Daniel Jasper04a71a42014-05-08 11:58:24 +00001817 if (FormatTok->is(tok::l_brace)) {
1818 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1819 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001820 if (Style.BraceWrapping.BeforeCatch) {
Daniel Jasper04a71a42014-05-08 11:58:24 +00001821 addUnwrappedLine();
1822 } else {
1823 NeedsUnwrappedLine = true;
1824 }
1825 } else if (!FormatTok->is(tok::kw_catch)) {
1826 // The C++ standard requires a compound-statement after a try.
1827 // If there's none, we try to assume there's a structuralElement
1828 // and try to continue.
Daniel Jasper04a71a42014-05-08 11:58:24 +00001829 addUnwrappedLine();
1830 ++Line->Level;
1831 parseStructuralElement();
1832 --Line->Level;
1833 }
Nico Weber33381f52015-02-07 01:57:32 +00001834 while (1) {
1835 if (FormatTok->is(tok::at))
1836 nextToken();
1837 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1838 tok::kw___finally) ||
1839 ((Style.Language == FormatStyle::LK_Java ||
1840 Style.Language == FormatStyle::LK_JavaScript) &&
1841 FormatTok->is(Keywords.kw_finally)) ||
1842 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1843 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1844 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001845 nextToken();
1846 while (FormatTok->isNot(tok::l_brace)) {
1847 if (FormatTok->is(tok::l_paren)) {
1848 parseParens();
1849 continue;
1850 }
Daniel Jasper2bd7a642015-01-19 10:50:51 +00001851 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
Daniel Jasper04a71a42014-05-08 11:58:24 +00001852 return;
1853 nextToken();
1854 }
1855 NeedsUnwrappedLine = false;
1856 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1857 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001858 if (Style.BraceWrapping.BeforeCatch)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001859 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001860 else
Daniel Jasper04a71a42014-05-08 11:58:24 +00001861 NeedsUnwrappedLine = true;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001862 }
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001863 if (NeedsUnwrappedLine)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001864 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001865}
1866
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001867void UnwrappedLineParser::parseNamespace() {
Francois Ferrande8a301f2019-06-06 20:06:23 +00001868 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
1869 "'namespace' expected");
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001870
1871 const FormatToken &InitialToken = *FormatTok;
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001872 nextToken();
Francois Ferrande8a301f2019-06-06 20:06:23 +00001873 if (InitialToken.is(TT_NamespaceMacro)) {
1874 parseParens();
1875 } else {
Nico Weber37944132019-07-23 17:49:45 +00001876 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
1877 tok::l_square)) {
1878 if (FormatTok->is(tok::l_square))
1879 parseSquare();
1880 else
1881 nextToken();
1882 }
Francois Ferrande8a301f2019-06-06 20:06:23 +00001883 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001884 if (FormatTok->Tok.is(tok::l_brace)) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001885 if (ShouldBreakBeforeBrace(Style, InitialToken))
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001886 addUnwrappedLine();
1887
Daniel Jasper65ee3472013-07-31 23:16:02 +00001888 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1889 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1890 DeclarationScopeStack.size() > 1);
1891 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
Manuel Klimek046b9302013-02-06 16:08:09 +00001892 // Munch the semicolon after a namespace. This is more common than one would
1893 // think. Puttin the semicolon into its own line is very ugly.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001894 if (FormatTok->Tok.is(tok::semi))
Manuel Klimek046b9302013-02-06 16:08:09 +00001895 nextToken();
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001896 addUnwrappedLine();
1897 }
1898 // FIXME: Add error handling.
1899}
1900
Daniel Jasper6acf5132015-03-12 14:44:29 +00001901void UnwrappedLineParser::parseNew() {
1902 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1903 nextToken();
1904 if (Style.Language != FormatStyle::LK_Java)
1905 return;
1906
1907 // In Java, we can parse everything up to the parens, which aren't optional.
1908 do {
1909 // There should not be a ;, { or } before the new's open paren.
1910 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1911 return;
1912
1913 // Consume the parens.
1914 if (FormatTok->is(tok::l_paren)) {
1915 parseParens();
1916
1917 // If there is a class body of an anonymous class, consume that as child.
1918 if (FormatTok->is(tok::l_brace))
1919 parseChildBlock();
1920 return;
1921 }
1922 nextToken();
1923 } while (!eof());
1924}
1925
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001926void UnwrappedLineParser::parseForOrWhileLoop() {
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001927 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
Daniel Jaspere1e43192014-04-01 12:55:11 +00001928 "'for', 'while' or foreach macro expected");
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001929 nextToken();
Martin Probsta050f412017-05-18 21:19:29 +00001930 // JS' for await ( ...
Martin Probstbd49e322017-05-15 19:33:20 +00001931 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probsta050f412017-05-18 21:19:29 +00001932 FormatTok->is(Keywords.kw_await))
Martin Probstbd49e322017-05-15 19:33:20 +00001933 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001934 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001935 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001936 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001937 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001938 parseBlock(/*MustBeDeclaration=*/false);
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001939 addUnwrappedLine();
1940 } else {
1941 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001942 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001943 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001944 --Line->Level;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001945 }
1946}
1947
Daniel Jasperf7935112012-12-03 18:12:45 +00001948void UnwrappedLineParser::parseDoWhile() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001949 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001950 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001951 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001952 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001953 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001954 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001955 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001956 } else {
1957 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001958 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001959 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001960 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001961 }
1962
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001963 // FIXME: Add error handling.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001964 if (!FormatTok->Tok.is(tok::kw_while)) {
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001965 addUnwrappedLine();
1966 return;
1967 }
1968
Daniel Jasperf7935112012-12-03 18:12:45 +00001969 nextToken();
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001970 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +00001971}
1972
1973void UnwrappedLineParser::parseLabel() {
Daniel Jasperf7935112012-12-03 18:12:45 +00001974 nextToken();
Manuel Klimek52b15152013-01-09 15:25:02 +00001975 unsigned OldLineLevel = Line->Level;
Daniel Jaspera1275122013-03-20 10:23:53 +00001976 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
Manuel Klimek52b15152013-01-09 15:25:02 +00001977 --Line->Level;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001978 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
Owen Pan806d5742019-04-08 23:36:25 +00001979 CompoundStatementIndenter Indenter(this, Line->Level,
1980 Style.BraceWrapping.AfterCaseLabel,
1981 Style.BraceWrapping.IndentBraces);
Nico Weber9096fc02013-06-26 00:30:14 +00001982 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001983 if (FormatTok->Tok.is(tok::kw_break)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001984 if (Style.BraceWrapping.AfterControlStatement)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001985 addUnwrappedLine();
1986 parseStructuralElement();
1987 }
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001988 addUnwrappedLine();
1989 } else {
Daniel Jasper1fe0d5c2015-05-06 15:19:47 +00001990 if (FormatTok->is(tok::semi))
1991 nextToken();
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001992 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001993 }
Manuel Klimek52b15152013-01-09 15:25:02 +00001994 Line->Level = OldLineLevel;
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001995 if (FormatTok->isNot(tok::l_brace)) {
Daniel Jasper40609472016-04-06 15:02:46 +00001996 parseStructuralElement();
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001997 addUnwrappedLine();
1998 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001999}
2000
2001void UnwrappedLineParser::parseCaseLabel() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002002 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00002003 // FIXME: fix handling of complex expressions here.
2004 do {
2005 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002006 } while (!eof() && !FormatTok->Tok.is(tok::colon));
Daniel Jasperf7935112012-12-03 18:12:45 +00002007 parseLabel();
2008}
2009
2010void UnwrappedLineParser::parseSwitch() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002011 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00002012 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002013 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00002014 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002015 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00002016 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Daniel Jasper65ee3472013-07-31 23:16:02 +00002017 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00002018 addUnwrappedLine();
2019 } else {
2020 addUnwrappedLine();
Daniel Jasper516d7972013-07-25 11:31:57 +00002021 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00002022 parseStructuralElement();
Daniel Jasper516d7972013-07-25 11:31:57 +00002023 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00002024 }
2025}
2026
2027void UnwrappedLineParser::parseAccessSpecifier() {
2028 nextToken();
Daniel Jasper84c47a12013-11-23 17:53:41 +00002029 // Understand Qt's slots.
Daniel Jasper53395402015-04-07 15:04:40 +00002030 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
Daniel Jasper84c47a12013-11-23 17:53:41 +00002031 nextToken();
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00002032 // Otherwise, we don't know what it is, and we'd better keep the next token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002033 if (FormatTok->Tok.is(tok::colon))
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00002034 nextToken();
Daniel Jasperf7935112012-12-03 18:12:45 +00002035 addUnwrappedLine();
2036}
2037
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002038bool UnwrappedLineParser::parseEnum() {
Daniel Jasper6be0f552014-11-13 15:56:28 +00002039 // Won't be 'enum' for NS_ENUMs.
2040 if (FormatTok->Tok.is(tok::kw_enum))
Daniel Jasperccb68b42014-11-19 22:38:18 +00002041 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002042
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002043 // In TypeScript, "enum" can also be used as property name, e.g. in interface
2044 // declarations. An "enum" keyword followed by a colon would be a syntax
2045 // error and thus assume it is just an identifier.
Daniel Jasper87379302016-02-03 05:33:44 +00002046 if (Style.Language == FormatStyle::LK_JavaScript &&
2047 FormatTok->isOneOf(tok::colon, tok::question))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002048 return false;
2049
Paul Hoada87ba1c2019-03-23 14:24:30 +00002050 // In protobuf, "enum" can be used as a field name.
2051 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
2052 return false;
2053
Daniel Jasper2b41a822013-08-20 12:42:50 +00002054 // Eat up enum class ...
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002055 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
2056 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002057
Daniel Jasper786a5502013-09-06 21:32:35 +00002058 while (FormatTok->Tok.getIdentifierInfo() ||
Daniel Jasperccb68b42014-11-19 22:38:18 +00002059 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
2060 tok::greater, tok::comma, tok::question)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00002061 nextToken();
2062 // We can have macros or attributes in between 'enum' and the enum name.
Daniel Jasperccb68b42014-11-19 22:38:18 +00002063 if (FormatTok->is(tok::l_paren))
Alexander Kornienkob7076a22012-12-04 14:46:19 +00002064 parseParens();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002065 if (FormatTok->is(tok::identifier)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00002066 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002067 // If there are two identifiers in a row, this is likely an elaborate
2068 // return type. In Java, this can be "implements", etc.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002069 if (Style.isCpp() && FormatTok->is(tok::identifier))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002070 return false;
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002071 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00002072 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00002073
2074 // Just a declaration or something is wrong.
Daniel Jasperccb68b42014-11-19 22:38:18 +00002075 if (FormatTok->isNot(tok::l_brace))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002076 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00002077 FormatTok->BlockKind = BK_Block;
2078
2079 if (Style.Language == FormatStyle::LK_Java) {
2080 // Java enums are different.
2081 parseJavaEnumBody();
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002082 return true;
2083 }
2084 if (Style.Language == FormatStyle::LK_Proto) {
Daniel Jasperc6dd2732015-07-16 14:25:43 +00002085 parseBlock(/*MustBeDeclaration=*/true);
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002086 return true;
Manuel Klimek2cec0192013-01-21 19:17:52 +00002087 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00002088
2089 // Parse enum body.
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002090 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002091 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
2092 if (HasError) {
2093 if (FormatTok->is(tok::semi))
2094 nextToken();
2095 addUnwrappedLine();
2096 }
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002097 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00002098
Daniel Jasper90cf3802015-06-17 09:44:02 +00002099 // There is no addUnwrappedLine() here so that we fall through to parsing a
2100 // structural element afterwards. Thus, in "enum A {} n, m;",
Manuel Klimek2cec0192013-01-21 19:17:52 +00002101 // "} n, m;" will end up in one unwrapped line.
Daniel Jasper6be0f552014-11-13 15:56:28 +00002102}
2103
2104void UnwrappedLineParser::parseJavaEnumBody() {
2105 // Determine whether the enum is simple, i.e. does not have a semicolon or
2106 // constants with class bodies. Simple enums can be formatted like braced
2107 // lists, contracted to a single line, etc.
2108 unsigned StoredPosition = Tokens->getPosition();
2109 bool IsSimple = true;
2110 FormatToken *Tok = Tokens->getNextToken();
2111 while (Tok) {
2112 if (Tok->is(tok::r_brace))
2113 break;
2114 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2115 IsSimple = false;
2116 break;
2117 }
2118 // FIXME: This will also mark enums with braces in the arguments to enum
2119 // constants as "not simple". This is probably fine in practice, though.
2120 Tok = Tokens->getNextToken();
2121 }
2122 FormatTok = Tokens->setPosition(StoredPosition);
2123
2124 if (IsSimple) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002125 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002126 parseBracedList();
Daniel Jasperdf2ff002014-11-02 22:31:39 +00002127 addUnwrappedLine();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002128 return;
2129 }
2130
2131 // Parse the body of a more complex enum.
2132 // First add a line for everything up to the "{".
2133 nextToken();
2134 addUnwrappedLine();
2135 ++Line->Level;
2136
2137 // Parse the enum constants.
2138 while (FormatTok) {
2139 if (FormatTok->is(tok::l_brace)) {
2140 // Parse the constant's class body.
2141 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2142 /*MunchSemi=*/false);
2143 } else if (FormatTok->is(tok::l_paren)) {
2144 parseParens();
2145 } else if (FormatTok->is(tok::comma)) {
2146 nextToken();
2147 addUnwrappedLine();
2148 } else if (FormatTok->is(tok::semi)) {
2149 nextToken();
2150 addUnwrappedLine();
2151 break;
2152 } else if (FormatTok->is(tok::r_brace)) {
2153 addUnwrappedLine();
2154 break;
2155 } else {
2156 nextToken();
2157 }
2158 }
2159
2160 // Parse the class body after the enum's ";" if any.
2161 parseLevel(/*HasOpeningBrace=*/true);
2162 nextToken();
2163 --Line->Level;
2164 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00002165}
2166
Martin Probst1027fb82017-02-07 14:05:30 +00002167void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00002168 const FormatToken &InitialToken = *FormatTok;
Manuel Klimek28cacc72013-01-07 18:10:23 +00002169 nextToken();
Daniel Jasper04785d02015-05-06 14:03:02 +00002170
Daniel Jasper04785d02015-05-06 14:03:02 +00002171 // The actual identifier can be a nested name specifier, and in macros
2172 // it is often token-pasted.
2173 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2174 tok::kw___attribute, tok::kw___declspec,
2175 tok::kw_alignas) ||
2176 ((Style.Language == FormatStyle::LK_Java ||
2177 Style.Language == FormatStyle::LK_JavaScript) &&
2178 FormatTok->isOneOf(tok::period, tok::comma))) {
Martin Probstcb870c52017-08-01 15:46:10 +00002179 if (Style.Language == FormatStyle::LK_JavaScript &&
2180 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2181 // JavaScript/TypeScript supports inline object types in
2182 // extends/implements positions:
2183 // class Foo implements {bar: number} { }
2184 nextToken();
2185 if (FormatTok->is(tok::l_brace)) {
2186 tryToParseBracedList();
2187 continue;
2188 }
2189 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002190 bool IsNonMacroIdentifier =
2191 FormatTok->is(tok::identifier) &&
2192 FormatTok->TokenText != FormatTok->TokenText.upper();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002193 nextToken();
2194 // We can have macros or attributes in between 'class' and the class name.
Daniel Jasper04785d02015-05-06 14:03:02 +00002195 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
Manuel Klimeke01bab52013-01-15 13:38:33 +00002196 parseParens();
Daniel Jasper04785d02015-05-06 14:03:02 +00002197 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00002198
Daniel Jasper04785d02015-05-06 14:03:02 +00002199 // Note that parsing away template declarations here leads to incorrectly
2200 // accepting function declarations as record declarations.
2201 // In general, we cannot solve this problem. Consider:
2202 // class A<int> B() {}
2203 // which can be a function definition or a class definition when B() is a
2204 // macro. If we find enough real-world cases where this is a problem, we
2205 // can parse for the 'template' keyword in the beginning of the statement,
2206 // and thus rule out the record production in case there is no template
2207 // (this would still leave us with an ambiguity between template function
2208 // and class declarations).
Daniel Jasperadba2aa2015-05-18 12:52:00 +00002209 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2210 while (!eof()) {
Daniel Jasper3c883d12015-05-18 14:49:19 +00002211 if (FormatTok->is(tok::l_brace)) {
2212 calculateBraceTypes(/*ExpectClassBody=*/true);
2213 if (!tryToParseBracedList())
2214 break;
2215 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002216 if (FormatTok->Tok.is(tok::semi))
2217 return;
2218 nextToken();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002219 }
2220 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002221 if (FormatTok->Tok.is(tok::l_brace)) {
Martin Probst1027fb82017-02-07 14:05:30 +00002222 if (ParseAsExpr) {
2223 parseChildBlock();
2224 } else {
2225 if (ShouldBreakBeforeBrace(Style, InitialToken))
2226 addUnwrappedLine();
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002227
Martin Probst1027fb82017-02-07 14:05:30 +00002228 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2229 /*MunchSemi=*/false);
2230 }
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002231 }
Daniel Jasper90cf3802015-06-17 09:44:02 +00002232 // There is no addUnwrappedLine() here so that we fall through to parsing a
2233 // structural element afterwards. Thus, in "class A {} n, m;",
2234 // "} n, m;" will end up in one unwrapped line.
Manuel Klimek28cacc72013-01-07 18:10:23 +00002235}
2236
Ben Hamilton707e68f2018-05-30 15:21:38 +00002237void UnwrappedLineParser::parseObjCMethod() {
2238 assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2239 "'(' or identifier expected.");
2240 do {
2241 if (FormatTok->Tok.is(tok::semi)) {
2242 nextToken();
2243 addUnwrappedLine();
2244 return;
2245 } else if (FormatTok->Tok.is(tok::l_brace)) {
Ben Hamilton97034a32018-10-12 19:43:01 +00002246 if (Style.BraceWrapping.AfterFunction)
2247 addUnwrappedLine();
Ben Hamilton707e68f2018-05-30 15:21:38 +00002248 parseBlock(/*MustBeDeclaration=*/false);
2249 addUnwrappedLine();
2250 return;
2251 } else {
2252 nextToken();
2253 }
2254 } while (!eof());
2255}
2256
Nico Weber8696a8d2013-01-09 21:15:03 +00002257void UnwrappedLineParser::parseObjCProtocolList() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002258 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
Ben Hamilton1462e842018-04-05 15:26:25 +00002259 do {
Nico Weber8696a8d2013-01-09 21:15:03 +00002260 nextToken();
Ben Hamilton1462e842018-04-05 15:26:25 +00002261 // Early exit in case someone forgot a close angle.
2262 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2263 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2264 return;
2265 } while (!eof() && FormatTok->Tok.isNot(tok::greater));
Nico Weber8696a8d2013-01-09 21:15:03 +00002266 nextToken(); // Skip '>'.
2267}
2268
2269void UnwrappedLineParser::parseObjCUntilAtEnd() {
2270 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002271 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002272 nextToken();
2273 addUnwrappedLine();
2274 break;
2275 }
Daniel Jaspera15da302013-08-28 08:04:23 +00002276 if (FormatTok->is(tok::l_brace)) {
2277 parseBlock(/*MustBeDeclaration=*/false);
2278 // In ObjC interfaces, nothing should be following the "}".
2279 addUnwrappedLine();
Benjamin Kramere21cb742014-01-08 15:59:42 +00002280 } else if (FormatTok->is(tok::r_brace)) {
2281 // Ignore stray "}". parseStructuralElement doesn't consume them.
2282 nextToken();
2283 addUnwrappedLine();
Ben Hamilton707e68f2018-05-30 15:21:38 +00002284 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2285 nextToken();
2286 parseObjCMethod();
Daniel Jaspera15da302013-08-28 08:04:23 +00002287 } else {
2288 parseStructuralElement();
2289 }
Nico Weber8696a8d2013-01-09 21:15:03 +00002290 } while (!eof());
2291}
2292
Nico Weber2ce0ac52013-01-09 23:25:37 +00002293void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
Nico Weberc068ff72018-01-23 17:10:25 +00002294 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2295 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
Nico Weber7eecf4b2013-01-09 20:25:35 +00002296 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002297 nextToken(); // interface name
Nico Weber7eecf4b2013-01-09 20:25:35 +00002298
Ben Hamilton1462e842018-04-05 15:26:25 +00002299 // @interface can be followed by a lightweight generic
2300 // specialization list, then either a base class or a category.
2301 if (FormatTok->Tok.is(tok::less)) {
2302 // Unlike protocol lists, generic parameterizations support
2303 // nested angles:
2304 //
2305 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
2306 // NSObject <NSCopying, NSSecureCoding>
2307 //
2308 // so we need to count how many open angles we have left.
2309 unsigned NumOpenAngles = 1;
2310 do {
2311 nextToken();
2312 // Early exit in case someone forgot a close angle.
2313 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2314 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2315 break;
2316 if (FormatTok->Tok.is(tok::less))
2317 ++NumOpenAngles;
2318 else if (FormatTok->Tok.is(tok::greater)) {
2319 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
2320 --NumOpenAngles;
2321 }
2322 } while (!eof() && NumOpenAngles != 0);
2323 nextToken(); // Skip '>'.
2324 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002325 if (FormatTok->Tok.is(tok::colon)) {
Nico Weber7eecf4b2013-01-09 20:25:35 +00002326 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002327 nextToken(); // base class name
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002328 } else if (FormatTok->Tok.is(tok::l_paren))
Nico Weber7eecf4b2013-01-09 20:25:35 +00002329 // Skip category, if present.
2330 parseParens();
2331
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002332 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002333 parseObjCProtocolList();
Nico Weber7eecf4b2013-01-09 20:25:35 +00002334
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002335 if (FormatTok->Tok.is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002336 if (Style.BraceWrapping.AfterObjCDeclaration)
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002337 addUnwrappedLine();
Nico Weber9096fc02013-06-26 00:30:14 +00002338 parseBlock(/*MustBeDeclaration=*/true);
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002339 }
Nico Weber7eecf4b2013-01-09 20:25:35 +00002340
2341 // With instance variables, this puts '}' on its own line. Without instance
2342 // variables, this ends the @interface line.
2343 addUnwrappedLine();
2344
Nico Weber8696a8d2013-01-09 21:15:03 +00002345 parseObjCUntilAtEnd();
2346}
Nico Weber7eecf4b2013-01-09 20:25:35 +00002347
Nico Weberc068ff72018-01-23 17:10:25 +00002348// Returns true for the declaration/definition form of @protocol,
2349// false for the expression form.
2350bool UnwrappedLineParser::parseObjCProtocol() {
2351 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
Nico Weber8696a8d2013-01-09 21:15:03 +00002352 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002353
2354 if (FormatTok->is(tok::l_paren))
2355 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2356 return false;
2357
2358 // The definition/declaration form,
2359 // @protocol Foo
2360 // - (int)someMethod;
2361 // @end
2362
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002363 nextToken(); // protocol name
Nico Weber8696a8d2013-01-09 21:15:03 +00002364
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002365 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002366 parseObjCProtocolList();
2367
2368 // Check for protocol declaration.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002369 if (FormatTok->Tok.is(tok::semi)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002370 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002371 addUnwrappedLine();
2372 return true;
Nico Weber8696a8d2013-01-09 21:15:03 +00002373 }
2374
2375 addUnwrappedLine();
2376 parseObjCUntilAtEnd();
Nico Weberc068ff72018-01-23 17:10:25 +00002377 return true;
Nico Weber7eecf4b2013-01-09 20:25:35 +00002378}
2379
Daniel Jasperfca735c2015-02-19 16:14:18 +00002380void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
Martin Probst053f1aa2016-04-19 14:55:37 +00002381 bool IsImport = FormatTok->is(Keywords.kw_import);
2382 assert(IsImport || FormatTok->is(tok::kw_export));
Daniel Jasper354aa512015-02-19 16:07:32 +00002383 nextToken();
Daniel Jasperfca735c2015-02-19 16:14:18 +00002384
Daniel Jasperec05fc72015-05-11 09:14:50 +00002385 // Consume the "default" in "export default class/function".
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002386 if (FormatTok->is(tok::kw_default))
2387 nextToken();
Daniel Jasperec05fc72015-05-11 09:14:50 +00002388
Martin Probst5f8445b2016-04-24 22:05:09 +00002389 // Consume "async function", "function" and "default function", so that these
2390 // get parsed as free-standing JS functions, i.e. do not require a trailing
2391 // semicolon.
2392 if (FormatTok->is(Keywords.kw_async))
2393 nextToken();
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002394 if (FormatTok->is(Keywords.kw_function)) {
2395 nextToken();
2396 return;
2397 }
2398
Martin Probst053f1aa2016-04-19 14:55:37 +00002399 // For imports, `export *`, `export {...}`, consume the rest of the line up
2400 // to the terminating `;`. For everything else, just return and continue
2401 // parsing the structural element, i.e. the declaration or expression for
2402 // `export default`.
2403 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2404 !FormatTok->isStringLiteral())
2405 return;
Daniel Jasperfca735c2015-02-19 16:14:18 +00002406
Martin Probstd40bca42017-01-09 08:56:36 +00002407 while (!eof()) {
2408 if (FormatTok->is(tok::semi))
2409 return;
Krasimir Georgiev112c2e92017-11-09 13:22:03 +00002410 if (Line->Tokens.empty()) {
Martin Probstd40bca42017-01-09 08:56:36 +00002411 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2412 // import statement should terminate.
2413 return;
2414 }
Daniel Jasperefc1a832016-01-07 08:53:35 +00002415 if (FormatTok->is(tok::l_brace)) {
2416 FormatTok->BlockKind = BK_Block;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002417 nextToken();
Daniel Jasperefc1a832016-01-07 08:53:35 +00002418 parseBracedList();
2419 } else {
2420 nextToken();
2421 }
Daniel Jasper354aa512015-02-19 16:07:32 +00002422 }
2423}
2424
Paul Hoad5bcf99b2019-03-01 09:09:54 +00002425void UnwrappedLineParser::parseStatementMacro() {
Francois Ferrand6f40e212018-10-02 16:37:51 +00002426 nextToken();
2427 if (FormatTok->is(tok::l_paren))
2428 parseParens();
2429 if (FormatTok->is(tok::semi))
2430 nextToken();
2431 addUnwrappedLine();
2432}
2433
Daniel Jasper3b203a62013-09-05 16:05:56 +00002434LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2435 StringRef Prefix = "") {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002436 llvm::dbgs() << Prefix << "Line(" << Line.Level
2437 << ", FSC=" << Line.FirstStartColumn << ")"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002438 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2439 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2440 E = Line.Tokens.end();
2441 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002442 llvm::dbgs() << I->Tok->Tok.getName() << "["
Manuel Klimek89628f62017-09-20 09:51:03 +00002443 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2444 << "] ";
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002445 }
2446 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2447 E = Line.Tokens.end();
2448 I != E; ++I) {
2449 const UnwrappedLineNode &Node = *I;
2450 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2451 I = Node.Children.begin(),
2452 E = Node.Children.end();
2453 I != E; ++I) {
2454 printDebugInfo(*I, "\nChild: ");
2455 }
2456 }
2457 llvm::dbgs() << "\n";
2458}
2459
Daniel Jasperf7935112012-12-03 18:12:45 +00002460void UnwrappedLineParser::addUnwrappedLine() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002461 if (Line->Tokens.empty())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00002462 return;
Nicola Zaghen3538b392018-05-15 13:30:56 +00002463 LLVM_DEBUG({
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002464 if (CurrentLines == &Lines)
2465 printDebugInfo(*Line);
Manuel Klimekab3dc002013-01-16 12:31:12 +00002466 });
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002467 CurrentLines->push_back(std::move(*Line));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002468 Line->Tokens.clear();
Krasimir Georgiev85c37042017-03-01 16:38:08 +00002469 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002470 Line->FirstStartColumn = 0;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002471 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002472 CurrentLines->append(
2473 std::make_move_iterator(PreprocessorDirectives.begin()),
2474 std::make_move_iterator(PreprocessorDirectives.end()));
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002475 PreprocessorDirectives.clear();
2476 }
Manuel Klimeke411aa82017-09-20 09:29:37 +00002477 // Disconnect the current token from the last token on the previous line.
2478 FormatTok->Previous = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +00002479}
2480
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002481bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
Daniel Jasperf7935112012-12-03 18:12:45 +00002482
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002483bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002484 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2485 FormatTok.NewlinesBefore > 0;
2486}
2487
Krasimir Georgiev91834222017-01-25 13:58:58 +00002488// Checks if \p FormatTok is a line comment that continues the line comment
2489// section on \p Line.
Krasimir Georgievea222a72017-05-22 10:07:56 +00002490static bool continuesLineCommentSection(const FormatToken &FormatTok,
2491 const UnwrappedLine &Line,
2492 llvm::Regex &CommentPragmasRegex) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002493 if (Line.Tokens.empty())
2494 return false;
Krasimir Georgiev84321612017-01-30 19:18:55 +00002495
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002496 StringRef IndentContent = FormatTok.TokenText;
2497 if (FormatTok.TokenText.startswith("//") ||
2498 FormatTok.TokenText.startswith("/*"))
2499 IndentContent = FormatTok.TokenText.substr(2);
2500 if (CommentPragmasRegex.match(IndentContent))
2501 return false;
2502
Krasimir Georgiev91834222017-01-25 13:58:58 +00002503 // If Line starts with a line comment, then FormatTok continues the comment
Krasimir Georgiev84321612017-01-30 19:18:55 +00002504 // section if its original column is greater or equal to the original start
Krasimir Georgiev91834222017-01-25 13:58:58 +00002505 // column of the line.
2506 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002507 // Define the min column token of a line as follows: if a line ends in '{' or
2508 // contains a '{' followed by a line comment, then the min column token is
2509 // that '{'. Otherwise, the min column token of the line is the first token of
2510 // the line.
2511 //
2512 // If Line starts with a token other than a line comment, then FormatTok
2513 // continues the comment section if its original column is greater than the
2514 // original start column of the min column token of the line.
Krasimir Georgiev91834222017-01-25 13:58:58 +00002515 //
2516 // For example, the second line comment continues the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002517 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002518 // // first line
2519 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002520 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002521 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002522 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002523 // // first line
2524 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002525 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002526 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002527 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002528 // int i; // first line
2529 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002530 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002531 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002532 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002533 // do { // first line
2534 // // second line
2535 // int i;
2536 // } while (true);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002537 //
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002538 // and:
2539 //
2540 // enum {
2541 // a, // first line
2542 // // second line
2543 // b
2544 // };
2545 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002546 // The second line comment doesn't continue the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002547 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002548 // // first line
2549 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002550 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002551 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002552 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002553 // int i; // first line
2554 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002555 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002556 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002557 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002558 // do { // first line
2559 // // second line
2560 // int i;
2561 // } while (true);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002562 //
2563 // and:
2564 //
2565 // enum {
2566 // a, // first line
2567 // // second line
2568 // };
Krasimir Georgiev84321612017-01-30 19:18:55 +00002569 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2570
2571 // Scan for '{//'. If found, use the column of '{' as a min column for line
2572 // comment section continuation.
2573 const FormatToken *PreviousToken = nullptr;
Krasimir Georgievd86c25d2017-03-10 13:09:29 +00002574 for (const UnwrappedLineNode &Node : Line.Tokens) {
Krasimir Georgiev84321612017-01-30 19:18:55 +00002575 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2576 isLineComment(*Node.Tok)) {
2577 MinColumnToken = PreviousToken;
2578 break;
2579 }
2580 PreviousToken = Node.Tok;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002581
2582 // Grab the last newline preceding a token in this unwrapped line.
2583 if (Node.Tok->NewlinesBefore > 0) {
2584 MinColumnToken = Node.Tok;
2585 }
Krasimir Georgiev84321612017-01-30 19:18:55 +00002586 }
2587 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2588 MinColumnToken = PreviousToken;
2589 }
2590
Krasimir Georgievea222a72017-05-22 10:07:56 +00002591 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2592 MinColumnToken);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002593}
2594
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002595void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2596 bool JustComments = Line->Tokens.empty();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002597 for (SmallVectorImpl<FormatToken *>::const_iterator
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002598 I = CommentsBeforeNextToken.begin(),
2599 E = CommentsBeforeNextToken.end();
2600 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002601 // Line comments that belong to the same line comment section are put on the
2602 // same line since later we might want to reflow content between them.
Krasimir Georgiev753625b2017-01-31 13:32:38 +00002603 // Additional fine-grained breaking of line comment sections is controlled
2604 // by the class BreakableLineCommentSection in case it is desirable to keep
2605 // several line comment sections in the same unwrapped line.
2606 //
2607 // FIXME: Consider putting separate line comment sections as children to the
2608 // unwrapped line instead.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002609 (*I)->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002610 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002611 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002612 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002613 pushToken(*I);
2614 }
Daniel Jaspere60cba12015-05-13 11:35:53 +00002615 if (NewlineBeforeNext && JustComments)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002616 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002617 CommentsBeforeNextToken.clear();
2618}
2619
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002620void UnwrappedLineParser::nextToken(int LevelDifference) {
Daniel Jasperf7935112012-12-03 18:12:45 +00002621 if (eof())
2622 return;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002623 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002624 pushToken(FormatTok);
Manuel Klimek89628f62017-09-20 09:51:03 +00002625 FormatToken *Previous = FormatTok;
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002626 if (Style.Language != FormatStyle::LK_JavaScript)
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002627 readToken(LevelDifference);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002628 else
2629 readTokenWithJavaScriptASI();
Manuel Klimeke411aa82017-09-20 09:29:37 +00002630 FormatTok->Previous = Previous;
Daniel Jasperb9a49902016-01-09 15:56:28 +00002631}
2632
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002633void UnwrappedLineParser::distributeComments(
2634 const SmallVectorImpl<FormatToken *> &Comments,
2635 const FormatToken *NextTok) {
2636 // Whether or not a line comment token continues a line is controlled by
Krasimir Georgievea222a72017-05-22 10:07:56 +00002637 // the method continuesLineCommentSection, with the following caveat:
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002638 //
2639 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2640 // that each comment line from the trail is aligned with the next token, if
2641 // the next token exists. If a trail exists, the beginning of the maximal
2642 // trail is marked as a start of a new comment section.
2643 //
2644 // For example in this code:
2645 //
2646 // int a; // line about a
2647 // // line 1 about b
2648 // // line 2 about b
2649 // int b;
2650 //
2651 // the two lines about b form a maximal trail, so there are two sections, the
2652 // first one consisting of the single comment "// line about a" and the
2653 // second one consisting of the next two comments.
2654 if (Comments.empty())
2655 return;
2656 bool ShouldPushCommentsInCurrentLine = true;
2657 bool HasTrailAlignedWithNextToken = false;
2658 unsigned StartOfTrailAlignedWithNextToken = 0;
2659 if (NextTok) {
2660 // We are skipping the first element intentionally.
2661 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2662 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2663 HasTrailAlignedWithNextToken = true;
2664 StartOfTrailAlignedWithNextToken = i;
2665 }
2666 }
2667 }
2668 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2669 FormatToken *FormatTok = Comments[i];
Manuel Klimek89628f62017-09-20 09:51:03 +00002670 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002671 FormatTok->ContinuesLineCommentSection = false;
2672 } else {
2673 FormatTok->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002674 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002675 }
2676 if (!FormatTok->ContinuesLineCommentSection &&
2677 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2678 ShouldPushCommentsInCurrentLine = false;
2679 }
2680 if (ShouldPushCommentsInCurrentLine) {
2681 pushToken(FormatTok);
2682 } else {
2683 CommentsBeforeNextToken.push_back(FormatTok);
2684 }
2685 }
2686}
2687
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002688void UnwrappedLineParser::readToken(int LevelDifference) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002689 SmallVector<FormatToken *, 1> Comments;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002690 do {
2691 FormatTok = Tokens->getNextToken();
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00002692 assert(FormatTok);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002693 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2694 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002695 distributeComments(Comments, FormatTok);
2696 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002697 // If there is an unfinished unwrapped line, we flush the preprocessor
2698 // directives only after that unwrapped line was finished later.
Daniel Jasper29d39d52015-02-08 09:34:49 +00002699 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002700 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002701 assert((LevelDifference >= 0 ||
2702 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2703 "LevelDifference makes Line->Level negative");
2704 Line->Level += LevelDifference;
Alexander Kornienkob1be9d62013-04-03 12:38:53 +00002705 // Comments stored before the preprocessor directive need to be output
2706 // before the preprocessor directive, at the same level as the
2707 // preprocessor directive, as we consider them to apply to the directive.
Paul Hoad701a0d72019-03-20 20:49:43 +00002708 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
2709 PPBranchLevel > 0)
2710 Line->Level += PPBranchLevel;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002711 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002712 parsePPDirective();
2713 }
Manuel Klimek68b03042014-04-14 09:14:11 +00002714 while (FormatTok->Type == TT_ConflictStart ||
2715 FormatTok->Type == TT_ConflictEnd ||
2716 FormatTok->Type == TT_ConflictAlternative) {
2717 if (FormatTok->Type == TT_ConflictStart) {
2718 conditionalCompilationStart(/*Unreachable=*/false);
2719 } else if (FormatTok->Type == TT_ConflictAlternative) {
2720 conditionalCompilationAlternative();
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002721 } else if (FormatTok->Type == TT_ConflictEnd) {
Manuel Klimek68b03042014-04-14 09:14:11 +00002722 conditionalCompilationEnd();
2723 }
2724 FormatTok = Tokens->getNextToken();
2725 FormatTok->MustBreakBefore = true;
2726 }
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002727
Francois Ferranda98a95c2017-07-28 07:56:14 +00002728 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002729 !Line->InPPDirective) {
2730 continue;
2731 }
2732
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002733 if (!FormatTok->Tok.is(tok::comment)) {
2734 distributeComments(Comments, FormatTok);
2735 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002736 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002737 }
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002738
2739 Comments.push_back(FormatTok);
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002740 } while (!eof());
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002741
2742 distributeComments(Comments, nullptr);
2743 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002744}
2745
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002746void UnwrappedLineParser::pushToken(FormatToken *Tok) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002747 Line->Tokens.push_back(UnwrappedLineNode(Tok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002748 if (MustBreakBeforeNextToken) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002749 Line->Tokens.back().Tok->MustBreakBefore = true;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002750 MustBreakBeforeNextToken = false;
Manuel Klimek1abf7892013-01-04 23:34:14 +00002751 }
Daniel Jasperf7935112012-12-03 18:12:45 +00002752}
2753
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002754} // end namespace format
2755} // end namespace clang