UnwrappedLineParser.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  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. class ScopedMacroState : public FormatTokenSource {
  50. public:
  51. ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
  52. FormatToken *&ResetToken)
  53. : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
  54. PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
  55. Token(nullptr) {
  56. TokenSource = this;
  57. Line.Level = 0;
  58. Line.InPPDirective = true;
  59. }
  60. ~ScopedMacroState() override {
  61. TokenSource = PreviousTokenSource;
  62. ResetToken = Token;
  63. Line.InPPDirective = false;
  64. Line.Level = PreviousLineLevel;
  65. }
  66. FormatToken *getNextToken() override {
  67. // The \c UnwrappedLineParser guards against this by never calling
  68. // \c getNextToken() after it has encountered the first eof token.
  69. assert(!eof());
  70. Token = PreviousTokenSource->getNextToken();
  71. if (eof())
  72. return getFakeEOF();
  73. return Token;
  74. }
  75. unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
  76. FormatToken *setPosition(unsigned Position) override {
  77. Token = PreviousTokenSource->setPosition(Position);
  78. return Token;
  79. }
  80. private:
  81. bool eof() { return Token && Token->HasUnescapedNewline; }
  82. FormatToken *getFakeEOF() {
  83. static bool EOFInitialized = false;
  84. static FormatToken FormatTok;
  85. if (!EOFInitialized) {
  86. FormatTok.Tok.startToken();
  87. FormatTok.Tok.setKind(tok::eof);
  88. EOFInitialized = true;
  89. }
  90. return &FormatTok;
  91. }
  92. UnwrappedLine &Line;
  93. FormatTokenSource *&TokenSource;
  94. FormatToken *&ResetToken;
  95. unsigned PreviousLineLevel;
  96. FormatTokenSource *PreviousTokenSource;
  97. FormatToken *Token;
  98. };
  99. } // end anonymous namespace
  100. class ScopedLineState {
  101. public:
  102. ScopedLineState(UnwrappedLineParser &Parser,
  103. bool SwitchToPreprocessorLines = false)
  104. : Parser(Parser), OriginalLines(Parser.CurrentLines) {
  105. if (SwitchToPreprocessorLines)
  106. Parser.CurrentLines = &Parser.PreprocessorDirectives;
  107. else if (!Parser.Line->Tokens.empty())
  108. Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
  109. PreBlockLine = std::move(Parser.Line);
  110. Parser.Line = llvm::make_unique<UnwrappedLine>();
  111. Parser.Line->Level = PreBlockLine->Level;
  112. Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
  113. }
  114. ~ScopedLineState() {
  115. if (!Parser.Line->Tokens.empty()) {
  116. Parser.addUnwrappedLine();
  117. }
  118. assert(Parser.Line->Tokens.empty());
  119. Parser.Line = std::move(PreBlockLine);
  120. if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
  121. Parser.MustBreakBeforeNextToken = true;
  122. Parser.CurrentLines = OriginalLines;
  123. }
  124. private:
  125. UnwrappedLineParser &Parser;
  126. std::unique_ptr<UnwrappedLine> PreBlockLine;
  127. SmallVectorImpl<UnwrappedLine> *OriginalLines;
  128. };
  129. class CompoundStatementIndenter {
  130. public:
  131. CompoundStatementIndenter(UnwrappedLineParser *Parser,
  132. const FormatStyle &Style, unsigned &LineLevel)
  133. : LineLevel(LineLevel), OldLineLevel(LineLevel) {
  134. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman) {
  135. Parser->addUnwrappedLine();
  136. } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
  137. Parser->addUnwrappedLine();
  138. ++LineLevel;
  139. }
  140. }
  141. ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
  142. private:
  143. unsigned &LineLevel;
  144. unsigned OldLineLevel;
  145. };
  146. namespace {
  147. class IndexedTokenSource : public FormatTokenSource {
  148. public:
  149. IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
  150. : Tokens(Tokens), Position(-1) {}
  151. FormatToken *getNextToken() override {
  152. ++Position;
  153. return Tokens[Position];
  154. }
  155. unsigned getPosition() override {
  156. assert(Position >= 0);
  157. return Position;
  158. }
  159. FormatToken *setPosition(unsigned P) override {
  160. Position = P;
  161. return Tokens[Position];
  162. }
  163. void reset() { Position = -1; }
  164. private:
  165. ArrayRef<FormatToken *> Tokens;
  166. int Position;
  167. };
  168. } // end anonymous namespace
  169. UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
  170. const AdditionalKeywords &Keywords,
  171. ArrayRef<FormatToken *> Tokens,
  172. UnwrappedLineConsumer &Callback)
  173. : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
  174. CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr),
  175. Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {}
  176. void UnwrappedLineParser::reset() {
  177. PPBranchLevel = -1;
  178. Line.reset(new UnwrappedLine);
  179. CommentsBeforeNextToken.clear();
  180. FormatTok = nullptr;
  181. MustBreakBeforeNextToken = false;
  182. PreprocessorDirectives.clear();
  183. CurrentLines = &Lines;
  184. DeclarationScopeStack.clear();
  185. PPStack.clear();
  186. }
  187. void UnwrappedLineParser::parse() {
  188. IndexedTokenSource TokenSource(AllTokens);
  189. do {
  190. DEBUG(llvm::dbgs() << "----\n");
  191. reset();
  192. Tokens = &TokenSource;
  193. TokenSource.reset();
  194. readToken();
  195. parseFile();
  196. // Create line with eof token.
  197. pushToken(FormatTok);
  198. addUnwrappedLine();
  199. for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
  200. E = Lines.end();
  201. I != E; ++I) {
  202. Callback.consumeUnwrappedLine(*I);
  203. }
  204. Callback.finishRun();
  205. Lines.clear();
  206. while (!PPLevelBranchIndex.empty() &&
  207. PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
  208. PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
  209. PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
  210. }
  211. if (!PPLevelBranchIndex.empty()) {
  212. ++PPLevelBranchIndex.back();
  213. assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
  214. assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
  215. }
  216. } while (!PPLevelBranchIndex.empty());
  217. }
  218. void UnwrappedLineParser::parseFile() {
  219. // The top-level context in a file always has declarations, except for pre-
  220. // processor directives and JavaScript files.
  221. bool MustBeDeclaration =
  222. !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
  223. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  224. MustBeDeclaration);
  225. parseLevel(/*HasOpeningBrace=*/false);
  226. // Make sure to format the remaining tokens.
  227. flushComments(true);
  228. addUnwrappedLine();
  229. }
  230. void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
  231. bool SwitchLabelEncountered = false;
  232. do {
  233. tok::TokenKind kind = FormatTok->Tok.getKind();
  234. if (FormatTok->Type == TT_MacroBlockBegin) {
  235. kind = tok::l_brace;
  236. } else if (FormatTok->Type == TT_MacroBlockEnd) {
  237. kind = tok::r_brace;
  238. }
  239. switch (kind) {
  240. case tok::comment:
  241. nextToken();
  242. addUnwrappedLine();
  243. break;
  244. case tok::l_brace:
  245. // FIXME: Add parameter whether this can happen - if this happens, we must
  246. // be in a non-declaration context.
  247. parseBlock(/*MustBeDeclaration=*/false);
  248. addUnwrappedLine();
  249. break;
  250. case tok::r_brace:
  251. if (HasOpeningBrace)
  252. return;
  253. nextToken();
  254. addUnwrappedLine();
  255. break;
  256. case tok::kw_default:
  257. case tok::kw_case:
  258. if (!SwitchLabelEncountered &&
  259. (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
  260. ++Line->Level;
  261. SwitchLabelEncountered = true;
  262. parseStructuralElement();
  263. break;
  264. default:
  265. parseStructuralElement();
  266. break;
  267. }
  268. } while (!eof());
  269. }
  270. void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
  271. // We'll parse forward through the tokens until we hit
  272. // a closing brace or eof - note that getNextToken() will
  273. // parse macros, so this will magically work inside macro
  274. // definitions, too.
  275. unsigned StoredPosition = Tokens->getPosition();
  276. FormatToken *Tok = FormatTok;
  277. // Keep a stack of positions of lbrace tokens. We will
  278. // update information about whether an lbrace starts a
  279. // braced init list or a different block during the loop.
  280. SmallVector<FormatToken *, 8> LBraceStack;
  281. assert(Tok->Tok.is(tok::l_brace));
  282. do {
  283. // Get next none-comment token.
  284. FormatToken *NextTok;
  285. unsigned ReadTokens = 0;
  286. do {
  287. NextTok = Tokens->getNextToken();
  288. ++ReadTokens;
  289. } while (NextTok->is(tok::comment));
  290. switch (Tok->Tok.getKind()) {
  291. case tok::l_brace:
  292. Tok->BlockKind = BK_Unknown;
  293. LBraceStack.push_back(Tok);
  294. break;
  295. case tok::r_brace:
  296. if (!LBraceStack.empty()) {
  297. if (LBraceStack.back()->BlockKind == BK_Unknown) {
  298. bool ProbablyBracedList = false;
  299. if (Style.Language == FormatStyle::LK_Proto) {
  300. ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
  301. } else {
  302. // Using OriginalColumn to distinguish between ObjC methods and
  303. // binary operators is a bit hacky.
  304. bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
  305. NextTok->OriginalColumn == 0;
  306. // If there is a comma, semicolon or right paren after the closing
  307. // brace, we assume this is a braced initializer list. Note that
  308. // regardless how we mark inner braces here, we will overwrite the
  309. // BlockKind later if we parse a braced list (where all blocks
  310. // inside are by default braced lists), or when we explicitly detect
  311. // blocks (for example while parsing lambdas).
  312. //
  313. // We exclude + and - as they can be ObjC visibility modifiers.
  314. ProbablyBracedList =
  315. NextTok->isOneOf(tok::comma, tok::period, tok::colon,
  316. tok::r_paren, tok::r_square, tok::l_brace,
  317. tok::l_paren, tok::ellipsis) ||
  318. (NextTok->is(tok::semi) &&
  319. (!ExpectClassBody || LBraceStack.size() != 1)) ||
  320. (NextTok->isBinaryOperator() && !NextIsObjCMethod);
  321. }
  322. if (ProbablyBracedList) {
  323. Tok->BlockKind = BK_BracedInit;
  324. LBraceStack.back()->BlockKind = BK_BracedInit;
  325. } else {
  326. Tok->BlockKind = BK_Block;
  327. LBraceStack.back()->BlockKind = BK_Block;
  328. }
  329. }
  330. LBraceStack.pop_back();
  331. }
  332. break;
  333. case tok::at:
  334. case tok::semi:
  335. case tok::kw_if:
  336. case tok::kw_while:
  337. case tok::kw_for:
  338. case tok::kw_switch:
  339. case tok::kw_try:
  340. case tok::kw___try:
  341. if (!LBraceStack.empty())
  342. LBraceStack.back()->BlockKind = BK_Block;
  343. break;
  344. default:
  345. break;
  346. }
  347. Tok = NextTok;
  348. } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
  349. // Assume other blocks for all unclosed opening braces.
  350. for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
  351. if (LBraceStack[i]->BlockKind == BK_Unknown)
  352. LBraceStack[i]->BlockKind = BK_Block;
  353. }
  354. FormatTok = Tokens->setPosition(StoredPosition);
  355. }
  356. void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
  357. bool MunchSemi) {
  358. assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
  359. "'{' or macro block token expected");
  360. const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
  361. unsigned InitialLevel = Line->Level;
  362. nextToken();
  363. if (MacroBlock && FormatTok->is(tok::l_paren))
  364. parseParens();
  365. addUnwrappedLine();
  366. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  367. MustBeDeclaration);
  368. if (AddLevel)
  369. ++Line->Level;
  370. parseLevel(/*HasOpeningBrace=*/true);
  371. if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
  372. : !FormatTok->is(tok::r_brace)) {
  373. Line->Level = InitialLevel;
  374. return;
  375. }
  376. nextToken(); // Munch the closing brace.
  377. if (MacroBlock && FormatTok->is(tok::l_paren))
  378. parseParens();
  379. if (MunchSemi && FormatTok->Tok.is(tok::semi))
  380. nextToken();
  381. Line->Level = InitialLevel;
  382. }
  383. static bool isGoogScope(const UnwrappedLine &Line) {
  384. // FIXME: Closure-library specific stuff should not be hard-coded but be
  385. // configurable.
  386. if (Line.Tokens.size() < 4)
  387. return false;
  388. auto I = Line.Tokens.begin();
  389. if (I->Tok->TokenText != "goog")
  390. return false;
  391. ++I;
  392. if (I->Tok->isNot(tok::period))
  393. return false;
  394. ++I;
  395. if (I->Tok->TokenText != "scope")
  396. return false;
  397. ++I;
  398. return I->Tok->is(tok::l_paren);
  399. }
  400. static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
  401. const FormatToken &InitialToken) {
  402. switch (Style.BreakBeforeBraces) {
  403. case FormatStyle::BS_Linux:
  404. return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class);
  405. case FormatStyle::BS_Mozilla:
  406. return InitialToken.isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union);
  407. case FormatStyle::BS_Allman:
  408. case FormatStyle::BS_GNU:
  409. return true;
  410. default:
  411. return false;
  412. }
  413. }
  414. void UnwrappedLineParser::parseChildBlock() {
  415. FormatTok->BlockKind = BK_Block;
  416. nextToken();
  417. {
  418. bool GoogScope =
  419. Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line);
  420. ScopedLineState LineState(*this);
  421. ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
  422. /*MustBeDeclaration=*/false);
  423. Line->Level += GoogScope ? 0 : 1;
  424. parseLevel(/*HasOpeningBrace=*/true);
  425. flushComments(isOnNewLine(*FormatTok));
  426. Line->Level -= GoogScope ? 0 : 1;
  427. }
  428. nextToken();
  429. }
  430. void UnwrappedLineParser::parsePPDirective() {
  431. assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
  432. ScopedMacroState MacroState(*Line, Tokens, FormatTok);
  433. nextToken();
  434. if (!FormatTok->Tok.getIdentifierInfo()) {
  435. parsePPUnknown();
  436. return;
  437. }
  438. switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
  439. case tok::pp_define:
  440. parsePPDefine();
  441. return;
  442. case tok::pp_if:
  443. parsePPIf(/*IfDef=*/false);
  444. break;
  445. case tok::pp_ifdef:
  446. case tok::pp_ifndef:
  447. parsePPIf(/*IfDef=*/true);
  448. break;
  449. case tok::pp_else:
  450. parsePPElse();
  451. break;
  452. case tok::pp_elif:
  453. parsePPElIf();
  454. break;
  455. case tok::pp_endif:
  456. parsePPEndIf();
  457. break;
  458. default:
  459. parsePPUnknown();
  460. break;
  461. }
  462. }
  463. void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
  464. if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
  465. PPStack.push_back(PP_Unreachable);
  466. else
  467. PPStack.push_back(PP_Conditional);
  468. }
  469. void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
  470. ++PPBranchLevel;
  471. assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
  472. if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
  473. PPLevelBranchIndex.push_back(0);
  474. PPLevelBranchCount.push_back(0);
  475. }
  476. PPChainBranchIndex.push(0);
  477. bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
  478. conditionalCompilationCondition(Unreachable || Skip);
  479. }
  480. void UnwrappedLineParser::conditionalCompilationAlternative() {
  481. if (!PPStack.empty())
  482. PPStack.pop_back();
  483. assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
  484. if (!PPChainBranchIndex.empty())
  485. ++PPChainBranchIndex.top();
  486. conditionalCompilationCondition(
  487. PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
  488. PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
  489. }
  490. void UnwrappedLineParser::conditionalCompilationEnd() {
  491. assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
  492. if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
  493. if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
  494. PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
  495. }
  496. }
  497. // Guard against #endif's without #if.
  498. if (PPBranchLevel > 0)
  499. --PPBranchLevel;
  500. if (!PPChainBranchIndex.empty())
  501. PPChainBranchIndex.pop();
  502. if (!PPStack.empty())
  503. PPStack.pop_back();
  504. }
  505. void UnwrappedLineParser::parsePPIf(bool IfDef) {
  506. nextToken();
  507. bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
  508. FormatTok->Tok.getLiteralData() != nullptr &&
  509. StringRef(FormatTok->Tok.getLiteralData(),
  510. FormatTok->Tok.getLength()) == "0") ||
  511. FormatTok->Tok.is(tok::kw_false);
  512. conditionalCompilationStart(!IfDef && IsLiteralFalse);
  513. parsePPUnknown();
  514. }
  515. void UnwrappedLineParser::parsePPElse() {
  516. conditionalCompilationAlternative();
  517. parsePPUnknown();
  518. }
  519. void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
  520. void UnwrappedLineParser::parsePPEndIf() {
  521. conditionalCompilationEnd();
  522. parsePPUnknown();
  523. }
  524. void UnwrappedLineParser::parsePPDefine() {
  525. nextToken();
  526. if (FormatTok->Tok.getKind() != tok::identifier) {
  527. parsePPUnknown();
  528. return;
  529. }
  530. nextToken();
  531. if (FormatTok->Tok.getKind() == tok::l_paren &&
  532. FormatTok->WhitespaceRange.getBegin() ==
  533. FormatTok->WhitespaceRange.getEnd()) {
  534. parseParens();
  535. }
  536. addUnwrappedLine();
  537. Line->Level = 1;
  538. // Errors during a preprocessor directive can only affect the layout of the
  539. // preprocessor directive, and thus we ignore them. An alternative approach
  540. // would be to use the same approach we use on the file level (no
  541. // re-indentation if there was a structural error) within the macro
  542. // definition.
  543. parseFile();
  544. }
  545. void UnwrappedLineParser::parsePPUnknown() {
  546. do {
  547. nextToken();
  548. } while (!eof());
  549. addUnwrappedLine();
  550. }
  551. // Here we blacklist certain tokens that are not usually the first token in an
  552. // unwrapped line. This is used in attempt to distinguish macro calls without
  553. // trailing semicolons from other constructs split to several lines.
  554. static bool tokenCanStartNewLine(const clang::Token &Tok) {
  555. // Semicolon can be a null-statement, l_square can be a start of a macro or
  556. // a C++11 attribute, but this doesn't seem to be common.
  557. return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
  558. Tok.isNot(tok::l_square) &&
  559. // Tokens that can only be used as binary operators and a part of
  560. // overloaded operator names.
  561. Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
  562. Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
  563. Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
  564. Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
  565. Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
  566. Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
  567. Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
  568. Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
  569. Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
  570. Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
  571. Tok.isNot(tok::lesslessequal) &&
  572. // Colon is used in labels, base class lists, initializer lists,
  573. // range-based for loops, ternary operator, but should never be the
  574. // first token in an unwrapped line.
  575. Tok.isNot(tok::colon) &&
  576. // 'noexcept' is a trailing annotation.
  577. Tok.isNot(tok::kw_noexcept);
  578. }
  579. void UnwrappedLineParser::parseStructuralElement() {
  580. assert(!FormatTok->Tok.is(tok::l_brace));
  581. switch (FormatTok->Tok.getKind()) {
  582. case tok::at:
  583. nextToken();
  584. if (FormatTok->Tok.is(tok::l_brace)) {
  585. parseBracedList();
  586. break;
  587. }
  588. switch (FormatTok->Tok.getObjCKeywordID()) {
  589. case tok::objc_public:
  590. case tok::objc_protected:
  591. case tok::objc_package:
  592. case tok::objc_private:
  593. return parseAccessSpecifier();
  594. case tok::objc_interface:
  595. case tok::objc_implementation:
  596. return parseObjCInterfaceOrImplementation();
  597. case tok::objc_protocol:
  598. return parseObjCProtocol();
  599. case tok::objc_end:
  600. return; // Handled by the caller.
  601. case tok::objc_optional:
  602. case tok::objc_required:
  603. nextToken();
  604. addUnwrappedLine();
  605. return;
  606. case tok::objc_autoreleasepool:
  607. nextToken();
  608. if (FormatTok->Tok.is(tok::l_brace)) {
  609. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  610. Style.BreakBeforeBraces == FormatStyle::BS_GNU)
  611. addUnwrappedLine();
  612. parseBlock(/*MustBeDeclaration=*/false);
  613. }
  614. addUnwrappedLine();
  615. return;
  616. case tok::objc_try:
  617. // This branch isn't strictly necessary (the kw_try case below would
  618. // do this too after the tok::at is parsed above). But be explicit.
  619. parseTryCatch();
  620. return;
  621. default:
  622. break;
  623. }
  624. break;
  625. case tok::kw_asm:
  626. nextToken();
  627. if (FormatTok->is(tok::l_brace)) {
  628. FormatTok->Type = TT_InlineASMBrace;
  629. nextToken();
  630. while (FormatTok && FormatTok->isNot(tok::eof)) {
  631. if (FormatTok->is(tok::r_brace)) {
  632. FormatTok->Type = TT_InlineASMBrace;
  633. nextToken();
  634. addUnwrappedLine();
  635. break;
  636. }
  637. FormatTok->Finalized = true;
  638. nextToken();
  639. }
  640. }
  641. break;
  642. case tok::kw_namespace:
  643. parseNamespace();
  644. return;
  645. case tok::kw_inline:
  646. nextToken();
  647. if (FormatTok->Tok.is(tok::kw_namespace)) {
  648. parseNamespace();
  649. return;
  650. }
  651. break;
  652. case tok::kw_public:
  653. case tok::kw_protected:
  654. case tok::kw_private:
  655. if (Style.Language == FormatStyle::LK_Java ||
  656. Style.Language == FormatStyle::LK_JavaScript)
  657. nextToken();
  658. else
  659. parseAccessSpecifier();
  660. return;
  661. case tok::kw_if:
  662. parseIfThenElse();
  663. return;
  664. case tok::kw_for:
  665. case tok::kw_while:
  666. parseForOrWhileLoop();
  667. return;
  668. case tok::kw_do:
  669. parseDoWhile();
  670. return;
  671. case tok::kw_switch:
  672. parseSwitch();
  673. return;
  674. case tok::kw_default:
  675. nextToken();
  676. parseLabel();
  677. return;
  678. case tok::kw_case:
  679. parseCaseLabel();
  680. return;
  681. case tok::kw_try:
  682. case tok::kw___try:
  683. parseTryCatch();
  684. return;
  685. case tok::kw_extern:
  686. nextToken();
  687. if (FormatTok->Tok.is(tok::string_literal)) {
  688. nextToken();
  689. if (FormatTok->Tok.is(tok::l_brace)) {
  690. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
  691. addUnwrappedLine();
  692. return;
  693. }
  694. }
  695. break;
  696. case tok::kw_export:
  697. if (Style.Language == FormatStyle::LK_JavaScript) {
  698. parseJavaScriptEs6ImportExport();
  699. return;
  700. }
  701. break;
  702. case tok::identifier:
  703. if (FormatTok->is(TT_ForEachMacro)) {
  704. parseForOrWhileLoop();
  705. return;
  706. }
  707. if (FormatTok->is(TT_MacroBlockBegin)) {
  708. parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
  709. /*MunchSemi=*/false);
  710. return;
  711. }
  712. if (Style.Language == FormatStyle::LK_JavaScript &&
  713. FormatTok->is(Keywords.kw_import)) {
  714. parseJavaScriptEs6ImportExport();
  715. return;
  716. }
  717. if (FormatTok->is(Keywords.kw_signals)) {
  718. nextToken();
  719. if (FormatTok->is(tok::colon)) {
  720. nextToken();
  721. addUnwrappedLine();
  722. }
  723. return;
  724. }
  725. // In all other cases, parse the declaration.
  726. break;
  727. default:
  728. break;
  729. }
  730. do {
  731. switch (FormatTok->Tok.getKind()) {
  732. case tok::at:
  733. nextToken();
  734. if (FormatTok->Tok.is(tok::l_brace))
  735. parseBracedList();
  736. break;
  737. case tok::kw_enum:
  738. // parseEnum falls through and does not yet add an unwrapped line as an
  739. // enum definition can start a structural element.
  740. parseEnum();
  741. // This does not apply for Java and JavaScript.
  742. if (Style.Language == FormatStyle::LK_Java ||
  743. Style.Language == FormatStyle::LK_JavaScript) {
  744. addUnwrappedLine();
  745. return;
  746. }
  747. break;
  748. case tok::kw_typedef:
  749. nextToken();
  750. if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
  751. Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
  752. parseEnum();
  753. break;
  754. case tok::kw_struct:
  755. case tok::kw_union:
  756. case tok::kw_class:
  757. // parseRecord falls through and does not yet add an unwrapped line as a
  758. // record declaration or definition can start a structural element.
  759. parseRecord();
  760. // This does not apply for Java and JavaScript.
  761. if (Style.Language == FormatStyle::LK_Java ||
  762. Style.Language == FormatStyle::LK_JavaScript) {
  763. addUnwrappedLine();
  764. return;
  765. }
  766. break;
  767. case tok::period:
  768. nextToken();
  769. // In Java, classes have an implicit static member "class".
  770. if (Style.Language == FormatStyle::LK_Java && FormatTok &&
  771. FormatTok->is(tok::kw_class))
  772. nextToken();
  773. break;
  774. case tok::semi:
  775. nextToken();
  776. addUnwrappedLine();
  777. return;
  778. case tok::r_brace:
  779. addUnwrappedLine();
  780. return;
  781. case tok::l_paren:
  782. parseParens();
  783. break;
  784. case tok::caret:
  785. nextToken();
  786. if (FormatTok->Tok.isAnyIdentifier() ||
  787. FormatTok->isSimpleTypeSpecifier())
  788. nextToken();
  789. if (FormatTok->is(tok::l_paren))
  790. parseParens();
  791. if (FormatTok->is(tok::l_brace))
  792. parseChildBlock();
  793. break;
  794. case tok::l_brace:
  795. if (!tryToParseBracedList()) {
  796. // A block outside of parentheses must be the last part of a
  797. // structural element.
  798. // FIXME: Figure out cases where this is not true, and add projections
  799. // for them (the one we know is missing are lambdas).
  800. if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
  801. addUnwrappedLine();
  802. FormatTok->Type = TT_FunctionLBrace;
  803. parseBlock(/*MustBeDeclaration=*/false);
  804. addUnwrappedLine();
  805. return;
  806. }
  807. // Otherwise this was a braced init list, and the structural
  808. // element continues.
  809. break;
  810. case tok::kw_try:
  811. // We arrive here when parsing function-try blocks.
  812. parseTryCatch();
  813. return;
  814. case tok::identifier: {
  815. if (FormatTok->is(TT_MacroBlockEnd)) {
  816. addUnwrappedLine();
  817. return;
  818. }
  819. // Parse function literal unless 'function' is the first token in a line
  820. // in which case this should be treated as a free-standing function.
  821. if (Style.Language == FormatStyle::LK_JavaScript &&
  822. FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) {
  823. tryToParseJSFunction();
  824. break;
  825. }
  826. if ((Style.Language == FormatStyle::LK_JavaScript ||
  827. Style.Language == FormatStyle::LK_Java) &&
  828. FormatTok->is(Keywords.kw_interface)) {
  829. parseRecord();
  830. addUnwrappedLine();
  831. return;
  832. }
  833. StringRef Text = FormatTok->TokenText;
  834. nextToken();
  835. if (Line->Tokens.size() == 1 &&
  836. // JS doesn't have macros, and within classes colons indicate fields,
  837. // not labels.
  838. Style.Language != FormatStyle::LK_JavaScript) {
  839. if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
  840. parseLabel();
  841. return;
  842. }
  843. // Recognize function-like macro usages without trailing semicolon as
  844. // well as free-standing macros like Q_OBJECT.
  845. bool FunctionLike = FormatTok->is(tok::l_paren);
  846. if (FunctionLike)
  847. parseParens();
  848. bool FollowedByNewline =
  849. CommentsBeforeNextToken.empty()
  850. ? FormatTok->NewlinesBefore > 0
  851. : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
  852. if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
  853. tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
  854. addUnwrappedLine();
  855. return;
  856. }
  857. }
  858. break;
  859. }
  860. case tok::equal:
  861. // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
  862. // TT_JsFatArrow. The always start an expression or a child block if
  863. // followed by a curly.
  864. if (FormatTok->is(TT_JsFatArrow)) {
  865. nextToken();
  866. if (FormatTok->is(tok::l_brace))
  867. parseChildBlock();
  868. break;
  869. }
  870. nextToken();
  871. if (FormatTok->Tok.is(tok::l_brace)) {
  872. parseBracedList();
  873. }
  874. break;
  875. case tok::l_square:
  876. parseSquare();
  877. break;
  878. case tok::kw_new:
  879. parseNew();
  880. break;
  881. default:
  882. nextToken();
  883. break;
  884. }
  885. } while (!eof());
  886. }
  887. bool UnwrappedLineParser::tryToParseLambda() {
  888. if (Style.Language != FormatStyle::LK_Cpp) {
  889. nextToken();
  890. return false;
  891. }
  892. // FIXME: This is a dirty way to access the previous token. Find a better
  893. // solution.
  894. if (!Line->Tokens.empty() &&
  895. (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator,
  896. tok::kw_new, tok::kw_delete) ||
  897. Line->Tokens.back().Tok->closesScope() ||
  898. Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
  899. nextToken();
  900. return false;
  901. }
  902. assert(FormatTok->is(tok::l_square));
  903. FormatToken &LSquare = *FormatTok;
  904. if (!tryToParseLambdaIntroducer())
  905. return false;
  906. while (FormatTok->isNot(tok::l_brace)) {
  907. if (FormatTok->isSimpleTypeSpecifier()) {
  908. nextToken();
  909. continue;
  910. }
  911. switch (FormatTok->Tok.getKind()) {
  912. case tok::l_brace:
  913. break;
  914. case tok::l_paren:
  915. parseParens();
  916. break;
  917. case tok::amp:
  918. case tok::star:
  919. case tok::kw_const:
  920. case tok::comma:
  921. case tok::less:
  922. case tok::greater:
  923. case tok::identifier:
  924. case tok::coloncolon:
  925. case tok::kw_mutable:
  926. nextToken();
  927. break;
  928. case tok::arrow:
  929. FormatTok->Type = TT_LambdaArrow;
  930. nextToken();
  931. break;
  932. default:
  933. return true;
  934. }
  935. }
  936. LSquare.Type = TT_LambdaLSquare;
  937. parseChildBlock();
  938. return true;
  939. }
  940. bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
  941. nextToken();
  942. if (FormatTok->is(tok::equal)) {
  943. nextToken();
  944. if (FormatTok->is(tok::r_square)) {
  945. nextToken();
  946. return true;
  947. }
  948. if (FormatTok->isNot(tok::comma))
  949. return false;
  950. nextToken();
  951. } else if (FormatTok->is(tok::amp)) {
  952. nextToken();
  953. if (FormatTok->is(tok::r_square)) {
  954. nextToken();
  955. return true;
  956. }
  957. if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
  958. return false;
  959. }
  960. if (FormatTok->is(tok::comma))
  961. nextToken();
  962. } else if (FormatTok->is(tok::r_square)) {
  963. nextToken();
  964. return true;
  965. }
  966. do {
  967. if (FormatTok->is(tok::amp))
  968. nextToken();
  969. if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
  970. return false;
  971. nextToken();
  972. if (FormatTok->is(tok::ellipsis))
  973. nextToken();
  974. if (FormatTok->is(tok::comma)) {
  975. nextToken();
  976. } else if (FormatTok->is(tok::r_square)) {
  977. nextToken();
  978. return true;
  979. } else {
  980. return false;
  981. }
  982. } while (!eof());
  983. return false;
  984. }
  985. void UnwrappedLineParser::tryToParseJSFunction() {
  986. nextToken();
  987. // Consume function name.
  988. if (FormatTok->is(tok::identifier))
  989. nextToken();
  990. if (FormatTok->isNot(tok::l_paren))
  991. return;
  992. // Parse formal parameter list.
  993. parseParens();
  994. if (FormatTok->is(tok::colon)) {
  995. // Parse a type definition.
  996. nextToken();
  997. // Eat the type declaration. For braced inline object types, balance braces,
  998. // otherwise just parse until finding an l_brace for the function body.
  999. if (FormatTok->is(tok::l_brace))
  1000. tryToParseBracedList();
  1001. else
  1002. while (FormatTok->isNot(tok::l_brace) && !eof())
  1003. nextToken();
  1004. }
  1005. parseChildBlock();
  1006. }
  1007. bool UnwrappedLineParser::tryToParseBracedList() {
  1008. if (FormatTok->BlockKind == BK_Unknown)
  1009. calculateBraceTypes();
  1010. assert(FormatTok->BlockKind != BK_Unknown);
  1011. if (FormatTok->BlockKind == BK_Block)
  1012. return false;
  1013. parseBracedList();
  1014. return true;
  1015. }
  1016. bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
  1017. bool HasError = false;
  1018. nextToken();
  1019. // FIXME: Once we have an expression parser in the UnwrappedLineParser,
  1020. // replace this by using parseAssigmentExpression() inside.
  1021. do {
  1022. if (Style.Language == FormatStyle::LK_JavaScript) {
  1023. if (FormatTok->is(Keywords.kw_function)) {
  1024. tryToParseJSFunction();
  1025. continue;
  1026. }
  1027. if (FormatTok->is(TT_JsFatArrow)) {
  1028. nextToken();
  1029. // Fat arrows can be followed by simple expressions or by child blocks
  1030. // in curly braces.
  1031. if (FormatTok->is(tok::l_brace)) {
  1032. parseChildBlock();
  1033. continue;
  1034. }
  1035. }
  1036. }
  1037. switch (FormatTok->Tok.getKind()) {
  1038. case tok::caret:
  1039. nextToken();
  1040. if (FormatTok->is(tok::l_brace)) {
  1041. parseChildBlock();
  1042. }
  1043. break;
  1044. case tok::l_square:
  1045. tryToParseLambda();
  1046. break;
  1047. case tok::l_brace:
  1048. // Assume there are no blocks inside a braced init list apart
  1049. // from the ones we explicitly parse out (like lambdas).
  1050. FormatTok->BlockKind = BK_BracedInit;
  1051. parseBracedList();
  1052. break;
  1053. case tok::l_paren:
  1054. parseParens();
  1055. // JavaScript can just have free standing methods and getters/setters in
  1056. // object literals. Detect them by a "{" following ")".
  1057. if (Style.Language == FormatStyle::LK_JavaScript) {
  1058. if (FormatTok->is(tok::l_brace))
  1059. parseChildBlock();
  1060. break;
  1061. }
  1062. break;
  1063. case tok::r_brace:
  1064. nextToken();
  1065. return !HasError;
  1066. case tok::semi:
  1067. HasError = true;
  1068. if (!ContinueOnSemicolons)
  1069. return !HasError;
  1070. nextToken();
  1071. break;
  1072. case tok::comma:
  1073. nextToken();
  1074. break;
  1075. default:
  1076. nextToken();
  1077. break;
  1078. }
  1079. } while (!eof());
  1080. return false;
  1081. }
  1082. void UnwrappedLineParser::parseParens() {
  1083. assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
  1084. nextToken();
  1085. do {
  1086. switch (FormatTok->Tok.getKind()) {
  1087. case tok::l_paren:
  1088. parseParens();
  1089. if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
  1090. parseChildBlock();
  1091. break;
  1092. case tok::r_paren:
  1093. nextToken();
  1094. return;
  1095. case tok::r_brace:
  1096. // A "}" inside parenthesis is an error if there wasn't a matching "{".
  1097. return;
  1098. case tok::l_square:
  1099. tryToParseLambda();
  1100. break;
  1101. case tok::l_brace:
  1102. if (!tryToParseBracedList())
  1103. parseChildBlock();
  1104. break;
  1105. case tok::at:
  1106. nextToken();
  1107. if (FormatTok->Tok.is(tok::l_brace))
  1108. parseBracedList();
  1109. break;
  1110. case tok::identifier:
  1111. if (Style.Language == FormatStyle::LK_JavaScript &&
  1112. FormatTok->is(Keywords.kw_function))
  1113. tryToParseJSFunction();
  1114. else
  1115. nextToken();
  1116. break;
  1117. default:
  1118. nextToken();
  1119. break;
  1120. }
  1121. } while (!eof());
  1122. }
  1123. void UnwrappedLineParser::parseSquare() {
  1124. assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
  1125. if (tryToParseLambda())
  1126. return;
  1127. do {
  1128. switch (FormatTok->Tok.getKind()) {
  1129. case tok::l_paren:
  1130. parseParens();
  1131. break;
  1132. case tok::r_square:
  1133. nextToken();
  1134. return;
  1135. case tok::r_brace:
  1136. // A "}" inside parenthesis is an error if there wasn't a matching "{".
  1137. return;
  1138. case tok::l_square:
  1139. parseSquare();
  1140. break;
  1141. case tok::l_brace: {
  1142. if (!tryToParseBracedList())
  1143. parseChildBlock();
  1144. break;
  1145. }
  1146. case tok::at:
  1147. nextToken();
  1148. if (FormatTok->Tok.is(tok::l_brace))
  1149. parseBracedList();
  1150. break;
  1151. default:
  1152. nextToken();
  1153. break;
  1154. }
  1155. } while (!eof());
  1156. }
  1157. void UnwrappedLineParser::parseIfThenElse() {
  1158. assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
  1159. nextToken();
  1160. if (FormatTok->Tok.is(tok::l_paren))
  1161. parseParens();
  1162. bool NeedsUnwrappedLine = false;
  1163. if (FormatTok->Tok.is(tok::l_brace)) {
  1164. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1165. parseBlock(/*MustBeDeclaration=*/false);
  1166. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  1167. Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
  1168. addUnwrappedLine();
  1169. } else {
  1170. NeedsUnwrappedLine = true;
  1171. }
  1172. } else {
  1173. addUnwrappedLine();
  1174. ++Line->Level;
  1175. parseStructuralElement();
  1176. --Line->Level;
  1177. }
  1178. if (FormatTok->Tok.is(tok::kw_else)) {
  1179. if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
  1180. addUnwrappedLine();
  1181. nextToken();
  1182. if (FormatTok->Tok.is(tok::l_brace)) {
  1183. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1184. parseBlock(/*MustBeDeclaration=*/false);
  1185. addUnwrappedLine();
  1186. } else if (FormatTok->Tok.is(tok::kw_if)) {
  1187. parseIfThenElse();
  1188. } else {
  1189. addUnwrappedLine();
  1190. ++Line->Level;
  1191. parseStructuralElement();
  1192. --Line->Level;
  1193. }
  1194. } else if (NeedsUnwrappedLine) {
  1195. addUnwrappedLine();
  1196. }
  1197. }
  1198. void UnwrappedLineParser::parseTryCatch() {
  1199. assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
  1200. nextToken();
  1201. bool NeedsUnwrappedLine = false;
  1202. if (FormatTok->is(tok::colon)) {
  1203. // We are in a function try block, what comes is an initializer list.
  1204. nextToken();
  1205. while (FormatTok->is(tok::identifier)) {
  1206. nextToken();
  1207. if (FormatTok->is(tok::l_paren))
  1208. parseParens();
  1209. if (FormatTok->is(tok::comma))
  1210. nextToken();
  1211. }
  1212. }
  1213. // Parse try with resource.
  1214. if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
  1215. parseParens();
  1216. }
  1217. if (FormatTok->is(tok::l_brace)) {
  1218. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1219. parseBlock(/*MustBeDeclaration=*/false);
  1220. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  1221. Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
  1222. Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
  1223. addUnwrappedLine();
  1224. } else {
  1225. NeedsUnwrappedLine = true;
  1226. }
  1227. } else if (!FormatTok->is(tok::kw_catch)) {
  1228. // The C++ standard requires a compound-statement after a try.
  1229. // If there's none, we try to assume there's a structuralElement
  1230. // and try to continue.
  1231. addUnwrappedLine();
  1232. ++Line->Level;
  1233. parseStructuralElement();
  1234. --Line->Level;
  1235. }
  1236. while (1) {
  1237. if (FormatTok->is(tok::at))
  1238. nextToken();
  1239. if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
  1240. tok::kw___finally) ||
  1241. ((Style.Language == FormatStyle::LK_Java ||
  1242. Style.Language == FormatStyle::LK_JavaScript) &&
  1243. FormatTok->is(Keywords.kw_finally)) ||
  1244. (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
  1245. FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
  1246. break;
  1247. nextToken();
  1248. while (FormatTok->isNot(tok::l_brace)) {
  1249. if (FormatTok->is(tok::l_paren)) {
  1250. parseParens();
  1251. continue;
  1252. }
  1253. if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
  1254. return;
  1255. nextToken();
  1256. }
  1257. NeedsUnwrappedLine = false;
  1258. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1259. parseBlock(/*MustBeDeclaration=*/false);
  1260. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  1261. Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
  1262. Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
  1263. addUnwrappedLine();
  1264. } else {
  1265. NeedsUnwrappedLine = true;
  1266. }
  1267. }
  1268. if (NeedsUnwrappedLine) {
  1269. addUnwrappedLine();
  1270. }
  1271. }
  1272. void UnwrappedLineParser::parseNamespace() {
  1273. assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
  1274. const FormatToken &InitialToken = *FormatTok;
  1275. nextToken();
  1276. if (FormatTok->Tok.is(tok::identifier))
  1277. nextToken();
  1278. if (FormatTok->Tok.is(tok::l_brace)) {
  1279. if (ShouldBreakBeforeBrace(Style, InitialToken))
  1280. addUnwrappedLine();
  1281. bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
  1282. (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
  1283. DeclarationScopeStack.size() > 1);
  1284. parseBlock(/*MustBeDeclaration=*/true, AddLevel);
  1285. // Munch the semicolon after a namespace. This is more common than one would
  1286. // think. Puttin the semicolon into its own line is very ugly.
  1287. if (FormatTok->Tok.is(tok::semi))
  1288. nextToken();
  1289. addUnwrappedLine();
  1290. }
  1291. // FIXME: Add error handling.
  1292. }
  1293. void UnwrappedLineParser::parseNew() {
  1294. assert(FormatTok->is(tok::kw_new) && "'new' expected");
  1295. nextToken();
  1296. if (Style.Language != FormatStyle::LK_Java)
  1297. return;
  1298. // In Java, we can parse everything up to the parens, which aren't optional.
  1299. do {
  1300. // There should not be a ;, { or } before the new's open paren.
  1301. if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
  1302. return;
  1303. // Consume the parens.
  1304. if (FormatTok->is(tok::l_paren)) {
  1305. parseParens();
  1306. // If there is a class body of an anonymous class, consume that as child.
  1307. if (FormatTok->is(tok::l_brace))
  1308. parseChildBlock();
  1309. return;
  1310. }
  1311. nextToken();
  1312. } while (!eof());
  1313. }
  1314. void UnwrappedLineParser::parseForOrWhileLoop() {
  1315. assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
  1316. "'for', 'while' or foreach macro expected");
  1317. nextToken();
  1318. if (FormatTok->Tok.is(tok::l_paren))
  1319. parseParens();
  1320. if (FormatTok->Tok.is(tok::l_brace)) {
  1321. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1322. parseBlock(/*MustBeDeclaration=*/false);
  1323. addUnwrappedLine();
  1324. } else {
  1325. addUnwrappedLine();
  1326. ++Line->Level;
  1327. parseStructuralElement();
  1328. --Line->Level;
  1329. }
  1330. }
  1331. void UnwrappedLineParser::parseDoWhile() {
  1332. assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
  1333. nextToken();
  1334. if (FormatTok->Tok.is(tok::l_brace)) {
  1335. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1336. parseBlock(/*MustBeDeclaration=*/false);
  1337. if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
  1338. addUnwrappedLine();
  1339. } else {
  1340. addUnwrappedLine();
  1341. ++Line->Level;
  1342. parseStructuralElement();
  1343. --Line->Level;
  1344. }
  1345. // FIXME: Add error handling.
  1346. if (!FormatTok->Tok.is(tok::kw_while)) {
  1347. addUnwrappedLine();
  1348. return;
  1349. }
  1350. nextToken();
  1351. parseStructuralElement();
  1352. }
  1353. void UnwrappedLineParser::parseLabel() {
  1354. nextToken();
  1355. unsigned OldLineLevel = Line->Level;
  1356. if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
  1357. --Line->Level;
  1358. if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
  1359. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1360. parseBlock(/*MustBeDeclaration=*/false);
  1361. if (FormatTok->Tok.is(tok::kw_break)) {
  1362. // "break;" after "}" on its own line only for BS_Allman and BS_GNU
  1363. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  1364. Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
  1365. addUnwrappedLine();
  1366. }
  1367. parseStructuralElement();
  1368. }
  1369. addUnwrappedLine();
  1370. } else {
  1371. if (FormatTok->is(tok::semi))
  1372. nextToken();
  1373. addUnwrappedLine();
  1374. }
  1375. Line->Level = OldLineLevel;
  1376. }
  1377. void UnwrappedLineParser::parseCaseLabel() {
  1378. assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
  1379. // FIXME: fix handling of complex expressions here.
  1380. do {
  1381. nextToken();
  1382. } while (!eof() && !FormatTok->Tok.is(tok::colon));
  1383. parseLabel();
  1384. }
  1385. void UnwrappedLineParser::parseSwitch() {
  1386. assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
  1387. nextToken();
  1388. if (FormatTok->Tok.is(tok::l_paren))
  1389. parseParens();
  1390. if (FormatTok->Tok.is(tok::l_brace)) {
  1391. CompoundStatementIndenter Indenter(this, Style, Line->Level);
  1392. parseBlock(/*MustBeDeclaration=*/false);
  1393. addUnwrappedLine();
  1394. } else {
  1395. addUnwrappedLine();
  1396. ++Line->Level;
  1397. parseStructuralElement();
  1398. --Line->Level;
  1399. }
  1400. }
  1401. void UnwrappedLineParser::parseAccessSpecifier() {
  1402. nextToken();
  1403. // Understand Qt's slots.
  1404. if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
  1405. nextToken();
  1406. // Otherwise, we don't know what it is, and we'd better keep the next token.
  1407. if (FormatTok->Tok.is(tok::colon))
  1408. nextToken();
  1409. addUnwrappedLine();
  1410. }
  1411. void UnwrappedLineParser::parseEnum() {
  1412. // Won't be 'enum' for NS_ENUMs.
  1413. if (FormatTok->Tok.is(tok::kw_enum))
  1414. nextToken();
  1415. // Eat up enum class ...
  1416. if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
  1417. nextToken();
  1418. while (FormatTok->Tok.getIdentifierInfo() ||
  1419. FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
  1420. tok::greater, tok::comma, tok::question)) {
  1421. nextToken();
  1422. // We can have macros or attributes in between 'enum' and the enum name.
  1423. if (FormatTok->is(tok::l_paren))
  1424. parseParens();
  1425. if (FormatTok->is(tok::identifier)) {
  1426. nextToken();
  1427. // If there are two identifiers in a row, this is likely an elaborate
  1428. // return type. In Java, this can be "implements", etc.
  1429. if (Style.Language == FormatStyle::LK_Cpp &&
  1430. FormatTok->is(tok::identifier))
  1431. return;
  1432. }
  1433. }
  1434. // Just a declaration or something is wrong.
  1435. if (FormatTok->isNot(tok::l_brace))
  1436. return;
  1437. FormatTok->BlockKind = BK_Block;
  1438. if (Style.Language == FormatStyle::LK_Java) {
  1439. // Java enums are different.
  1440. parseJavaEnumBody();
  1441. return;
  1442. }
  1443. // Parse enum body.
  1444. bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
  1445. if (HasError) {
  1446. if (FormatTok->is(tok::semi))
  1447. nextToken();
  1448. addUnwrappedLine();
  1449. }
  1450. // There is no addUnwrappedLine() here so that we fall through to parsing a
  1451. // structural element afterwards. Thus, in "enum A {} n, m;",
  1452. // "} n, m;" will end up in one unwrapped line.
  1453. }
  1454. void UnwrappedLineParser::parseJavaEnumBody() {
  1455. // Determine whether the enum is simple, i.e. does not have a semicolon or
  1456. // constants with class bodies. Simple enums can be formatted like braced
  1457. // lists, contracted to a single line, etc.
  1458. unsigned StoredPosition = Tokens->getPosition();
  1459. bool IsSimple = true;
  1460. FormatToken *Tok = Tokens->getNextToken();
  1461. while (Tok) {
  1462. if (Tok->is(tok::r_brace))
  1463. break;
  1464. if (Tok->isOneOf(tok::l_brace, tok::semi)) {
  1465. IsSimple = false;
  1466. break;
  1467. }
  1468. // FIXME: This will also mark enums with braces in the arguments to enum
  1469. // constants as "not simple". This is probably fine in practice, though.
  1470. Tok = Tokens->getNextToken();
  1471. }
  1472. FormatTok = Tokens->setPosition(StoredPosition);
  1473. if (IsSimple) {
  1474. parseBracedList();
  1475. addUnwrappedLine();
  1476. return;
  1477. }
  1478. // Parse the body of a more complex enum.
  1479. // First add a line for everything up to the "{".
  1480. nextToken();
  1481. addUnwrappedLine();
  1482. ++Line->Level;
  1483. // Parse the enum constants.
  1484. while (FormatTok) {
  1485. if (FormatTok->is(tok::l_brace)) {
  1486. // Parse the constant's class body.
  1487. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
  1488. /*MunchSemi=*/false);
  1489. } else if (FormatTok->is(tok::l_paren)) {
  1490. parseParens();
  1491. } else if (FormatTok->is(tok::comma)) {
  1492. nextToken();
  1493. addUnwrappedLine();
  1494. } else if (FormatTok->is(tok::semi)) {
  1495. nextToken();
  1496. addUnwrappedLine();
  1497. break;
  1498. } else if (FormatTok->is(tok::r_brace)) {
  1499. addUnwrappedLine();
  1500. break;
  1501. } else {
  1502. nextToken();
  1503. }
  1504. }
  1505. // Parse the class body after the enum's ";" if any.
  1506. parseLevel(/*HasOpeningBrace=*/true);
  1507. nextToken();
  1508. --Line->Level;
  1509. addUnwrappedLine();
  1510. }
  1511. void UnwrappedLineParser::parseRecord() {
  1512. const FormatToken &InitialToken = *FormatTok;
  1513. nextToken();
  1514. // The actual identifier can be a nested name specifier, and in macros
  1515. // it is often token-pasted.
  1516. while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
  1517. tok::kw___attribute, tok::kw___declspec,
  1518. tok::kw_alignas) ||
  1519. ((Style.Language == FormatStyle::LK_Java ||
  1520. Style.Language == FormatStyle::LK_JavaScript) &&
  1521. FormatTok->isOneOf(tok::period, tok::comma))) {
  1522. bool IsNonMacroIdentifier =
  1523. FormatTok->is(tok::identifier) &&
  1524. FormatTok->TokenText != FormatTok->TokenText.upper();
  1525. nextToken();
  1526. // We can have macros or attributes in between 'class' and the class name.
  1527. if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
  1528. parseParens();
  1529. }
  1530. // Note that parsing away template declarations here leads to incorrectly
  1531. // accepting function declarations as record declarations.
  1532. // In general, we cannot solve this problem. Consider:
  1533. // class A<int> B() {}
  1534. // which can be a function definition or a class definition when B() is a
  1535. // macro. If we find enough real-world cases where this is a problem, we
  1536. // can parse for the 'template' keyword in the beginning of the statement,
  1537. // and thus rule out the record production in case there is no template
  1538. // (this would still leave us with an ambiguity between template function
  1539. // and class declarations).
  1540. if (FormatTok->isOneOf(tok::colon, tok::less)) {
  1541. while (!eof()) {
  1542. if (FormatTok->is(tok::l_brace)) {
  1543. calculateBraceTypes(/*ExpectClassBody=*/true);
  1544. if (!tryToParseBracedList())
  1545. break;
  1546. }
  1547. if (FormatTok->Tok.is(tok::semi))
  1548. return;
  1549. nextToken();
  1550. }
  1551. }
  1552. if (FormatTok->Tok.is(tok::l_brace)) {
  1553. if (ShouldBreakBeforeBrace(Style, InitialToken))
  1554. addUnwrappedLine();
  1555. parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
  1556. /*MunchSemi=*/false);
  1557. }
  1558. // There is no addUnwrappedLine() here so that we fall through to parsing a
  1559. // structural element afterwards. Thus, in "class A {} n, m;",
  1560. // "} n, m;" will end up in one unwrapped line.
  1561. }
  1562. void UnwrappedLineParser::parseObjCProtocolList() {
  1563. assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
  1564. do
  1565. nextToken();
  1566. while (!eof() && FormatTok->Tok.isNot(tok::greater));
  1567. nextToken(); // Skip '>'.
  1568. }
  1569. void UnwrappedLineParser::parseObjCUntilAtEnd() {
  1570. do {
  1571. if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
  1572. nextToken();
  1573. addUnwrappedLine();
  1574. break;
  1575. }
  1576. if (FormatTok->is(tok::l_brace)) {
  1577. parseBlock(/*MustBeDeclaration=*/false);
  1578. // In ObjC interfaces, nothing should be following the "}".
  1579. addUnwrappedLine();
  1580. } else if (FormatTok->is(tok::r_brace)) {
  1581. // Ignore stray "}". parseStructuralElement doesn't consume them.
  1582. nextToken();
  1583. addUnwrappedLine();
  1584. } else {
  1585. parseStructuralElement();
  1586. }
  1587. } while (!eof());
  1588. }
  1589. void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
  1590. nextToken();
  1591. nextToken(); // interface name
  1592. // @interface can be followed by either a base class, or a category.
  1593. if (FormatTok->Tok.is(tok::colon)) {
  1594. nextToken();
  1595. nextToken(); // base class name
  1596. } else if (FormatTok->Tok.is(tok::l_paren))
  1597. // Skip category, if present.
  1598. parseParens();
  1599. if (FormatTok->Tok.is(tok::less))
  1600. parseObjCProtocolList();
  1601. if (FormatTok->Tok.is(tok::l_brace)) {
  1602. if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  1603. Style.BreakBeforeBraces == FormatStyle::BS_GNU)
  1604. addUnwrappedLine();
  1605. parseBlock(/*MustBeDeclaration=*/true);
  1606. }
  1607. // With instance variables, this puts '}' on its own line. Without instance
  1608. // variables, this ends the @interface line.
  1609. addUnwrappedLine();
  1610. parseObjCUntilAtEnd();
  1611. }
  1612. void UnwrappedLineParser::parseObjCProtocol() {
  1613. nextToken();
  1614. nextToken(); // protocol name
  1615. if (FormatTok->Tok.is(tok::less))
  1616. parseObjCProtocolList();
  1617. // Check for protocol declaration.
  1618. if (FormatTok->Tok.is(tok::semi)) {
  1619. nextToken();
  1620. return addUnwrappedLine();
  1621. }
  1622. addUnwrappedLine();
  1623. parseObjCUntilAtEnd();
  1624. }
  1625. void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
  1626. assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
  1627. nextToken();
  1628. // Consume the "default" in "export default class/function".
  1629. if (FormatTok->is(tok::kw_default))
  1630. nextToken();
  1631. // Consume "function" and "default function", so that these get parsed as
  1632. // free-standing JS functions, i.e. do not require a trailing semicolon.
  1633. if (FormatTok->is(Keywords.kw_function)) {
  1634. nextToken();
  1635. return;
  1636. }
  1637. if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, tok::kw_enum,
  1638. Keywords.kw_var))
  1639. return; // Fall through to parsing the corresponding structure.
  1640. if (FormatTok->is(tok::l_brace)) {
  1641. FormatTok->BlockKind = BK_Block;
  1642. parseBracedList();
  1643. }
  1644. while (!eof() && FormatTok->isNot(tok::semi) &&
  1645. FormatTok->isNot(tok::l_brace)) {
  1646. nextToken();
  1647. }
  1648. }
  1649. LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
  1650. StringRef Prefix = "") {
  1651. llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
  1652. << (Line.InPPDirective ? " MACRO" : "") << ": ";
  1653. for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
  1654. E = Line.Tokens.end();
  1655. I != E; ++I) {
  1656. llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
  1657. }
  1658. for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
  1659. E = Line.Tokens.end();
  1660. I != E; ++I) {
  1661. const UnwrappedLineNode &Node = *I;
  1662. for (SmallVectorImpl<UnwrappedLine>::const_iterator
  1663. I = Node.Children.begin(),
  1664. E = Node.Children.end();
  1665. I != E; ++I) {
  1666. printDebugInfo(*I, "\nChild: ");
  1667. }
  1668. }
  1669. llvm::dbgs() << "\n";
  1670. }
  1671. void UnwrappedLineParser::addUnwrappedLine() {
  1672. if (Line->Tokens.empty())
  1673. return;
  1674. DEBUG({
  1675. if (CurrentLines == &Lines)
  1676. printDebugInfo(*Line);
  1677. });
  1678. CurrentLines->push_back(std::move(*Line));
  1679. Line->Tokens.clear();
  1680. if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
  1681. CurrentLines->append(
  1682. std::make_move_iterator(PreprocessorDirectives.begin()),
  1683. std::make_move_iterator(PreprocessorDirectives.end()));
  1684. PreprocessorDirectives.clear();
  1685. }
  1686. }
  1687. bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
  1688. bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
  1689. return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
  1690. FormatTok.NewlinesBefore > 0;
  1691. }
  1692. void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
  1693. bool JustComments = Line->Tokens.empty();
  1694. for (SmallVectorImpl<FormatToken *>::const_iterator
  1695. I = CommentsBeforeNextToken.begin(),
  1696. E = CommentsBeforeNextToken.end();
  1697. I != E; ++I) {
  1698. if (isOnNewLine(**I) && JustComments)
  1699. addUnwrappedLine();
  1700. pushToken(*I);
  1701. }
  1702. if (NewlineBeforeNext && JustComments)
  1703. addUnwrappedLine();
  1704. CommentsBeforeNextToken.clear();
  1705. }
  1706. void UnwrappedLineParser::nextToken() {
  1707. if (eof())
  1708. return;
  1709. flushComments(isOnNewLine(*FormatTok));
  1710. pushToken(FormatTok);
  1711. readToken();
  1712. }
  1713. void UnwrappedLineParser::readToken() {
  1714. bool CommentsInCurrentLine = true;
  1715. do {
  1716. FormatTok = Tokens->getNextToken();
  1717. assert(FormatTok);
  1718. while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
  1719. (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
  1720. // If there is an unfinished unwrapped line, we flush the preprocessor
  1721. // directives only after that unwrapped line was finished later.
  1722. bool SwitchToPreprocessorLines = !Line->Tokens.empty();
  1723. ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
  1724. // Comments stored before the preprocessor directive need to be output
  1725. // before the preprocessor directive, at the same level as the
  1726. // preprocessor directive, as we consider them to apply to the directive.
  1727. flushComments(isOnNewLine(*FormatTok));
  1728. parsePPDirective();
  1729. }
  1730. while (FormatTok->Type == TT_ConflictStart ||
  1731. FormatTok->Type == TT_ConflictEnd ||
  1732. FormatTok->Type == TT_ConflictAlternative) {
  1733. if (FormatTok->Type == TT_ConflictStart) {
  1734. conditionalCompilationStart(/*Unreachable=*/false);
  1735. } else if (FormatTok->Type == TT_ConflictAlternative) {
  1736. conditionalCompilationAlternative();
  1737. } else if (FormatTok->Type == TT_ConflictEnd) {
  1738. conditionalCompilationEnd();
  1739. }
  1740. FormatTok = Tokens->getNextToken();
  1741. FormatTok->MustBreakBefore = true;
  1742. }
  1743. if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
  1744. !Line->InPPDirective) {
  1745. continue;
  1746. }
  1747. if (!FormatTok->Tok.is(tok::comment))
  1748. return;
  1749. if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
  1750. CommentsInCurrentLine = false;
  1751. }
  1752. if (CommentsInCurrentLine) {
  1753. pushToken(FormatTok);
  1754. } else {
  1755. CommentsBeforeNextToken.push_back(FormatTok);
  1756. }
  1757. } while (!eof());
  1758. }
  1759. void UnwrappedLineParser::pushToken(FormatToken *Tok) {
  1760. Line->Tokens.push_back(UnwrappedLineNode(Tok));
  1761. if (MustBreakBeforeNextToken) {
  1762. Line->Tokens.back().Tok->MustBreakBefore = true;
  1763. MustBreakBeforeNextToken = false;
  1764. }
  1765. }
  1766. } // end namespace format
  1767. } // end namespace clang