PlistDiagnostics.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  1. //===--- PlistDiagnostics.cpp - Plist Diagnostics for Paths -----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the PlistDiagnostics object.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Basic/PlistSupport.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/Version.h"
  16. #include "clang/CrossTU/CrossTranslationUnit.h"
  17. #include "clang/Frontend/ASTUnit.h"
  18. #include "clang/Lex/Preprocessor.h"
  19. #include "clang/Lex/TokenConcatenation.h"
  20. #include "clang/Rewrite/Core/HTMLRewrite.h"
  21. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  22. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  23. #include "clang/StaticAnalyzer/Core/IssueHash.h"
  24. #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/Support/Casting.h"
  29. using namespace clang;
  30. using namespace ento;
  31. using namespace markup;
  32. //===----------------------------------------------------------------------===//
  33. // Declarations of helper classes and functions for emitting bug reports in
  34. // plist format.
  35. //===----------------------------------------------------------------------===//
  36. namespace {
  37. class PlistDiagnostics : public PathDiagnosticConsumer {
  38. const std::string OutputFile;
  39. const Preprocessor &PP;
  40. const cross_tu::CrossTranslationUnitContext &CTU;
  41. AnalyzerOptions &AnOpts;
  42. const bool SupportsCrossFileDiagnostics;
  43. public:
  44. PlistDiagnostics(AnalyzerOptions &AnalyzerOpts, const std::string &prefix,
  45. const Preprocessor &PP,
  46. const cross_tu::CrossTranslationUnitContext &CTU,
  47. bool supportsMultipleFiles);
  48. ~PlistDiagnostics() override {}
  49. void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
  50. FilesMade *filesMade) override;
  51. StringRef getName() const override {
  52. return "PlistDiagnostics";
  53. }
  54. PathGenerationScheme getGenerationScheme() const override {
  55. return Extensive;
  56. }
  57. bool supportsLogicalOpControlFlow() const override { return true; }
  58. bool supportsCrossFileDiagnostics() const override {
  59. return SupportsCrossFileDiagnostics;
  60. }
  61. };
  62. } // end anonymous namespace
  63. namespace {
  64. /// A helper class for emitting a single report.
  65. class PlistPrinter {
  66. const FIDMap& FM;
  67. AnalyzerOptions &AnOpts;
  68. const Preprocessor &PP;
  69. const cross_tu::CrossTranslationUnitContext &CTU;
  70. llvm::SmallVector<const PathDiagnosticMacroPiece *, 0> MacroPieces;
  71. public:
  72. PlistPrinter(const FIDMap& FM, AnalyzerOptions &AnOpts,
  73. const Preprocessor &PP,
  74. const cross_tu::CrossTranslationUnitContext &CTU)
  75. : FM(FM), AnOpts(AnOpts), PP(PP), CTU(CTU) {
  76. }
  77. void ReportDiag(raw_ostream &o, const PathDiagnosticPiece& P) {
  78. ReportPiece(o, P, /*indent*/ 4, /*depth*/ 0, /*includeControlFlow*/ true);
  79. // Don't emit a warning about an unused private field.
  80. (void)AnOpts;
  81. }
  82. /// Print the expansions of the collected macro pieces.
  83. ///
  84. /// Each time ReportDiag is called on a PathDiagnosticMacroPiece (or, if one
  85. /// is found through a call piece, etc), it's subpieces are reported, and the
  86. /// piece itself is collected. Call this function after the entire bugpath
  87. /// was reported.
  88. void ReportMacroExpansions(raw_ostream &o, unsigned indent);
  89. private:
  90. void ReportPiece(raw_ostream &o, const PathDiagnosticPiece &P,
  91. unsigned indent, unsigned depth, bool includeControlFlow,
  92. bool isKeyEvent = false) {
  93. switch (P.getKind()) {
  94. case PathDiagnosticPiece::ControlFlow:
  95. if (includeControlFlow)
  96. ReportControlFlow(o, cast<PathDiagnosticControlFlowPiece>(P), indent);
  97. break;
  98. case PathDiagnosticPiece::Call:
  99. ReportCall(o, cast<PathDiagnosticCallPiece>(P), indent,
  100. depth);
  101. break;
  102. case PathDiagnosticPiece::Event:
  103. ReportEvent(o, cast<PathDiagnosticEventPiece>(P), indent, depth,
  104. isKeyEvent);
  105. break;
  106. case PathDiagnosticPiece::Macro:
  107. ReportMacroSubPieces(o, cast<PathDiagnosticMacroPiece>(P), indent,
  108. depth);
  109. break;
  110. case PathDiagnosticPiece::Note:
  111. ReportNote(o, cast<PathDiagnosticNotePiece>(P), indent);
  112. break;
  113. case PathDiagnosticPiece::PopUp:
  114. ReportPopUp(o, cast<PathDiagnosticPopUpPiece>(P), indent);
  115. break;
  116. }
  117. }
  118. void EmitRanges(raw_ostream &o, const ArrayRef<SourceRange> Ranges,
  119. unsigned indent);
  120. void EmitMessage(raw_ostream &o, StringRef Message, unsigned indent);
  121. void ReportControlFlow(raw_ostream &o,
  122. const PathDiagnosticControlFlowPiece& P,
  123. unsigned indent);
  124. void ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P,
  125. unsigned indent, unsigned depth, bool isKeyEvent = false);
  126. void ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P,
  127. unsigned indent, unsigned depth);
  128. void ReportMacroSubPieces(raw_ostream &o, const PathDiagnosticMacroPiece& P,
  129. unsigned indent, unsigned depth);
  130. void ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P,
  131. unsigned indent);
  132. void ReportPopUp(raw_ostream &o, const PathDiagnosticPopUpPiece &P,
  133. unsigned indent);
  134. };
  135. } // end of anonymous namespace
  136. namespace {
  137. struct ExpansionInfo {
  138. std::string MacroName;
  139. std::string Expansion;
  140. ExpansionInfo(std::string N, std::string E)
  141. : MacroName(std::move(N)), Expansion(std::move(E)) {}
  142. };
  143. } // end of anonymous namespace
  144. static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM,
  145. AnalyzerOptions &AnOpts, const Preprocessor &PP,
  146. const cross_tu::CrossTranslationUnitContext &CTU,
  147. const PathPieces &Path);
  148. /// Print coverage information to output stream {@code o}.
  149. /// May modify the used list of files {@code Fids} by inserting new ones.
  150. static void printCoverage(const PathDiagnostic *D,
  151. unsigned InputIndentLevel,
  152. SmallVectorImpl<FileID> &Fids,
  153. FIDMap &FM,
  154. llvm::raw_fd_ostream &o);
  155. static ExpansionInfo
  156. getExpandedMacro(SourceLocation MacroLoc, const Preprocessor &PP,
  157. const cross_tu::CrossTranslationUnitContext &CTU);
  158. //===----------------------------------------------------------------------===//
  159. // Methods of PlistPrinter.
  160. //===----------------------------------------------------------------------===//
  161. void PlistPrinter::EmitRanges(raw_ostream &o,
  162. const ArrayRef<SourceRange> Ranges,
  163. unsigned indent) {
  164. if (Ranges.empty())
  165. return;
  166. Indent(o, indent) << "<key>ranges</key>\n";
  167. Indent(o, indent) << "<array>\n";
  168. ++indent;
  169. const SourceManager &SM = PP.getSourceManager();
  170. const LangOptions &LangOpts = PP.getLangOpts();
  171. for (auto &R : Ranges)
  172. EmitRange(o, SM,
  173. Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts),
  174. FM, indent + 1);
  175. --indent;
  176. Indent(o, indent) << "</array>\n";
  177. }
  178. void PlistPrinter::EmitMessage(raw_ostream &o, StringRef Message,
  179. unsigned indent) {
  180. // Output the text.
  181. assert(!Message.empty());
  182. Indent(o, indent) << "<key>extended_message</key>\n";
  183. Indent(o, indent);
  184. EmitString(o, Message) << '\n';
  185. // Output the short text.
  186. // FIXME: Really use a short string.
  187. Indent(o, indent) << "<key>message</key>\n";
  188. Indent(o, indent);
  189. EmitString(o, Message) << '\n';
  190. }
  191. void PlistPrinter::ReportControlFlow(raw_ostream &o,
  192. const PathDiagnosticControlFlowPiece& P,
  193. unsigned indent) {
  194. const SourceManager &SM = PP.getSourceManager();
  195. const LangOptions &LangOpts = PP.getLangOpts();
  196. Indent(o, indent) << "<dict>\n";
  197. ++indent;
  198. Indent(o, indent) << "<key>kind</key><string>control</string>\n";
  199. // Emit edges.
  200. Indent(o, indent) << "<key>edges</key>\n";
  201. ++indent;
  202. Indent(o, indent) << "<array>\n";
  203. ++indent;
  204. for (PathDiagnosticControlFlowPiece::const_iterator I=P.begin(), E=P.end();
  205. I!=E; ++I) {
  206. Indent(o, indent) << "<dict>\n";
  207. ++indent;
  208. // Make the ranges of the start and end point self-consistent with adjacent edges
  209. // by forcing to use only the beginning of the range. This simplifies the layout
  210. // logic for clients.
  211. Indent(o, indent) << "<key>start</key>\n";
  212. SourceRange StartEdge(
  213. SM.getExpansionLoc(I->getStart().asRange().getBegin()));
  214. EmitRange(o, SM, Lexer::getAsCharRange(StartEdge, SM, LangOpts), FM,
  215. indent + 1);
  216. Indent(o, indent) << "<key>end</key>\n";
  217. SourceRange EndEdge(SM.getExpansionLoc(I->getEnd().asRange().getBegin()));
  218. EmitRange(o, SM, Lexer::getAsCharRange(EndEdge, SM, LangOpts), FM,
  219. indent + 1);
  220. --indent;
  221. Indent(o, indent) << "</dict>\n";
  222. }
  223. --indent;
  224. Indent(o, indent) << "</array>\n";
  225. --indent;
  226. // Output any helper text.
  227. const auto &s = P.getString();
  228. if (!s.empty()) {
  229. Indent(o, indent) << "<key>alternate</key>";
  230. EmitString(o, s) << '\n';
  231. }
  232. --indent;
  233. Indent(o, indent) << "</dict>\n";
  234. }
  235. void PlistPrinter::ReportEvent(raw_ostream &o, const PathDiagnosticEventPiece& P,
  236. unsigned indent, unsigned depth,
  237. bool isKeyEvent) {
  238. const SourceManager &SM = PP.getSourceManager();
  239. Indent(o, indent) << "<dict>\n";
  240. ++indent;
  241. Indent(o, indent) << "<key>kind</key><string>event</string>\n";
  242. if (isKeyEvent) {
  243. Indent(o, indent) << "<key>key_event</key><true/>\n";
  244. }
  245. // Output the location.
  246. FullSourceLoc L = P.getLocation().asLocation();
  247. Indent(o, indent) << "<key>location</key>\n";
  248. EmitLocation(o, SM, L, FM, indent);
  249. // Output the ranges (if any).
  250. ArrayRef<SourceRange> Ranges = P.getRanges();
  251. EmitRanges(o, Ranges, indent);
  252. // Output the call depth.
  253. Indent(o, indent) << "<key>depth</key>";
  254. EmitInteger(o, depth) << '\n';
  255. // Output the text.
  256. EmitMessage(o, P.getString(), indent);
  257. // Finish up.
  258. --indent;
  259. Indent(o, indent); o << "</dict>\n";
  260. }
  261. void PlistPrinter::ReportCall(raw_ostream &o, const PathDiagnosticCallPiece &P,
  262. unsigned indent,
  263. unsigned depth) {
  264. if (auto callEnter = P.getCallEnterEvent())
  265. ReportPiece(o, *callEnter, indent, depth, /*includeControlFlow*/ true,
  266. P.isLastInMainSourceFile());
  267. ++depth;
  268. if (auto callEnterWithinCaller = P.getCallEnterWithinCallerEvent())
  269. ReportPiece(o, *callEnterWithinCaller, indent, depth,
  270. /*includeControlFlow*/ true);
  271. for (PathPieces::const_iterator I = P.path.begin(), E = P.path.end();I!=E;++I)
  272. ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ true);
  273. --depth;
  274. if (auto callExit = P.getCallExitEvent())
  275. ReportPiece(o, *callExit, indent, depth, /*includeControlFlow*/ true);
  276. }
  277. void PlistPrinter::ReportMacroSubPieces(raw_ostream &o,
  278. const PathDiagnosticMacroPiece& P,
  279. unsigned indent, unsigned depth) {
  280. MacroPieces.push_back(&P);
  281. for (PathPieces::const_iterator I = P.subPieces.begin(),
  282. E = P.subPieces.end();
  283. I != E; ++I) {
  284. ReportPiece(o, **I, indent, depth, /*includeControlFlow*/ false);
  285. }
  286. }
  287. void PlistPrinter::ReportMacroExpansions(raw_ostream &o, unsigned indent) {
  288. for (const PathDiagnosticMacroPiece *P : MacroPieces) {
  289. const SourceManager &SM = PP.getSourceManager();
  290. ExpansionInfo EI = getExpandedMacro(P->getLocation().asLocation(), PP, CTU);
  291. Indent(o, indent) << "<dict>\n";
  292. ++indent;
  293. // Output the location.
  294. FullSourceLoc L = P->getLocation().asLocation();
  295. Indent(o, indent) << "<key>location</key>\n";
  296. EmitLocation(o, SM, L, FM, indent);
  297. // Output the ranges (if any).
  298. ArrayRef<SourceRange> Ranges = P->getRanges();
  299. EmitRanges(o, Ranges, indent);
  300. // Output the macro name.
  301. Indent(o, indent) << "<key>name</key>";
  302. EmitString(o, EI.MacroName) << '\n';
  303. // Output what it expands into.
  304. Indent(o, indent) << "<key>expansion</key>";
  305. EmitString(o, EI.Expansion) << '\n';
  306. // Finish up.
  307. --indent;
  308. Indent(o, indent);
  309. o << "</dict>\n";
  310. }
  311. }
  312. void PlistPrinter::ReportNote(raw_ostream &o, const PathDiagnosticNotePiece& P,
  313. unsigned indent) {
  314. const SourceManager &SM = PP.getSourceManager();
  315. Indent(o, indent) << "<dict>\n";
  316. ++indent;
  317. // Output the location.
  318. FullSourceLoc L = P.getLocation().asLocation();
  319. Indent(o, indent) << "<key>location</key>\n";
  320. EmitLocation(o, SM, L, FM, indent);
  321. // Output the ranges (if any).
  322. ArrayRef<SourceRange> Ranges = P.getRanges();
  323. EmitRanges(o, Ranges, indent);
  324. // Output the text.
  325. EmitMessage(o, P.getString(), indent);
  326. // Finish up.
  327. --indent;
  328. Indent(o, indent); o << "</dict>\n";
  329. }
  330. void PlistPrinter::ReportPopUp(raw_ostream &o,
  331. const PathDiagnosticPopUpPiece &P,
  332. unsigned indent) {
  333. const SourceManager &SM = PP.getSourceManager();
  334. Indent(o, indent) << "<dict>\n";
  335. ++indent;
  336. Indent(o, indent) << "<key>kind</key><string>pop-up</string>\n";
  337. // Output the location.
  338. FullSourceLoc L = P.getLocation().asLocation();
  339. Indent(o, indent) << "<key>location</key>\n";
  340. EmitLocation(o, SM, L, FM, indent);
  341. // Output the ranges (if any).
  342. ArrayRef<SourceRange> Ranges = P.getRanges();
  343. EmitRanges(o, Ranges, indent);
  344. // Output the text.
  345. EmitMessage(o, P.getString(), indent);
  346. // Finish up.
  347. --indent;
  348. Indent(o, indent) << "</dict>\n";
  349. }
  350. //===----------------------------------------------------------------------===//
  351. // Static function definitions.
  352. //===----------------------------------------------------------------------===//
  353. /// Print coverage information to output stream {@code o}.
  354. /// May modify the used list of files {@code Fids} by inserting new ones.
  355. static void printCoverage(const PathDiagnostic *D,
  356. unsigned InputIndentLevel,
  357. SmallVectorImpl<FileID> &Fids,
  358. FIDMap &FM,
  359. llvm::raw_fd_ostream &o) {
  360. unsigned IndentLevel = InputIndentLevel;
  361. Indent(o, IndentLevel) << "<key>ExecutedLines</key>\n";
  362. Indent(o, IndentLevel) << "<dict>\n";
  363. IndentLevel++;
  364. // Mapping from file IDs to executed lines.
  365. const FilesToLineNumsMap &ExecutedLines = D->getExecutedLines();
  366. for (auto I = ExecutedLines.begin(), E = ExecutedLines.end(); I != E; ++I) {
  367. unsigned FileKey = AddFID(FM, Fids, I->first);
  368. Indent(o, IndentLevel) << "<key>" << FileKey << "</key>\n";
  369. Indent(o, IndentLevel) << "<array>\n";
  370. IndentLevel++;
  371. for (unsigned LineNo : I->second) {
  372. Indent(o, IndentLevel);
  373. EmitInteger(o, LineNo) << "\n";
  374. }
  375. IndentLevel--;
  376. Indent(o, IndentLevel) << "</array>\n";
  377. }
  378. IndentLevel--;
  379. Indent(o, IndentLevel) << "</dict>\n";
  380. assert(IndentLevel == InputIndentLevel);
  381. }
  382. static void printBugPath(llvm::raw_ostream &o, const FIDMap& FM,
  383. AnalyzerOptions &AnOpts, const Preprocessor &PP,
  384. const cross_tu::CrossTranslationUnitContext &CTU,
  385. const PathPieces &Path) {
  386. PlistPrinter Printer(FM, AnOpts, PP, CTU);
  387. assert(std::is_partitioned(
  388. Path.begin(), Path.end(),
  389. [](const std::shared_ptr<PathDiagnosticPiece> &E)
  390. { return E->getKind() == PathDiagnosticPiece::Note; }) &&
  391. "PathDiagnostic is not partitioned so that notes precede the rest");
  392. PathPieces::const_iterator FirstNonNote = std::partition_point(
  393. Path.begin(), Path.end(),
  394. [](const std::shared_ptr<PathDiagnosticPiece> &E)
  395. { return E->getKind() == PathDiagnosticPiece::Note; });
  396. PathPieces::const_iterator I = Path.begin();
  397. if (FirstNonNote != Path.begin()) {
  398. o << " <key>notes</key>\n"
  399. " <array>\n";
  400. for (; I != FirstNonNote; ++I)
  401. Printer.ReportDiag(o, **I);
  402. o << " </array>\n";
  403. }
  404. o << " <key>path</key>\n";
  405. o << " <array>\n";
  406. for (PathPieces::const_iterator E = Path.end(); I != E; ++I)
  407. Printer.ReportDiag(o, **I);
  408. o << " </array>\n";
  409. if (!AnOpts.ShouldDisplayMacroExpansions)
  410. return;
  411. o << " <key>macro_expansions</key>\n"
  412. " <array>\n";
  413. Printer.ReportMacroExpansions(o, /* indent */ 4);
  414. o << " </array>\n";
  415. }
  416. //===----------------------------------------------------------------------===//
  417. // Methods of PlistDiagnostics.
  418. //===----------------------------------------------------------------------===//
  419. PlistDiagnostics::PlistDiagnostics(
  420. AnalyzerOptions &AnalyzerOpts, const std::string &output,
  421. const Preprocessor &PP, const cross_tu::CrossTranslationUnitContext &CTU,
  422. bool supportsMultipleFiles)
  423. : OutputFile(output), PP(PP), CTU(CTU), AnOpts(AnalyzerOpts),
  424. SupportsCrossFileDiagnostics(supportsMultipleFiles) {
  425. // FIXME: Will be used by a later planned change.
  426. (void)this->CTU;
  427. }
  428. void ento::createPlistDiagnosticConsumer(
  429. AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
  430. const std::string &s, const Preprocessor &PP,
  431. const cross_tu::CrossTranslationUnitContext &CTU) {
  432. C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, CTU,
  433. /*supportsMultipleFiles*/ false));
  434. }
  435. void ento::createPlistMultiFileDiagnosticConsumer(
  436. AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
  437. const std::string &s, const Preprocessor &PP,
  438. const cross_tu::CrossTranslationUnitContext &CTU) {
  439. C.push_back(new PlistDiagnostics(AnalyzerOpts, s, PP, CTU,
  440. /*supportsMultipleFiles*/ true));
  441. }
  442. void PlistDiagnostics::FlushDiagnosticsImpl(
  443. std::vector<const PathDiagnostic *> &Diags,
  444. FilesMade *filesMade) {
  445. // Build up a set of FIDs that we use by scanning the locations and
  446. // ranges of the diagnostics.
  447. FIDMap FM;
  448. SmallVector<FileID, 10> Fids;
  449. const SourceManager& SM = PP.getSourceManager();
  450. const LangOptions &LangOpts = PP.getLangOpts();
  451. auto AddPieceFID = [&FM, &Fids, &SM](const PathDiagnosticPiece &Piece) {
  452. AddFID(FM, Fids, SM, Piece.getLocation().asLocation());
  453. ArrayRef<SourceRange> Ranges = Piece.getRanges();
  454. for (const SourceRange &Range : Ranges) {
  455. AddFID(FM, Fids, SM, Range.getBegin());
  456. AddFID(FM, Fids, SM, Range.getEnd());
  457. }
  458. };
  459. for (const PathDiagnostic *D : Diags) {
  460. SmallVector<const PathPieces *, 5> WorkList;
  461. WorkList.push_back(&D->path);
  462. while (!WorkList.empty()) {
  463. const PathPieces &Path = *WorkList.pop_back_val();
  464. for (const auto &Iter : Path) {
  465. const PathDiagnosticPiece &Piece = *Iter;
  466. AddPieceFID(Piece);
  467. if (const PathDiagnosticCallPiece *Call =
  468. dyn_cast<PathDiagnosticCallPiece>(&Piece)) {
  469. if (auto CallEnterWithin = Call->getCallEnterWithinCallerEvent())
  470. AddPieceFID(*CallEnterWithin);
  471. if (auto CallEnterEvent = Call->getCallEnterEvent())
  472. AddPieceFID(*CallEnterEvent);
  473. WorkList.push_back(&Call->path);
  474. } else if (const PathDiagnosticMacroPiece *Macro =
  475. dyn_cast<PathDiagnosticMacroPiece>(&Piece)) {
  476. WorkList.push_back(&Macro->subPieces);
  477. }
  478. }
  479. }
  480. }
  481. // Open the file.
  482. std::error_code EC;
  483. llvm::raw_fd_ostream o(OutputFile, EC, llvm::sys::fs::OF_Text);
  484. if (EC) {
  485. llvm::errs() << "warning: could not create file: " << EC.message() << '\n';
  486. return;
  487. }
  488. EmitPlistHeader(o);
  489. // Write the root object: a <dict> containing...
  490. // - "clang_version", the string representation of clang version
  491. // - "files", an <array> mapping from FIDs to file names
  492. // - "diagnostics", an <array> containing the path diagnostics
  493. o << "<dict>\n" <<
  494. " <key>clang_version</key>\n";
  495. EmitString(o, getClangFullVersion()) << '\n';
  496. o << " <key>diagnostics</key>\n"
  497. " <array>\n";
  498. for (std::vector<const PathDiagnostic*>::iterator DI=Diags.begin(),
  499. DE = Diags.end(); DI!=DE; ++DI) {
  500. o << " <dict>\n";
  501. const PathDiagnostic *D = *DI;
  502. printBugPath(o, FM, AnOpts, PP, CTU, D->path);
  503. // Output the bug type and bug category.
  504. o << " <key>description</key>";
  505. EmitString(o, D->getShortDescription()) << '\n';
  506. o << " <key>category</key>";
  507. EmitString(o, D->getCategory()) << '\n';
  508. o << " <key>type</key>";
  509. EmitString(o, D->getBugType()) << '\n';
  510. o << " <key>check_name</key>";
  511. EmitString(o, D->getCheckName()) << '\n';
  512. o << " <!-- This hash is experimental and going to change! -->\n";
  513. o << " <key>issue_hash_content_of_line_in_context</key>";
  514. PathDiagnosticLocation UPDLoc = D->getUniqueingLoc();
  515. FullSourceLoc L(SM.getExpansionLoc(UPDLoc.isValid()
  516. ? UPDLoc.asLocation()
  517. : D->getLocation().asLocation()),
  518. SM);
  519. const Decl *DeclWithIssue = D->getDeclWithIssue();
  520. EmitString(o, GetIssueHash(SM, L, D->getCheckName(), D->getBugType(),
  521. DeclWithIssue, LangOpts))
  522. << '\n';
  523. // Output information about the semantic context where
  524. // the issue occurred.
  525. if (const Decl *DeclWithIssue = D->getDeclWithIssue()) {
  526. // FIXME: handle blocks, which have no name.
  527. if (const NamedDecl *ND = dyn_cast<NamedDecl>(DeclWithIssue)) {
  528. StringRef declKind;
  529. switch (ND->getKind()) {
  530. case Decl::CXXRecord:
  531. declKind = "C++ class";
  532. break;
  533. case Decl::CXXMethod:
  534. declKind = "C++ method";
  535. break;
  536. case Decl::ObjCMethod:
  537. declKind = "Objective-C method";
  538. break;
  539. case Decl::Function:
  540. declKind = "function";
  541. break;
  542. default:
  543. break;
  544. }
  545. if (!declKind.empty()) {
  546. const std::string &declName = ND->getDeclName().getAsString();
  547. o << " <key>issue_context_kind</key>";
  548. EmitString(o, declKind) << '\n';
  549. o << " <key>issue_context</key>";
  550. EmitString(o, declName) << '\n';
  551. }
  552. // Output the bug hash for issue unique-ing. Currently, it's just an
  553. // offset from the beginning of the function.
  554. if (const Stmt *Body = DeclWithIssue->getBody()) {
  555. // If the bug uniqueing location exists, use it for the hash.
  556. // For example, this ensures that two leaks reported on the same line
  557. // will have different issue_hashes and that the hash will identify
  558. // the leak location even after code is added between the allocation
  559. // site and the end of scope (leak report location).
  560. if (UPDLoc.isValid()) {
  561. FullSourceLoc UFunL(
  562. SM.getExpansionLoc(
  563. D->getUniqueingDecl()->getBody()->getBeginLoc()),
  564. SM);
  565. o << " <key>issue_hash_function_offset</key><string>"
  566. << L.getExpansionLineNumber() - UFunL.getExpansionLineNumber()
  567. << "</string>\n";
  568. // Otherwise, use the location on which the bug is reported.
  569. } else {
  570. FullSourceLoc FunL(SM.getExpansionLoc(Body->getBeginLoc()), SM);
  571. o << " <key>issue_hash_function_offset</key><string>"
  572. << L.getExpansionLineNumber() - FunL.getExpansionLineNumber()
  573. << "</string>\n";
  574. }
  575. }
  576. }
  577. }
  578. // Output the location of the bug.
  579. o << " <key>location</key>\n";
  580. EmitLocation(o, SM, D->getLocation().asLocation(), FM, 2);
  581. // Output the diagnostic to the sub-diagnostic client, if any.
  582. if (!filesMade->empty()) {
  583. StringRef lastName;
  584. PDFileEntry::ConsumerFiles *files = filesMade->getFiles(*D);
  585. if (files) {
  586. for (PDFileEntry::ConsumerFiles::const_iterator CI = files->begin(),
  587. CE = files->end(); CI != CE; ++CI) {
  588. StringRef newName = CI->first;
  589. if (newName != lastName) {
  590. if (!lastName.empty()) {
  591. o << " </array>\n";
  592. }
  593. lastName = newName;
  594. o << " <key>" << lastName << "_files</key>\n";
  595. o << " <array>\n";
  596. }
  597. o << " <string>" << CI->second << "</string>\n";
  598. }
  599. o << " </array>\n";
  600. }
  601. }
  602. printCoverage(D, /*IndentLevel=*/2, Fids, FM, o);
  603. // Close up the entry.
  604. o << " </dict>\n";
  605. }
  606. o << " </array>\n";
  607. o << " <key>files</key>\n"
  608. " <array>\n";
  609. for (FileID FID : Fids)
  610. EmitString(o << " ", SM.getFileEntryForID(FID)->getName()) << '\n';
  611. o << " </array>\n";
  612. if (llvm::AreStatisticsEnabled() && AnOpts.ShouldSerializeStats) {
  613. o << " <key>statistics</key>\n";
  614. std::string stats;
  615. llvm::raw_string_ostream os(stats);
  616. llvm::PrintStatisticsJSON(os);
  617. os.flush();
  618. EmitString(o, html::EscapeText(stats)) << '\n';
  619. }
  620. // Finish.
  621. o << "</dict>\n</plist>\n";
  622. }
  623. //===----------------------------------------------------------------------===//
  624. // Declarations of helper functions and data structures for expanding macros.
  625. //===----------------------------------------------------------------------===//
  626. namespace {
  627. using ExpArgTokens = llvm::SmallVector<Token, 2>;
  628. /// Maps unexpanded macro arguments to expanded arguments. A macro argument may
  629. /// need to expanded further when it is nested inside another macro.
  630. class MacroArgMap : public std::map<const IdentifierInfo *, ExpArgTokens> {
  631. public:
  632. void expandFromPrevMacro(const MacroArgMap &Super);
  633. };
  634. struct MacroNameAndArgs {
  635. std::string Name;
  636. const MacroInfo *MI = nullptr;
  637. MacroArgMap Args;
  638. MacroNameAndArgs(std::string N, const MacroInfo *MI, MacroArgMap M)
  639. : Name(std::move(N)), MI(MI), Args(std::move(M)) {}
  640. };
  641. class TokenPrinter {
  642. llvm::raw_ostream &OS;
  643. const Preprocessor &PP;
  644. Token PrevTok, PrevPrevTok;
  645. TokenConcatenation ConcatInfo;
  646. public:
  647. TokenPrinter(llvm::raw_ostream &OS, const Preprocessor &PP)
  648. : OS(OS), PP(PP), ConcatInfo(PP) {
  649. PrevTok.setKind(tok::unknown);
  650. PrevPrevTok.setKind(tok::unknown);
  651. }
  652. void printToken(const Token &Tok);
  653. };
  654. } // end of anonymous namespace
  655. /// The implementation method of getMacroExpansion: It prints the expansion of
  656. /// a macro to \p Printer, and returns with the name of the macro.
  657. ///
  658. /// Since macros can be nested in one another, this function may call itself
  659. /// recursively.
  660. ///
  661. /// Unfortunately, macro arguments have to expanded manually. To understand why,
  662. /// observe the following example:
  663. ///
  664. /// #define PRINT(x) print(x)
  665. /// #define DO_SOMETHING(str) PRINT(str)
  666. ///
  667. /// DO_SOMETHING("Cute panda cubs.");
  668. ///
  669. /// As we expand the last line, we'll immediately replace PRINT(str) with
  670. /// print(x). The information that both 'str' and 'x' refers to the same string
  671. /// is an information we have to forward, hence the argument \p PrevArgs.
  672. ///
  673. /// To avoid infinite recursion we maintain the already processed tokens in
  674. /// a set. This is carried as a parameter through the recursive calls. The set
  675. /// is extended with the currently processed token and after processing it, the
  676. /// token is removed. If the token is already in the set, then recursion stops:
  677. ///
  678. /// #define f(y) x
  679. /// #define x f(x)
  680. static std::string getMacroNameAndPrintExpansion(
  681. TokenPrinter &Printer,
  682. SourceLocation MacroLoc,
  683. const Preprocessor &PP,
  684. const MacroArgMap &PrevArgs,
  685. llvm::SmallPtrSet<IdentifierInfo *, 8> &AlreadyProcessedTokens);
  686. /// Retrieves the name of the macro and what it's arguments expand into
  687. /// at \p ExpanLoc.
  688. ///
  689. /// For example, for the following macro expansion:
  690. ///
  691. /// #define SET_TO_NULL(x) x = 0
  692. /// #define NOT_SUSPICIOUS(a) \
  693. /// { \
  694. /// int b = 0; \
  695. /// } \
  696. /// SET_TO_NULL(a)
  697. ///
  698. /// int *ptr = new int(4);
  699. /// NOT_SUSPICIOUS(&ptr);
  700. /// *ptr = 5;
  701. ///
  702. /// When \p ExpanLoc references the last line, the macro name "NOT_SUSPICIOUS"
  703. /// and the MacroArgMap map { (a, &ptr) } will be returned.
  704. ///
  705. /// When \p ExpanLoc references "SET_TO_NULL(a)" within the definition of
  706. /// "NOT_SUSPICOUS", the macro name "SET_TO_NULL" and the MacroArgMap map
  707. /// { (x, a) } will be returned.
  708. static MacroNameAndArgs getMacroNameAndArgs(SourceLocation ExpanLoc,
  709. const Preprocessor &PP);
  710. /// Retrieves the ')' token that matches '(' \p It points to.
  711. static MacroInfo::tokens_iterator getMatchingRParen(
  712. MacroInfo::tokens_iterator It,
  713. MacroInfo::tokens_iterator End);
  714. /// Retrieves the macro info for \p II refers to at \p Loc. This is important
  715. /// because macros can be redefined or undefined.
  716. static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP,
  717. const SourceManager &SM,
  718. const IdentifierInfo *II,
  719. SourceLocation Loc);
  720. //===----------------------------------------------------------------------===//
  721. // Definitions of helper functions and methods for expanding macros.
  722. //===----------------------------------------------------------------------===//
  723. static ExpansionInfo
  724. getExpandedMacro(SourceLocation MacroLoc, const Preprocessor &PP,
  725. const cross_tu::CrossTranslationUnitContext &CTU) {
  726. const Preprocessor *PPToUse = &PP;
  727. if (auto LocAndUnit = CTU.getImportedFromSourceLocation(MacroLoc)) {
  728. MacroLoc = LocAndUnit->first;
  729. PPToUse = &LocAndUnit->second->getPreprocessor();
  730. }
  731. llvm::SmallString<200> ExpansionBuf;
  732. llvm::raw_svector_ostream OS(ExpansionBuf);
  733. TokenPrinter Printer(OS, *PPToUse);
  734. llvm::SmallPtrSet<IdentifierInfo*, 8> AlreadyProcessedTokens;
  735. std::string MacroName = getMacroNameAndPrintExpansion(
  736. Printer, MacroLoc, *PPToUse, MacroArgMap{}, AlreadyProcessedTokens);
  737. return { MacroName, OS.str() };
  738. }
  739. static std::string getMacroNameAndPrintExpansion(
  740. TokenPrinter &Printer,
  741. SourceLocation MacroLoc,
  742. const Preprocessor &PP,
  743. const MacroArgMap &PrevArgs,
  744. llvm::SmallPtrSet<IdentifierInfo *, 8> &AlreadyProcessedTokens) {
  745. const SourceManager &SM = PP.getSourceManager();
  746. MacroNameAndArgs Info = getMacroNameAndArgs(SM.getExpansionLoc(MacroLoc), PP);
  747. IdentifierInfo* IDInfo = PP.getIdentifierInfo(Info.Name);
  748. // TODO: If the macro definition contains another symbol then this function is
  749. // called recursively. In case this symbol is the one being defined, it will
  750. // be an infinite recursion which is stopped by this "if" statement. However,
  751. // in this case we don't get the full expansion text in the Plist file. See
  752. // the test file where "value" is expanded to "garbage_" instead of
  753. // "garbage_value".
  754. if (AlreadyProcessedTokens.find(IDInfo) != AlreadyProcessedTokens.end())
  755. return Info.Name;
  756. AlreadyProcessedTokens.insert(IDInfo);
  757. if (!Info.MI)
  758. return Info.Name;
  759. // Manually expand its arguments from the previous macro.
  760. Info.Args.expandFromPrevMacro(PrevArgs);
  761. // Iterate over the macro's tokens and stringify them.
  762. for (auto It = Info.MI->tokens_begin(), E = Info.MI->tokens_end(); It != E;
  763. ++It) {
  764. Token T = *It;
  765. // If this token is not an identifier, we only need to print it.
  766. if (T.isNot(tok::identifier)) {
  767. Printer.printToken(T);
  768. continue;
  769. }
  770. const auto *II = T.getIdentifierInfo();
  771. assert(II &&
  772. "This token is an identifier but has no IdentifierInfo!");
  773. // If this token is a macro that should be expanded inside the current
  774. // macro.
  775. if (getMacroInfoForLocation(PP, SM, II, T.getLocation())) {
  776. getMacroNameAndPrintExpansion(Printer, T.getLocation(), PP, Info.Args,
  777. AlreadyProcessedTokens);
  778. // If this is a function-like macro, skip its arguments, as
  779. // getExpandedMacro() already printed them. If this is the case, let's
  780. // first jump to the '(' token.
  781. auto N = std::next(It);
  782. if (N != E && N->is(tok::l_paren))
  783. It = getMatchingRParen(++It, E);
  784. continue;
  785. }
  786. // If this token is the current macro's argument, we should expand it.
  787. auto ArgMapIt = Info.Args.find(II);
  788. if (ArgMapIt != Info.Args.end()) {
  789. for (MacroInfo::tokens_iterator ArgIt = ArgMapIt->second.begin(),
  790. ArgEnd = ArgMapIt->second.end();
  791. ArgIt != ArgEnd; ++ArgIt) {
  792. // These tokens may still be macros, if that is the case, handle it the
  793. // same way we did above.
  794. const auto *ArgII = ArgIt->getIdentifierInfo();
  795. if (!ArgII) {
  796. Printer.printToken(*ArgIt);
  797. continue;
  798. }
  799. const auto *MI = PP.getMacroInfo(ArgII);
  800. if (!MI) {
  801. Printer.printToken(*ArgIt);
  802. continue;
  803. }
  804. getMacroNameAndPrintExpansion(Printer, ArgIt->getLocation(), PP,
  805. Info.Args, AlreadyProcessedTokens);
  806. // Peek the next token if it is a tok::l_paren. This way we can decide
  807. // if this is the application or just a reference to a function maxro
  808. // symbol:
  809. //
  810. // #define apply(f) ...
  811. // #define func(x) ...
  812. // apply(func)
  813. // apply(func(42))
  814. auto N = std::next(ArgIt);
  815. if (N != ArgEnd && N->is(tok::l_paren))
  816. ArgIt = getMatchingRParen(++ArgIt, ArgEnd);
  817. }
  818. continue;
  819. }
  820. // If control reached here, then this token isn't a macro identifier, nor an
  821. // unexpanded macro argument that we need to handle, print it.
  822. Printer.printToken(T);
  823. }
  824. AlreadyProcessedTokens.erase(IDInfo);
  825. return Info.Name;
  826. }
  827. static MacroNameAndArgs getMacroNameAndArgs(SourceLocation ExpanLoc,
  828. const Preprocessor &PP) {
  829. const SourceManager &SM = PP.getSourceManager();
  830. const LangOptions &LangOpts = PP.getLangOpts();
  831. // First, we create a Lexer to lex *at the expansion location* the tokens
  832. // referring to the macro's name and its arguments.
  833. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ExpanLoc);
  834. const llvm::MemoryBuffer *MB = SM.getBuffer(LocInfo.first);
  835. const char *MacroNameTokenPos = MB->getBufferStart() + LocInfo.second;
  836. Lexer RawLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
  837. MB->getBufferStart(), MacroNameTokenPos, MB->getBufferEnd());
  838. // Acquire the macro's name.
  839. Token TheTok;
  840. RawLexer.LexFromRawLexer(TheTok);
  841. std::string MacroName = PP.getSpelling(TheTok);
  842. const auto *II = PP.getIdentifierInfo(MacroName);
  843. assert(II && "Failed to acquire the IndetifierInfo for the macro!");
  844. const MacroInfo *MI = getMacroInfoForLocation(PP, SM, II, ExpanLoc);
  845. // assert(MI && "The macro must've been defined at it's expansion location!");
  846. //
  847. // We should always be able to obtain the MacroInfo in a given TU, but if
  848. // we're running the analyzer with CTU, the Preprocessor won't contain the
  849. // directive history (or anything for that matter) from another TU.
  850. // TODO: assert when we're not running with CTU.
  851. if (!MI)
  852. return { MacroName, MI, {} };
  853. // Acquire the macro's arguments.
  854. //
  855. // The rough idea here is to lex from the first left parentheses to the last
  856. // right parentheses, and map the macro's unexpanded arguments to what they
  857. // will be expanded to. An expanded macro argument may contain several tokens
  858. // (like '3 + 4'), so we'll lex until we find a tok::comma or tok::r_paren, at
  859. // which point we start lexing the next argument or finish.
  860. ArrayRef<const IdentifierInfo *> MacroArgs = MI->params();
  861. if (MacroArgs.empty())
  862. return { MacroName, MI, {} };
  863. RawLexer.LexFromRawLexer(TheTok);
  864. // When this is a token which expands to another macro function then its
  865. // parentheses are not at its expansion locaiton. For example:
  866. //
  867. // #define foo(x) int bar() { return x; }
  868. // #define apply_zero(f) f(0)
  869. // apply_zero(foo)
  870. // ^
  871. // This is not a tok::l_paren, but foo is a function.
  872. if (TheTok.isNot(tok::l_paren))
  873. return { MacroName, MI, {} };
  874. MacroArgMap Args;
  875. // When the macro's argument is a function call, like
  876. // CALL_FN(someFunctionName(param1, param2))
  877. // we will find tok::l_paren, tok::r_paren, and tok::comma that do not divide
  878. // actual macro arguments, or do not represent the macro argument's closing
  879. // parentheses, so we'll count how many parentheses aren't closed yet.
  880. // If ParanthesesDepth
  881. // * = 0, then there are no more arguments to lex.
  882. // * = 1, then if we find a tok::comma, we can start lexing the next arg.
  883. // * > 1, then tok::comma is a part of the current arg.
  884. int ParenthesesDepth = 1;
  885. // If we encounter __VA_ARGS__, we will lex until the closing tok::r_paren,
  886. // even if we lex a tok::comma and ParanthesesDepth == 1.
  887. const IdentifierInfo *__VA_ARGS__II = PP.getIdentifierInfo("__VA_ARGS__");
  888. for (const IdentifierInfo *UnexpArgII : MacroArgs) {
  889. MacroArgMap::mapped_type ExpandedArgTokens;
  890. // One could also simply not supply a single argument to __VA_ARGS__ -- this
  891. // results in a preprocessor warning, but is not an error:
  892. // #define VARIADIC(ptr, ...) \
  893. // someVariadicTemplateFunction(__VA_ARGS__)
  894. //
  895. // int *ptr;
  896. // VARIADIC(ptr); // Note that there are no commas, this isn't just an
  897. // // empty parameter -- there are no parameters for '...'.
  898. // In any other case, ParenthesesDepth mustn't be 0 here.
  899. if (ParenthesesDepth != 0) {
  900. // Lex the first token of the next macro parameter.
  901. RawLexer.LexFromRawLexer(TheTok);
  902. while (!(ParenthesesDepth == 1 &&
  903. (UnexpArgII == __VA_ARGS__II ? false : TheTok.is(tok::comma)))) {
  904. assert(TheTok.isNot(tok::eof) &&
  905. "EOF encountered while looking for expanded macro args!");
  906. if (TheTok.is(tok::l_paren))
  907. ++ParenthesesDepth;
  908. if (TheTok.is(tok::r_paren))
  909. --ParenthesesDepth;
  910. if (ParenthesesDepth == 0)
  911. break;
  912. if (TheTok.is(tok::raw_identifier))
  913. PP.LookUpIdentifierInfo(TheTok);
  914. ExpandedArgTokens.push_back(TheTok);
  915. RawLexer.LexFromRawLexer(TheTok);
  916. }
  917. } else {
  918. assert(UnexpArgII == __VA_ARGS__II);
  919. }
  920. Args.emplace(UnexpArgII, std::move(ExpandedArgTokens));
  921. }
  922. assert(TheTok.is(tok::r_paren) &&
  923. "Expanded macro argument acquisition failed! After the end of the loop"
  924. " this token should be ')'!");
  925. return { MacroName, MI, Args };
  926. }
  927. static MacroInfo::tokens_iterator getMatchingRParen(
  928. MacroInfo::tokens_iterator It,
  929. MacroInfo::tokens_iterator End) {
  930. assert(It->is(tok::l_paren) && "This token should be '('!");
  931. // Skip until we find the closing ')'.
  932. int ParenthesesDepth = 1;
  933. while (ParenthesesDepth != 0) {
  934. ++It;
  935. assert(It->isNot(tok::eof) &&
  936. "Encountered EOF while attempting to skip macro arguments!");
  937. assert(It != End &&
  938. "End of the macro definition reached before finding ')'!");
  939. if (It->is(tok::l_paren))
  940. ++ParenthesesDepth;
  941. if (It->is(tok::r_paren))
  942. --ParenthesesDepth;
  943. }
  944. return It;
  945. }
  946. static const MacroInfo *getMacroInfoForLocation(const Preprocessor &PP,
  947. const SourceManager &SM,
  948. const IdentifierInfo *II,
  949. SourceLocation Loc) {
  950. const MacroDirective *MD = PP.getLocalMacroDirectiveHistory(II);
  951. if (!MD)
  952. return nullptr;
  953. return MD->findDirectiveAtLoc(Loc, SM).getMacroInfo();
  954. }
  955. void MacroArgMap::expandFromPrevMacro(const MacroArgMap &Super) {
  956. for (value_type &Pair : *this) {
  957. ExpArgTokens &CurrExpArgTokens = Pair.second;
  958. // For each token in the expanded macro argument.
  959. auto It = CurrExpArgTokens.begin();
  960. while (It != CurrExpArgTokens.end()) {
  961. if (It->isNot(tok::identifier)) {
  962. ++It;
  963. continue;
  964. }
  965. const auto *II = It->getIdentifierInfo();
  966. assert(II);
  967. // Is this an argument that "Super" expands further?
  968. if (!Super.count(II)) {
  969. ++It;
  970. continue;
  971. }
  972. const ExpArgTokens &SuperExpArgTokens = Super.at(II);
  973. It = CurrExpArgTokens.insert(
  974. It, SuperExpArgTokens.begin(), SuperExpArgTokens.end());
  975. std::advance(It, SuperExpArgTokens.size());
  976. It = CurrExpArgTokens.erase(It);
  977. }
  978. }
  979. }
  980. void TokenPrinter::printToken(const Token &Tok) {
  981. // If this is the first token to be printed, don't print space.
  982. if (PrevTok.isNot(tok::unknown)) {
  983. // If the tokens were already space separated, or if they must be to avoid
  984. // them being implicitly pasted, add a space between them.
  985. if(Tok.hasLeadingSpace() || ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok,
  986. Tok)) {
  987. // AvoidConcat doesn't check for ##, don't print a space around it.
  988. if (PrevTok.isNot(tok::hashhash) && Tok.isNot(tok::hashhash)) {
  989. OS << ' ';
  990. }
  991. }
  992. }
  993. if (!Tok.isOneOf(tok::hash, tok::hashhash)) {
  994. if (PrevTok.is(tok::hash))
  995. OS << '\"' << PP.getSpelling(Tok) << '\"';
  996. else
  997. OS << PP.getSpelling(Tok);
  998. }
  999. PrevPrevTok = PrevTok;
  1000. PrevTok = Tok;
  1001. }