332{
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";
336 return false;
337 }
338 const TemporaryDirectory cleanup(std::filesystem::path(temporary.str().str()));
339
340 const std::filesystem::path scan_file = cleanup.path / "mf_reflect_scan.cpp";
341 {
342 std::ofstream source(scan_file, std::ios::binary | std::ios::trunc);
344 if (!source) {
345 error = "cannot write " + scan_file.string();
346 return false;
347 }
348 }
349
350 ScanInput effective = input.
scan;
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";
354 if (!file) {
355 error = "cannot write " + (cleanup.path / stub).string();
356 return false;
357 }
358 }
360 effective.extra_args.push_back("-I" + cleanup.path.generic_string());
361 }
362
363 clang::tooling::CompileCommand command;
365 if (!borrowed_command(input.
scan, scan_file, command, error)) {
366 return false;
367 }
368 } else {
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";
376 }
377
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));
382
383 clang::ast_matchers::MatchFinder finder;
384 attach(finder);
385
386 clang::DependencyCollector collector;
387 RecordingFactory factory(finder, collector);
388 if (tool.run(&factory) != 0) {
389 error =
"Clang could not scan the selected headers";
390 return false;
391 }
392
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;
398 }
399 path = absolute_of(path.string());
400 const auto relative = path.lexically_relative(temporary_root);
401 if (!relative.empty() && *relative.begin() != "..") {
402 continue;
403 }
404 dependencies.push_back(std::move(path));
405 }
406 std::ranges::sort(dependencies);
407 dependencies.erase(std::ranges::unique(dependencies).begin(), dependencies.end());
408 return true;
409}
void error(Component component, Context context, std::source_location location, std::string_view message)
Log an error message and optionally throw an exception.