Blame external/pybind11/include/pybind11/detail/init.h

Packit 534379
/*
Packit 534379
    pybind11/detail/init.h: init factory function implementation and support code.
Packit 534379
Packit 534379
    Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>
Packit 534379
Packit 534379
    All rights reserved. Use of this source code is governed by a
Packit 534379
    BSD-style license that can be found in the LICENSE file.
Packit 534379
*/
Packit 534379
Packit 534379
#pragma once
Packit 534379
Packit 534379
#include "class.h"
Packit 534379
Packit 534379
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
Packit 534379
NAMESPACE_BEGIN(detail)
Packit 534379
Packit 534379
template <>
Packit 534379
class type_caster<value_and_holder> {
Packit 534379
public:
Packit 534379
    bool load(handle h, bool) {
Packit 534379
        value = reinterpret_cast<value_and_holder *>(h.ptr());
Packit 534379
        return true;
Packit 534379
    }
Packit 534379
Packit 534379
    template <typename> using cast_op_type = value_and_holder &;
Packit 534379
    operator value_and_holder &() { return *value; }
Packit 534379
    static constexpr auto name = _<value_and_holder>();
Packit 534379
Packit 534379
private:
Packit 534379
    value_and_holder *value = nullptr;
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_BEGIN(initimpl)
Packit 534379
Packit 534379
inline void no_nullptr(void *ptr) {
Packit 534379
    if (!ptr) throw type_error("pybind11::init(): factory function returned nullptr");
Packit 534379
}
Packit 534379
Packit 534379
// Implementing functions for all forms of py::init<...> and py::init(...)
Packit 534379
template <typename Class> using Cpp = typename Class::type;
Packit 534379
template <typename Class> using Alias = typename Class::type_alias;
Packit 534379
template <typename Class> using Holder = typename Class::holder_type;
Packit 534379
Packit 534379
template <typename Class> using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
Packit 534379
Packit 534379
// Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
Packit 534379
template <typename Class, enable_if_t<Class::has_alias, int> = 0>
Packit 534379
bool is_alias(Cpp<Class> *ptr) {
Packit 534379
    return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
Packit 534379
}
Packit 534379
// Failing fallback version of the above for a no-alias class (always returns false)
Packit 534379
template <typename /*Class*/>
Packit 534379
constexpr bool is_alias(void *) { return false; }
Packit 534379
Packit 534379
// Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
Packit 534379
// back to brace aggregate initiailization so that for aggregate initialization can be used with
Packit 534379
// py::init, e.g.  `py::init<int, int>` to initialize a `struct T { int a; int b; }`.  For
Packit 534379
// non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
Packit 534379
// works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
Packit 534379
template <typename Class, typename... Args, detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
Packit 534379
inline Class *construct_or_initialize(Args &&...args) { return new Class(std::forward<Args>(args)...); }
Packit 534379
template <typename Class, typename... Args, detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
Packit 534379
inline Class *construct_or_initialize(Args &&...args) { return new Class{std::forward<Args>(args)...}; }
Packit 534379
Packit 534379
// Attempts to constructs an alias using a `Alias(Cpp &&)` constructor.  This allows types with
Packit 534379
// an alias to provide only a single Cpp factory function as long as the Alias can be
Packit 534379
// constructed from an rvalue reference of the base Cpp type.  This means that Alias classes
Packit 534379
// can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
Packit 534379
// inherit all the base class constructors.
Packit 534379
template <typename Class>
Packit 534379
void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
Packit 534379
                              value_and_holder &v_h, Cpp<Class> &&base) {
Packit 534379
    v_h.value_ptr() = new Alias<Class>(std::move(base));
Packit 534379
}
Packit 534379
template <typename Class>
Packit 534379
[[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
Packit 534379
                                           value_and_holder &, Cpp<Class> &&) {
Packit 534379
    throw type_error("pybind11::init(): unable to convert returned instance to required "
Packit 534379
                     "alias class: no `Alias<Class>(Class &&)` constructor available");
Packit 534379
}
Packit 534379
Packit 534379
// Error-generating fallback for factories that don't match one of the below construction
Packit 534379
// mechanisms.
Packit 534379
template <typename Class>
Packit 534379
void construct(...) {
Packit 534379
    static_assert(!std::is_same<Class, Class>::value /* always false */,
Packit 534379
            "pybind11::init(): init function must return a compatible pointer, "
Packit 534379
            "holder, or value");
Packit 534379
}
Packit 534379
Packit 534379
// Pointer return v1: the factory function returns a class pointer for a registered class.
Packit 534379
// If we don't need an alias (because this class doesn't have one, or because the final type is
Packit 534379
// inherited on the Python side) we can simply take over ownership.  Otherwise we need to try to
Packit 534379
// construct an Alias from the returned base instance.
Packit 534379
template <typename Class>
Packit 534379
void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
Packit 534379
    no_nullptr(ptr);
Packit 534379
    if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
Packit 534379
        // We're going to try to construct an alias by moving the cpp type.  Whether or not
Packit 534379
        // that succeeds, we still need to destroy the original cpp pointer (either the
Packit 534379
        // moved away leftover, if the alias construction works, or the value itself if we
Packit 534379
        // throw an error), but we can't just call `delete ptr`: it might have a special
Packit 534379
        // deleter, or might be shared_from_this.  So we construct a holder around it as if
Packit 534379
        // it was a normal instance, then steal the holder away into a local variable; thus
Packit 534379
        // the holder and destruction happens when we leave the C++ scope, and the holder
Packit 534379
        // class gets to handle the destruction however it likes.
Packit 534379
        v_h.value_ptr() = ptr;
Packit 534379
        v_h.set_instance_registered(true); // To prevent init_instance from registering it
Packit 534379
        v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
Packit 534379
        Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
Packit 534379
        v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
Packit 534379
        v_h.set_instance_registered(false);
Packit 534379
Packit 534379
        construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
Packit 534379
    } else {
Packit 534379
        // Otherwise the type isn't inherited, so we don't need an Alias
Packit 534379
        v_h.value_ptr() = ptr;
Packit 534379
    }
