182{
184 error = "a compile database directory is required (-p)";
185 return false;
186 }
187
188 std::string load_error;
189 const auto database = clang::tooling::CompilationDatabase::loadFromDirectory(input.
build_path.string(), load_error);
190 if (!database) {
191 error =
"cannot load compile_commands.json from " + input.
build_path.string() +
": " + load_error;
192 return false;
193 }
194
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();
200 return false;
201 }
202
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";
206 return false;
207 }
208 const TemporaryDirectory cleanup(std::filesystem::path(temporary.str().str()));
209
210 const std::filesystem::path scan_file = cleanup.path / "mf_reflect_scan.cpp";
211 {
212 std::ofstream
source(scan_file, std::ios::binary | std::ios::trunc);
214 if (!source) {
215 error =
"cannot write " + scan_file.string();
216 return false;
217 }
218 }
219
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";
225 if (!file) {
226 error =
"cannot write " + (cleanup.path / stub).
string();
227 return false;
228 }
229 }
230 effective.extra_args.push_back("-I" + cleanup.path.generic_string());
231 }
232
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";
236 return false;
237 }
238
239 std::cerr <<
"Scanning " << input.
headers.size() <<
" header(s) with the compile command of " << unit.string() <<
'\n';
240
241 const ScanDatabase scan_database(std::move(command));
242 clang::tooling::ClangTool tool(scan_database, { scan_file.string() });
243 tool.appendArgumentsAdjuster(make_adjuster(effective));
244
245 clang::ast_matchers::MatchFinder finder;
246 attach(finder);
247
248 if (tool.run(clang::tooling::newFrontendActionFactory(&finder).get()) != 0) {
249 error =
"Clang could not scan the selected headers (translation unit " + unit.string() +
")";
250 return false;
251 }
252 return true;
253}
void error(Component component, Context context, std::source_location location, std::string_view message)
Log an error message and optionally throw an exception.