Debian Codegraph @

tools/cppgir.cpp

raw symbols SCIP
1 #include "common.hpp"
2 #include "fs.hpp"
3 #include "genbase.hpp"
4 #include "genns.hpp"
5 #include "repository.hpp"
6
7 #include <boost/algorithm/string/classification.hpp>
8 #include <boost/algorithm/string/split.hpp>
9
10 #include <map>
11 #include <set>
12 #include <vector>
13
14 // thanks go to glib
15 #define GI_STRINGIFY(macro_or_string) GI_STRINGIFY_ARG(macro_or_string)
16 #define GI_STRINGIFY_ARG(contents) #contents
17
18 #ifndef DEFAULT_IGNORE_FILE
19 // embed ignore data
20 #include "ignore.hpp"
21 static std::string GI_DEFAULT_IGNORE;
22 #else
23 static const char *GI_DATA_IGNORE = "";
24 static std::string GI_DEFAULT_IGNORE{GI_STRINGIFY(DEFAULT_IGNORE_FILE)};
25 #endif
26
27 #if defined(_WIN32) && !defined(__CYGWIN__)
28 static const char PATH_SEP = '\\';
29 static const char *PATH_ARR_SEP = ";";
30 #else
31 static const char PATH_SEP = '/';
32 static const char *PATH_ARR_SEP = ":";
33 #endif
34 static const std::string GIR_SUBDIR{"gir-1.0"};
35
36 Log _loglevel = Log::WARNING;
37
38 class Generator
39 {
40 GeneratorContext &ctx_;
41 std::vector<std::string> girdirs_;
42 // processes ns (ns: ns header)
43 std::map<std::string, std::string> processed_;
44
45 public:
46 Generator(GeneratorContext &_ctx, const std::vector<std::string> &girdirs)
47 : ctx_(_ctx), girdirs_(girdirs)
48 {}
49
50 std::string find_in_dir(const fs::path p, const std::string &ns) const
51 {
52 std::string result;
53 fs::error_code ec;
54 // check if in this directory
55 if (!fs::is_directory(p, ec))
56 return "";
57
58 auto f = p / (ns + GIR_SUFFIX);
59 std::vector<fs::directory_entry> dirs;
60 for (auto &&entry : fs::directory_iterator(p, ec)) {
61 if (fs::is_directory(entry, ec)) {
62 dirs.emplace_back(entry);
63 } else if (f == entry) {
64 // exact match
65 result = f.string();
66 } else {
67 // non-version match
68 auto ename = entry.path().filename().string();
69 auto s = ns.size();
70 if (ename.substr(0, s) == ns && ename.size() > s && ename[s] == '-')
71 result = entry.path().string();
72 }
73 }
74 // check dirs
75 while (!dirs.empty() && result.empty()) {
76 result = find_in_dir(dirs.back(), ns);
77 dirs.pop_back();
78 }
79 return result;
80 }
81
82 std::string find(const std::string &ns) const
83 {
84 for (auto &&d : girdirs_) {
85 auto res = find_in_dir(fs::path(d), ns);
86 if (!res.empty())
87 return res;
88 }
89 return "";
90 }
91
92 // gir might be:
93 // + a GIR filename
94 // + or a GIR namespace (ns-version)
95 // + or a GIR namespace (no version appended)
96 void generate(const std::string &gir, bool recurse)
97 {
98 fs::path f(gir);
99 fs::error_code ec;
100 auto path = fs::exists(f, ec) ? gir : find(gir);
101 if (path.empty())
102 throw std::runtime_error("could not find GIR for " + gir);
103 // avoid reading if possible
104 if (processed_.count(gir))
105 return;
106 auto genp = NamespaceGenerator::new_(ctx_, path);
107 auto &gen = *genp;
108 // normalize namespace
109 auto &&ns = gen.get_ns();
110 // prevent duplicate processing
111 if (processed_.count(ns))
112 return;
113 // generate deps
114 auto &&deps = gen.get_dependencies();
115 std::vector<std::string> headers;
116 if (recurse) {
117 for (auto &&d : deps) {
118 generate(d, recurse);
119 // should be available now
120 headers.emplace_back(processed_[d]);
121 }
122 }
123 // now generate this one
124 // also mark processed and retain ns header file
125 processed_[ns] = gen.process_tree(headers);
126 }
127 };
128
129 static std::string
130 wrap(const char *s)
131 {
132 std::string res;
133 if (s)
134 res = s;
135 return res;
136 }
137
138 static int
139 die(const std::string &desc, const std::string &msg = "")
140 {
141 std::cout << msg << std::endl << std::endl;
142 std::cout << desc << std::endl;
143 return 1;
144 }
145
146 static std::string
147 make_subdir(const std::string &dir, const std::string &subdir)
148 {
149 auto result = dir;
150 if (subdir.size()) {
151 assert(subdir.front() != PATH_SEP);
152 if (result.back() != PATH_SEP)
153 result += PATH_SEP;
154 result += subdir;
155 }
156 return result;
157 }
158
159 static void
160 addsplit(std::vector<std::string> &target, const std::string &src,
161 const std::string &suffix = "", const std::string &seps = PATH_ARR_SEP)
162 {
163 std::vector<std::string> tmp;
164 boost::split(tmp, src, boost::is_any_of(seps));
165 for (auto &&d : tmp) {
166 if (d.size()) {
167 target.emplace_back(make_subdir(d, suffix));
168 }
169 }
170 }
171
172 namespace options
173 {
174 using OptionParseFunc = std::function<bool(const char *)>;
175
176 struct Option
177 {
178 std::string arg;
179 OptionParseFunc func;
180 };
181
182 Option
183 make_parser(bool *val)
184 {
185 auto h = [val](const char *v) {
186 // no arg for command-line option, set to true in that case
187 *val = v ? atoi(v) : true;
188 return true;
189 };
190 return {"", h};
191 }
192
193 Option
194 make_parser(int *val)
195 {
196 auto h = [val](const char *nextarg) {
197 try {
198 *val = std::stoi(nextarg);
199 return true;
200 } catch (const std::exception &exc) {
201 return false;
202 }
203 };
204 return {"number", h};
205 }
206
207 Option
208 make_parser(std::string *val)
209 {
210 auto h = [val](const char *nextarg) {
211 *val = nextarg;
212 return true;
213 };
214 return {"arg", h};
215 }
216
217 } // namespace options
218
219 int
220 main(int argc, char *argv[])
221 {
222 (void)argc;
223 (void)argv;
224
225 using namespace options;
226
227 // env/options targets
228 int debug_level{};
229 std::string fpath_ignore;
230 std::string fpath_suppress{};
231 std::string fpath_gen_suppress;
232 std::string output_dir;
233 bool doclass{};
234 bool dofullclass{};
235 bool use_dl{};
236 bool use_expected{};
237 bool const_method{};
238 bool output_top{};
239 int call_args{-1};
240 bool only_changed{};
241 bool basic_collection{};
242 bool dump_ignore{};
243 std::string gir_path;
244
245 std::string helpdesc;
246 struct OptionData
247 {
248 std::string opt;
249 std::string var;
250 const char *desc;
251 Option option{};
252 };
253 std::vector<OptionData> descs = {
254 {"help", "", "produce help message"},
255 {"debug", "GI_DEBUG", "debug level", make_parser(&debug_level)},
256 {"ignore", "GI_IGNORE", "colon separated ignore files",
257 make_parser(&fpath_ignore)},
258 {"suppression", "GI_SUPPRESSION", "colon separated suppression files",
259 make_parser(&fpath_suppress)},
260 {"gen-suppression", "G_GEN_SUPPRESSION", "generate suppression file",
261 make_parser(&fpath_gen_suppress)},
262 {"output", "GI_OUTPUT", "output directory", make_parser(&output_dir)},
263 {"gir-path", "GI_GIR_PATH", "colon separated GIR search path",
264 make_parser(&gir_path)},
265 {"class", "GI_CLASS", "generate class implementation",
266 make_parser(&doclass)},
267 {"class-full", "GI_CLASS_FULL", "generate fallback class methods",
268 make_parser(&dofullclass)},
269 {"dl", "GI_DL", "use dynamic dlopen/dlsym rather than static link",
270 make_parser(&use_dl)},
271 {"expected", "GI_EXPECTED", "use expected<> return rather than exception",
272 make_parser(&use_expected)},
273 {"const-method", "GI_CONST_METHOD", "generate const methods",
274 make_parser(&const_method)},
275 {"output-top", "GI_OUTPUT_TOP",
276 "generate convenience wrappers in output dir",
277 make_parser(&output_top)},
278 {"only-changed", "GI_ONLY_CHANGED",
279 "only generate output if new or changed", make_parser(&only_changed)},
280 {"call-args", "GI_CALL_ARGS",
281 "(if >= 0) min #optional arguments to enable a CallArgs variant",
282 make_parser(&call_args)},
283 {"basic-collection", "GI_BASIC_COLLECTION",
284 "also generate collection for input collection of basic type",
285 make_parser(&basic_collection)},
286 };
287
288 // optionally dump embedded ignore
289 if (*GI_DATA_IGNORE) {
290 descs.push_back({"dump-ignore", "", "dump embedded ignore data",
291 make_parser(&dump_ignore)});
292 }
293
294 std::map<std::string, OptionData *> descs_index;
295
296 // first collect settings from environment
297 for (auto &e : descs) {
298 // build index
299 descs_index[e.opt] = &e;
300 // check env var
301 if (!e.var.empty() && e.option.func) {
302 if (auto v = getenv(e.var.c_str())) {
303 e.option.func(v);
304 }
305 }
306 }
307
308 // non-option argument analogue
309 auto gir_top = wrap(getenv("GI_GIR"));
310
311 // into settings
312 std::vector<std::string> girs, ignore_files, suppress_files;
313 std::vector<std::string> girdirs;
314
315 // collect ignore files
316 auto fpath_ignore_env = std::move(fpath_ignore);
317 // suppress files
318 auto fpath_suppress_env = std::move(fpath_suppress);
319 // GIR path
320 auto gir_path_env = std::move(gir_path);
321
322 { // basic command line processing
323 // assemble help description
324 auto tmpl = (R"|(
325 {} [options] girs...
326
327 Supported options and environment variables
328 (specify 0 or 1 as environment variable value for a boolean switch):
329
330 )|");
331 helpdesc = fmt::format(tmpl, argv[0]);
332 for (auto &entry : std::as_const(descs)) {
333 std::string var = entry.var;
334 var = !var.empty() ? fmt::format("[{}] ", var) : var;
335 helpdesc += fmt::format(" --{:<25}{}{}\n",
336 entry.opt + ' ' + entry.option.arg, var, entry.desc);
337 }
338 if (!GI_DEFAULT_IGNORE.empty()) {
339 helpdesc +=
340 fmt::format("\nDefault ignore files:\n{}\n", GI_DEFAULT_IGNORE);
341 }
342
343 // simple command line processing
344 for (int i = 1; i < argc; ++i) {
345 std::string opt = argv[i];
346 if (opt == "-h" || opt == "--help")
347 return die(helpdesc);
348 if (opt.size() > 2 && opt.find("--") == 0) {
349 auto oi = descs_index.find(opt.substr(2));
350 if (oi != descs_index.end()) {
351 assert(oi->second);
352 auto &option = *oi->second;
353 assert(option.option.func);
354 char *nextarg = nullptr;
355 if (!option.option.arg.empty()) {
356 if (i + 1 >= argc) {
357 return die(helpdesc, opt + "; missing argument");
358 } else {
359 nextarg = argv[i + 1];
360 ++i;
361 }
362 }
363 logger(Log::LOG,
364 fmt::format("processing option {} {}", opt, wrap(nextarg)));
365 if (!option.option.func(nextarg))
366 return die(helpdesc, opt + "; invalid argument " + nextarg);
367 } else {
368 return die(helpdesc, "unknown option " + opt);
369 }
370 } else if (!opt.empty() && opt[0] == '-') {
371 return die(helpdesc, "unknown option " + opt);
372 } else {
373 girs.push_back(opt);
374 }
375 }
376 }
377
378 if (dump_ignore) {
379 std::cout << GI_DATA_IGNORE << std::endl;
380 return 0;
381 }
382
383 // collect some more files
384 addsplit(ignore_files, fpath_ignore);
385 addsplit(suppress_files, fpath_suppress);
386 addsplit(girdirs, gir_path);
387
388 // add env specified
389 addsplit(ignore_files, fpath_ignore_env);
390 addsplit(suppress_files, fpath_suppress_env);
391 addsplit(girdirs, gir_path_env);
392
393 // level
394 if (debug_level > 0)
395 _loglevel = (Log)debug_level;
396
397 // system default
398 {
399 // gobject-introspection considers XDG_DATA_HOME first
400 // (essentially g_get_user_data_dir)
401 auto xdg_data_home = wrap(getenv("XDG_DATA_HOME"));
402 if (xdg_data_home.empty()) {
403 xdg_data_home = wrap(getenv("HOME"));
404 if (!xdg_data_home.empty()) {
405 if (xdg_data_home.back() != PATH_SEP)
406 xdg_data_home += PATH_SEP;
407 xdg_data_home += fmt::format(".local{}share", PATH_SEP);
408 }
409 }
410 std::vector<std::string> default_gir_dirs;
411 if (!xdg_data_home.empty())
412 default_gir_dirs.push_back(xdg_data_home);
413 // gobject-introspection uses XDG_DATA_DIRS next
414 // (essentially g_get_system_data_dirs)
415 auto xdg_data_dirs = wrap(getenv("XDG_DATA_DIRS"));
416 addsplit(default_gir_dirs, xdg_data_dirs);
417 // g_get_system_data_dirs optionally falls back to fixed /usr[/local] now
418 // but that would then precede custom paths, which is a bit unfortunate
419 // so, instead, consider those only as the very last resort (below)
420 for (auto &d : default_gir_dirs) {
421 girdirs.push_back(make_subdir(d, GIR_SUBDIR));
422 }
423 }
424
425 // extra GIR paths that gobject-introspection considers
426 #ifdef GI_GIR_DIR
427 girdirs.push_back(GI_STRINGIFY(GI_GIR_DIR));
428 #endif
429 #ifdef GI_DATA_DIR
430 girdirs.push_back(GI_STRINGIFY(GI_DATA_DIR));
431 #endif
432 #ifdef DEFAULT_GIRPATH
433 // optional (hard) fallback
434 addsplit(girdirs, GI_STRINGIFY(DEFAULT_GIRPATH), GIR_SUBDIR);
435 #endif
436
437 for (auto &&d : girdirs)
438 logger(Log::DEBUG, "extending GIR path " + d);
439
440 // system default
441 if (!GI_DEFAULT_IGNORE.empty())
442 addsplit(ignore_files, GI_DEFAULT_IGNORE);
443
444 // collect girs to process
445 addsplit(girs, gir_top);
446
447 // sanity check
448 if (output_dir.empty())
449 return die(helpdesc, "missing output directory");
450 if (girs.empty())
451 return die(helpdesc, "nothing to process");
452
453 // check for now
454 if (girdirs.empty())
455 return die(helpdesc, "empty search path");
456
457 // at least the standard ignore file is required
458 // or things will go wrong
459 int cnt = 0;
460 fs::error_code ec;
461 for (auto &f : ignore_files)
462 cnt += fs::exists(f, ec);
463
464 if (cnt == 0 && !GI_DEFAULT_IGNORE.empty())
465 return die(helpdesc, "required default ignore file location not specified");
466
467 // HACKety hack; extract some other config from ignore files
468 // (avoids coming up with another separate config file for now)
469 std::map<std::string, std::string> custom_c_types;
470 auto custom = [&custom_c_types](const std::string &line) {
471 if (line.find("#!ctype:") == 0) {
472 std::vector<std::string> tmp;
473 addsplit(tmp, line);
474 if (tmp.size() == 3) {
475 custom_c_types[tmp[1]] = tmp[2];
476 }
477 }
478 };
479
480 auto match_ignore = Matcher(ignore_files, GI_DATA_IGNORE, custom);
481 auto match_suppress = Matcher(suppress_files);
482
483 // now let's start
484 GeneratorOptions options;
485 options.rootdir = output_dir;
486 options.classimpl = doclass;
487 options.classfull = dofullclass;
488 options.dl = use_dl;
489 options.expected = use_expected;
490 options.const_method = const_method;
491 options.output_top = output_top;
492 options.only_changed = only_changed;
493 options.call_args = call_args;
494 options.basic_collection = basic_collection;
495
496 logger(Log::INFO, "generating to directory {}", options.rootdir);
497
498 auto repo = Repository::new_(custom_c_types);
499 std::set<std::string> suppressions;
500 GeneratorContext ctx{
501 options, *repo, match_ignore, match_suppress, suppressions};
502 Generator gen(ctx, girdirs);
503 try {
504 for (auto &&g : girs)
505 gen.generate(g, true);
506
507 // write suppression
508 if (fpath_gen_suppress.size()) {
509 std::vector<std::string> sup(suppressions.begin(), suppressions.end());
510 sort(sup.begin(), sup.end());
511 logger(Log::INFO, "writing {} suppressions to {}", sup.size(),
512 fpath_gen_suppress);
513
514 std::ofstream fsup(fpath_gen_suppress);
515 for (auto &&v : sup)
516 fsup << v << std::endl;
517 }
518 } catch (std::runtime_error &ex) {
519 logger(Log::ERROR, ex.what());
520 return EXIT_FAILURE;
521 }
522
523 return EXIT_SUCCESS;
524 }