ClangDocMain.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 <mutex>
  46. #include <string>
  47. using namespace clang::ast_matchers;
  48. using namespace clang::tooling;
  49. using namespace clang;
  50. static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  51. static llvm::cl::OptionCategory ClangDocCategory("clang-doc options");
  52. static llvm::cl::opt<std::string>
  53. ProjectName("project-name", llvm::cl::desc("Name of project."),
  54. llvm::cl::cat(ClangDocCategory));
  55. static llvm::cl::opt<bool> IgnoreMappingFailures(
  56. "ignore-map-errors",
  57. llvm::cl::desc("Continue if files are not mapped correctly."),
  58. llvm::cl::init(true), llvm::cl::cat(ClangDocCategory));
  59. static llvm::cl::opt<std::string>
  60. OutDirectory("output",
  61. llvm::cl::desc("Directory for outputting generated files."),
  62. llvm::cl::init("docs"), llvm::cl::cat(ClangDocCategory));
  63. static llvm::cl::opt<bool>
  64. PublicOnly("public", llvm::cl::desc("Document only public declarations."),
  65. llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
  66. static llvm::cl::opt<bool> DoxygenOnly(
  67. "doxygen",
  68. llvm::cl::desc("Use only doxygen-style comments to generate docs."),
  69. llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
  70. static llvm::cl::list<std::string> UserStylesheets(
  71. "stylesheets", llvm::cl::CommaSeparated,
  72. llvm::cl::desc("CSS stylesheets to extend the default styles."),
  73. llvm::cl::cat(ClangDocCategory));
  74. static llvm::cl::opt<std::string> SourceRoot("source-root", llvm::cl::desc(R"(
  75. Directory where processed files are stored.
  76. Links to definition locations will only be
  77. generated if the file is in this dir.)"),
  78. llvm::cl::cat(ClangDocCategory));
  79. static llvm::cl::opt<std::string>
  80. RepositoryUrl("repository", llvm::cl::desc(R"(
  81. URL of repository that hosts code.
  82. Used for links to definition locations.)"),
  83. llvm::cl::cat(ClangDocCategory));
  84. enum OutputFormatTy {
  85. md,
  86. yaml,
  87. html,
  88. };
  89. static llvm::cl::opt<OutputFormatTy>
  90. FormatEnum("format", llvm::cl::desc("Format for outputted docs."),
  91. llvm::cl::values(clEnumValN(OutputFormatTy::yaml, "yaml",
  92. "Documentation in YAML format."),
  93. clEnumValN(OutputFormatTy::md, "md",
  94. "Documentation in MD format."),
  95. clEnumValN(OutputFormatTy::html, "html",
  96. "Documentation in HTML format.")),
  97. llvm::cl::init(OutputFormatTy::yaml),
  98. llvm::cl::cat(ClangDocCategory));
  99. std::string getFormatString() {
  100. switch (FormatEnum) {
  101. case OutputFormatTy::yaml:
  102. return "yaml";
  103. case OutputFormatTy::md:
  104. return "md";
  105. case OutputFormatTy::html:
  106. return "html";
  107. }
  108. llvm_unreachable("Unknown OutputFormatTy");
  109. }
  110. // This function isn't referenced outside its translation unit, but it
  111. // can't use the "static" keyword because its address is used for
  112. // GetMainExecutable (since some platforms don't support taking the
  113. // address of main, and some platforms can't implement GetMainExecutable
  114. // without being given the address of a function in the main executable).
  115. std::string GetExecutablePath(const char *Argv0, void *MainAddr) {
  116. return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
  117. }
  118. int main(int argc, const char **argv) {
  119. llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  120. std::error_code OK;
  121. const char *Overview =
  122. R"(Generates documentation from source code and comments.
  123. Example usage for files without flags (default):
  124. $ clang-doc File1.cpp File2.cpp ... FileN.cpp
  125. Example usage for a project using a compile commands database:
  126. $ clang-doc --executor=all-TUs compile_commands.json
  127. )";
  128. auto Executor = clang::tooling::createExecutorFromCommandLineArgs(
  129. argc, argv, ClangDocCategory, Overview);
  130. if (!Executor) {
  131. llvm::errs() << toString(Executor.takeError()) << "\n";
  132. return 1;
  133. }
  134. // Fail early if an invalid format was provided.
  135. std::string Format = getFormatString();
  136. llvm::outs() << "Emiting docs in " << Format << " format.\n";
  137. auto G = doc::findGeneratorByName(Format);
  138. if (!G) {
  139. llvm::errs() << toString(G.takeError()) << "\n";
  140. return 1;
  141. }
  142. ArgumentsAdjuster ArgAdjuster;
  143. if (!DoxygenOnly)
  144. ArgAdjuster = combineAdjusters(
  145. getInsertArgumentAdjuster("-fparse-all-comments",
  146. tooling::ArgumentInsertPosition::END),
  147. ArgAdjuster);
  148. clang::doc::ClangDocContext CDCtx = {
  149. Executor->get()->getExecutionContext(),
  150. ProjectName,
  151. PublicOnly,
  152. OutDirectory,
  153. SourceRoot,
  154. RepositoryUrl,
  155. {UserStylesheets.begin(), UserStylesheets.end()},
  156. {"index.js", "index_json.js"}};
  157. if (Format == "html") {
  158. void *MainAddr = (void *)(intptr_t)GetExecutablePath;
  159. std::string ClangDocPath = GetExecutablePath(argv[0], MainAddr);
  160. llvm::SmallString<128> NativeClangDocPath;
  161. llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
  162. llvm::SmallString<128> AssetsPath;
  163. AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
  164. llvm::sys::path::append(AssetsPath, "..", "share", "clang");
  165. llvm::SmallString<128> DefaultStylesheet;
  166. llvm::sys::path::native(AssetsPath, DefaultStylesheet);
  167. llvm::sys::path::append(DefaultStylesheet,
  168. "clang-doc-default-stylesheet.css");
  169. llvm::SmallString<128> IndexJS;
  170. llvm::sys::path::native(AssetsPath, IndexJS);
  171. llvm::sys::path::append(IndexJS, "index.js");
  172. CDCtx.UserStylesheets.insert(CDCtx.UserStylesheets.begin(),
  173. std::string(DefaultStylesheet.str()));
  174. CDCtx.FilesToCopy.emplace_back(IndexJS.str());
  175. }
  176. // Mapping phase
  177. llvm::outs() << "Mapping decls...\n";
  178. auto Err =
  179. Executor->get()->execute(doc::newMapperActionFactory(CDCtx), ArgAdjuster);
  180. if (Err) {
  181. if (IgnoreMappingFailures)
  182. llvm::errs() << "Error mapping decls in files. Clang-doc will ignore "
  183. "these files and continue:\n"
  184. << toString(std::move(Err)) << "\n";
  185. else {
  186. llvm::errs() << toString(std::move(Err)) << "\n";
  187. return 1;
  188. }
  189. }
  190. // Collect values into output by key.
  191. // In ToolResults, the Key is the hashed USR and the value is the
  192. // bitcode-encoded representation of the Info object.
  193. llvm::outs() << "Collecting infos...\n";
  194. llvm::StringMap<std::vector<StringRef>> USRToBitcode;
  195. Executor->get()->getToolResults()->forEachResult(
  196. [&](StringRef Key, StringRef Value) {
  197. auto R = USRToBitcode.try_emplace(Key, std::vector<StringRef>());
  198. R.first->second.emplace_back(Value);
  199. });
  200. // Collects all Infos according to their unique USR value. This map is added
  201. // to from the thread pool below and is protected by the USRToInfoMutex.
  202. llvm::sys::Mutex USRToInfoMutex;
  203. llvm::StringMap<std::unique_ptr<doc::Info>> USRToInfo;
  204. // First reducing phase (reduce all decls into one info per decl).
  205. llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n";
  206. std::atomic<bool> Error;
  207. Error = false;
  208. llvm::sys::Mutex IndexMutex;
  209. // ExecutorConcurrency is a flag exposed by AllTUsExecution.h
  210. llvm::ThreadPool Pool(llvm::hardware_concurrency(ExecutorConcurrency));
  211. for (auto &Group : USRToBitcode) {
  212. Pool.async([&]() {
  213. std::vector<std::unique_ptr<doc::Info>> Infos;
  214. for (auto &Bitcode : Group.getValue()) {
  215. llvm::BitstreamCursor Stream(Bitcode);
  216. doc::ClangDocBitcodeReader Reader(Stream);
  217. auto ReadInfos = Reader.readBitcode();
  218. if (!ReadInfos) {
  219. llvm::errs() << toString(ReadInfos.takeError()) << "\n";
  220. Error = true;
  221. return;
  222. }
  223. std::move(ReadInfos->begin(), ReadInfos->end(),
  224. std::back_inserter(Infos));
  225. }
  226. auto Reduced = doc::mergeInfos(Infos);
  227. if (!Reduced) {
  228. llvm::errs() << llvm::toString(Reduced.takeError());
  229. return;
  230. }
  231. // Add a reference to this Info in the Index
  232. {
  233. std::lock_guard<llvm::sys::Mutex> Guard(IndexMutex);
  234. clang::doc::Generator::addInfoToIndex(CDCtx.Idx, Reduced.get().get());
  235. }
  236. // Save in the result map (needs a lock due to threaded access).
  237. {
  238. std::lock_guard<llvm::sys::Mutex> Guard(USRToInfoMutex);
  239. USRToInfo[Group.getKey()] = std::move(Reduced.get());
  240. }
  241. });
  242. }
  243. Pool.wait();
  244. if (Error)
  245. return 1;
  246. // Ensure the root output directory exists.
  247. if (std::error_code Err = llvm::sys::fs::create_directories(OutDirectory);
  248. Err != std::error_code()) {
  249. llvm::errs() << "Failed to create directory '" << OutDirectory << "'\n";
  250. return 1;
  251. }
  252. // Run the generator.
  253. llvm::outs() << "Generating docs...\n";
  254. if (auto Err =
  255. G->get()->generateDocs(OutDirectory, std::move(USRToInfo), CDCtx)) {
  256. llvm::errs() << toString(std::move(Err)) << "\n";
  257. return 1;
  258. }
  259. llvm::outs() << "Generating assets for docs...\n";
  260. Err = G->get()->createResources(CDCtx);
  261. if (Err) {
  262. llvm::errs() << toString(std::move(Err)) << "\n";
  263. return 1;
  264. }
  265. return 0;
  266. }