#include "function.hpp"

#include <boost/algorithm/string/join.hpp>
#include <boost/format.hpp>

#include <fmt/format.h>

namespace
{ // anonymous

const int INDEX_RETURN{-5};
const int INDEX_INSTANCE{-1};

struct FunctionGenerator : public GeneratorBase
{
  using Output = FunctionDefinition::Output;

  const ElementFunction &func;
  // duplicated from above
  const std::string &kind;
  const std::string &klass, &klasstype;
  // errors collected along the way (trigger abort)
  std::vector<std::string> errors;
  // collected dependencies
  std::set<std::string> &deps;
  // tweak debug level upon error
  bool ignored = false;
  bool introspectable = true;

  // also detect various function generation alternatives
  enum class opt_except {
    NOEXCEPT,
    THROW,
    EXPECTED,
    GERROR,
    DEFAULT = NOEXCEPT,
    ALT = GERROR
  };
  std::set<opt_except> do_except = {opt_except::DEFAULT};
  enum class opt_output { PARAM, TUPLE, DEFAULT = PARAM, ALT = TUPLE };
  std::set<opt_output> do_output = {opt_output::DEFAULT};
  enum class opt_nullable {
    PRESENT,
    DISCARD,
    DEFAULT = PRESENT,
    ALT = DISCARD
  };
  std::set<opt_nullable> do_nullable = {opt_nullable::DEFAULT};

  struct Options
  {
    opt_except except{};
    opt_output output{};
    opt_nullable nullable{};
    Options(opt_except _except, opt_output _output, opt_nullable _nullable)
        : except(_except), output(_output), nullable(_nullable)
    {}
    Options() {}
  };

  // global info
  // track callback's user_data
  int found_user_data = INDEX_DEFAULT;
  // const method
  bool const_method = false;
  // typical async method;
  // has GAsyncReadyCallback param with async scope
  std::string async_cb_wrapper;
  // indexed by GIR numbering (first non-instance parameter index 0)
  std::map<int, Parameter> paraminfo;
  // param numbers referenced by some other parameter
  std::set<int> referenced;
  // collects generated declaration and implementation
  std::ostringstream oss_decl, oss_impl;

  struct FunctionData : public FunctionDefinition
  {
    // (indexed as above)
    std::vector<decltype(cpp_decl)::mapped_type> cpp_decl_unfolded;
  };

public:
  FunctionGenerator(GeneratorContext &_ctx, const std::string _ns,
      const ElementFunction &_func, const std::string &_klass,
      const std::string &_klasstype, std::set<std::string> &_deps)
      : GeneratorBase(_ctx, _ns), func(_func), kind(func.kind), klass(_klass),
        klasstype(_klasstype), deps(_deps)
  {
    assert(func.name.size());
    assert(func.kind.size());
    assert(func.c_id.size());
    assert(func.functionexp.size());
  }

  void handle_skip(const skip &ex)
  {
    // we tried but it went wrong ...
    if (errors.empty() && !introspectable) {
      errors.push_back("not introspectable");
      // ... so let's not complain about it
      ignored = true;
    }
    if (ex.cause == skip::INVALID) {
      auto level = ignored ? Log::DEBUG : Log::WARNING;
      if (check_suppression(ns, kind, func.c_id))
        level = Log::DEBUG;
      logger(level, "skipping {} {}; {}", kind, func.c_id, ex.what());
    } else if (ex.cause == skip::IGNORE) {
      ignored = true;
    }
    errors.push_back(ex.what());
  }

  bool check_errors()
  {
    // check errors
    if (errors.size()) {
      auto reason = ignored ? "IGNORE" : "SKIP";
      auto err = fmt::format(
          "// {}; {}", reason, boost::algorithm::join(errors, ", "));
      oss_decl << err << std::endl;
      oss_impl << err << std::endl;
      return true;
    }
    return false;
  }

  // all parameters should have ctype info except for signal case
  void check_ctype(const ArgInfo &info)
  {
    if (info.ctype.empty() && kind != EL_SIGNAL)
      throw skip("missing c:type info");
  }

  void collect_param(const pt::ptree::value_type &n, int &param_no)
  {
    Parameter pinfo;
    pinfo.name = unreserve(get_name(n.second), false);
    pinfo.tinfo = parse_arginfo(n.second);
    check_ctype(pinfo.tinfo);
    // instance parameter not in cpp signature
    auto &el = n.first;
    pinfo.instance = (el == EL_INSTANCE_PARAMETER);
    param_no += pinfo.instance ? 0 : 1;
    // gather a bunch of attributes
    pinfo.direction = get_attribute(n.second, AT_DIRECTION, DIR_IN);
    pinfo.transfer = get_attribute(n.second, AT_TRANSFER);
    pinfo.closure = get_attribute<int>(n.second, AT_CLOSURE, -10);
    pinfo.destroy = get_attribute<int>(n.second, AT_DESTROY, -10);
    pinfo.callerallocates =
        get_attribute<int>(n.second, AT_CALLER_ALLOCATES, 0);
    pinfo.scope = get_attribute(n.second, AT_SCOPE, "");
    check_ctype(pinfo.tinfo);
    bool allownone = get_attribute<bool>(n.second, AT_ALLOW_NONE, 0);
    pinfo.optional = allownone || get_attribute<bool>(n.second, AT_OPTIONAL, 0);
    pinfo.nullable = allownone || get_attribute<bool>(n.second, AT_NULLABLE, 0);
    paraminfo.emplace(std::move(param_no), std::move(pinfo));
  }

  void collect_node(const pt::ptree::value_type &entry)
  {
    auto &node = entry.second;

    // should be ignored in some cases
    try {
      auto deprecated = get_attribute<int>(node, AT_DEPRECATED, 0);
      if (ctx.match_ignore.matches(ns, kind, {func.name, func.c_id}))
        throw skip("marked ignore", skip::IGNORE);
      if (deprecated)
        throw skip("deprecated", skip::IGNORE);
      // there are a few nice-to-have in this case (e.g. some _get_source)
      // so let's try anyway but not complain too much if it goes wrong
      auto intro = get_attribute<int>(node, AT_INTROSPECTABLE, 1);
      // except when renaming is at hand
      auto shadowed = get_attribute(node, AT_SHADOWED_BY, "");
      if (shadowed.size() && !intro)
        throw skip("not introspectable; shadowed-by " + shadowed, skip::IGNORE);
      // otherwise mark and try ...
      introspectable = intro;
    } catch (skip &ex) {
      handle_skip(ex);
    }

    try {
      // return value
      auto pinfo = Parameter();
      auto &ret = node.get_child(EL_RETURN);
      pinfo.tinfo = parse_arginfo(ret);
      // override constructor to return class instance
      if (kind == EL_CONSTRUCTOR)
        parse_typeinfo(klasstype, pinfo.tinfo);
      check_ctype(pinfo.tinfo);
      pinfo.direction = DIR_RETURN;
      pinfo.transfer = pinfo.tinfo.cpptype == CPP_VOID
                           ? TRANSFER_FULL
                           : get_attribute(ret, AT_TRANSFER);
      // ok if made it here
      paraminfo[INDEX_RETURN] = std::move(pinfo);
    } catch (skip &ex) {
      handle_skip(ex);
    }

    { // first pass to collect parameter info
      int param_no = INDEX_INSTANCE;
      auto params = node.get_child_optional(EL_PARAMETERS);
      if (params.is_initialized()) {
        for (auto &n : params.value()) {
          try {
            auto el = n.first;
            if (el == EL_PARAMETER || el == EL_INSTANCE_PARAMETER) {
              collect_param(n, param_no);
            }
          } catch (skip &ex) {
            handle_skip(ex);
          }
        }
      }
    }
  }