Packit 534379
}
Packit 534379
Packit 534379
// Pointer return v2: a factory that always returns an alias instance ptr.  We simply take over
Packit 534379
// ownership of the pointer.
Packit 534379
template <typename Class, enable_if_t<Class::has_alias, int> = 0>
Packit 534379
void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
Packit 534379
    no_nullptr(alias_ptr);
Packit 534379
    v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
Packit 534379
}
Packit 534379
Packit 534379
// Holder return: copy its pointer, and move or copy the returned holder into the new instance's
Packit 534379
// holder.  This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
Packit 534379
// derived type (through those holder's implicit conversion from derived class holder constructors).
Packit 534379
template <typename Class>
Packit 534379
void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
Packit 534379
    auto *ptr = holder_helper<Holder<Class>>::get(holder);
Packit 534379
    // If we need an alias, check that the held pointer is actually an alias instance
Packit 534379
    if (Class::has_alias && need_alias && !is_alias<Class>(ptr))
Packit 534379
        throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
Packit 534379
                         "is not an alias instance");
Packit 534379
Packit 534379
    v_h.value_ptr() = ptr;
Packit 534379
    v_h.type->init_instance(v_h.inst, &holder);
Packit 534379
}
Packit 534379
Packit 534379
// return-by-value version 1: returning a cpp class by value.  If the class has an alias and an
Packit 534379
// alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
Packit 534379
// the alias from the base when needed (i.e. because of Python-side inheritance).  When we don't
Packit 534379
// need it, we simply move-construct the cpp value into a new instance.
Packit 534379
template <typename Class>
Packit 534379
void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
Packit 534379
    static_assert(std::is_move_constructible<Cpp<Class>>::value,
Packit 534379
        "pybind11::init() return-by-value factory function requires a movable class");
Packit 534379
    if (Class::has_alias && need_alias)
Packit 534379
        construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
Packit 534379
    else
Packit 534379
        v_h.value_ptr() = new Cpp<Class>(std::move(result));
