3#include <clang/AST/ASTConsumer.h>
4#include <clang/Frontend/CompilerInstance.h>
5#include <clang/Frontend/FrontendAction.h>
6#include <clang/Frontend/Utils.h>
12 constexpr const char* marker_source = R
"(#define MAYAFLUX_REFLECT_SCAN
16#define MF_REFLECT_JOIN_IMPL(a, b) a##b
17#define MF_REFLECT_JOIN(a, b) MF_REFLECT_JOIN_IMPL(a, b)
18#define MF_DESCRIBE(...) using MF_REFLECT_JOIN(mf_reflection_request_, __COUNTER__) = __VA_ARGS__;
19#ifdef MF_DESCRIBE_FUNCTION
20#undef MF_DESCRIBE_FUNCTION
22#define MF_DESCRIBE_FUNCTION(...) inline constexpr auto MF_REFLECT_JOIN(mf_signature_request_, __COUNTER__) = __VA_ARGS__;
25 std::filesystem::path absolute_of(const std::string& file)
28 auto resolved = std::filesystem::weakly_canonical(file, code);
29 return code ? std::filesystem::path(file) : resolved;
32 std::filesystem::path select_translation_unit(
33 const clang::tooling::CompilationDatabase& database,
36 if (!input.translation_unit.empty()) {
37 return absolute_of(input.translation_unit.string());
39 const std::vector<std::string> files = database.getAllFiles();
40 for (
const std::string& file : files) {
41 const std::filesystem::path candidate = absolute_of(file);
42 for (
const auto& root : input.roots) {
43 const auto relative = candidate.lexically_relative(root);
44 if (!relative.empty() && *relative.begin() !=
"..") {
49 return files.empty() ? std::filesystem::path {} : absolute_of(files.front());
52 std::string scan_source(
const std::vector<std::filesystem::path>& headers)
54 std::string
source = marker_source;
55 for (
const auto& header : headers) {
56 source +=
"#include \"" + header.generic_string() +
"\"\n";
61 clang::tooling::ArgumentsAdjuster make_adjuster(
const ScanInput& input)
63 return [resource = input.resource_dir, extra = input.extra_args](
64 const clang::tooling::CommandLineArguments& arguments, llvm::StringRef) {
65 clang::tooling::CommandLineArguments adjusted;
66 adjusted.reserve(arguments.size() + extra.size() + 2);
67 bool has_resource =
false;
68 for (std::size_t i = 0; i < arguments.size(); ++i) {
69 const std::string& argument = arguments[i];
70 if (argument ==
"-Xclang" && i + 3 < arguments.size() && arguments[i + 1] ==
"-include-pch") {
74 if (argument ==
"-include-pch") {
79 if (argument.size() >= 3 && (argument.front() ==
'/' || argument.front() ==
'-')) {
80 const std::string_view option = std::string_view(argument).substr(1);
81 if (option.starts_with(
"Yu") || option.starts_with(
"Yc") || option.starts_with(
"Fp")) {
82 if (option.size() == 2 && i + 1 < arguments.size()
83 && !arguments[i + 1].empty()
84 && arguments[i + 1].front() !=
'/'
85 && arguments[i + 1].front() !=
'-') {
92 has_resource = has_resource || argument ==
"-resource-dir";
93 adjusted.push_back(argument);
95 const auto insert_at = adjusted.begin() + (adjusted.empty() ? 0 : 1);
96 std::vector<std::string> added;
97 if (!has_resource && !resource.empty() && llvm::sys::fs::is_directory(resource)) {
98 added.emplace_back(
"-resource-dir");
99 added.push_back(resource);
101 added.insert(added.end(), extra.begin(), extra.end());
102 adjusted.insert(insert_at, added.begin(), added.end());
107 struct TemporaryDirectory {
108 std::filesystem::path path;
110 explicit TemporaryDirectory(std::filesystem::path directory)
111 : path(std::
move(directory))
115 TemporaryDirectory(
const TemporaryDirectory&) =
delete;
116 TemporaryDirectory& operator=(
const TemporaryDirectory&) =
delete;
117 TemporaryDirectory(TemporaryDirectory&&) =
delete;
118 TemporaryDirectory& operator=(TemporaryDirectory&&) =
delete;
120 ~TemporaryDirectory()
122 std::error_code code;
123 std::filesystem::remove_all(path, code);
127 class ScanDatabase :
public clang::tooling::CompilationDatabase {
129 explicit ScanDatabase(clang::tooling::CompileCommand command)
130 : m_command(std::
move(command))
134 [[nodiscard]] std::vector<clang::tooling::CompileCommand> getCompileCommands(llvm::StringRef file)
const override
136 if (file == m_command.Filename) {
137 return { m_command };
142 [[nodiscard]] std::vector<std::string> getAllFiles()
const override {
return { m_command.Filename }; }
144 [[nodiscard]] std::vector<clang::tooling::CompileCommand> getAllCompileCommands()
const override
146 return { m_command };
150 clang::tooling::CompileCommand m_command;
153 bool retarget(clang::tooling::CompileCommand& command,
const std::filesystem::path& unit,
154 const std::filesystem::path& scan_file)
156 bool replaced =
false;
157 for (std::string& argument : command.CommandLine) {
158 if (argument.empty() || argument.front() ==
'-') {
161 std::filesystem::path candidate(argument);
162 if (candidate.is_relative()) {
163 candidate = std::filesystem::path(command.Directory) / candidate;
165 if (absolute_of(candidate.string()) == unit) {
166 argument = scan_file.string();
170 command.Filename = scan_file.string();
178 return scan(input, [&collector](clang::ast_matchers::MatchFinder& finder) { collector.
attach(finder); }, error);
184 error =
"a compile database directory is required (-p)";
188 std::string load_error;
189 const auto database = clang::tooling::CompilationDatabase::loadFromDirectory(input.
build_path.string(), load_error);
191 error =
"cannot load compile_commands.json from " + input.
build_path.string() +
": " + load_error;
195 const std::filesystem::path unit = select_translation_unit(*database, input);
196 const auto commands = unit.empty() ? std::vector<clang::tooling::CompileCommand> {}
197 : database->getCompileCommands(unit.string());
198 if (commands.empty()) {
199 error =
"no compile command found for translation unit " + unit.string();
203 llvm::SmallString<128> temporary;
204 if (llvm::sys::fs::createUniqueDirectory(
"mayaflux-reflect", temporary)) {
205 error =
"cannot create a temporary directory for the scan source";
208 const TemporaryDirectory cleanup(std::filesystem::path(temporary.str().str()));
210 const std::filesystem::path scan_file = cleanup.path /
"mf_reflect_scan.cpp";
212 std::ofstream source(scan_file, std::ios::binary | std::ios::trunc);
213 source << scan_source(input.
headers);
215 error =
"cannot write " + scan_file.string();
221 if (!input.
stubs.empty()) {
222 for (
const std::string& stub : input.
stubs) {
223 std::ofstream file(cleanup.path / stub, std::ios::binary | std::ios::trunc);
224 file <<
"#pragma once\n";
226 error =
"cannot write " + (cleanup.path / stub).
string();
230 effective.
extra_args.push_back(
"-I" + cleanup.path.generic_string());
233 clang::tooling::CompileCommand command = commands.front();
234 if (!retarget(command, unit, scan_file)) {
235 error =
"the compile command of " + unit.string() +
" does not name its source file";
239 std::cerr <<
"Scanning " << input.
headers.size() <<
" header(s) with the compile command of " << unit.string() <<
'\n';
241 const ScanDatabase scan_database(std::move(command));
242 clang::tooling::ClangTool tool(scan_database, { scan_file.string() });
243 tool.appendArgumentsAdjuster(make_adjuster(effective));
245 clang::ast_matchers::MatchFinder finder;
248 if (tool.run(clang::tooling::newFrontendActionFactory(&finder).get()) != 0) {
249 error =
"Clang could not scan the selected headers (translation unit " + unit.string() +
")";
257 class RecordingAction :
public clang::ASTFrontendAction {
259 RecordingAction(clang::ast_matchers::MatchFinder& finder, clang::DependencyCollector& collector)
261 , m_collector(collector)
266 std::unique_ptr<clang::ASTConsumer> CreateASTConsumer(
267 clang::CompilerInstance& instance, llvm::StringRef)
override
269 m_collector.attachToPreprocessor(instance.getPreprocessor());
270 return m_finder.newASTConsumer();
274 clang::ast_matchers::MatchFinder& m_finder;
275 clang::DependencyCollector& m_collector;
278 class RecordingFactory :
public clang::tooling::FrontendActionFactory {
280 RecordingFactory(clang::ast_matchers::MatchFinder& finder, clang::DependencyCollector& collector)
282 , m_collector(collector)
286 std::unique_ptr<clang::FrontendAction>
create()
override
288 return std::make_unique<RecordingAction>(m_finder, m_collector);
292 clang::ast_matchers::MatchFinder& m_finder;
293 clang::DependencyCollector& m_collector;
296 bool borrowed_command(
const ScanInput& input,
const std::filesystem::path& scan_file,
297 clang::tooling::CompileCommand& command, std::string& error)
299 if (input.build_path.empty()) {
300 error =
"a compile database directory is required (-p) when no --compile-arg is given";
304 std::string load_error;
305 const auto database = clang::tooling::CompilationDatabase::loadFromDirectory(input.build_path.string(), load_error);
307 error =
"cannot load compile_commands.json from " + input.build_path.string() +
": " + load_error;
311 const std::filesystem::path unit = select_translation_unit(*database, input);
312 const auto commands = unit.empty() ? std::vector<clang::tooling::CompileCommand> {}
313 : database->getCompileCommands(unit.string());
314 if (commands.empty()) {
315 error =
"no compile command found for translation unit " + unit.string();
319 command = commands.front();
320 if (!retarget(command, unit, scan_file)) {
321 error =
"the compile command of " + unit.string() +
" does not name its source file";
324 std::cerr <<
"Scanning " << input.headers.size() <<
" header(s) with the compile command of " << unit.string() <<
'\n';
331 std::vector<std::filesystem::path>& dependencies, std::string& error)
333 llvm::SmallString<128> temporary;
334 if (llvm::sys::fs::createUniqueDirectory(
"mayaflux-reflect", temporary)) {
335 error =
"cannot create a temporary directory for the scan source";
338 const TemporaryDirectory cleanup(std::filesystem::path(temporary.str().str()));
340 const std::filesystem::path scan_file = cleanup.path /
"mf_reflect_scan.cpp";
342 std::ofstream source(scan_file, std::ios::binary | std::ios::trunc);
345 error =
"cannot write " + scan_file.string();
351 for (
const std::string& stub : input.
scan.
stubs) {
352 std::ofstream file(cleanup.path / stub, std::ios::binary | std::ios::trunc);
353 file <<
"#pragma once\n";
355 error =
"cannot write " + (cleanup.path / stub).
string();
360 effective.
extra_args.push_back(
"-I" + cleanup.path.generic_string());
363 clang::tooling::CompileCommand command;
365 if (!borrowed_command(input.
scan, scan_file, command, error)) {
369 std::error_code code;
370 command.Directory = std::filesystem::current_path(code).string();
371 command.Filename = scan_file.string();
372 command.CommandLine.emplace_back(
"clang++");
374 command.CommandLine.push_back(scan_file.string());
375 std::cerr <<
"Scanning " << input.
scan.
headers.size() <<
" header(s) with explicit compile arguments\n";
378 const std::filesystem::path directory(command.Directory);
379 const ScanDatabase scan_database(std::move(command));
380 clang::tooling::ClangTool tool(scan_database, { scan_file.string() });
381 tool.appendArgumentsAdjuster(make_adjuster(effective));
383 clang::ast_matchers::MatchFinder finder;
386 clang::DependencyCollector collector;
387 RecordingFactory factory(finder, collector);
388 if (tool.run(&factory) != 0) {
389 error =
"Clang could not scan the selected headers";
393 const std::filesystem::path temporary_root = absolute_of(cleanup.path.string());
394 for (
const std::string& file : collector.getDependencies()) {
395 std::filesystem::path path(file);
396 if (path.is_relative()) {
397 path = directory / path;
399 path = absolute_of(path.string());
400 const auto relative = path.lexically_relative(temporary_root);
401 if (!relative.empty() && *relative.begin() !=
"..") {
404 dependencies.push_back(std::move(path));
406 std::ranges::sort(dependencies);
407 dependencies.erase(std::ranges::unique(dependencies).begin(), dependencies.end());
void error(Component component, Context context, std::source_location location, std::string_view message)
Log an error message and optionally throw an exception.
void move(EditableText &s, int n)
Move the cursor by n codepoints.