  // could be dropped if wrap/unwrap is made more casual about const-stuff
  // but on the other hand these checks catch some incorrect annotations
  // so some warning or discarding still has merit
  void verify_const_transfer(const ArgInfo &info, const std::string &transfer,
      const std::string &direction, bool /*wrap*/)
  {
    auto ctype = info.ctype;
    // never mind in case of signal
    if (kind == EL_SIGNAL)
      return;
    // note that const for parameter is not always picked up reliably
    // so if the ctype is const, it probably really is
    // (and so we might complain or warn)
    // but if the ctype is not const, the real one in function might
    // actually be (so we can't know for sure and then should not warn)
    // const and transfer full should not go together
    if (is_const(ctype) && transfer != TRANSFER_NOTHING) {
      auto level =
          check_suppression(ns, kind, func.c_id) ? Log::DEBUG : Log::WARNING;
      logger(level, "warning; {}; const transfer {} mismatch [{}]", func.c_id,
          transfer, direction);
    }
#if 0
    if ((flags & TYPE_BASIC) && (flags & TYPE_CLASS)) {
      // string transfer none preferably unwraps to a const
      // but as mentioned above; this check is not reliable
      if (!wrap && !is_const (ctype) && transfer == TRANSFER_NOTHING)
        throw skip ("transfer none on non-const string");
    }
#endif
  }

  bool process_param_in_callback(int param_no, const Parameter &pinfo,
      const Options & /*options*/, FunctionData &def, bool defaultable)
  {
    auto closure = pinfo.closure;
    auto scope = pinfo.scope;
    auto destroy = pinfo.destroy;
    auto &pname = pinfo.name;
    auto &cpptype = pinfo.tinfo.cpptype;

    logger(Log::LOG, "param_in_callback {} {}", param_no, pname);
    // lots of sanity to check
    static const std::string SCOPE_ASYNC_DEP("async_dep");
    const bool async_method = !async_cb_wrapper.empty();
    if (closure < 0)
      throw skip("callback misses closure info");
    auto it = paraminfo.find(closure);
    if (it == paraminfo.end())
      throw skip("callback has invalid closure parameter");
    auto ctype = it->second.tinfo.ctype;
    if (get_pointer_depth(ctype) != 1)
      throw skip("invalid callback closure parameter type " + ctype);
    // if async method, there is at least 1 async scope callback
    // if call also supports another callback, it could in principle
    // have any valid scope, but quite likely it has no "sane" scope,
    // and its user_data parameter is assumed to live within the async scope
    // so allow for this case in the sanity checks below
    if (scope.empty()) {
      if (!async_method)
        throw skip("callback misses scope info");
      scope = SCOPE_ASYNC_DEP;
    }
    if ((scope == SCOPE_NOTIFIED) != (destroy >= 0)) {
      if (!async_method)
        throw skip("callback destroy info mismatch");
      scope = SCOPE_ASYNC_DEP;
    }
    if (destroy >= 0) {
      it = paraminfo.find(destroy);
      if (it == paraminfo.end()) {
        throw skip("callback has invalid destroynotify parameter");
      } else {
        auto girname = it->second.tinfo.girname;
        // mind qualification
        if (girname != GIR_GDESTROYNOTIFY)
          throw skip(
              "invalid callback destroy notify parameter type " + girname);
      }
    }
    // there may be multiple callbacks, but they should not overlap
    // so check if we already entered something for the call parameter
    if (def.c_call.find(closure) != def.c_call.end())
      throw skip("callback closure parameter already used");
    if (def.c_call.find(destroy) != def.c_call.end())
      throw skip("callback destroy parameter already used");

    // declaration always the same
    def.cpp_decl[param_no] = fmt::format("{} {}", cpptype, pname);
    // could be nullable/optional
    if (pinfo.nullable && defaultable) {
      def.cpp_decl[param_no] += " = nullptr";
    } else {
      defaultable = false;
    }

    // some variation in handling
    auto cbw_pname = pname + "_wrap_";
    // pass along empty callback as NULL
    if (scope == SCOPE_CALL) {
      auto s = fmt::format("auto {} = {} ? unwrap (std::move ({}), "
                           "gi::scope_call) : nullptr",
          cbw_pname, pname, pname);
      def.pre_call.push_back(s);
      s = fmt::format("std::unique_ptr<std::remove_pointer<decltype({})>:"
                      ":type> {}_sp ({})",
          cbw_pname, cbw_pname, cbw_pname);
      def.pre_call.push_back(s);
    } else if (scope == SCOPE_NOTIFIED || scope == SCOPE_ASYNC ||
               scope == SCOPE_ASYNC_DEP) {
      // consider async_dep like notified but without a destroy;
      // ownership of the wrapper (pointer) is made part of the async callback
      auto pscope =
          scope != SCOPE_ASYNC ? "gi::scope_notified" : "gi::scope_async";
      def.pre_call.push_back(
          fmt::format("auto {} = {} ? unwrap (std::move ({}), {}) : nullptr",
              cbw_pname, pname, pname, pscope));
      // track wrapper for potential use below
      // (may have to take ownership of another callback wrapper)
      // NOTE ctype could have been set to ptype by this time
      // (ptype = normalized parsed form by this time (see make_ctype)
      const auto &ctype = pinfo.tinfo.ctype;
      if (scope == SCOPE_ASYNC &&
          ctype.find("AsyncReadyCallback") != ctype.npos &&
          async_cb_wrapper.empty())
        async_cb_wrapper = cbw_pname;
      if (destroy >= 0) {
        def.c_call[destroy] =
            fmt::format("{} ? &{}->destroy : nullptr", cbw_pname, cbw_pname);
      } else {
        assert(scope != SCOPE_NOTIFIED);
        if (scope == SCOPE_ASYNC_DEP && !async_cb_wrapper.empty()) {
          // make async scope callback take ownership of this wrapper callback
          def.pre_call.push_back(
              fmt::format("{}->take_data ({})", async_cb_wrapper, cbw_pname));
        }
      }
    } else {
      throw skip("invalid callback scope " + scope);
    }
    // common part
    def.c_call[param_no] =
        fmt::format("{} ? &{}->wrapper : nullptr", cbw_pname, cbw_pname);
    def.c_call[closure] = cbw_pname;

    return defaultable;
  }

