attr.h revision 12391:ceeca8b41e4b
1/*
2    pybind11/attr.h: Infrastructure for processing custom
3    type and function attributes
4
5    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
7    All rights reserved. Use of this source code is governed by a
8    BSD-style license that can be found in the LICENSE file.
9*/
10
11#pragma once
12
13#include "cast.h"
14
15NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
17/// \addtogroup annotations
18/// @{
19
20/// Annotation for methods
21struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
22
23/// Annotation for operators
24struct is_operator { };
25
26/// Annotation for parent scope
27struct scope { handle value; scope(const handle &s) : value(s) { } };
28
29/// Annotation for documentation
30struct doc { const char *value; doc(const char *value) : value(value) { } };
31
32/// Annotation for function names
33struct name { const char *value; name(const char *value) : value(value) { } };
34
35/// Annotation indicating that a function is an overload associated with a given "sibling"
36struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
37
38/// Annotation indicating that a class derives from another given type
39template <typename T> struct base {
40    PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
41    base() { }
42};
43
44/// Keep patient alive while nurse lives
45template <size_t Nurse, size_t Patient> struct keep_alive { };
46
47/// Annotation indicating that a class is involved in a multiple inheritance relationship
48struct multiple_inheritance { };
49
50/// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
51struct dynamic_attr { };
52
53/// Annotation which enables the buffer protocol for a type
54struct buffer_protocol { };
55
56/// Annotation which requests that a special metaclass is created for a type
57struct metaclass {
58    handle value;
59
60    PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
61    metaclass() {}
62
63    /// Override pybind11's default metaclass
64    explicit metaclass(handle value) : value(value) { }
65};
66
67/// Annotation that marks a class as local to the module:
68struct module_local { const bool value; constexpr module_local(bool v = true) : value(v) { } };
69
70/// Annotation to mark enums as an arithmetic type
71struct arithmetic { };
72
73/** \rst
74    A call policy which places one or more guard variables (``Ts...``) around the function call.
75
76    For example, this definition:
77
78    .. code-block:: cpp
79
80        m.def("foo", foo, py::call_guard<T>());
81
82    is equivalent to the following pseudocode:
83
84    .. code-block:: cpp
85
86        m.def("foo", [](args...) {
87            T scope_guard;
88            return foo(args...); // forwarded arguments
89        });
90 \endrst */
91template <typename... Ts> struct call_guard;
92
93template <> struct call_guard<> { using type = detail::void_type; };
94
95template <typename T>
96struct call_guard<T> {
97    static_assert(std::is_default_constructible<T>::value,
98                  "The guard type must be default constructible");
99
100    using type = T;
101};
102
103template <typename T, typename... Ts>
104struct call_guard<T, Ts...> {
105    struct type {
106        T guard{}; // Compose multiple guard types with left-to-right default-constructor order
107        typename call_guard<Ts...>::type next{};
108    };
109};
110
111/// @} annotations
112
113NAMESPACE_BEGIN(detail)
114/* Forward declarations */
115enum op_id : int;
116enum op_type : int;
117struct undefined_t;
118template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
119inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
120
121/// Internal data structure which holds metadata about a keyword argument
122struct argument_record {
123    const char *name;  ///< Argument name
124    const char *descr; ///< Human-readable version of the argument value
125    handle value;      ///< Associated Python object
126    bool convert : 1;  ///< True if the argument is allowed to convert when loading
127    bool none : 1;     ///< True if None is allowed when loading
128
129    argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
130        : name(name), descr(descr), value(value), convert(convert), none(none) { }
131};
132
133/// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
134struct function_record {
135    function_record()
136        : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
137          is_operator(false), has_args(false), has_kwargs(false), is_method(false) { }
138
139    /// Function name
140    char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
141
142    // User-specified documentation string
143    char *doc = nullptr;
144
145    /// Human-readable version of the function signature
146    char *signature = nullptr;
147
148    /// List of registered keyword arguments
149    std::vector<argument_record> args;
150
151    /// Pointer to lambda function which converts arguments and performs the actual call
152    handle (*impl) (function_call &) = nullptr;
153
154    /// Storage for the wrapped function pointer and captured data, if any
155    void *data[3] = { };
156
157    /// Pointer to custom destructor for 'data' (if needed)
158    void (*free_data) (function_record *ptr) = nullptr;
159
160    /// Return value policy associated with this function
161    return_value_policy policy = return_value_policy::automatic;
162
163    /// True if name == '__init__'
164    bool is_constructor : 1;
165
166    /// True if this is a new-style `__init__` defined in `detail/init.h`
167    bool is_new_style_constructor : 1;
168
169    /// True if this is a stateless function pointer
170    bool is_stateless : 1;
171
172    /// True if this is an operator (__add__), etc.
173    bool is_operator : 1;
174
175    /// True if the function has a '*args' argument
176    bool has_args : 1;
177
178    /// True if the function has a '**kwargs' argument
179    bool has_kwargs : 1;
180
181    /// True if this is a method
182    bool is_method : 1;
183
184    /// Number of arguments (including py::args and/or py::kwargs, if present)
185    std::uint16_t nargs;
186
187    /// Python method object
188    PyMethodDef *def = nullptr;
189
190    /// Python handle to the parent scope (a class or a module)
191    handle scope;
192
193    /// Python handle to the sibling function representing an overload chain
194    handle sibling;
195
196    /// Pointer to next overload
197    function_record *next = nullptr;
198};
199
200/// Special data structure which (temporarily) holds metadata about a bound class
201struct type_record {
202    PYBIND11_NOINLINE type_record()
203        : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false), module_local(false) { }
204
205    /// Handle to the parent scope
206    handle scope;
207
208    /// Name of the class
209    const char *name = nullptr;
210
211    // Pointer to RTTI type_info data structure
212    const std::type_info *type = nullptr;
213
214    /// How large is the underlying C++ type?
215    size_t type_size = 0;
216
217    /// How large is the type's holder?
218    size_t holder_size = 0;
219
220    /// The global operator new can be overridden with a class-specific variant
221    void *(*operator_new)(size_t) = ::operator new;
222
223    /// Function pointer to class_<..>::init_instance
224    void (*init_instance)(instance *, const void *) = nullptr;
225
226    /// Function pointer to class_<..>::dealloc
227    void (*dealloc)(detail::value_and_holder &) = nullptr;
228
229    /// List of base classes of the newly created type
230    list bases;
231
232    /// Optional docstring
233    const char *doc = nullptr;
234
235    /// Custom metaclass (optional)
236    handle metaclass;
237
238    /// Multiple inheritance marker
239    bool multiple_inheritance : 1;
240
241    /// Does the class manage a __dict__?
242    bool dynamic_attr : 1;
243
244    /// Does the class implement the buffer protocol?
245    bool buffer_protocol : 1;
246
247    /// Is the default (unique_ptr) holder type used?
248    bool default_holder : 1;
249
250    /// Is the class definition local to the module shared object?
251    bool module_local : 1;
252
253    PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) {
254        auto base_info = detail::get_type_info(base, false);
255        if (!base_info) {
256            std::string tname(base.name());
257            detail::clean_type_id(tname);
258            pybind11_fail("generic_type: type \"" + std::string(name) +
259                          "\" referenced unknown base type \"" + tname + "\"");
260        }
261
262        if (default_holder != base_info->default_holder) {
263            std::string tname(base.name());
264            detail::clean_type_id(tname);
265            pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
266                    (default_holder ? "does not have" : "has") +
267                    " a non-default holder type while its base \"" + tname + "\" " +
268                    (base_info->default_holder ? "does not" : "does"));
269        }
270
271        bases.append((PyObject *) base_info->type);
272
273        if (base_info->type->tp_dictoffset != 0)
274            dynamic_attr = true;
275
276        if (caster)
277            base_info->implicit_casts.emplace_back(type, caster);
278    }
279};
280
281inline function_call::function_call(function_record &f, handle p) :
282        func(f), parent(p) {
283    args.reserve(f.nargs);
284    args_convert.reserve(f.nargs);
285}
286
287/// Tag for a new-style `__init__` defined in `detail/init.h`
288struct is_new_style_constructor { };
289
290/**
291 * Partial template specializations to process custom attributes provided to
292 * cpp_function_ and class_. These are either used to initialize the respective
293 * fields in the type_record and function_record data structures or executed at
294 * runtime to deal with custom call policies (e.g. keep_alive).
295 */
296template <typename T, typename SFINAE = void> struct process_attribute;
297
298template <typename T> struct process_attribute_default {
299    /// Default implementation: do nothing
300    static void init(const T &, function_record *) { }
301    static void init(const T &, type_record *) { }
302    static void precall(function_call &) { }
303    static void postcall(function_call &, handle) { }
304};
305
306/// Process an attribute specifying the function's name
307template <> struct process_attribute<name> : process_attribute_default<name> {
308    static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
309};
310
311/// Process an attribute specifying the function's docstring
312template <> struct process_attribute<doc> : process_attribute_default<doc> {
313    static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
314};
315
316/// Process an attribute specifying the function's docstring (provided as a C-style string)
317template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
318    static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
319    static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
320};
321template <> struct process_attribute<char *> : process_attribute<const char *> { };
322
323/// Process an attribute indicating the function's return value policy
324template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
325    static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
326};
327
328/// Process an attribute which indicates that this is an overloaded function associated with a given sibling
329template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
330    static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
331};
332
333/// Process an attribute which indicates that this function is a method
334template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
335    static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
336};
337
338/// Process an attribute which indicates the parent scope of a method
339template <> struct process_attribute<scope> : process_attribute_default<scope> {
340    static void init(const scope &s, function_record *r) { r->scope = s.value; }
341};
342
343/// Process an attribute which indicates that this function is an operator
344template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
345    static void init(const is_operator &, function_record *r) { r->is_operator = true; }
346};
347
348template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> {
349    static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; }
350};
351
352/// Process a keyword argument attribute (*without* a default value)
353template <> struct process_attribute<arg> : process_attribute_default<arg> {
354    static void init(const arg &a, function_record *r) {
355        if (r->is_method && r->args.empty())
356            r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
357        r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
358    }
359};
360
361/// Process a keyword argument attribute (*with* a default value)
362template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
363    static void init(const arg_v &a, function_record *r) {
364        if (r->is_method && r->args.empty())
365            r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/);
366
367        if (!a.value) {
368#if !defined(NDEBUG)
369            std::string descr("'");
370            if (a.name) descr += std::string(a.name) + ": ";
371            descr += a.type + "'";
372            if (r->is_method) {
373                if (r->name)
374                    descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
375                else
376                    descr += " in method of '" + (std::string) str(r->scope) + "'";
377            } else if (r->name) {
378                descr += " in function '" + (std::string) r->name + "'";
379            }
380            pybind11_fail("arg(): could not convert default argument "
381                          + descr + " into a Python object (type not registered yet?)");
382#else
383            pybind11_fail("arg(): could not convert default argument "
384                          "into a Python object (type not registered yet?). "
385                          "Compile in debug mode for more information.");
386#endif
387        }
388        r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
389    }
390};
391
392/// Process a parent class attribute.  Single inheritance only (class_ itself already guarantees that)
393template <typename T>
394struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
395    static void init(const handle &h, type_record *r) { r->bases.append(h); }
396};
397
398/// Process a parent class attribute (deprecated, does not support multiple inheritance)
399template <typename T>
400struct process_attribute<base<T>> : process_attribute_default<base<T>> {
401    static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
402};
403
404/// Process a multiple inheritance attribute
405template <>
406struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
407    static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
408};
409
410template <>
411struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
412    static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
413};
414
415template <>
416struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
417    static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
418};
419
420template <>
421struct process_attribute<metaclass> : process_attribute_default<metaclass> {
422    static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
423};
424
425template <>
426struct process_attribute<module_local> : process_attribute_default<module_local> {
427    static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
428};
429
430/// Process an 'arithmetic' attribute for enums (does nothing here)
431template <>
432struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
433
434template <typename... Ts>
435struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { };
436
437/**
438 * Process a keep_alive call policy -- invokes keep_alive_impl during the
439 * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
440 * otherwise
441 */
442template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
443    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
444    static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
445    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
446    static void postcall(function_call &, handle) { }
447    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
448    static void precall(function_call &) { }
449    template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
450    static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
451};
452
453/// Recursively iterate over variadic template arguments
454template <typename... Args> struct process_attributes {
455    static void init(const Args&... args, function_record *r) {
456        int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
457        ignore_unused(unused);
458    }
459    static void init(const Args&... args, type_record *r) {
460        int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
461        ignore_unused(unused);
462    }
463    static void precall(function_call &call) {
464        int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
465        ignore_unused(unused);
466    }
467    static void postcall(function_call &call, handle fn_ret) {
468        int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
469        ignore_unused(unused);
470    }
471};
472
473template <typename T>
474using is_call_guard = is_instantiation<call_guard, T>;
475
476/// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
477template <typename... Extra>
478using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
479
480/// Check the number of named arguments at compile time
481template <typename... Extra,
482          size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
483          size_t self  = constexpr_sum(std::is_same<is_method, Extra>::value...)>
484constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
485    return named == 0 || (self + named + has_args + has_kwargs) == nargs;
486}
487
488NAMESPACE_END(detail)
489NAMESPACE_END(PYBIND11_NAMESPACE)
490