clang-tools 24.0.0git
ClangDocMain.cpp
Go to the documentation of this file.
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
20#include "BitcodeReader.h"
21#include "ClangDoc.h"
22#include "Generators.h"
23#include "Representation.h"
24#include "support/Utils.h"
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"
43#include <atomic>
44#include <mutex>
45#include <string>
46
47using namespace clang::tooling;
48using namespace clang;
50
51static llvm::cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
52static llvm::cl::OptionCategory ClangDocCategory("clang-doc options");
53
54static llvm::cl::opt<std::string>
55 ProjectName("project-name", llvm::cl::desc("Name of project."),
56 llvm::cl::cat(ClangDocCategory));
57
58static llvm::cl::opt<bool> IgnoreMappingFailures(
59 "ignore-map-errors",
60 llvm::cl::desc("Continue if files are not mapped correctly."),
61 llvm::cl::init(true), llvm::cl::cat(ClangDocCategory));
62
63static llvm::cl::opt<std::string>
64 OutDirectory("output",
65 llvm::cl::desc("Directory for outputting generated files."),
66 llvm::cl::init("docs"), llvm::cl::cat(ClangDocCategory));
67
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.)"),
72 llvm::cl::init(""), llvm::cl::cat(ClangDocCategory));
73
74static llvm::cl::opt<bool>
75 PublicOnly("public", llvm::cl::desc("Document only public declarations."),
76 llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
78static llvm::cl::opt<bool> DoxygenOnly(
79 "doxygen",
80 llvm::cl::desc("Use only doxygen-style comments to generate docs."),
81 llvm::cl::init(false), llvm::cl::cat(ClangDocCategory));
83static llvm::cl::list<std::string> UserStylesheets(
84 "stylesheets", llvm::cl::CommaSeparated,
85 llvm::cl::desc("CSS stylesheets to extend the default styles."),
86 llvm::cl::cat(ClangDocCategory));
88static llvm::cl::opt<std::string> UserAssetPath(
89 "asset",
90 llvm::cl::desc("User supplied asset path to "
91 "override the default css and js files for html output"),
92 llvm::cl::cat(ClangDocCategory));
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.)"),
98 llvm::cl::cat(ClangDocCategory));
99
100static llvm::cl::opt<std::string>
101 RepositoryUrl("repository", llvm::cl::desc(R"(
102URL of repository that hosts code.
103Used for links to definition locations.)"),
104 llvm::cl::cat(ClangDocCategory));
106static llvm::cl::opt<std::string> RepositoryCodeLinePrefix(
107 "repository-line-prefix",
108 llvm::cl::desc("Prefix of line code for repository."),
109 llvm::cl::cat(ClangDocCategory));
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),
114 llvm::cl::cat(ClangDocCategory));
115
116static llvm::cl::opt<bool>
117 Pretty("pretty-json", llvm::cl::desc("Serialize JSON with whitespace."),
118 llvm::cl::cat(ClangDocCategory));
119
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),
129 llvm::cl::cat(ClangDocCategory));
130
131static llvm::ExitOnError ExitOnErr;
132
133static llvm::StringRef getFormatString() {
134 switch (FormatEnum) {
135 case OutputFormatTy::md:
136 return "md";
137 case OutputFormatTy::html:
138 return "html";
139 case OutputFormatTy::json:
140 return "json";
141 }
142 llvm_unreachable("Unknown OutputFormatTy");
144
145// This function isn't referenced outside its translation unit, but it
146// can't use the "static" keyword because its address is used for
147// GetMainExecutable (since some platforms don't support taking the
148// address of main, and some platforms can't implement GetMainExecutable
149// without being given the address of a function in the main executable).
150static std::string getExecutablePath(const char *Argv0, void *MainAddr) {
151 return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
152}
153
154// TODO: Rename this, since it only gets custom CSS/JS
155static llvm::Error getAssetFiles(clang::doc::ClangDocContext &CDCtx) {
156 using DirIt = llvm::sys::fs::directory_iterator;
157 std::error_code FileErr;
158 llvm::SmallString<128> FilePath(UserAssetPath);
159 for (DirIt DirStart = DirIt(UserAssetPath, FileErr), DirEnd;
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")
164 CDCtx.UserStylesheets.insert(CDCtx.UserStylesheets.begin(),
165 std::string(FilePath));
166 else if (llvm::sys::path::extension(FilePath) == ".js")
167 CDCtx.JsScripts.emplace_back(FilePath.str());
169 }
170 if (FileErr)
171 return llvm::createFileError(FilePath, FileErr);
172 return llvm::Error::success();
173}
174
175static llvm::Error getHtmlFiles(const char *Argv0,
177 bool IsDir = llvm::sys::fs::is_directory(UserAssetPath);
178 if (!UserAssetPath.empty() && !IsDir)
179 llvm::outs() << "Asset path supply is not a directory: " << UserAssetPath
180 << " falling back to default\n";
181 if (IsDir) {
182 if (FormatEnum == OutputFormatTy::html) {
183 if (auto Err = getAssetFiles(CDCtx))
184 return Err;
185 }
186 }
187 void *MainAddr = (void *)(intptr_t)getExecutablePath;
188 std::string ClangDocPath = getExecutablePath(Argv0, MainAddr);
189 llvm::SmallString<128> NativeClangDocPath;
190 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
191
192 llvm::SmallString<128> AssetsPath;
193 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
194 llvm::sys::path::append(AssetsPath, "..", "share", "clang-doc");
195
196 getHtmlFiles(AssetsPath, CDCtx);
197
198 return llvm::Error::success();
199}
200
201static llvm::Error getMdFiles(const char *Argv0,
203 bool IsDir = llvm::sys::fs::is_directory(UserAssetPath);
204 if (!UserAssetPath.empty() && !IsDir)
205 llvm::outs() << "Asset path supply is not a directory: " << UserAssetPath
206 << " falling back to default\n";
207
208 void *MainAddr = (void *)(intptr_t)getExecutablePath;
209 std::string ClangDocPath = getExecutablePath(Argv0, MainAddr);
210 llvm::SmallString<128> NativeClangDocPath;
211 llvm::sys::path::native(ClangDocPath, NativeClangDocPath);
212
213 llvm::SmallString<128> AssetsPath;
214 AssetsPath = llvm::sys::path::parent_path(NativeClangDocPath);
215 llvm::sys::path::append(AssetsPath, "..", "share", "clang-doc", "md");
216
217 getMdFiles(AssetsPath, CDCtx);
218
219 return llvm::Error::success();
220}
221
222/// Make the output of clang-doc deterministic by sorting the children of
223/// namespaces and records.
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();
231 }
232}
233
234static llvm::Error handleMappingFailures(DiagnosticsEngine &Diags,
235 llvm::Error Err) {
236 if (!Err)
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 "
242 "continue:\n%0");
243 Diags.Report(ID) << toString(std::move(Err));
244 return llvm::Error::success();
245 }
246 return Err;
247}
248
249static llvm::Error createDirectories(llvm::StringRef OutDirectory) {
250 if (std::error_code Err = llvm::sys::fs::create_directories(OutDirectory))
251 return llvm::createFileError(OutDirectory, Err,
252 "failed to create directory.");
253 return llvm::Error::success();
254}
255
256int main(int argc, const char **argv) {
257 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
258 std::error_code OK;
259
260 ExitOnErr.setBanner("clang-doc error: ");
261
262 const char *Overview =
263 R"(Generates documentation from source code and comments.
264
265Example usage for files without flags (default):
266
267 $ clang-doc File1.cpp File2.cpp ... FileN.cpp
268
269Example usage for a project using a compile commands database:
270
271 $ clang-doc --executor=all-TUs compile_commands.json
272)";
273
274 auto Executor = ExitOnErr(clang::tooling::createExecutorFromCommandLineArgs(
275 argc, argv, ClangDocCategory, Overview));
276
277 // turns on ftime trace profiling
278 if (FTimeTrace)
279 llvm::timeTraceProfilerInitialize(200, "clang-doc");
280 {
281 llvm::TimeTraceScope("main");
282
283 // Fail early if an invalid format was provided.
284 llvm::StringRef Format = getFormatString();
285 llvm::outs() << "Emiting docs in " << Format << " format.\n";
286 auto G = ExitOnErr(doc::findGeneratorByName(Format));
287
288 ArgumentsAdjuster ArgAdjuster;
289 if (!DoxygenOnly)
290 ArgAdjuster = combineAdjusters(
291 getInsertArgumentAdjuster("-fparse-all-comments",
292 tooling::ArgumentInsertPosition::END),
293 ArgAdjuster);
294
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);
300
302 Executor->getExecutionContext(), ProjectName, PublicOnly, OutDirectory,
304 {UserStylesheets.begin(), UserStylesheets.end()}, Diags, FormatEnum,
306
307 if (Format == "html")
308 ExitOnErr(getHtmlFiles(argv[0], CDCtx));
309 else if (Format == "md")
310 ExitOnErr(getMdFiles(argv[0], CDCtx));
311
312 llvm::timeTraceProfilerBegin("Executor Launch", "total runtime");
313 // Mapping phase
314 llvm::outs() << "Mapping decls...\n";
316 Diags,
317 Executor->execute(doc::newMapperActionFactory(CDCtx), ArgAdjuster)));
318 llvm::timeTraceProfilerEnd();
319
320 // Collect values into output by key.
321 // In ToolResults, the Key is the hashed USR and the value is the
322 // bitcode-encoded representation of the Info object.
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);
329 });
330 llvm::timeTraceProfilerEnd();
331
332 // Collects all Infos according to their unique USR value. This map is added
333 // to from the thread pool below and is protected by the USRToInfoMutex.
334 llvm::sys::Mutex USRToInfoMutex;
335 llvm::StringMap<doc::Info *> USRToInfo;
336
337 // First reducing phase (reduce all decls into one info per decl).
338 llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n";
339 std::atomic<bool> Error;
340 Error = false;
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");
347 // Note: we use per-thread arenas, so Pool must outlive the last use of this
348 // memory in the generators.
349 llvm::DefaultThreadPool Pool(
350 // ExecutorConcurrency is a flag exposed by AllTUsExecution.h
351 llvm::hardware_concurrency(ExecutorConcurrency));
352 {
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]() {
360 if (CDCtx.FTimeTrace)
361 llvm::timeTraceProfilerInitialize(200, "clang-doc");
362
363 doc::Info *Reduced = nullptr;
364 {
365 llvm::TimeTraceScope Red("decoding and merging bitcode");
366 for (const auto &Bitcode : Bitcodes) {
367
368 llvm::scope_exit ArenaGuard(
369 [] { clang::doc::getTransientArena().Reset(); });
370 llvm::BitstreamCursor Stream(Bitcode);
371 doc::ClangDocBitcodeReader Reader(Stream, Diags);
372 auto ReadInfos = Reader.readBitcode();
373 if (!ReadInfos) {
374 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
375
376 Diags.Report(DiagIDBitcodeReading)
377 << toString(ReadInfos.takeError());
378 Error = true;
379 return;
380 }
381 for (auto &I : *ReadInfos) {
382 if (auto Err = doc::mergeSingleInfo(
383 Reduced, std::move(I),
385 std::lock_guard<llvm::sys::Mutex> Guard(DiagMutex);
386 Diags.Report(DiagIDBitcodeMerging)
387 << toString(std::move(Err));
388 return;
389 }
390 }
391 }
392 } // time trace decoding and merging bitcode
393
394 // Add a reference to this Info in the Index
395 {
396 llvm::TimeTraceScope Merge("addInfoToIndex");
397 std::lock_guard<llvm::sys::Mutex> Guard(IndexMutex);
399 }
400 // Save in the result map (needs a lock due to threaded access).
401 {
402 llvm::TimeTraceScope Merge("USRToInfo");
403 std::lock_guard<llvm::sys::Mutex> Guard(USRToInfoMutex);
404 USRToInfo[Key] = std::move(Reduced);
405 }
406
407 if (CDCtx.FTimeTrace)
408 llvm::timeTraceProfilerFinishThread();
409 });
410 }
411
412 Pool.wait();
413 } // time trace reduce
414
415 if (Error)
416 return 1;
417
418 {
419 llvm::TimeTraceScope Sort("Sort USRToInfo");
420 sortUsrToInfo(USRToInfo);
421 }
422
423 llvm::timeTraceProfilerBegin("Writing output", "total runtime");
424 // Ensure the root output directory exists.
426
427 // Run the generator.
428 llvm::outs() << "Generating docs...\n";
429
430 ExitOnErr(
431 G->generateDocumentation(OutDirectory, std::move(USRToInfo), CDCtx));
432 llvm::outs() << "Generating assets for docs...\n";
433 ExitOnErr(G->createResources(CDCtx));
434 llvm::timeTraceProfilerEnd();
435 } // time trace main
436
437 if (FTimeTrace) {
438 std::error_code EC;
439 llvm::raw_fd_ostream OS("clang-doc-tracing.json", EC,
440 llvm::sys::fs::OF_Text);
441 if (!EC) {
442 llvm::timeTraceProfilerWrite(OS);
443 llvm::timeTraceProfilerCleanup();
444 } else
445 return 1;
446 }
447 return 0;
448}
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))
const char * Argv0
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.
Definition Protocol.h:755
@ Error
An error message.
Definition Protocol.h:751
std::unique_ptr< tooling::FrontendActionFactory > newMapperActionFactory(ClangDocContext CDCtx)
Definition ClangDoc.cpp:52
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
A base struct for Infos.