  // returns defaultable status
  bool process_param_in_data(int param_no, const Parameter &pinfo,
      const Options &options, FunctionData &def, bool defaultable)
  {
    auto flags = pinfo.tinfo.flags;
    auto &pname = pinfo.name;
    auto &cpptype = pinfo.tinfo.cpptype;
    auto &ctype = pinfo.tinfo.ctype;
    auto &transfer = pinfo.transfer;
    auto &tinfo = pinfo.tinfo;

    typedef std::vector<std::pair<int, std::string>> callexp_t;
    callexp_t callexps;
    std::string callexp, cpp_decl;

    logger(Log::LOG, "param_in_data {} {}", param_no, pname);
    if (flags & TYPE_VALUE) {
      // value types always passed simply
      // mind g(const)pointer case (const not in normalized girtype)
      cpp_decl = ((flags & TYPE_ENUM) ? cpptype : ctype) + " " + pname;
      callexp = flags & TYPE_ENUM
                    ? fmt::format(GI_NS_SCOPED + "unwrap ({})", pname)
                    : pname;
    } else if (flags & TYPE_CLASS) {
      // otherwise have to mind ownership issues
      if (pinfo.nullable && options.nullable != opt_nullable::PRESENT) {
        // discard nullable
        // NOTE: default value not possible with only forward
        // declaration
        callexp = "nullptr";
      } else {
        // preserve const signature and always so for string
        bool is_string = (flags & TYPE_BASIC);
        if (is_const(ctype) || is_string) {
          cpp_decl = fmt::format("const {} & {}", cpptype, pname);
        } else {
          cpp_decl = fmt::format("{} {}", cpptype, pname);
        }
        callexp =
            fmt::format(GI_NS_SCOPED + "unwrap ({}, {}, gi::direction_in)",
                pname, get_transfer_parameter(transfer));
      }
    } else if (flags & TYPE_CONTAINER) {
      auto tmpvar = pname + "_w";
      auto unwrapvar = pname + "_i";
      std::string exp_data, exp_size, unwrapsetup;
      if (flags & TYPE_MAP) {
        cpp_decl = fmt::format("const std::map<{}, {}> & {}",
            tinfo.first.cpptype, tinfo.second.cpptype, pname);
        unwrapsetup = fmt::format("auto & {} = {}", unwrapvar, pname);
      } else if ((flags & TYPE_LIST) || tinfo.zeroterminated) {
        cpp_decl = fmt::format(
            "const std::vector<{}> & {}", tinfo.first.cpptype, pname);
        auto ltype =
            (flags & TYPE_LIST)
                ? tinfo.ctype.substr(0, tinfo.ctype.size() - 1)
                : fmt::format("traits::ctype<{}>::type", tinfo.first.cpptype);
        unwrapsetup =
            fmt::format("auto {} = detail::make_list_unwrap_range<{}> ({})",
                unwrapvar, ltype, pname);
      } else if (tinfo.fixedsize) {
        cpp_decl = fmt::format(
            "{} {}[{}]", tinfo.first.cpptype, pname, tinfo.fixedsize);
        exp_data = pname;
        exp_size = std::to_string(tinfo.fixedsize);
      } else {
        // need length parameter
        auto len = tinfo.length;
        auto it = len >= 0 ? paraminfo.find(len) : paraminfo.end();
        if (it == paraminfo.end())
          throw skip("array has invalid length parameter");
        // NOTE a pointer/size representation is used here on cpp side
        // while that may be less natural than a particular container
        // it avoids forcing the caller to use a specific container/view
        // this is an input parameter, so add const
        // (as what will be passed is likely const)
        cpp_decl = fmt::format("const {} * {}", tinfo.first.cpptype, pname);
        exp_data = pname;
        auto &linfo = it->second;
        exp_size = linfo.name;
        callexps.emplace_back(len, fmt::format("{}.size()", tmpvar));
        def.cpp_decl[len] = linfo.tinfo.cpptype + " " + linfo.name;
      }
      // remaining array prep
      if (unwrapsetup.empty())
        unwrapsetup = fmt::format(
            "auto {} = detail::make_list_unwrap_range ({}, {}, {})", unwrapvar,
            exp_data, exp_size, tinfo.zeroterminated ? "true" : "false");
      auto s = fmt::format("auto {} = unwrap ({}, {}, direction_in)", tmpvar,
          unwrapvar, get_transfer_parameter(pinfo.transfer));
      def.pre_call.push_back(unwrapsetup);
      def.pre_call.push_back(s);
      callexp = fmt::format("{}.gobj_({})", tmpvar,
          (transfer != TRANSFER_NOTHING ? "true" : "false"));
      callexps.emplace_back(param_no, callexp);
    } else {
      throw std::logic_error("invalid flags");
    }
    // transfer to def
    if (callexps.empty()) {
      if (callexp.empty())
        throw std::logic_error("unhandled flags");
      callexps.emplace_back(std::move(param_no), std::move(callexp));
    }
    if (cpp_decl.size()) {
      def.cpp_decl.emplace(std::move(param_no), std::move(cpp_decl));
      // a declaration here has no defaults
      // so no defaults further down
      defaultable = false;
    }
    for (auto &&s : callexps) {
      // use intermediate var for clarity
      if (s.first == param_no) {
        // sigh, our input name may actually be an expression
        // FIXME ?? fall back to global data
        auto varname = paraminfo[param_no].name + "_to_c";
        def.pre_call.emplace_back(
            fmt::format("auto {} = {}", varname, s.second));
        def.c_call[s.first] = varname;
      } else {
        def.c_call[s.first] = s.second;
      }
    }
    return defaultable;
  }

  bool process_param_in(int param_no, const Parameter &pinfo,
      const Options &options, FunctionData &def, bool defaultable)
  {
    auto flags = pinfo.tinfo.flags;

    verify_const_transfer(
        pinfo.tinfo, pinfo.transfer, pinfo.direction, kind == EL_CALLBACK);
    if (pinfo.instance) {
      // check sanity
      assert(flags & TYPE_CLASS);
      // method is const if it can operate on a const C struct
      const_method = is_const(pinfo.tinfo.ctype);
      def.c_call[param_no] = "gobj_()";
      // NOTE transfer != NOTHING might be a silly case (e.g. _unref)
      // or a useful one (such as some _merge cases)
      defaultable = false;
    } else if (flags & TYPE_CALLBACK) {
      defaultable =
          process_param_in_callback(param_no, pinfo, options, def, defaultable);
    } else {
      defaultable =
          process_param_in_data(param_no, pinfo, options, def, defaultable);
    }
    return defaultable;
  }

  static std::string make_out_type(const ArgInfo &info)
  {
    if (!info.flags)
      throw skip(fmt::format("return type {} not supported", info.cpptype));
    else if (info.flags & (TYPE_LIST | TYPE_ARRAY)) {
      return fmt::format("std::vector<{}>", info.first.cpptype);
    } else if (info.flags & TYPE_MAP) {
      return fmt::format(
          "std::map<{}, {}>", info.first.cpptype, info.second.cpptype);
    } else {
      return info.cpptype;
    }
  }

