UnwrappedLineParser.cpp 84 KB

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