UnwrappedLineParser.cpp 85 KB

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