  void process_param_out_array(int param_no, const Parameter &pinfo,
      const Options & /*options*/, FunctionData &def)
  {
    auto pname = pinfo.name;
    auto &tinfo = pinfo.tinfo;
    auto &transfer = pinfo.transfer;
    bool inout = pinfo.direction == DIR_INOUT;

    std::string exp_outdata(pname), exp_size;
    int length = -1;
    Parameter *plinfo = nullptr;

    if (tinfo.fixedsize) {
      def.cpp_decl[param_no] =
          fmt::format("{} {}[{}]", tinfo.first.cpptype, pname, tinfo.fixedsize);
      exp_size = std::to_string(tinfo.fixedsize);
    } else {
      // must have this (likely checked already though ...)
      length = tinfo.length;
      if (length < 0)
        throw skip("array misses length info");
      auto it = paraminfo.find(length);
      if (it == paraminfo.end())
        throw skip("array has invalid length parameter");
      plinfo = &it->second;
      auto &linfo = it->second;
      inout |= linfo.direction == DIR_INOUT;
      // in case of length parameter it is never treated as an output
      // since the length is a required input
      // so it is always in the declaration
      def.cpp_decl[param_no] = tinfo.first.cpptype + " * " + pname;
      // also handle length parameter here
      def.cpp_decl[length] = linfo.tinfo.cpptype + " " + linfo.name;
      exp_size = linfo.name;
    }
    // FIXME ?? no real examples here and semantics not entirely clear
    // (probably a single lvalue container argument could be used here)
    if (inout)
      throw skip("inout array not supported");
    // typically lots of different pointer types around (e.g. gpointer)
    // so establish own types all the way
    auto tname_cpp = pname + "_cpptype";
    auto tname_cpp_def =
        fmt::format("typedef {} {}", tinfo.first.cpptype, tname_cpp);
    auto outvar = (pname.size() ? pname : "_ret") + "_o";
    if (pinfo.callerallocates) {
      if ((tinfo.first.flags & TYPE_BASIC) &&
          (tinfo.first.flags & TYPE_VALUE)) {
        // optimization; avoid intermediate copy below
        // simply pass along input and done
        def.c_call[param_no] = pname;
        if (length >= 0)
          def.c_call[length] = plinfo->name;
        return;
      }
      // vexing parse parentheses
      def.pre_call.push_back(tname_cpp_def);
      def.pre_call.push_back(fmt::format(
          "std::vector<{}> {} (({}))", tname_cpp, outvar, exp_size));
      def.c_call[param_no] = fmt::format("{}.data()", outvar);
      if (length >= 0)
        def.c_call[length] = fmt::format("{}.size()", outvar);
      def.post_call.push_back(
          fmt::format("detail::wrap_array ({}.data(), {}, {}.size(), {})",
              outvar, get_transfer_parameter(transfer), outvar, pname));
    } else {
      auto tname_c = pname + "_ctype";
      if (pinfo.direction != DIR_RETURN) {
        // prepare an output parameter var
        def.pre_call.push_back(tname_cpp_def);
        def.pre_call.push_back(fmt::format(
            "typedef traits::ctype<{}>::type {}", tname_cpp, tname_c));
        def.pre_call.push_back(fmt::format("{} *{}", tname_c, outvar));
        def.c_call[param_no] = fmt::format("({}) &{}", tinfo.ctype, outvar);
      } else {
        // assign return to var
        def.ret_format = fmt::format("auto {} = {{}}", outvar);
      }
      auto cppoutvar = pname;
      auto cppouttype = make_out_type(tinfo);
      bool cppcontainer = false;
      if (length >= 0) {
        auto &linfo = *plinfo;
        if (linfo.direction != DIR_IN) {
          // oops, exception case on declaration
          // an lvalue container as parameter/return, no size
          // parameter
          cppcontainer = true;
          def.cpp_decl[param_no] = fmt::format(cppouttype + " & " + cppoutvar);
          def.cpp_decl.erase(length);
          def.pre_call.push_back(
              fmt::format("{} {}", linfo.tinfo.cpptype, linfo.name));
          def.c_call[length] = fmt::format("&{}", linfo.name);
          // arranged above
          assert(exp_size == linfo.name);
        } else {
          def.c_call[length] = exp_size;
          exp_outdata = cppoutvar;
        }
      }
      // tweak the array return case
      // uses cpp container return in all cases
      if (pinfo.direction == DIR_RETURN) {
        cppcontainer = true;
        // so no cpp parameter
        def.cpp_decl.erase(param_no);
        // output container is temp helper var instead
        cppoutvar = "_temp_ret";
        def.pre_call.push_back(fmt::format("{} {}", cppouttype, cppoutvar));
        def.cpp_outputs.push_back({cppouttype, cppoutvar});
      }
      if (cppcontainer) {
        // ensure pre-allocate prior to transform copy
        exp_outdata = cppoutvar + ".data()";
        def.post_call.push_back(
            fmt::format("{}.resize({})", cppoutvar, exp_size));
      }
      def.post_call.push_back(fmt::format("detail::wrap_array ({}, {}, {}, {})",
          outvar, get_transfer_parameter(transfer), exp_size, exp_outdata));
      if (transfer != TRANSFER_NOTHING)
        def.post_call.push_back(fmt::format("g_free ({})", outvar));
    }
  }

