blob: 010b086587ed92b759d852efe72c32c295d7964d [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)
175 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000176 if (Style.BraceWrapping.AfterControlStatement)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000177 Parser->addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000178 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000179 ++LineLevel;
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000180 }
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000181 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
Alexander Kornienko3a33f022013-12-12 09:49:52 +0000182
183private:
184 unsigned &LineLevel;
185 unsigned OldLineLevel;
186};
187
Craig Topper69665e12013-07-01 04:21:54 +0000188namespace {
189
Manuel Klimekab419912013-05-23 09:41:43 +0000190class IndexedTokenSource : public FormatTokenSource {
191public:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000192 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
Manuel Klimekab419912013-05-23 09:41:43 +0000193 : Tokens(Tokens), Position(-1) {}
194
Craig Topperfb6b25b2014-03-15 04:29:04 +0000195 FormatToken *getNextToken() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000196 ++Position;
197 return Tokens[Position];
198 }
199
Craig Topperfb6b25b2014-03-15 04:29:04 +0000200 unsigned getPosition() override {
Manuel Klimekab419912013-05-23 09:41:43 +0000201 assert(Position >= 0);
202 return Position;
203 }
204
Craig Topperfb6b25b2014-03-15 04:29:04 +0000205 FormatToken *setPosition(unsigned P) override {
Manuel Klimekab419912013-05-23 09:41:43 +0000206 Position = P;
207 return Tokens[Position];
208 }
209
Manuel Klimek71814b42013-10-11 21:25:45 +0000210 void reset() { Position = -1; }
211
Manuel Klimekab419912013-05-23 09:41:43 +0000212private:
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000213 ArrayRef<FormatToken *> Tokens;
Manuel Klimekab419912013-05-23 09:41:43 +0000214 int Position;
215};
216
Craig Topper69665e12013-07-01 04:21:54 +0000217} // end anonymous namespace
218
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000219UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
Daniel Jasperd0ec0d62014-11-04 12:41:02 +0000220 const AdditionalKeywords &Keywords,
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000221 unsigned FirstStartColumn,
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000222 ArrayRef<FormatToken *> Tokens,
Daniel Jasperd2ae41a2013-05-15 08:14:19 +0000223 UnwrappedLineConsumer &Callback)
Daniel Jasperb05a81d2014-05-09 13:11:16 +0000224 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
Krasimir Georgiev00c5c722017-02-02 15:32:19 +0000225 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
226 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
Krasimir Georgievad47c902017-08-30 14:34:57 +0000227 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000228 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
229 ? IG_Rejected
230 : IG_Inited),
231 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
Manuel Klimek71814b42013-10-11 21:25:45 +0000232
233void UnwrappedLineParser::reset() {
234 PPBranchLevel = -1;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000235 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
236 ? IG_Rejected
237 : IG_Inited;
238 IncludeGuardToken = nullptr;
Manuel Klimek71814b42013-10-11 21:25:45 +0000239 Line.reset(new UnwrappedLine);
240 CommentsBeforeNextToken.clear();
Craig Topper2145bc02014-05-09 08:15:10 +0000241 FormatTok = nullptr;
Manuel Klimek71814b42013-10-11 21:25:45 +0000242 MustBreakBeforeNextToken = false;
243 PreprocessorDirectives.clear();
244 CurrentLines = &Lines;
245 DeclarationScopeStack.clear();
Manuel Klimek71814b42013-10-11 21:25:45 +0000246 PPStack.clear();
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000247 Line->FirstStartColumn = FirstStartColumn;
Manuel Klimek71814b42013-10-11 21:25:45 +0000248}
Daniel Jasperf7935112012-12-03 18:12:45 +0000249
Manuel Klimek20e0af62015-05-06 11:56:29 +0000250void UnwrappedLineParser::parse() {
Manuel Klimekab419912013-05-23 09:41:43 +0000251 IndexedTokenSource TokenSource(AllTokens);
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +0000252 Line->FirstStartColumn = FirstStartColumn;
Manuel Klimek71814b42013-10-11 21:25:45 +0000253 do {
Nicola Zaghen3538b392018-05-15 13:30:56 +0000254 LLVM_DEBUG(llvm::dbgs() << "----\n");
Manuel Klimek71814b42013-10-11 21:25:45 +0000255 reset();
256 Tokens = &TokenSource;
257 TokenSource.reset();
Daniel Jaspera79064a2013-03-01 18:11:39 +0000258
Manuel Klimek71814b42013-10-11 21:25:45 +0000259 readToken();
260 parseFile();
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000261
262 // If we found an include guard then all preprocessor directives (other than
263 // the guard) are over-indented by one.
264 if (IncludeGuard == IG_Found)
265 for (auto &Line : Lines)
266 if (Line.InPPDirective && Line.Level > 0)
267 --Line.Level;
268
Manuel Klimek71814b42013-10-11 21:25:45 +0000269 // Create line with eof token.
270 pushToken(FormatTok);
271 addUnwrappedLine();
272
273 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
274 E = Lines.end();
275 I != E; ++I) {
276 Callback.consumeUnwrappedLine(*I);
277 }
278 Callback.finishRun();
279 Lines.clear();
280 while (!PPLevelBranchIndex.empty() &&
Daniel Jasper53bd1672013-10-12 13:32:56 +0000281 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000282 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
283 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
284 }
285 if (!PPLevelBranchIndex.empty()) {
286 ++PPLevelBranchIndex.back();
287 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
288 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
289 }
290 } while (!PPLevelBranchIndex.empty());
Manuel Klimek1abf7892013-01-04 23:34:14 +0000291}
292
Manuel Klimek1a18c402013-04-12 14:13:36 +0000293void UnwrappedLineParser::parseFile() {
Daniel Jasper9326f912015-05-05 08:40:32 +0000294 // The top-level context in a file always has declarations, except for pre-
295 // processor directives and JavaScript files.
296 bool MustBeDeclaration =
297 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
298 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
299 MustBeDeclaration);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +0000300 if (Style.Language == FormatStyle::LK_TextProto)
301 parseBracedList();
302 else
303 parseLevel(/*HasOpeningBrace=*/false);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000304 // Make sure to format the remaining tokens.
Krasimir Georgiev0895f5e2018-06-25 11:08:24 +0000305 //
306 // LK_TextProto is special since its top-level is parsed as the body of a
307 // braced list, which does not necessarily have natural line separators such
308 // as a semicolon. Comments after the last entry that have been determined to
309 // not belong to that line, as in:
310 // key: value
311 // // endfile comment
312 // do not have a chance to be put on a line of their own until this point.
313 // Here we add this newline before end-of-file comments.
314 if (Style.Language == FormatStyle::LK_TextProto &&
315 !CommentsBeforeNextToken.empty())
316 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000317 flushComments(true);
Manuel Klimek1abf7892013-01-04 23:34:14 +0000318 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000319}
320
Manuel Klimek1a18c402013-04-12 14:13:36 +0000321void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000322 bool SwitchLabelEncountered = false;
Daniel Jasperf7935112012-12-03 18:12:45 +0000323 do {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000324 tok::TokenKind kind = FormatTok->Tok.getKind();
325 if (FormatTok->Type == TT_MacroBlockBegin) {
326 kind = tok::l_brace;
327 } else if (FormatTok->Type == TT_MacroBlockEnd) {
328 kind = tok::r_brace;
329 }
330
331 switch (kind) {
Daniel Jasperf7935112012-12-03 18:12:45 +0000332 case tok::comment:
Daniel Jaspere25509f2012-12-17 11:29:41 +0000333 nextToken();
334 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000335 break;
336 case tok::l_brace:
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000337 // FIXME: Add parameter whether this can happen - if this happens, we must
338 // be in a non-declaration context.
Daniel Jasperb86e2722015-08-24 13:23:37 +0000339 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
340 continue;
Nico Weber9096fc02013-06-26 00:30:14 +0000341 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +0000342 addUnwrappedLine();
343 break;
344 case tok::r_brace:
Manuel Klimek1a18c402013-04-12 14:13:36 +0000345 if (HasOpeningBrace)
346 return;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000347 nextToken();
348 addUnwrappedLine();
Manuel Klimek1058d982013-01-06 20:07:31 +0000349 break;
Nico Weberc29f83b2018-01-23 16:30:56 +0000350 case tok::kw_default: {
351 unsigned StoredPosition = Tokens->getPosition();
Jonas Toth90d2aa22018-08-24 17:25:06 +0000352 FormatToken *Next;
353 do {
354 Next = Tokens->getNextToken();
355 } while (Next && Next->is(tok::comment));
Nico Weberc29f83b2018-01-23 16:30:56 +0000356 FormatTok = Tokens->setPosition(StoredPosition);
357 if (Next && Next->isNot(tok::colon)) {
358 // default not followed by ':' is not a case label; treat it like
359 // an identifier.
360 parseStructuralElement();
361 break;
362 }
363 // Else, if it is 'default:', fall through to the case handling.
Nico Weberf1add5e2018-01-24 01:47:22 +0000364 LLVM_FALLTHROUGH;
Nico Weberc29f83b2018-01-23 16:30:56 +0000365 }
Daniel Jasper516d7972013-07-25 11:31:57 +0000366 case tok::kw_case:
Manuel Klimek89628f62017-09-20 09:51:03 +0000367 if (Style.Language == FormatStyle::LK_JavaScript &&
368 Line->MustBeDeclaration) {
Martin Probstf785fd92017-08-04 17:07:15 +0000369 // A 'case: string' style field declaration.
370 parseStructuralElement();
371 break;
372 }
Daniel Jasper72407622013-09-02 08:26:29 +0000373 if (!SwitchLabelEncountered &&
374 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
375 ++Line->Level;
Daniel Jasper516d7972013-07-25 11:31:57 +0000376 SwitchLabelEncountered = true;
377 parseStructuralElement();
378 break;
Daniel Jasperf7935112012-12-03 18:12:45 +0000379 default:
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000380 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +0000381 break;
382 }
383 } while (!eof());
384}
385
Daniel Jasperadba2aa2015-05-18 12:52:00 +0000386void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
Manuel Klimekab419912013-05-23 09:41:43 +0000387 // We'll parse forward through the tokens until we hit
388 // a closing brace or eof - note that getNextToken() will
389 // parse macros, so this will magically work inside macro
390 // definitions, too.
391 unsigned StoredPosition = Tokens->getPosition();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000392 FormatToken *Tok = FormatTok;
Manuel Klimek89628f62017-09-20 09:51:03 +0000393 const FormatToken *PrevTok = Tok->Previous;
Manuel Klimekab419912013-05-23 09:41:43 +0000394 // Keep a stack of positions of lbrace tokens. We will
395 // update information about whether an lbrace starts a
396 // braced init list or a different block during the loop.
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000397 SmallVector<FormatToken *, 8> LBraceStack;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000398 assert(Tok->Tok.is(tok::l_brace));
Manuel Klimekab419912013-05-23 09:41:43 +0000399 do {
Daniel Jaspereb65e912015-12-21 18:31:15 +0000400 // Get next non-comment token.
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000401 FormatToken *NextTok;
Daniel Jasperca7bd722013-07-01 16:43:38 +0000402 unsigned ReadTokens = 0;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000403 do {
404 NextTok = Tokens->getNextToken();
Daniel Jasperca7bd722013-07-01 16:43:38 +0000405 ++ReadTokens;
Daniel Jasper7f5d53e2013-07-01 09:15:46 +0000406 } while (NextTok->is(tok::comment));
407
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000408 switch (Tok->Tok.getKind()) {
Manuel Klimekab419912013-05-23 09:41:43 +0000409 case tok::l_brace:
Martin Probst95ed8e72017-05-31 09:29:40 +0000410 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
Martin Probste8e27ca2017-11-25 09:33:47 +0000411 if (PrevTok->isOneOf(tok::colon, tok::less))
412 // A ':' indicates this code is in a type, or a braced list
413 // following a label in an object literal ({a: {b: 1}}).
414 // A '<' could be an object used in a comparison, but that is nonsense
415 // code (can never return true), so more likely it is a generic type
416 // argument (`X<{a: string; b: number}>`).
417 // The code below could be confused by semicolons between the
418 // individual members in a type member list, which would normally
419 // trigger BK_Block. In both cases, this must be parsed as an inline
420 // braced init.
Martin Probst95ed8e72017-05-31 09:29:40 +0000421 Tok->BlockKind = BK_BracedInit;
422 else if (PrevTok->is(tok::r_paren))
423 // `) { }` can only occur in function or method declarations in JS.
424 Tok->BlockKind = BK_Block;
425 } else {
Daniel Jasperb9a49902016-01-09 15:56:28 +0000426 Tok->BlockKind = BK_Unknown;
Martin Probst95ed8e72017-05-31 09:29:40 +0000427 }
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000428 LBraceStack.push_back(Tok);
Manuel Klimekab419912013-05-23 09:41:43 +0000429 break;
430 case tok::r_brace:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000431 if (LBraceStack.empty())
432 break;
433 if (LBraceStack.back()->BlockKind == BK_Unknown) {
434 bool ProbablyBracedList = false;
435 if (Style.Language == FormatStyle::LK_Proto) {
436 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
437 } else {
438 // Using OriginalColumn to distinguish between ObjC methods and
439 // binary operators is a bit hacky.
440 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
441 NextTok->OriginalColumn == 0;
Daniel Jasper91b032a2014-05-22 12:46:38 +0000442
Daniel Jasperb9a49902016-01-09 15:56:28 +0000443 // If there is a comma, semicolon or right paren after the closing
444 // brace, we assume this is a braced initializer list. Note that
445 // regardless how we mark inner braces here, we will overwrite the
446 // BlockKind later if we parse a braced list (where all blocks
447 // inside are by default braced lists), or when we explicitly detect
448 // blocks (for example while parsing lambdas).
Martin Probst95ed8e72017-05-31 09:29:40 +0000449 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
450 // braced list in JS.
Daniel Jasperb9a49902016-01-09 15:56:28 +0000451 ProbablyBracedList =
Daniel Jasperacffeb82016-03-05 18:34:26 +0000452 (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probste1e12a72016-08-19 14:35:01 +0000453 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
454 Keywords.kw_as)) ||
Martin Probstb7fb2672017-05-10 13:53:29 +0000455 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000456 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
457 tok::r_paren, tok::r_square, tok::l_brace,
Manuel Klimekd0f3fe52018-04-11 14:51:54 +0000458 tok::ellipsis) ||
Daniel Jaspere4ada022016-12-13 10:05:03 +0000459 (NextTok->is(tok::identifier) &&
460 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
Daniel Jasperb9a49902016-01-09 15:56:28 +0000461 (NextTok->is(tok::semi) &&
462 (!ExpectClassBody || LBraceStack.size() != 1)) ||
463 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
Manuel Klimekd0f3fe52018-04-11 14:51:54 +0000464 if (NextTok->is(tok::l_square)) {
465 // We can have an array subscript after a braced init
466 // list, but C++11 attributes are expected after blocks.
467 NextTok = Tokens->getNextToken();
468 ++ReadTokens;
469 ProbablyBracedList = NextTok->isNot(tok::l_square);
470 }
Manuel Klimekab419912013-05-23 09:41:43 +0000471 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000472 if (ProbablyBracedList) {
473 Tok->BlockKind = BK_BracedInit;
474 LBraceStack.back()->BlockKind = BK_BracedInit;
475 } else {
476 Tok->BlockKind = BK_Block;
477 LBraceStack.back()->BlockKind = BK_Block;
478 }
Manuel Klimekab419912013-05-23 09:41:43 +0000479 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000480 LBraceStack.pop_back();
Manuel Klimekab419912013-05-23 09:41:43 +0000481 break;
Francois Ferrand6f40e212018-10-02 16:37:51 +0000482 case tok::identifier:
483 if (!Tok->is(TT_StatementMacro))
Paul Hoad5bcf99b2019-03-01 09:09:54 +0000484 break;
Francois Ferrand6f40e212018-10-02 16:37:51 +0000485 LLVM_FALLTHROUGH;
Daniel Jasperac7e34e2014-03-13 10:11:17 +0000486 case tok::at:
Manuel Klimekab419912013-05-23 09:41:43 +0000487 case tok::semi:
488 case tok::kw_if:
489 case tok::kw_while:
490 case tok::kw_for:
491 case tok::kw_switch:
492 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +0000493 case tok::kw___try:
Daniel Jasperb9a49902016-01-09 15:56:28 +0000494 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000495 LBraceStack.back()->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000496 break;
497 default:
498 break;
499 }
Daniel Jasperb9a49902016-01-09 15:56:28 +0000500 PrevTok = Tok;
Manuel Klimekab419912013-05-23 09:41:43 +0000501 Tok = NextTok;
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000502 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
Daniel Jasperb9a49902016-01-09 15:56:28 +0000503
Manuel Klimekab419912013-05-23 09:41:43 +0000504 // Assume other blocks for all unclosed opening braces.
505 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
Daniel Jasperb1f74a82013-07-09 09:06:29 +0000506 if (LBraceStack[i]->BlockKind == BK_Unknown)
507 LBraceStack[i]->BlockKind = BK_Block;
Manuel Klimekab419912013-05-23 09:41:43 +0000508 }
Manuel Klimekbab25fd2013-09-04 08:20:47 +0000509
Manuel Klimekab419912013-05-23 09:41:43 +0000510 FormatTok = Tokens->setPosition(StoredPosition);
511}
512
Francois Ferranda98a95c2017-07-28 07:56:14 +0000513template <class T>
514static inline void hash_combine(std::size_t &seed, const T &v) {
515 std::hash<T> hasher;
516 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
517}
518
519size_t UnwrappedLineParser::computePPHash() const {
520 size_t h = 0;
521 for (const auto &i : PPStack) {
522 hash_combine(h, size_t(i.Kind));
523 hash_combine(h, i.Line);
524 }
525 return h;
526}
527
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000528void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
529 bool MunchSemi) {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000530 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
531 "'{' or macro block token expected");
532 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
Daniel Jaspereb65e912015-12-21 18:31:15 +0000533 FormatTok->BlockKind = BK_Block;
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000534
Francois Ferranda98a95c2017-07-28 07:56:14 +0000535 size_t PPStartHash = computePPHash();
536
Daniel Jasper516d7972013-07-25 11:31:57 +0000537 unsigned InitialLevel = Line->Level;
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000538 nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
Daniel Jasperf7935112012-12-03 18:12:45 +0000539
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000540 if (MacroBlock && FormatTok->is(tok::l_paren))
541 parseParens();
542
Francois Ferranda98a95c2017-07-28 07:56:14 +0000543 size_t NbPreprocessorDirectives =
544 CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
Manuel Klimeka4fe1c12013-01-21 16:42:44 +0000545 addUnwrappedLine();
Francois Ferranda98a95c2017-07-28 07:56:14 +0000546 size_t OpeningLineIndex =
547 CurrentLines->empty()
548 ? (UnwrappedLine::kInvalidIndex)
549 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
Daniel Jasperf7935112012-12-03 18:12:45 +0000550
Manuel Klimek0a3a3c92013-01-23 09:32:48 +0000551 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
552 MustBeDeclaration);
Daniel Jasper65ee3472013-07-31 23:16:02 +0000553 if (AddLevel)
554 ++Line->Level;
Nico Weber9096fc02013-06-26 00:30:14 +0000555 parseLevel(/*HasOpeningBrace=*/true);
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000556
Marianne Mailhot-Sarrasin03137c62016-04-14 14:56:49 +0000557 if (eof())
558 return;
559
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000560 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
561 : !FormatTok->is(tok::r_brace)) {
Daniel Jasper516d7972013-07-25 11:31:57 +0000562 Line->Level = InitialLevel;
Daniel Jaspereb65e912015-12-21 18:31:15 +0000563 FormatTok->BlockKind = BK_Block;
Manuel Klimek1a18c402013-04-12 14:13:36 +0000564 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +0000565 }
Alexander Kornienko0ea8e102012-12-04 15:40:36 +0000566
Francois Ferranda98a95c2017-07-28 07:56:14 +0000567 size_t PPEndHash = computePPHash();
568
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000569 // Munch the closing brace.
570 nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +0000571
572 if (MacroBlock && FormatTok->is(tok::l_paren))
573 parseParens();
574
Manuel Klimekb212f3b2013-10-12 22:46:56 +0000575 if (MunchSemi && FormatTok->Tok.is(tok::semi))
576 nextToken();
Krasimir Georgiev3e051052017-07-24 14:51:59 +0000577 Line->Level = InitialLevel;
Francois Ferranda98a95c2017-07-28 07:56:14 +0000578
579 if (PPStartHash == PPEndHash) {
580 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
581 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
582 // Update the opening line to add the forward reference as well
Manuel Klimek0dddcf72018-04-23 09:34:26 +0000583 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
Francois Ferranda98a95c2017-07-28 07:56:14 +0000584 CurrentLines->size() - 1;
585 }
Francois Ferrande56a8292017-06-14 12:29:47 +0000586 }
Daniel Jasperf7935112012-12-03 18:12:45 +0000587}
588
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000589static bool isGoogScope(const UnwrappedLine &Line) {
Daniel Jasper616de8642014-11-23 16:46:28 +0000590 // FIXME: Closure-library specific stuff should not be hard-coded but be
591 // configurable.
Daniel Jasper4a39c842014-05-06 13:54:10 +0000592 if (Line.Tokens.size() < 4)
593 return false;
594 auto I = Line.Tokens.begin();
595 if (I->Tok->TokenText != "goog")
596 return false;
597 ++I;
598 if (I->Tok->isNot(tok::period))
599 return false;
600 ++I;
601 if (I->Tok->TokenText != "scope")
602 return false;
603 ++I;
604 return I->Tok->is(tok::l_paren);
605}
606
Martin Probst101ec892017-05-09 20:04:09 +0000607static bool isIIFE(const UnwrappedLine &Line,
608 const AdditionalKeywords &Keywords) {
609 // Look for the start of an immediately invoked anonymous function.
610 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
611 // This is commonly done in JavaScript to create a new, anonymous scope.
612 // Example: (function() { ... })()
613 if (Line.Tokens.size() < 3)
614 return false;
615 auto I = Line.Tokens.begin();
616 if (I->Tok->isNot(tok::l_paren))
617 return false;
618 ++I;
619 if (I->Tok->isNot(Keywords.kw_function))
620 return false;
621 ++I;
622 return I->Tok->is(tok::l_paren);
623}
624
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000625static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
626 const FormatToken &InitialToken) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +0000627 if (InitialToken.is(tok::kw_namespace))
628 return Style.BraceWrapping.AfterNamespace;
629 if (InitialToken.is(tok::kw_class))
630 return Style.BraceWrapping.AfterClass;
631 if (InitialToken.is(tok::kw_union))
632 return Style.BraceWrapping.AfterUnion;
633 if (InitialToken.is(tok::kw_struct))
634 return Style.BraceWrapping.AfterStruct;
635 return false;
Roman Kashitsyna043ced2014-08-11 12:18:01 +0000636}
637
Manuel Klimek516e0542013-09-04 13:25:30 +0000638void UnwrappedLineParser::parseChildBlock() {
639 FormatTok->BlockKind = BK_Block;
640 nextToken();
641 {
Manuel Klimek89628f62017-09-20 09:51:03 +0000642 bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
643 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
Manuel Klimek516e0542013-09-04 13:25:30 +0000644 ScopedLineState LineState(*this);
645 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
646 /*MustBeDeclaration=*/false);
Martin Probst101ec892017-05-09 20:04:09 +0000647 Line->Level += SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000648 parseLevel(/*HasOpeningBrace=*/true);
Daniel Jasper02c7bca2015-03-30 09:56:50 +0000649 flushComments(isOnNewLine(*FormatTok));
Martin Probst101ec892017-05-09 20:04:09 +0000650 Line->Level -= SkipIndent ? 0 : 1;
Manuel Klimek516e0542013-09-04 13:25:30 +0000651 }
652 nextToken();
653}
654
Daniel Jasperf7935112012-12-03 18:12:45 +0000655void UnwrappedLineParser::parsePPDirective() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000656 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
Manuel Klimek20e0af62015-05-06 11:56:29 +0000657 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
Paul Hoad701a0d72019-03-20 20:49:43 +0000658
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000659 nextToken();
660
Craig Topper2145bc02014-05-09 08:15:10 +0000661 if (!FormatTok->Tok.getIdentifierInfo()) {
Manuel Klimek591b5802013-01-31 15:58:48 +0000662 parsePPUnknown();
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000663 return;
Daniel Jasperf7935112012-12-03 18:12:45 +0000664 }
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000665
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000666 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000667 case tok::pp_define:
668 parsePPDefine();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000669 return;
670 case tok::pp_if:
Manuel Klimek71814b42013-10-11 21:25:45 +0000671 parsePPIf(/*IfDef=*/false);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000672 break;
673 case tok::pp_ifdef:
674 case tok::pp_ifndef:
Manuel Klimek71814b42013-10-11 21:25:45 +0000675 parsePPIf(/*IfDef=*/true);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000676 break;
677 case tok::pp_else:
678 parsePPElse();
679 break;
680 case tok::pp_elif:
681 parsePPElIf();
682 break;
683 case tok::pp_endif:
684 parsePPEndIf();
Manuel Klimek1abf7892013-01-04 23:34:14 +0000685 break;
686 default:
687 parsePPUnknown();
688 break;
689 }
690}
691
Manuel Klimek68b03042014-04-14 09:14:11 +0000692void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
Francois Ferranda98a95c2017-07-28 07:56:14 +0000693 size_t Line = CurrentLines->size();
694 if (CurrentLines == &PreprocessorDirectives)
695 Line += Lines.size();
696
697 if (Unreachable ||
698 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
699 PPStack.push_back({PP_Unreachable, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000700 else
Francois Ferranda98a95c2017-07-28 07:56:14 +0000701 PPStack.push_back({PP_Conditional, Line});
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000702}
703
Manuel Klimek68b03042014-04-14 09:14:11 +0000704void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000705 ++PPBranchLevel;
706 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
707 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
708 PPLevelBranchIndex.push_back(0);
709 PPLevelBranchCount.push_back(0);
710 }
711 PPChainBranchIndex.push(0);
Manuel Klimek68b03042014-04-14 09:14:11 +0000712 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
713 conditionalCompilationCondition(Unreachable || Skip);
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000714}
715
Manuel Klimek68b03042014-04-14 09:14:11 +0000716void UnwrappedLineParser::conditionalCompilationAlternative() {
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000717 if (!PPStack.empty())
718 PPStack.pop_back();
Manuel Klimek71814b42013-10-11 21:25:45 +0000719 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
720 if (!PPChainBranchIndex.empty())
721 ++PPChainBranchIndex.top();
Manuel Klimek68b03042014-04-14 09:14:11 +0000722 conditionalCompilationCondition(
723 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
724 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000725}
726
Manuel Klimek68b03042014-04-14 09:14:11 +0000727void UnwrappedLineParser::conditionalCompilationEnd() {
Manuel Klimek71814b42013-10-11 21:25:45 +0000728 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
729 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
730 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
Manuel Klimek71814b42013-10-11 21:25:45 +0000731 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
732 }
733 }
Manuel Klimek14bd9172014-01-29 08:49:02 +0000734 // Guard against #endif's without #if.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000735 if (PPBranchLevel > -1)
Manuel Klimek14bd9172014-01-29 08:49:02 +0000736 --PPBranchLevel;
Manuel Klimek71814b42013-10-11 21:25:45 +0000737 if (!PPChainBranchIndex.empty())
738 PPChainBranchIndex.pop();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000739 if (!PPStack.empty())
740 PPStack.pop_back();
Manuel Klimek68b03042014-04-14 09:14:11 +0000741}
742
743void UnwrappedLineParser::parsePPIf(bool IfDef) {
Daniel Jasper62703eb2017-03-01 11:10:11 +0000744 bool IfNDef = FormatTok->is(tok::pp_ifndef);
Manuel Klimek68b03042014-04-14 09:14:11 +0000745 nextToken();
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000746 bool Unreachable = false;
747 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
748 Unreachable = true;
Daniel Jasper62703eb2017-03-01 11:10:11 +0000749 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
Daniel Jaspereab6cd42017-03-01 10:47:52 +0000750 Unreachable = true;
751 conditionalCompilationStart(Unreachable);
Krasimir Georgievad47c902017-08-30 14:34:57 +0000752 FormatToken *IfCondition = FormatTok;
753 // If there's a #ifndef on the first line, and the only lines before it are
754 // comments, it could be an include guard.
755 bool MaybeIncludeGuard = IfNDef;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000756 if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000757 for (auto &Line : Lines) {
758 if (!Line.Tokens.front().Tok->is(tok::comment)) {
759 MaybeIncludeGuard = false;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000760 IncludeGuard = IG_Rejected;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000761 break;
762 }
763 }
Krasimir Georgievad47c902017-08-30 14:34:57 +0000764 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000765 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000766 ++PPBranchLevel;
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000767 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
768 IncludeGuard = IG_IfNdefed;
769 IncludeGuardToken = IfCondition;
770 }
Manuel Klimek68b03042014-04-14 09:14:11 +0000771}
772
773void UnwrappedLineParser::parsePPElse() {
Krasimir Georgievad47c902017-08-30 14:34:57 +0000774 // If a potential include guard has an #else, it's not an include guard.
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000775 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
776 IncludeGuard = IG_Rejected;
Manuel Klimek68b03042014-04-14 09:14:11 +0000777 conditionalCompilationAlternative();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000778 if (PPBranchLevel > -1)
779 --PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000780 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000781 ++PPBranchLevel;
Manuel Klimek68b03042014-04-14 09:14:11 +0000782}
783
784void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
785
786void UnwrappedLineParser::parsePPEndIf() {
787 conditionalCompilationEnd();
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000788 parsePPUnknown();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000789 // If the #endif of a potential include guard is the last thing in the file,
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000790 // then we found an include guard.
Krasimir Georgievad47c902017-08-30 14:34:57 +0000791 unsigned TokenPosition = Tokens->getPosition();
792 FormatToken *PeekNext = AllTokens[TokenPosition];
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000793 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
794 PeekNext->is(tok::eof) &&
Daniel Jasper4df130f2017-09-04 13:33:52 +0000795 Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000796 IncludeGuard = IG_Found;
Alexander Kornienkof2e02122013-05-24 18:24:24 +0000797}
798
Manuel Klimek1abf7892013-01-04 23:34:14 +0000799void UnwrappedLineParser::parsePPDefine() {
800 nextToken();
801
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000802 if (FormatTok->Tok.getKind() != tok::identifier) {
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000803 IncludeGuard = IG_Rejected;
804 IncludeGuardToken = nullptr;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000805 parsePPUnknown();
806 return;
807 }
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000808
809 if (IncludeGuard == IG_IfNdefed &&
810 IncludeGuardToken->TokenText == FormatTok->TokenText) {
811 IncludeGuard = IG_Defined;
812 IncludeGuardToken = nullptr;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000813 for (auto &Line : Lines) {
814 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000815 IncludeGuard = IG_Rejected;
Krasimir Georgievad47c902017-08-30 14:34:57 +0000816 break;
817 }
818 }
819 }
Mark Zeren1c3afaf2018-02-05 15:59:00 +0000820
Manuel Klimek1abf7892013-01-04 23:34:14 +0000821 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000822 if (FormatTok->Tok.getKind() == tok::l_paren &&
823 FormatTok->WhitespaceRange.getBegin() ==
824 FormatTok->WhitespaceRange.getEnd()) {
Manuel Klimek1abf7892013-01-04 23:34:14 +0000825 parseParens();
826 }
Paul Hoad701a0d72019-03-20 20:49:43 +0000827 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000828 Line->Level += PPBranchLevel + 1;
Manuel Klimek1abf7892013-01-04 23:34:14 +0000829 addUnwrappedLine();
Krasimir Georgievad47c902017-08-30 14:34:57 +0000830 ++Line->Level;
Manuel Klimek1b896292013-01-07 09:34:28 +0000831
832 // Errors during a preprocessor directive can only affect the layout of the
833 // preprocessor directive, and thus we ignore them. An alternative approach
834 // would be to use the same approach we use on the file level (no
835 // re-indentation if there was a structural error) within the macro
836 // definition.
Manuel Klimek1abf7892013-01-04 23:34:14 +0000837 parseFile();
838}
839
840void UnwrappedLineParser::parsePPUnknown() {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000841 do {
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000842 nextToken();
843 } while (!eof());
Paul Hoad701a0d72019-03-20 20:49:43 +0000844 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Krasimir Georgievad47c902017-08-30 14:34:57 +0000845 Line->Level += PPBranchLevel + 1;
Manuel Klimeka71e5d82013-01-02 16:30:12 +0000846 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +0000847}
848
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000849// Here we blacklist certain tokens that are not usually the first token in an
850// unwrapped line. This is used in attempt to distinguish macro calls without
851// trailing semicolons from other constructs split to several lines.
Benjamin Kramer8407df72015-03-09 16:47:52 +0000852static bool tokenCanStartNewLine(const clang::Token &Tok) {
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000853 // Semicolon can be a null-statement, l_square can be a start of a macro or
854 // a C++11 attribute, but this doesn't seem to be common.
855 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
856 Tok.isNot(tok::l_square) &&
857 // Tokens that can only be used as binary operators and a part of
858 // overloaded operator names.
859 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
860 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
861 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
862 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
863 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
864 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
865 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
866 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
867 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
868 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
869 Tok.isNot(tok::lesslessequal) &&
870 // Colon is used in labels, base class lists, initializer lists,
871 // range-based for loops, ternary operator, but should never be the
872 // first token in an unwrapped line.
Daniel Jasper5ebb2f32014-05-21 13:08:17 +0000873 Tok.isNot(tok::colon) &&
874 // 'noexcept' is a trailing annotation.
875 Tok.isNot(tok::kw_noexcept);
Alexander Kornienkoa04e5e22013-04-09 16:15:19 +0000876}
877
Martin Probst533965c2016-04-19 18:19:06 +0000878static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
879 const FormatToken *FormatTok) {
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000880 // FIXME: This returns true for C/C++ keywords like 'struct'.
881 return FormatTok->is(tok::identifier) &&
882 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
Martin Probst3dbbefa2016-11-10 16:21:02 +0000883 !FormatTok->isOneOf(
884 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
885 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
886 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
887 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
888 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
Manuel Klimek89628f62017-09-20 09:51:03 +0000889 Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
890 Keywords.kw_from));
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000891}
892
Martin Probst533965c2016-04-19 18:19:06 +0000893static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
894 const FormatToken *FormatTok) {
Martin Probstb9316ff2016-09-18 17:21:52 +0000895 return FormatTok->Tok.isLiteral() ||
896 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
897 mustBeJSIdent(Keywords, FormatTok);
Martin Probst533965c2016-04-19 18:19:06 +0000898}
899
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000900// isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
901// when encountered after a value (see mustBeJSIdentOrValue).
902static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
903 const FormatToken *FormatTok) {
904 return FormatTok->isOneOf(
Martin Probst5f8445b2016-04-24 22:05:09 +0000905 tok::kw_return, Keywords.kw_yield,
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000906 // conditionals
907 tok::kw_if, tok::kw_else,
908 // loops
909 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
910 // switch/case
911 tok::kw_switch, tok::kw_case,
912 // exceptions
913 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
914 // declaration
915 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
Martin Probst5f8445b2016-04-24 22:05:09 +0000916 Keywords.kw_async, Keywords.kw_function,
917 // import/export
918 Keywords.kw_import, tok::kw_export);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000919}
920
921// readTokenWithJavaScriptASI reads the next token and terminates the current
922// line if JavaScript Automatic Semicolon Insertion must
923// happen between the current token and the next token.
924//
925// This method is conservative - it cannot cover all edge cases of JavaScript,
926// but only aims to correctly handle certain well known cases. It *must not*
927// return true in speculative cases.
928void UnwrappedLineParser::readTokenWithJavaScriptASI() {
929 FormatToken *Previous = FormatTok;
930 readToken();
931 FormatToken *Next = FormatTok;
932
933 bool IsOnSameLine =
934 CommentsBeforeNextToken.empty()
935 ? Next->NewlinesBefore == 0
936 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
937 if (IsOnSameLine)
938 return;
939
940 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
Martin Probst717f6dc2016-10-21 05:11:38 +0000941 bool PreviousStartsTemplateExpr =
942 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
Martin Probst7e0f25b2017-11-25 09:19:42 +0000943 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
944 // If the line contains an '@' sign, the previous token might be an
945 // annotation, which can precede another identifier/value.
946 bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
947 [](UnwrappedLineNode &LineNode) {
948 return LineNode.Tok->is(tok::at);
949 }) != Line->Tokens.end();
950 if (HasAt)
Martin Probstbbffeac2016-04-11 07:35:57 +0000951 return;
952 }
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000953 if (Next->is(tok::exclaim) && PreviousMustBeValue)
Martin Probstd40bca42017-01-09 08:56:36 +0000954 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000955 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
Martin Probst717f6dc2016-10-21 05:11:38 +0000956 bool NextEndsTemplateExpr =
957 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
958 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
959 (PreviousMustBeValue ||
960 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
961 tok::minusminus)))
Martin Probstd40bca42017-01-09 08:56:36 +0000962 return addUnwrappedLine();
Martin Probst0a19d432017-08-09 15:19:16 +0000963 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
964 isJSDeclOrStmt(Keywords, Next))
Martin Probstd40bca42017-01-09 08:56:36 +0000965 return addUnwrappedLine();
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +0000966}
967
Manuel Klimek6b9eeba2013-01-07 14:56:16 +0000968void UnwrappedLineParser::parseStructuralElement() {
Daniel Jasper498f5582015-12-25 08:53:31 +0000969 assert(!FormatTok->is(tok::l_brace));
970 if (Style.Language == FormatStyle::LK_TableGen &&
971 FormatTok->is(tok::pp_include)) {
972 nextToken();
973 if (FormatTok->is(tok::string_literal))
974 nextToken();
975 addUnwrappedLine();
976 return;
977 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +0000978 switch (FormatTok->Tok.getKind()) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000979 case tok::kw_asm:
Daniel Jasper8f463652014-08-26 23:15:12 +0000980 nextToken();
981 if (FormatTok->is(tok::l_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000982 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper2337f282015-01-12 10:14:56 +0000983 nextToken();
Daniel Jasper4429f142014-08-27 17:16:46 +0000984 while (FormatTok && FormatTok->isNot(tok::eof)) {
Daniel Jasper8f463652014-08-26 23:15:12 +0000985 if (FormatTok->is(tok::r_brace)) {
Daniel Jasperc6366072015-05-10 08:42:04 +0000986 FormatTok->Type = TT_InlineASMBrace;
Daniel Jasper8f463652014-08-26 23:15:12 +0000987 nextToken();
Daniel Jasper790d4f92015-05-11 11:59:46 +0000988 addUnwrappedLine();
Daniel Jasper8f463652014-08-26 23:15:12 +0000989 break;
990 }
Daniel Jasper2337f282015-01-12 10:14:56 +0000991 FormatTok->Finalized = true;
Daniel Jasper8f463652014-08-26 23:15:12 +0000992 nextToken();
993 }
994 }
995 break;
Alexander Kornienko578fdd82012-12-06 18:03:27 +0000996 case tok::kw_namespace:
997 parseNamespace();
998 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +0000999 case tok::kw_public:
1000 case tok::kw_protected:
1001 case tok::kw_private:
Daniel Jasper83709082015-02-18 17:14:05 +00001002 if (Style.Language == FormatStyle::LK_Java ||
Paul Hoadcbb726d2019-03-21 13:09:22 +00001003 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
Daniel Jasperc58c70e2014-09-15 11:21:46 +00001004 nextToken();
1005 else
1006 parseAccessSpecifier();
Daniel Jasperf7935112012-12-03 18:12:45 +00001007 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001008 case tok::kw_if:
1009 parseIfThenElse();
Daniel Jasperf7935112012-12-03 18:12:45 +00001010 return;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001011 case tok::kw_for:
1012 case tok::kw_while:
1013 parseForOrWhileLoop();
1014 return;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001015 case tok::kw_do:
1016 parseDoWhile();
1017 return;
1018 case tok::kw_switch:
Martin Probstf785fd92017-08-04 17:07:15 +00001019 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1020 // 'switch: string' field declaration.
1021 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001022 parseSwitch();
1023 return;
1024 case tok::kw_default:
Martin Probstf785fd92017-08-04 17:07:15 +00001025 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1026 // 'default: string' field declaration.
1027 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001028 nextToken();
Nico Weberc29f83b2018-01-23 16:30:56 +00001029 if (FormatTok->is(tok::colon)) {
1030 parseLabel();
1031 return;
1032 }
1033 // e.g. "default void f() {}" in a Java interface.
1034 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001035 case tok::kw_case:
Martin Probstf785fd92017-08-04 17:07:15 +00001036 if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1037 // 'case: string' field declaration.
1038 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001039 parseCaseLabel();
1040 return;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001041 case tok::kw_try:
Nico Weberfac23712015-02-04 15:26:27 +00001042 case tok::kw___try:
Daniel Jasper04a71a42014-05-08 11:58:24 +00001043 parseTryCatch();
1044 return;
Manuel Klimekae610d12013-01-21 14:32:05 +00001045 case tok::kw_extern:
1046 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001047 if (FormatTok->Tok.is(tok::string_literal)) {
Manuel Klimekae610d12013-01-21 14:32:05 +00001048 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001049 if (FormatTok->Tok.is(tok::l_brace)) {
Krasimir Georgievd6ce9372017-09-15 11:23:50 +00001050 if (Style.BraceWrapping.AfterExternBlock) {
1051 addUnwrappedLine();
1052 parseBlock(/*MustBeDeclaration=*/true);
1053 } else {
1054 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1055 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001056 addUnwrappedLine();
1057 return;
1058 }
1059 }
Daniel Jaspere1e43192014-04-01 12:55:11 +00001060 break;
Daniel Jasperfca735c2015-02-19 16:14:18 +00001061 case tok::kw_export:
1062 if (Style.Language == FormatStyle::LK_JavaScript) {
1063 parseJavaScriptEs6ImportExport();
1064 return;
1065 }
Sam McCall6f3778c2018-09-05 07:44:02 +00001066 if (!Style.isCpp())
1067 break;
1068 // Handle C++ "(inline|export) namespace".
1069 LLVM_FALLTHROUGH;
1070 case tok::kw_inline:
1071 nextToken();
1072 if (FormatTok->Tok.is(tok::kw_namespace)) {
1073 parseNamespace();
1074 return;
1075 }
Daniel Jasperfca735c2015-02-19 16:14:18 +00001076 break;
Daniel Jaspere1e43192014-04-01 12:55:11 +00001077 case tok::identifier:
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001078 if (FormatTok->is(TT_ForEachMacro)) {
Daniel Jaspere1e43192014-04-01 12:55:11 +00001079 parseForOrWhileLoop();
1080 return;
1081 }
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001082 if (FormatTok->is(TT_MacroBlockBegin)) {
1083 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1084 /*MunchSemi=*/false);
1085 return;
1086 }
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001087 if (FormatTok->is(Keywords.kw_import)) {
1088 if (Style.Language == FormatStyle::LK_JavaScript) {
1089 parseJavaScriptEs6ImportExport();
1090 return;
1091 }
1092 if (Style.Language == FormatStyle::LK_Proto) {
1093 nextToken();
Daniel Jasper8b61d142016-06-20 20:39:53 +00001094 if (FormatTok->is(tok::kw_public))
1095 nextToken();
Daniel Jasper3d5a7d62016-06-20 18:20:38 +00001096 if (!FormatTok->is(tok::string_literal))
1097 return;
1098 nextToken();
1099 if (FormatTok->is(tok::semi))
1100 nextToken();
1101 addUnwrappedLine();
1102 return;
1103 }
Daniel Jasper354aa512015-02-19 16:07:32 +00001104 }
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001105 if (Style.isCpp() &&
Daniel Jasper72b33572017-03-31 12:04:37 +00001106 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
Daniel Jaspera00de632015-12-01 12:05:04 +00001107 Keywords.kw_slots, Keywords.kw_qslots)) {
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001108 nextToken();
1109 if (FormatTok->is(tok::colon)) {
1110 nextToken();
1111 addUnwrappedLine();
Daniel Jasper31343832016-07-27 10:13:24 +00001112 return;
Daniel Jasperde0d1f32015-04-24 07:50:34 +00001113 }
Daniel Jasper53395402015-04-07 15:04:40 +00001114 }
Francois Ferrand6f40e212018-10-02 16:37:51 +00001115 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1116 parseStatementMacro();
1117 return;
1118 }
Manuel Klimekae610d12013-01-21 14:32:05 +00001119 // In all other cases, parse the declaration.
1120 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001121 default:
1122 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001123 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001124 do {
Manuel Klimeke411aa82017-09-20 09:29:37 +00001125 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001126 switch (FormatTok->Tok.getKind()) {
Nico Weber372d8dc2013-02-10 20:35:35 +00001127 case tok::at:
1128 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001129 if (FormatTok->Tok.is(tok::l_brace)) {
1130 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001131 parseBracedList();
Nico Weberc068ff72018-01-23 17:10:25 +00001132 break;
Hans Wennborg749c1b52018-10-19 16:19:52 +00001133 } else if (Style.Language == FormatStyle::LK_Java &&
1134 FormatTok->is(Keywords.kw_interface)) {
1135 nextToken();
1136 break;
Nico Weberc068ff72018-01-23 17:10:25 +00001137 }
1138 switch (FormatTok->Tok.getObjCKeywordID()) {
1139 case tok::objc_public:
1140 case tok::objc_protected:
1141 case tok::objc_package:
1142 case tok::objc_private:
1143 return parseAccessSpecifier();
1144 case tok::objc_interface:
1145 case tok::objc_implementation:
1146 return parseObjCInterfaceOrImplementation();
1147 case tok::objc_protocol:
1148 if (parseObjCProtocol())
1149 return;
1150 break;
1151 case tok::objc_end:
1152 return; // Handled by the caller.
1153 case tok::objc_optional:
1154 case tok::objc_required:
1155 nextToken();
1156 addUnwrappedLine();
1157 return;
1158 case tok::objc_autoreleasepool:
1159 nextToken();
1160 if (FormatTok->Tok.is(tok::l_brace)) {
Francois Ferranda2484b22018-02-27 13:48:27 +00001161 if (Style.BraceWrapping.AfterControlStatement)
Nico Weberc068ff72018-01-23 17:10:25 +00001162 addUnwrappedLine();
1163 parseBlock(/*MustBeDeclaration=*/false);
1164 }
1165 addUnwrappedLine();
1166 return;
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001167 case tok::objc_synchronized:
1168 nextToken();
1169 if (FormatTok->Tok.is(tok::l_paren))
Paul Hoad5bcf99b2019-03-01 09:09:54 +00001170 // Skip synchronization object
1171 parseParens();
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001172 if (FormatTok->Tok.is(tok::l_brace)) {
Francois Ferranda2484b22018-02-27 13:48:27 +00001173 if (Style.BraceWrapping.AfterControlStatement)
Francois Ferrandba91c3d2018-02-27 13:48:21 +00001174 addUnwrappedLine();
1175 parseBlock(/*MustBeDeclaration=*/false);
1176 }
1177 addUnwrappedLine();
1178 return;
Nico Weberc068ff72018-01-23 17:10:25 +00001179 case tok::objc_try:
1180 // This branch isn't strictly necessary (the kw_try case below would
1181 // do this too after the tok::at is parsed above). But be explicit.
1182 parseTryCatch();
1183 return;
1184 default:
1185 break;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001186 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001187 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001188 case tok::kw_enum:
Daniel Jaspera7900ad2016-05-08 18:12:22 +00001189 // Ignore if this is part of "template <enum ...".
1190 if (Previous && Previous->is(tok::less)) {
1191 nextToken();
1192 break;
1193 }
1194
Daniel Jasper90cf3802015-06-17 09:44:02 +00001195 // parseEnum falls through and does not yet add an unwrapped line as an
1196 // enum definition can start a structural element.
Daniel Jasper6f5a1932015-12-29 08:54:23 +00001197 if (!parseEnum())
1198 break;
Daniel Jasperc6dd2732015-07-16 14:25:43 +00001199 // This only applies for C++.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001200 if (!Style.isCpp()) {
Daniel Jasper90cf3802015-06-17 09:44:02 +00001201 addUnwrappedLine();
1202 return;
1203 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00001204 break;
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001205 case tok::kw_typedef:
1206 nextToken();
Daniel Jasper31f6c542014-12-05 10:42:21 +00001207 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1208 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
Daniel Jaspera88f80a2014-01-30 14:38:37 +00001209 parseEnum();
1210 break;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001211 case tok::kw_struct:
1212 case tok::kw_union:
Manuel Klimek28cacc72013-01-07 18:10:23 +00001213 case tok::kw_class:
Daniel Jasper910807d2015-06-12 04:52:02 +00001214 // parseRecord falls through and does not yet add an unwrapped line as a
1215 // record declaration or definition can start a structural element.
Manuel Klimeke01bab52013-01-15 13:38:33 +00001216 parseRecord();
Paul Hoadcbb726d2019-03-21 13:09:22 +00001217 // This does not apply for Java, JavaScript and C#.
Daniel Jasper910807d2015-06-12 04:52:02 +00001218 if (Style.Language == FormatStyle::LK_Java ||
Paul Hoadcbb726d2019-03-21 13:09:22 +00001219 Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
Daniel Jasperd5ec65b2016-01-08 07:06:07 +00001220 if (FormatTok->is(tok::semi))
1221 nextToken();
Daniel Jasper910807d2015-06-12 04:52:02 +00001222 addUnwrappedLine();
1223 return;
1224 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00001225 break;
Daniel Jaspere5d74862014-11-26 08:17:08 +00001226 case tok::period:
1227 nextToken();
1228 // In Java, classes have an implicit static member "class".
1229 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1230 FormatTok->is(tok::kw_class))
1231 nextToken();
Daniel Jasperba52fcb2015-09-28 14:29:45 +00001232 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1233 FormatTok->Tok.getIdentifierInfo())
1234 // JavaScript only has pseudo keywords, all keywords are allowed to
1235 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1236 nextToken();
Daniel Jaspere5d74862014-11-26 08:17:08 +00001237 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001238 case tok::semi:
1239 nextToken();
1240 addUnwrappedLine();
1241 return;
Alexander Kornienko1231e062013-01-16 11:43:46 +00001242 case tok::r_brace:
1243 addUnwrappedLine();
1244 return;
Daniel Jasperf7935112012-12-03 18:12:45 +00001245 case tok::l_paren:
1246 parseParens();
1247 break;
Daniel Jasper5af04a42015-10-07 03:43:10 +00001248 case tok::kw_operator:
1249 nextToken();
1250 if (FormatTok->isBinaryOperator())
1251 nextToken();
1252 break;
Manuel Klimek516e0542013-09-04 13:25:30 +00001253 case tok::caret:
1254 nextToken();
Daniel Jasper395193c2014-03-28 07:48:59 +00001255 if (FormatTok->Tok.isAnyIdentifier() ||
1256 FormatTok->isSimpleTypeSpecifier())
1257 nextToken();
1258 if (FormatTok->is(tok::l_paren))
1259 parseParens();
1260 if (FormatTok->is(tok::l_brace))
Manuel Klimek516e0542013-09-04 13:25:30 +00001261 parseChildBlock();
Manuel Klimek516e0542013-09-04 13:25:30 +00001262 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001263 case tok::l_brace:
Manuel Klimekab419912013-05-23 09:41:43 +00001264 if (!tryToParseBracedList()) {
1265 // A block outside of parentheses must be the last part of a
1266 // structural element.
1267 // FIXME: Figure out cases where this is not true, and add projections
1268 // for them (the one we know is missing are lambdas).
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001269 if (Style.BraceWrapping.AfterFunction)
Manuel Klimekab419912013-05-23 09:41:43 +00001270 addUnwrappedLine();
Alexander Kornienko3cfa9732013-11-20 16:33:05 +00001271 FormatTok->Type = TT_FunctionLBrace;
Nico Weber9096fc02013-06-26 00:30:14 +00001272 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001273 addUnwrappedLine();
Manuel Klimekab419912013-05-23 09:41:43 +00001274 return;
1275 }
1276 // Otherwise this was a braced init list, and the structural
1277 // element continues.
1278 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001279 case tok::kw_try:
1280 // We arrive here when parsing function-try blocks.
Owen Pancb5ffbe2018-09-28 09:17:00 +00001281 if (Style.BraceWrapping.AfterFunction)
1282 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001283 parseTryCatch();
1284 return;
Daniel Jasper40e19212013-05-29 13:16:10 +00001285 case tok::identifier: {
Birunthan Mohanathasb001a0b2015-07-03 17:25:16 +00001286 if (FormatTok->is(TT_MacroBlockEnd)) {
1287 addUnwrappedLine();
1288 return;
1289 }
1290
Martin Probst973ff792017-04-27 13:07:24 +00001291 // Function declarations (as opposed to function expressions) are parsed
1292 // on their own unwrapped line by continuing this loop. Function
1293 // expressions (functions that are not on their own line) must not create
1294 // a new unwrapped line, so they are special cased below.
1295 size_t TokenCount = Line->Tokens.size();
Daniel Jasper9326f912015-05-05 08:40:32 +00001296 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst973ff792017-04-27 13:07:24 +00001297 FormatTok->is(Keywords.kw_function) &&
1298 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1299 Keywords.kw_async)))) {
Daniel Jasper069e5f42014-05-20 11:14:57 +00001300 tryToParseJSFunction();
1301 break;
1302 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001303 if ((Style.Language == FormatStyle::LK_JavaScript ||
1304 Style.Language == FormatStyle::LK_Java) &&
1305 FormatTok->is(Keywords.kw_interface)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001306 if (Style.Language == FormatStyle::LK_JavaScript) {
1307 // In JavaScript/TypeScript, "interface" can be used as a standalone
1308 // identifier, e.g. in `var interface = 1;`. If "interface" is
1309 // followed by another identifier, it is very like to be an actual
1310 // interface declaration.
1311 unsigned StoredPosition = Tokens->getPosition();
1312 FormatToken *Next = Tokens->getNextToken();
1313 FormatTok = Tokens->setPosition(StoredPosition);
Martin Probst533965c2016-04-19 18:19:06 +00001314 if (Next && !mustBeJSIdent(Keywords, Next)) {
Martin Probst1e8261e2016-04-19 18:18:59 +00001315 nextToken();
1316 break;
1317 }
1318 }
Daniel Jasper9326f912015-05-05 08:40:32 +00001319 parseRecord();
Daniel Jasper259188b2015-06-12 04:56:34 +00001320 addUnwrappedLine();
Daniel Jasper5c235c02015-07-06 14:26:04 +00001321 return;
Daniel Jasper9326f912015-05-05 08:40:32 +00001322 }
1323
Francois Ferrand6f40e212018-10-02 16:37:51 +00001324 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1325 parseStatementMacro();
1326 return;
1327 }
1328
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00001329 // See if the following token should start a new unwrapped line.
Daniel Jasper9326f912015-05-05 08:40:32 +00001330 StringRef Text = FormatTok->TokenText;
Daniel Jasperf7935112012-12-03 18:12:45 +00001331 nextToken();
Daniel Jasper83709082015-02-18 17:14:05 +00001332 if (Line->Tokens.size() == 1 &&
1333 // JS doesn't have macros, and within classes colons indicate fields,
1334 // not labels.
Daniel Jasper676e5162015-04-07 14:36:33 +00001335 Style.Language != FormatStyle::LK_JavaScript) {
1336 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
Daniel Jasper40609472016-04-06 15:02:46 +00001337 Line->Tokens.begin()->Tok->MustBreakBefore = true;
Alexander Kornienkode644272013-04-08 22:16:06 +00001338 parseLabel();
1339 return;
1340 }
Daniel Jasper680b09b2014-11-05 10:48:04 +00001341 // Recognize function-like macro usages without trailing semicolon as
Daniel Jasper83709082015-02-18 17:14:05 +00001342 // well as free-standing macros like Q_OBJECT.
Daniel Jasper680b09b2014-11-05 10:48:04 +00001343 bool FunctionLike = FormatTok->is(tok::l_paren);
1344 if (FunctionLike)
Alexander Kornienkode644272013-04-08 22:16:06 +00001345 parseParens();
Daniel Jaspere60cba12015-05-13 11:35:53 +00001346
1347 bool FollowedByNewline =
1348 CommentsBeforeNextToken.empty()
1349 ? FormatTok->NewlinesBefore > 0
1350 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1351
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001352 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
Daniel Jasper680b09b2014-11-05 10:48:04 +00001353 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
Daniel Jasper40e19212013-05-29 13:16:10 +00001354 addUnwrappedLine();
Daniel Jasper41a0f782013-05-29 14:09:17 +00001355 return;
Alexander Kornienkode644272013-04-08 22:16:06 +00001356 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001357 }
1358 break;
Daniel Jasper40e19212013-05-29 13:16:10 +00001359 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001360 case tok::equal:
Manuel Klimek79e06082015-05-21 12:23:34 +00001361 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1362 // TT_JsFatArrow. The always start an expression or a child block if
1363 // followed by a curly.
1364 if (FormatTok->is(TT_JsFatArrow)) {
1365 nextToken();
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001366 if (FormatTok->is(tok::l_brace))
Manuel Klimek79e06082015-05-21 12:23:34 +00001367 parseChildBlock();
Manuel Klimek79e06082015-05-21 12:23:34 +00001368 break;
1369 }
1370
Daniel Jaspere25509f2012-12-17 11:29:41 +00001371 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001372 if (FormatTok->Tok.is(tok::l_brace)) {
1373 nextToken();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001374 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001375 } else if (Style.Language == FormatStyle::LK_Proto &&
Manuel Klimek89628f62017-09-20 09:51:03 +00001376 FormatTok->Tok.is(tok::less)) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001377 nextToken();
Krasimir Georgiev0b41fcb2017-06-27 13:58:41 +00001378 parseBracedList(/*ContinueOnSemicolons=*/false,
1379 /*ClosingBraceKind=*/tok::greater);
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001380 }
Daniel Jaspere25509f2012-12-17 11:29:41 +00001381 break;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001382 case tok::l_square:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001383 parseSquare();
Manuel Klimekffdeb592013-09-03 15:10:01 +00001384 break;
Daniel Jasper6acf5132015-03-12 14:44:29 +00001385 case tok::kw_new:
1386 parseNew();
1387 break;
Alexander Kornienkob7076a22012-12-04 14:46:19 +00001388 default:
1389 nextToken();
1390 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001391 }
1392 } while (!eof());
1393}
1394
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001395bool UnwrappedLineParser::tryToParseLambda() {
Daniel Jasper1dbc2102017-03-31 13:30:24 +00001396 if (!Style.isCpp()) {
Daniel Jasper1feab0f2015-06-02 15:31:37 +00001397 nextToken();
1398 return false;
1399 }
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001400 assert(FormatTok->is(tok::l_square));
1401 FormatToken &LSquare = *FormatTok;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001402 if (!tryToParseLambdaIntroducer())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001403 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001404
Krasimir Georgievc416c522019-03-11 16:02:52 +00001405 bool SeenArrow = false;
1406
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00001407 while (FormatTok->isNot(tok::l_brace)) {
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001408 if (FormatTok->isSimpleTypeSpecifier()) {
1409 nextToken();
1410 continue;
1411 }
Manuel Klimekffdeb592013-09-03 15:10:01 +00001412 switch (FormatTok->Tok.getKind()) {
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001413 case tok::l_brace:
1414 break;
1415 case tok::l_paren:
1416 parseParens();
1417 break;
Daniel Jasperbcb55ee2014-11-21 14:08:38 +00001418 case tok::amp:
1419 case tok::star:
1420 case tok::kw_const:
Daniel Jasper3431b752014-12-08 13:22:37 +00001421 case tok::comma:
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001422 case tok::less:
1423 case tok::greater:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001424 case tok::identifier:
Daniel Jasper5eaa0092015-08-13 13:37:08 +00001425 case tok::numeric_constant:
Daniel Jasper1067ab02014-02-11 10:16:55 +00001426 case tok::coloncolon:
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001427 case tok::kw_mutable:
Ben Hamilton4e442bb2019-01-30 13:54:32 +00001428 case tok::kw_noexcept:
Krasimir Georgievc416c522019-03-11 16:02:52 +00001429 nextToken();
1430 break;
Jan Korous88e15142019-03-05 19:27:24 +00001431 // Specialization of a template with an integer parameter can contain
1432 // arithmetic, logical, comparison and ternary operators.
Krasimir Georgievc416c522019-03-11 16:02:52 +00001433 //
1434 // FIXME: This also accepts sequences of operators that are not in the scope
1435 // of a template argument list.
1436 //
1437 // In a C++ lambda a template type can only occur after an arrow. We use
1438 // this as an heuristic to distinguish between Objective-C expressions
1439 // followed by an `a->b` expression, such as:
1440 // ([obj func:arg] + a->b)
1441 // Otherwise the code below would parse as a lambda.
Jan Korous88e15142019-03-05 19:27:24 +00001442 case tok::plus:
1443 case tok::minus:
1444 case tok::exclaim:
1445 case tok::tilde:
1446 case tok::slash:
1447 case tok::percent:
1448 case tok::lessless:
1449 case tok::pipe:
1450 case tok::pipepipe:
1451 case tok::ampamp:
1452 case tok::caret:
1453 case tok::equalequal:
1454 case tok::exclaimequal:
1455 case tok::greaterequal:
1456 case tok::lessequal:
1457 case tok::question:
1458 case tok::colon:
Paul Hoad10de3952019-03-05 22:20:25 +00001459 case tok::kw_true:
1460 case tok::kw_false:
Krasimir Georgievc416c522019-03-11 16:02:52 +00001461 if (SeenArrow) {
1462 nextToken();
1463 break;
1464 }
1465 return true;
Daniel Jaspercb51cf42014-01-16 09:11:55 +00001466 case tok::arrow:
Ben Hamilton30b7d092019-02-08 15:55:18 +00001467 // This might or might not actually be a lambda arrow (this could be an
1468 // ObjC method invocation followed by a dereferencing arrow). We might
1469 // reset this back to TT_Unknown in TokenAnnotator.
Daniel Jasper6f2b88a2015-06-05 13:18:09 +00001470 FormatTok->Type = TT_LambdaArrow;
Krasimir Georgievc416c522019-03-11 16:02:52 +00001471 SeenArrow = true;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001472 nextToken();
1473 break;
1474 default:
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001475 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001476 }
1477 }
Ronald Wamplera83e2db2019-03-26 20:18:14 +00001478 FormatTok->Type = TT_LambdaLBrace;
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00001479 LSquare.Type = TT_LambdaLSquare;
Manuel Klimek516e0542013-09-04 13:25:30 +00001480 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001481 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001482}
1483
1484bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
Manuel Klimek89628f62017-09-20 09:51:03 +00001485 const FormatToken *Previous = FormatTok->Previous;
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001486 if (Previous &&
1487 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
Manuel Klimekd0f3fe52018-04-11 14:51:54 +00001488 tok::kw_delete, tok::l_square) ||
Manuel Klimek89628f62017-09-20 09:51:03 +00001489 FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1490 Previous->isSimpleTypeSpecifier())) {
Manuel Klimekffdeb592013-09-03 15:10:01 +00001491 nextToken();
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001492 return false;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001493 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001494 nextToken();
Manuel Klimekd0f3fe52018-04-11 14:51:54 +00001495 if (FormatTok->is(tok::l_square)) {
1496 return false;
1497 }
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001498 parseSquare(/*LambdaIntroducer=*/true);
1499 return true;
Manuel Klimekffdeb592013-09-03 15:10:01 +00001500}
1501
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001502void UnwrappedLineParser::tryToParseJSFunction() {
Martin Probst409697e2016-05-29 14:41:07 +00001503 assert(FormatTok->is(Keywords.kw_function) ||
1504 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
Martin Probst5f8445b2016-04-24 22:05:09 +00001505 if (FormatTok->is(Keywords.kw_async))
1506 nextToken();
1507 // Consume "function".
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001508 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001509
Daniel Jasper71e50af2016-11-01 06:22:59 +00001510 // Consume * (generator function). Treat it like C++'s overloaded operators.
1511 if (FormatTok->is(tok::star)) {
1512 FormatTok->Type = TT_OverloadedOperator;
Martin Probst5f8445b2016-04-24 22:05:09 +00001513 nextToken();
Daniel Jasper71e50af2016-11-01 06:22:59 +00001514 }
Martin Probst5f8445b2016-04-24 22:05:09 +00001515
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001516 // Consume function name.
1517 if (FormatTok->is(tok::identifier))
Daniel Jasperfca735c2015-02-19 16:14:18 +00001518 nextToken();
Daniel Jasper5217a8b2014-06-13 07:02:04 +00001519
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001520 if (FormatTok->isNot(tok::l_paren))
1521 return;
Manuel Klimek79e06082015-05-21 12:23:34 +00001522
1523 // Parse formal parameter list.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001524 parseParens();
Manuel Klimek79e06082015-05-21 12:23:34 +00001525
1526 if (FormatTok->is(tok::colon)) {
1527 // Parse a type definition.
1528 nextToken();
1529
1530 // Eat the type declaration. For braced inline object types, balance braces,
1531 // otherwise just parse until finding an l_brace for the function body.
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001532 if (FormatTok->is(tok::l_brace))
1533 tryToParseBracedList();
1534 else
Martin Probstaf16c502017-01-04 13:36:43 +00001535 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
Manuel Klimek79e06082015-05-21 12:23:34 +00001536 nextToken();
Manuel Klimek79e06082015-05-21 12:23:34 +00001537 }
1538
Martin Probstaf16c502017-01-04 13:36:43 +00001539 if (FormatTok->is(tok::semi))
1540 return;
1541
Manuel Klimek79e06082015-05-21 12:23:34 +00001542 parseChildBlock();
1543}
1544
Daniel Jasper3c883d12015-05-18 14:49:19 +00001545bool UnwrappedLineParser::tryToParseBracedList() {
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001546 if (FormatTok->BlockKind == BK_Unknown)
Daniel Jasper3c883d12015-05-18 14:49:19 +00001547 calculateBraceTypes();
Daniel Jasperb1f74a82013-07-09 09:06:29 +00001548 assert(FormatTok->BlockKind != BK_Unknown);
1549 if (FormatTok->BlockKind == BK_Block)
Manuel Klimekab419912013-05-23 09:41:43 +00001550 return false;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001551 nextToken();
Manuel Klimekab419912013-05-23 09:41:43 +00001552 parseBracedList();
1553 return true;
1554}
1555
Krasimir Georgievff747be2017-06-27 13:43:07 +00001556bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1557 tok::TokenKind ClosingBraceKind) {
Daniel Jasper015ed022013-09-13 09:20:45 +00001558 bool HasError = false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001559
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001560 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1561 // replace this by using parseAssigmentExpression() inside.
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001562 do {
Manuel Klimek79e06082015-05-21 12:23:34 +00001563 if (Style.Language == FormatStyle::LK_JavaScript) {
Martin Probst409697e2016-05-29 14:41:07 +00001564 if (FormatTok->is(Keywords.kw_function) ||
1565 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001566 tryToParseJSFunction();
1567 continue;
Daniel Jasperbe520bd2015-05-31 08:51:54 +00001568 }
1569 if (FormatTok->is(TT_JsFatArrow)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001570 nextToken();
1571 // Fat arrows can be followed by simple expressions or by child blocks
1572 // in curly braces.
Daniel Jaspere6fcf7d2015-06-17 13:08:06 +00001573 if (FormatTok->is(tok::l_brace)) {
Manuel Klimek79e06082015-05-21 12:23:34 +00001574 parseChildBlock();
1575 continue;
1576 }
1577 }
Martin Probst8e3eba02017-02-07 16:33:13 +00001578 if (FormatTok->is(tok::l_brace)) {
1579 // Could be a method inside of a braced list `{a() { return 1; }}`.
1580 if (tryToParseBracedList())
1581 continue;
1582 parseChildBlock();
1583 }
Daniel Jasperc03e16a2014-05-08 09:25:39 +00001584 }
Krasimir Georgievff747be2017-06-27 13:43:07 +00001585 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1586 nextToken();
1587 return !HasError;
1588 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001589 switch (FormatTok->Tok.getKind()) {
Manuel Klimek516e0542013-09-04 13:25:30 +00001590 case tok::caret:
1591 nextToken();
1592 if (FormatTok->is(tok::l_brace)) {
1593 parseChildBlock();
1594 }
1595 break;
1596 case tok::l_square:
1597 tryToParseLambda();
1598 break;
Daniel Jaspera87af7a2015-06-30 11:32:22 +00001599 case tok::l_paren:
1600 parseParens();
Daniel Jasperf46dec82015-03-31 14:34:15 +00001601 // JavaScript can just have free standing methods and getters/setters in
1602 // object literals. Detect them by a "{" following ")".
1603 if (Style.Language == FormatStyle::LK_JavaScript) {
Daniel Jasperf46dec82015-03-31 14:34:15 +00001604 if (FormatTok->is(tok::l_brace))
1605 parseChildBlock();
1606 break;
1607 }
Daniel Jasperf46dec82015-03-31 14:34:15 +00001608 break;
Martin Probst8e3eba02017-02-07 16:33:13 +00001609 case tok::l_brace:
1610 // Assume there are no blocks inside a braced init list apart
1611 // from the ones we explicitly parse out (like lambdas).
1612 FormatTok->BlockKind = BK_BracedInit;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001613 nextToken();
Martin Probst8e3eba02017-02-07 16:33:13 +00001614 parseBracedList();
1615 break;
Krasimir Georgievfa4dbb62017-08-03 13:43:45 +00001616 case tok::less:
1617 if (Style.Language == FormatStyle::LK_Proto) {
1618 nextToken();
1619 parseBracedList(/*ContinueOnSemicolons=*/false,
1620 /*ClosingBraceKind=*/tok::greater);
1621 } else {
1622 nextToken();
1623 }
1624 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001625 case tok::semi:
Daniel Jasperb9a49902016-01-09 15:56:28 +00001626 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1627 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1628 // used for error recovery if we have otherwise determined that this is
1629 // a braced list.
1630 if (Style.Language == FormatStyle::LK_JavaScript) {
1631 nextToken();
1632 break;
1633 }
Daniel Jasper015ed022013-09-13 09:20:45 +00001634 HasError = true;
1635 if (!ContinueOnSemicolons)
1636 return !HasError;
1637 nextToken();
1638 break;
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001639 case tok::comma:
1640 nextToken();
Manuel Klimeka3ff45e2013-04-10 09:52:05 +00001641 break;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001642 default:
1643 nextToken();
1644 break;
1645 }
1646 } while (!eof());
Daniel Jasper015ed022013-09-13 09:20:45 +00001647 return false;
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001648}
1649
Daniel Jasperf7935112012-12-03 18:12:45 +00001650void UnwrappedLineParser::parseParens() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001651 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
Daniel Jasperf7935112012-12-03 18:12:45 +00001652 nextToken();
1653 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001654 switch (FormatTok->Tok.getKind()) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001655 case tok::l_paren:
1656 parseParens();
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001657 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1658 parseChildBlock();
Daniel Jasperf7935112012-12-03 18:12:45 +00001659 break;
1660 case tok::r_paren:
1661 nextToken();
1662 return;
Daniel Jasper393564f2013-05-31 14:56:29 +00001663 case tok::r_brace:
1664 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1665 return;
Daniel Jasper9a8d48b2013-09-05 10:04:31 +00001666 case tok::l_square:
1667 tryToParseLambda();
1668 break;
Daniel Jasper5f1fa852015-01-04 20:40:51 +00001669 case tok::l_brace:
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001670 if (!tryToParseBracedList())
Manuel Klimekf017dc02013-09-04 13:34:14 +00001671 parseChildBlock();
Manuel Klimek8e07a1b2013-01-10 11:52:21 +00001672 break;
Nico Weber372d8dc2013-02-10 20:35:35 +00001673 case tok::at:
1674 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001675 if (FormatTok->Tok.is(tok::l_brace)) {
1676 nextToken();
Nico Weber372d8dc2013-02-10 20:35:35 +00001677 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001678 }
Nico Weber372d8dc2013-02-10 20:35:35 +00001679 break;
Martin Probst1027fb82017-02-07 14:05:30 +00001680 case tok::kw_class:
1681 if (Style.Language == FormatStyle::LK_JavaScript)
1682 parseRecord(/*ParseAsExpr=*/true);
1683 else
1684 nextToken();
1685 break;
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001686 case tok::identifier:
1687 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probst409697e2016-05-29 14:41:07 +00001688 (FormatTok->is(Keywords.kw_function) ||
1689 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
Daniel Jasper3f69ba12014-09-05 08:42:27 +00001690 tryToParseJSFunction();
1691 else
1692 nextToken();
1693 break;
Daniel Jasperf7935112012-12-03 18:12:45 +00001694 default:
1695 nextToken();
1696 break;
1697 }
1698 } while (!eof());
1699}
1700
Manuel Klimek9f0a4e52017-09-19 09:59:30 +00001701void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1702 if (!LambdaIntroducer) {
1703 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1704 if (tryToParseLambda())
1705 return;
1706 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001707 do {
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001708 switch (FormatTok->Tok.getKind()) {
1709 case tok::l_paren:
1710 parseParens();
1711 break;
1712 case tok::r_square:
1713 nextToken();
1714 return;
1715 case tok::r_brace:
1716 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1717 return;
1718 case tok::l_square:
1719 parseSquare();
1720 break;
1721 case tok::l_brace: {
Daniel Jasperadba2aa2015-05-18 12:52:00 +00001722 if (!tryToParseBracedList())
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001723 parseChildBlock();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001724 break;
1725 }
1726 case tok::at:
1727 nextToken();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001728 if (FormatTok->Tok.is(tok::l_brace)) {
1729 nextToken();
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001730 parseBracedList();
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00001731 }
Daniel Jasperb88b25f2013-12-23 07:29:06 +00001732 break;
1733 default:
1734 nextToken();
1735 break;
1736 }
1737 } while (!eof());
1738}
1739
Daniel Jasperf7935112012-12-03 18:12:45 +00001740void UnwrappedLineParser::parseIfThenElse() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001741 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001742 nextToken();
Daniel Jasper6a7d5a72017-06-19 07:40:49 +00001743 if (FormatTok->Tok.is(tok::kw_constexpr))
1744 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001745 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimekadededf2013-01-11 18:28:36 +00001746 parseParens();
Daniel Jasperf7935112012-12-03 18:12:45 +00001747 bool NeedsUnwrappedLine = false;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001748 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001749 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001750 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001751 if (Style.BraceWrapping.BeforeElse)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001752 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001753 else
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001754 NeedsUnwrappedLine = true;
Daniel Jasperf7935112012-12-03 18:12:45 +00001755 } else {
1756 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001757 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001758 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001759 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001760 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001761 if (FormatTok->Tok.is(tok::kw_else)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001762 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001763 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001764 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001765 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001766 addUnwrappedLine();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001767 } else if (FormatTok->Tok.is(tok::kw_if)) {
Daniel Jasperf7935112012-12-03 18:12:45 +00001768 parseIfThenElse();
1769 } else {
1770 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001771 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001772 parseStructuralElement();
Daniel Jasper451544a2016-05-19 06:30:48 +00001773 if (FormatTok->is(tok::eof))
1774 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001775 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001776 }
1777 } else if (NeedsUnwrappedLine) {
1778 addUnwrappedLine();
1779 }
1780}
1781
Daniel Jasper04a71a42014-05-08 11:58:24 +00001782void UnwrappedLineParser::parseTryCatch() {
Nico Weberfac23712015-02-04 15:26:27 +00001783 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
Daniel Jasper04a71a42014-05-08 11:58:24 +00001784 nextToken();
1785 bool NeedsUnwrappedLine = false;
1786 if (FormatTok->is(tok::colon)) {
1787 // We are in a function try block, what comes is an initializer list.
1788 nextToken();
1789 while (FormatTok->is(tok::identifier)) {
1790 nextToken();
1791 if (FormatTok->is(tok::l_paren))
1792 parseParens();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001793 if (FormatTok->is(tok::comma))
1794 nextToken();
1795 }
1796 }
Daniel Jaspere189d462015-01-14 10:48:41 +00001797 // Parse try with resource.
1798 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1799 parseParens();
1800 }
Daniel Jasper04a71a42014-05-08 11:58:24 +00001801 if (FormatTok->is(tok::l_brace)) {
1802 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1803 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001804 if (Style.BraceWrapping.BeforeCatch) {
Daniel Jasper04a71a42014-05-08 11:58:24 +00001805 addUnwrappedLine();
1806 } else {
1807 NeedsUnwrappedLine = true;
1808 }
1809 } else if (!FormatTok->is(tok::kw_catch)) {
1810 // The C++ standard requires a compound-statement after a try.
1811 // If there's none, we try to assume there's a structuralElement
1812 // and try to continue.
Daniel Jasper04a71a42014-05-08 11:58:24 +00001813 addUnwrappedLine();
1814 ++Line->Level;
1815 parseStructuralElement();
1816 --Line->Level;
1817 }
Nico Weber33381f52015-02-07 01:57:32 +00001818 while (1) {
1819 if (FormatTok->is(tok::at))
1820 nextToken();
1821 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1822 tok::kw___finally) ||
1823 ((Style.Language == FormatStyle::LK_Java ||
1824 Style.Language == FormatStyle::LK_JavaScript) &&
1825 FormatTok->is(Keywords.kw_finally)) ||
1826 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1827 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1828 break;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001829 nextToken();
1830 while (FormatTok->isNot(tok::l_brace)) {
1831 if (FormatTok->is(tok::l_paren)) {
1832 parseParens();
1833 continue;
1834 }
Daniel Jasper2bd7a642015-01-19 10:50:51 +00001835 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
Daniel Jasper04a71a42014-05-08 11:58:24 +00001836 return;
1837 nextToken();
1838 }
1839 NeedsUnwrappedLine = false;
1840 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1841 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001842 if (Style.BraceWrapping.BeforeCatch)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001843 addUnwrappedLine();
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001844 else
Daniel Jasper04a71a42014-05-08 11:58:24 +00001845 NeedsUnwrappedLine = true;
Daniel Jasper04a71a42014-05-08 11:58:24 +00001846 }
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001847 if (NeedsUnwrappedLine)
Daniel Jasper04a71a42014-05-08 11:58:24 +00001848 addUnwrappedLine();
Daniel Jasper04a71a42014-05-08 11:58:24 +00001849}
1850
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001851void UnwrappedLineParser::parseNamespace() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001852 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001853
1854 const FormatToken &InitialToken = *FormatTok;
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001855 nextToken();
Saleem Abdulrasool328085f2015-10-30 05:07:56 +00001856 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001857 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001858 if (FormatTok->Tok.is(tok::l_brace)) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00001859 if (ShouldBreakBeforeBrace(Style, InitialToken))
Manuel Klimeka8eb9142013-05-13 12:51:40 +00001860 addUnwrappedLine();
1861
Daniel Jasper65ee3472013-07-31 23:16:02 +00001862 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1863 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1864 DeclarationScopeStack.size() > 1);
1865 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
Manuel Klimek046b9302013-02-06 16:08:09 +00001866 // Munch the semicolon after a namespace. This is more common than one would
1867 // think. Puttin the semicolon into its own line is very ugly.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001868 if (FormatTok->Tok.is(tok::semi))
Manuel Klimek046b9302013-02-06 16:08:09 +00001869 nextToken();
Alexander Kornienko578fdd82012-12-06 18:03:27 +00001870 addUnwrappedLine();
1871 }
1872 // FIXME: Add error handling.
1873}
1874
Daniel Jasper6acf5132015-03-12 14:44:29 +00001875void UnwrappedLineParser::parseNew() {
1876 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1877 nextToken();
1878 if (Style.Language != FormatStyle::LK_Java)
1879 return;
1880
1881 // In Java, we can parse everything up to the parens, which aren't optional.
1882 do {
1883 // There should not be a ;, { or } before the new's open paren.
1884 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1885 return;
1886
1887 // Consume the parens.
1888 if (FormatTok->is(tok::l_paren)) {
1889 parseParens();
1890
1891 // If there is a class body of an anonymous class, consume that as child.
1892 if (FormatTok->is(tok::l_brace))
1893 parseChildBlock();
1894 return;
1895 }
1896 nextToken();
1897 } while (!eof());
1898}
1899
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001900void UnwrappedLineParser::parseForOrWhileLoop() {
Daniel Jasper66cb8c52015-05-04 09:22:29 +00001901 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
Daniel Jaspere1e43192014-04-01 12:55:11 +00001902 "'for', 'while' or foreach macro expected");
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001903 nextToken();
Martin Probsta050f412017-05-18 21:19:29 +00001904 // JS' for await ( ...
Martin Probstbd49e322017-05-15 19:33:20 +00001905 if (Style.Language == FormatStyle::LK_JavaScript &&
Martin Probsta050f412017-05-18 21:19:29 +00001906 FormatTok->is(Keywords.kw_await))
Martin Probstbd49e322017-05-15 19:33:20 +00001907 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001908 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001909 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001910 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001911 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001912 parseBlock(/*MustBeDeclaration=*/false);
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001913 addUnwrappedLine();
1914 } else {
1915 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001916 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001917 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001918 --Line->Level;
Alexander Kornienko37d6c942012-12-05 15:06:06 +00001919 }
1920}
1921
Daniel Jasperf7935112012-12-03 18:12:45 +00001922void UnwrappedLineParser::parseDoWhile() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001923 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001924 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001925 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001926 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001927 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001928 if (Style.BraceWrapping.IndentBraces)
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001929 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001930 } else {
1931 addUnwrappedLine();
Manuel Klimek52b15152013-01-09 15:25:02 +00001932 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001933 parseStructuralElement();
Manuel Klimek52b15152013-01-09 15:25:02 +00001934 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001935 }
1936
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001937 // FIXME: Add error handling.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001938 if (!FormatTok->Tok.is(tok::kw_while)) {
Alexander Kornienko0ea8e102012-12-04 15:40:36 +00001939 addUnwrappedLine();
1940 return;
1941 }
1942
Daniel Jasperf7935112012-12-03 18:12:45 +00001943 nextToken();
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001944 parseStructuralElement();
Daniel Jasperf7935112012-12-03 18:12:45 +00001945}
1946
1947void UnwrappedLineParser::parseLabel() {
Daniel Jasperf7935112012-12-03 18:12:45 +00001948 nextToken();
Manuel Klimek52b15152013-01-09 15:25:02 +00001949 unsigned OldLineLevel = Line->Level;
Daniel Jaspera1275122013-03-20 10:23:53 +00001950 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
Manuel Klimek52b15152013-01-09 15:25:02 +00001951 --Line->Level;
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001952 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001953 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Nico Weber9096fc02013-06-26 00:30:14 +00001954 parseBlock(/*MustBeDeclaration=*/false);
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001955 if (FormatTok->Tok.is(tok::kw_break)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00001956 if (Style.BraceWrapping.AfterControlStatement)
Manuel Klimekd3ed59a2013-08-02 21:31:59 +00001957 addUnwrappedLine();
1958 parseStructuralElement();
1959 }
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001960 addUnwrappedLine();
1961 } else {
Daniel Jasper1fe0d5c2015-05-06 15:19:47 +00001962 if (FormatTok->is(tok::semi))
1963 nextToken();
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001964 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00001965 }
Manuel Klimek52b15152013-01-09 15:25:02 +00001966 Line->Level = OldLineLevel;
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001967 if (FormatTok->isNot(tok::l_brace)) {
Daniel Jasper40609472016-04-06 15:02:46 +00001968 parseStructuralElement();
Daniel Jasper2cce7b72016-04-06 16:41:39 +00001969 addUnwrappedLine();
1970 }
Daniel Jasperf7935112012-12-03 18:12:45 +00001971}
1972
1973void UnwrappedLineParser::parseCaseLabel() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001974 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001975 // FIXME: fix handling of complex expressions here.
1976 do {
1977 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001978 } while (!eof() && !FormatTok->Tok.is(tok::colon));
Daniel Jasperf7935112012-12-03 18:12:45 +00001979 parseLabel();
1980}
1981
1982void UnwrappedLineParser::parseSwitch() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001983 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
Daniel Jasperf7935112012-12-03 18:12:45 +00001984 nextToken();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001985 if (FormatTok->Tok.is(tok::l_paren))
Manuel Klimek9fa8d552013-01-11 19:23:05 +00001986 parseParens();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00001987 if (FormatTok->Tok.is(tok::l_brace)) {
Alexander Kornienko3a33f022013-12-12 09:49:52 +00001988 CompoundStatementIndenter Indenter(this, Style, Line->Level);
Daniel Jasper65ee3472013-07-31 23:16:02 +00001989 parseBlock(/*MustBeDeclaration=*/false);
Daniel Jasperf7935112012-12-03 18:12:45 +00001990 addUnwrappedLine();
1991 } else {
1992 addUnwrappedLine();
Daniel Jasper516d7972013-07-25 11:31:57 +00001993 ++Line->Level;
Manuel Klimek6b9eeba2013-01-07 14:56:16 +00001994 parseStructuralElement();
Daniel Jasper516d7972013-07-25 11:31:57 +00001995 --Line->Level;
Daniel Jasperf7935112012-12-03 18:12:45 +00001996 }
1997}
1998
1999void UnwrappedLineParser::parseAccessSpecifier() {
2000 nextToken();
Daniel Jasper84c47a12013-11-23 17:53:41 +00002001 // Understand Qt's slots.
Daniel Jasper53395402015-04-07 15:04:40 +00002002 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
Daniel Jasper84c47a12013-11-23 17:53:41 +00002003 nextToken();
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00002004 // Otherwise, we don't know what it is, and we'd better keep the next token.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002005 if (FormatTok->Tok.is(tok::colon))
Alexander Kornienko2ca766f2012-12-10 16:34:48 +00002006 nextToken();
Daniel Jasperf7935112012-12-03 18:12:45 +00002007 addUnwrappedLine();
2008}
2009
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002010bool UnwrappedLineParser::parseEnum() {
Daniel Jasper6be0f552014-11-13 15:56:28 +00002011 // Won't be 'enum' for NS_ENUMs.
2012 if (FormatTok->Tok.is(tok::kw_enum))
Daniel Jasperccb68b42014-11-19 22:38:18 +00002013 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002014
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002015 // In TypeScript, "enum" can also be used as property name, e.g. in interface
2016 // declarations. An "enum" keyword followed by a colon would be a syntax
2017 // error and thus assume it is just an identifier.
Daniel Jasper87379302016-02-03 05:33:44 +00002018 if (Style.Language == FormatStyle::LK_JavaScript &&
2019 FormatTok->isOneOf(tok::colon, tok::question))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002020 return false;
2021
Paul Hoada87ba1c2019-03-23 14:24:30 +00002022 // In protobuf, "enum" can be used as a field name.
2023 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
2024 return false;
2025
Daniel Jasper2b41a822013-08-20 12:42:50 +00002026 // Eat up enum class ...
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002027 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
2028 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002029
Daniel Jasper786a5502013-09-06 21:32:35 +00002030 while (FormatTok->Tok.getIdentifierInfo() ||
Daniel Jasperccb68b42014-11-19 22:38:18 +00002031 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
2032 tok::greater, tok::comma, tok::question)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00002033 nextToken();
2034 // We can have macros or attributes in between 'enum' and the enum name.
Daniel Jasperccb68b42014-11-19 22:38:18 +00002035 if (FormatTok->is(tok::l_paren))
Alexander Kornienkob7076a22012-12-04 14:46:19 +00002036 parseParens();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002037 if (FormatTok->is(tok::identifier)) {
Manuel Klimek2cec0192013-01-21 19:17:52 +00002038 nextToken();
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002039 // If there are two identifiers in a row, this is likely an elaborate
2040 // return type. In Java, this can be "implements", etc.
Daniel Jasper1dbc2102017-03-31 13:30:24 +00002041 if (Style.isCpp() && FormatTok->is(tok::identifier))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002042 return false;
Daniel Jasperb5a0b852015-06-19 08:17:32 +00002043 }
Manuel Klimek2cec0192013-01-21 19:17:52 +00002044 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00002045
2046 // Just a declaration or something is wrong.
Daniel Jasperccb68b42014-11-19 22:38:18 +00002047 if (FormatTok->isNot(tok::l_brace))
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002048 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00002049 FormatTok->BlockKind = BK_Block;
2050
2051 if (Style.Language == FormatStyle::LK_Java) {
2052 // Java enums are different.
2053 parseJavaEnumBody();
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002054 return true;
2055 }
2056 if (Style.Language == FormatStyle::LK_Proto) {
Daniel Jasperc6dd2732015-07-16 14:25:43 +00002057 parseBlock(/*MustBeDeclaration=*/true);
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002058 return true;
Manuel Klimek2cec0192013-01-21 19:17:52 +00002059 }
Daniel Jasper6be0f552014-11-13 15:56:28 +00002060
2061 // Parse enum body.
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002062 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002063 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
2064 if (HasError) {
2065 if (FormatTok->is(tok::semi))
2066 nextToken();
2067 addUnwrappedLine();
2068 }
Daniel Jasper6f5a1932015-12-29 08:54:23 +00002069 return true;
Daniel Jasper6be0f552014-11-13 15:56:28 +00002070
Daniel Jasper90cf3802015-06-17 09:44:02 +00002071 // There is no addUnwrappedLine() here so that we fall through to parsing a
2072 // structural element afterwards. Thus, in "enum A {} n, m;",
Manuel Klimek2cec0192013-01-21 19:17:52 +00002073 // "} n, m;" will end up in one unwrapped line.
Daniel Jasper6be0f552014-11-13 15:56:28 +00002074}
2075
2076void UnwrappedLineParser::parseJavaEnumBody() {
2077 // Determine whether the enum is simple, i.e. does not have a semicolon or
2078 // constants with class bodies. Simple enums can be formatted like braced
2079 // lists, contracted to a single line, etc.
2080 unsigned StoredPosition = Tokens->getPosition();
2081 bool IsSimple = true;
2082 FormatToken *Tok = Tokens->getNextToken();
2083 while (Tok) {
2084 if (Tok->is(tok::r_brace))
2085 break;
2086 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2087 IsSimple = false;
2088 break;
2089 }
2090 // FIXME: This will also mark enums with braces in the arguments to enum
2091 // constants as "not simple". This is probably fine in practice, though.
2092 Tok = Tokens->getNextToken();
2093 }
2094 FormatTok = Tokens->setPosition(StoredPosition);
2095
2096 if (IsSimple) {
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002097 nextToken();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002098 parseBracedList();
Daniel Jasperdf2ff002014-11-02 22:31:39 +00002099 addUnwrappedLine();
Daniel Jasper6be0f552014-11-13 15:56:28 +00002100 return;
2101 }
2102
2103 // Parse the body of a more complex enum.
2104 // First add a line for everything up to the "{".
2105 nextToken();
2106 addUnwrappedLine();
2107 ++Line->Level;
2108
2109 // Parse the enum constants.
2110 while (FormatTok) {
2111 if (FormatTok->is(tok::l_brace)) {
2112 // Parse the constant's class body.
2113 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2114 /*MunchSemi=*/false);
2115 } else if (FormatTok->is(tok::l_paren)) {
2116 parseParens();
2117 } else if (FormatTok->is(tok::comma)) {
2118 nextToken();
2119 addUnwrappedLine();
2120 } else if (FormatTok->is(tok::semi)) {
2121 nextToken();
2122 addUnwrappedLine();
2123 break;
2124 } else if (FormatTok->is(tok::r_brace)) {
2125 addUnwrappedLine();
2126 break;
2127 } else {
2128 nextToken();
2129 }
2130 }
2131
2132 // Parse the class body after the enum's ";" if any.
2133 parseLevel(/*HasOpeningBrace=*/true);
2134 nextToken();
2135 --Line->Level;
2136 addUnwrappedLine();
Daniel Jasperf7935112012-12-03 18:12:45 +00002137}
2138
Martin Probst1027fb82017-02-07 14:05:30 +00002139void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
Roman Kashitsyna043ced2014-08-11 12:18:01 +00002140 const FormatToken &InitialToken = *FormatTok;
Manuel Klimek28cacc72013-01-07 18:10:23 +00002141 nextToken();
Daniel Jasper04785d02015-05-06 14:03:02 +00002142
Daniel Jasper04785d02015-05-06 14:03:02 +00002143 // The actual identifier can be a nested name specifier, and in macros
2144 // it is often token-pasted.
2145 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2146 tok::kw___attribute, tok::kw___declspec,
2147 tok::kw_alignas) ||
2148 ((Style.Language == FormatStyle::LK_Java ||
2149 Style.Language == FormatStyle::LK_JavaScript) &&
2150 FormatTok->isOneOf(tok::period, tok::comma))) {
Martin Probstcb870c52017-08-01 15:46:10 +00002151 if (Style.Language == FormatStyle::LK_JavaScript &&
2152 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2153 // JavaScript/TypeScript supports inline object types in
2154 // extends/implements positions:
2155 // class Foo implements {bar: number} { }
2156 nextToken();
2157 if (FormatTok->is(tok::l_brace)) {
2158 tryToParseBracedList();
2159 continue;
2160 }
2161 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002162 bool IsNonMacroIdentifier =
2163 FormatTok->is(tok::identifier) &&
2164 FormatTok->TokenText != FormatTok->TokenText.upper();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002165 nextToken();
2166 // We can have macros or attributes in between 'class' and the class name.
Daniel Jasper04785d02015-05-06 14:03:02 +00002167 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
Manuel Klimeke01bab52013-01-15 13:38:33 +00002168 parseParens();
Daniel Jasper04785d02015-05-06 14:03:02 +00002169 }
Manuel Klimeke01bab52013-01-15 13:38:33 +00002170
Daniel Jasper04785d02015-05-06 14:03:02 +00002171 // Note that parsing away template declarations here leads to incorrectly
2172 // accepting function declarations as record declarations.
2173 // In general, we cannot solve this problem. Consider:
2174 // class A<int> B() {}
2175 // which can be a function definition or a class definition when B() is a
2176 // macro. If we find enough real-world cases where this is a problem, we
2177 // can parse for the 'template' keyword in the beginning of the statement,
2178 // and thus rule out the record production in case there is no template
2179 // (this would still leave us with an ambiguity between template function
2180 // and class declarations).
Daniel Jasperadba2aa2015-05-18 12:52:00 +00002181 if (FormatTok->isOneOf(tok::colon, tok::less)) {
2182 while (!eof()) {
Daniel Jasper3c883d12015-05-18 14:49:19 +00002183 if (FormatTok->is(tok::l_brace)) {
2184 calculateBraceTypes(/*ExpectClassBody=*/true);
2185 if (!tryToParseBracedList())
2186 break;
2187 }
Daniel Jasper04785d02015-05-06 14:03:02 +00002188 if (FormatTok->Tok.is(tok::semi))
2189 return;
2190 nextToken();
Manuel Klimeke01bab52013-01-15 13:38:33 +00002191 }
2192 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002193 if (FormatTok->Tok.is(tok::l_brace)) {
Martin Probst1027fb82017-02-07 14:05:30 +00002194 if (ParseAsExpr) {
2195 parseChildBlock();
2196 } else {
2197 if (ShouldBreakBeforeBrace(Style, InitialToken))
2198 addUnwrappedLine();
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002199
Martin Probst1027fb82017-02-07 14:05:30 +00002200 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2201 /*MunchSemi=*/false);
2202 }
Manuel Klimeka8eb9142013-05-13 12:51:40 +00002203 }
Daniel Jasper90cf3802015-06-17 09:44:02 +00002204 // There is no addUnwrappedLine() here so that we fall through to parsing a
2205 // structural element afterwards. Thus, in "class A {} n, m;",
2206 // "} n, m;" will end up in one unwrapped line.
Manuel Klimek28cacc72013-01-07 18:10:23 +00002207}
2208
Ben Hamilton707e68f2018-05-30 15:21:38 +00002209void UnwrappedLineParser::parseObjCMethod() {
2210 assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2211 "'(' or identifier expected.");
2212 do {
2213 if (FormatTok->Tok.is(tok::semi)) {
2214 nextToken();
2215 addUnwrappedLine();
2216 return;
2217 } else if (FormatTok->Tok.is(tok::l_brace)) {
Ben Hamilton97034a32018-10-12 19:43:01 +00002218 if (Style.BraceWrapping.AfterFunction)
2219 addUnwrappedLine();
Ben Hamilton707e68f2018-05-30 15:21:38 +00002220 parseBlock(/*MustBeDeclaration=*/false);
2221 addUnwrappedLine();
2222 return;
2223 } else {
2224 nextToken();
2225 }
2226 } while (!eof());
2227}
2228
Nico Weber8696a8d2013-01-09 21:15:03 +00002229void UnwrappedLineParser::parseObjCProtocolList() {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002230 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
Ben Hamilton1462e842018-04-05 15:26:25 +00002231 do {
Nico Weber8696a8d2013-01-09 21:15:03 +00002232 nextToken();
Ben Hamilton1462e842018-04-05 15:26:25 +00002233 // Early exit in case someone forgot a close angle.
2234 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2235 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2236 return;
2237 } while (!eof() && FormatTok->Tok.isNot(tok::greater));
Nico Weber8696a8d2013-01-09 21:15:03 +00002238 nextToken(); // Skip '>'.
2239}
2240
2241void UnwrappedLineParser::parseObjCUntilAtEnd() {
2242 do {
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002243 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002244 nextToken();
2245 addUnwrappedLine();
2246 break;
2247 }
Daniel Jaspera15da302013-08-28 08:04:23 +00002248 if (FormatTok->is(tok::l_brace)) {
2249 parseBlock(/*MustBeDeclaration=*/false);
2250 // In ObjC interfaces, nothing should be following the "}".
2251 addUnwrappedLine();
Benjamin Kramere21cb742014-01-08 15:59:42 +00002252 } else if (FormatTok->is(tok::r_brace)) {
2253 // Ignore stray "}". parseStructuralElement doesn't consume them.
2254 nextToken();
2255 addUnwrappedLine();
Ben Hamilton707e68f2018-05-30 15:21:38 +00002256 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2257 nextToken();
2258 parseObjCMethod();
Daniel Jaspera15da302013-08-28 08:04:23 +00002259 } else {
2260 parseStructuralElement();
2261 }
Nico Weber8696a8d2013-01-09 21:15:03 +00002262 } while (!eof());
2263}
2264
Nico Weber2ce0ac52013-01-09 23:25:37 +00002265void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
Nico Weberc068ff72018-01-23 17:10:25 +00002266 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2267 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
Nico Weber7eecf4b2013-01-09 20:25:35 +00002268 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002269 nextToken(); // interface name
Nico Weber7eecf4b2013-01-09 20:25:35 +00002270
Ben Hamilton1462e842018-04-05 15:26:25 +00002271 // @interface can be followed by a lightweight generic
2272 // specialization list, then either a base class or a category.
2273 if (FormatTok->Tok.is(tok::less)) {
2274 // Unlike protocol lists, generic parameterizations support
2275 // nested angles:
2276 //
2277 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
2278 // NSObject <NSCopying, NSSecureCoding>
2279 //
2280 // so we need to count how many open angles we have left.
2281 unsigned NumOpenAngles = 1;
2282 do {
2283 nextToken();
2284 // Early exit in case someone forgot a close angle.
2285 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2286 FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2287 break;
2288 if (FormatTok->Tok.is(tok::less))
2289 ++NumOpenAngles;
2290 else if (FormatTok->Tok.is(tok::greater)) {
2291 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
2292 --NumOpenAngles;
2293 }
2294 } while (!eof() && NumOpenAngles != 0);
2295 nextToken(); // Skip '>'.
2296 }
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002297 if (FormatTok->Tok.is(tok::colon)) {
Nico Weber7eecf4b2013-01-09 20:25:35 +00002298 nextToken();
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002299 nextToken(); // base class name
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002300 } else if (FormatTok->Tok.is(tok::l_paren))
Nico Weber7eecf4b2013-01-09 20:25:35 +00002301 // Skip category, if present.
2302 parseParens();
2303
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002304 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002305 parseObjCProtocolList();
Nico Weber7eecf4b2013-01-09 20:25:35 +00002306
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002307 if (FormatTok->Tok.is(tok::l_brace)) {
Daniel Jasperc1bc38e2015-09-29 14:57:55 +00002308 if (Style.BraceWrapping.AfterObjCDeclaration)
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002309 addUnwrappedLine();
Nico Weber9096fc02013-06-26 00:30:14 +00002310 parseBlock(/*MustBeDeclaration=*/true);
Dinesh Dwivediea3aca82014-05-02 17:01:46 +00002311 }
Nico Weber7eecf4b2013-01-09 20:25:35 +00002312
2313 // With instance variables, this puts '}' on its own line. Without instance
2314 // variables, this ends the @interface line.
2315 addUnwrappedLine();
2316
Nico Weber8696a8d2013-01-09 21:15:03 +00002317 parseObjCUntilAtEnd();
2318}
Nico Weber7eecf4b2013-01-09 20:25:35 +00002319
Nico Weberc068ff72018-01-23 17:10:25 +00002320// Returns true for the declaration/definition form of @protocol,
2321// false for the expression form.
2322bool UnwrappedLineParser::parseObjCProtocol() {
2323 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
Nico Weber8696a8d2013-01-09 21:15:03 +00002324 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002325
2326 if (FormatTok->is(tok::l_paren))
2327 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2328 return false;
2329
2330 // The definition/declaration form,
2331 // @protocol Foo
2332 // - (int)someMethod;
2333 // @end
2334
Daniel Jasperd1ae3582013-03-20 12:37:50 +00002335 nextToken(); // protocol name
Nico Weber8696a8d2013-01-09 21:15:03 +00002336
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002337 if (FormatTok->Tok.is(tok::less))
Nico Weber8696a8d2013-01-09 21:15:03 +00002338 parseObjCProtocolList();
2339
2340 // Check for protocol declaration.
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002341 if (FormatTok->Tok.is(tok::semi)) {
Nico Weber8696a8d2013-01-09 21:15:03 +00002342 nextToken();
Nico Weberc068ff72018-01-23 17:10:25 +00002343 addUnwrappedLine();
2344 return true;
Nico Weber8696a8d2013-01-09 21:15:03 +00002345 }
2346
2347 addUnwrappedLine();
2348 parseObjCUntilAtEnd();
Nico Weberc068ff72018-01-23 17:10:25 +00002349 return true;
Nico Weber7eecf4b2013-01-09 20:25:35 +00002350}
2351
Daniel Jasperfca735c2015-02-19 16:14:18 +00002352void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
Martin Probst053f1aa2016-04-19 14:55:37 +00002353 bool IsImport = FormatTok->is(Keywords.kw_import);
2354 assert(IsImport || FormatTok->is(tok::kw_export));
Daniel Jasper354aa512015-02-19 16:07:32 +00002355 nextToken();
Daniel Jasperfca735c2015-02-19 16:14:18 +00002356
Daniel Jasperec05fc72015-05-11 09:14:50 +00002357 // Consume the "default" in "export default class/function".
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002358 if (FormatTok->is(tok::kw_default))
2359 nextToken();
Daniel Jasperec05fc72015-05-11 09:14:50 +00002360
Martin Probst5f8445b2016-04-24 22:05:09 +00002361 // Consume "async function", "function" and "default function", so that these
2362 // get parsed as free-standing JS functions, i.e. do not require a trailing
2363 // semicolon.
2364 if (FormatTok->is(Keywords.kw_async))
2365 nextToken();
Daniel Jasper668c7bb2015-05-11 09:03:10 +00002366 if (FormatTok->is(Keywords.kw_function)) {
2367 nextToken();
2368 return;
2369 }
2370
Martin Probst053f1aa2016-04-19 14:55:37 +00002371 // For imports, `export *`, `export {...}`, consume the rest of the line up
2372 // to the terminating `;`. For everything else, just return and continue
2373 // parsing the structural element, i.e. the declaration or expression for
2374 // `export default`.
2375 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2376 !FormatTok->isStringLiteral())
2377 return;
Daniel Jasperfca735c2015-02-19 16:14:18 +00002378
Martin Probstd40bca42017-01-09 08:56:36 +00002379 while (!eof()) {
2380 if (FormatTok->is(tok::semi))
2381 return;
Krasimir Georgiev112c2e92017-11-09 13:22:03 +00002382 if (Line->Tokens.empty()) {
Martin Probstd40bca42017-01-09 08:56:36 +00002383 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2384 // import statement should terminate.
2385 return;
2386 }
Daniel Jasperefc1a832016-01-07 08:53:35 +00002387 if (FormatTok->is(tok::l_brace)) {
2388 FormatTok->BlockKind = BK_Block;
Krasimir Georgiev26b144c2017-07-03 15:05:14 +00002389 nextToken();
Daniel Jasperefc1a832016-01-07 08:53:35 +00002390 parseBracedList();
2391 } else {
2392 nextToken();
2393 }
Daniel Jasper354aa512015-02-19 16:07:32 +00002394 }
2395}
2396
Paul Hoad5bcf99b2019-03-01 09:09:54 +00002397void UnwrappedLineParser::parseStatementMacro() {
Francois Ferrand6f40e212018-10-02 16:37:51 +00002398 nextToken();
2399 if (FormatTok->is(tok::l_paren))
2400 parseParens();
2401 if (FormatTok->is(tok::semi))
2402 nextToken();
2403 addUnwrappedLine();
2404}
2405
Daniel Jasper3b203a62013-09-05 16:05:56 +00002406LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2407 StringRef Prefix = "") {
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002408 llvm::dbgs() << Prefix << "Line(" << Line.Level
2409 << ", FSC=" << Line.FirstStartColumn << ")"
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002410 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2411 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2412 E = Line.Tokens.end();
2413 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002414 llvm::dbgs() << I->Tok->Tok.getName() << "["
Manuel Klimek89628f62017-09-20 09:51:03 +00002415 << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
2416 << "] ";
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002417 }
2418 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2419 E = Line.Tokens.end();
2420 I != E; ++I) {
2421 const UnwrappedLineNode &Node = *I;
2422 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2423 I = Node.Children.begin(),
2424 E = Node.Children.end();
2425 I != E; ++I) {
2426 printDebugInfo(*I, "\nChild: ");
2427 }
2428 }
2429 llvm::dbgs() << "\n";
2430}
2431
Daniel Jasperf7935112012-12-03 18:12:45 +00002432void UnwrappedLineParser::addUnwrappedLine() {
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002433 if (Line->Tokens.empty())
Daniel Jasper7c85fde2013-01-08 14:56:18 +00002434 return;
Nicola Zaghen3538b392018-05-15 13:30:56 +00002435 LLVM_DEBUG({
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002436 if (CurrentLines == &Lines)
2437 printDebugInfo(*Line);
Manuel Klimekab3dc002013-01-16 12:31:12 +00002438 });
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002439 CurrentLines->push_back(std::move(*Line));
Daniel Jasperdaffc0d2013-01-16 09:10:19 +00002440 Line->Tokens.clear();
Krasimir Georgiev85c37042017-03-01 16:38:08 +00002441 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
Krasimir Georgiev9ad83fe2017-10-30 14:01:50 +00002442 Line->FirstStartColumn = 0;
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002443 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
Benjamin Kramerc7551a42015-05-31 11:18:05 +00002444 CurrentLines->append(
2445 std::make_move_iterator(PreprocessorDirectives.begin()),
2446 std::make_move_iterator(PreprocessorDirectives.end()));
Manuel Klimekd3b92fa2013-01-18 14:04:34 +00002447 PreprocessorDirectives.clear();
2448 }
Manuel Klimeke411aa82017-09-20 09:29:37 +00002449 // Disconnect the current token from the last token on the previous line.
2450 FormatTok->Previous = nullptr;
Daniel Jasperf7935112012-12-03 18:12:45 +00002451}
2452
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002453bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
Daniel Jasperf7935112012-12-03 18:12:45 +00002454
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002455bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002456 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2457 FormatTok.NewlinesBefore > 0;
2458}
2459
Krasimir Georgiev91834222017-01-25 13:58:58 +00002460// Checks if \p FormatTok is a line comment that continues the line comment
2461// section on \p Line.
Krasimir Georgievea222a72017-05-22 10:07:56 +00002462static bool continuesLineCommentSection(const FormatToken &FormatTok,
2463 const UnwrappedLine &Line,
2464 llvm::Regex &CommentPragmasRegex) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002465 if (Line.Tokens.empty())
2466 return false;
Krasimir Georgiev84321612017-01-30 19:18:55 +00002467
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002468 StringRef IndentContent = FormatTok.TokenText;
2469 if (FormatTok.TokenText.startswith("//") ||
2470 FormatTok.TokenText.startswith("/*"))
2471 IndentContent = FormatTok.TokenText.substr(2);
2472 if (CommentPragmasRegex.match(IndentContent))
2473 return false;
2474
Krasimir Georgiev91834222017-01-25 13:58:58 +00002475 // If Line starts with a line comment, then FormatTok continues the comment
Krasimir Georgiev84321612017-01-30 19:18:55 +00002476 // section if its original column is greater or equal to the original start
Krasimir Georgiev91834222017-01-25 13:58:58 +00002477 // column of the line.
2478 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002479 // Define the min column token of a line as follows: if a line ends in '{' or
2480 // contains a '{' followed by a line comment, then the min column token is
2481 // that '{'. Otherwise, the min column token of the line is the first token of
2482 // the line.
2483 //
2484 // If Line starts with a token other than a line comment, then FormatTok
2485 // continues the comment section if its original column is greater than the
2486 // original start column of the min column token of the line.
Krasimir Georgiev91834222017-01-25 13:58:58 +00002487 //
2488 // For example, the second line comment continues the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002489 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002490 // // first line
2491 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002492 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002493 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002494 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002495 // // first line
2496 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002497 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002498 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002499 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002500 // int i; // first line
2501 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002502 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002503 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002504 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002505 // do { // first line
2506 // // second line
2507 // int i;
2508 // } while (true);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002509 //
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002510 // and:
2511 //
2512 // enum {
2513 // a, // first line
2514 // // second line
2515 // b
2516 // };
2517 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002518 // The second line comment doesn't continue the first in these cases:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002519 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002520 // // first line
2521 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002522 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002523 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002524 //
Krasimir Georgiev91834222017-01-25 13:58:58 +00002525 // int i; // first line
2526 // // second line
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002527 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002528 // and:
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002529 //
Krasimir Georgiev84321612017-01-30 19:18:55 +00002530 // do { // first line
2531 // // second line
2532 // int i;
2533 // } while (true);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002534 //
2535 // and:
2536 //
2537 // enum {
2538 // a, // first line
2539 // // second line
2540 // };
Krasimir Georgiev84321612017-01-30 19:18:55 +00002541 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2542
2543 // Scan for '{//'. If found, use the column of '{' as a min column for line
2544 // comment section continuation.
2545 const FormatToken *PreviousToken = nullptr;
Krasimir Georgievd86c25d2017-03-10 13:09:29 +00002546 for (const UnwrappedLineNode &Node : Line.Tokens) {
Krasimir Georgiev84321612017-01-30 19:18:55 +00002547 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2548 isLineComment(*Node.Tok)) {
2549 MinColumnToken = PreviousToken;
2550 break;
2551 }
2552 PreviousToken = Node.Tok;
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002553
2554 // Grab the last newline preceding a token in this unwrapped line.
2555 if (Node.Tok->NewlinesBefore > 0) {
2556 MinColumnToken = Node.Tok;
2557 }
Krasimir Georgiev84321612017-01-30 19:18:55 +00002558 }
2559 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2560 MinColumnToken = PreviousToken;
2561 }
2562
Krasimir Georgievea222a72017-05-22 10:07:56 +00002563 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2564 MinColumnToken);
Krasimir Georgiev91834222017-01-25 13:58:58 +00002565}
2566
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002567void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2568 bool JustComments = Line->Tokens.empty();
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002569 for (SmallVectorImpl<FormatToken *>::const_iterator
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002570 I = CommentsBeforeNextToken.begin(),
2571 E = CommentsBeforeNextToken.end();
2572 I != E; ++I) {
Krasimir Georgiev91834222017-01-25 13:58:58 +00002573 // Line comments that belong to the same line comment section are put on the
2574 // same line since later we might want to reflow content between them.
Krasimir Georgiev753625b2017-01-31 13:32:38 +00002575 // Additional fine-grained breaking of line comment sections is controlled
2576 // by the class BreakableLineCommentSection in case it is desirable to keep
2577 // several line comment sections in the same unwrapped line.
2578 //
2579 // FIXME: Consider putting separate line comment sections as children to the
2580 // unwrapped line instead.
Krasimir Georgiev00c5c722017-02-02 15:32:19 +00002581 (*I)->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002582 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
Krasimir Georgievb6ccd382017-02-02 14:36:50 +00002583 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002584 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002585 pushToken(*I);
2586 }
Daniel Jaspere60cba12015-05-13 11:35:53 +00002587 if (NewlineBeforeNext && JustComments)
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002588 addUnwrappedLine();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002589 CommentsBeforeNextToken.clear();
2590}
2591
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002592void UnwrappedLineParser::nextToken(int LevelDifference) {
Daniel Jasperf7935112012-12-03 18:12:45 +00002593 if (eof())
2594 return;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002595 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002596 pushToken(FormatTok);
Manuel Klimek89628f62017-09-20 09:51:03 +00002597 FormatToken *Previous = FormatTok;
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002598 if (Style.Language != FormatStyle::LK_JavaScript)
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002599 readToken(LevelDifference);
Daniel Jasper1dcbbcfc2016-03-14 19:21:36 +00002600 else
2601 readTokenWithJavaScriptASI();
Manuel Klimeke411aa82017-09-20 09:29:37 +00002602 FormatTok->Previous = Previous;
Daniel Jasperb9a49902016-01-09 15:56:28 +00002603}
2604
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002605void UnwrappedLineParser::distributeComments(
2606 const SmallVectorImpl<FormatToken *> &Comments,
2607 const FormatToken *NextTok) {
2608 // Whether or not a line comment token continues a line is controlled by
Krasimir Georgievea222a72017-05-22 10:07:56 +00002609 // the method continuesLineCommentSection, with the following caveat:
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002610 //
2611 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2612 // that each comment line from the trail is aligned with the next token, if
2613 // the next token exists. If a trail exists, the beginning of the maximal
2614 // trail is marked as a start of a new comment section.
2615 //
2616 // For example in this code:
2617 //
2618 // int a; // line about a
2619 // // line 1 about b
2620 // // line 2 about b
2621 // int b;
2622 //
2623 // the two lines about b form a maximal trail, so there are two sections, the
2624 // first one consisting of the single comment "// line about a" and the
2625 // second one consisting of the next two comments.
2626 if (Comments.empty())
2627 return;
2628 bool ShouldPushCommentsInCurrentLine = true;
2629 bool HasTrailAlignedWithNextToken = false;
2630 unsigned StartOfTrailAlignedWithNextToken = 0;
2631 if (NextTok) {
2632 // We are skipping the first element intentionally.
2633 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2634 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2635 HasTrailAlignedWithNextToken = true;
2636 StartOfTrailAlignedWithNextToken = i;
2637 }
2638 }
2639 }
2640 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2641 FormatToken *FormatTok = Comments[i];
Manuel Klimek89628f62017-09-20 09:51:03 +00002642 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002643 FormatTok->ContinuesLineCommentSection = false;
2644 } else {
2645 FormatTok->ContinuesLineCommentSection =
Krasimir Georgievea222a72017-05-22 10:07:56 +00002646 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002647 }
2648 if (!FormatTok->ContinuesLineCommentSection &&
2649 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2650 ShouldPushCommentsInCurrentLine = false;
2651 }
2652 if (ShouldPushCommentsInCurrentLine) {
2653 pushToken(FormatTok);
2654 } else {
2655 CommentsBeforeNextToken.push_back(FormatTok);
2656 }
2657 }
2658}
2659
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002660void UnwrappedLineParser::readToken(int LevelDifference) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002661 SmallVector<FormatToken *, 1> Comments;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002662 do {
2663 FormatTok = Tokens->getNextToken();
Alexander Kornienkoc2ee9cf2014-03-13 13:59:48 +00002664 assert(FormatTok);
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002665 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2666 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002667 distributeComments(Comments, FormatTok);
2668 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002669 // If there is an unfinished unwrapped line, we flush the preprocessor
2670 // directives only after that unwrapped line was finished later.
Daniel Jasper29d39d52015-02-08 09:34:49 +00002671 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002672 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
Krasimir Georgiev3e051052017-07-24 14:51:59 +00002673 assert((LevelDifference >= 0 ||
2674 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2675 "LevelDifference makes Line->Level negative");
2676 Line->Level += LevelDifference;
Alexander Kornienkob1be9d62013-04-03 12:38:53 +00002677 // Comments stored before the preprocessor directive need to be output
2678 // before the preprocessor directive, at the same level as the
2679 // preprocessor directive, as we consider them to apply to the directive.
Paul Hoad701a0d72019-03-20 20:49:43 +00002680 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
2681 PPBranchLevel > 0)
2682 Line->Level += PPBranchLevel;
Manuel Klimek1fcbe672014-04-11 12:27:47 +00002683 flushComments(isOnNewLine(*FormatTok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002684 parsePPDirective();
2685 }
Manuel Klimek68b03042014-04-14 09:14:11 +00002686 while (FormatTok->Type == TT_ConflictStart ||
2687 FormatTok->Type == TT_ConflictEnd ||
2688 FormatTok->Type == TT_ConflictAlternative) {
2689 if (FormatTok->Type == TT_ConflictStart) {
2690 conditionalCompilationStart(/*Unreachable=*/false);
2691 } else if (FormatTok->Type == TT_ConflictAlternative) {
2692 conditionalCompilationAlternative();
Daniel Jasperb05a81d2014-05-09 13:11:16 +00002693 } else if (FormatTok->Type == TT_ConflictEnd) {
Manuel Klimek68b03042014-04-14 09:14:11 +00002694 conditionalCompilationEnd();
2695 }
2696 FormatTok = Tokens->getNextToken();
2697 FormatTok->MustBreakBefore = true;
2698 }
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002699
Francois Ferranda98a95c2017-07-28 07:56:14 +00002700 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
Alexander Kornienkof2e02122013-05-24 18:24:24 +00002701 !Line->InPPDirective) {
2702 continue;
2703 }
2704
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002705 if (!FormatTok->Tok.is(tok::comment)) {
2706 distributeComments(Comments, FormatTok);
2707 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002708 return;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002709 }
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002710
2711 Comments.push_back(FormatTok);
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002712 } while (!eof());
Krasimir Georgievf62f9582017-02-08 10:30:44 +00002713
2714 distributeComments(Comments, nullptr);
2715 Comments.clear();
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002716}
2717
Manuel Klimek15dfe7a2013-05-28 11:55:06 +00002718void UnwrappedLineParser::pushToken(FormatToken *Tok) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002719 Line->Tokens.push_back(UnwrappedLineNode(Tok));
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002720 if (MustBreakBeforeNextToken) {
Daniel Jasper9fe0e8d2013-09-05 09:29:45 +00002721 Line->Tokens.back().Tok->MustBreakBefore = true;
Manuel Klimekf92f7bc2013-01-22 16:31:55 +00002722 MustBreakBeforeNextToken = false;
Manuel Klimek1abf7892013-01-04 23:34:14 +00002723 }
Daniel Jasperf7935112012-12-03 18:12:45 +00002724}
2725
Daniel Jasper8d1832e2013-01-07 13:26:07 +00002726} // end namespace format
2727} // end namespace clang