2 pybind11/attr.h: Infrastructure for processing custom
3 type and function attributes
5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
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.
15 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
17 /// \addtogroup annotations
20 /// Annotation for methods
21 struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
23 /// Annotation for operators
24 struct is_operator { };
26 /// Annotation for parent scope
27 struct scope { handle value; scope(const handle &s) : value(s) { } };
29 /// Annotation for documentation
30 struct doc { const char *value; doc(const char *value) : value(value) { } };
32 /// Annotation for function names
33 struct name { const char *value; name(const char *value) : value(value) { } };
35 /// Annotation indicating that a function is an overload associated with a given "sibling"
36 struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
38 /// Annotation indicating that a class derives from another given type
39 template <typename T> struct base {
40 PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
44 /// Keep patient alive while nurse lives
45 template <size_t Nurse, size_t Patient> struct keep_alive { };
47 /// Annotation indicating that a class is involved in a multiple inheritance relationship
48 struct multiple_inheritance { };
50 /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
51 struct dynamic_attr { };
53 /// Annotation which enables the buffer protocol for a type
54 struct buffer_protocol { };
56 /// Annotation which requests that a special metaclass is created for a type
60 PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
63 /// Override pybind11's default metaclass
64 explicit metaclass(handle value) : value(value) { }
67 /// Annotation that marks a class as local to the module:
68 struct module_local { const bool value; constexpr module_local(bool v = true) : value(v) { } };
70 /// Annotation to mark enums as an arithmetic type
71 struct arithmetic { };
74 A call policy which places one or more guard variables (``Ts...``) around the function call.
76 For example, this definition:
80 m.def("foo", foo, py::call_guard<T>());
82 is equivalent to the following pseudocode:
86 m.def("foo", [](args...) {
88 return foo(args...); // forwarded arguments
91 template <typename... Ts> struct call_guard;
93 template <> struct call_guard<> { using type = detail::void_type; };
96 struct call_guard<T> {
97 static_assert(std::is_default_constructible<T>::value,
98 "The guard type must be default constructible");
103 template <typename T, typename... Ts>
104 struct call_guard<T, Ts...> {
106 T guard{}; // Compose multiple guard types with left-to-right default-constructor order
107 typename call_guard<Ts...>::type next{};
113 NAMESPACE_BEGIN(detail)
114 /* Forward declarations */
118 template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
119 inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
121 /// Internal data structure which holds metadata about a keyword argument
122 struct 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
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) { }
133 /// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
134 struct 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) { }
140 char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
142 // User-specified documentation string
145 /// Human-readable version of the function signature
146 char *signature = nullptr;
148 /// List of registered keyword arguments
149 std::vector<argument_record> args;
151 /// Pointer to lambda function which converts arguments and performs the actual call
152 handle (*impl) (function_call &) = nullptr;
154 /// Storage for the wrapped function pointer and captured data, if any
157 /// Pointer to custom destructor for 'data' (if needed)
158 void (*free_data) (function_record *ptr) = nullptr;
160 /// Return value policy associated with this function
161 return_value_policy policy = return_value_policy::automatic;
163 /// True if name == '__init__'
164 bool is_constructor : 1;
166 /// True if this is a new-style `__init__` defined in `detail/init.h`
167 bool is_new_style_constructor : 1;
169 /// True if this is a stateless function pointer
170 bool is_stateless : 1;
172 /// True if this is an operator (__add__), etc.
173 bool is_operator : 1;
175 /// True if the function has a '*args' argument
178 /// True if the function has a '**kwargs' argument
181 /// True if this is a method
184 /// Number of arguments (including py::args and/or py::kwargs, if present)
187 /// Python method object
188 PyMethodDef *def = nullptr;
190 /// Python handle to the parent scope (a class or a module)
193 /// Python handle to the sibling function representing an overload chain
196 /// Pointer to next overload
197 function_record *next = nullptr;
200 /// Special data structure which (temporarily) holds metadata about a bound class
202 PYBIND11_NOINLINE type_record()
203 : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
204 default_holder(true), module_local(false) { }
206 /// Handle to the parent scope
209 /// Name of the class
210 const char *name = nullptr;
212 // Pointer to RTTI type_info data structure
213 const std::type_info *type = nullptr;
215 /// How large is the underlying C++ type?
216 size_t type_size = 0;
218 /// What is the alignment of the underlying C++ type?
219 size_t type_align = 0;
221 /// How large is the type's holder?
222 size_t holder_size = 0;
224 /// The global operator new can be overridden with a class-specific variant
225 void *(*operator_new)(size_t) = nullptr;
227 /// Function pointer to class_<..>::init_instance
228 void (*init_instance)(instance *, const void *) = nullptr;
230 /// Function pointer to class_<..>::dealloc
231 void (*dealloc)(detail::value_and_holder &) = nullptr;
233 /// List of base classes of the newly created type
236 /// Optional docstring
237 const char *doc = nullptr;
239 /// Custom metaclass (optional)
242 /// Multiple inheritance marker
243 bool multiple_inheritance : 1;
245 /// Does the class manage a __dict__?
246 bool dynamic_attr : 1;
248 /// Does the class implement the buffer protocol?
249 bool buffer_protocol : 1;
251 /// Is the default (unique_ptr) holder type used?
252 bool default_holder : 1;
254 /// Is the class definition local to the module shared object?
255 bool module_local : 1;
257 PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *)) {
258 auto base_info = detail::get_type_info(base, false);
260 std::string tname(base.name());
261 detail::clean_type_id(tname);
262 pybind11_fail("generic_type: type \"" + std::string(name) +
263 "\" referenced unknown base type \"" + tname + "\"");
266 if (default_holder != base_info->default_holder) {
267 std::string tname(base.name());
268 detail::clean_type_id(tname);
269 pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
270 (default_holder ? "does not have" : "has") +
271 " a non-default holder type while its base \"" + tname + "\" " +
272 (base_info->default_holder ? "does not" : "does"));
275 bases.append((PyObject *) base_info->type);
277 if (base_info->type->tp_dictoffset != 0)
281 base_info->implicit_casts.emplace_back(type, caster);
285 inline function_call::function_call(const function_record &f, handle p) :
287 args.reserve(f.nargs);
288 args_convert.reserve(f.nargs);
291 /// Tag for a new-style `__init__` defined in `detail/init.h`
292 struct is_new_style_constructor { };
295 * Partial template specializations to process custom attributes provided to
296 * cpp_function_ and class_. These are either used to initialize the respective
297 * fields in the type_record and function_record data structures or executed at
298 * runtime to deal with custom call policies (e.g. keep_alive).
300 template <typename T, typename SFINAE = void> struct process_attribute;
302 template <typename T> struct process_attribute_default {
303 /// Default implementation: do nothing
304 static void init(const T &, function_record *) { }
305 static void init(const T &, type_record *) { }
306 static void precall(function_call &) { }
307 static void postcall(function_call &, handle) { }
310 /// Process an attribute specifying the function's name
311 template <> struct process_attribute<name> : process_attribute_default<name> {
312 static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
315 /// Process an attribute specifying the function's docstring
316 template <> struct process_attribute<doc> : process_attribute_default<doc> {
317 static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
320 /// Process an attribute specifying the function's docstring (provided as a C-style string)
321 template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
322 static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
323 static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
325 template <> struct process_attribute<char *> : process_attribute<const char *> { };
327 /// Process an attribute indicating the function's return value policy
328 template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
329 static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
332 /// Process an attribute which indicates that this is an overloaded function associated with a given sibling
333 template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
334 static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
337 /// Process an attribute which indicates that this function is a method
338 template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
339 static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
342 /// Process an attribute which indicates the parent scope of a method
343 template <> struct process_attribute<scope> : process_attribute_default<scope> {
344 static void init(const scope &s, function_record *r) { r->scope = s.value; }
347 /// Process an attribute which indicates that this function is an operator
348 template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
349 static void init(const is_operator &, function_record *r) { r->is_operator = true; }
352 template <> struct process_attribute<is_new_style_constructor> : process_attribute_default<is_new_style_constructor> {
353 static void init(const is_new_style_constructor &, function_record *r) { r->is_new_style_constructor = true; }
356 /// Process a keyword argument attribute (*without* a default value)
357 template <> struct process_attribute<arg> : process_attribute_default<arg> {
358 static void init(const arg &a, function_record *r) {
359 if (r->is_method && r->args.empty())
360 r->args.emplace_back("self", nullptr, handle(), true /*convert*/, false /*none not allowed*/);
361 r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
365 /// Process a keyword argument attribute (*with* a default value)
366 template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
367 static void init(const arg_v &a, function_record *r) {
368 if (r->is_method && r->args.empty())
369 r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/, false /*none not allowed*/);
373 std::string descr("'");
374 if (a.name) descr += std::string(a.name) + ": ";
375 descr += a.type + "'";
378 descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
380 descr += " in method of '" + (std::string) str(r->scope) + "'";
381 } else if (r->name) {
382 descr += " in function '" + (std::string) r->name + "'";
384 pybind11_fail("arg(): could not convert default argument "
385 + descr + " into a Python object (type not registered yet?)");
387 pybind11_fail("arg(): could not convert default argument "
388 "into a Python object (type not registered yet?). "
389 "Compile in debug mode for more information.");
392 r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
396 /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that)
397 template <typename T>
398 struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
399 static void init(const handle &h, type_record *r) { r->bases.append(h); }
402 /// Process a parent class attribute (deprecated, does not support multiple inheritance)
403 template <typename T>
404 struct process_attribute<base<T>> : process_attribute_default<base<T>> {
405 static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
408 /// Process a multiple inheritance attribute
410 struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
411 static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
415 struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
416 static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
420 struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
421 static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
425 struct process_attribute<metaclass> : process_attribute_default<metaclass> {
426 static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
430 struct process_attribute<module_local> : process_attribute_default<module_local> {
431 static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
434 /// Process an 'arithmetic' attribute for enums (does nothing here)
436 struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
438 template <typename... Ts>
439 struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> { };
442 * Process a keep_alive call policy -- invokes keep_alive_impl during the
443 * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
446 template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
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 &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
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 &, handle) { }
451 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
452 static void precall(function_call &) { }
453 template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
454 static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
457 /// Recursively iterate over variadic template arguments
458 template <typename... Args> struct process_attributes {
459 static void init(const Args&... args, function_record *r) {
460 int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
461 ignore_unused(unused);
463 static void init(const Args&... args, type_record *r) {
464 int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
465 ignore_unused(unused);
467 static void precall(function_call &call) {
468 int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
469 ignore_unused(unused);
471 static void postcall(function_call &call, handle fn_ret) {
472 int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
473 ignore_unused(unused);
477 template <typename T>
478 using is_call_guard = is_instantiation<call_guard, T>;
480 /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
481 template <typename... Extra>
482 using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
484 /// Check the number of named arguments at compile time
485 template <typename... Extra,
486 size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
487 size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
488 constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
489 return named == 0 || (self + named + has_args + has_kwargs) == nargs;
492 NAMESPACE_END(detail)
493 NAMESPACE_END(PYBIND11_NAMESPACE)