  // returns defaultable status
  bool process_param_out(int param_no, const Parameter &pinfo,
      const Options &options, FunctionData &def, bool defaultable)
  {
    auto pname = pinfo.name;
    auto &tinfo = pinfo.tinfo;
    auto &ctype = tinfo.ctype;
    int flags = tinfo.flags;
    auto &transfer = pinfo.transfer;
    bool inout = pinfo.direction == DIR_INOUT;

    verify_const_transfer(
        tinfo, transfer, pinfo.direction, kind != EL_CALLBACK);
    if (pinfo.instance)
      throw skip("instance out");

    // zero-terminated handled below
    if ((flags & TYPE_ARRAY) && !tinfo.zeroterminated) {
      process_param_out_array(param_no, pinfo, options, def);
      return false;
    }

    if (pinfo.direction == DIR_RETURN) {
      // FIXME ?? what about array return with size param
      // (e.g. gst_adapter_map) ?? annotation is not correctly generated
      // btw
      def.transfers.push_back(pinfo.transfer);
      if (tinfo.cpptype == CPP_VOID) {
        def.ret_format = "{}";
      } else {
        auto cpp_ret = make_out_type(tinfo);
        auto tmpvar = "_temp_ret";
        def.ret_format = fmt::format("auto {} = {{}}", tmpvar);
        def.cpp_outputs.push_back(
            {cpp_ret, fmt::format(make_wrap_format(tinfo, transfer), tmpvar)});
      }
      return false;
    }

    // inout never in output tuple
    bool as_param = (options.output == opt_output::PARAM) || inout;

    // one-to-one non-array cases
    // this also handles list/map output with suitable pointer depth
    auto paramtype = make_out_type(tinfo);
    bool optional = false;
    if (as_param) {
      optional = pinfo.optional;
      auto pass = pinfo.optional ? " * " : " & ";
      // no (nullptr) default for pointer output
      // as that leads to call ambiguity with the output tuple variant
      // if no argument given in call
      def.cpp_decl[param_no] = paramtype + pass + pname;
      defaultable = false;
    } else {
      // FIXME ?? could consider defaultable in this case ??
      defaultable = false;
    }

    if ((flags & TYPE_BOXED) && pinfo.callerallocates) {
      // special case; use provided output plain struct directly
      // mimic typical call sequence; declare local struct and pass that
      auto cvar = pname + "_c";
      // such call is typically used for things that do not need cleanup
      // (e.g. GstMapInfo, etc), though GValue is a popular and prominent
      // exception so let's use a trait to allow for custom additional
      // destructor cleanup when needed
      def.pre_call.push_back(
          fmt::format("traits::unset_wrapper<{}>::type {}", tinfo.dtype, cvar));
      auto cvalue = fmt::format("({}*) &{}", tinfo.dtype, cvar);
      def.c_call[param_no] =
          pinfo.optional && as_param
              ? fmt::format("{} ? {} : nullptr", pname, cvalue)
              : cvalue;
      // then wrap the local var into output
      auto output =
          fmt::format(make_wrap_format(tinfo, TRANSFER_NOTHING), cvalue);
      if (!as_param) {
        def.cpp_outputs.push_back({paramtype, output});
      } else {
        auto prefix = pinfo.optional ? fmt::format("if ({}) *", pname) : "";
        def.post_call.push_back(
            fmt::format("{}{} = {}", prefix, pname, output));
      }
      return defaultable;
    }

    // otherwise use a temp variable and then wrap that one
    auto outvar = pname + "_o";
    // adjust arginfo for wrapping
    auto opinfo = pinfo;
    auto &otinfo = opinfo.tinfo;
    if (ctype[ctype.size() - 1] != GI_PTR)
      throw skip(pname + "; inconsistent pointer type");
    // adjust type
    otinfo.ctype = ctype.substr(0, ctype.size() - 1);

    // optionally init the temp variable using input (if such)
    std::string init(" {}");
    if (inout && as_param) {
      // operate on a temporary definition
      // only need to re-use transformation of input to call expression
      auto tdef = def;
      tdef.pre_call.clear();
      // optionally tweak the input expression (type adjusted above)
      if (optional)
        opinfo.name.insert(0, "*");
      process_param_in_data(param_no, opinfo, options, tdef, defaultable);
      // be nice, include requested code
      for (auto &&p : tdef.pre_call)
        def.pre_call.emplace_back(p);
      // rest we handle here
      init = fmt::format(" = {}", tdef.c_call[param_no]);
    }

    // always same precall, but slight variation for pointer/ref
    def.pre_call.push_back(otinfo.ctype + " " + outvar + init);
    auto call = std::string("&") + outvar;
    def.c_call[param_no] =
        optional ? fmt::format("{} ? {} : nullptr", pname, call) : call;
    auto wrapf = fmt::format(make_wrap_format(otinfo, transfer), outvar);
    // assign post call or return
    if (as_param) {
      auto guard = optional ? fmt::format("if ({}) ", pname) : EMPTY;
      auto deref = optional ? "*" : "";
      def.post_call.push_back(
          fmt::format("{}{}{} = {}", guard, deref, pname, wrapf));
    } else {
      def.cpp_outputs.push_back({paramtype, wrapf});
    }
    return defaultable;
  }

  // process info to construct function
  // returns defaultable status
  bool process_param(int param_no, Parameter &pinfo, const Options &options,
      FunctionData &def, bool defaultable)
  {
    auto &tinfo = pinfo.tinfo;
    auto ctype = tinfo.ctype;
    int flags = tinfo.flags;

    // check type first, so we do not raise any complaints on unknown type
    if (!flags)
      throw skip(
          fmt::format("{} type {} not supported", pinfo.name, tinfo.cpptype),
          skip::OK);
    // sanity check on pointer depth to verify annotation
    // array annotation or out parameter is frequently missing
    auto argdepth = std::count(pinfo.ptype.begin(), pinfo.ptype.end(), GI_PTR);
    auto rpdepth = get_pointer_depth(pinfo.tinfo.ctype);
    // array declaration is not properly decayed to (additional pointer)
    // type so allow for that but it could also mean that an array of plain
    // records is at hand (rather than array of pointers, e.g.
    // g_main_context_query)
    if (kind != EL_SIGNAL && (argdepth != rpdepth) &&
        !((flags & TYPE_ARRAY) && (argdepth == rpdepth + 1) &&
            !(tinfo.first.flags & TYPE_BOXED)))
      throw skip(fmt::format("inconsistent {} {} pointer depth ({} vs {})",
          pinfo.direction, pinfo.name, rpdepth, argdepth));
    // now that has been checked, replace the declared type by deduced type
    pinfo.tinfo.ctype = pinfo.ptype;

    // perhaps this param is part of another's one (e.g. callback)
    // processing various checks to bail out early
    if (def.c_call.find(param_no) != def.c_call.end()) {
      logger(Log::LOG, "call fragment for parameter {} already specified",
          param_no);
      return false;
    } else if (kind != EL_CALLBACK && kind != EL_SIGNAL &&
               referenced.count(param_no)) {
      /* managing parameter might come later, so skip this one for now
       * if a call has to be emitted
       * (also; user_data closure in callback can reference itself,
       * and that has to be discovered below */
      logger(Log::LOG, "parameter {} referenced elsewhere", param_no);
      return false;
    }
    // on with it now
    if (pinfo.direction != DIR_IN) {
      // (in)out or return
      defaultable =
          process_param_out(param_no, pinfo, options, def, defaultable);
    } else {
      defaultable =
          process_param_in(param_no, pinfo, options, def, defaultable);
      // handle callback user_data
      if (kind == EL_CALLBACK) {
        if (pinfo.closure >= 0) {
          if (pinfo.closure != param_no)
            throw skip("invalid closure user_data");
          if (ctype != "gpointer")
            throw skip("invalid type user_data");
          if (found_user_data >= 0)
            throw skip("duplicate user_data");
          found_user_data = param_no;
          // user_data not included in signature (nor transfer)
          def.cpp_decl.erase(param_no);
        } else {
          def.transfers.push_back(pinfo.transfer);
        }
      } else if (!pinfo.instance && kind == EL_VIRTUAL_METHOD) {
        def.transfers.push_back(pinfo.transfer);
      }
    }

    return defaultable;
  }

  std::string join_outputs(
      const std::vector<FunctionDefinition::Output> &outputs,
      std::string FunctionDefinition::Output::*m,
      std::string (*transform)(std::string) = nullptr)
  {
    std::vector<std::string> temp;
    for (auto &&o : outputs)
      temp.emplace_back(transform ? transform(o.*m) : o.*m);
    return boost::algorithm::join(temp, ", ");
  }

