ClangDocMain.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //===-- ClangDocMain.cpp - ClangDoc -----------------------------*- 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 tool for generating C and C++ documentation from source code
  10. // and comments. Generally, it runs a LibTooling FrontendAction on source files,
  11. // mapping each declaration in those files to its USR and serializing relevant
  12. // information into LLVM bitcode. It then runs a pass over the collected
  13. // declaration information, reducing by USR. There is an option to dump this
  14. // intermediate result to bitcode. Finally, it hands the reduced information
  15. // off to a generator, which does the final parsing from the intermediate
  16. // representation to the desired output format.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #include "BitcodeReader.h"
  20. #include "BitcodeWriter.h"
  21. #include "ClangDoc.h"
  22. #include "Generators.h"
  23. #include "Representation.h"
  24. #include "clang/AST/AST.h"
  25. #include "clang/AST/Decl.h"
  26. #include "clang/ASTMatchers/ASTMatchFinder.h"
  27. #include "clang/ASTMatchers/ASTMatchersInternal.h"
  28. #include "clang/Driver/Options.h"
  29. #include "clang/Frontend/FrontendActions.h"
  30. #include "clang/Tooling/AllTUsExecution.h"
  31. #include "clang/Tooling/CommonOptionsParser.h"
  32. #include "clang/Tooling/Execution.h"
  33. #include "clang/Tooling/Tooling.h"
  34. #include "llvm/ADT/APFloat.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Error.h"
  37. #include "llvm/Support/FileSystem.h"
  38. #include "llvm/Support/Mutex.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/Signals.h"
  42. #include "llvm/Support/ThreadPool.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include <atomic>
  45. #include <string>
  46. using namespace clang::ast_matchers;
  47. using namespace clang::tooling;
  48. using namespace clang;
  49. static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  50. static llvm::cl::OptionCategory ClangDocCategory("clang-doc options");
  51. static llvm::cl::opt<std::string>
  52. ProjectName("project-name", llvm::cl::desc("Name of project."),
  53. llvm::cl::cat(ClangDocCategory));
  54. static llvm::cl::opt<bool> IgnoreMappingFailures(
  55. "ignore-map-errors",
  56. llvm::cl::desc("Continue if files are not mapped correctly."),
  57. llvm::cl::init(true), llvm::cl::cat(ClangDocCategory));
  58. static llvm::cl::opt<std::string>
  59. OutDirectory("output",
  60. llvm::cl::desc("Directory for outputting generated files."),
  61. llvm::cl::init("docs"), llvm::cl::cat(ClangDocCategory));
  62. static llvm::cl::opt<bool>
  63. PublicOnly("public", llvm::cl::desc("Document only public declarations."),
  64. llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
  65. static llvm::cl::opt<bool> DoxygenOnly(
  66. "doxygen",
  67. llvm::cl::desc("Use only doxygen-style comments to generate docs."),
  68. llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
  69. static llvm::cl::list<std::string> UserStylesheets(
  70. "stylesheets", llvm::cl::CommaSeparated,
  71. llvm::cl::desc("CSS stylesheets to extend the default styles."),
  72. llvm::cl::cat(ClangDocCategory));
  73. static llvm::cl::opt<std::string> SourceRoot("source-root", llvm::cl::desc(R"(
  74. Directory where processed files are stored.
  75. Links to definition locations will only be
  76. generated if the file is in this dir.)"),
  77. llvm::cl::cat(ClangDocCategory));
  78. static llvm::cl::opt<std::string>
  79. RepositoryUrl("repository", llvm::cl::desc(R"(
  80. URL of repository that hosts code.
  81. Used for links to definition locations.)"),
  82. llvm::cl::cat(ClangDocCategory));
  83. enum OutputFormatTy {
  84. md,
  85. yaml,
  86. html,
  87. };
  88. static llvm::cl::opt<OutputFormatTy>
  89. FormatEnum("format", llvm::cl::desc("Format for outputted docs."),
  90. llvm::cl::values(clEnumValN(OutputFormatTy::yaml, "yaml",
  91. "Documentation in YAML format."),
  92. clEnumValN(OutputFormatTy::md, "md",
  93. "Documentation in MD format."),
  94. clEnumValN(OutputFormatTy::html, "html",
  95. "Documentation in HTML format.")),
  96. llvm::cl::init(OutputFormatTy::yaml),
  97. llvm::cl::cat(ClangDocCategory));
  98. std::string getFormatString() {
  99. switch (FormatEnum) {
  100. case OutputFormatTy::yaml:
  101. return "yaml";
  102. case OutputFormatTy::md:
  103. return "md";
  104. case OutputFormatTy::html:
  105. return "html";
  106. }
  107. llvm_unreachable("Unknown OutputFormatTy");
  108. }
  109. // This function isn't referenced outside its translation unit, but it
  110. // can't use the "static" keyword because its address is used for
  111. // GetMainExecutable (since some platforms don't support taking the
  112. // address of main, and some platforms can't implement GetMainExecutable
  113. // without being given the address of a function in the main executable).
  114. std::string GetExecutablePath(const char *Argv0, void *MainAddr) {
  115. return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
  116. }
  117. bool CreateDirectory(const Twine &DirName, bool ClearDirectory = false) {
  118. std::error_code OK;
  119. llvm::SmallString<128> DocsRootPath;
  120. if (ClearDirectory) {
  121. std::error_code RemoveStatus = llvm::sys::fs::remove_directories(DirName);
  122. if (RemoveStatus != OK) {
  123. llvm::errs() << "Unable to remove existing documentation directory for "
  124. << DirName << ".\n";
  125. return true;
  126. }
  127. }
  128. std::error_code DirectoryStatus = llvm::sys::fs::create_directories(DirName);
  129. if (DirectoryStatus != OK) {
  130. llvm::errs() << "Unable to create documentation directories.\n";
  131. return true;
  132. }
  133. return false;
  134. }
  135. // A function to extract the appropriate file name for a given info's
  136. // documentation. The path returned is a composite of the output directory, the
  137. // info's relative path and name and the extension. The relative path should
  138. // have been constructed in the serialization phase.
  139. //
  140. // Example: Given the below, the <ext> path for class C will be
  141. // <root>/A/B/C.<ext>
  142. //
  143. // namespace A {
  144. // namespace B {
  145. //
  146. // class C {};
  147. //
  148. // }
  149. // }
  150. llvm::Expected<llvm::SmallString<128>> getInfoOutputFile(StringRef Root,
  151. StringRef RelativePath,
  152. StringRef Name,
  153. StringRef Ext) {
  154. llvm::SmallString<128> Path;
  155. llvm::sys::path::native(Root, Path);
  156. llvm::sys::path::append(Path, RelativePath);
  157. if (CreateDirectory(Path))
  158. return llvm::createStringError(llvm::inconvertibleErrorCode(),
  159. "failed to create directory");
  160. llvm::sys::path::append(Path, Name + Ext);
  161. return Path;
  162. }
  163. int main(int argc, const char **argv) {
  164. llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  165. std::error_code OK;
  166. ExecutorName.setInitialValue("all-TUs");
  167. auto Exec = clang::tooling::createExecutorFromCommandLineArgs(
  168. argc, argv, ClangDocCategory);
  169. if (!Exec) {
  170. llvm::errs() << toString(Exec.takeError()) << "\n";
  171. return 1;
  172. }
  173. // Fail early if an invalid format was provided.
  174. std::string Format = getFormatString();
  175. llvm::outs() << "Emiting docs in " << Format << " format.\n";
  176. auto G = doc::findGeneratorByName(Format);
  177. if (!G) {
  178. llvm::errs() << toString(G.takeError()) << "\n";
  179. return 1;
  180. }
  181. ArgumentsAdjuster ArgAdjuster;
  182. if (!DoxygenOnly)
  183. ArgAdjuster = combineAdjusters(
  184. getInsertArgumentAdjuster("-fparse-all-comments",
  185. tooling::ArgumentInsertPosition::END),
  186. ArgAdjuster);
  187. clang::doc::ClangDocContext CDCtx = {
  188. Exec->get()->getExecutionContext(),
  189. ProjectName,
  190. PublicOnly,
  191. OutDirectory,
  192. SourceRoot,
  193. RepositoryUrl,
  194. {UserStylesheets.begin(), UserStylesheets.end()},
  195. {"index.js", "index_json.js"}};
  196. if (Format == "html") {
  197. void *MainAddr = (void *)(intptr_t)GetExecutablePath;
  198. std::string ClangDocPath = GetExecutablePath(argv[0], MainAddr);
  199. llvm::SmallString<128> AssetsPath;
  200. llvm::sys::path::native(ClangDocPath, AssetsPath);
  201. AssetsPath = llvm::sys::path::parent_path(AssetsPath);
  202. llvm::sys::path::append(AssetsPath, "..", "share", "clang");
  203. llvm::SmallString<128> DefaultStylesheet;
  204. llvm::sys::path::native(AssetsPath, DefaultStylesheet);
  205. llvm::sys::path::append(DefaultStylesheet,
  206. "clang-doc-default-stylesheet.css");
  207. llvm::SmallString<128> IndexJS;
  208. llvm::sys::path::native(AssetsPath, IndexJS);
  209. llvm::sys::path::append(IndexJS, "index.js");
  210. CDCtx.UserStylesheets.insert(CDCtx.UserStylesheets.begin(),
  211. std::string(DefaultStylesheet.str()));
  212. CDCtx.FilesToCopy.emplace_back(IndexJS.str());
  213. }
  214. // Mapping phase
  215. llvm::outs() << "Mapping decls...\n";
  216. auto Err =
  217. Exec->get()->execute(doc::newMapperActionFactory(CDCtx), ArgAdjuster);
  218. if (Err) {
  219. if (IgnoreMappingFailures)
  220. llvm::errs() << "Error mapping decls in files. Clang-doc will ignore "
  221. "these files and continue:\n"
  222. << toString(std::move(Err)) << "\n";
  223. else {
  224. llvm::errs() << toString(std::move(Err)) << "\n";
  225. return 1;
  226. }
  227. }
  228. // Collect values into output by key.
  229. // In ToolResults, the Key is the hashed USR and the value is the
  230. // bitcode-encoded representation of the Info object.
  231. llvm::outs() << "Collecting infos...\n";
  232. llvm::StringMap<std::vector<StringRef>> USRToBitcode;
  233. Exec->get()->getToolResults()->forEachResult(
  234. [&](StringRef Key, StringRef Value) {
  235. auto R = USRToBitcode.try_emplace(Key, std::vector<StringRef>());
  236. R.first->second.emplace_back(Value);
  237. });
  238. // First reducing phase (reduce all decls into one info per decl).
  239. llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n";
  240. std::atomic<bool> Error;
  241. Error = false;
  242. llvm::sys::Mutex IndexMutex;
  243. // ExecutorConcurrency is a flag exposed by AllTUsExecution.h
  244. llvm::ThreadPool Pool(llvm::hardware_concurrency(ExecutorConcurrency));
  245. for (auto &Group : USRToBitcode) {
  246. Pool.async([&]() {
  247. std::vector<std::unique_ptr<doc::Info>> Infos;
  248. for (auto &Bitcode : Group.getValue()) {
  249. llvm::BitstreamCursor Stream(Bitcode);
  250. doc::ClangDocBitcodeReader Reader(Stream);
  251. auto ReadInfos = Reader.readBitcode();
  252. if (!ReadInfos) {
  253. llvm::errs() << toString(ReadInfos.takeError()) << "\n";
  254. Error = true;
  255. return;
  256. }
  257. std::move(ReadInfos->begin(), ReadInfos->end(),
  258. std::back_inserter(Infos));
  259. }
  260. auto Reduced = doc::mergeInfos(Infos);
  261. if (!Reduced) {
  262. llvm::errs() << llvm::toString(Reduced.takeError());
  263. return;
  264. }
  265. doc::Info *I = Reduced.get().get();
  266. auto InfoPath =
  267. getInfoOutputFile(OutDirectory, I->getRelativeFilePath(""),
  268. I->getFileBaseName(), "." + Format);
  269. if (!InfoPath) {
  270. llvm::errs() << toString(InfoPath.takeError()) << "\n";
  271. Error = true;
  272. return;
  273. }
  274. std::error_code FileErr;
  275. llvm::raw_fd_ostream InfoOS(InfoPath.get(), FileErr,
  276. llvm::sys::fs::OF_None);
  277. if (FileErr) {
  278. llvm::errs() << "Error opening info file " << InfoPath.get() << ": "
  279. << FileErr.message() << "\n";
  280. return;
  281. }
  282. IndexMutex.lock();
  283. // Add a reference to this Info in the Index
  284. clang::doc::Generator::addInfoToIndex(CDCtx.Idx, I);
  285. IndexMutex.unlock();
  286. if (auto Err = G->get()->generateDocForInfo(I, InfoOS, CDCtx))
  287. llvm::errs() << toString(std::move(Err)) << "\n";
  288. });
  289. }
  290. Pool.wait();
  291. if (Error)
  292. return 1;
  293. llvm::outs() << "Generating assets for docs...\n";
  294. Err = G->get()->createResources(CDCtx);
  295. if (Err) {
  296. llvm::errs() << toString(std::move(Err)) << "\n";
  297. return 1;
  298. }
  299. return 0;
  300. }