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>
121 FormatEnum(
"format", llvm::cl::desc(
"Format for outputted docs."),
122 llvm::cl::values(clEnumValN(OutputFormatTy::md,
"md",
123 "Documentation in MD format."),
124 clEnumValN(OutputFormatTy::html,
"html",
125 "Documentation in HTML format."),
126 clEnumValN(OutputFormatTy::json,
"json",
127 "Documentation in JSON format")),
128 llvm::cl::init(OutputFormatTy::json),
135 case OutputFormatTy::md:
137 case OutputFormatTy::html:
139 case OutputFormatTy::json:
142 llvm_unreachable(
"Unknown OutputFormatTy");
151 return llvm::sys::fs::getMainExecutable(
Argv0, MainAddr);
156 using DirIt = llvm::sys::fs::directory_iterator;
157 std::error_code FileErr;
160 !FileErr && DirStart != DirEnd; DirStart.increment(FileErr)) {
161 FilePath = DirStart->path();
162 if (llvm::sys::fs::is_regular_file(FilePath)) {
163 if (llvm::sys::path::extension(FilePath) ==
".css")
165 std::string(FilePath));
166 else if (llvm::sys::path::extension(FilePath) ==
".js")
167 CDCtx.
JsScripts.emplace_back(FilePath.str());
171 return llvm::createFileError(FilePath, FileErr);
172 return llvm::Error::success();
179 llvm::outs() <<
"Asset path supply is not a directory: " <<
UserAssetPath
180 <<
" falling back to default\n";
189 llvm::SmallString<128> NativeClangDocPath;
190 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
192 llvm::SmallString<128> AssetsPath;
193 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
194 llvm::sys::path::append(AssetsPath,
"..",
"share",
"clang-doc");
198 return llvm::Error::success();
205 llvm::outs() <<
"Asset path supply is not a directory: " <<
UserAssetPath
206 <<
" falling back to default\n";
210 llvm::SmallString<128> NativeClangDocPath;
211 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
213 llvm::SmallString<128> AssetsPath;
214 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
215 llvm::sys::path::append(AssetsPath,
"..",
"share",
"clang-doc",
"md");
219 return llvm::Error::success();
224static void sortUsrToInfo(llvm::StringMap<doc::Info *> &USRToInfo) {
225 for (
auto &I : USRToInfo) {
226 auto &
Info = I.second;
227 if (
auto *Namespace = dyn_cast<doc::NamespaceInfo>(Info))
228 Namespace->Children.sort();
229 else if (
auto *Record = dyn_cast<doc::RecordInfo>(Info))
230 Record->Children.sort();
237 return llvm::Error::success();
239 unsigned ID = Diags.getCustomDiagID(
240 DiagnosticsEngine::Warning,
241 "Error mapping decls in files. Clang-doc will ignore these files and "
243 Diags.Report(ID) << toString(std::move(Err));
244 return llvm::Error::success();
250 if (std::error_code Err = llvm::sys::fs::create_directories(
OutDirectory))
252 "failed to create directory.");
253 return llvm::Error::success();
256int main(
int argc,
const char **argv) {
257 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
260 ExitOnErr.setBanner(
"clang-doc error: ");
262 const char *Overview =
263 R
"(Generates documentation from source code and comments.
265Example usage for files without flags (default):
267 $ clang-doc File1.cpp File2.cpp ... FileN.cpp
269Example usage for a project using a compile commands database:
271 $ clang-doc --executor=all-TUs compile_commands.json
274 auto Executor =
ExitOnErr(clang::tooling::createExecutorFromCommandLineArgs(
279 llvm::timeTraceProfilerInitialize(200,
"clang-doc");
281 llvm::TimeTraceScope(
"main");
285 llvm::outs() <<
"Emiting docs in " << Format <<
" format.\n";
288 ArgumentsAdjuster ArgAdjuster;
290 ArgAdjuster = combineAdjusters(
291 getInsertArgumentAdjuster(
"-fparse-all-comments",
292 tooling::ArgumentInsertPosition::END),
295 auto DiagOpts = std::make_unique<DiagnosticOptions>();
296 TextDiagnosticPrinter *DiagClient =
297 new TextDiagnosticPrinter(llvm::errs(), *DiagOpts);
298 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(
new DiagnosticIDs());
299 DiagnosticsEngine Diags(DiagID, *DiagOpts, DiagClient);
304 {UserStylesheets.begin(), UserStylesheets.end()}, Diags,
FormatEnum,
307 if (Format ==
"html")
309 else if (Format ==
"md")
312 llvm::timeTraceProfilerBegin(
"Executor Launch",
"total runtime");
314 llvm::outs() <<
"Mapping decls...\n";
318 llvm::timeTraceProfilerEnd();
323 llvm::timeTraceProfilerBegin(
"Collect Info",
"total runtime");
324 llvm::outs() <<
"Collecting infos...\n";
325 llvm::StringMap<std::vector<StringRef>> USRToBitcode;
326 Executor->getToolResults()->forEachResult(
327 [&](StringRef Key, StringRef Value) {
328 USRToBitcode[
Key].emplace_back(Value);
330 llvm::timeTraceProfilerEnd();
334 llvm::sys::Mutex USRToInfoMutex;
335 llvm::StringMap<doc::Info *> USRToInfo;
338 llvm::outs() <<
"Reducing " << USRToBitcode.size() <<
" infos...\n";
339 std::atomic<bool>
Error;
341 llvm::sys::Mutex IndexMutex;
342 llvm::sys::Mutex DiagMutex;
343 unsigned DiagIDBitcodeReading = Diags.getCustomDiagID(
344 DiagnosticsEngine::Error,
"error reading bitcode: %0");
345 unsigned DiagIDBitcodeMerging = Diags.getCustomDiagID(
346 DiagnosticsEngine::Error,
"error merging bitcode: %0");
349 llvm::DefaultThreadPool Pool(
351 llvm::hardware_concurrency(ExecutorConcurrency));
353 llvm::TimeTraceScope TS(
"Reduce");
354 for (
const auto &Group : USRToBitcode) {
355 StringRef
Key = Group.getKey();
356 std::vector<StringRef> Bitcodes = Group.getValue();
357 Pool.async([Key, Bitcodes, &CDCtx, &Diags, &USRToInfo, &USRToInfoMutex,
358 &IndexMutex, &DiagMutex, &Error, DiagIDBitcodeReading,
359 DiagIDBitcodeMerging]() {
361 llvm::timeTraceProfilerInitialize(200,
"clang-doc");
365 llvm::TimeTraceScope Red(
"decoding and merging bitcode");
366 for (
const auto &Bitcode : Bitcodes) {
368 llvm::scope_exit ArenaGuard(
370 llvm::BitstreamCursor Stream(Bitcode);
372 auto ReadInfos = Reader.readBitcode();
374 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
376 Diags.Report(DiagIDBitcodeReading)
377 << toString(ReadInfos.takeError());
381 for (
auto &I : *ReadInfos) {
383 Reduced, std::move(I),
385 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
386 Diags.Report(DiagIDBitcodeMerging)
387 << toString(std::move(Err));
396 llvm::TimeTraceScope
Merge(
"addInfoToIndex");
397 std::lock_guard<llvm::sys::Mutex> Guard(IndexMutex);
402 llvm::TimeTraceScope
Merge(
"USRToInfo");
403 std::lock_guard<llvm::sys::Mutex> Guard(USRToInfoMutex);
404 USRToInfo[
Key] = std::move(Reduced);
408 llvm::timeTraceProfilerFinishThread();
419 llvm::TimeTraceScope Sort(
"Sort USRToInfo");
423 llvm::timeTraceProfilerBegin(
"Writing output",
"total runtime");
428 llvm::outs() <<
"Generating docs...\n";
431 G->generateDocumentation(
OutDirectory, std::move(USRToInfo), CDCtx));
432 llvm::outs() <<
"Generating assets for docs...\n";
434 llvm::timeTraceProfilerEnd();
439 llvm::raw_fd_ostream OS(
"clang-doc-tracing.json", EC,
440 llvm::sys::fs::OF_Text);
442 llvm::timeTraceProfilerWrite(OS);
443 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::md, "md", "Documentation in MD format."), clEnumValN(OutputFormatTy::html, "html", "Documentation in HTML format."), clEnumValN(OutputFormatTy::json, "json", "Documentation in JSON format")), llvm::cl::init(OutputFormatTy::json), 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)
llvm::BumpPtrAllocator & getPersistentArena()
llvm::BumpPtrAllocator & getTransientArena()
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