  void make_function(
      const Options &options, const FunctionData &def, const std::string &fname)
  {
    auto &name = func.name;
    // determine return type
    std::string cpp_ret(CPP_VOID);
    if (def.cpp_outputs.size() == 1) {
      cpp_ret = def.cpp_outputs[0].type;
    } else if (def.cpp_outputs.size() > 1) {
      cpp_ret = fmt::format(
          "std::tuple<{}>", join_outputs(def.cpp_outputs, &Output::type));
    }
    if (options.except == opt_except::EXPECTED) {
      cpp_ret = fmt::format("gi::result<{}>", cpp_ret);
    }
    const auto &cpp_decl = def.cpp_decl_unfolded;
    // generate based on type
    if (kind == EL_SIGNAL) {
      auto decl_name = name;
      // always include instance in signature
      auto cpp_decls = cpp_decl;
      cpp_decls.insert(cpp_decls.begin(), qualify(klasstype, TYPE_OBJECT));
      // the function type specified as gi::signal_proxy template parameter
      // serves 2 purposes;
      // + provide a compile-time type check
      // + select each parameter's corresponding GValue GType
      //   (according to the association defined in gi/value.hpp)
      // so we should make sure to pick the proper type, especially for the
      // latter item, as e.g. gint64 may simply be a long
      // (which would not map to a G_TYPE_INT64)
      auto normalize = [](std::string &subject, const std::string &in,
                           const std::string &sub) {
        if (subject.find(in) == 0 &&
            (subject.size() == in.size() || subject[in.size()] == ' ')) {
          subject.replace(subject.begin(), subject.begin() + in.size(), sub);
        }
      };
      for (auto &decl : cpp_decls) {
        normalize(decl, "gint64", "long long");
        normalize(decl, "guint64", "unsigned long long");
      }
      // convert signal name to valid identifier
      std::replace(decl_name.begin(), decl_name.end(), '-', '_');
      auto ret = fmt::format("gi::signal_proxy<{}({})>", cpp_ret,
          boost::algorithm::join(cpp_decls, ", "));
      oss_decl << boost::format(
                      "%1% signal_%2%()\n{ return %1% (*this, \"%3%\"); }") %
                      ret % decl_name % name
               << std::endl;
    } else if (kind != EL_CALLBACK) {
      auto make_sig = [&](bool impl) {
        auto prefix =
            impl ? EMPTY
                 : (kind == EL_VIRTUAL_METHOD
                           ? "virtual "
                           : ((kind != EL_METHOD) && klass.size() ? "static "
                                                                  : ""));
        auto klprefix = klass.size() && impl ? klass + "::" : "";
        auto pure = (kind == EL_VIRTUAL_METHOD && !impl ? " = 0" : "");
        if (!impl)
          prefix += GI_INLINE + ' ';
        auto sig =
            prefix +
            fmt::format("{} {}{} ({}){}{}{}", cpp_ret, klprefix,
                unreserve(fname, kind == EL_VIRTUAL_METHOD),
                boost::algorithm::join(cpp_decl, ", "),
                (const_method ? " const" : ""),
                ((options.except == opt_except::THROW) ? "" : " noexcept"),
                pure);
        // remove default values in definition
        static const std::regex re_defaultv(" =[^,)]*", std::regex::optimize);
        return impl ? std::regex_replace(sig, re_defaultv, "") : sig;
      };
      oss_decl << make_sig(false) << ";" << std::endl;
      oss_impl << make_sig(true) << std::endl;
      // transform to list for joining
      std::vector<std::string> temp;
      for (auto &&e : def.c_call)
        temp.emplace_back(e.second);
      auto call = fmt::format(
          "{} ({})", def.c_callee, boost::algorithm::join(temp, ", "));
      call = fmt::format(def.ret_format, call);
      std::string returns;
      if (def.cpp_outputs.size() == 1) {
        returns = fmt::format("return {};", def.cpp_outputs[0].value);
      } else if (def.cpp_outputs.size() > 1) {
        returns = fmt::format("return std::make_tuple ({});",
            join_outputs(def.cpp_outputs, &Output::value));
      }
      if (options.except == opt_except::EXPECTED && returns.empty()) {
        // expected<void> is no longer void, so needs explicit return
        returns = "return {};";
      }
      oss_impl << "{" << std::endl;
      // prevent calling NULL in case of vmethod
      // (i.e. Subclass::method != Superclass::method)
      if (kind == EL_VIRTUAL_METHOD) {
        // FIXME ?? it is unfortunate that the superclass has NULL in
        // this entry whereas the subclass had to fill in something to
        // allow for vmethod override
        // so as long as the user sub-subclass does not override the default
        // virtual method, the return value here is a bit nasty and
        // hoping for the best
        // (though *mm does no better here) ...
        auto retexp = fmt::format(
            "return {};", cpp_ret == CPP_VOID ? EMPTY : cpp_ret + "{}");
        retexp = fmt::format("if (!{}) {}", func.functionexp, retexp);
        oss_impl << indent << retexp << std::endl;
      }
      for (const auto &p : def.pre_call)
        oss_impl << indent << p << ';' << std::endl;
      oss_impl << indent << call << ';' << std::endl;
      for (const auto &p : def.post_call)
        oss_impl << indent << p << ';' << std::endl;
      if (returns.size())
        oss_impl << indent << returns << std::endl;
      oss_impl << "}" << std::endl;
    } else { // callback
      // NOTE no container support at present
      // argument transfers; return type to start with
      std::vector<std::string> transfers;
      for (auto &&t : def.transfers)
        transfers.emplace_back(get_transfer_parameter(t, true));
      oss_decl << fmt::format("typedef {}callback<{}({}), {}> {}",
                      GI_NS_DETAIL_SCOPED, cpp_ret,
                      boost::algorithm::join(cpp_decl, ", "),
                      boost::algorithm::join(transfers, ", "), unreserve(name))
               << ";" << std::endl;
    }
  }

