25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/DiagnosticOptions.h"
27#include "clang/Frontend/TextDiagnosticPrinter.h"
28#include "clang/Tooling/AllTUsExecution.h"
29#include "clang/Tooling/CommonOptionsParser.h"
30#include "clang/Tooling/Execution.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/ScopeExit.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Error.h"
35#include "llvm/Support/FileSystem.h"
36#include "llvm/Support/Mutex.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/Process.h"
39#include "llvm/Support/Signals.h"
40#include "llvm/Support/ThreadPool.h"
41#include "llvm/Support/TimeProfiler.h"
42#include "llvm/Support/raw_ostream.h"
51static llvm::cl::extrahelp
CommonHelp(CommonOptionsParser::HelpMessage);
54static llvm::cl::opt<std::string>
55 ProjectName(
"project-name", llvm::cl::desc(
"Name of project."),
60 llvm::cl::desc(
"Continue if files are not mapped correctly."),
63static llvm::cl::opt<std::string>
65 llvm::cl::desc(
"Directory for outputting generated files."),
68static llvm::cl::opt<std::string>
70 llvm::cl::desc(R
"(Base Directory for generated documentation.
71URLs will be rooted at this directory for HTML links.)"),
74static llvm::cl::opt<bool>
75 PublicOnly(
"public", llvm::cl::desc(
"Document only public declarations."),
80 llvm::cl::desc(
"Use only doxygen-style comments to generate docs."),
84 "stylesheets", llvm::cl::CommaSeparated,
85 llvm::cl::desc(
"CSS stylesheets to extend the default styles."),
90 llvm::cl::desc(
"User supplied asset path to "
91 "override the default css and js files for html output"),
94static llvm::cl::opt<std::string>
SourceRoot(
"source-root", llvm::cl::desc(R
"(
95Directory where processed files are stored.
96Links to definition locations will only be
97generated if the file is in this dir.)"),
100static llvm::cl::opt<std::string>
102URL of repository that hosts code.
103Used for links to definition locations.)"),
107 "repository-line-prefix",
108 llvm::cl::desc(
"Prefix of line code for repository."),
111static llvm::cl::opt<bool>
FTimeTrace(
"ftime-trace", llvm::cl::desc(R
"(
112Turn on time profiler. Generates clang-doc-tracing.json)"),
113 llvm::cl::init(false),
116static llvm::cl::opt<bool>
117 Pretty(
"pretty-json", llvm::cl::desc(
"Serialize JSON with whitespace."),
120static llvm::cl::opt<OutputFormatTy>
FormatEnum(
121 "format", llvm::cl::desc(
"Format for outputted docs."),
122 llvm::cl::values(clEnumValN(OutputFormatTy::yaml,
"yaml",
123 "Documentation in YAML format."),
124 clEnumValN(OutputFormatTy::md,
"md",
125 "Documentation in MD format."),
126 clEnumValN(OutputFormatTy::html,
"html",
127 "Documentation in HTML format."),
128 clEnumValN(OutputFormatTy::json,
"json",
129 "Documentation in JSON format"),
130 clEnumValN(OutputFormatTy::md_mustache,
"md_mustache",
131 "Documentation in MD format.")),
138 case OutputFormatTy::yaml:
140 case OutputFormatTy::md:
142 case OutputFormatTy::html:
144 case OutputFormatTy::json:
146 case OutputFormatTy::md_mustache:
147 return "md_mustache";
149 llvm_unreachable(
"Unknown OutputFormatTy");
158 return llvm::sys::fs::getMainExecutable(
Argv0, MainAddr);
163 using DirIt = llvm::sys::fs::directory_iterator;
164 std::error_code FileErr;
167 !FileErr && DirStart != DirEnd; DirStart.increment(FileErr)) {
168 FilePath = DirStart->path();
169 if (llvm::sys::fs::is_regular_file(FilePath)) {
170 if (llvm::sys::path::extension(FilePath) ==
".css")
172 std::string(FilePath));
173 else if (llvm::sys::path::extension(FilePath) ==
".js")
174 CDCtx.
JsScripts.emplace_back(FilePath.str());
178 return llvm::createFileError(FilePath, FileErr);
179 return llvm::Error::success();
186 llvm::outs() <<
"Asset path supply is not a directory: " <<
UserAssetPath
187 <<
" falling back to default\n";
196 llvm::SmallString<128> NativeClangDocPath;
197 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
199 llvm::SmallString<128> AssetsPath;
200 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
201 llvm::sys::path::append(AssetsPath,
"..",
"share",
"clang-doc");
205 return llvm::Error::success();
212 llvm::outs() <<
"Asset path supply is not a directory: " <<
UserAssetPath
213 <<
" falling back to default\n";
217 llvm::SmallString<128> NativeClangDocPath;
218 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
220 llvm::SmallString<128> AssetsPath;
221 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
222 llvm::sys::path::append(AssetsPath,
"..",
"share",
"clang-doc",
"md");
226 return llvm::Error::success();
231static void sortUsrToInfo(llvm::StringMap<doc::Info *> &USRToInfo) {
232 for (
auto &I : USRToInfo) {
233 auto &
Info = I.second;
240 Record->Children.sort();
248 return llvm::Error::success();
250 unsigned ID = Diags.getCustomDiagID(
251 DiagnosticsEngine::Warning,
252 "Error mapping decls in files. Clang-doc will ignore these files and "
254 Diags.Report(ID) << toString(std::move(Err));
255 return llvm::Error::success();
261 if (std::error_code Err = llvm::sys::fs::create_directories(
OutDirectory))
263 "failed to create directory.");
264 return llvm::Error::success();
267int main(
int argc,
const char **argv) {
268 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
271 ExitOnErr.setBanner(
"clang-doc error: ");
273 const char *Overview =
274 R
"(Generates documentation from source code and comments.
276Example usage for files without flags (default):
278 $ clang-doc File1.cpp File2.cpp ... FileN.cpp
280Example usage for a project using a compile commands database:
282 $ clang-doc --executor=all-TUs compile_commands.json
285 auto Executor =
ExitOnErr(clang::tooling::createExecutorFromCommandLineArgs(
290 llvm::timeTraceProfilerInitialize(200,
"clang-doc");
292 llvm::TimeTraceScope(
"main");
296 llvm::outs() <<
"Emiting docs in " << Format <<
" format.\n";
299 ArgumentsAdjuster ArgAdjuster;
301 ArgAdjuster = combineAdjusters(
302 getInsertArgumentAdjuster(
"-fparse-all-comments",
303 tooling::ArgumentInsertPosition::END),
306 auto DiagOpts = std::make_unique<DiagnosticOptions>();
307 TextDiagnosticPrinter *DiagClient =
308 new TextDiagnosticPrinter(llvm::errs(), *DiagOpts);
309 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(
new DiagnosticIDs());
310 DiagnosticsEngine Diags(DiagID, *DiagOpts, DiagClient);
315 {UserStylesheets.begin(), UserStylesheets.end()}, Diags,
FormatEnum,
318 if (Format ==
"html")
320 else if (Format ==
"md_mustache")
323 llvm::timeTraceProfilerBegin(
"Executor Launch",
"total runtime");
325 llvm::outs() <<
"Mapping decls...\n";
329 llvm::timeTraceProfilerEnd();
334 llvm::timeTraceProfilerBegin(
"Collect Info",
"total runtime");
335 llvm::outs() <<
"Collecting infos...\n";
336 llvm::StringMap<std::vector<StringRef>> USRToBitcode;
337 Executor->getToolResults()->forEachResult(
338 [&](StringRef Key, StringRef Value) {
339 USRToBitcode[
Key].emplace_back(Value);
341 llvm::timeTraceProfilerEnd();
345 llvm::sys::Mutex USRToInfoMutex;
346 llvm::StringMap<doc::Info *> USRToInfo;
349 llvm::outs() <<
"Reducing " << USRToBitcode.size() <<
" infos...\n";
350 std::atomic<bool>
Error;
352 llvm::sys::Mutex IndexMutex;
353 llvm::sys::Mutex DiagMutex;
354 unsigned DiagIDBitcodeReading = Diags.getCustomDiagID(
355 DiagnosticsEngine::Error,
"error reading bitcode: %0");
356 unsigned DiagIDBitcodeMerging = Diags.getCustomDiagID(
357 DiagnosticsEngine::Error,
"error merging bitcode: %0");
360 llvm::DefaultThreadPool Pool(
362 llvm::hardware_concurrency(ExecutorConcurrency));
364 llvm::TimeTraceScope TS(
"Reduce");
365 for (
const auto &Group : USRToBitcode) {
366 StringRef
Key = Group.getKey();
367 std::vector<StringRef> Bitcodes = Group.getValue();
368 Pool.async([Key, Bitcodes, &CDCtx, &Diags, &USRToInfo, &USRToInfoMutex,
369 &IndexMutex, &DiagMutex, &Error, DiagIDBitcodeReading,
370 DiagIDBitcodeMerging]() {
372 llvm::timeTraceProfilerInitialize(200,
"clang-doc");
376 llvm::TimeTraceScope Red(
"decoding and merging bitcode");
377 for (
const auto &Bitcode : Bitcodes) {
379 llvm::scope_exit ArenaGuard(
381 llvm::BitstreamCursor Stream(Bitcode);
383 auto ReadInfos = Reader.readBitcode();
385 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
387 Diags.Report(DiagIDBitcodeReading)
388 << toString(ReadInfos.takeError());
392 for (
auto &I : *ReadInfos) {
395 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
396 Diags.Report(DiagIDBitcodeMerging)
397 << toString(std::move(Err));
406 llvm::TimeTraceScope
Merge(
"addInfoToIndex");
407 std::lock_guard<llvm::sys::Mutex> Guard(IndexMutex);
412 llvm::TimeTraceScope
Merge(
"USRToInfo");
413 std::lock_guard<llvm::sys::Mutex> Guard(USRToInfoMutex);
414 USRToInfo[
Key] = std::move(Reduced);
418 llvm::timeTraceProfilerFinishThread();
429 llvm::TimeTraceScope Sort(
"Sort USRToInfo");
433 llvm::timeTraceProfilerBegin(
"Writing output",
"total runtime");
438 llvm::outs() <<
"Generating docs...\n";
441 G->generateDocumentation(
OutDirectory, std::move(USRToInfo), CDCtx));
442 llvm::outs() <<
"Generating assets for docs...\n";
444 llvm::timeTraceProfilerEnd();
449 llvm::raw_fd_ostream OS(
"clang-doc-tracing.json", EC,
450 llvm::sys::fs::OF_Text);
452 llvm::timeTraceProfilerWrite(OS);
453 llvm::timeTraceProfilerCleanup();
static llvm::cl::opt< std::string > UserAssetPath("asset", llvm::cl::desc("User supplied asset path to " "override the default css and js files for html output"), llvm::cl::cat(ClangDocCategory))
static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
static std::string getExecutablePath(const char *Argv0, void *MainAddr)
static llvm::cl::opt< bool > PublicOnly("public", llvm::cl::desc("Document only public declarations."), llvm::cl::init(false), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< std::string > RepositoryCodeLinePrefix("repository-line-prefix", llvm::cl::desc("Prefix of line code for repository."), llvm::cl::cat(ClangDocCategory))
int main(int argc, const char **argv)
static llvm::cl::opt< std::string > ProjectName("project-name", llvm::cl::desc("Name of project."), llvm::cl::cat(ClangDocCategory))
static llvm::Error getHtmlFiles(const char *Argv0, clang::doc::ClangDocContext &CDCtx)
static llvm::Error createDirectories(llvm::StringRef OutDirectory)
static llvm::cl::opt< bool > Pretty("pretty-json", llvm::cl::desc("Serialize JSON with whitespace."), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< bool > FTimeTrace("ftime-trace", llvm::cl::desc(R"(
Turn on time profiler. Generates clang-doc-tracing.json)"), llvm::cl::init(false), llvm::cl::cat(ClangDocCategory))
static llvm::StringRef getFormatString()
static llvm::cl::list< std::string > UserStylesheets("stylesheets", llvm::cl::CommaSeparated, llvm::cl::desc("CSS stylesheets to extend the default styles."), llvm::cl::cat(ClangDocCategory))
static llvm::ExitOnError ExitOnErr
static llvm::cl::opt< std::string > SourceRoot("source-root", llvm::cl::desc(R"(
Directory where processed files are stored.
Links to definition locations will only be
generated if the file is in this dir.)"), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< OutputFormatTy > FormatEnum("format", llvm::cl::desc("Format for outputted docs."), llvm::cl::values(clEnumValN(OutputFormatTy::yaml, "yaml", "Documentation in YAML format."), clEnumValN(OutputFormatTy::md, "md", "Documentation in MD format."), clEnumValN(OutputFormatTy::html, "html", "Documentation in HTML format."), clEnumValN(OutputFormatTy::json, "json", "Documentation in JSON format"), clEnumValN(OutputFormatTy::md_mustache, "md_mustache", "Documentation in MD format.")), llvm::cl::init(OutputFormatTy::yaml), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< std::string > BaseDirectory("base", llvm::cl::desc(R"(Base Directory for generated documentation.
URLs will be rooted at this directory for HTML links.)"), llvm::cl::init(""), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< bool > IgnoreMappingFailures("ignore-map-errors", llvm::cl::desc("Continue if files are not mapped correctly."), llvm::cl::init(true), llvm::cl::cat(ClangDocCategory))
static llvm::cl::opt< std::string > OutDirectory("output", llvm::cl::desc("Directory for outputting generated files."), llvm::cl::init("docs"), llvm::cl::cat(ClangDocCategory))
static llvm::Error getMdFiles(const char *Argv0, clang::doc::ClangDocContext &CDCtx)
static llvm::Error getAssetFiles(clang::doc::ClangDocContext &CDCtx)
static llvm::cl::opt< bool > DoxygenOnly("doxygen", llvm::cl::desc("Use only doxygen-style comments to generate docs."), llvm::cl::init(false), llvm::cl::cat(ClangDocCategory))
static void sortUsrToInfo(llvm::StringMap< doc::Info * > &USRToInfo)
Make the output of clang-doc deterministic by sorting the children of namespaces and records.
static llvm::Error handleMappingFailures(DiagnosticsEngine &Diags, llvm::Error Err)
static llvm::cl::OptionCategory ClangDocCategory("clang-doc options")
static llvm::cl::opt< std::string > RepositoryUrl("repository", llvm::cl::desc(R"(
URL of repository that hosts code.
Used for links to definition locations.)"), llvm::cl::cat(ClangDocCategory))
This file contains general utility functions and helpers used across the clang-doc tool,...
static void addInfoToIndex(Index &Idx, const doc::Info *Info)
@ Info
An information message.
std::unique_ptr< tooling::FrontendActionFactory > newMapperActionFactory(ClangDocContext CDCtx)
llvm::Expected< std::unique_ptr< Generator > > findGeneratorByName(llvm::StringRef Format)
thread_local llvm::BumpPtrAllocator PersistentArena
thread_local llvm::BumpPtrAllocator TransientArena
llvm::Error mergeSingleInfo(doc::Info *&Reduced, doc::Info *NewInfo, llvm::BumpPtrAllocator &Arena)
bool Merge(llvm::StringRef MergeDir, llvm::StringRef OutputFile)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::vector< std::string > UserStylesheets
std::vector< std::string > JsScripts