UnwrappedLineParser.cpp 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649
  1. //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// This file contains the implementation of the UnwrappedLineParser,
  12. /// which turns a stream of tokens into UnwrappedLines.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "UnwrappedLineParser.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/Support/Debug.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. #include <algorithm>
  20. #define DEBUG_TYPE "format-parser"
  21. namespace clang {
  22. namespace format {
  23. class FormatTokenSource {
  24. public:
  25. virtual ~FormatTokenSource() {}
  26. virtual FormatToken *getNextToken() = 0;
  27. virtual unsigned getPosition() = 0;
  28. virtual FormatToken *setPosition(unsigned Position) = 0;
  29. };
  30. namespace {
  31. class ScopedDeclarationState {
  32. public:
  33. ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
  34. bool MustBeDeclaration)
  35. : Line(Line), Stack(Stack) {
  36. Line.MustBeDeclaration = MustBeDeclaration;
  37. Stack.push_back(MustBeDeclaration);
  38. }
  39. ~ScopedDeclarationState() {
  40. Stack.pop_back();
  41. if (!Stack.empty())
  42. Line.MustBeDeclaration = Stack.back();
  43. else
  44. Line.MustBeDeclaration = true;
  45. }
  46. private:
  47. UnwrappedLine &Line;
  48. std::vector<bool> &Stack;
  49. };
  50. static bool isLineComment(const FormatToken &FormatTok) {
  51. return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
  52. }
  53. // Checks if \p FormatTok is a line comment that continues the line comment
  54. // \p Previous. The original column of \p MinColumnToken is used to determine
  55. // whether \p FormatTok is indented enough to the right to continue \p Previous.
  56. static bool continuesLineComment(const FormatToken &FormatTok,
  57. const FormatToken *Previous,
  58. const FormatToken *MinColumnToken) {
  59. if (!Previous || !MinColumnToken)
  60. return false;
  61. unsigned MinContinueColumn =
  62. MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
  63. return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
  64. isLineComment(*Previous) &&
  65. FormatTok.OriginalColumn >= MinContinueColumn;
  66. }
  67. class ScopedMacroState : public FormatTokenSource {
  68. public:
  69. ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
  70. FormatToken *&ResetToken)
  71. : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
  72. PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
  73. Token(nullptr), PreviousToken(nullptr) {
  74. FakeEOF.Tok.startToken();
  75. FakeEOF.Tok.setKind(tok::eof);
  76. TokenSource = this;
  77. Line.Level = 0;
  78. Line.InPPDirective = true;
  79. }
  80. ~ScopedMacroState() override {
  81. TokenSource = PreviousTokenSource;
  82. ResetToken = Token;
  83. Line.InPPDirective = false;
  84. Line.Level = PreviousLineLevel;
  85. }
  86. FormatToken *getNextToken() override {
  87. // The \c UnwrappedLineParser guards against this by never calling
  88. // \c getNextToken() after it has encountered the first eof token.
  89. assert(!eof());
  90. PreviousToken = Token;
  91. Token = PreviousTokenSource->getNextToken();
  92. if (eof())
  93. return &FakeEOF;
  94. return Token;
  95. }
  96. unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
  97. FormatToken *setPosition(unsigned Position) override {
  98. PreviousToken = nullptr;
  99. Token = PreviousTokenSource->setPosition(Position);
  100. return Token;
  101. }
  102. private:
  103. bool eof() {
  104. return Token && Token->HasUnescapedNewline &&
  105. !continuesLineComment(*Token, PreviousToken,
  106. /*MinColumnToken=*/PreviousToken);
  107. }
  108. FormatToken FakeEOF;
  109. UnwrappedLine &Line;
  110. FormatTokenSource *&TokenSource;
  111. FormatToken *&ResetToken;
  112. unsigned PreviousLineLevel;
  113. FormatTokenSource *PreviousTokenSource;
  114. FormatToken *Token;
  115. FormatToken *PreviousToken;
  116. };
  117. } // end anonymous namespace
  118. class ScopedLineState {
  119. public:
  120. ScopedLineState(UnwrappedLineParser &Parser,
  121. bool SwitchToPreprocessorLines = false)
  122. : Parser(Parser), OriginalLines(Parser.CurrentLines) {
  123. if (SwitchToPreprocessorLines)
  124. Parser.CurrentLines = &Parser.PreprocessorDirectives;
  125. else if (!Parser.Line->Tokens.empty())
  126. Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
  127. PreBlockLine = std::move(Parser.Line);
  128. Parser.Line = llvm::make_unique<UnwrappedLine>();
  129. Parser.Line->Level = PreBlockLine->Level;
  130. Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
  131. }
  132. ~ScopedLineState() {
  133. if (!Parser.Line->Tokens.empty()) {
  134. Parser.addUnwrappedLine();
  135. }
  136. assert(Parser.Line->Tokens.empty());
  137. Parser.Line = std::move(PreBlockLine);
  138. if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
  139. Parser.MustBreakBeforeNextToken = true;
  140. Parser.CurrentLines = OriginalLines;
  141. }
  142. private:
  143. UnwrappedLineParser &Parser;
  144. std::unique_ptr<UnwrappedLine> PreBlockLine;
  145. SmallVectorImpl<UnwrappedLine> *OriginalLines;
  146. };
  147. class CompoundStatementIndenter {
  148. public:
  149. CompoundStatementIndenter(UnwrappedLineParser *Parser,
  150. const FormatStyle &Style, unsigned &LineLevel)
  151. : LineLevel(LineLevel), OldLineLevel(LineLevel) {
  152. if (Style.BraceWrapping.AfterControlStatement)
  153. Parser->addUnwrappedLine();
  154. if (Style.BraceWrapping.IndentBraces)
  155. ++LineLevel;
  156. }
  157. ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
  158. private:
  159. unsigned &LineLevel;
  160. unsigned OldLineLevel;
  161. };
  162. namespace {
  163. class IndexedTokenSource : public FormatTokenSource {
  164. public:
  165. IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
  166. : Tokens(Tokens), Position(-1) {}
  167. FormatToken *getNextToken() override {
  168. ++Position;
  169. return Tokens[Position];
  170. }
  171. unsigned getPosition() override {
  172. assert(Position >= 0);
  173. return Position;
  174. }
  175. FormatToken *setPosition(unsigned P) override {
  176. Position = P;
  177. return Tokens[Position];
  178. }
  179. void reset() { Position = -1; }
  180. private:
  181. ArrayRef<FormatToken *> Tokens;
  182. int Position;
  183. };
  184. } // end anonymous namespace
  185. UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
  186. const AdditionalKeywords &Keywords,
  187. unsigned FirstStartColumn,
  188. ArrayRef<FormatToken *> Tokens,
  189. UnwrappedLineConsumer &Callback)
  190. : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
  191. CurrentLines(&Lines), Style(Style), Keywords(Keywords),
  192. CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
  193. Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
  194. IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
  195. ? IG_Rejected
  196. : IG_Inited),
  197. IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
  198. void UnwrappedLineParser::reset() {
  199. PPBranchLevel = -1;
  200. IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
  201. ? IG_Rejected
  202. : IG_Inited;
  203. IncludeGuardToken = nullptr;
  204. Line.reset(new UnwrappedLine);
  205. CommentsBeforeNextToken.clear();
  206. FormatTok = nullptr;
  207. MustBreakBeforeNextToken = false;
  208. PreprocessorDirectives.clear();
  209. CurrentLines = &Lines;
  210. DeclarationScopeStack.clear();
  211. PPStack.clear();
  212. Line->FirstStartColumn = FirstStartColumn;
  213. }
  214. void UnwrappedLineParser::parse() {
  215. IndexedTokenSource TokenSource(AllTokens);
  216. Line->FirstStartColumn = FirstStartColumn;
  217. do {
  218. LLVM_DEBUG(llvm::dbgs() << "----\n");
  219. reset();
  220. Tokens = &TokenSource;
  221. TokenSource.reset();
  222. readToken();
  223. parseFile();
  224. // If we found an include guard then all preprocessor directives (other than
  225. // the guard) are over-indented by one.
  226. if (IncludeGuard == IG_Found)
  227. for (auto &Line : Lines)
  228. if (Line.InPPDirective && Line.Level > 0)
  229. --Line.Level;
  230. // Create line with eof token.
  231. pushToken(FormatTok);
  232. addUnwrappedLine();
  233. for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
  234. E = Lines.end();
  235. I != E; ++I) {
  236. Callback.consumeUnwrappedLine(*I);
  237. }
  238. Callback.finishRun();
  239. Lines.clear();
  240. while (!PPLevelBranchIndex.empty() &&
  241. PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
  242. PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
  243. PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
  244. }
  245. if (!PPLevelBranchIndex.empty()) {
  246. ++PPLevelBranchIndex.back();
  247. assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
  248. assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
  249. }
  250. } while (!PPLevelBranchIndex.empty());
  251. }
  252. void UnwrappedLineParser::parseFile() {
  253. // The top-level context in a file always has declarations, except for pre-
  254. // processor directives and JavaScript files.
  255. bool MustBeDeclaration =
  256. !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
  257. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  258. MustBeDeclaration);
  259. if (Style.Language == FormatStyle::LK_TextProto)
  260. parseBracedList();
  261. else
  262. parseLevel(/*HasOpeningBrace=*/false);
  263. // Make sure to format the remaining tokens.
  264. //
  265. // LK_TextProto is special since its top-level is parsed as the body of a
  266. // braced list, which does not necessarily have natural line separators such
  267. // as a semicolon. Comments after the last entry that have been determined to
  268. // not belong to that line, as in:
  269. // key: value
  270. // // endfile comment
  271. // do not have a chance to be put on a line of their own until this point.
  272. // Here we add this newline before end-of-file comments.
  273. if (Style.Language == FormatStyle::LK_TextProto &&
  274. !CommentsBeforeNextToken.empty())
  275. addUnwrappedLine();
  276. flushComments(true);
  277. addUnwrappedLine();
  278. }
  279. void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
  280. bool SwitchLabelEncountered = false;
  281. do {
  282. tok::TokenKind kind = FormatTok->Tok.getKind();
  283. if (FormatTok->Type == TT_MacroBlockBegin) {
  284. kind = tok::l_brace;
  285. } else if (FormatTok->Type == TT_MacroBlockEnd) {
  286. kind = tok::r_brace;
  287. }
  288. switch (kind) {
  289. case tok::comment:
  290. nextToken();
  291. addUnwrappedLine();
  292. break;
  293. case tok::l_brace:
  294. // FIXME: Add parameter whether this can happen - if this happens, we must
  295. // be in a non-declaration context.
  296. if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
  297. continue;
  298. parseBlock(/*MustBeDeclaration=*/false);
  299. addUnwrappedLine();
  300. break;
  301. case tok::r_brace:
  302. if (HasOpeningBrace)
  303. return;
  304. nextToken();
  305. addUnwrappedLine();
  306. break;
  307. case tok::kw_default: {
  308. unsigned StoredPosition = Tokens->getPosition();
  309. FormatToken *Next;
  310. do {
  311. Next = Tokens->getNextToken();
  312. } while (Next && Next->is(tok::comment));
  313. FormatTok = Tokens->setPosition(StoredPosition);
  314. if (Next && Next->isNot(tok::colon)) {
  315. // default not followed by ':' is not a case label; treat it like
  316. // an identifier.
  317. parseStructuralElement();
  318. break;
  319. }
  320. // Else, if it is 'default:', fall through to the case handling.
  321. LLVM_FALLTHROUGH;
  322. }
  323. case tok::kw_case:
  324. if (Style.Language == FormatStyle::LK_JavaScript &&
  325. Line->MustBeDeclaration) {
  326. // A 'case: string' style field declaration.
  327. parseStructuralElement();
  328. break;
  329. }
  330. if (!SwitchLabelEncountered &&
  331. (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
  332. ++Line->Level;
  333. SwitchLabelEncountered = true;
  334. parseStructuralElement();
  335. break;
  336. default:
  337. parseStructuralElement();
  338. break;
  339. }
  340. } while (!eof());
  341. }
  342. void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
  343. // We'll parse forward through the tokens until we hit
  344. // a closing brace or eof - note that getNextToken() will
  345. // parse macros, so this will magically work inside macro
  346. // definitions, too.
  347. unsigned StoredPosition = Tokens->getPosition();
  348. FormatToken *Tok = FormatTok;
  349. const FormatToken *PrevTok = Tok->Previous;
  350. // Keep a stack of positions of lbrace tokens. We will
  351. // update information about whether an lbrace starts a
  352. // braced init list or a different block during the loop.
  353. SmallVector<FormatToken *, 8> LBraceStack;
  354. assert(Tok->Tok.is(tok::l_brace));
  355. do {
  356. // Get next non-comment token.
  357. FormatToken *NextTok;
  358. unsigned ReadTokens = 0;
  359. do {
  360. NextTok = Tokens->getNextToken();
  361. ++ReadTokens;
  362. } while (NextTok->is(tok::comment));
  363. switch (Tok->Tok.getKind()) {
  364. case tok::l_brace:
  365. if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
  366. if (PrevTok->isOneOf(tok::colon, tok::less))
  367. // A ':' indicates this code is in a type, or a braced list
  368. // following a label in an object literal ({a: {b: 1}}).
  369. // A '<' could be an object used in a comparison, but that is nonsense
  370. // code (can never return true), so more likely it is a generic type
  371. // argument (`X<{a: string; b: number}>`).
  372. // The code below could be confused by semicolons between the
  373. // individual members in a type member list, which would normally
  374. // trigger BK_Block. In both cases, this must be parsed as an inline
  375. // braced init.
  376. Tok->BlockKind = BK_BracedInit;
  377. else if (PrevTok->is(tok::r_paren))
  378. // `) { }` can only occur in function or method declarations in JS.
  379. Tok->BlockKind = BK_Block;
  380. } else {
  381. Tok->BlockKind = BK_Unknown;
  382. }
  383. LBraceStack.push_back(Tok);
  384. break;
  385. case tok::r_brace:
  386. if (LBraceStack.empty())
  387. break;
  388. if (LBraceStack.back()->BlockKind == BK_Unknown) {
  389. bool ProbablyBracedList = false;
  390. if (Style.Language == FormatStyle::LK_Proto) {
  391. ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
  392. } else {
  393. // Using OriginalColumn to distinguish between ObjC methods and
  394. // binary operators is a bit hacky.
  395. bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
  396. NextTok->OriginalColumn == 0;
  397. // If there is a comma, semicolon or right paren after the closing
  398. // brace, we assume this is a braced initializer list. Note that
  399. // regardless how we mark inner braces here, we will overwrite the
  400. // BlockKind later if we parse a braced list (where all blocks
  401. // inside are by default braced lists), or when we explicitly detect
  402. // blocks (for example while parsing lambdas).
  403. // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
  404. // braced list in JS.
  405. ProbablyBracedList =
  406. (Style.Language == FormatStyle::LK_JavaScript &&
  407. NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
  408. Keywords.kw_as)) ||
  409. (Style.isCpp() && NextTok->is(tok::l_paren)) ||
  410. NextTok->isOneOf(tok::comma, tok::period, tok::colon,
  411. tok::r_paren, tok::r_square, tok::l_brace,
  412. tok::ellipsis) ||
  413. (NextTok->is(tok::identifier) &&
  414. !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
  415. (NextTok->is(tok::semi) &&
  416. (!ExpectClassBody || LBraceStack.size() != 1)) ||
  417. (NextTok->isBinaryOperator() && !NextIsObjCMethod);
  418. if (NextTok->is(tok::l_square)) {
  419. // We can have an array subscript after a braced init
  420. // list, but C++11 attributes are expected after blocks.
  421. NextTok = Tokens->getNextToken();
  422. ++ReadTokens;
  423. ProbablyBracedList = NextTok->isNot(tok::l_square);
  424. }
  425. }
  426. if (ProbablyBracedList) {
  427. Tok->BlockKind = BK_BracedInit;
  428. LBraceStack.back()->BlockKind = BK_BracedInit;
  429. } else {
  430. Tok->BlockKind = BK_Block;
  431. LBraceStack.back()->BlockKind = BK_Block;
  432. }
  433. }
  434. LBraceStack.pop_back();
  435. break;
  436. case tok::at:
  437. case tok::semi:
  438. case tok::kw_if:
  439. case tok::kw_while:
  440. case tok::kw_for:
  441. case tok::kw_switch:
  442. case tok::kw_try:
  443. case tok::kw___try:
  444. if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
  445. LBraceStack.back()->BlockKind = BK_Block;
  446. break;
  447. default:
  448. break;
  449. }
  450. PrevTok = Tok;
  451. Tok = NextTok;
  452. } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
  453. // Assume other blocks for all unclosed opening braces.
  454. for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
  455. if (LBraceStack[i]->BlockKind == BK_Unknown)
  456. LBraceStack[i]->BlockKind = BK_Block;
  457. }
  458. FormatTok = Tokens->setPosition(StoredPosition);
  459. }
  460. template <class T>
  461. static inline void hash_combine(std::size_t &seed, const T &v) {
  462. std::hash<T> hasher;
  463. seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
  464. }
  465. size_t UnwrappedLineParser::computePPHash() const {
  466. size_t h = 0;
  467. for (const auto &i : PPStack) {
  468. hash_combine(h, size_t(i.Kind));
  469. hash_combine(h, i.Line);
  470. }
  471. return h;
  472. }
  473. void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
  474. bool MunchSemi) {
  475. assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  476. "'{' or macro block token expected");
  477. const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
  478. FormatTok->BlockKind = BK_Block;
  479. size_t PPStartHash = computePPHash();
  480. unsigned InitialLevel = Line->Level;
  481. nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
  482. if (MacroBlock && FormatTok->is(tok::l_paren))
  483. parseParens();
  484. size_t NbPreprocessorDirectives =
  485. CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
  486. addUnwrappedLine();
  487. size_t OpeningLineIndex =
  488. CurrentLines->empty()
  489. ? (UnwrappedLine::kInvalidIndex)
  490. : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
  491. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  492. MustBeDeclaration);
  493. if (AddLevel)
  494. ++Line->Level;
  495. parseLevel(/*HasOpeningBrace=*/true);
  496. if (eof())
  497. return;
  498. if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
  499. : !FormatTok->is(tok::r_brace)) {
  500. Line->Level = InitialLevel;
  501. FormatTok->BlockKind = BK_Block;
  502. return;
  503. }
  504. size_t PPEndHash = computePPHash();
  505. // Munch the closing brace.
  506. nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
  507. if (MacroBlock && FormatTok->is(tok::l_paren))
  508. parseParens();
  509. if (MunchSemi && FormatTok->Tok.is(tok::semi))
  510. nextToken();
  511. Line->Level = InitialLevel;
  512. if (PPStartHash == PPEndHash) {
  513. Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
  514. if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
  515. // Update the opening line to add the forward reference as well
  516. (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
  517. CurrentLines->size() - 1;
  518. }
  519. }
  520. }
  521. static bool isGoogScope(const UnwrappedLine &Line) {
  522. // FIXME: Closure-library specific stuff should not be hard-coded but be
  523. // configurable.
  524. if (Line.Tokens.size() < 4)
  525. return false;
  526. auto I = Line.Tokens.begin();
  527. if (I->Tok->TokenText != "goog")
  528. return false;
  529. ++I;
  530. if (I->Tok->isNot(tok::period))
  531. return false;
  532. ++I;
  533. if (I->Tok->TokenText != "scope")
  534. return false;
  535. ++I;
  536. return I->Tok->is(tok::l_paren);
  537. }
  538. static bool isIIFE(const UnwrappedLine &Line,
  539. const AdditionalKeywords &Keywords) {
  540. // Look for the start of an immediately invoked anonymous function.
  541. // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
  542. // This is commonly done in JavaScript to create a new, anonymous scope.
  543. // Example: (function() { ... })()
  544. if (Line.Tokens.size() < 3)
  545. return false;
  546. auto I = Line.Tokens.begin();
  547. if (I->Tok->isNot(tok::l_paren))
  548. return false;
  549. ++I;
  550. if (I->Tok->isNot(Keywords.kw_function))
  551. return false;
  552. ++I;
  553. return I->Tok->is(tok::l_paren);
  554. }
  555. static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
  556. const FormatToken &InitialToken) {
  557. if (InitialToken.is(tok::kw_namespace))
  558. return Style.BraceWrapping.AfterNamespace;
  559. if (InitialToken.is(tok::kw_class))
  560. return Style.BraceWrapping.AfterClass;
  561. if (InitialToken.is(tok::kw_union))
  562. return Style.BraceWrapping.AfterUnion;
  563. if (InitialToken.is(tok::kw_struct))
  564. return Style.BraceWrapping.AfterStruct;
  565. return false;
  566. }
  567. void UnwrappedLineParser::parseChildBlock() {
  568. FormatTok->BlockKind = BK_Block;
  569. nextToken();
  570. {
  571. bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
  572. (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
  573. ScopedLineState LineState(*this);
  574. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  575. /*MustBeDeclaration=*/false);
  576. Line->Level += SkipIndent ? 0 : 1;
  577. parseLevel(/*HasOpeningBrace=*/true);
  578. flushComments(isOnNewLine(*FormatTok));
  579. Line->Level -= SkipIndent ? 0 : 1;
  580. }
  581. nextToken();
  582. }
  583. void UnwrappedLineParser::parsePPDirective() {
  584. assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
  585. ScopedMacroState MacroState(*Line, Tokens, FormatTok);
  586. nextToken();
  587. if (!FormatTok->Tok.getIdentifierInfo()) {
  588. parsePPUnknown();
  589. return;
  590. }
  591. switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
  592. case tok::pp_define:
  593. parsePPDefine();
  594. return;
  595. case tok::pp_if:
  596. parsePPIf(/*IfDef=*/false);
  597. break;
  598. case tok::pp_ifdef:
  599. case tok::pp_ifndef:
  600. parsePPIf(/*IfDef=*/true);
  601. break;
  602. case tok::pp_else:
  603. parsePPElse();
  604. break;
  605. case tok::pp_elif:
  606. parsePPElIf();
  607. break;
  608. case tok::pp_endif:
  609. parsePPEndIf();
  610. break;
  611. default:
  612. parsePPUnknown();
  613. break;
  614. }
  615. }
  616. void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
  617. size_t Line = CurrentLines->size();
  618. if (CurrentLines == &PreprocessorDirectives)
  619. Line += Lines.size();
  620. if (Unreachable ||
  621. (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
  622. PPStack.push_back({PP_Unreachable, Line});
  623. else
  624. PPStack.push_back({PP_Conditional, Line});
  625. }
  626. void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
  627. ++PPBranchLevel;
  628. assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
  629. if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
  630. PPLevelBranchIndex.push_back(0);
  631. PPLevelBranchCount.push_back(0);
  632. }
  633. PPChainBranchIndex.push(0);
  634. bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
  635. conditionalCompilationCondition(Unreachable || Skip);
  636. }
  637. void UnwrappedLineParser::conditionalCompilationAlternative() {
  638. if (!PPStack.empty())
  639. PPStack.pop_back();
  640. assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
  641. if (!PPChainBranchIndex.empty())
  642. ++PPChainBranchIndex.top();
  643. conditionalCompilationCondition(
  644. PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
  645. PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
  646. }
  647. void UnwrappedLineParser::conditionalCompilationEnd() {
  648. assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
  649. if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
  650. if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
  651. PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
  652. }
  653. }
  654. // Guard against #endif's without #if.
  655. if (PPBranchLevel > -1)
  656. --PPBranchLevel;
  657. if (!PPChainBranchIndex.empty())
  658. PPChainBranchIndex.pop();
  659. if (!PPStack.empty())
  660. PPStack.pop_back();
  661. }
  662. void UnwrappedLineParser::parsePPIf(bool IfDef) {
  663. bool IfNDef = FormatTok->is(tok::pp_ifndef);
  664. nextToken();
  665. bool Unreachable = false;
  666. if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
  667. Unreachable = true;
  668. if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
  669. Unreachable = true;
  670. conditionalCompilationStart(Unreachable);
  671. FormatToken *IfCondition = FormatTok;
  672. // If there's a #ifndef on the first line, and the only lines before it are
  673. // comments, it could be an include guard.
  674. bool MaybeIncludeGuard = IfNDef;
  675. if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
  676. for (auto &Line : Lines) {
  677. if (!Line.Tokens.front().Tok->is(tok::comment)) {
  678. MaybeIncludeGuard = false;
  679. IncludeGuard = IG_Rejected;
  680. break;
  681. }
  682. }
  683. --PPBranchLevel;
  684. parsePPUnknown();
  685. ++PPBranchLevel;
  686. if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
  687. IncludeGuard = IG_IfNdefed;
  688. IncludeGuardToken = IfCondition;
  689. }
  690. }
  691. void UnwrappedLineParser::parsePPElse() {
  692. // If a potential include guard has an #else, it's not an include guard.
  693. if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
  694. IncludeGuard = IG_Rejected;
  695. conditionalCompilationAlternative();
  696. if (PPBranchLevel > -1)
  697. --PPBranchLevel;
  698. parsePPUnknown();
  699. ++PPBranchLevel;
  700. }
  701. void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
  702. void UnwrappedLineParser::parsePPEndIf() {
  703. conditionalCompilationEnd();
  704. parsePPUnknown();
  705. // If the #endif of a potential include guard is the last thing in the file,
  706. // then we found an include guard.
  707. unsigned TokenPosition = Tokens->getPosition();
  708. FormatToken *PeekNext = AllTokens[TokenPosition];
  709. if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
  710. PeekNext->is(tok::eof) &&
  711. Style.IndentPPDirectives != FormatStyle::PPDIS_None)
  712. IncludeGuard = IG_Found;
  713. }
  714. void UnwrappedLineParser::parsePPDefine() {
  715. nextToken();
  716. if (FormatTok->Tok.getKind() != tok::identifier) {
  717. IncludeGuard = IG_Rejected;
  718. IncludeGuardToken = nullptr;
  719. parsePPUnknown();
  720. return;
  721. }
  722. if (IncludeGuard == IG_IfNdefed &&
  723. IncludeGuardToken->TokenText == FormatTok->TokenText) {
  724. IncludeGuard = IG_Defined;
  725. IncludeGuardToken = nullptr;
  726. for (auto &Line : Lines) {
  727. if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
  728. IncludeGuard = IG_Rejected;
  729. break;
  730. }
  731. }
  732. }
  733. nextToken();
  734. if (FormatTok->Tok.getKind() == tok::l_paren &&
  735. FormatTok->WhitespaceRange.getBegin() ==
  736. FormatTok->WhitespaceRange.getEnd()) {
  737. parseParens();
  738. }
  739. if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
  740. Line->Level += PPBranchLevel + 1;
  741. addUnwrappedLine();
  742. ++Line->Level;
  743. // Errors during a preprocessor directive can only affect the layout of the
  744. // preprocessor directive, and thus we ignore them. An alternative approach
  745. // would be to use the same approach we use on the file level (no
  746. // re-indentation if there was a structural error) within the macro
  747. // definition.
  748. parseFile();
  749. }
  750. void UnwrappedLineParser::parsePPUnknown() {
  751. do {
  752. nextToken();
  753. } while (!eof());
  754. if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash)
  755. Line->Level += PPBranchLevel + 1;
  756. addUnwrappedLine();
  757. }
  758. // Here we blacklist certain tokens that are not usually the first token in an
  759. // unwrapped line. This is used in attempt to distinguish macro calls without
  760. // trailing semicolons from other constructs split to several lines.
  761. static bool tokenCanStartNewLine(const clang::Token &Tok) {
  762. // Semicolon can be a null-statement, l_square can be a start of a macro or
  763. // a C++11 attribute, but this doesn't seem to be common.
  764. return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
  765. Tok.isNot(tok::l_square) &&
  766. // Tokens that can only be used as binary operators and a part of
  767. // overloaded operator names.
  768. Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
  769. Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
  770. Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
  771. Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
  772. Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
  773. Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
  774. Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
  775. Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
  776. Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
  777. Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
  778. Tok.isNot(tok::lesslessequal) &&
  779. // Colon is used in labels, base class lists, initializer lists,
  780. // range-based for loops, ternary operator, but should never be the
  781. // first token in an unwrapped line.
  782. Tok.isNot(tok::colon) &&
  783. // 'noexcept' is a trailing annotation.
  784. Tok.isNot(tok::kw_noexcept);
  785. }
  786. static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
  787. const FormatToken *FormatTok) {
  788. // FIXME: This returns true for C/C++ keywords like 'struct'.
  789. return FormatTok->is(tok::identifier) &&
  790. (FormatTok->Tok.getIdentifierInfo() == nullptr ||
  791. !FormatTok->isOneOf(
  792. Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
  793. Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
  794. Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
  795. Keywords.kw_let, Keywords.kw_var, tok::kw_const,
  796. Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
  797. Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
  798. Keywords.kw_from));
  799. }
  800. static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
  801. const FormatToken *FormatTok) {
  802. return FormatTok->Tok.isLiteral() ||
  803. FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
  804. mustBeJSIdent(Keywords, FormatTok);
  805. }
  806. // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
  807. // when encountered after a value (see mustBeJSIdentOrValue).
  808. static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
  809. const FormatToken *FormatTok) {
  810. return FormatTok->isOneOf(
  811. tok::kw_return, Keywords.kw_yield,
  812. // conditionals
  813. tok::kw_if, tok::kw_else,
  814. // loops
  815. tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
  816. // switch/case
  817. tok::kw_switch, tok::kw_case,
  818. // exceptions
  819. tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
  820. // declaration
  821. tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
  822. Keywords.kw_async, Keywords.kw_function,
  823. // import/export
  824. Keywords.kw_import, tok::kw_export);
  825. }
  826. // readTokenWithJavaScriptASI reads the next token and terminates the current
  827. // line if JavaScript Automatic Semicolon Insertion must
  828. // happen between the current token and the next token.
  829. //
  830. // This method is conservative - it cannot cover all edge cases of JavaScript,
  831. // but only aims to correctly handle certain well known cases. It *must not*
  832. // return true in speculative cases.
  833. void UnwrappedLineParser::readTokenWithJavaScriptASI() {
  834. FormatToken *Previous = FormatTok;
  835. readToken();
  836. FormatToken *Next = FormatTok;
  837. bool IsOnSameLine =
  838. CommentsBeforeNextToken.empty()
  839. ? Next->NewlinesBefore == 0
  840. : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
  841. if (IsOnSameLine)
  842. return;
  843. bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
  844. bool PreviousStartsTemplateExpr =
  845. Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
  846. if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
  847. // If the line contains an '@' sign, the previous token might be an
  848. // annotation, which can precede another identifier/value.
  849. bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
  850. [](UnwrappedLineNode &LineNode) {
  851. return LineNode.Tok->is(tok::at);
  852. }) != Line->Tokens.end();
  853. if (HasAt)
  854. return;
  855. }
  856. if (Next->is(tok::exclaim) && PreviousMustBeValue)
  857. return addUnwrappedLine();
  858. bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
  859. bool NextEndsTemplateExpr =
  860. Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
  861. if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
  862. (PreviousMustBeValue ||
  863. Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
  864. tok::minusminus)))
  865. return addUnwrappedLine();
  866. if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
  867. isJSDeclOrStmt(Keywords, Next))
  868. return addUnwrappedLine();
  869. }
  870. void UnwrappedLineParser::parseStructuralElement() {
  871. assert(!FormatTok->is(tok::l_brace));
  872. if (Style.Language == FormatStyle::LK_TableGen &&
  873. FormatTok->is(tok::pp_include)) {
  874. nextToken();
  875. if (FormatTok->is(tok::string_literal))
  876. nextToken();
  877. addUnwrappedLine();
  878. return;
  879. }
  880. switch (FormatTok->Tok.getKind()) {
  881. case tok::kw_asm:
  882. nextToken();
  883. if (FormatTok->is(tok::l_brace)) {
  884. FormatTok->Type = TT_InlineASMBrace;
  885. nextToken();
  886. while (FormatTok && FormatTok->isNot(tok::eof)) {
  887. if (FormatTok->is(tok::r_brace)) {
  888. FormatTok->Type = TT_InlineASMBrace;
  889. nextToken();
  890. addUnwrappedLine();
  891. break;
  892. }
  893. FormatTok->Finalized = true;
  894. nextToken();
  895. }
  896. }
  897. break;
  898. case tok::kw_namespace:
  899. parseNamespace();
  900. return;
  901. case tok::kw_public:
  902. case tok::kw_protected:
  903. case tok::kw_private:
  904. if (Style.Language == FormatStyle::LK_Java ||
  905. Style.Language == FormatStyle::LK_JavaScript)
  906. nextToken();
  907. else
  908. parseAccessSpecifier();
  909. return;
  910. case tok::kw_if:
  911. parseIfThenElse();
  912. return;
  913. case tok::kw_for:
  914. case tok::kw_while:
  915. parseForOrWhileLoop();
  916. return;
  917. case tok::kw_do:
  918. parseDoWhile();
  919. return;
  920. case tok::kw_switch:
  921. if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
  922. // 'switch: string' field declaration.
  923. break;
  924. parseSwitch();
  925. return;
  926. case tok::kw_default:
  927. if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
  928. // 'default: string' field declaration.
  929. break;
  930. nextToken();
  931. if (FormatTok->is(tok::colon)) {
  932. parseLabel();
  933. return;
  934. }
  935. // e.g. "default void f() {}" in a Java interface.
  936. break;
  937. case tok::kw_case:
  938. if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
  939. // 'case: string' field declaration.
  940. break;
  941. parseCaseLabel();
  942. return;
  943. case tok::kw_try:
  944. case tok::kw___try:
  945. parseTryCatch();
  946. return;
  947. case tok::kw_extern:
  948. nextToken();
  949. if (FormatTok->Tok.is(tok::string_literal)) {
  950. nextToken();
  951. if (FormatTok->Tok.is(tok::l_brace)) {
  952. if (Style.BraceWrapping.AfterExternBlock) {
  953. addUnwrappedLine();
  954. parseBlock(/*MustBeDeclaration=*/true);
  955. } else {
  956. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
  957. }
  958. addUnwrappedLine();
  959. return;
  960. }
  961. }
  962. break;
  963. case tok::kw_export:
  964. if (Style.Language == FormatStyle::LK_JavaScript) {
  965. parseJavaScriptEs6ImportExport();
  966. return;
  967. }
  968. if (!Style.isCpp())
  969. break;
  970. // Handle C++ "(inline|export) namespace".
  971. LLVM_FALLTHROUGH;
  972. case tok::kw_inline:
  973. nextToken();
  974. if (FormatTok->Tok.is(tok::kw_namespace)) {
  975. parseNamespace();
  976. return;
  977. }
  978. break;
  979. case tok::identifier:
  980. if (FormatTok->is(TT_ForEachMacro)) {
  981. parseForOrWhileLoop();
  982. return;
  983. }
  984. if (FormatTok->is(TT_MacroBlockBegin)) {
  985. parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
  986. /*MunchSemi=*/false);
  987. return;
  988. }
  989. if (FormatTok->is(Keywords.kw_import)) {
  990. if (Style.Language == FormatStyle::LK_JavaScript) {
  991. parseJavaScriptEs6ImportExport();
  992. return;
  993. }
  994. if (Style.Language == FormatStyle::LK_Proto) {
  995. nextToken();
  996. if (FormatTok->is(tok::kw_public))
  997. nextToken();
  998. if (!FormatTok->is(tok::string_literal))
  999. return;
  1000. nextToken();
  1001. if (FormatTok->is(tok::semi))
  1002. nextToken();
  1003. addUnwrappedLine();
  1004. return;
  1005. }
  1006. }
  1007. if (Style.isCpp() &&
  1008. FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
  1009. Keywords.kw_slots, Keywords.kw_qslots)) {
  1010. nextToken();
  1011. if (FormatTok->is(tok::colon)) {
  1012. nextToken();
  1013. addUnwrappedLine();
  1014. return;
  1015. }
  1016. }
  1017. // In all other cases, parse the declaration.
  1018. break;
  1019. default:
  1020. break;
  1021. }
  1022. do {
  1023. const FormatToken *Previous = FormatTok->Previous;
  1024. switch (FormatTok->Tok.getKind()) {
  1025. case tok::at:
  1026. nextToken();
  1027. if (FormatTok->Tok.is(tok::l_brace)) {
  1028. nextToken();
  1029. parseBracedList();
  1030. break;
  1031. }
  1032. switch (FormatTok->Tok.getObjCKeywordID()) {
  1033. case tok::objc_public:
  1034. case tok::objc_protected:
  1035. case tok::objc_package:
  1036. case tok::objc_private:
  1037. return parseAccessSpecifier();
  1038. case tok::objc_interface:
  1039. case tok::objc_implementation:
  1040. return parseObjCInterfaceOrImplementation();
  1041. case tok::objc_protocol:
  1042. if (parseObjCProtocol())
  1043. return;
  1044. break;
  1045. case tok::objc_end:
  1046. return; // Handled by the caller.
  1047. case tok::objc_optional:
  1048. case tok::objc_required:
  1049. nextToken();
  1050. addUnwrappedLine();
  1051. return;
  1052. case tok::objc_autoreleasepool:
  1053. nextToken();
  1054. if (FormatTok->Tok.is(tok::l_brace)) {
  1055. if (Style.BraceWrapping.AfterControlStatement)
  1056. addUnwrappedLine();
  1057. parseBlock(/*MustBeDeclaration=*/false);
  1058. }
  1059. addUnwrappedLine();
  1060. return;
  1061. case tok::objc_synchronized:
  1062. nextToken();
  1063. if (FormatTok->Tok.is(tok::l_paren))
  1064. // Skip synchronization object
  1065. parseParens();
  1066. if (FormatTok->Tok.is(tok::l_brace)) {
  1067. if (Style.BraceWrapping.AfterControlStatement)
  1068. addUnwrappedLine();
  1069. parseBlock(/*MustBeDeclaration=*/false);
  1070. }
  1071. addUnwrappedLine();
  1072. return;
  1073. case tok::objc_try:
  1074. // This branch isn't strictly necessary (the kw_try case below would
  1075. // do this too after the tok::at is parsed above). But be explicit.
  1076. parseTryCatch();
  1077. return;
  1078. default:
  1079. break;
  1080. }
  1081. break;
  1082. case tok::kw_enum:
  1083. // Ignore if this is part of "template <enum ...".
  1084. if (Previous && Previous->is(tok::less)) {
  1085. nextToken();
  1086. break;
  1087. }
  1088. // parseEnum falls through and does not yet add an unwrapped line as an
  1089. // enum definition can start a structural element.
  1090. if (!parseEnum())
  1091. break;
  1092. // This only applies for C++.
  1093. if (!Style.isCpp()) {
  1094. addUnwrappedLine();
  1095. return;
  1096. }
  1097. break;
  1098. case tok::kw_typedef:
  1099. nextToken();
  1100. if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
  1101. Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
  1102. parseEnum();
  1103. break;
  1104. case tok::kw_struct:
  1105. case tok::kw_union:
  1106. case tok::kw_class:
  1107. // parseRecord falls through and does not yet add an unwrapped line as a
  1108. // record declaration or definition can start a structural element.
  1109. parseRecord();
  1110. // This does not apply for Java and JavaScript.
  1111. if (Style.Language == FormatStyle::LK_Java ||
  1112. Style.Language == FormatStyle::LK_JavaScript) {
  1113. if (FormatTok->is(tok::semi))
  1114. nextToken();
  1115. addUnwrappedLine();
  1116. return;
  1117. }
  1118. break;
  1119. case tok::period:
  1120. nextToken();
  1121. // In Java, classes have an implicit static member "class".
  1122. if (Style.Language == FormatStyle::LK_Java && FormatTok &&
  1123. FormatTok->is(tok::kw_class))
  1124. nextToken();
  1125. if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
  1126. FormatTok->Tok.getIdentifierInfo())
  1127. // JavaScript only has pseudo keywords, all keywords are allowed to
  1128. // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
  1129. nextToken();
  1130. break;
  1131. case tok::semi:
  1132. nextToken();
  1133. addUnwrappedLine();
  1134. return;
  1135. case tok::r_brace:
  1136. addUnwrappedLine();
  1137. return;
  1138. case tok::l_paren:
  1139. parseParens();
  1140. break;
  1141. case tok::kw_operator:
  1142. nextToken();
  1143. if (FormatTok->isBinaryOperator())
  1144. nextToken();
  1145. break;
  1146. case tok::caret:
  1147. nextToken();
  1148. if (FormatTok->Tok.isAnyIdentifier() ||
  1149. FormatTok->isSimpleTypeSpecifier())
  1150. nextToken();
  1151. if (FormatTok->is(tok::l_paren))
  1152. parseParens();
  1153. if (FormatTok->is(tok::l_brace))
  1154. parseChildBlock();
  1155. break;
  1156. case tok::l_brace:
  1157. if (!tryToParseBracedList()) {
  1158. // A block outside of parentheses must be the last part of a
  1159. // structural element.
  1160. // FIXME: Figure out cases where this is not true, and add projections
  1161. // for them (the one we know is missing are lambdas).
  1162. if (Style.BraceWrapping.AfterFunction)
  1163. addUnwrappedLine();
  1164. FormatTok->Type = TT_FunctionLBrace;
  1165. parseBlock(/*MustBeDeclaration=*/false);
  1166. addUnwrappedLine();
  1167. return;
  1168. }
  1169. // Otherwise this was a braced init list, and the structural
  1170. // element continues.
  1171. break;
  1172. case tok::kw_try:
  1173. // We arrive here when parsing function-try blocks.
  1174. if (Style.BraceWrapping.AfterFunction)
  1175. addUnwrappedLine();
  1176. parseTryCatch();
  1177. return;
  1178. case tok::identifier: {
  1179. if (FormatTok->is(TT_MacroBlockEnd)) {
  1180. addUnwrappedLine();
  1181. return;
  1182. }
  1183. // Function declarations (as opposed to function expressions) are parsed
  1184. // on their own unwrapped line by continuing this loop. Function
  1185. // expressions (functions that are not on their own line) must not create
  1186. // a new unwrapped line, so they are special cased below.
  1187. size_t TokenCount = Line->Tokens.size();
  1188. if (Style.Language == FormatStyle::LK_JavaScript &&
  1189. FormatTok->is(Keywords.kw_function) &&
  1190. (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
  1191. Keywords.kw_async)))) {
  1192. tryToParseJSFunction();
  1193. break;
  1194. }
  1195. if ((Style.Language == FormatStyle::LK_JavaScript ||
  1196. Style.Language == FormatStyle::LK_Java) &&
  1197. FormatTok->is(Keywords.kw_interface)) {
  1198. if (Style.Language == FormatStyle::LK_JavaScript) {
  1199. // In JavaScript/TypeScript, "interface" can be used as a standalone
  1200. // identifier, e.g. in `var interface = 1;`. If "interface" is
  1201. // followed by another identifier, it is very like to be an actual
  1202. // interface declaration.
  1203. unsigned StoredPosition = Tokens->getPosition();
  1204. FormatToken *Next = Tokens->getNextToken();
  1205. FormatTok = Tokens->setPosition(StoredPosition);
  1206. if (Next && !mustBeJSIdent(Keywords, Next)) {
  1207. nextToken();
  1208. break;
  1209. }
  1210. }
  1211. parseRecord();
  1212. addUnwrappedLine();
  1213. return;
  1214. }
  1215. // See if the following token should start a new unwrapped line.
  1216. StringRef Text = FormatTok->TokenText;
  1217. nextToken();
  1218. if (Line->Tokens.size() == 1 &&
  1219. // JS doesn't have macros, and within classes colons indicate fields,
  1220. // not labels.
  1221. Style.Language != FormatStyle::LK_JavaScript) {
  1222. if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
  1223. Line->Tokens.begin()->Tok->MustBreakBefore = true;
  1224. parseLabel();
  1225. return;
  1226. }
  1227. // Recognize function-like macro usages without trailing semicolon as
  1228. // well as free-standing macros like Q_OBJECT.
  1229. bool FunctionLike = FormatTok->is(tok::l_paren);
  1230. if (FunctionLike)
  1231. parseParens();
  1232. bool FollowedByNewline =
  1233. CommentsBeforeNextToken.empty()
  1234. ? FormatTok->NewlinesBefore > 0
  1235. : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
  1236. if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
  1237. tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
  1238. addUnwrappedLine();
  1239. return;
  1240. }
  1241. }
  1242. break;
  1243. }
  1244. case tok::equal:
  1245. // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
  1246. // TT_JsFatArrow. The always start an expression or a child block if
  1247. // followed by a curly.
  1248. if (FormatTok->is(TT_JsFatArrow)) {
  1249. nextToken();
  1250. if (FormatTok->is(tok::l_brace))
  1251. parseChildBlock();
  1252. break;
  1253. }
  1254. nextToken();
  1255. if (FormatTok->Tok.is(tok::l_brace)) {
  1256. nextToken();
  1257. parseBracedList();
  1258. } else if (Style.Language == FormatStyle::LK_Proto &&
  1259. FormatTok->Tok.is(tok::less)) {
  1260. nextToken();
  1261. parseBracedList(/*ContinueOnSemicolons=*/false,
  1262. /*ClosingBraceKind=*/tok::greater);
  1263. }
  1264. break;
  1265. case tok::l_square:
  1266. parseSquare();
  1267. break;
  1268. case tok::kw_new:
  1269. parseNew();
  1270. break;
  1271. default:
  1272. nextToken();
  1273. break;
  1274. }
  1275. } while (!eof());
  1276. }
  1277. bool UnwrappedLineParser::tryToParseLambda() {
  1278. if (!Style.isCpp()) {
  1279. nextToken();
  1280. return false;
  1281. }
  1282. assert(FormatTok->is(tok::l_square));
  1283. FormatToken &LSquare = *FormatTok;
  1284. if (!tryToParseLambdaIntroducer())
  1285. return false;
  1286. while (FormatTok->isNot(tok::l_brace)) {
  1287. if (FormatTok->isSimpleTypeSpecifier()) {
  1288. nextToken();
  1289. continue;
  1290. }
  1291. switch (FormatTok->Tok.getKind()) {
  1292. case tok::l_brace:
  1293. break;
  1294. case tok::l_paren:
  1295. parseParens();
  1296. break;
  1297. case tok::amp:
  1298. case tok::star:
  1299. case tok::kw_const:
  1300. case tok::comma:
  1301. case tok::less:
  1302. case tok::greater:
  1303. case tok::identifier:
  1304. case tok::numeric_constant:
  1305. case tok::coloncolon:
  1306. case tok::kw_mutable:
  1307. nextToken();
  1308. break;
  1309. case tok::arrow:
  1310. FormatTok->Type = TT_LambdaArrow;
  1311. nextToken();
  1312. break;
  1313. default:
  1314. return true;
  1315. }
  1316. }
  1317. LSquare.Type = TT_LambdaLSquare;
  1318. parseChildBlock();
  1319. return true;
  1320. }
  1321. bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
  1322. const FormatToken *Previous = FormatTok->Previous;
  1323. if (Previous &&
  1324. (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
  1325. tok::kw_delete, tok::l_square) ||
  1326. FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
  1327. Previous->isSimpleTypeSpecifier())) {
  1328. nextToken();
  1329. return false;
  1330. }
  1331. nextToken();
  1332. if (FormatTok->is(tok::l_square)) {
  1333. return false;
  1334. }
  1335. parseSquare(/*LambdaIntroducer=*/true);
  1336. return true;
  1337. }
  1338. void UnwrappedLineParser::tryToParseJSFunction() {
  1339. assert(FormatTok->is(Keywords.kw_function) ||
  1340. FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
  1341. if (FormatTok->is(Keywords.kw_async))
  1342. nextToken();
  1343. // Consume "function".
  1344. nextToken();
  1345. // Consume * (generator function). Treat it like C++'s overloaded operators.
  1346. if (FormatTok->is(tok::star)) {
  1347. FormatTok->Type = TT_OverloadedOperator;
  1348. nextToken();
  1349. }
  1350. // Consume function name.
  1351. if (FormatTok->is(tok::identifier))
  1352. nextToken();
  1353. if (FormatTok->isNot(tok::l_paren))
  1354. return;
  1355. // Parse formal parameter list.
  1356. parseParens();
  1357. if (FormatTok->is(tok::colon)) {
  1358. // Parse a type definition.
  1359. nextToken();
  1360. // Eat the type declaration. For braced inline object types, balance braces,
  1361. // otherwise just parse until finding an l_brace for the function body.
  1362. if (FormatTok->is(tok::l_brace))
  1363. tryToParseBracedList();
  1364. else
  1365. while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
  1366. nextToken();
  1367. }
  1368. if (FormatTok->is(tok::semi))
  1369. return;
  1370. parseChildBlock();
  1371. }
  1372. bool UnwrappedLineParser::tryToParseBracedList() {
  1373. if (FormatTok->BlockKind == BK_Unknown)
  1374. calculateBraceTypes();
  1375. assert(FormatTok->BlockKind != BK_Unknown);
  1376. if (FormatTok->BlockKind == BK_Block)
  1377. return false;
  1378. nextToken();
  1379. parseBracedList();
  1380. return true;
  1381. }
  1382. bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
  1383. tok::TokenKind ClosingBraceKind) {
  1384. bool HasError = false;
  1385. // FIXME: Once we have an expression parser in the UnwrappedLineParser,
  1386. // replace this by using parseAssigmentExpression() inside.
  1387. do {
  1388. if (Style.Language == FormatStyle::LK_JavaScript) {
  1389. if (FormatTok->is(Keywords.kw_function) ||
  1390. FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
  1391. tryToParseJSFunction();
  1392. continue;
  1393. }
  1394. if (FormatTok->is(TT_JsFatArrow)) {
  1395. nextToken();
  1396. // Fat arrows can be followed by simple expressions or by child blocks
  1397. // in curly braces.
  1398. if (FormatTok->is(tok::l_brace)) {
  1399. parseChildBlock();
  1400. continue;
  1401. }
  1402. }
  1403. if (FormatTok->is(tok::l_brace)) {
  1404. // Could be a method inside of a braced list `{a() { return 1; }}`.
  1405. if (tryToParseBracedList())
  1406. continue;
  1407. parseChildBlock();
  1408. }
  1409. }
  1410. if (FormatTok->Tok.getKind() == ClosingBraceKind) {
  1411. nextToken();
  1412. return !HasError;
  1413. }
  1414. switch (FormatTok->Tok.getKind()) {
  1415. case tok::caret:
  1416. nextToken();
  1417. if (FormatTok->is(tok::l_brace)) {
  1418. parseChildBlock();
  1419. }
  1420. break;
  1421. case tok::l_square:
  1422. tryToParseLambda();
  1423. break;
  1424. case tok::l_paren:
  1425. parseParens();
  1426. // JavaScript can just have free standing methods and getters/setters in
  1427. // object literals. Detect them by a "{" following ")".
  1428. if (Style.Language == FormatStyle::LK_JavaScript) {
  1429. if (FormatTok->is(tok::l_brace))
  1430. parseChildBlock();
  1431. break;
  1432. }
  1433. break;
  1434. case tok::l_brace:
  1435. // Assume there are no blocks inside a braced init list apart
  1436. // from the ones we explicitly parse out (like lambdas).
  1437. FormatTok->BlockKind = BK_BracedInit;
  1438. nextToken();
  1439. parseBracedList();
  1440. break;
  1441. case tok::less:
  1442. if (Style.Language == FormatStyle::LK_Proto) {
  1443. nextToken();
  1444. parseBracedList(/*ContinueOnSemicolons=*/false,
  1445. /*ClosingBraceKind=*/tok::greater);
  1446. } else {
  1447. nextToken();
  1448. }
  1449. break;
  1450. case tok::semi:
  1451. // JavaScript (or more precisely TypeScript) can have semicolons in braced
  1452. // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
  1453. // used for error recovery if we have otherwise determined that this is
  1454. // a braced list.
  1455. if (Style.Language == FormatStyle::LK_JavaScript) {
  1456. nextToken();
  1457. break;
  1458. }
  1459. HasError = true;
  1460. if (!ContinueOnSemicolons)
  1461. return !HasError;
  1462. nextToken();
  1463. break;
  1464. case tok::comma:
  1465. nextToken();
  1466. break;
  1467. default:
  1468. nextToken();
  1469. break;
  1470. }
  1471. } while (!eof());
  1472. return false;
  1473. }
  1474. void UnwrappedLineParser::parseParens() {
  1475. assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
  1476. nextToken();
  1477. do {
  1478. switch (FormatTok->Tok.getKind()) {
  1479. case tok::l_paren:
  1480. parseParens();
  1481. if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
  1482. parseChildBlock();
  1483. break;
  1484. case tok::r_paren:
  1485. nextToken();
  1486. return;
  1487. case tok::r_brace:
  1488. // A "}" inside parenthesis is an error if there wasn't a matching "{".
  1489. return;
  1490. case tok::l_square:
  1491. tryToParseLambda();
  1492. break;
  1493. case tok::l_brace:
  1494. if (!tryToParseBracedList())
  1495. parseChildBlock();
  1496. break;
  1497. case tok::at:
  1498. nextToken();
  1499. if (FormatTok->Tok.is(tok::l_brace)) {
  1500. nextToken();
  1501. parseBracedList();
  1502. }
  1503. break;
  1504. case tok::kw_class:
  1505. if (Style.Language == FormatStyle::LK_JavaScript)
  1506. parseRecord(/*ParseAsExpr=*/true);
  1507. else
  1508. nextToken();
  1509. break;
  1510. case tok::identifier:
  1511. if (Style.Language == FormatStyle::LK_JavaScript &&
  1512. (FormatTok->is(Keywords.kw_function) ||
  1513. FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
  1514. tryToParseJSFunction();
  1515. else
  1516. nextToken();
  1517. break;
  1518. default:
  1519. nextToken();
  1520. break;
  1521. }
  1522. } while (!eof());
  1523. }
  1524. void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
  1525. if (!LambdaIntroducer) {
  1526. assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
  1527. if (tryToParseLambda())
  1528. return;
  1529. }
  1530. do {
  1531. switch (FormatTok->Tok.getKind()) {
  1532. case tok::l_paren:
  1533. parseParens();
  1534. break;
  1535. case tok::r_square:
  1536. nextToken();
  1537. return;
  1538. case tok::r_brace:
  1539. // A "}" inside parenthesis is an error if there wasn't a matching "{".
  1540. return;
  1541. case tok::l_square:
  1542. parseSquare();
  1543. break;
  1544. case tok::l_brace: {
  1545. if (!tryToParseBracedList())
  1546. parseChildBlock();
  1547. break;
  1548. }
  1549. case tok::at:
  1550. nextToken();
  1551. if (FormatTok->Tok.is(tok::l_brace)) {
  1552. nextToken();
  1553. parseBracedList();
  1554. }
  1555. break;
  1556. default:
  1557. nextToken();
  1558. break;
  1559. }
  1560. } while (!eof());
  1561. }
  1562. void UnwrappedLineParser::parseIfThenElse() {
  1563. assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
  1564. nextToken();
  1565. if (FormatTok->Tok.is(tok::kw_constexpr))
  1566. nextToken();
  1567. if (FormatTok->Tok.is(tok::l_paren))
  1568. parseParens();
  1569. bool NeedsUnwrappedLine = false;
  1570. if (FormatTok->Tok.is(tok::l_brace)) {
  1571. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1572. parseBlock(/*MustBeDeclaration=*/false);
  1573. if (Style.BraceWrapping.BeforeElse)
  1574. addUnwrappedLine();
  1575. else
  1576. NeedsUnwrappedLine = true;
  1577. } else {
  1578. addUnwrappedLine();
  1579. ++Line->Level;
  1580. parseStructuralElement();
  1581. --Line->Level;
  1582. }
  1583. if (FormatTok->Tok.is(tok::kw_else)) {
  1584. nextToken();
  1585. if (FormatTok->Tok.is(tok::l_brace)) {
  1586. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1587. parseBlock(/*MustBeDeclaration=*/false);
  1588. addUnwrappedLine();
  1589. } else if (FormatTok->Tok.is(tok::kw_if)) {
  1590. parseIfThenElse();
  1591. } else {
  1592. addUnwrappedLine();
  1593. ++Line->Level;
  1594. parseStructuralElement();
  1595. if (FormatTok->is(tok::eof))
  1596. addUnwrappedLine();
  1597. --Line->Level;
  1598. }
  1599. } else if (NeedsUnwrappedLine) {
  1600. addUnwrappedLine();
  1601. }
  1602. }
  1603. void UnwrappedLineParser::parseTryCatch() {
  1604. assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
  1605. nextToken();
  1606. bool NeedsUnwrappedLine = false;
  1607. if (FormatTok->is(tok::colon)) {
  1608. // We are in a function try block, what comes is an initializer list.
  1609. nextToken();
  1610. while (FormatTok->is(tok::identifier)) {
  1611. nextToken();
  1612. if (FormatTok->is(tok::l_paren))
  1613. parseParens();
  1614. if (FormatTok->is(tok::comma))
  1615. nextToken();
  1616. }
  1617. }
  1618. // Parse try with resource.
  1619. if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
  1620. parseParens();
  1621. }
  1622. if (FormatTok->is(tok::l_brace)) {
  1623. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1624. parseBlock(/*MustBeDeclaration=*/false);
  1625. if (Style.BraceWrapping.BeforeCatch) {
  1626. addUnwrappedLine();
  1627. } else {
  1628. NeedsUnwrappedLine = true;
  1629. }
  1630. } else if (!FormatTok->is(tok::kw_catch)) {
  1631. // The C++ standard requires a compound-statement after a try.
  1632. // If there's none, we try to assume there's a structuralElement
  1633. // and try to continue.
  1634. addUnwrappedLine();
  1635. ++Line->Level;
  1636. parseStructuralElement();
  1637. --Line->Level;
  1638. }
  1639. while (1) {
  1640. if (FormatTok->is(tok::at))
  1641. nextToken();
  1642. if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
  1643. tok::kw___finally) ||
  1644. ((Style.Language == FormatStyle::LK_Java ||
  1645. Style.Language == FormatStyle::LK_JavaScript) &&
  1646. FormatTok->is(Keywords.kw_finally)) ||
  1647. (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
  1648. FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
  1649. break;
  1650. nextToken();
  1651. while (FormatTok->isNot(tok::l_brace)) {
  1652. if (FormatTok->is(tok::l_paren)) {
  1653. parseParens();
  1654. continue;
  1655. }
  1656. if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
  1657. return;
  1658. nextToken();
  1659. }
  1660. NeedsUnwrappedLine = false;
  1661. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1662. parseBlock(/*MustBeDeclaration=*/false);
  1663. if (Style.BraceWrapping.BeforeCatch)
  1664. addUnwrappedLine();
  1665. else
  1666. NeedsUnwrappedLine = true;
  1667. }
  1668. if (NeedsUnwrappedLine)
  1669. addUnwrappedLine();
  1670. }
  1671. void UnwrappedLineParser::parseNamespace() {
  1672. assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
  1673. const FormatToken &InitialToken = *FormatTok;
  1674. nextToken();
  1675. while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
  1676. nextToken();
  1677. if (FormatTok->Tok.is(tok::l_brace)) {
  1678. if (ShouldBreakBeforeBrace(Style, InitialToken))
  1679. addUnwrappedLine();
  1680. bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
  1681. (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
  1682. DeclarationScopeStack.size() > 1);
  1683. parseBlock(/*MustBeDeclaration=*/true, AddLevel);
  1684. // Munch the semicolon after a namespace. This is more common than one would
  1685. // think. Puttin the semicolon into its own line is very ugly.
  1686. if (FormatTok->Tok.is(tok::semi))
  1687. nextToken();
  1688. addUnwrappedLine();
  1689. }
  1690. // FIXME: Add error handling.
  1691. }
  1692. void UnwrappedLineParser::parseNew() {
  1693. assert(FormatTok->is(tok::kw_new) && "'new' expected");
  1694. nextToken();
  1695. if (Style.Language != FormatStyle::LK_Java)
  1696. return;
  1697. // In Java, we can parse everything up to the parens, which aren't optional.
  1698. do {
  1699. // There should not be a ;, { or } before the new's open paren.
  1700. if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
  1701. return;
  1702. // Consume the parens.
  1703. if (FormatTok->is(tok::l_paren)) {
  1704. parseParens();
  1705. // If there is a class body of an anonymous class, consume that as child.
  1706. if (FormatTok->is(tok::l_brace))
  1707. parseChildBlock();
  1708. return;
  1709. }
  1710. nextToken();
  1711. } while (!eof());
  1712. }
  1713. void UnwrappedLineParser::parseForOrWhileLoop() {
  1714. assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
  1715. "'for', 'while' or foreach macro expected");
  1716. nextToken();
  1717. // JS' for await ( ...
  1718. if (Style.Language == FormatStyle::LK_JavaScript &&
  1719. FormatTok->is(Keywords.kw_await))
  1720. nextToken();
  1721. if (FormatTok->Tok.is(tok::l_paren))
  1722. parseParens();
  1723. if (FormatTok->Tok.is(tok::l_brace)) {
  1724. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1725. parseBlock(/*MustBeDeclaration=*/false);
  1726. addUnwrappedLine();
  1727. } else {
  1728. addUnwrappedLine();
  1729. ++Line->Level;
  1730. parseStructuralElement();
  1731. --Line->Level;
  1732. }
  1733. }
  1734. void UnwrappedLineParser::parseDoWhile() {
  1735. assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
  1736. nextToken();
  1737. if (FormatTok->Tok.is(tok::l_brace)) {
  1738. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1739. parseBlock(/*MustBeDeclaration=*/false);
  1740. if (Style.BraceWrapping.IndentBraces)
  1741. addUnwrappedLine();
  1742. } else {
  1743. addUnwrappedLine();
  1744. ++Line->Level;
  1745. parseStructuralElement();
  1746. --Line->Level;
  1747. }
  1748. // FIXME: Add error handling.
  1749. if (!FormatTok->Tok.is(tok::kw_while)) {
  1750. addUnwrappedLine();
  1751. return;
  1752. }
  1753. nextToken();
  1754. parseStructuralElement();
  1755. }
  1756. void UnwrappedLineParser::parseLabel() {
  1757. nextToken();
  1758. unsigned OldLineLevel = Line->Level;
  1759. if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
  1760. --Line->Level;
  1761. if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
  1762. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1763. parseBlock(/*MustBeDeclaration=*/false);
  1764. if (FormatTok->Tok.is(tok::kw_break)) {
  1765. if (Style.BraceWrapping.AfterControlStatement)
  1766. addUnwrappedLine();
  1767. parseStructuralElement();
  1768. }
  1769. addUnwrappedLine();
  1770. } else {
  1771. if (FormatTok->is(tok::semi))
  1772. nextToken();
  1773. addUnwrappedLine();
  1774. }
  1775. Line->Level = OldLineLevel;
  1776. if (FormatTok->isNot(tok::l_brace)) {
  1777. parseStructuralElement();
  1778. addUnwrappedLine();
  1779. }
  1780. }
  1781. void UnwrappedLineParser::parseCaseLabel() {
  1782. assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
  1783. // FIXME: fix handling of complex expressions here.
  1784. do {
  1785. nextToken();
  1786. } while (!eof() && !FormatTok->Tok.is(tok::colon));
  1787. parseLabel();
  1788. }
  1789. void UnwrappedLineParser::parseSwitch() {
  1790. assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
  1791. nextToken();
  1792. if (FormatTok->Tok.is(tok::l_paren))
  1793. parseParens();
  1794. if (FormatTok->Tok.is(tok::l_brace)) {
  1795. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1796. parseBlock(/*MustBeDeclaration=*/false);
  1797. addUnwrappedLine();
  1798. } else {
  1799. addUnwrappedLine();
  1800. ++Line->Level;
  1801. parseStructuralElement();
  1802. --Line->Level;
  1803. }
  1804. }
  1805. void UnwrappedLineParser::parseAccessSpecifier() {
  1806. nextToken();
  1807. // Understand Qt's slots.
  1808. if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
  1809. nextToken();
  1810. // Otherwise, we don't know what it is, and we'd better keep the next token.
  1811. if (FormatTok->Tok.is(tok::colon))
  1812. nextToken();
  1813. addUnwrappedLine();
  1814. }
  1815. bool UnwrappedLineParser::parseEnum() {
  1816. // Won't be 'enum' for NS_ENUMs.
  1817. if (FormatTok->Tok.is(tok::kw_enum))
  1818. nextToken();
  1819. // In TypeScript, "enum" can also be used as property name, e.g. in interface
  1820. // declarations. An "enum" keyword followed by a colon would be a syntax
  1821. // error and thus assume it is just an identifier.
  1822. if (Style.Language == FormatStyle::LK_JavaScript &&
  1823. FormatTok->isOneOf(tok::colon, tok::question))
  1824. return false;
  1825. // Eat up enum class ...
  1826. if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
  1827. nextToken();
  1828. while (FormatTok->Tok.getIdentifierInfo() ||
  1829. FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
  1830. tok::greater, tok::comma, tok::question)) {
  1831. nextToken();
  1832. // We can have macros or attributes in between 'enum' and the enum name.
  1833. if (FormatTok->is(tok::l_paren))
  1834. parseParens();
  1835. if (FormatTok->is(tok::identifier)) {
  1836. nextToken();
  1837. // If there are two identifiers in a row, this is likely an elaborate
  1838. // return type. In Java, this can be "implements", etc.
  1839. if (Style.isCpp() && FormatTok->is(tok::identifier))
  1840. return false;
  1841. }
  1842. }
  1843. // Just a declaration or something is wrong.
  1844. if (FormatTok->isNot(tok::l_brace))
  1845. return true;
  1846. FormatTok->BlockKind = BK_Block;
  1847. if (Style.Language == FormatStyle::LK_Java) {
  1848. // Java enums are different.
  1849. parseJavaEnumBody();
  1850. return true;
  1851. }
  1852. if (Style.Language == FormatStyle::LK_Proto) {
  1853. parseBlock(/*MustBeDeclaration=*/true);
  1854. return true;
  1855. }
  1856. // Parse enum body.
  1857. nextToken();
  1858. bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
  1859. if (HasError) {
  1860. if (FormatTok->is(tok::semi))
  1861. nextToken();
  1862. addUnwrappedLine();
  1863. }
  1864. return true;
  1865. // There is no addUnwrappedLine() here so that we fall through to parsing a
  1866. // structural element afterwards. Thus, in "enum A {} n, m;",
  1867. // "} n, m;" will end up in one unwrapped line.
  1868. }
  1869. void UnwrappedLineParser::parseJavaEnumBody() {
  1870. // Determine whether the enum is simple, i.e. does not have a semicolon or
  1871. // constants with class bodies. Simple enums can be formatted like braced
  1872. // lists, contracted to a single line, etc.
  1873. unsigned StoredPosition = Tokens->getPosition();
  1874. bool IsSimple = true;
  1875. FormatToken *Tok = Tokens->getNextToken();
  1876. while (Tok) {
  1877. if (Tok->is(tok::r_brace))
  1878. break;
  1879. if (Tok->isOneOf(tok::l_brace, tok::semi)) {
  1880. IsSimple = false;
  1881. break;
  1882. }
  1883. // FIXME: This will also mark enums with braces in the arguments to enum
  1884. // constants as "not simple". This is probably fine in practice, though.
  1885. Tok = Tokens->getNextToken();
  1886. }
  1887. FormatTok = Tokens->setPosition(StoredPosition);
  1888. if (IsSimple) {
  1889. nextToken();
  1890. parseBracedList();
  1891. addUnwrappedLine();
  1892. return;
  1893. }
  1894. // Parse the body of a more complex enum.
  1895. // First add a line for everything up to the "{".
  1896. nextToken();
  1897. addUnwrappedLine();
  1898. ++Line->Level;
  1899. // Parse the enum constants.
  1900. while (FormatTok) {
  1901. if (FormatTok->is(tok::l_brace)) {
  1902. // Parse the constant's class body.
  1903. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
  1904. /*MunchSemi=*/false);
  1905. } else if (FormatTok->is(tok::l_paren)) {
  1906. parseParens();
  1907. } else if (FormatTok->is(tok::comma)) {
  1908. nextToken();
  1909. addUnwrappedLine();
  1910. } else if (FormatTok->is(tok::semi)) {
  1911. nextToken();
  1912. addUnwrappedLine();
  1913. break;
  1914. } else if (FormatTok->is(tok::r_brace)) {
  1915. addUnwrappedLine();
  1916. break;
  1917. } else {
  1918. nextToken();
  1919. }
  1920. }
  1921. // Parse the class body after the enum's ";" if any.
  1922. parseLevel(/*HasOpeningBrace=*/true);
  1923. nextToken();
  1924. --Line->Level;
  1925. addUnwrappedLine();
  1926. }
  1927. void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
  1928. const FormatToken &InitialToken = *FormatTok;
  1929. nextToken();
  1930. // The actual identifier can be a nested name specifier, and in macros
  1931. // it is often token-pasted.
  1932. while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
  1933. tok::kw___attribute, tok::kw___declspec,
  1934. tok::kw_alignas) ||
  1935. ((Style.Language == FormatStyle::LK_Java ||
  1936. Style.Language == FormatStyle::LK_JavaScript) &&
  1937. FormatTok->isOneOf(tok::period, tok::comma))) {
  1938. if (Style.Language == FormatStyle::LK_JavaScript &&
  1939. FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
  1940. // JavaScript/TypeScript supports inline object types in
  1941. // extends/implements positions:
  1942. // class Foo implements {bar: number} { }
  1943. nextToken();
  1944. if (FormatTok->is(tok::l_brace)) {
  1945. tryToParseBracedList();
  1946. continue;
  1947. }
  1948. }
  1949. bool IsNonMacroIdentifier =
  1950. FormatTok->is(tok::identifier) &&
  1951. FormatTok->TokenText != FormatTok->TokenText.upper();
  1952. nextToken();
  1953. // We can have macros or attributes in between 'class' and the class name.
  1954. if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
  1955. parseParens();
  1956. }
  1957. // Note that parsing away template declarations here leads to incorrectly
  1958. // accepting function declarations as record declarations.
  1959. // In general, we cannot solve this problem. Consider:
  1960. // class A<int> B() {}
  1961. // which can be a function definition or a class definition when B() is a
  1962. // macro. If we find enough real-world cases where this is a problem, we
  1963. // can parse for the 'template' keyword in the beginning of the statement,
  1964. // and thus rule out the record production in case there is no template
  1965. // (this would still leave us with an ambiguity between template function
  1966. // and class declarations).
  1967. if (FormatTok->isOneOf(tok::colon, tok::less)) {
  1968. while (!eof()) {
  1969. if (FormatTok->is(tok::l_brace)) {
  1970. calculateBraceTypes(/*ExpectClassBody=*/true);
  1971. if (!tryToParseBracedList())
  1972. break;
  1973. }
  1974. if (FormatTok->Tok.is(tok::semi))
  1975. return;
  1976. nextToken();
  1977. }
  1978. }
  1979. if (FormatTok->Tok.is(tok::l_brace)) {
  1980. if (ParseAsExpr) {
  1981. parseChildBlock();
  1982. } else {
  1983. if (ShouldBreakBeforeBrace(Style, InitialToken))
  1984. addUnwrappedLine();
  1985. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
  1986. /*MunchSemi=*/false);
  1987. }
  1988. }
  1989. // There is no addUnwrappedLine() here so that we fall through to parsing a
  1990. // structural element afterwards. Thus, in "class A {} n, m;",
  1991. // "} n, m;" will end up in one unwrapped line.
  1992. }
  1993. void UnwrappedLineParser::parseObjCMethod() {
  1994. assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
  1995. "'(' or identifier expected.");
  1996. do {
  1997. if (FormatTok->Tok.is(tok::semi)) {
  1998. nextToken();
  1999. addUnwrappedLine();
  2000. return;
  2001. } else if (FormatTok->Tok.is(tok::l_brace)) {
  2002. parseBlock(/*MustBeDeclaration=*/false);
  2003. addUnwrappedLine();
  2004. return;
  2005. } else {
  2006. nextToken();
  2007. }
  2008. } while (!eof());
  2009. }
  2010. void UnwrappedLineParser::parseObjCProtocolList() {
  2011. assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
  2012. do {
  2013. nextToken();
  2014. // Early exit in case someone forgot a close angle.
  2015. if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
  2016. FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
  2017. return;
  2018. } while (!eof() && FormatTok->Tok.isNot(tok::greater));
  2019. nextToken(); // Skip '>'.
  2020. }
  2021. void UnwrappedLineParser::parseObjCUntilAtEnd() {
  2022. do {
  2023. if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
  2024. nextToken();
  2025. addUnwrappedLine();
  2026. break;
  2027. }
  2028. if (FormatTok->is(tok::l_brace)) {
  2029. parseBlock(/*MustBeDeclaration=*/false);
  2030. // In ObjC interfaces, nothing should be following the "}".
  2031. addUnwrappedLine();
  2032. } else if (FormatTok->is(tok::r_brace)) {
  2033. // Ignore stray "}". parseStructuralElement doesn't consume them.
  2034. nextToken();
  2035. addUnwrappedLine();
  2036. } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
  2037. nextToken();
  2038. parseObjCMethod();
  2039. } else {
  2040. parseStructuralElement();
  2041. }
  2042. } while (!eof());
  2043. }
  2044. void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
  2045. assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
  2046. FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
  2047. nextToken();
  2048. nextToken(); // interface name
  2049. // @interface can be followed by a lightweight generic
  2050. // specialization list, then either a base class or a category.
  2051. if (FormatTok->Tok.is(tok::less)) {
  2052. // Unlike protocol lists, generic parameterizations support
  2053. // nested angles:
  2054. //
  2055. // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
  2056. // NSObject <NSCopying, NSSecureCoding>
  2057. //
  2058. // so we need to count how many open angles we have left.
  2059. unsigned NumOpenAngles = 1;
  2060. do {
  2061. nextToken();
  2062. // Early exit in case someone forgot a close angle.
  2063. if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
  2064. FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
  2065. break;
  2066. if (FormatTok->Tok.is(tok::less))
  2067. ++NumOpenAngles;
  2068. else if (FormatTok->Tok.is(tok::greater)) {
  2069. assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
  2070. --NumOpenAngles;
  2071. }
  2072. } while (!eof() && NumOpenAngles != 0);
  2073. nextToken(); // Skip '>'.
  2074. }
  2075. if (FormatTok->Tok.is(tok::colon)) {
  2076. nextToken();
  2077. nextToken(); // base class name
  2078. } else if (FormatTok->Tok.is(tok::l_paren))
  2079. // Skip category, if present.
  2080. parseParens();
  2081. if (FormatTok->Tok.is(tok::less))
  2082. parseObjCProtocolList();
  2083. if (FormatTok->Tok.is(tok::l_brace)) {
  2084. if (Style.BraceWrapping.AfterObjCDeclaration)
  2085. addUnwrappedLine();
  2086. parseBlock(/*MustBeDeclaration=*/true);
  2087. }
  2088. // With instance variables, this puts '}' on its own line. Without instance
  2089. // variables, this ends the @interface line.
  2090. addUnwrappedLine();
  2091. parseObjCUntilAtEnd();
  2092. }
  2093. // Returns true for the declaration/definition form of @protocol,
  2094. // false for the expression form.
  2095. bool UnwrappedLineParser::parseObjCProtocol() {
  2096. assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
  2097. nextToken();
  2098. if (FormatTok->is(tok::l_paren))
  2099. // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
  2100. return false;
  2101. // The definition/declaration form,
  2102. // @protocol Foo
  2103. // - (int)someMethod;
  2104. // @end
  2105. nextToken(); // protocol name
  2106. if (FormatTok->Tok.is(tok::less))
  2107. parseObjCProtocolList();
  2108. // Check for protocol declaration.
  2109. if (FormatTok->Tok.is(tok::semi)) {
  2110. nextToken();
  2111. addUnwrappedLine();
  2112. return true;
  2113. }
  2114. addUnwrappedLine();
  2115. parseObjCUntilAtEnd();
  2116. return true;
  2117. }
  2118. void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
  2119. bool IsImport = FormatTok->is(Keywords.kw_import);
  2120. assert(IsImport || FormatTok->is(tok::kw_export));
  2121. nextToken();
  2122. // Consume the "default" in "export default class/function".
  2123. if (FormatTok->is(tok::kw_default))
  2124. nextToken();
  2125. // Consume "async function", "function" and "default function", so that these
  2126. // get parsed as free-standing JS functions, i.e. do not require a trailing
  2127. // semicolon.
  2128. if (FormatTok->is(Keywords.kw_async))
  2129. nextToken();
  2130. if (FormatTok->is(Keywords.kw_function)) {
  2131. nextToken();
  2132. return;
  2133. }
  2134. // For imports, `export *`, `export {...}`, consume the rest of the line up
  2135. // to the terminating `;`. For everything else, just return and continue
  2136. // parsing the structural element, i.e. the declaration or expression for
  2137. // `export default`.
  2138. if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
  2139. !FormatTok->isStringLiteral())
  2140. return;
  2141. while (!eof()) {
  2142. if (FormatTok->is(tok::semi))
  2143. return;
  2144. if (Line->Tokens.empty()) {
  2145. // Common issue: Automatic Semicolon Insertion wrapped the line, so the
  2146. // import statement should terminate.
  2147. return;
  2148. }
  2149. if (FormatTok->is(tok::l_brace)) {
  2150. FormatTok->BlockKind = BK_Block;
  2151. nextToken();
  2152. parseBracedList();
  2153. } else {
  2154. nextToken();
  2155. }
  2156. }
  2157. }
  2158. LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
  2159. StringRef Prefix = "") {
  2160. llvm::dbgs() << Prefix << "Line(" << Line.Level
  2161. << ", FSC=" << Line.FirstStartColumn << ")"
  2162. << (Line.InPPDirective ? " MACRO" : "") << ": ";
  2163. for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
  2164. E = Line.Tokens.end();
  2165. I != E; ++I) {
  2166. llvm::dbgs() << I->Tok->Tok.getName() << "["
  2167. << "T=" << I->Tok->Type << ", OC=" << I->Tok->OriginalColumn
  2168. << "] ";
  2169. }
  2170. for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
  2171. E = Line.Tokens.end();
  2172. I != E; ++I) {
  2173. const UnwrappedLineNode &Node = *I;
  2174. for (SmallVectorImpl<UnwrappedLine>::const_iterator
  2175. I = Node.Children.begin(),
  2176. E = Node.Children.end();
  2177. I != E; ++I) {
  2178. printDebugInfo(*I, "\nChild: ");
  2179. }
  2180. }
  2181. llvm::dbgs() << "\n";
  2182. }
  2183. void UnwrappedLineParser::addUnwrappedLine() {
  2184. if (Line->Tokens.empty())
  2185. return;
  2186. LLVM_DEBUG({
  2187. if (CurrentLines == &Lines)
  2188. printDebugInfo(*Line);
  2189. });
  2190. CurrentLines->push_back(std::move(*Line));
  2191. Line->Tokens.clear();
  2192. Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
  2193. Line->FirstStartColumn = 0;
  2194. if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
  2195. CurrentLines->append(
  2196. std::make_move_iterator(PreprocessorDirectives.begin()),
  2197. std::make_move_iterator(PreprocessorDirectives.end()));
  2198. PreprocessorDirectives.clear();
  2199. }
  2200. // Disconnect the current token from the last token on the previous line.
  2201. FormatTok->Previous = nullptr;
  2202. }
  2203. bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
  2204. bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
  2205. return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
  2206. FormatTok.NewlinesBefore > 0;
  2207. }
  2208. // Checks if \p FormatTok is a line comment that continues the line comment
  2209. // section on \p Line.
  2210. static bool continuesLineCommentSection(const FormatToken &FormatTok,
  2211. const UnwrappedLine &Line,
  2212. llvm::Regex &CommentPragmasRegex) {
  2213. if (Line.Tokens.empty())
  2214. return false;
  2215. StringRef IndentContent = FormatTok.TokenText;
  2216. if (FormatTok.TokenText.startswith("//") ||
  2217. FormatTok.TokenText.startswith("/*"))
  2218. IndentContent = FormatTok.TokenText.substr(2);
  2219. if (CommentPragmasRegex.match(IndentContent))
  2220. return false;
  2221. // If Line starts with a line comment, then FormatTok continues the comment
  2222. // section if its original column is greater or equal to the original start
  2223. // column of the line.
  2224. //
  2225. // Define the min column token of a line as follows: if a line ends in '{' or
  2226. // contains a '{' followed by a line comment, then the min column token is
  2227. // that '{'. Otherwise, the min column token of the line is the first token of
  2228. // the line.
  2229. //
  2230. // If Line starts with a token other than a line comment, then FormatTok
  2231. // continues the comment section if its original column is greater than the
  2232. // original start column of the min column token of the line.
  2233. //
  2234. // For example, the second line comment continues the first in these cases:
  2235. //
  2236. // // first line
  2237. // // second line
  2238. //
  2239. // and:
  2240. //
  2241. // // first line
  2242. // // second line
  2243. //
  2244. // and:
  2245. //
  2246. // int i; // first line
  2247. // // second line
  2248. //
  2249. // and:
  2250. //
  2251. // do { // first line
  2252. // // second line
  2253. // int i;
  2254. // } while (true);
  2255. //
  2256. // and:
  2257. //
  2258. // enum {
  2259. // a, // first line
  2260. // // second line
  2261. // b
  2262. // };
  2263. //
  2264. // The second line comment doesn't continue the first in these cases:
  2265. //
  2266. // // first line
  2267. // // second line
  2268. //
  2269. // and:
  2270. //
  2271. // int i; // first line
  2272. // // second line
  2273. //
  2274. // and:
  2275. //
  2276. // do { // first line
  2277. // // second line
  2278. // int i;
  2279. // } while (true);
  2280. //
  2281. // and:
  2282. //
  2283. // enum {
  2284. // a, // first line
  2285. // // second line
  2286. // };
  2287. const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
  2288. // Scan for '{//'. If found, use the column of '{' as a min column for line
  2289. // comment section continuation.
  2290. const FormatToken *PreviousToken = nullptr;
  2291. for (const UnwrappedLineNode &Node : Line.Tokens) {
  2292. if (PreviousToken && PreviousToken->is(tok::l_brace) &&
  2293. isLineComment(*Node.Tok)) {
  2294. MinColumnToken = PreviousToken;
  2295. break;
  2296. }
  2297. PreviousToken = Node.Tok;
  2298. // Grab the last newline preceding a token in this unwrapped line.
  2299. if (Node.Tok->NewlinesBefore > 0) {
  2300. MinColumnToken = Node.Tok;
  2301. }
  2302. }
  2303. if (PreviousToken && PreviousToken->is(tok::l_brace)) {
  2304. MinColumnToken = PreviousToken;
  2305. }
  2306. return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
  2307. MinColumnToken);
  2308. }
  2309. void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
  2310. bool JustComments = Line->Tokens.empty();
  2311. for (SmallVectorImpl<FormatToken *>::const_iterator
  2312. I = CommentsBeforeNextToken.begin(),
  2313. E = CommentsBeforeNextToken.end();
  2314. I != E; ++I) {
  2315. // Line comments that belong to the same line comment section are put on the
  2316. // same line since later we might want to reflow content between them.
  2317. // Additional fine-grained breaking of line comment sections is controlled
  2318. // by the class BreakableLineCommentSection in case it is desirable to keep
  2319. // several line comment sections in the same unwrapped line.
  2320. //
  2321. // FIXME: Consider putting separate line comment sections as children to the
  2322. // unwrapped line instead.
  2323. (*I)->ContinuesLineCommentSection =
  2324. continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
  2325. if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
  2326. addUnwrappedLine();
  2327. pushToken(*I);
  2328. }
  2329. if (NewlineBeforeNext && JustComments)
  2330. addUnwrappedLine();
  2331. CommentsBeforeNextToken.clear();
  2332. }
  2333. void UnwrappedLineParser::nextToken(int LevelDifference) {
  2334. if (eof())
  2335. return;
  2336. flushComments(isOnNewLine(*FormatTok));
  2337. pushToken(FormatTok);
  2338. FormatToken *Previous = FormatTok;
  2339. if (Style.Language != FormatStyle::LK_JavaScript)
  2340. readToken(LevelDifference);
  2341. else
  2342. readTokenWithJavaScriptASI();
  2343. FormatTok->Previous = Previous;
  2344. }
  2345. void UnwrappedLineParser::distributeComments(
  2346. const SmallVectorImpl<FormatToken *> &Comments,
  2347. const FormatToken *NextTok) {
  2348. // Whether or not a line comment token continues a line is controlled by
  2349. // the method continuesLineCommentSection, with the following caveat:
  2350. //
  2351. // Define a trail of Comments to be a nonempty proper postfix of Comments such
  2352. // that each comment line from the trail is aligned with the next token, if
  2353. // the next token exists. If a trail exists, the beginning of the maximal
  2354. // trail is marked as a start of a new comment section.
  2355. //
  2356. // For example in this code:
  2357. //
  2358. // int a; // line about a
  2359. // // line 1 about b
  2360. // // line 2 about b
  2361. // int b;
  2362. //
  2363. // the two lines about b form a maximal trail, so there are two sections, the
  2364. // first one consisting of the single comment "// line about a" and the
  2365. // second one consisting of the next two comments.
  2366. if (Comments.empty())
  2367. return;
  2368. bool ShouldPushCommentsInCurrentLine = true;
  2369. bool HasTrailAlignedWithNextToken = false;
  2370. unsigned StartOfTrailAlignedWithNextToken = 0;
  2371. if (NextTok) {
  2372. // We are skipping the first element intentionally.
  2373. for (unsigned i = Comments.size() - 1; i > 0; --i) {
  2374. if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
  2375. HasTrailAlignedWithNextToken = true;
  2376. StartOfTrailAlignedWithNextToken = i;
  2377. }
  2378. }
  2379. }
  2380. for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
  2381. FormatToken *FormatTok = Comments[i];
  2382. if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
  2383. FormatTok->ContinuesLineCommentSection = false;
  2384. } else {
  2385. FormatTok->ContinuesLineCommentSection =
  2386. continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
  2387. }
  2388. if (!FormatTok->ContinuesLineCommentSection &&
  2389. (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
  2390. ShouldPushCommentsInCurrentLine = false;
  2391. }
  2392. if (ShouldPushCommentsInCurrentLine) {
  2393. pushToken(FormatTok);
  2394. } else {
  2395. CommentsBeforeNextToken.push_back(FormatTok);
  2396. }
  2397. }
  2398. }
  2399. void UnwrappedLineParser::readToken(int LevelDifference) {
  2400. SmallVector<FormatToken *, 1> Comments;
  2401. do {
  2402. FormatTok = Tokens->getNextToken();
  2403. assert(FormatTok);
  2404. while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
  2405. (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
  2406. distributeComments(Comments, FormatTok);
  2407. Comments.clear();
  2408. // If there is an unfinished unwrapped line, we flush the preprocessor
  2409. // directives only after that unwrapped line was finished later.
  2410. bool SwitchToPreprocessorLines = !Line->Tokens.empty();
  2411. ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
  2412. assert((LevelDifference >= 0 ||
  2413. static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
  2414. "LevelDifference makes Line->Level negative");
  2415. Line->Level += LevelDifference;
  2416. // Comments stored before the preprocessor directive need to be output
  2417. // before the preprocessor directive, at the same level as the
  2418. // preprocessor directive, as we consider them to apply to the directive.
  2419. flushComments(isOnNewLine(*FormatTok));
  2420. parsePPDirective();
  2421. }
  2422. while (FormatTok->Type == TT_ConflictStart ||
  2423. FormatTok->Type == TT_ConflictEnd ||
  2424. FormatTok->Type == TT_ConflictAlternative) {
  2425. if (FormatTok->Type == TT_ConflictStart) {
  2426. conditionalCompilationStart(/*Unreachable=*/false);
  2427. } else if (FormatTok->Type == TT_ConflictAlternative) {
  2428. conditionalCompilationAlternative();
  2429. } else if (FormatTok->Type == TT_ConflictEnd) {
  2430. conditionalCompilationEnd();
  2431. }
  2432. FormatTok = Tokens->getNextToken();
  2433. FormatTok->MustBreakBefore = true;
  2434. }
  2435. if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
  2436. !Line->InPPDirective) {
  2437. continue;
  2438. }
  2439. if (!FormatTok->Tok.is(tok::comment)) {
  2440. distributeComments(Comments, FormatTok);
  2441. Comments.clear();
  2442. return;
  2443. }
  2444. Comments.push_back(FormatTok);
  2445. } while (!eof());
  2446. distributeComments(Comments, nullptr);
  2447. Comments.clear();
  2448. }
  2449. void UnwrappedLineParser::pushToken(FormatToken *Tok) {
  2450. Line->Tokens.push_back(UnwrappedLineNode(Tok));
  2451. if (MustBreakBeforeNextToken) {
  2452. Line->Tokens.back().Tok->MustBreakBefore = true;
  2453. MustBreakBeforeNextToken = false;
  2454. }
  2455. }
  2456. } // end namespace format
  2457. } // end namespace clang