  FunctionDefinition process()
  {
    auto &name = func.name;

    const bool callee = kind == EL_CALLBACK || kind == EL_VIRTUAL_METHOD;
    // pass over parameters to collect info to assemble signature
    struct signature
    {
      std::string c_ret;
      std::vector<std::string> c_decl;
    };
    signature sig_ctype, sig_ptype;
    std::map<int, int> array_sizes;

    for (auto &p : paraminfo) {
      try {
        auto &pinfo = p.second;
        assert(pinfo.name.size() || pinfo.direction == DIR_RETURN);
        assert(pinfo.transfer.size());
        assert(pinfo.direction.size());
        // c signature
        if (p.first == INDEX_RETURN) {
          sig_ctype.c_ret = pinfo.tinfo.ctype;
        } else {
          sig_ctype.c_decl.push_back(pinfo.tinfo.ctype + " " + pinfo.name);
        }
        auto flags = pinfo.tinfo.flags;
        // also sanity checks
        if (pinfo.direction == DIR_RETURN) {
          // moreover, transfer none for callback return can only mean
          // floating and so is a bit nasty and is only handled for
          // GObject see also e.g.
          // https://bugzilla.gnome.org/show_bug.cgi?id=693393)
          if (callee && (flags & TYPE_CLASS) &&
              pinfo.transfer != TRANSFER_FULL && !(flags & TYPE_OBJECT))
            throw skip("invalid callback return transfer " + pinfo.transfer);
          if (callee && (flags & TYPE_CONTAINER))
            throw skip("container return not supported");
          // NOTE constructor return transfer is often marked none =
          // floating (so that needs a ref_sink)
        } else {
          // overall checks
          bool function_type = false;
          if (callee || kind == EL_SIGNAL) {
            function_type = true;
            // no defaults in signatures
            pinfo.nullable = false;
            pinfo.optional = false;
            // FIXME not supported
            // could be done, but these cases are moderately rare
            // and not all that important
            if (pinfo.direction != DIR_IN)
              throw skip(kind + " out parameter not supported");
            if (flags & TYPE_CONTAINER)
              throw skip(kind + " container parameter not supported");
            if (flags & TYPE_CALLBACK)
              throw skip(kind + " callback parameter not supported");
          }
          // trigger additional applicable overload generation
          if (!function_type) {
            if (pinfo.direction == DIR_OUT)
              do_output.insert(opt_output::ALT);
            if ((flags & TYPE_CLASS) && pinfo.nullable &&
                pinfo.direction == DIR_IN)
              do_nullable.insert(opt_nullable::ALT);
          }
        }
        track_dependency(deps, pinfo.tinfo);
        // closure attribute should only be on callback argument,
        // but is sometimes also on user_data referring back to callback
        // remove the latter circular reference
        if (!callee && !(flags & TYPE_CALLBACK))
          pinfo.closure = INDEX_DEFAULT;
        // collect parameters that are referenced from elsewhere
        // and as such managed elsewhere
        for (auto p : {&pinfo.closure, &pinfo.destroy, &pinfo.tinfo.length})
          if (*p >= 0)
            referenced.insert(*p);
        array_sizes[pinfo.tinfo.length] = p.first;
      } catch (skip &ex) {
        handle_skip(ex);
      }
    }

    // another pass to determine expected normalized parameter type
    // unfortunately some array length size parameters share annotation
    // with the array, so a caller-allocates out array lead to wrong ptr
    // depth (if not compensated for that)
    for (auto &p : paraminfo) {
      try {
        auto &pinfo = p.second;
        // special case; out array length is not so consistent
        // always marked as out (even when passed no-ptr)
        // even when out, then caller-allocates is reversed from a
        // regular out int
        if (pinfo.direction == DIR_OUT) {
          auto it = array_sizes.find(p.first);
          if (it != array_sizes.end()) {
            // normalize based on declaration
            pinfo.direction =
                get_pointer_depth(pinfo.tinfo.ctype) > 0 ? DIR_OUT : DIR_IN;
            // make sure we end up with ptr
            if (pinfo.direction == DIR_OUT)
              pinfo.callerallocates = false;
          }
        }
        pinfo.ptype =
            make_ctype(pinfo.tinfo, pinfo.direction, pinfo.callerallocates);
        // collect deduced signature
        if (p.first == INDEX_RETURN) {
          sig_ptype.c_ret = pinfo.ptype;
        } else {
          sig_ptype.c_decl.push_back(pinfo.ptype + " " + pinfo.name);
        }
      } catch (skip &ex) {
        handle_skip(ex);
      }
    }

    // could affect declaration signature
    if (func.throws) {
      // FIXME ?? though not many instances so far
      if (callee)
        errors.push_back("callee GError not supported");
      // fixed signature
      sig_ctype.c_decl.push_back("GError ** error");
      sig_ptype.c_decl.push_back("GError ** error");
      do_except = {
          ctx.options.expected ? opt_except::EXPECTED : opt_except::THROW,
          opt_except::GERROR};
    }

    // we collected enough info so far to reconstruct original declaration
    auto make_declaration = [&](bool def, const std::string name,
                                const signature &sig) {
      auto c_sig_fmt = !def ? "{} {} ({})" : "typedef {} (*{}) ({})";
      return fmt::format(
          c_sig_fmt, sig.c_ret, name, boost::algorithm::join(sig.c_decl, ", "));
    };

    if (kind != EL_SIGNAL) {
      // dump both parsed and derived
      for (auto &sig : {sig_ctype, sig_ptype}) {
        auto c_sig = make_declaration(kind == EL_CALLBACK, func.c_id, sig);
        oss_decl << "// " << c_sig << ";" << std::endl;
        oss_impl << "// " << c_sig << ";" << std::endl;
      }
    } else {
      oss_decl << "// signal " << name << std::endl;
    }

    // special index where no real parameter is expected
    const int INDEX_USER = std::numeric_limits<int>::max() / 2;

    auto make_definition = [&](Options options) {
      logger(Log::LOG, "generating {} with except {}, output {}, nullable {}",
          func.c_id, (int)options.except, (int)options.output,
          (int)options.nullable);
      FunctionData def;
      def.c_callee = func.functionexp;

      {
        // enforce deduced function signature by cast
        // i.e. type cast to deduced function type
        std::string call_wrap_t = "call_wrap_t";
        std::string call_wrap_v = "call_wrap_v";
        def.pre_call.push_back(make_declaration(true, call_wrap_t, sig_ptype));
        def.pre_call.push_back(fmt::format("{} {} = ({}) {}", call_wrap_t,
            call_wrap_v, call_wrap_t, def.c_callee));
        def.c_callee = call_wrap_v;
      }

      // process parameters from last to first
      // that way we can track whether it is possible to specify a default
      // which is only acceptable if so for all later parameters
      // (or later ones are dropped from signature)
      // init defaultable status to start
      // trailing GError prevents default
      bool defaultable = options.except != opt_except::GERROR;

      // in case of callback;
      // check if some parameter is specified as closure (aka userdata)
      // as it may sadly be missing
      bool has_closure = false;
      if (kind == EL_CALLBACK) {
        for (auto it = paraminfo.rbegin(); it != paraminfo.rend(); ++it) {
          auto &&e = *it;
          if (e.second.closure >= 0) {
            has_closure = true;
            break;
          }
        }
      }

      auto ends_with = [](std::string const &value, std::string const &ending) {
        if (ending.size() > value.size())
          return false;
        return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
      };

      // if userdata/closure not specified for a closure,
      // accept last parameter as userdata based on name
      if (kind == EL_CALLBACK && !has_closure && paraminfo.size()) {
        auto &e = *paraminfo.rbegin();
        if (e.second.name == "data" || ends_with(e.second.name, "_data")) {
          e.second.closure = e.first;
          logger(Log::DEBUG, "{}; guessed userdata parameter {}", func.c_id,
              e.second.name);
        }
      }

      for (auto it = paraminfo.rbegin(); it != paraminfo.rend(); ++it) {
        auto &&e = *it;
        try {
          defaultable =
              process_param(e.first, e.second, options, def, defaultable);
        } catch (const skip &ex) {
          handle_skip(ex);
        }
      }

      // reverse some results
      std::reverse(def.cpp_outputs.begin(), def.cpp_outputs.end());
      std::reverse(def.transfers.begin(), def.transfers.end());

      // enforce deduced function signature by cast
      for (auto &&p : def.c_call) {
        auto it = paraminfo.find(p.first);
        if (it != paraminfo.end()) {
          auto &pinfo = it->second;
          p.second = fmt::format("({}) ({})", pinfo.ptype, p.second);
        }
      }

      // if marked throws, GError argument is not mentioned in argument list
      // deal with it here
      switch (options.except) {
        case opt_except::THROW:
        case opt_except::EXPECTED:
          def.pre_call.push_back("GError *error = NULL");
          def.c_call[def.c_call.size() + 10] = "&error";
          if (options.except == opt_except::THROW) {
            def.post_call.push_back("gi::check_error (error)");
          } else {
            // terminating ; added later
            def.post_call.push_back(
                "if (error) gi::detail::make_unexpected (error)");
          }
          break;
        case opt_except::GERROR: {
          // simulate optional output error parameter
          options.output = opt_output::PARAM;
          Parameter err;
          err.optional = true;
          err.direction = DIR_OUT;
          err.transfer = TRANSFER_FULL;
          err.name = "_error";
          parse_typeinfo("GLib.Error", err.tinfo);
          err.tinfo.ctype = "GError**";
          // process non-nullable to make sure there is no signature
          // ambiguity
          try {
            process_param_out(INDEX_USER, err, options, def, false);
          } catch (const skip &ex) {
            handle_skip(ex);
          }
        }
        default:
          break;
      }

      // process decl map into plain list
      def.cpp_decl_unfolded.clear();
      for (auto &&e : def.cpp_decl)
        def.cpp_decl_unfolded.emplace_back(e.second);

      return def;
    };

    // mild check on overload conflict
    // TODO improve check ??
    // what about defaultable arguments and overlap that causes
    std::set<std::vector<std::string>> signatures;

    // pass over to produce cpp declarations and content
    // generate each option
    FunctionData def;
    if (!check_errors()) {
      for (auto &&output : do_output) {
        for (auto &&except : do_except) {
          for (auto &&nullable : do_nullable) {
            // context for this option run
            Options options(except, output, nullable);
            def = make_definition(options);

            // only care about callbacks with (trailing) user_data
            auto last = paraminfo.end();
            --last;
            if (kind == EL_CALLBACK && found_user_data != last->first)
              errors.push_back("not a callback since no user_data");

            if (check_errors())
              return std::move(def);

            // duplicate could happen for a special boxed output
            // which is never returned in a tuple
            // normalize without const
            // conflict might otherwise occur e.g. in case of
            // (string output, string input nullable)

            auto cpp_sig = def.cpp_decl_unfolded;
            static const std::regex re_const("const ", std::regex::optimize);
            for (auto &d : cpp_sig)
              d = std::regex_replace(d, re_const, EMPTY);
            if (signatures.count(cpp_sig)) {
              logger(Log::DEBUG,
                  "discarding duplicate signature for " + func.c_id);
            } else {
              auto fname =
                  !callee && !func.shadows.empty() ? func.shadows : name;
              make_function(options, def, fname);
              // mark ok
              def.name = name;
              signatures.insert(cpp_sig);
            }
          }
        }
      }
    }

    return std::move(def);
  }

