UnwrappedLineParser.cpp 79 KB

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