MacroCallReconstructor.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. //===--- MacroCallReconstructor.cpp - Format C++ code -----------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// This file contains the implementation of MacroCallReconstructor, which fits
  12. /// an reconstructed macro call to a parsed set of UnwrappedLines.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "Macros.h"
  16. #include "UnwrappedLineParser.h"
  17. #include "clang/Basic/TokenKinds.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/Support/Debug.h"
  20. #include <cassert>
  21. #define DEBUG_TYPE "format-reconstruct"
  22. namespace clang {
  23. namespace format {
  24. // Call \p Call for each token in the unwrapped line given, passing
  25. // the token, its parent and whether it is the first token in the line.
  26. template <typename T>
  27. void forEachToken(const UnwrappedLine &Line, const T &Call,
  28. FormatToken *Parent = nullptr) {
  29. bool First = true;
  30. for (const auto &N : Line.Tokens) {
  31. Call(N.Tok, Parent, First);
  32. First = false;
  33. for (const auto &Child : N.Children)
  34. forEachToken(Child, Call, N.Tok);
  35. }
  36. }
  37. MacroCallReconstructor::MacroCallReconstructor(
  38. unsigned Level,
  39. const llvm::DenseMap<FormatToken *, std::unique_ptr<UnwrappedLine>>
  40. &ActiveExpansions)
  41. : Level(Level), IdToReconstructed(ActiveExpansions) {
  42. Result.Tokens.push_back(std::make_unique<LineNode>());
  43. ActiveReconstructedLines.push_back(&Result);
  44. }
  45. void MacroCallReconstructor::addLine(const UnwrappedLine &Line) {
  46. assert(State != Finalized);
  47. LLVM_DEBUG(llvm::dbgs() << "MCR: new line...\n");
  48. forEachToken(Line, [&](FormatToken *Token, FormatToken *Parent, bool First) {
  49. add(Token, Parent, First);
  50. });
  51. assert(InProgress || finished());
  52. }
  53. UnwrappedLine MacroCallReconstructor::takeResult() && {
  54. finalize();
  55. assert(Result.Tokens.size() == 1 &&
  56. Result.Tokens.front()->Children.size() == 1);
  57. UnwrappedLine Final =
  58. createUnwrappedLine(*Result.Tokens.front()->Children.front(), Level);
  59. assert(!Final.Tokens.empty());
  60. return Final;
  61. }
  62. // Reconstruct the position of the next \p Token, given its parent \p
  63. // ExpandedParent in the incoming unwrapped line. \p First specifies whether it
  64. // is the first token in a given unwrapped line.
  65. void MacroCallReconstructor::add(FormatToken *Token,
  66. FormatToken *ExpandedParent, bool First) {
  67. LLVM_DEBUG(
  68. llvm::dbgs() << "MCR: Token: " << Token->TokenText << ", Parent: "
  69. << (ExpandedParent ? ExpandedParent->TokenText : "<null>")
  70. << ", First: " << First << "\n");
  71. // In order to be able to find the correct parent in the reconstructed token
  72. // stream, we need to continue the last open reconstruction until we find the
  73. // given token if it is part of the reconstructed token stream.
  74. //
  75. // Note that hidden tokens can be part of the reconstructed stream in nested
  76. // macro calls.
  77. // For example, given
  78. // #define C(x, y) x y
  79. // #define B(x) {x}
  80. // And the call:
  81. // C(a, B(b))
  82. // The outer macro call will be C(a, {b}), and the hidden token '}' can be
  83. // found in the reconstructed token stream of that expansion level.
  84. // In the expanded token stream
  85. // a {b}
  86. // 'b' is a child of '{'. We need to continue the open expansion of the ','
  87. // in the call of 'C' in order to correctly set the ',' as the parent of '{',
  88. // so we later set the spelled token 'b' as a child of the ','.
  89. if (!ActiveExpansions.empty() && Token->MacroCtx &&
  90. (Token->MacroCtx->Role != MR_Hidden ||
  91. ActiveExpansions.size() != Token->MacroCtx->ExpandedFrom.size())) {
  92. if (/*PassedMacroComma = */ reconstructActiveCallUntil(Token))
  93. First = true;
  94. }
  95. prepareParent(ExpandedParent, First);
  96. if (Token->MacroCtx) {
  97. // If this token was generated by a macro call, add the reconstructed
  98. // equivalent of the token.
  99. reconstruct(Token);
  100. } else {
  101. // Otherwise, we add it to the current line.
  102. appendToken(Token);
  103. }
  104. }
  105. // Adjusts the stack of active reconstructed lines so we're ready to push
  106. // tokens. The tokens to be pushed are children of ExpandedParent in the
  107. // expanded code.
  108. //
  109. // This may entail:
  110. // - creating a new line, if the parent is on the active line
  111. // - popping active lines, if the parent is further up the stack
  112. //
  113. // Postcondition:
  114. // ActiveReconstructedLines.back() is the line that has \p ExpandedParent or its
  115. // reconstructed replacement token as a parent (when possible) - that is, the
  116. // last token in \c ActiveReconstructedLines[ActiveReconstructedLines.size()-2]
  117. // is the parent of ActiveReconstructedLines.back() in the reconstructed
  118. // unwrapped line.
  119. void MacroCallReconstructor::prepareParent(FormatToken *ExpandedParent,
  120. bool NewLine) {
  121. LLVM_DEBUG({
  122. llvm::dbgs() << "ParentMap:\n";
  123. debugParentMap();
  124. });
  125. // We want to find the parent in the new unwrapped line, where the expanded
  126. // parent might have been replaced during reconstruction.
  127. FormatToken *Parent = getParentInResult(ExpandedParent);
  128. LLVM_DEBUG(llvm::dbgs() << "MCR: New parent: "
  129. << (Parent ? Parent->TokenText : "<null>") << "\n");
  130. FormatToken *OpenMacroParent = nullptr;
  131. if (!MacroCallStructure.empty()) {
  132. // Inside a macro expansion, it is possible to lose track of the correct
  133. // parent - either because it is already popped, for example because it was
  134. // in a different macro argument (e.g. M({, })), or when we work on invalid
  135. // code.
  136. // Thus, we use the innermost macro call's parent as the parent at which
  137. // we stop; this allows us to stay within the macro expansion and keeps
  138. // any problems confined to the extent of the macro call.
  139. OpenMacroParent =
  140. getParentInResult(MacroCallStructure.back().MacroCallLParen);
  141. LLVM_DEBUG(llvm::dbgs()
  142. << "MacroCallLParen: "
  143. << MacroCallStructure.back().MacroCallLParen->TokenText
  144. << ", OpenMacroParent: "
  145. << (OpenMacroParent ? OpenMacroParent->TokenText : "<null>")
  146. << "\n");
  147. }
  148. if (NewLine ||
  149. (!ActiveReconstructedLines.back()->Tokens.empty() &&
  150. Parent == ActiveReconstructedLines.back()->Tokens.back()->Tok)) {
  151. // If we are at the first token in a new line, we want to also
  152. // create a new line in the resulting reconstructed unwrapped line.
  153. while (ActiveReconstructedLines.back()->Tokens.empty() ||
  154. (Parent != ActiveReconstructedLines.back()->Tokens.back()->Tok &&
  155. ActiveReconstructedLines.back()->Tokens.back()->Tok !=
  156. OpenMacroParent)) {
  157. ActiveReconstructedLines.pop_back();
  158. assert(!ActiveReconstructedLines.empty());
  159. }
  160. assert(!ActiveReconstructedLines.empty());
  161. ActiveReconstructedLines.back()->Tokens.back()->Children.push_back(
  162. std::make_unique<ReconstructedLine>());
  163. ActiveReconstructedLines.push_back(
  164. &*ActiveReconstructedLines.back()->Tokens.back()->Children.back());
  165. } else if (parentLine().Tokens.back()->Tok != Parent) {
  166. // If we're not the first token in a new line, pop lines until we find
  167. // the child of \c Parent in the stack.
  168. while (Parent != parentLine().Tokens.back()->Tok &&
  169. parentLine().Tokens.back()->Tok &&
  170. parentLine().Tokens.back()->Tok != OpenMacroParent) {
  171. ActiveReconstructedLines.pop_back();
  172. assert(!ActiveReconstructedLines.empty());
  173. }
  174. }
  175. assert(!ActiveReconstructedLines.empty());
  176. }
  177. // For a given \p Parent in the incoming expanded token stream, find the
  178. // corresponding parent in the output.
  179. FormatToken *MacroCallReconstructor::getParentInResult(FormatToken *Parent) {
  180. FormatToken *Mapped = SpelledParentToReconstructedParent.lookup(Parent);
  181. if (!Mapped)
  182. return Parent;
  183. for (; Mapped; Mapped = SpelledParentToReconstructedParent.lookup(Parent))
  184. Parent = Mapped;
  185. // If we use a different token than the parent in the expanded token stream
  186. // as parent, mark it as a special parent, so the formatting code knows it
  187. // needs to have its children formatted.
  188. Parent->MacroParent = true;
  189. return Parent;
  190. }
  191. // Reconstruct a \p Token that was expanded from a macro call.
  192. void MacroCallReconstructor::reconstruct(FormatToken *Token) {
  193. assert(Token->MacroCtx);
  194. // A single token can be the only result of a macro call:
  195. // Given: #define ID(x, y) ;
  196. // And the call: ID(<some>, <tokens>)
  197. // ';' in the expanded stream will reconstruct all of ID(<some>, <tokens>).
  198. if (Token->MacroCtx->StartOfExpansion) {
  199. startReconstruction(Token);
  200. // If the order of tokens in the expanded token stream is not the
  201. // same as the order of tokens in the reconstructed stream, we need
  202. // to reconstruct tokens that arrive later in the stream.
  203. if (Token->MacroCtx->Role != MR_Hidden)
  204. reconstructActiveCallUntil(Token);
  205. }
  206. assert(!ActiveExpansions.empty());
  207. if (ActiveExpansions.back().SpelledI != ActiveExpansions.back().SpelledE) {
  208. assert(ActiveExpansions.size() == Token->MacroCtx->ExpandedFrom.size());
  209. if (Token->MacroCtx->Role != MR_Hidden) {
  210. // The current token in the reconstructed token stream must be the token
  211. // we're looking for - we either arrive here after startReconstruction,
  212. // which initiates the stream to the first token, or after
  213. // continueReconstructionUntil skipped until the expected token in the
  214. // reconstructed stream at the start of add(...).
  215. assert(ActiveExpansions.back().SpelledI->Tok == Token);
  216. processNextReconstructed();
  217. } else if (!currentLine()->Tokens.empty()) {
  218. // Map all hidden tokens to the last visible token in the output.
  219. // If the hidden token is a parent, we'll use the last visible
  220. // token as the parent of the hidden token's children.
  221. SpelledParentToReconstructedParent[Token] =
  222. currentLine()->Tokens.back()->Tok;
  223. } else {
  224. for (auto I = ActiveReconstructedLines.rbegin(),
  225. E = ActiveReconstructedLines.rend();
  226. I != E; ++I) {
  227. if (!(*I)->Tokens.empty()) {
  228. SpelledParentToReconstructedParent[Token] = (*I)->Tokens.back()->Tok;
  229. break;
  230. }
  231. }
  232. }
  233. }
  234. if (Token->MacroCtx->EndOfExpansion)
  235. endReconstruction(Token);
  236. }
  237. // Given a \p Token that starts an expansion, reconstruct the beginning of the
  238. // macro call.
  239. // For example, given: #define ID(x) x
  240. // And the call: ID(int a)
  241. // Reconstructs: ID(
  242. void MacroCallReconstructor::startReconstruction(FormatToken *Token) {
  243. assert(Token->MacroCtx);
  244. assert(!Token->MacroCtx->ExpandedFrom.empty());
  245. assert(ActiveExpansions.size() <= Token->MacroCtx->ExpandedFrom.size());
  246. #ifndef NDEBUG
  247. // Check that the token's reconstruction stack matches our current
  248. // reconstruction stack.
  249. for (size_t I = 0; I < ActiveExpansions.size(); ++I) {
  250. assert(ActiveExpansions[I].ID ==
  251. Token->MacroCtx
  252. ->ExpandedFrom[Token->MacroCtx->ExpandedFrom.size() - 1 - I]);
  253. }
  254. #endif
  255. // Start reconstruction for all calls for which this token is the first token
  256. // generated by the call.
  257. // Note that the token's expanded from stack is inside-to-outside, and the
  258. // expansions for which this token is not the first are the outermost ones.
  259. ArrayRef<FormatToken *> StartedMacros =
  260. ArrayRef(Token->MacroCtx->ExpandedFrom)
  261. .drop_back(ActiveExpansions.size());
  262. assert(StartedMacros.size() == Token->MacroCtx->StartOfExpansion);
  263. // We reconstruct macro calls outside-to-inside.
  264. for (FormatToken *ID : llvm::reverse(StartedMacros)) {
  265. // We found a macro call to be reconstructed; the next time our
  266. // reconstruction stack is empty we know we finished an reconstruction.
  267. #ifndef NDEBUG
  268. State = InProgress;
  269. #endif
  270. // Put the reconstructed macro call's token into our reconstruction stack.
  271. auto IU = IdToReconstructed.find(ID);
  272. assert(IU != IdToReconstructed.end());
  273. ActiveExpansions.push_back(
  274. {ID, IU->second->Tokens.begin(), IU->second->Tokens.end()});
  275. // Process the macro call's identifier.
  276. processNextReconstructed();
  277. if (ActiveExpansions.back().SpelledI == ActiveExpansions.back().SpelledE)
  278. continue;
  279. if (ActiveExpansions.back().SpelledI->Tok->is(tok::l_paren)) {
  280. // Process the optional opening parenthesis.
  281. processNextReconstructed();
  282. }
  283. }
  284. }
  285. // Add all tokens in the reconstruction stream to the output until we find the
  286. // given \p Token.
  287. bool MacroCallReconstructor::reconstructActiveCallUntil(FormatToken *Token) {
  288. assert(!ActiveExpansions.empty());
  289. bool PassedMacroComma = false;
  290. // FIXME: If Token was already expanded earlier, due to
  291. // a change in order, we will not find it, but need to
  292. // skip it.
  293. while (ActiveExpansions.back().SpelledI != ActiveExpansions.back().SpelledE &&
  294. ActiveExpansions.back().SpelledI->Tok != Token) {
  295. PassedMacroComma = processNextReconstructed() || PassedMacroComma;
  296. }
  297. return PassedMacroComma;
  298. }
  299. // End all reconstructions for which \p Token is the final token.
  300. void MacroCallReconstructor::endReconstruction(FormatToken *Token) {
  301. assert(Token->MacroCtx &&
  302. (ActiveExpansions.size() >= Token->MacroCtx->EndOfExpansion));
  303. for (size_t I = 0; I < Token->MacroCtx->EndOfExpansion; ++I) {
  304. #ifndef NDEBUG
  305. // Check all remaining tokens but the final closing parenthesis and optional
  306. // trailing comment were already reconstructed at an inner expansion level.
  307. for (auto T = ActiveExpansions.back().SpelledI;
  308. T != ActiveExpansions.back().SpelledE; ++T) {
  309. FormatToken *Token = T->Tok;
  310. bool ClosingParen = (std::next(T) == ActiveExpansions.back().SpelledE ||
  311. std::next(T)->Tok->isTrailingComment()) &&
  312. !Token->MacroCtx && Token->is(tok::r_paren);
  313. bool TrailingComment = Token->isTrailingComment();
  314. bool PreviousLevel =
  315. Token->MacroCtx &&
  316. (ActiveExpansions.size() < Token->MacroCtx->ExpandedFrom.size());
  317. if (!ClosingParen && !TrailingComment && !PreviousLevel)
  318. llvm::dbgs() << "At token: " << Token->TokenText << "\n";
  319. // In addition to the following cases, we can also run into this
  320. // when a macro call had more arguments than expected; in that case,
  321. // the comma and the remaining tokens in the macro call will potentially
  322. // end up in the line when we finish the expansion.
  323. // FIXME: Add the information which arguments are unused, and assert
  324. // one of the cases below plus reconstructed macro argument tokens.
  325. // assert(ClosingParen || TrailingComment || PreviousLevel);
  326. }
  327. #endif
  328. // Handle the remaining open tokens:
  329. // - expand the closing parenthesis, if it exists, including an optional
  330. // trailing comment
  331. // - handle tokens that were already reconstructed at an inner expansion
  332. // level
  333. // - handle tokens when a macro call had more than the expected number of
  334. // arguments, i.e. when #define M(x) is called as M(a, b, c) we'll end
  335. // up with the sequence ", b, c)" being open at the end of the
  336. // reconstruction; we want to gracefully handle that case
  337. //
  338. // FIXME: See the above debug-check for what we will need to do to be
  339. // able to assert this.
  340. for (auto T = ActiveExpansions.back().SpelledI;
  341. T != ActiveExpansions.back().SpelledE; ++T) {
  342. processNextReconstructed();
  343. }
  344. ActiveExpansions.pop_back();
  345. }
  346. }
  347. void MacroCallReconstructor::debugParentMap() const {
  348. llvm::DenseSet<FormatToken *> Values;
  349. for (const auto &P : SpelledParentToReconstructedParent)
  350. Values.insert(P.second);
  351. for (const auto &P : SpelledParentToReconstructedParent) {
  352. if (Values.contains(P.first))
  353. continue;
  354. llvm::dbgs() << (P.first ? P.first->TokenText : "<null>");
  355. for (auto I = SpelledParentToReconstructedParent.find(P.first),
  356. E = SpelledParentToReconstructedParent.end();
  357. I != E; I = SpelledParentToReconstructedParent.find(I->second)) {
  358. llvm::dbgs() << " -> " << (I->second ? I->second->TokenText : "<null>");
  359. }
  360. llvm::dbgs() << "\n";
  361. }
  362. }
  363. // If visible, add the next token of the reconstructed token sequence to the
  364. // output. Returns whether reconstruction passed a comma that is part of a
  365. // macro call.
  366. bool MacroCallReconstructor::processNextReconstructed() {
  367. FormatToken *Token = ActiveExpansions.back().SpelledI->Tok;
  368. ++ActiveExpansions.back().SpelledI;
  369. if (Token->MacroCtx) {
  370. // Skip tokens that are not part of the macro call.
  371. if (Token->MacroCtx->Role == MR_Hidden)
  372. return false;
  373. // Skip tokens we already expanded during an inner reconstruction.
  374. // For example, given: #define ID(x) {x}
  375. // And the call: ID(ID(f))
  376. // We get two reconstructions:
  377. // ID(f) -> {f}
  378. // ID({f}) -> {{f}}
  379. // We reconstruct f during the first reconstruction, and skip it during the
  380. // second reconstruction.
  381. if (ActiveExpansions.size() < Token->MacroCtx->ExpandedFrom.size())
  382. return false;
  383. }
  384. // Tokens that do not have a macro context are tokens in that are part of the
  385. // macro call that have not taken part in expansion.
  386. if (!Token->MacroCtx) {
  387. // Put the parentheses and commas of a macro call into the same line;
  388. // if the arguments produce new unwrapped lines, they will become children
  389. // of the corresponding opening parenthesis or comma tokens in the
  390. // reconstructed call.
  391. if (Token->is(tok::l_paren)) {
  392. MacroCallStructure.push_back(MacroCallState(
  393. currentLine(), parentLine().Tokens.back()->Tok, Token));
  394. // All tokens that are children of the previous line's last token in the
  395. // reconstructed token stream will now be children of the l_paren token.
  396. // For example, for the line containing the macro calls:
  397. // auto x = ID({ID(2)});
  398. // We will build up a map <null> -> ( -> ( with the first and second
  399. // l_paren of the macro call respectively. New lines that come in with a
  400. // <null> parent will then become children of the l_paren token of the
  401. // currently innermost macro call.
  402. SpelledParentToReconstructedParent[MacroCallStructure.back()
  403. .ParentLastToken] = Token;
  404. appendToken(Token);
  405. prepareParent(Token, /*NewLine=*/true);
  406. Token->MacroParent = true;
  407. return false;
  408. }
  409. if (!MacroCallStructure.empty()) {
  410. if (Token->is(tok::comma)) {
  411. // Make new lines inside the next argument children of the comma token.
  412. SpelledParentToReconstructedParent
  413. [MacroCallStructure.back().Line->Tokens.back()->Tok] = Token;
  414. Token->MacroParent = true;
  415. appendToken(Token, MacroCallStructure.back().Line);
  416. prepareParent(Token, /*NewLine=*/true);
  417. return true;
  418. }
  419. if (Token->is(tok::r_paren)) {
  420. appendToken(Token, MacroCallStructure.back().Line);
  421. SpelledParentToReconstructedParent.erase(
  422. MacroCallStructure.back().ParentLastToken);
  423. MacroCallStructure.pop_back();
  424. return false;
  425. }
  426. }
  427. }
  428. // Note that any tokens that are tagged with MR_None have been passed as
  429. // arguments to the macro that have not been expanded, for example:
  430. // Given: #define ID(X) x
  431. // When calling: ID(a, b)
  432. // 'b' will be part of the reconstructed token stream, but tagged MR_None.
  433. // Given that erroring out in this case would be disruptive, we continue
  434. // pushing the (unformatted) token.
  435. // FIXME: This can lead to unfortunate formatting decisions - give the user
  436. // a hint that their macro definition is broken.
  437. appendToken(Token);
  438. return false;
  439. }
  440. void MacroCallReconstructor::finalize() {
  441. #ifndef NDEBUG
  442. assert(State != Finalized && finished());
  443. State = Finalized;
  444. #endif
  445. // We created corresponding unwrapped lines for each incoming line as children
  446. // the the toplevel null token.
  447. assert(Result.Tokens.size() == 1 && !Result.Tokens.front()->Children.empty());
  448. LLVM_DEBUG({
  449. llvm::dbgs() << "Finalizing reconstructed lines:\n";
  450. debug(Result, 0);
  451. });
  452. // The first line becomes the top level line in the resulting unwrapped line.
  453. LineNode &Top = *Result.Tokens.front();
  454. auto *I = Top.Children.begin();
  455. // Every subsequent line will become a child of the last token in the previous
  456. // line, which is the token prior to the first token in the line.
  457. LineNode *Last = (*I)->Tokens.back().get();
  458. ++I;
  459. for (auto *E = Top.Children.end(); I != E; ++I) {
  460. assert(Last->Children.empty());
  461. Last->Children.push_back(std::move(*I));
  462. // Mark the previous line's last token as generated by a macro expansion
  463. // so the formatting algorithm can take that into account.
  464. Last->Tok->MacroParent = true;
  465. Last = Last->Children.back()->Tokens.back().get();
  466. }
  467. Top.Children.resize(1);
  468. }
  469. void MacroCallReconstructor::appendToken(FormatToken *Token,
  470. ReconstructedLine *L) {
  471. L = L ? L : currentLine();
  472. LLVM_DEBUG(llvm::dbgs() << "-> " << Token->TokenText << "\n");
  473. L->Tokens.push_back(std::make_unique<LineNode>(Token));
  474. }
  475. UnwrappedLine
  476. MacroCallReconstructor::createUnwrappedLine(const ReconstructedLine &Line,
  477. int Level) {
  478. UnwrappedLine Result;
  479. Result.Level = Level;
  480. for (const auto &N : Line.Tokens) {
  481. Result.Tokens.push_back(N->Tok);
  482. UnwrappedLineNode &Current = Result.Tokens.back();
  483. for (const auto &Child : N->Children) {
  484. if (Child->Tokens.empty())
  485. continue;
  486. Current.Children.push_back(createUnwrappedLine(*Child, Level + 1));
  487. }
  488. if (Current.Children.size() == 1 &&
  489. Current.Tok->isOneOf(tok::l_paren, tok::comma)) {
  490. Result.Tokens.splice(Result.Tokens.end(),
  491. Current.Children.front().Tokens);
  492. Current.Children.clear();
  493. }
  494. }
  495. return Result;
  496. }
  497. void MacroCallReconstructor::debug(const ReconstructedLine &Line, int Level) {
  498. for (int i = 0; i < Level; ++i)
  499. llvm::dbgs() << " ";
  500. for (const auto &N : Line.Tokens) {
  501. if (!N)
  502. continue;
  503. if (N->Tok)
  504. llvm::dbgs() << N->Tok->TokenText << " ";
  505. for (const auto &Child : N->Children) {
  506. llvm::dbgs() << "\n";
  507. debug(*Child, Level + 1);
  508. for (int i = 0; i < Level; ++i)
  509. llvm::dbgs() << " ";
  510. }
  511. }
  512. llvm::dbgs() << "\n";
  513. }
  514. MacroCallReconstructor::ReconstructedLine &
  515. MacroCallReconstructor::parentLine() {
  516. return **std::prev(std::prev(ActiveReconstructedLines.end()));
  517. }
  518. MacroCallReconstructor::ReconstructedLine *
  519. MacroCallReconstructor::currentLine() {
  520. return ActiveReconstructedLines.back();
  521. }
  522. MacroCallReconstructor::MacroCallState::MacroCallState(
  523. MacroCallReconstructor::ReconstructedLine *Line,
  524. FormatToken *ParentLastToken, FormatToken *MacroCallLParen)
  525. : Line(Line), ParentLastToken(ParentLastToken),
  526. MacroCallLParen(MacroCallLParen) {
  527. LLVM_DEBUG(
  528. llvm::dbgs() << "ParentLastToken: "
  529. << (ParentLastToken ? ParentLastToken->TokenText : "<null>")
  530. << "\n");
  531. assert(MacroCallLParen->is(tok::l_paren));
  532. }
  533. } // namespace format
  534. } // namespace clang