  FunctionDefinition process(const pt::ptree::value_type *entry,
      const std::vector<Parameter> *params, std::ostream &out,
      std::ostream &impl)
  {
    assert(!params || !entry);

    logger(Log::LOG, "processing " + func.c_id);
    try {
      // check if we made it all the way
      // remove callback from known types if failure
      bool success = kind == EL_CALLBACK ? false : true;
      ScopeGuard g([&] {
        if (!success)
          ctx.repo.discard(func.name);
      });

      if (entry) {
        collect_node(*entry);
      } else {
        int pno = 0;
        for (auto &p : *params) {
          int index = pno;
          if (p.direction == DIR_RETURN) {
            index = INDEX_RETURN;
          } else if (p.instance) {
            index = INDEX_INSTANCE;
          } else {
            ++pno;
          }
          paraminfo[index] = p;
        }
      }

      auto &&def = process();
      success = def.name.size() > 0;

      out << oss_decl.str() << std::endl;
      impl << oss_impl.str() << std::endl;
      return std::move(def);
    } catch (std::runtime_error &ex) {
      auto err = fmt::format("// FAILURE on {}; {}", func.c_id, ex.what());
      out << err << std::endl;
      impl << err << std::endl;
    }

    return FunctionDefinition();
  }
};

} // namespace

// process a function (or alike) and callback
//
// for a call;
// const on parameter is maintained, always added for string
// return value and output parameters always non-const
//
// callback; likewise (but not output params for now)
//
// klass: actual name of class being declared/defined (e.g. xxxBase)
// klasstype: intended target type of class (e.g. xxx), used in signal instance
// / constructor returns: last processed function definition (possibly only 1)
FunctionDefinition
process_element_function(GeneratorContext &_ctx, const std::string _ns,
    const pt::ptree::value_type &entry, std::ostream &out, std::ostream &impl,
    const std::string &klass, const std::string &klasstype,
    std::set<std::string> &deps)
{
  ElementFunction func;

  auto &kind = func.kind = entry.first;
  auto &node = entry.second;

  auto &name = func.name = get_name(node);
  auto c_name = (kind == EL_SIGNAL || kind == EL_VIRTUAL_METHOD)
                    ? name
                    : get_attribute(node,
                          kind == EL_CALLBACK ? AT_CTYPE : AT_CIDENTIFIER);
  func.c_id = (kind == EL_VIRTUAL_METHOD) ? klasstype + "::" + c_name : c_name;
  func.functionexp = kind == EL_VIRTUAL_METHOD
                         ? fmt::format("get_struct_()->{}", c_name)
                         : c_name;

  func.throws = get_attribute<int>(node, AT_THROWS, 0);
  func.shadows = get_attribute(node, AT_SHADOWS, "");

  FunctionGenerator gen(_ctx, _ns, func, klass, klasstype, deps);
  return gen.process(&entry, nullptr, out, impl);
}

FunctionDefinition
process_element_function(GeneratorContext &_ctx, const std::string _ns,
    const ElementFunction &func, const std::vector<Parameter> &params,
    std::ostream &out, std::ostream &impl, const std::string &klass,
    const std::string &klasstype, std::set<std::string> &deps)
{
  FunctionGenerator gen(_ctx, _ns, func, klass, klasstype, deps);
  return gen.process(nullptr, &params, out, impl);
}