Packit 534379
}
Packit 534379
Packit 534379
// return-by-value version 2: returning a value of the alias type itself.  We move-construct an
Packit 534379
// Alias instance (even if no the python-side inheritance is involved).  The is intended for
Packit 534379
// cases where Alias initialization is always desired.
Packit 534379
template <typename Class>
Packit 534379
void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
Packit 534379
    static_assert(std::is_move_constructible<Alias<Class>>::value,
Packit 534379
        "pybind11::init() return-by-alias-value factory function requires a movable alias class");
Packit 534379
    v_h.value_ptr() = new Alias<Class>(std::move(result));
Packit 534379
}
Packit 534379
Packit 534379
// Implementing class for py::init<...>()
Packit 534379
template <typename... Args>
Packit 534379
struct constructor {
Packit 534379
    template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
Packit 534379
    static void execute(Class &cl, const Extra&... extra) {
Packit 534379
        cl.def("__init__", [](value_and_holder &v_h, Args... args) {
Packit 534379
            v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
Packit 534379
    template 
Packit 534379
              enable_if_t
Packit 534379
                          std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
Packit 534379
    static void execute(Class &cl, const Extra&... extra) {
Packit 534379
        cl.def("__init__", [](value_and_holder &v_h, Args... args) {
Packit 534379
            if (Py_TYPE(v_h.inst) == v_h.type->type)
Packit 534379
                v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
Packit 534379
            else
Packit 534379
                v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
Packit 534379
    template 
Packit 534379
              enable_if_t
Packit 534379
                          !std::is_constructible<Cpp<Class>, Args...>::value, int> = 0>
Packit 534379
    static void execute(Class &cl, const Extra&... extra) {
Packit 534379
        cl.def("__init__", [](value_and_holder &v_h, Args... args) {
Packit 534379
            v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
// Implementing class for py::init_alias<...>()
Packit 534379
template <typename... Args> struct alias_constructor {
Packit 534379
    template 
Packit 534379
              enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int> = 0>
Packit 534379
    static void execute(Class &cl, const Extra&... extra) {
Packit 534379
        cl.def("__init__", [](value_and_holder &v_h, Args... args) {
Packit 534379
            v_h.value_ptr() = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
// Implementation class for py::init(Func) and py::init(Func, AliasFunc)
Packit 534379
template 
Packit 534379
          typename = function_signature_t<CFunc>, typename = function_signature_t<AFunc>>
Packit 534379
struct factory;
Packit 534379
Packit 534379
// Specialization for py::init(Func)
Packit 534379
template <typename Func, typename Return, typename... Args>
Packit 534379
struct factory<Func, void_type (*)(), Return(Args...)> {
Packit 534379
    remove_reference_t<Func> class_factory;
Packit 534379
Packit 534379
    factory(Func &&f) : class_factory(std::forward<Func>(f)) { }
Packit 534379
Packit 534379
    // The given class either has no alias or has no separate alias factory;
Packit 534379
    // this always constructs the class itself.  If the class is registered with an alias
Packit 534379
    // type and an alias instance is needed (i.e. because the final type is a Python class
Packit 534379
    // inheriting from the C++ type) the returned value needs to either already be an alias
Packit 534379
    // instance, or the alias needs to be constructible from a `Class &&` argument.
Packit 534379
    template <typename Class, typename... Extra>
Packit 534379
    void execute(Class &cl, const Extra &...extra) && {
Packit 534379
        #if defined(PYBIND11_CPP14)
Packit 534379
        cl.def("__init__", [func = std::move(class_factory)]
Packit 534379
        #else
Packit 534379
        auto &func = class_factory;
Packit 534379
        cl.def("__init__", [func]
Packit 534379
        #endif
Packit 534379
        (value_and_holder &v_h, Args... args) {
Packit 534379
            construct<Class>(v_h, func(std::forward<Args>(args)...),
Packit 534379
                             Py_TYPE(v_h.inst) != v_h.type->type);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
// Specialization for py::init(Func, AliasFunc)
Packit 534379
template 
Packit 534379
          typename CReturn, typename... CArgs, typename AReturn, typename... AArgs>
Packit 534379
struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
Packit 534379
    static_assert(sizeof...(CArgs) == sizeof...(AArgs),
Packit 534379
                  "pybind11::init(class_factory, alias_factory): class and alias factories "
Packit 534379
                  "must have identical argument signatures");
Packit 534379
    static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
Packit 534379
                  "pybind11::init(class_factory, alias_factory): class and alias factories "
Packit 534379
                  "must have identical argument signatures");
Packit 534379
Packit 534379
    remove_reference_t<CFunc> class_factory;
Packit 534379
    remove_reference_t<AFunc> alias_factory;
Packit 534379
Packit 534379
    factory(CFunc &&c, AFunc &&a)
Packit 534379
        : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) { }
Packit 534379
Packit 534379
    // The class factory is called when the `self` type passed to `__init__` is the direct
Packit 534379
    // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
Packit 534379
    template <typename Class, typename... Extra>
Packit 534379
    void execute(Class &cl, const Extra&... extra) && {
Packit 534379
        static_assert(Class::has_alias, "The two-argument version of `py::init()` can "
Packit 534379
                                        "only be used if the class has an alias");
Packit 534379
        #if defined(PYBIND11_CPP14)
Packit 534379
        cl.def("__init__", [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
Packit 534379
        #else
Packit 534379
        auto &class_func = class_factory;
Packit 534379
        auto &alias_func = alias_factory;
Packit 534379
        cl.def("__init__", [class_func, alias_func]
Packit 534379
        #endif
Packit 534379
        (value_and_holder &v_h, CArgs... args) {
Packit 534379
            if (Py_TYPE(v_h.inst) == v_h.type->type)
Packit 534379
                // If the instance type equals the registered type we don't have inheritance, so
Packit 534379
                // don't need the alias and can construct using the class function:
Packit 534379
                construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
Packit 534379
            else
Packit 534379
                construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
/// Set just the C++ state. Same as `__init__`.
Packit 534379
template <typename Class, typename T>
Packit 534379
void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
Packit 534379
    construct<Class>(v_h, std::forward<T>(result), need_alias);
Packit 534379
}
Packit 534379
Packit 534379
/// Set both the C++ and Python states
Packit 534379
template 
Packit 534379
          enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
Packit 534379
void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
Packit 534379
    construct<Class>(v_h, std::move(result.first), need_alias);
Packit 534379
    setattr((PyObject *) v_h.inst, "__dict__", result.second);
Packit 534379
}
Packit 534379
Packit 534379
/// Implementation for py::pickle(GetState, SetState)
Packit 534379
template 
Packit 534379
          typename = function_signature_t<Get>, typename = function_signature_t<Set>>
Packit 534379
struct pickle_factory;
Packit 534379
Packit 534379
template 
Packit 534379
          typename RetState, typename Self, typename NewInstance, typename ArgState>
Packit 534379
struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
Packit 534379
    static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
Packit 534379
                  "The type returned by `__getstate__` must be the same "
Packit 534379
                  "as the argument accepted by `__setstate__`");
Packit 534379
Packit 534379
    remove_reference_t<Get> get;
Packit 534379
    remove_reference_t<Set> set;
Packit 534379
Packit 534379
    pickle_factory(Get get, Set set)
Packit 534379
        : get(std::forward<Get>(get)), set(std::forward<Set>(set)) { }
Packit 534379
Packit 534379
    template <typename Class, typename... Extra>
Packit 534379
    void execute(Class &cl, const Extra &...extra) && {
Packit 534379
        cl.def("__getstate__", std::move(get));
Packit 534379
Packit 534379
#if defined(PYBIND11_CPP14)
Packit 534379
        cl.def("__setstate__", [func = std::move(set)]
Packit 534379
#else
Packit 534379
        auto &func = set;
Packit 534379
        cl.def("__setstate__", [func]
Packit 534379
#endif
Packit 534379
        (value_and_holder &v_h, ArgState state) {
Packit 534379
            setstate<Class>(v_h, func(std::forward<ArgState>(state)),
Packit 534379
                            Py_TYPE(v_h.inst) != v_h.type->type);
Packit 534379
        }, is_new_style_constructor(), extra...);
Packit 534379
    }
Packit 534379
};
Packit 534379
Packit 534379
NAMESPACE_END(initimpl)
Packit 534379
NAMESPACE_END(detail)
Packit 534379
NAMESPACE_END(pybind11)