Debian Codegraph @

tools/function.cpp

raw symbols SCIP
1 #include "function.hpp"
2
3 #include <boost/algorithm/string/join.hpp>
4 #include <boost/range/adaptor/transformed.hpp>
5 #include <boost/range/iterator.hpp>
6
7 #include <map>
8 #include <tuple>
9
10 namespace
11 { // anonymous
12
13 const int INDEX_RETURN{-5};
14 const int INDEX_INSTANCE{-1};
15 const int INDEX_CF{150};
16 const int INDEX_ERROR{100};
17 const std::string MOVE = "std::move";
18
19 struct FunctionGenerator : public GeneratorBase
20 {
21 using Output = FunctionDefinition::Output;
22
23 const ElementFunction &func;
24 // duplicated from above
25 const std::string &kind;
26 const std::string &klass, &klasstype;
27 // errors collected along the way (trigger abort)
28 std::vector<std::string> errors;
29 // collected dependencies
30 DepsSet &deps;
31 // collected CallArgs definitions
32 std::ostream *call_args_decl{};
33 // tweak debug level upon error
34 bool ignored = false;
35 bool introspectable = true;
36 bool allow_deprecated = false;
37
38 // also detect various function generation alternatives
39 enum class opt_except {
40 NOEXCEPT,
41 THROW,
42 EXPECTED,
43 GERROR,
44 DEFAULT = NOEXCEPT,
45 ALT = GERROR
46 };
47 std::set<opt_except> do_except = {opt_except::DEFAULT};
48 enum class opt_output { PARAM, TUPLE, DEFAULT = PARAM, ALT = TUPLE };
49 std::set<opt_output> do_output = {opt_output::DEFAULT};
50 enum class opt_nullable {
51 PRESENT,
52 DISCARD,
53 DEFAULT = PRESENT,
54 ALT = DISCARD
55 };
56 std::set<opt_nullable> do_nullable = {opt_nullable::DEFAULT};
57 // basic value container
58 enum class opt_basic_container {
59 PASS,
60 COLLECTION,
61 DEFAULT = PASS,
62 ALT = COLLECTION
63 };
64 // default is fixed and always processed
65 std::set<opt_basic_container> do_basic_container;
66
67 struct Options
68 {
69 opt_except except{};
70 opt_output output{};
71 opt_nullable nullable{};
72 opt_basic_container basic_container{};
73 Options(opt_except _except, opt_output _output, opt_nullable _nullable)
74 : except(_except), output(_output), nullable(_nullable)
75 {}
76 Options() {}
77 };
78
79 // global info
80 // track callback's user_data
81 int found_user_data = INDEX_DEFAULT;
82 // const method
83 bool const_method = false;
84 // typical async method;
85 // has GAsyncReadyCallback param with async scope
86 std::string async_cb_wrapper;
87 // indexed by GIR numbering (first non-instance parameter index 0)
88 std::map<int, Parameter> paraminfo;
89 // param numbers referenced by some other parameter
90 std::set<int> referenced;
91 // defined/declared CallArgs
92 // (various exception variants may re-use the same)
93 std::set<std::string> call_args_types;
94 // collects generated declaration and implementation
95 std::ostringstream oss_decl, oss_impl;
96
97 using FunctionData = FunctionDefinition;
98
99 struct FunctionDataExtended : public FunctionDefinition
100 {
101 // (indexed as above)
102 std::vector<decltype(cpp_decl)::mapped_type> cpp_decl_unfolded;
103
104 FunctionDataExtended() = default;
105
106 FunctionDataExtended(FunctionDefinition odef)
107 : FunctionDefinition(std::move(odef))
108 {
109 auto &def = *this;
110 // process decl map into plain list
111 def.cpp_decl_unfolded.clear();
112 for (auto &&e : def.cpp_decl)
113 def.cpp_decl_unfolded.emplace_back(e.second);
114 }
115 };
116
117 public:
118 FunctionGenerator(GeneratorContext &_ctx, const std::string _ns,
119 const ElementFunction &_func, const std::string &_klass,
120 const std::string &_klasstype, DepsSet &_deps, std::ostream *_call_args,
121 bool _allow_deprecated = false)
122 : GeneratorBase(_ctx, _ns), func(_func), kind(func.kind), klass(_klass),
123 klasstype(_klasstype), deps(_deps), call_args_decl(_call_args),
124 allow_deprecated(_allow_deprecated)
125 {
126 assert(func.name.size());
127 assert(func.kind.size());
128 assert(func.c_id.size());
129 assert(func.functionexp.size());
130 }
131
132 static bool ends_with(std::string const &value, std::string const &ending)
133 {
134 if (ending.size() > value.size())
135 return false;
136 return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
137 };
138
139 void handle_skip(const skip &ex)
140 {
141 // we tried but it went wrong ...
142 if (errors.empty() && !introspectable) {
143 errors.push_back("not introspectable");
144 // ... so let's not complain about it
145 ignored = true;
146 }
147 if (ex.cause == skip::INVALID) {
148 auto level = ignored ? Log::DEBUG : Log::WARNING;
149 if (check_suppression(ns, kind, func.c_id))
150 level = Log::DEBUG;
151 logger(level, "skipping {} {}; {}", kind, func.c_id, ex.what());
152 } else if (ex.cause == skip::IGNORE) {
153 ignored = true;
154 }
155 errors.push_back(ex.what());
156 }
157
158 bool check_errors()
159 {
160 // check errors
161 if (errors.size()) {
162 auto reason = ignored ? "IGNORE" : "SKIP";
163 auto err = fmt::format(
164 "// {}; {}", reason, boost::algorithm::join(errors, ", "));
165 oss_decl << err << std::endl;
166 // no impl for signals
167 if (kind != EL_SIGNAL)
168 oss_impl << err << std::endl;
169 return true;
170 }
171 return false;
172 }
173
174 // all parameters should have ctype info except for signal case
175 void check_ctype(const ArgInfo &info)
176 {
177 if (info.ctype.empty() && kind != EL_SIGNAL)
178 throw skip("missing c:type info");
179 }
180
181 void collect_param(const pt::ptree::value_type &n, int &param_no)
182 {
183 // instance parameter not in cpp signature
184 auto &el = n.first;
185 bool instance = (el == EL_INSTANCE_PARAMETER);
186 param_no += instance ? 0 : 1;
187 // directly parse into target
188 // so we always have minimal attributes for raw fallback
189 auto &pinfo = paraminfo[param_no];
190 pinfo.instance = instance;
191 pinfo.name = unreserve(get_name(n.second), false);
192 // gather a bunch of attributes
193 pinfo.direction = get_attribute(n.second, AT_DIRECTION, DIR_IN);
194 pinfo.transfer = get_attribute(n.second, AT_TRANSFER);
195 pinfo.closure = get_attribute<int>(n.second, AT_CLOSURE, -10);
196 pinfo.destroy = get_attribute<int>(n.second, AT_DESTROY, -10);
197 pinfo.callerallocates =
198 get_attribute<int>(n.second, AT_CALLER_ALLOCATES, 0);
199 pinfo.scope = get_attribute(n.second, AT_SCOPE, "");
200 bool allownone = get_attribute<bool>(n.second, AT_ALLOW_NONE, 0);
201 // limited backwards compatbility for allow-none
202 bool is_out = pinfo.direction.find(DIR_OUT) != pinfo.direction.npos;
203 pinfo.optional =
204 (is_out && allownone) || get_attribute<bool>(n.second, AT_OPTIONAL, 0);
205 pinfo.nullable =
206 (!is_out && allownone) || get_attribute<bool>(n.second, AT_NULLABLE, 0);
207 // might fail
208 parse_arginfo(n.second, &pinfo.tinfo);
209 check_ctype(pinfo.tinfo);
210 }
211
212 void collect_node(const pt::ptree::value_type &entry)
213 {
214 auto &node = entry.second;
215
216 // should be ignored in some cases
217 try {
218 auto deprecated = get_attribute<int>(node, AT_DEPRECATED, 0);
219 if (ctx.match_ignore.matches(ns, kind, {func.name, func.c_id}))
220 throw skip("marked ignore", skip::IGNORE);
221 if (deprecated && !allow_deprecated)
222 throw skip("deprecated", skip::IGNORE);
223 // there are a few nice-to-have in this case (e.g. some _get_source)
224 // so let's try anyway but not complain too much if it goes wrong
225 auto intro = get_attribute<int>(node, AT_INTROSPECTABLE, 1);
226 // except when renaming is at hand
227 auto shadowed = get_attribute(node, AT_SHADOWED_BY, "");
228 if (shadowed.size() && !intro)
229 throw skip("not introspectable; shadowed-by " + shadowed, skip::IGNORE);
230 // otherwise mark and try ...
231 introspectable = intro;
232 } catch (skip &ex) {
233 handle_skip(ex);
234 }
235
236 try {
237 auto &ret = node.get_child(EL_RETURN);
238 // return value
239 // always try to read minimal info (e.g. ctype)
240 // as it might be needed for method fallback
241 auto &pinfo = paraminfo[INDEX_RETURN];
242 pinfo.direction = DIR_RETURN;
243 // best effort for now, see also below
244 pinfo.transfer = get_attribute(ret, AT_TRANSFER, TRANSFER_FULL);
245 pinfo.nullable = get_attribute<bool>(ret, AT_NULLABLE, 0);
246 parse_arginfo(ret, &pinfo.tinfo);
247 // override constructor to return class instance
248 if (kind == EL_CONSTRUCTOR)
249 parse_typeinfo(klasstype, pinfo.tinfo);
250 check_ctype(pinfo.tinfo);
251 pinfo.transfer = pinfo.tinfo.cpptype == CPP_VOID
252 ? TRANSFER_FULL
253 : get_attribute(ret, AT_TRANSFER);
254 } catch (skip &ex) {
255 handle_skip(ex);
256 }
257
258 { // first pass to collect parameter info
259 int param_no = INDEX_INSTANCE;
260 auto params = node.get_child_optional(EL_PARAMETERS);
261 if (params.is_initialized()) {
262 for (auto &n : params.value()) {
263 try {
264 auto el = n.first;
265 if (el == EL_PARAMETER || el == EL_INSTANCE_PARAMETER) {
266 collect_param(n, param_no);
267 }
268 } catch (skip &ex) {
269 handle_skip(ex);
270 }
271 }
272 }
273 }
274 }
275
276 // could be dropped if wrap/unwrap is made more casual about const-stuff
277 // but on the other hand these checks catch some incorrect annotations
278 // so some warning or discarding still has merit
279 void verify_const_transfer(const ArgInfo &info, const std::string &transfer,
280 const std::string &direction, bool /*wrap*/)
281 {
282 auto ctype = info.ctype;
283 // never mind in case of signal
284 if (kind == EL_SIGNAL)
285 return;
286 // note that const for parameter is not always picked up reliably
287 // so if the ctype is const, it probably really is
288 // (and so we might complain or warn)
289 // but if the ctype is not const, the real one in function might
290 // actually be (so we can't know for sure and then should not warn)
291 // const and transfer full should not go together
292 if (is_const(ctype) && transfer != TRANSFER_NOTHING) {
293 auto level =
294 check_suppression(ns, kind, func.c_id) ? Log::DEBUG : Log::WARNING;
295 logger(level, "warning; {}; const transfer {} mismatch [{}]", func.c_id,
296 transfer, direction);
297 }
298 #if 0
299 if ((flags & TYPE_BASIC) && (flags & TYPE_CLASS)) {
300 // string transfer none preferably unwraps to a const
301 // but as mentioned above; this check is not reliable
302 if (!wrap && !is_const (ctype) && transfer == TRANSFER_NOTHING)
303 throw skip ("transfer none on non-const string");
304 }
305 #endif
306 }
307
308 bool process_param_in_callback(int param_no, const Parameter &pinfo,
309 const Options & /*options*/, FunctionData &def, bool defaultable)
310 {
311 auto closure = pinfo.closure;
312 auto scope = pinfo.scope;
313 auto destroy = pinfo.destroy;
314 auto &pname = pinfo.name;
315 auto &&cpptype = pinfo.tinfo.cppreftype(pinfo.transfer);
316 const bool callee = kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD;
317
318 logger(Log::LOG, "param_in_callback {} {}", param_no, pname);
319 // lots of sanity to check
320 static const std::string SCOPE_ASYNC_DEP("async_dep");
321 const bool async_method = !async_cb_wrapper.empty();
322 if (closure < 0)
323 throw skip("callback misses closure info");
324 auto it = paraminfo.find(closure);
325 if (it == paraminfo.end())
326 throw skip("callback has invalid closure parameter");
327 const auto &cctype = it->second.ptype;
328 if (get_pointer_depth(cctype) != 1)
329 throw skip("invalid callback closure parameter type " + cctype);
330 // if async method, there is at least 1 async scope callback
331 // if call also supports another callback, it could in principle
332 // have any valid scope, but quite likely it has no "sane" scope,
333 // and its user_data parameter is assumed to live within the async scope
334 // so allow for this case in the sanity checks below
335 // though this case is only dealt with in regular callforward code
336 // (not in callback code)
337 if (scope.empty()) {
338 if (!async_method)
339 throw skip("callback misses scope info");
340 else if (callee)
341 throw skip(kind + "; async_dep scope not supported");
342 scope = SCOPE_ASYNC_DEP;
343 }
344 if ((scope == SCOPE_NOTIFIED) != (destroy >= 0)) {
345 if (!async_method)
346 throw skip("callback destroy info mismatch");
347 scope = SCOPE_ASYNC_DEP;
348 }
349 if (destroy >= 0) {
350 it = paraminfo.find(destroy);
351 if (it == paraminfo.end()) {
352 throw skip("callback has invalid destroynotify parameter");
353 } else {
354 auto girname = it->second.tinfo.girname;
355 // mind qualification
356 if (girname != GIR_GDESTROYNOTIFY)
357 throw skip(
358 "invalid callback destroy notify parameter type " + girname);
359 }
360 }
361 // there may be multiple callbacks, but they should not overlap
362 // so check if we already entered something for the call parameter
363 if (def.c_call.find(closure) != def.c_call.end())
364 throw skip("callback closure parameter already used");
365 if (def.c_call.find(destroy) != def.c_call.end())
366 throw skip("callback destroy parameter already used");
367
368 { // this could be callback parameter within a callback or virtual method
369 // so collect the needed parts for the argument trait
370 // (which have been validated above)
371 auto &ti = def.arg_traits[param_no];
372 ti.args = {param_no, closure};
373 if (destroy >= 0)
374 ti.args.push_back(destroy);
375 // determine custom arg trait type from type name
376 // (with suitable suffix and in internal namespace)
377 auto index = cpptype.rfind(GI_SCOPE);
378 auto insert = index != cpptype.npos ? index + GI_SCOPE.size() : 0;
379 ti.custom = cpptype;
380 ti.custom.insert(insert, GI_NS_INTERNAL + GI_SCOPE);
381 ti.custom += GI_SUFFIX_CB_TRAIT;
382 }
383
384 // declaration always the same
385 def.cpp_decl[param_no] = fmt::format("{} {}", cpptype, pname);
386 // could be nullable/optional
387 if (pinfo.nullable && defaultable) {
388 def.cpp_decl[param_no] += " = nullptr";
389 } else {
390 defaultable = false;
391 }
392
393 // some variation in handling
394 auto cbw_pname = pname + "_wrap_";
395 // pass along empty callback as NULL
396 if (scope == SCOPE_CALL) {
397 auto s = fmt::format("auto {} = {} ? unwrap (std::move ({}), "
398 "gi::scope_call) : nullptr",
399 cbw_pname, pname, pname);
400 def.pre_call.push_back(s);
401 s = fmt::format("std::unique_ptr<std::remove_pointer<decltype({})>:"
402 ":type> {}_sp ({})",
403 cbw_pname, cbw_pname, cbw_pname);
404 def.pre_call.push_back(s);
405 } else if (scope == SCOPE_NOTIFIED || scope == SCOPE_ASYNC ||
406 scope == SCOPE_ASYNC_DEP) {
407 // consider async_dep like notified but without a destroy;
408 // ownership of the wrapper (pointer) is made part of the async callback
409 auto pscope =
410 scope != SCOPE_ASYNC ? "gi::scope_notified" : "gi::scope_async";
411 def.pre_call.push_back(
412 fmt::format("auto {} = {} ? unwrap (std::move ({}), {}) : nullptr",
413 cbw_pname, pname, pname, pscope));
414 // track wrapper for potential use below
415 // (may have to take ownership of another callback wrapper)
416 const auto &ctype = pinfo.tinfo.ctype;
417 if (scope == SCOPE_ASYNC &&
418 ctype.find("AsyncReadyCallback") != ctype.npos &&
419 async_cb_wrapper.empty())
420 async_cb_wrapper = cbw_pname;
421 if (destroy >= 0) {
422 def.c_call[destroy] =
423 fmt::format("{} ? &{}->destroy : nullptr", cbw_pname, cbw_pname);
424 } else {
425 assert(scope != SCOPE_NOTIFIED);
426 if (scope == SCOPE_ASYNC_DEP && !async_cb_wrapper.empty()) {
427 // make async scope callback take ownership of this wrapper callback
428 def.pre_call.push_back(
429 fmt::format("{}->take_data ({})", async_cb_wrapper, cbw_pname));
430 }
431 }
432 } else {
433 throw skip("invalid callback scope " + scope);
434 }
435 // common part
436 def.c_call[param_no] =
437 fmt::format("{} ? &{}->wrapper : nullptr", cbw_pname, cbw_pname);
438 def.c_call[closure] = cbw_pname;
439
440 return defaultable;
441 }
442
443 // returns defaultable status
444 bool process_param_in_data(int param_no, const Parameter &pinfo,
445 const Options &options, FunctionData &def, bool defaultable)
446 {
447 auto flags = pinfo.tinfo.flags;
448 auto &pname = pinfo.name;
449 auto &&cpptype = pinfo.tinfo.cppreftype(pinfo.transfer);
450 auto &ctype = pinfo.ptype;
451 auto &transfer = pinfo.transfer;
452 auto &tinfo = pinfo.tinfo;
453 const bool callee = kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD;
454
455 typedef std::vector<std::pair<int, std::string>> callexp_t;
456 callexp_t callexps;
457 std::string callexp, cpp_decl;
458
459 logger(Log::LOG, "param_in_data {} {}", param_no, pname);
460 if (flags & TYPE_VALUE) {
461 // value types always passed simply
462 // mind g(const)pointer case (const not in normalized girtype)
463 cpp_decl = ((flags & TYPE_ENUM) ? cpptype : ctype) + " " + pname;
464 callexp = flags & TYPE_ENUM
465 ? fmt::format(GI_NS_SCOPED + "unwrap ({})", pname)
466 : pname;
467 } else if (flags & TYPE_CLASS) {
468 // otherwise have to mind ownership issues
469 if (pinfo.nullable && options.nullable != opt_nullable::PRESENT) {
470 // discard nullable
471 // NOTE: default value not possible with only forward
472 // declaration
473 callexp = "nullptr";
474 } else {
475 // preserve const signature
476 // at least, if it makes sense; full transfer on const does not
477 // (as we may have to move from it)
478 if ((is_const(ctype) && transfer == TRANSFER_NOTHING)) {
479 if (flags & TYPE_OBJECT) {
480 // side-step ref/unref, in as much as such matters
481 cpp_decl = fmt::format("const {} & {}", cpptype, pname);
482 } else {
483 cpp_decl = fmt::format("const {} {}", cpptype, pname);
484 }
485 } else {
486 cpp_decl = fmt::format("{} {}", cpptype, pname);
487 }
488 auto wpname = pname;
489 // may need to move from a boxed wrapper or string
490 bool is_string = (flags & TYPE_BASIC);
491 if ((is_string || (flags & TYPE_BOXED)) &&
492 pinfo.transfer == TRANSFER_FULL)
493 wpname = fmt::format("{}({})", MOVE, pname);
494 callexp = fmt::format(GI_NS_SCOPED + "unwrap ({}, {})", wpname,
495 get_transfer_parameter(transfer));
496 }
497 } else if (flags & TYPE_CONTAINER) {
498 auto &&cppreftype = tinfo.first.cppreftype(pinfo.transfer);
499 auto tmpvar = pname + "_w";
500 auto unwrapvar = pname + "_i";
501 std::string coltype;
502 std::string coleltype = tinfo.first.argtype;
503 if (flags & TYPE_MAP) {
504 coltype = get_list_type(tinfo);
505 coleltype = fmt::format(
506 "std::pair<{}, {}>", tinfo.first.argtype, tinfo.second.argtype);
507 } else if ((flags & TYPE_LIST) || tinfo.zeroterminated) {
508 if (flags & TYPE_LIST)
509 coltype = get_list_type(tinfo);
510 if (tinfo.zeroterminated)
511 coltype = "gi::ZTSpan";
512 } else if (tinfo.fixedsize) {
513 coltype = fmt::format("gi::FSpan<{}>", tinfo.fixedsize);
514 } else {
515 // need length parameter
516 auto len = tinfo.length;
517 auto it = len >= 0 ? paraminfo.find(len) : paraminfo.end();
518 if (it == paraminfo.end())
519 throw skip("array has invalid length parameter");
520 const bool basicvalue = (tinfo.first.flags & TYPE_BASIC) &&
521 (tinfo.first.flags & TYPE_VALUE);
522 // annotations are often wrong with low-level buffers
523 // so stick to simple interface below in that case
524 // (which also works in case of bogus in/out mixup)
525 if (!basicvalue ||
526 options.basic_container == opt_basic_container::COLLECTION) {
527 if (callee)
528 def.arg_traits[param_no].args = {param_no, len};
529 callexps.emplace_back(len, fmt::format("{}._size()", pname));
530 coltype = "gi::DSpan";
531 } else {
532 // this is an input parameter, so add const
533 // (as what will be passed is likely const)
534 cpp_decl = fmt::format("const {} * {}", cppreftype, pname);
535 // plain basic case, so essentially pass-through
536 auto &linfo = it->second;
537 callexps.emplace_back(param_no, pname);
538 def.cpp_decl[len] = linfo.tinfo.cpptype + " " + linfo.name;
539 callexps.emplace_back(len, linfo.name);
540 // mark that the alternative above is a possibility
541 do_basic_container.insert(opt_basic_container::COLLECTION);
542 }
543 }
544 if (coltype.size() && coleltype.size()) {
545 // for a regular function, enable auto-list creation/conversion
546 // which then manages ownership as a temporary during call expression
547 // but no such otherwise (neither output neither for callee input)
548 auto suffix = callee ? "" : "Parameter";
549 auto cpp_list = fmt::format("gi::Collection{}<{}, {}, {}>", suffix,
550 coltype, coleltype, get_transfer_parameter(pinfo.transfer, true));
551 cpp_decl = fmt::format("{} {}", cpp_list, pname);
552 // move needed in case of full transfer with single ownership
553 // so let's move anyways in all cases
554 unwrapvar = fmt::format("{}({})", MOVE, pname);
555 auto s = fmt::format("auto {} = unwrap ({}, {})", tmpvar, unwrapvar,
556 get_transfer_parameter(pinfo.transfer));
557 def.pre_call.push_back(s);
558 callexps.emplace_back(param_no, tmpvar);
559 } else {
560 // plain case above should have handled
561 assert(callexps.size());
562 }
563 } else {
564 throw std::logic_error("invalid flags");
565 }
566 // transfer to def
567 if (callexps.empty()) {
568 if (callexp.empty())
569 throw std::logic_error("unhandled flags");
570 callexps.emplace_back(std::move(param_no), std::move(callexp));
571 }
572 if (cpp_decl.size()) {
573 def.cpp_decl.emplace(std::move(param_no), std::move(cpp_decl));
574 // a declaration here has no defaults
575 // so no defaults further down
576 defaultable = false;
577 }
578 for (auto &&s : callexps) {
579 // use intermediate var for clarity
580 if (s.first == param_no) {
581 // sigh, our input name may actually be an expression
582 // FIXME ?? fall back to global data
583 auto varname = paraminfo[param_no].name + "_to_c";
584 def.pre_call.emplace_back(
585 fmt::format("auto {} = {}", varname, s.second));
586 def.c_call[s.first] = varname;
587 } else {
588 def.c_call[s.first] = s.second;
589 }
590 }
591 return defaultable;
592 }
593
594 bool process_param_in(int param_no, const Parameter &pinfo,
595 const Options &options, FunctionData &def, bool defaultable)
596 {
597 auto flags = pinfo.tinfo.flags;
598
599 verify_const_transfer(
600 pinfo.tinfo, pinfo.transfer, pinfo.direction, kind == EL_CALLBACK);
601 if (pinfo.instance) {
602 // check sanity
603 assert(flags & TYPE_CLASS);
604 // method is const if it can operate on a const C struct
605 const_method = const_method || is_const(pinfo.ptype);
606 def.c_call[param_no] = "gobj_()";
607 // NOTE transfer != NOTHING might be a silly case (e.g. _unref)
608 // or a useful one (such as some _merge cases)
609 defaultable = false;
610 } else if (flags & TYPE_CALLBACK) {
611 defaultable =
612 process_param_in_callback(param_no, pinfo, options, def, defaultable);
613 } else {
614 defaultable =
615 process_param_in_data(param_no, pinfo, options, def, defaultable);
616 }
617 return defaultable;
618 }
619
620 std::string get_list_type(const GeneratorBase::ArgInfo &info)
621 {
622 assert(info.flags & (TYPE_LIST | TYPE_MAP));
623 // should be in qualified GLib.listsuffix form
624 assert(info.girname.find("GLib.") == 0);
625 auto c = info.girname;
626 c.erase(c.begin() + 1, c.begin() + 5);
627 return c;
628 }
629
630 std::string make_out_type(const Parameter &pinfo)
631 {
632 const auto &info = pinfo.tinfo;
633 if (!info.flags)
634 throw skip(fmt::format("return type {} not supported", info.cpptype));
635 else if (info.flags & (TYPE_LIST | TYPE_ARRAY)) {
636 std::string listtype;
637 if (info.flags & TYPE_LIST) {
638 listtype = get_list_type(pinfo.tinfo);
639 } else if (info.zeroterminated) {
640 listtype = "gi::ZTSpan";
641 } else if (info.fixedsize) {
642 listtype = fmt::format("gi::FSpan<{}>", info.fixedsize);
643 } else {
644 listtype = "gi::DSpan";
645 }
646 return fmt::format("gi::Collection<{}, {}, {}>", listtype,
647 info.first.argtype, get_transfer_parameter(pinfo.transfer, true));
648 } else if (info.flags & TYPE_MAP) {
649 return fmt::format("gi::Collection<{}, std::pair<{}, {}>, {}>",
650 get_list_type(pinfo.tinfo), info.first.argtype, info.second.argtype,
651 get_transfer_parameter(pinfo.transfer, true));
652 } else if ((info.flags & TYPE_BOXED) && pinfo.callerallocates) {
653 // these always really have transfer full semantics;
654 // the caller has performed allocation and thus has ownership
655 return info.cppreftype(TRANSFER_FULL);
656 } else {
657 auto ret = info.cppreftype(pinfo.transfer);
658 return ret;
659 }
660 }
661
662 void process_param_out_array(int param_no, const Parameter &pinfo,
663 const Options &options, FunctionData &def)
664 {
665 auto pname = pinfo.name;
666 auto &tinfo = pinfo.tinfo;
667 auto transfer = pinfo.transfer;
668 bool inout = pinfo.direction == DIR_INOUT;
669 bool as_param = (options.output == opt_output::PARAM) || inout;
670
671 std::string exp_size;
672 int length = -1;
673 Parameter *plinfo = nullptr;
674
675 if (tinfo.fixedsize) {
676 def.cpp_decl[param_no] = fmt::format("{} {}[{}]",
677 tinfo.first.cppreftype(pinfo.transfer), pname, tinfo.fixedsize);
678 exp_size = std::to_string(tinfo.fixedsize);
679 } else {
680 // must have this (likely checked already though ...)
681 length = tinfo.length;
682 if (length < 0)
683 throw skip("array misses length info");
684 auto it = paraminfo.find(length);
685 if (it == paraminfo.end())
686 throw skip("array has invalid length parameter");
687 plinfo = &it->second;
688 auto &linfo = it->second;
689 inout |= linfo.direction == DIR_INOUT;
690 // in case of length parameter it is never treated as an output
691 // since the length is a required input
692 // so it is always in the declaration
693 def.cpp_decl[param_no] =
694 tinfo.first.cppreftype(pinfo.transfer) + " * " + pname;
695 // also handle length parameter here
696 def.cpp_decl[length] = linfo.tinfo.cpptype + " " + linfo.name;
697 exp_size = linfo.name;
698 }
699 // FIXME ?? no real examples here and semantics not entirely clear
700 // (probably a single lvalue container argument could be used here)
701 if (inout)
702 throw skip("inout array not supported");
703 // typically lots of different pointer types around (e.g. gpointer)
704 // so establish own types all the way
705 auto tname_cpp = pname + "_cpptype";
706 auto tname_cpp_def = fmt::format(
707 "typedef {} {}", tinfo.first.cppreftype(pinfo.transfer), tname_cpp);
708 auto tname_c = pname + "_ctype";
709 auto tname_c_def =
710 fmt::format("typedef traits::ctype<{}>::type {}", tname_cpp, tname_c);
711 auto outvar = (pname.size() ? pname : "_ret") + "_o";
712 auto cppouttype = make_out_type(pinfo);
713 std::string wrap_data;
714 std::string cppoutvar;
715 // some remaining restriction in callee case
716 auto check_callee_support = [this, &pinfo]() {
717 if (kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD) {
718 throw skip(kind + " " + pinfo.direction + " array not supported");
719 }
720 };
721 if (pinfo.callerallocates) {
722 if ((tinfo.first.flags & TYPE_BASIC) &&
723 (tinfo.first.flags & TYPE_VALUE)) {
724 // optimization; avoid intermediate copy below
725 // simply pass along input and done
726 def.c_call[param_no] = pname;
727 if (length >= 0)
728 def.c_call[length] = plinfo->name;
729 return;
730 }
731 check_callee_support();
732 // pretty much expected
733 if (plinfo && plinfo->direction != DIR_IN)
734 throw skip("unexpected length parameter");
735 // vexing parse parentheses
736 def.pre_call.push_back(tname_cpp_def);
737 def.pre_call.push_back(tname_c_def);
738 def.pre_call.push_back(fmt::format(
739 "detail::unique_ptr<{}> {} ((g_malloc_n({}, sizeof({}))))", tname_c,
740 outvar, exp_size, tname_c));
741 def.c_call[param_no] = fmt::format("{}.get()", outvar);
742 if (length >= 0)
743 def.c_call[length] = exp_size;
744 wrap_data = "outvar.release()";
745 // normalize transfer as we allocated above
746 if (transfer != TRANSFER_FULL)
747 transfer = TRANSFER_CONTAINER;
748 } else {
749 if (pinfo.direction != DIR_RETURN) {
750 // prepare an output parameter var
751 def.pre_call.push_back(tname_cpp_def);
752 def.pre_call.push_back(tname_c_def);
753 def.pre_call.push_back(fmt::format("{} *{}", tname_c, outvar));
754 def.c_call[param_no] = fmt::format("({}) &{}", pinfo.ptype, outvar);
755 } else {
756 check_callee_support();
757 // assign return to var
758 def.ret_format = fmt::format("auto {} = {{}}", outvar);
759 }
760 wrap_data = outvar;
761 cppoutvar = pname;
762 if (length >= 0) {
763 auto &linfo = *plinfo;
764 // in either case, lvalue container as parameter/return
765 def.cpp_decl[param_no] = fmt::format(cppouttype + " & " + cppoutvar);
766 // arranged above
767 assert(exp_size == linfo.name);
768 if (linfo.direction != DIR_IN) {
769 // no size parameter in Cpp signature, use local variable
770 def.cpp_decl.erase(length);
771 def.pre_call.push_back(
772 fmt::format("{} {}", linfo.tinfo.cpptype, linfo.name));
773 def.c_call[length] = fmt::format("&{}", linfo.name);
774 } else {
775 // use/keep input size parameter in Cpp signature
776 def.c_call[length] = exp_size;
777 }
778 // add length to callee arg trait (regardless of in/out, etc)
779 def.arg_traits[param_no].args = {param_no, length};
780 if (linfo.direction != DIR_OUT) {
781 // an additional argument is needed in Cpp signature
782 // (as the input size is/can not passed as part of array collection)
783 def.cpp_decl_extra[length] =
784 fmt::format("{} {}", linfo.tinfo.cpptype, linfo.name);
785 // if needed, use any non-void type to mark inout case
786 // (no longer passthrough, Cpp signature is plain, C signature is ptr)
787 if (linfo.direction == DIR_INOUT) {
788 auto &ti = def.arg_traits[length];
789 ti.args = {length};
790 ti.inout = true;
791 ti.custom = "bool";
792 ti.transfer = linfo.transfer;
793 }
794 // TODO however, no known cases and untested at present, so skip
795 // (if not already skipped above by inout check)
796 check_callee_support();
797 }
798 }
799 // in case return; always use container wrapper as return
800 if (pinfo.direction == DIR_RETURN || (!as_param && length >= 0)) {
801 // so no cpp parameter
802 def.cpp_decl.erase(param_no);
803 // output container is temp helper var instead
804 // make name if return value
805 if (cppoutvar.empty())
806 cppoutvar = "_temp_ret";
807 def.post_call.push_back(fmt::format("{} {}", cppouttype, cppoutvar));
808 def.cpp_outputs.push_back({cppouttype, cppoutvar});
809 }
810 }
811 if (cppoutvar.empty()) {
812 cppoutvar = pname + "_temp_wrap_";
813 def.post_call.push_back(fmt::format("{} {}", cppouttype, cppoutvar));
814 }
815 def.post_call.push_back(
816 fmt::format("{} = gi::wrap_to<{}>({}, {}, {})", cppoutvar, cppouttype,
817 wrap_data, exp_size, get_transfer_parameter(transfer)));
818 }
819
820 // returns defaultable status
821 bool process_param_out(int param_no, const Parameter &pinfo,
822 const Options &options, FunctionData &def, bool defaultable)
823 {
824 auto pname = pinfo.name;
825 auto &tinfo = pinfo.tinfo;
826 auto &ctype = pinfo.ptype;
827 int flags = tinfo.flags;
828 auto &transfer = pinfo.transfer;
829 bool inout = pinfo.direction == DIR_INOUT;
830 const bool callee = kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD;
831
832 verify_const_transfer(
833 tinfo, transfer, pinfo.direction, kind != EL_CALLBACK);
834 if (pinfo.instance)
835 throw skip("instance out");
836
837 // zero-terminated handled below
838 if ((flags & TYPE_ARRAY) && !tinfo.zeroterminated) {
839 process_param_out_array(param_no, pinfo, options, def);
840 return false;
841 }
842
843 if (pinfo.direction == DIR_RETURN) {
844 if (tinfo.cpptype == CPP_VOID) {
845 def.ret_format = "{}";
846 } else {
847 auto cpp_ret = make_out_type(pinfo);
848 auto tmpvar = "_temp_ret";
849 def.ret_format = fmt::format("auto {} = {{}}", tmpvar);
850 def.cpp_outputs.push_back({cpp_ret,
851 fmt::format(make_wrap_format(tinfo, transfer, cpp_ret), tmpvar)});
852 }
853 return false;
854 }
855
856 // inout never in output tuple
857 bool as_param = (options.output == opt_output::PARAM) || inout;
858
859 // one-to-one non-array cases
860 // this also handles list/map output with suitable pointer depth
861 auto paramtype = make_out_type(pinfo);
862 bool optional = false;
863 if (as_param) {
864 optional = pinfo.optional;
865 auto pass = pinfo.optional ? " * " : " & ";
866 // no (nullptr) default for pointer output
867 // as that leads to call ambiguity with the output tuple variant
868 // if no argument given in call
869 def.cpp_decl[param_no] = paramtype + pass + pname;
870 defaultable = false;
871 } else {
872 // FIXME ?? could consider defaultable in this case ??
873 defaultable = false;
874 }
875
876 if ((flags & TYPE_BOXED) && pinfo.callerallocates) {
877 if (callee) {
878 // parameter can actually be considered an input (pointer/wrapper)
879 // (with transfer none, as caller has ownership)
880 def.cpp_decl.erase(param_no);
881 auto tpinfo = pinfo;
882 tpinfo.direction = DIR_IN;
883 def.arg_traits[param_no].transfer = tpinfo.transfer = TRANSFER_NOTHING;
884 return process_param_in_data(
885 param_no, tpinfo, options, def, defaultable);
886 }
887 // special case; use provided output plain struct directly
888 // mimic typical call sequence; declare local struct and pass that
889 auto cvar = pname + "_c";
890 // such call is typically used for things that do not need cleanup
891 // (e.g. GstMapInfo, etc), though GValue is a popular and prominent
892 // exception
893 // in any case, this means the struct is not opaque
894 // so we have no known way to allocate or free
895 // (well, we could free a boxed GType but not allocate)
896 // so we will really leave it up to the caller
897 // and only allocate in case of a GValue or a "plain struct" case
898 // (if non-optional)
899 // (which is already tricky if custom setup/free needed after all)
900 std::string deref;
901 if (!as_param) {
902 // make pname point to a local variable
903 def.pre_call.push_back(fmt::format("{} {}", paramtype, cvar));
904 def.pre_call.push_back(fmt::format("auto {} = &{}", pname, cvar));
905 // which is then returned
906 auto output = cvar;
907 def.cpp_outputs.push_back({paramtype, output});
908 deref = "*";
909 } else if (pinfo.optional) {
910 deref = "*";
911 }
912 if (!pinfo.optional) {
913 // this should only really do something for GValue or c-boxed
914 // no deref check needed here, as it is ok in either case
915 def.pre_call.push_back(
916 fmt::format("detail::allocate({}{})", deref, pname));
917 }
918 def.pre_call.push_back(fmt::format(
919 "static_assert(sizeof({}) == sizeof(*({}{}).gobj_()), \"\")",
920 tinfo.dtype, deref, pname));
921 auto cvalue =
922 fmt::format("({}*) ({}{}).gobj_()", tinfo.dtype, deref, pname);
923 def.c_call[param_no] =
924 deref.size() ? fmt::format("{} ? {} : nullptr", pname, cvalue)
925 : cvalue;
926 // no additional post-call
927 // (already done above in case of return value)
928 return defaultable;
929 }
930
931 // otherwise use a temp variable and then wrap that one
932 auto outvar = pname + "_o";
933 // adjust arginfo for wrapping
934 auto opinfo = pinfo;
935 auto &otinfo = opinfo.tinfo;
936 if (ctype[ctype.size() - 1] != GI_PTR)
937 throw skip(pname + "; inconsistent pointer type");
938 // adjust type
939 opinfo.ptype = ctype.substr(0, ctype.size() - 1);
940
941 // optionally init the temp variable using input (if such)
942 std::string init(" {}");
943 if (inout && as_param) {
944 // operate on a temporary definition
945 // only need to re-use transformation of input to call expression
946 auto tdef = def;
947 tdef.pre_call.clear();
948 // optionally tweak the input expression (type adjusted above)
949 if (optional)
950 opinfo.name.insert(0, "*");
951 process_param_in_data(param_no, opinfo, options, tdef, defaultable);
952 // be nice, include requested code
953 for (auto &&p : tdef.pre_call)
954 def.pre_call.emplace_back(p);
955 // rest we handle here
956 init = fmt::format(" = {}", tdef.c_call[param_no]);
957 }
958
959 // always same precall, but slight variation for pointer/ref
960 def.pre_call.push_back(opinfo.ptype + " " + outvar + init);
961 auto call = std::string("&") + outvar;
962 def.c_call[param_no] =
963 optional ? fmt::format("{} ? {} : nullptr", pname, call) : call;
964 auto wrapf =
965 fmt::format(make_wrap_format(otinfo, transfer, paramtype), outvar);
966 // assign post call or return
967 if (as_param) {
968 auto guard = optional ? fmt::format("if ({}) ", pname) : EMPTY;
969 auto deref = optional ? "*" : "";
970 def.post_call.push_back(
971 fmt::format("{}{}{} = {}", guard, deref, pname, wrapf));
972 } else {
973 def.cpp_outputs.push_back({paramtype, wrapf});
974 }
975 return defaultable;
976 }
977
978 // process info to construct function
979 // returns defaultable status
980 bool process_param(int param_no, const Parameter &pinfo,
981 const Options &options, FunctionData &def, bool defaultable)
982 {
983 auto &tinfo = pinfo.tinfo;
984 auto ctype = tinfo.ctype;
985 int flags = tinfo.flags;
986
987 // check type first, so we do not raise any complaints on unknown type
988 if (!flags)
989 throw skip(
990 fmt::format("{} type {} not supported", pinfo.name, tinfo.cpptype),
991 skip::OK);
992 // sanity check on pointer depth to verify annotation
993 // array annotation or out parameter is frequently missing
994 auto argdepth = std::count(pinfo.ptype.begin(), pinfo.ptype.end(), GI_PTR);
995 auto rpdepth = get_pointer_depth(pinfo.tinfo.ctype);
996 if ((kind != EL_SIGNAL) && (argdepth != rpdepth)) {
997 // this might happen for an input array of C-boxed structs
998 // (rather than the expected array of pointers to something-boxed)
999 if ((pinfo.tinfo.flags & TYPE_CONTAINER) &&
1000 (pinfo.tinfo.first.flags & TYPE_BOXED))
1001 throw skip(fmt::format("{} {} boxed array not supported (depth {})",
1002 pinfo.name, pinfo.direction, rpdepth));
1003 throw skip(fmt::format("inconsistent {} {} pointer depth ({} vs {})",
1004 pinfo.name, pinfo.direction, rpdepth, argdepth));
1005 }
1006
1007 // perhaps this param is part of another's one (e.g. callback)
1008 // processing various checks to bail out early
1009 if (def.c_call.find(param_no) != def.c_call.end()) {
1010 logger(Log::LOG, "call fragment for parameter {} already specified",
1011 param_no);
1012 return false;
1013 } else if (((kind != EL_CALLBACK && kind != EL_SIGNAL) ||
1014 (pinfo.closure < 0)) &&
1015 referenced.count(param_no)) {
1016 /* managing parameter might come later, so skip this one for now
1017 * if a call has to be emitted
1018 * (also; user_data closure in callback can reference itself,
1019 * and that has to be discovered below
1020 * userdata parameter also has to be processed below in callback case
1021 * (to insert proper callexp)
1022 */
1023 logger(Log::LOG, "parameter {} referenced elsewhere", param_no);
1024 return false;
1025 }
1026 // on with it now
1027 // standard transfer, can be overridden
1028 if (!pinfo.instance)
1029 def.arg_traits[param_no] = {
1030 pinfo.transfer, pinfo.direction == DIR_INOUT, {param_no}};
1031 if (pinfo.direction != DIR_IN) {
1032 // (in)out or return
1033 defaultable =
1034 process_param_out(param_no, pinfo, options, def, defaultable);
1035 } else {
1036 defaultable =
1037 process_param_in(param_no, pinfo, options, def, defaultable);
1038 // handle callback user_data
1039 if (kind == EL_CALLBACK) {
1040 if (pinfo.closure >= 0) {
1041 if (pinfo.closure != param_no)
1042 throw skip("invalid closure user_data");
1043 if (ctype != "gpointer")
1044 throw skip("invalid type user_data");
1045 if (found_user_data >= 0)
1046 throw skip("duplicate user_data");
1047 found_user_data = param_no;
1048 // user_data not included in signature (nor transfer)
1049 def.cpp_decl.erase(param_no);
1050 def.arg_traits.erase(param_no);
1051 }
1052 }
1053 }
1054
1055 return defaultable;
1056 }
1057
1058 std::string join_outputs(
1059 const std::vector<FunctionDefinition::Output> &outputs,
1060 std::string FunctionDefinition::Output::*m,
1061 std::string (*transform)(std::string) = nullptr)
1062 {
1063 std::vector<std::string> temp;
1064 for (auto &&o : outputs)
1065 temp.emplace_back(transform ? transform(o.*m) : o.*m);
1066 return boost::algorithm::join(temp, ", ");
1067 }
1068
1069 struct DeclData
1070 {
1071 std::string cpptype;
1072 std::string varname;
1073 bool is_ref{};
1074 bool has_init{};
1075 };
1076
1077 auto parse_var_name(const std::string &decl)
1078 {
1079 std::string name;
1080 bool is_ref = false;
1081 bool has_init = false;
1082 const char *last = nullptr;
1083 const char *start = nullptr;
1084 for (auto it = decl.rbegin(); it != decl.rend(); ++it) {
1085 if (*it == '=') {
1086 name.clear();
1087 has_init = true;
1088 last = nullptr;
1089 continue;
1090 }
1091 if (isspace(*it) && !last)
1092 continue;
1093 if (!isalnum(*it) && *it != '_' && name.empty()) {
1094 if (it == decl.rbegin()) {
1095 // weird format ?!
1096 throw skip(
1097 fmt::format("unexpected declaration {}", decl), skip::TODO);
1098 break;
1099 }
1100 start = &*it + 1;
1101 name = decl.substr(start - decl.data(), last - start + 1);
1102 } else if (!last) {
1103 last = &*it;
1104 }
1105 if (*it == '&') {
1106 is_ref = true;
1107 }
1108 }
1109 // see definition above
1110 assert(start > decl.data());
1111 --start;
1112 while (isspace(*start) && start > decl.data())
1113 --start;
1114 auto cpptype = start ? decl.substr(0, start - decl.data() + 1) : "";
1115 return std::tuple{cpptype, name.size() ? name : decl, is_ref, has_init};
1116 }
1117
1118 struct CallArgsData
1119 {
1120 std::string cpp_type_name;
1121 std::string cpp_decl;
1122 std::string cpp_call;
1123 };
1124
1125 CallArgsData make_function_call_args(const Options &options,
1126 const FunctionDataExtended &def, const std::string &fname)
1127 {
1128 CallArgsData result;
1129
1130 auto struct_name = klasstype + (klasstype.size() ? "_" : "") +
1131 unreserve(fname) + "_CallArgs";
1132 // different options lead to different signature, so needs different type
1133 std::vector<std::string> tags;
1134 if (options.output != opt_output::PARAM) {
1135 struct_name += "In";
1136 tags.push_back("gi::ca_in_tag");
1137 }
1138 if (options.basic_container != opt_basic_container::DEFAULT) {
1139 struct_name += "BC";
1140 tags.push_back("gi::ca_bc_tag");
1141 }
1142 // in case of a variant, use a first argument tag type to allow unambiguous
1143 // use of designated initializer syntax in call
1144 if (!tags.empty())
1145 result.cpp_decl =
1146 fmt::format("gi::ca<{}>, ", boost::algorithm::join(tags, ","));
1147
1148 // let's make it
1149 std::ostringstream argtype;
1150 argtype << "struct " << struct_name << " { " << std::endl;
1151
1152 std::vector<std::string> varnames;
1153 const std::string argname = "args";
1154 int count = 0;
1155 int optional = 0;
1156 // at least this much is needed in function signature
1157 // given the type name, a name clash is unlikely
1158 // but place into args sub-namespace, also for sake of convenience/clarity
1159 result.cpp_decl +=
1160 fmt::format("{}{}{} {}", GI_NS_ARGS, GI_SCOPE, struct_name, argname);
1161 // collect declarations
1162 for (const auto &e : def.cpp_decl) {
1163 // skip error, maintained as separate parameter
1164 auto [cpptype, varname, is_ref, has_init] = parse_var_name(e.second);
1165 if (e.first != INDEX_ERROR) {
1166 ++count;
1167 auto member = e.second;
1168 // ref is already required
1169 // if it has init, already optional
1170 optional += !!has_init;
1171 if (!is_ref && !has_init) {
1172 // lookup type
1173 auto it = paraminfo.find(e.first);
1174 if (it == paraminfo.end()) {
1175 // should not happen, where does it come from then
1176 throw skip("unexpected parameter", skip::TODO);
1177 }
1178 auto &pinfo = it->second;
1179 if (pinfo.nullable || pinfo.optional) {
1180 ++optional;
1181 // arrange init
1182 // callback does not allow (accidental) default construction
1183 member += (pinfo.tinfo.flags & TYPE_CALLBACK) ? "{nullptr}" : "{}";
1184 } else {
1185 member = fmt::format("gi::required<{}> {}", cpptype, varname);
1186 }
1187 }
1188 argtype << indent << member << ";" << std::endl;
1189 varname.insert(0, argname + '.');
1190 // mind move-only owning types, so move all non-refs
1191 if (!is_ref)
1192 varname = fmt::format("{}({})", MOVE, varname);
1193 } else {
1194 result.cpp_decl += ", " + e.second;
1195 }
1196 varnames.push_back(varname);
1197 }
1198 argtype << "};";
1199
1200 // only really create if needed
1201 // perhaps no input, only output arguments, or depending on options
1202 if (!count || ctx.options.call_args < 0 ||
1203 optional < ctx.options.call_args || !call_args_decl)
1204 return result;
1205
1206 // ok, makes sense, finish up
1207 result.cpp_type_name = struct_name;
1208 result.cpp_call = boost::algorithm::join(varnames, ", ");
1209
1210 // could have seen this type before, in another signature variation
1211 // NOTE the other parts could be different this time though
1212 auto [_, inserted] = call_args_types.insert(struct_name);
1213 if (inserted)
1214 *call_args_decl << argtype.str() << std::endl << std::endl;
1215
1216 return result;
1217 }
1218
1219 void make_function(const Options &options, const FunctionDataExtended &def,
1220 const std::string &fname, bool use_call_args = false)
1221 {
1222 auto &name = func.name;
1223 // determine return type
1224 std::string cpp_ret(CPP_VOID);
1225 if (def.cpp_outputs.size() == 1) {
1226 cpp_ret = def.cpp_outputs[0].type;
1227 } else if (def.cpp_outputs.size() > 1) {
1228 cpp_ret = fmt::format(
1229 "std::tuple<{}>", join_outputs(def.cpp_outputs, &Output::type));
1230 }
1231 if (options.except == opt_except::EXPECTED) {
1232 cpp_ret = fmt::format("gi::result<{}>", cpp_ret);
1233 }
1234 const auto &cpp_decl = def.cpp_decl_unfolded;
1235 // generate based on type
1236 if (kind == EL_SIGNAL) {
1237 auto decl_name = name;
1238 // always include instance in signature
1239 auto cpp_decls = cpp_decl;
1240 cpp_decls.insert(cpp_decls.begin(), qualify(klasstype, TYPE_OBJECT));
1241 // the function type specified as gi::signal_proxy template parameter
1242 // serves 2 purposes;
1243 // + provide a compile-time type check
1244 // + select each parameter's corresponding GValue GType
1245 // (according to the association defined in gi/value.hpp)
1246 // so we should make sure to pick the proper type, especially for the
1247 // latter item, as e.g. gint64 may simply be a long
1248 // (which would not map to a G_TYPE_INT64)
1249 auto normalize = [](std::string &subject, const std::string &in,
1250 const std::string &sub) {
1251 if (subject.find(in) == 0 &&
1252 (subject.size() == in.size() || subject[in.size()] == ' ')) {
1253 subject.replace(subject.begin(), subject.begin() + in.size(), sub);
1254 }
1255 };
1256 for (auto &decl : cpp_decls) {
1257 normalize(decl, "gint64", "long long");
1258 normalize(decl, "guint64", "unsigned long long");
1259 }
1260 // convert signal name to valid identifier
1261 std::replace(decl_name.begin(), decl_name.end(), '-', '_');
1262 auto ret = fmt::format("gi::signal_proxy<{}({})>", cpp_ret,
1263 boost::algorithm::join(cpp_decls, ", "));
1264 oss_decl << fmt::format(
1265 "{0} signal_{1}()\n{{ return {0} (*this, \"{2}\"); }}",
1266 ret, decl_name, name)
1267 << std::endl;
1268 } else {
1269 // internal namespace for callforward helper parts to avoid clutter
1270 NamespaceGuard nsg_decl(oss_decl);
1271 NamespaceGuard nsg_impl(oss_impl);
1272 if (kind == EL_CALLBACK) {
1273 nsg_decl.push(GI_NS_INTERNAL, false);
1274 nsg_impl.push(GI_NS_INTERNAL, false);
1275 }
1276 const char *CB_SUFFIX = "_CF";
1277 CallArgsData ca_data;
1278 if (use_call_args) {
1279 try {
1280 // always use original function name, not a shadow/renamed one
1281 // otherwise different function (signatures) define same typename
1282 ca_data = make_function_call_args(options, def, func.name);
1283 } catch (const skip &exc) {
1284 auto msg = fmt::format("fname CallArgs failed; {}", exc.what());
1285 logger(Log::WARNING, msg);
1286 oss_decl << "// " << msg << std::endl;
1287 }
1288 // bail out if not really applicable
1289 if (ca_data.cpp_type_name.empty())
1290 return;
1291 // arrange forward declare
1292 deps.insert(
1293 {GI_NS_ARGS, std::string("struct ") + ca_data.cpp_type_name});
1294 }
1295 bool vm = kind == EL_VIRTUAL_METHOD;
1296 auto rfname = unreserve(fname, vm);
1297 auto make_sig = [&](bool impl) {
1298 auto funcsuffix = kind == EL_CALLBACK ? CB_SUFFIX : "";
1299 auto prefix =
1300 impl
1301 ? EMPTY
1302 : (vm ? "virtual "
1303 : ((kind != EL_METHOD) && klass.size() ? "static " : ""));
1304 auto klprefix = klass.size() && impl ? klass + "::" : "";
1305 auto pure = (vm && !impl ? " = 0" : "");
1306 if (!impl)
1307 prefix += GI_INLINE + ' ';
1308 // virtual method might throw in addition to error parameter
1309 auto sig =
1310 prefix +
1311 fmt::format("{} {}{}{} ({}){}{}{}", cpp_ret, klprefix, rfname,
1312 funcsuffix,
1313 use_call_args ? ca_data.cpp_decl
1314 : boost::algorithm::join(cpp_decl, ", "),
1315 (const_method ? " const" : ""),
1316 (((options.except == opt_except::THROW) || (vm && func.throws))
1317 ? ""
1318 : " noexcept"),
1319 pure);
1320 // remove default values in definition
1321 static const std::regex re_defaultv(" =[^,)]*", std::regex::optimize);
1322 return impl ? std::regex_replace(sig, re_defaultv, "") : sig;
1323 };
1324 if (!def.cf_ctype.empty())
1325 oss_decl << def.cf_ctype << ';' << std::endl;
1326 oss_decl << make_sig(false) << ";" << std::endl;
1327 oss_impl << make_sig(true) << std::endl;
1328 // in CallArgs case, simply forward to existing standard function
1329 if (use_call_args) {
1330 // no ADL occurs for a method, which finds a declaration in a class
1331 // but for functions, it might find a similar method in another ns
1332 // (depending on the arguments involved)
1333 // mind static functions
1334 if (klasstype.empty() && kind == EL_FUNCTION)
1335 rfname.insert(0, ns + GI_SCOPE);
1336 oss_impl << "{ return " << rfname << " (" << ca_data.cpp_call << "); }"
1337 << std::endl
1338 << std::endl;
1339 return;
1340 }
1341 // transform to list for joining
1342 std::vector<std::string> temp;
1343 for (auto &&e : def.c_call)
1344 temp.emplace_back(e.second);
1345 auto call = fmt::format(
1346 "{} ({})", def.c_callee, boost::algorithm::join(temp, ", "));
1347 call = fmt::format(def.ret_format, call);
1348 std::vector<std::string> pre_return;
1349 std::string returns;
1350 if (def.cpp_outputs.size() == 1) {
1351 // avoid -Wpessimizing-move on std::move(x)
1352 // so pass along as-is
1353 auto &ret = def.cpp_outputs[0].value;
1354 returns = fmt::format("return {};", ret);
1355 } else if (def.cpp_outputs.size() > 1) {
1356 // wrap in a move()
1357 // may be needed for move-only types in temp variables
1358 // however, again avoid -Wpessimizing-move
1359 // (in case of moving from an expression/temporary)
1360 // so assign to an intermediate ref and move from that
1361 // (and should not hurt in other cases)
1362 // auto moved_outputs = def.cpp_outputs;
1363 static const std::string tmp_prefix = "tmp_return_";
1364 int count = 0;
1365 std::vector<std::string> outputs;
1366 for (auto &e : def.cpp_outputs) {
1367 pre_return.push_back(
1368 fmt::format("auto &&{}{} = {}", tmp_prefix, ++count, e.value));
1369 outputs.push_back(fmt::format("{}({}{})", MOVE, tmp_prefix, count));
1370 }
1371 returns = fmt::format("return std::make_tuple ({});",
1372 boost::algorithm::join(outputs, ","));
1373 }
1374 if (options.except == opt_except::EXPECTED && returns.empty()) {
1375 // expected<void> is no longer void, so needs explicit return
1376 returns = "return {};";
1377 }
1378 oss_impl << "{" << std::endl;
1379 // prevent calling NULL in case of vmethod
1380 // (i.e. Subclass::method != Superclass::method)
1381 if (kind == EL_VIRTUAL_METHOD) {
1382 // FIXME in the new approach the class/interface struct entry
1383 // is only filled if really needed, so it preserves the superclass
1384 // (unless needed) whether that is NULL or otherwise.
1385 // In particular, this fallback implementation should not get called
1386 // (which we could enforce if the new approach becomes the only one).
1387 // It might still get explicitly called, but then it should first be
1388 // checked whether the struct entry is non-NULL (as typically done
1389 // by C code). So, even in that case, we should not hit the situation
1390 // below that is forced to return some default value
1391 // (and that could also be enforced in future).
1392 // So, eventually, the nasty default return should not apply at runtime.
1393 // Until then, hoping for the best
1394 // (though *mm does no better here) ...
1395 // Log a fairly serious warning, as such should such no longer happen
1396 // (in the auto-detected or manual specification approach).
1397 auto retexp = fmt::format(
1398 "{{ g_critical (\"no method in class struct\"); return {}; }}",
1399 cpp_ret == CPP_VOID ? EMPTY : "{}");
1400 retexp = fmt::format("if (!{}) {}", func.functionexp, retexp);
1401 oss_impl << indent << retexp << std::endl;
1402 }
1403 for (const auto &p : def.pre_call)
1404 oss_impl << indent << p << ';' << std::endl;
1405 oss_impl << indent << call << ';' << std::endl;
1406 for (const auto &p : def.post_call)
1407 oss_impl << indent << p << ';' << std::endl;
1408 for (const auto &p : pre_return)
1409 oss_impl << indent << p << ';' << std::endl;
1410 if (returns.size())
1411 oss_impl << indent << returns << std::endl;
1412 oss_impl << "}" << std::endl;
1413 // generate helper trait type when used as argument in another callback
1414 if (kind == EL_CALLBACK) {
1415 auto base = unreserve(fname);
1416 oss_decl << fmt::format("GI_CB_ARG_CALLBACK_CUSTOM({}, {}, {});",
1417 base + GI_SUFFIX_CB_TRAIT, base + GI_SUFFIX_CF_CTYPE,
1418 base + CB_SUFFIX)
1419 << std::endl;
1420 }
1421 }
1422 if (kind == EL_CALLBACK) { // callback
1423 // NOTE limited container support at present
1424 // argument trait/transfers; return type to start with
1425 auto transfers = make_arg_traits(def.arg_traits, def.c_sig);
1426 // discard expected trailing callforward parameters in regular declaration
1427 // (return value also specified in transfers)
1428 assert(def.arg_traits.size() + (2 - 1) == cpp_decl.size());
1429 auto cpp_decls = boost::make_iterator_range(
1430 cpp_decl.begin(), cpp_decl.begin() + def.arg_traits.size() - 1);
1431 oss_decl << fmt::format("typedef {}callback<{}({}), {}> {}",
1432 GI_NS_DETAIL_SCOPED, cpp_ret,
1433 boost::algorithm::join(cpp_decls, ", "), transfers,
1434 unreserve(name))
1435 << ";" << std::endl;
1436 }
1437 }
1438
1439 FunctionDefinition process()
1440 {
1441 auto &name = func.name;
1442
1443 const bool callee = kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD;
1444 // pass over parameters to collect info to assemble signature
1445 struct signature
1446 {
1447 std::string c_ret;
1448 std::vector<std::string> c_decl;
1449 };
1450 signature sig_ctype, sig_ptype;
1451 // as above, but now each entry contains a comment annotation
1452 signature annotations;
1453 std::map<int, int> array_sizes;
1454
1455 // collect flags into a comment to append to parameter name in declaration
1456 auto annotate_parameter = [](const FunctionParameter &p) -> std::string {
1457 if ((p.tinfo.flags & TYPE_VALUE) || p.tinfo.cpptype == CPP_VOID)
1458 return {};
1459 auto dir = (p.direction.find(DIR_OUT) != p.direction.npos)
1460 ? fmt::format(",{}", p.direction)
1461 : "";
1462 return fmt::format(" /*{}{}{}{}{}*/", p.transfer, dir,
1463 p.optional ? ",opt" : "", p.nullable ? ",nullable" : "",
1464 p.callerallocates ? ",ca" : "");
1465 };
1466
1467 int callbacks = 0;
1468 Parameter *callback = nullptr;
1469 for (auto &p : paraminfo) {
1470 try {
1471 auto &pinfo = p.second;
1472 assert(pinfo.name.size() || pinfo.direction == DIR_RETURN);
1473 assert((pinfo.direction == DIR_RETURN) == (p.first == INDEX_RETURN));
1474 assert(pinfo.transfer.size());
1475 assert(pinfo.direction.size());
1476 auto annotation = annotate_parameter(pinfo);
1477 // c signature
1478 if (p.first == INDEX_RETURN) {
1479 sig_ctype.c_ret = pinfo.tinfo.ctype;
1480 annotations.c_ret = annotation;
1481 } else {
1482 sig_ctype.c_decl.push_back(pinfo.tinfo.ctype + " " + pinfo.name);
1483 annotations.c_decl.push_back(annotation);
1484 }
1485 auto flags = pinfo.tinfo.flags;
1486 // also sanity checks
1487 if (pinfo.direction == DIR_RETURN) {
1488 // NOTE no more check on none return needed
1489 // as return type adequately specifies this situation (e.g. cstring_v)
1490 // and usual caution wrt return "temporary string" then apply
1491 // (and floating return is handled by callback wrapping code)
1492 // NOTE constructor return transfer is often marked none = floating
1493 // so that needs a ref_sink (which wrap() will arrange)
1494 } else {
1495 // overall checks
1496 bool function_type = false;
1497 if (callee || kind == EL_SIGNAL) {
1498 function_type = true;
1499 // no defaults in signatures
1500 pinfo.nullable = false;
1501 pinfo.optional = false;
1502 }
1503 if (kind == EL_SIGNAL) {
1504 // a signal is handled much like a callback,
1505 // so more complex cases need argument trait info (like callback)
1506 // but that needs more changes in gi support code
1507 if (pinfo.direction != DIR_IN && !(flags & TYPE_BASIC))
1508 throw skip(
1509 kind + ' ' + pinfo.direction + " parameter not supported");
1510 if ((flags & TYPE_ARRAY) && !pinfo.tinfo.zeroterminated)
1511 throw skip(kind + ' ' + pinfo.direction +
1512 " array parameter not supported");
1513 }
1514 // trigger additional applicable overload generation
1515 if (!function_type) {
1516 if (pinfo.direction == DIR_OUT)
1517 do_output.insert(opt_output::ALT);
1518 if ((flags & TYPE_CLASS) && pinfo.nullable &&
1519 pinfo.direction == DIR_IN)
1520 do_nullable.insert(opt_nullable::ALT);
1521 }
1522 }
1523 // no known cases, but check anyway
1524 if ((pinfo.direction != DIR_IN) && (flags & TYPE_CALLBACK))
1525 throw skip(kind + " " + pinfo.direction +
1526 " callback parameter not supported");
1527 track_dependency(deps, pinfo.tinfo);
1528 // in case of a callback type definition,
1529 // closure on userdata refers to itself (to identify callback userdata)
1530 // otherwise, closure attribute should only be on callback argument,
1531 // but is sometimes also on user_data referring back to callback
1532 // remove the latter circular reference
1533 if (!(flags & TYPE_CALLBACK) && pinfo.closure != p.first)
1534 pinfo.closure = INDEX_DEFAULT;
1535 // collect parameters that are referenced from elsewhere
1536 // and as such managed elsewhere
1537 for (auto p : {&pinfo.closure, &pinfo.destroy, &pinfo.tinfo.length})
1538 if (*p >= 0)
1539 referenced.insert(*p);
1540 array_sizes[pinfo.tinfo.length] = p.first;
1541 // check if (single) callback parameter
1542 if (flags & TYPE_CALLBACK) {
1543 ++callbacks;
1544 if (pinfo.closure < 0)
1545 callback = &pinfo;
1546 }
1547 } catch (skip &ex) {
1548 handle_skip(ex);
1549 }
1550 }
1551
1552 // userdata parameter may not be properly annotated
1553 // (especially for functions considered not introspectable)
1554 // so, in case of only 1 callback parameter, try to guess userdata
1555 // (see also issue #85;
1556 // only limited cases so far, e.g. g_bytes_new_with_free_func)
1557 // as there is no way to guess the annotated scope,
1558 // we either have to hope that at least that one is properly annotated,
1559 // or alternatively let's only guess in specific circumstances
1560 if (callbacks == 1 && callback &&
1561 callback->tinfo.girname == GIR_GDESTROYNOTIFY &&
1562 callback->scope == SCOPE_ASYNC) {
1563 auto &e = *paraminfo.rbegin();
1564 // check last parameter
1565 auto &pinfo = e.second;
1566 if ((pinfo.name == "data" || ends_with(pinfo.name, "_data")) &&
1567 (pinfo.tinfo.girname == "gpointer")) {
1568 // assign as userdata to single callback
1569 callback->closure = e.first;
1570 // callback->
1571 referenced.insert(e.first);
1572 logger(Log::DEBUG, "{}; guessed {} userdata parameter {}", func.c_id,
1573 callback->name, pinfo.name);
1574 }
1575 }
1576
1577 // track if func has non-void return
1578 bool has_return = false;
1579 // another pass to determine expected normalized parameter type
1580 // unfortunately some array length size parameters share annotation
1581 // with the array, so a caller-allocates out array lead to wrong ptr
1582 // depth (if not compensated for that)
1583 for (auto &p : paraminfo) {
1584 try {
1585 auto &pinfo = p.second;
1586 // special case; out array length is not so consistent
1587 // always marked as out (even when passed no-ptr)
1588 // even when out, then caller-allocates is reversed from a
1589 // regular out int
1590 if (pinfo.direction == DIR_OUT) {
1591 auto it = array_sizes.find(p.first);
1592 if (it != array_sizes.end()) {
1593 // normalize based on declaration
1594 pinfo.direction =
1595 get_pointer_depth(pinfo.tinfo.ctype) > 0 ? DIR_OUT : DIR_IN;
1596 // make sure we end up with ptr
1597 if (pinfo.direction == DIR_OUT)
1598 pinfo.callerallocates = false;
1599 }
1600 }
1601 pinfo.ptype =
1602 make_ctype(pinfo.tinfo, pinfo.direction, pinfo.callerallocates);
1603 // collect deduced signature
1604 if (p.first == INDEX_RETURN) {
1605 has_return = pinfo.tinfo.cpptype != CPP_VOID;
1606 sig_ptype.c_ret = pinfo.ptype;
1607 } else {
1608 sig_ptype.c_decl.push_back(pinfo.ptype + " " + pinfo.name);
1609 }
1610 } catch (skip &ex) {
1611 handle_skip(ex);
1612 }
1613 }
1614
1615 // could affect declaration signature
1616 if (func.throws) {
1617 // fixed signature
1618 sig_ctype.c_decl.push_back("GError ** error");
1619 sig_ptype.c_decl.push_back("GError ** error");
1620 // stay in sync with parameters, even if empty
1621 annotations.c_decl.push_back({});
1622 do_except = {opt_except::GERROR};
1623 if (!callee)
1624 do_except.insert(
1625 ctx.options.expected ? opt_except::EXPECTED : opt_except::THROW);
1626 } else if (ctx.options.dl && func.lib_symbol) {
1627 do_except = {
1628 ctx.options.expected ? opt_except::EXPECTED : opt_except::THROW};
1629 }
1630
1631 // we collected enough info so far to reconstruct original declaration
1632 auto make_declaration = [&](bool def, const std::string name,
1633 const signature &sig,
1634 const signature *append = nullptr) {
1635 auto c_sig_fmt = !def ? "{} {} ({})" : "typedef {} (*{}) ({})";
1636 const signature *actual = &sig;
1637 signature combined;
1638 if (append && sig.c_decl.size() == append->c_decl.size()) {
1639 combined.c_ret = sig.c_ret + append->c_ret;
1640 for (std::size_t i = 0; i < sig.c_decl.size(); ++i)
1641 combined.c_decl.push_back(sig.c_decl[i] + append->c_decl[i]);
1642 actual = &combined;
1643 }
1644 return fmt::format(c_sig_fmt, actual->c_ret, name,
1645 boost::algorithm::join(actual->c_decl, ", "));
1646 };
1647
1648 { // dump original/derived declarations
1649 bool is_signal = kind == EL_SIGNAL;
1650 const char *prefix = is_signal ? "(signal) " : "";
1651 // dump both parsed and derived
1652 for (auto &sig : {sig_ctype, sig_ptype}) {
1653 auto c_sig =
1654 make_declaration(kind == EL_CALLBACK, func.c_id, sig, &annotations);
1655 oss_decl << "// " << prefix << c_sig << ";" << std::endl;
1656 if (!is_signal)
1657 oss_impl << "// " << c_sig << ";" << std::endl;
1658 }
1659 }
1660
1661 // name for error return parameter
1662 const static std::string ERROR_PARAM = "_error";
1663
1664 auto make_definition = [&](Options options, bool fallback = false) {
1665 logger(Log::LOG, "generating {} with except {}, output {}, nullable {}",
1666 func.c_id, (int)options.except, (int)options.output,
1667 (int)options.nullable);
1668 FunctionDefinition def;
1669 def.c_callee = func.functionexp;
1670 if (callee) {
1671 auto c_sig = sig_ptype;
1672 // instance parameter should not be included
1673 if (kind == EL_VIRTUAL_METHOD) {
1674 assert(!c_sig.c_decl.empty());
1675 c_sig.c_decl.erase(c_sig.c_decl.begin());
1676 }
1677 def.c_sig = make_declaration(false, "", c_sig, nullptr);
1678 }
1679
1680 if (fallback) {
1681 sig_ctype = signature{};
1682 logger(Log::INFO, "method {} creating fallback", name);
1683 // generate virtual method with original C signature as-is
1684 // however, do qualify/scope type names to avoid mixup with ns etc
1685 auto ctype = [](const FunctionParameter &pinfo) {
1686 if (pinfo.ptype.find(GI_SCOPE) == 0)
1687 return GI_SCOPE + pinfo.tinfo.ctype;
1688 return pinfo.tinfo.ctype;
1689 };
1690 for (const auto &p : paraminfo) {
1691 auto &pinfo = p.second;
1692 track_dependency(deps, pinfo.tinfo);
1693 if (pinfo.instance) {
1694 sig_ctype.c_decl.push_back(ctype(pinfo));
1695 def.c_call[p.first] = "gobj_()";
1696 } else if (pinfo.direction == DIR_RETURN) {
1697 sig_ctype.c_ret = ctype(pinfo);
1698 if (pinfo.tinfo.cpptype == CPP_VOID) {
1699 def.ret_format = "{}";
1700 } else {
1701 // assign return to var
1702 auto outvar = "result_";
1703 def.ret_format = fmt::format("auto {} = {{}}", outvar);
1704 def.cpp_outputs.push_back({ctype(pinfo), outvar});
1705 }
1706 } else {
1707 sig_ctype.c_decl.push_back(ctype(pinfo));
1708 def.cpp_decl[p.first] = ctype(pinfo) + " " + pinfo.name;
1709 def.c_call[p.first] = pinfo.name;
1710 }
1711 }
1712 // also consider optional GError
1713 if (func.throws) {
1714 const int LAST = INDEX_ERROR;
1715 const std::string evar = "error_";
1716 auto &p = def.cpp_decl[LAST] = "::GError **" + evar;
1717 def.c_call[LAST] = evar;
1718 sig_ctype.c_decl.push_back(p);
1719 }
1720 // commit/specify that a method def was made
1721 def.name = name;
1722 }
1723
1724 // arrange for dynamic load if so requested
1725 std::string symbol_name;
1726 if (ctx.options.dl && func.lib_symbol) {
1727 symbol_name = "_symbol_name";
1728 def.pre_call.push_back(
1729 fmt::format("const char *{} = \"{}\"", symbol_name, def.c_callee));
1730 def.c_callee = fmt::format(
1731 "detail::load_symbol(internal::_libs(), {})", symbol_name);
1732 }
1733
1734 if (kind != EL_CALLBACK) {
1735 // enforce deduced function signature by cast
1736 // i.e. type cast to deduced function type
1737 static const std::string call_wrap_t = "call_wrap_t";
1738 static const std::string call_wrap_v = "call_wrap_v";
1739 def.pre_call.push_back(make_declaration(
1740 true, call_wrap_t, fallback ? sig_ctype : sig_ptype));
1741 def.pre_call.push_back(fmt::format("{} {} = ({}) {}", call_wrap_t,
1742 call_wrap_v, call_wrap_t, def.c_callee));
1743 def.c_callee = call_wrap_v;
1744 if (symbol_name.size()) {
1745 std::string check_exp;
1746 if (options.except == opt_except::EXPECTED) {
1747 check_exp =
1748 fmt::format("if (!{}) "
1749 "return gi::detail::make_unexpected(gi::detail::"
1750 "missing_symbol_error({}))",
1751 call_wrap_v, symbol_name);
1752 } else if (options.except == opt_except::THROW) {
1753 check_exp = fmt::format(
1754 "if (!{}) "
1755 "gi::detail::try_throw(gi::detail::missing_symbol_error({}))",
1756 call_wrap_v, symbol_name);
1757 } else if (options.except == opt_except::GERROR) {
1758 // this could potentially cover up quite some error
1759 // (in case of null error parameter, but so be it ...)
1760 check_exp = fmt::format(
1761 "if (!{0}) {{"
1762 "if ({2}) *{2} = gi::detail::missing_symbol_error({1}); "
1763 "return {3}; "
1764 "}}",
1765 call_wrap_v, symbol_name, ERROR_PARAM, has_return ? "{}" : "");
1766 } else {
1767 // no other options should be possible
1768 // (due to options arranged for above)
1769 assert(false);
1770 }
1771 def.pre_call.push_back(check_exp);
1772 }
1773 }
1774
1775 if (fallback)
1776 return def;
1777
1778 // process parameters from last to first
1779 // that way we can track whether it is possible to specify a default
1780 // which is only acceptable if so for all later parameters
1781 // (or later ones are dropped from signature)
1782 // init defaultable status to start
1783 // trailing GError prevents default
1784 bool defaultable = options.except != opt_except::GERROR;
1785
1786 // in case of callback;
1787 // check if some parameter is specified as closure (aka userdata)
1788 // as it may sadly be missing
1789 bool has_closure = false;
1790 if (kind == EL_CALLBACK) {
1791 for (auto it = paraminfo.rbegin(); it != paraminfo.rend(); ++it) {
1792 auto &&e = *it;
1793 if (e.second.closure >= 0) {
1794 has_closure = true;
1795 break;
1796 }
1797 }
1798 }
1799
1800 // if userdata/closure not specified for a closure,
1801 // accept last parameter as userdata based on name
1802 if (kind == EL_CALLBACK && !has_closure && paraminfo.size()) {
1803 auto &e = *paraminfo.rbegin();
1804 if (e.second.name == "data" || ends_with(e.second.name, "_data")) {
1805 e.second.closure = e.first;
1806 logger(Log::DEBUG, "{}; guessed userdata parameter {}", func.c_id,
1807 e.second.name);
1808 }
1809 }
1810
1811 for (auto it = paraminfo.rbegin(); it != paraminfo.rend(); ++it) {
1812 auto &&e = *it;
1813 try {
1814 defaultable =
1815 process_param(e.first, e.second, options, def, defaultable);
1816 } catch (const skip &ex) {
1817 handle_skip(ex);
1818 }
1819 }
1820
1821 // reverse some results
1822 std::reverse(def.cpp_outputs.begin(), def.cpp_outputs.end());
1823
1824 // add potentially missing transfers from length parameters
1825 // that were not added previously
1826 // FIXME reorganize data to avoid such
1827 if (errors.empty() &&
1828 (kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD)) {
1829 for (auto &&p : paraminfo) {
1830 auto index = p.first;
1831 if (def.cpp_decl.count(index) && !def.arg_traits.count(index)) {
1832 if (array_sizes.count(index)) {
1833 def.arg_traits[p.first].transfer = p.second.transfer;
1834 def.arg_traits[p.first].args = {p.first};
1835 } else {
1836 handle_skip(skip("missing callback transfer info"));
1837 }
1838 }
1839 }
1840 }
1841
1842 // enforce deduced function signature by cast
1843 for (auto &&p : def.c_call) {
1844 auto it = paraminfo.find(p.first);
1845 if (it != paraminfo.end()) {
1846 auto &pinfo = it->second;
1847 p.second = fmt::format("({}) ({})", pinfo.ptype, p.second);
1848 }
1849 }
1850
1851 // callback/callforward; add additional call/userdata parameters
1852 if (kind == EL_CALLBACK && found_user_data >= 0 &&
1853 paraminfo.count(found_user_data)) {
1854 // need a type for the C function to call
1855 auto cfc = unreserve(func.name) + GI_SUFFIX_CF_CTYPE;
1856 def.cf_ctype =
1857 make_declaration(true, cfc, fallback ? sig_ctype : sig_ptype);
1858 // which is specified in an extra paramater
1859 static const std::string param_func = "_call";
1860 def.cpp_decl[INDEX_CF] = fmt::format("{} {}", cfc, param_func);
1861 // userdata also given in parameter; re-use original parameter name
1862 // (which should have been used in regular in parameter processing)
1863 def.cpp_decl[INDEX_CF + 1] =
1864 fmt::format("gpointer {}", paraminfo.at(found_user_data).name);
1865 // call supplied function
1866 def.c_callee = param_func;
1867 // def.c_call userdata part should have been arranged as usual
1868 }
1869
1870 // if marked throws, GError argument is not mentioned in argument list
1871 // deal with it here
1872 switch (options.except) {
1873 case opt_except::THROW:
1874 case opt_except::EXPECTED:
1875 // could be here due to dl only
1876 if (!func.throws)
1877 break;
1878 def.pre_call.push_back("GError *error = NULL");
1879 def.c_call[def.c_call.size() + 10] = "&error";
1880 if (options.except == opt_except::THROW) {
1881 def.post_call.push_back("gi::check_error (error)");
1882 } else {
1883 // terminating ; added later
1884 def.post_call.push_back(
1885 "if (error) return gi::detail::make_unexpected (error)");
1886 }
1887 break;
1888 case opt_except::GERROR: {
1889 // simulate optional output error parameter
1890 options.output = opt_output::PARAM;
1891 Parameter err;
1892 err.optional = true;
1893 err.direction = DIR_OUT;
1894 err.transfer = TRANSFER_FULL;
1895 err.name = ERROR_PARAM;
1896 parse_typeinfo("GLib.Error", err.tinfo);
1897 err.ptype = err.tinfo.ctype = "GError**";
1898 // process non-nullable to make sure there is no signature
1899 // ambiguity
1900 try {
1901 process_param_out(INDEX_ERROR, err, options, def, false);
1902 auto &ti = def.arg_traits[INDEX_ERROR];
1903 ti.transfer = err.transfer;
1904 auto lparam =
1905 paraminfo.empty() ? 0 : paraminfo.crbegin()->first + 1;
1906 ti.args = {lparam};
1907 } catch (const skip &ex) {
1908 handle_skip(ex);
1909 }
1910 }
1911 default:
1912 break;
1913 }
1914 return def;
1915 };
1916
1917 // mild check on overload conflict
1918 // TODO improve check ??
1919 // what about defaultable arguments and overlap that causes
1920 std::set<std::vector<std::string>> signatures;
1921
1922 // pass over to produce cpp declarations and content
1923 // generate each option
1924 FunctionDataExtended def;
1925 if (!check_errors()) {
1926 for (auto &&output : do_output) {
1927 for (auto &&except : do_except) {
1928 for (auto &&nullable : do_nullable) {
1929 // context for this option run
1930 Options options(except, output, nullable);
1931 resume:
1932 do_basic_container.clear();
1933 def = make_definition(options);
1934
1935 // only care about callbacks with (trailing) user_data
1936 auto last = paraminfo.end();
1937 --last;
1938 if (kind == EL_CALLBACK && found_user_data != last->first)
1939 errors.push_back("not a callback since no user_data");
1940
1941 if (check_errors())
1942 goto exit;
1943
1944 // duplicate could happen for a special boxed output
1945 // which is never returned in a tuple
1946 // normalize without const
1947 // conflict might otherwise occur e.g. in case of
1948 // (string output, string input nullable)
1949
1950 auto cpp_sig = def.cpp_decl_unfolded;
1951 static const std::regex re_const("const ", std::regex::optimize);
1952 for (auto &d : cpp_sig)
1953 d = std::regex_replace(d, re_const, EMPTY);
1954 if (signatures.count(cpp_sig)) {
1955 logger(Log::DEBUG,
1956 "discarding duplicate signature for " + func.c_id);
1957 } else {
1958 auto fname =
1959 !callee && !func.shadows.empty() ? func.shadows : name;
1960 make_function(options, def, fname);
1961 // mark ok
1962 def.name = name;
1963 signatures.insert(cpp_sig);
1964 // also produce a CallArgs variant if desired
1965 // full signature is needed
1966 if (ctx.options.call_args >= 0 && func.lib_symbol &&
1967 options.nullable == opt_nullable::PRESENT)
1968 make_function(options, def, fname, true);
1969 // another signature alternative
1970 // unlike other ones, this one is discovered in make_definition
1971 // so dynamically add another run to these loops
1972 if (ctx.options.basic_collection && func.lib_symbol &&
1973 do_basic_container.size()) {
1974 options.basic_container = *do_basic_container.begin();
1975 goto resume;
1976 }
1977 }
1978 }
1979 }
1980 }
1981 }
1982
1983 exit:
1984 // generate a raw fallback virtual method upon failure
1985 if (ctx.options.classfull && def.name.empty() &&
1986 kind == EL_VIRTUAL_METHOD) {
1987 Options options(
1988 opt_except::NOEXCEPT, opt_output::PARAM, opt_nullable::PRESENT);
1989 def = make_definition(options, true);
1990 if (def.name.size())
1991 make_function(options, def, name);
1992 }
1993
1994 return def;
1995 }
1996
1997 FunctionDefinition process(const pt::ptree::value_type *entry,
1998 const std::vector<Parameter> *params, std::ostream &out,
1999 std::ostream &impl)
2000 {
2001 assert(!params || !entry);
2002
2003 logger(Log::LOG, "processing " + func.c_id);
2004 try {
2005 // check if we made it all the way
2006 // remove callback from known types if failure
2007 bool success = kind == EL_CALLBACK ? false : true;
2008 ScopeGuard g([&] {
2009 if (!success)
2010 ctx.repo.discard(func.name);
2011 });
2012
2013 if (entry) {
2014 collect_node(*entry);
2015 } else {
2016 int pno = 0;
2017 for (auto &p : *params) {
2018 int index = pno;
2019 if (p.direction == DIR_RETURN) {
2020 index = INDEX_RETURN;
2021 } else if (p.instance) {
2022 index = INDEX_INSTANCE;
2023 } else {
2024 ++pno;
2025 }
2026 paraminfo[index] = p;
2027 }
2028 }
2029
2030 auto def = process();
2031 // only trigger remove on callback as such has a top-level GIR entry
2032 // whereas e.g. a method does not
2033 // (and its name might conflict/match a top-level one)
2034 success = success || (def.name.size() > 0);
2035
2036 out << oss_decl.str() << std::endl;
2037 impl << oss_impl.str() << std::endl;
2038 return def;
2039 } catch (std::runtime_error &ex) {
2040 auto err = fmt::format("// FAILURE on {}; {}", func.c_id, ex.what());
2041 out << err << std::endl;
2042 impl << err << std::endl;
2043 }
2044
2045 return FunctionDefinition();
2046 }
2047 };
2048
2049 } // namespace
2050
2051 std::string
2052 make_arg_traits(const std::map<int, FunctionDefinition::ArgTrait> &traits,
2053 const std::string &c_sig)
2054 {
2055 // check if in 1-to-1 case
2056 bool complex = false;
2057 for (auto &&t : traits) {
2058 if (t.second.args.size() > 1) {
2059 complex = true;
2060 break;
2061 }
2062 }
2063 // another pass to set up trait
2064 std::vector<std::string> transfers;
2065 std::string ret_transfer;
2066 for (auto &&t : traits) {
2067 auto &ti = t.second;
2068 auto tt = GeneratorBase::get_transfer_parameter(ti.transfer, true);
2069 // skip return
2070 if (t.first < 0) {
2071 ret_transfer = tt;
2072 continue;
2073 }
2074 if (complex) {
2075 auto transform = [](int index) { return std::to_string(index); };
2076 auto li = boost::algorithm::join(
2077 ti.args | boost::adaptors::transformed(transform), ", ");
2078 auto custom = ti.custom.empty() ? "void" : ti.custom;
2079 tt = fmt::format("detail::arg_info<{}, {}, {}, detail::args_index<{}>>",
2080 tt, ti.inout ? "true" : "false", custom, li);
2081 } else if (ti.inout) {
2082 tt = fmt::format("detail::arg_info<{}, true>", tt);
2083 }
2084 transfers.emplace_back(std::move(tt));
2085 }
2086 assert(!ret_transfer.empty());
2087 auto ret = fmt::format("{}, std::tuple<{}>", ret_transfer,
2088 boost::algorithm::join(transfers, ", "));
2089 // also add C signature if needed
2090 if (complex)
2091 ret += ", " + c_sig;
2092 return ret;
2093 }
2094
2095 // process a function (or alike) and callback
2096 //
2097 // for a call;
2098 // const on parameter is maintained, always added for string
2099 // return value and output parameters always non-const
2100 //
2101 // callback; likewise (but not output params for now)
2102 //
2103 // klass: actual name of class being declared/defined (e.g. xxxBase)
2104 // klasstype: intended target type of class (e.g. xxx), used in signal instance
2105 // / constructor returns: last processed function definition (possibly only 1)
2106 FunctionDefinition
2107 process_element_function(GeneratorContext &_ctx, const std::string _ns,
2108 const pt::ptree::value_type &entry, std::ostream &out, std::ostream &impl,
2109 const std::string &klass, const std::string &klasstype,
2110 GeneratorBase::DepsSet &deps, std::ostream *call_args,
2111 bool allow_deprecated)
2112 {
2113 ElementFunction func;
2114
2115 auto &kind = func.kind = entry.first;
2116 auto &node = entry.second;
2117
2118 auto &name = func.name = get_name(node);
2119 auto c_name = (kind == EL_SIGNAL || kind == EL_VIRTUAL_METHOD)
2120 ? name
2121 : get_attribute(node,
2122 kind == EL_CALLBACK ? AT_CTYPE : AT_CIDENTIFIER);
2123 func.c_id = (kind == EL_VIRTUAL_METHOD) ? klasstype + "::" + c_name : c_name;
2124 // global qualifier needed as c_name might otherwise resolve wrongly
2125 // e.g. if g_mkdir is macro to mkdir (and resolve to namespaced mkdir)
2126 // in case of dl loading, the symbol name is needed as-is
2127 std::string qualifier =
2128 (kind == EL_FUNCTION || kind == EL_METHOD) && !_ctx.options.dl ? "::"
2129 : "";
2130 func.functionexp = kind == EL_VIRTUAL_METHOD
2131 ? fmt::format("get_struct_()->{}", c_name)
2132 : qualifier + c_name;
2133
2134 func.throws = get_attribute<int>(node, AT_THROWS, 0);
2135 func.shadows = get_attribute(node, AT_SHADOWS, "");
2136 func.lib_symbol =
2137 (kind == EL_FUNCTION || kind == EL_METHOD || kind == EL_CONSTRUCTOR);
2138
2139 FunctionGenerator gen(
2140 _ctx, _ns, func, klass, klasstype, deps, call_args, allow_deprecated);
2141 gen.const_method = (kind == EL_METHOD) && _ctx.options.const_method;
2142 return gen.process(&entry, nullptr, out, impl);
2143 }
2144
2145 FunctionDefinition
2146 process_element_function(GeneratorContext &_ctx, const std::string _ns,
2147 const ElementFunction &func, const std::vector<Parameter> &params,
2148 std::ostream &out, std::ostream &impl, const std::string &klass,
2149 const std::string &klasstype, GeneratorBase::DepsSet &deps)
2150 {
2151 FunctionGenerator gen(_ctx, _ns, func, klass, klasstype, deps, nullptr);
2152 return gen.process(nullptr, &params, out, impl);
2153 }