attr.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /*
  2. pybind11/attr.h: Infrastructure for processing custom
  3. type and function attributes
  4. Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "detail/common.h"
  10. #include "cast.h"
  11. #include "trampoline_self_life_support.h"
  12. #include <functional>
  13. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  14. /// \addtogroup annotations
  15. /// @{
  16. /// Annotation for methods
  17. struct is_method {
  18. handle class_;
  19. explicit is_method(const handle &c) : class_(c) {}
  20. };
  21. /// Annotation for setters
  22. struct is_setter {};
  23. /// Annotation for operators
  24. struct is_operator {};
  25. /// Annotation for classes that cannot be subclassed
  26. struct is_final {};
  27. /// Annotation for parent scope
  28. struct scope {
  29. handle value;
  30. explicit scope(const handle &s) : value(s) {}
  31. };
  32. /// Annotation for documentation
  33. struct doc {
  34. const char *value;
  35. explicit doc(const char *value) : value(value) {}
  36. };
  37. /// Annotation for function names
  38. struct name {
  39. const char *value;
  40. explicit name(const char *value) : value(value) {}
  41. };
  42. /// Annotation indicating that a function is an overload associated with a given "sibling"
  43. struct sibling {
  44. handle value;
  45. explicit sibling(const handle &value) : value(value.ptr()) {}
  46. };
  47. /// Annotation indicating that a class derives from another given type
  48. template <typename T>
  49. struct base {
  50. PYBIND11_DEPRECATED(
  51. "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
  52. base() = default;
  53. };
  54. /// Keep patient alive while nurse lives
  55. template <size_t Nurse, size_t Patient>
  56. struct keep_alive {};
  57. /// Annotation indicating that a class is involved in a multiple inheritance relationship
  58. struct multiple_inheritance {};
  59. /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
  60. struct dynamic_attr {};
  61. /// Annotation which enables the buffer protocol for a type
  62. struct buffer_protocol {};
  63. /// Annotation which enables releasing the GIL before calling the C++ destructor of wrapped
  64. /// instances (pybind/pybind11#1446).
  65. struct release_gil_before_calling_cpp_dtor {};
  66. /// Annotation which requests that a special metaclass is created for a type
  67. struct metaclass {
  68. handle value;
  69. PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
  70. metaclass() = default;
  71. /// Override pybind11's default metaclass
  72. explicit metaclass(handle value) : value(value) {}
  73. };
  74. /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
  75. /// may be used to customize the Python type.
  76. ///
  77. /// The callback is invoked immediately before `PyType_Ready`.
  78. ///
  79. /// Note: This is an advanced interface, and uses of it may require changes to
  80. /// work with later versions of pybind11. You may wish to consult the
  81. /// implementation of `make_new_python_type` in `detail/classes.h` to understand
  82. /// the context in which the callback will be run.
  83. struct custom_type_setup {
  84. using callback = std::function<void(PyHeapTypeObject *heap_type)>;
  85. explicit custom_type_setup(callback value) : value(std::move(value)) {}
  86. callback value;
  87. };
  88. /// Annotation that marks a class as local to the module:
  89. struct module_local {
  90. const bool value;
  91. constexpr explicit module_local(bool v = true) : value(v) {}
  92. };
  93. /// Annotation to mark enums as an arithmetic type
  94. struct arithmetic {};
  95. /// Mark a function for addition at the beginning of the existing overload chain instead of the end
  96. struct prepend {};
  97. /** \rst
  98. A call policy which places one or more guard variables (``Ts...``) around the function call.
  99. For example, this definition:
  100. .. code-block:: cpp
  101. m.def("foo", foo, py::call_guard<T>());
  102. is equivalent to the following pseudocode:
  103. .. code-block:: cpp
  104. m.def("foo", [](args...) {
  105. T scope_guard;
  106. return foo(args...); // forwarded arguments
  107. });
  108. \endrst */
  109. template <typename... Ts>
  110. struct call_guard;
  111. template <>
  112. struct call_guard<> {
  113. using type = detail::void_type;
  114. };
  115. template <typename T>
  116. struct call_guard<T> {
  117. static_assert(std::is_default_constructible<T>::value,
  118. "The guard type must be default constructible");
  119. using type = T;
  120. };
  121. template <typename T, typename... Ts>
  122. struct call_guard<T, Ts...> {
  123. struct type {
  124. T guard{}; // Compose multiple guard types with left-to-right default-constructor order
  125. typename call_guard<Ts...>::type next{};
  126. };
  127. };
  128. /// @} annotations
  129. PYBIND11_NAMESPACE_BEGIN(detail)
  130. /* Forward declarations */
  131. enum op_id : int;
  132. enum op_type : int;
  133. struct undefined_t;
  134. template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
  135. struct op_;
  136. void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
  137. /// Internal data structure which holds metadata about a keyword argument
  138. struct argument_record {
  139. const char *name; ///< Argument name
  140. const char *descr; ///< Human-readable version of the argument value
  141. handle value; ///< Associated Python object
  142. bool convert : 1; ///< True if the argument is allowed to convert when loading
  143. bool none : 1; ///< True if None is allowed when loading
  144. argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
  145. : name(name), descr(descr), value(value), convert(convert), none(none) {}
  146. };
  147. /// Internal data structure which holds metadata about a bound function (signature, overloads,
  148. /// etc.)
  149. #define PYBIND11_DETAIL_FUNCTION_RECORD_ABI_ID "v1" // PLEASE UPDATE if the struct is changed.
  150. struct function_record {
  151. function_record()
  152. : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
  153. is_operator(false), is_method(false), is_setter(false), has_args(false),
  154. has_kwargs(false), prepend(false) {}
  155. /// Function name
  156. char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
  157. // User-specified documentation string
  158. char *doc = nullptr;
  159. /// Human-readable version of the function signature
  160. char *signature = nullptr;
  161. /// List of registered keyword arguments
  162. std::vector<argument_record> args;
  163. /// Pointer to lambda function which converts arguments and performs the actual call
  164. handle (*impl)(function_call &) = nullptr;
  165. /// Storage for the wrapped function pointer and captured data, if any
  166. void *data[3] = {};
  167. /// Pointer to custom destructor for 'data' (if needed)
  168. void (*free_data)(function_record *ptr) = nullptr;
  169. /// Return value policy associated with this function
  170. return_value_policy policy = return_value_policy::automatic;
  171. /// True if name == '__init__'
  172. bool is_constructor : 1;
  173. /// True if this is a new-style `__init__` defined in `detail/init.h`
  174. bool is_new_style_constructor : 1;
  175. /// True if this is a stateless function pointer
  176. bool is_stateless : 1;
  177. /// True if this is an operator (__add__), etc.
  178. bool is_operator : 1;
  179. /// True if this is a method
  180. bool is_method : 1;
  181. /// True if this is a setter
  182. bool is_setter : 1;
  183. /// True if the function has a '*args' argument
  184. bool has_args : 1;
  185. /// True if the function has a '**kwargs' argument
  186. bool has_kwargs : 1;
  187. /// True if this function is to be inserted at the beginning of the overload resolution chain
  188. bool prepend : 1;
  189. /// Number of arguments (including py::args and/or py::kwargs, if present)
  190. std::uint16_t nargs;
  191. /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
  192. /// argument or by a py::kw_only annotation.
  193. std::uint16_t nargs_pos = 0;
  194. /// Number of leading arguments (counted in `nargs`) that are positional-only
  195. std::uint16_t nargs_pos_only = 0;
  196. /// Python method object
  197. PyMethodDef *def = nullptr;
  198. /// Python handle to the parent scope (a class or a module)
  199. handle scope;
  200. /// Python handle to the sibling function representing an overload chain
  201. handle sibling;
  202. /// Pointer to next overload
  203. function_record *next = nullptr;
  204. };
  205. // The main purpose of this macro is to make it easy to pin-point the critically related code
  206. // sections.
  207. #define PYBIND11_ENSURE_PRECONDITION_FOR_FUNCTIONAL_H_PERFORMANCE_OPTIMIZATIONS(...) \
  208. static_assert( \
  209. __VA_ARGS__, \
  210. "Violation of precondition for pybind11/functional.h performance optimizations!")
  211. /// Special data structure which (temporarily) holds metadata about a bound class
  212. struct type_record {
  213. PYBIND11_NOINLINE type_record()
  214. : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
  215. module_local(false), is_final(false), release_gil_before_calling_cpp_dtor(false) {}
  216. /// Handle to the parent scope
  217. handle scope;
  218. /// Name of the class
  219. const char *name = nullptr;
  220. // Pointer to RTTI type_info data structure
  221. const std::type_info *type = nullptr;
  222. /// How large is the underlying C++ type?
  223. size_t type_size = 0;
  224. /// What is the alignment of the underlying C++ type?
  225. size_t type_align = 0;
  226. /// How large is the type's holder?
  227. size_t holder_size = 0;
  228. /// The global operator new can be overridden with a class-specific variant
  229. void *(*operator_new)(size_t) = nullptr;
  230. /// Function pointer to class_<..>::init_instance
  231. void (*init_instance)(instance *, const void *) = nullptr;
  232. /// Function pointer to class_<..>::dealloc
  233. void (*dealloc)(detail::value_and_holder &) = nullptr;
  234. /// Function pointer for casting alias class (aka trampoline) pointer to
  235. /// trampoline_self_life_support pointer. Sidesteps cross-DSO RTTI issues
  236. /// on platforms like macOS (see PR #5728 for details).
  237. get_trampoline_self_life_support_fn get_trampoline_self_life_support
  238. = [](void *) -> trampoline_self_life_support * { return nullptr; };
  239. /// List of base classes of the newly created type
  240. list bases;
  241. /// Optional docstring
  242. const char *doc = nullptr;
  243. /// Custom metaclass (optional)
  244. handle metaclass;
  245. /// Custom type setup.
  246. custom_type_setup::callback custom_type_setup_callback;
  247. /// Multiple inheritance marker
  248. bool multiple_inheritance : 1;
  249. /// Does the class manage a __dict__?
  250. bool dynamic_attr : 1;
  251. /// Does the class implement the buffer protocol?
  252. bool buffer_protocol : 1;
  253. /// Is the class definition local to the module shared object?
  254. bool module_local : 1;
  255. /// Is the class inheritable from python classes?
  256. bool is_final : 1;
  257. /// Solves pybind/pybind11#1446
  258. bool release_gil_before_calling_cpp_dtor : 1;
  259. holder_enum_t holder_enum_v = holder_enum_t::undefined;
  260. PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
  261. auto *base_info = detail::get_type_info(base, false);
  262. if (!base_info) {
  263. std::string tname(base.name());
  264. detail::clean_type_id(tname);
  265. pybind11_fail("generic_type: type \"" + std::string(name)
  266. + "\" referenced unknown base type \"" + tname + "\"");
  267. }
  268. // SMART_HOLDER_BAKEIN_FOLLOW_ON: Refine holder compatibility checks.
  269. bool this_has_unique_ptr_holder = (holder_enum_v == holder_enum_t::std_unique_ptr);
  270. bool base_has_unique_ptr_holder
  271. = (base_info->holder_enum_v == holder_enum_t::std_unique_ptr);
  272. if (this_has_unique_ptr_holder != base_has_unique_ptr_holder) {
  273. std::string tname(base.name());
  274. detail::clean_type_id(tname);
  275. pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
  276. + (this_has_unique_ptr_holder ? "does not have" : "has")
  277. + " a non-default holder type while its base \"" + tname + "\" "
  278. + (base_has_unique_ptr_holder ? "does not" : "does"));
  279. }
  280. bases.append((PyObject *) base_info->type);
  281. #ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET
  282. dynamic_attr |= base_info->type->tp_dictoffset != 0;
  283. #else
  284. dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;
  285. #endif
  286. if (caster) {
  287. base_info->implicit_casts.emplace_back(type, caster);
  288. }
  289. }
  290. };
  291. inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
  292. args.reserve(f.nargs);
  293. args_convert.reserve(f.nargs);
  294. }
  295. /// Tag for a new-style `__init__` defined in `detail/init.h`
  296. struct is_new_style_constructor {};
  297. /**
  298. * Partial template specializations to process custom attributes provided to
  299. * cpp_function_ and class_. These are either used to initialize the respective
  300. * fields in the type_record and function_record data structures or executed at
  301. * runtime to deal with custom call policies (e.g. keep_alive).
  302. */
  303. template <typename T, typename SFINAE = void>
  304. struct process_attribute;
  305. template <typename T>
  306. struct process_attribute_default {
  307. /// Default implementation: do nothing
  308. static void init(const T &, function_record *) {}
  309. static void init(const T &, type_record *) {}
  310. static void precall(function_call &) {}
  311. static void postcall(function_call &, handle) {}
  312. };
  313. /// Process an attribute specifying the function's name
  314. template <>
  315. struct process_attribute<name> : process_attribute_default<name> {
  316. static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
  317. };
  318. /// Process an attribute specifying the function's docstring
  319. template <>
  320. struct process_attribute<doc> : process_attribute_default<doc> {
  321. static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
  322. };
  323. /// Process an attribute specifying the function's docstring (provided as a C-style string)
  324. template <>
  325. struct process_attribute<const char *> : process_attribute_default<const char *> {
  326. static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
  327. static void init(const char *d, type_record *r) { r->doc = d; }
  328. };
  329. template <>
  330. struct process_attribute<char *> : process_attribute<const char *> {};
  331. /// Process an attribute indicating the function's return value policy
  332. template <>
  333. struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
  334. static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
  335. };
  336. /// Process an attribute which indicates that this is an overloaded function associated with a
  337. /// given sibling
  338. template <>
  339. struct process_attribute<sibling> : process_attribute_default<sibling> {
  340. static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
  341. };
  342. /// Process an attribute which indicates that this function is a method
  343. template <>
  344. struct process_attribute<is_method> : process_attribute_default<is_method> {
  345. static void init(const is_method &s, function_record *r) {
  346. r->is_method = true;
  347. r->scope = s.class_;
  348. }
  349. };
  350. /// Process an attribute which indicates that this function is a setter
  351. template <>
  352. struct process_attribute<is_setter> : process_attribute_default<is_setter> {
  353. static void init(const is_setter &, function_record *r) { r->is_setter = true; }
  354. };
  355. /// Process an attribute which indicates the parent scope of a method
  356. template <>
  357. struct process_attribute<scope> : process_attribute_default<scope> {
  358. static void init(const scope &s, function_record *r) { r->scope = s.value; }
  359. };
  360. /// Process an attribute which indicates that this function is an operator
  361. template <>
  362. struct process_attribute<is_operator> : process_attribute_default<is_operator> {
  363. static void init(const is_operator &, function_record *r) { r->is_operator = true; }
  364. };
  365. template <>
  366. struct process_attribute<is_new_style_constructor>
  367. : process_attribute_default<is_new_style_constructor> {
  368. static void init(const is_new_style_constructor &, function_record *r) {
  369. r->is_new_style_constructor = true;
  370. }
  371. };
  372. inline void check_kw_only_arg(const arg &a, function_record *r) {
  373. if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
  374. pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
  375. "args() argument");
  376. }
  377. }
  378. inline void append_self_arg_if_needed(function_record *r) {
  379. if (r->is_method && r->args.empty()) {
  380. r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
  381. }
  382. }
  383. /// Process a keyword argument attribute (*without* a default value)
  384. template <>
  385. struct process_attribute<arg> : process_attribute_default<arg> {
  386. static void init(const arg &a, function_record *r) {
  387. append_self_arg_if_needed(r);
  388. r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
  389. check_kw_only_arg(a, r);
  390. }
  391. };
  392. /// Process a keyword argument attribute (*with* a default value)
  393. template <>
  394. struct process_attribute<arg_v> : process_attribute_default<arg_v> {
  395. static void init(const arg_v &a, function_record *r) {
  396. if (r->is_method && r->args.empty()) {
  397. r->args.emplace_back(
  398. "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
  399. }
  400. if (!a.value) {
  401. #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
  402. std::string descr("'");
  403. if (a.name) {
  404. descr += std::string(a.name) + ": ";
  405. }
  406. descr += a.type + "'";
  407. if (r->is_method) {
  408. if (r->name) {
  409. descr += " in method '" + (std::string) str(r->scope) + "."
  410. + (std::string) r->name + "'";
  411. } else {
  412. descr += " in method of '" + (std::string) str(r->scope) + "'";
  413. }
  414. } else if (r->name) {
  415. descr += " in function '" + (std::string) r->name + "'";
  416. }
  417. pybind11_fail("arg(): could not convert default argument " + descr
  418. + " into a Python object (type not registered yet?)");
  419. #else
  420. pybind11_fail("arg(): could not convert default argument "
  421. "into a Python object (type not registered yet?). "
  422. "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
  423. "more information.");
  424. #endif
  425. }
  426. r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
  427. check_kw_only_arg(a, r);
  428. }
  429. };
  430. /// Process a keyword-only-arguments-follow pseudo argument
  431. template <>
  432. struct process_attribute<kw_only> : process_attribute_default<kw_only> {
  433. static void init(const kw_only &, function_record *r) {
  434. append_self_arg_if_needed(r);
  435. if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
  436. pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
  437. "argument location (or omit kw_only() entirely)");
  438. }
  439. r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
  440. }
  441. };
  442. /// Process a positional-only-argument maker
  443. template <>
  444. struct process_attribute<pos_only> : process_attribute_default<pos_only> {
  445. static void init(const pos_only &, function_record *r) {
  446. append_self_arg_if_needed(r);
  447. r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
  448. if (r->nargs_pos_only > r->nargs_pos) {
  449. pybind11_fail("pos_only(): cannot follow a py::args() argument");
  450. }
  451. // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
  452. }
  453. };
  454. /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
  455. /// that)
  456. template <typename T>
  457. struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
  458. : process_attribute_default<handle> {
  459. static void init(const handle &h, type_record *r) { r->bases.append(h); }
  460. };
  461. /// Process a parent class attribute (deprecated, does not support multiple inheritance)
  462. template <typename T>
  463. struct process_attribute<base<T>> : process_attribute_default<base<T>> {
  464. static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
  465. };
  466. /// Process a multiple inheritance attribute
  467. template <>
  468. struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
  469. static void init(const multiple_inheritance &, type_record *r) {
  470. r->multiple_inheritance = true;
  471. }
  472. };
  473. template <>
  474. struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
  475. static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
  476. };
  477. template <>
  478. struct process_attribute<custom_type_setup> {
  479. static void init(const custom_type_setup &value, type_record *r) {
  480. r->custom_type_setup_callback = value.value;
  481. }
  482. };
  483. template <>
  484. struct process_attribute<is_final> : process_attribute_default<is_final> {
  485. static void init(const is_final &, type_record *r) { r->is_final = true; }
  486. };
  487. template <>
  488. struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
  489. static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
  490. };
  491. template <>
  492. struct process_attribute<metaclass> : process_attribute_default<metaclass> {
  493. static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
  494. };
  495. template <>
  496. struct process_attribute<module_local> : process_attribute_default<module_local> {
  497. static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
  498. };
  499. template <>
  500. struct process_attribute<release_gil_before_calling_cpp_dtor>
  501. : process_attribute_default<release_gil_before_calling_cpp_dtor> {
  502. static void init(const release_gil_before_calling_cpp_dtor &, type_record *r) {
  503. r->release_gil_before_calling_cpp_dtor = true;
  504. }
  505. };
  506. /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
  507. template <>
  508. struct process_attribute<prepend> : process_attribute_default<prepend> {
  509. static void init(const prepend &, function_record *r) { r->prepend = true; }
  510. };
  511. /// Process an 'arithmetic' attribute for enums (does nothing here)
  512. template <>
  513. struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
  514. template <typename... Ts>
  515. struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
  516. /**
  517. * Process a keep_alive call policy -- invokes keep_alive_impl during the
  518. * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
  519. * otherwise
  520. */
  521. template <size_t Nurse, size_t Patient>
  522. struct process_attribute<keep_alive<Nurse, Patient>>
  523. : public process_attribute_default<keep_alive<Nurse, Patient>> {
  524. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
  525. static void precall(function_call &call) {
  526. keep_alive_impl(Nurse, Patient, call, handle());
  527. }
  528. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
  529. static void postcall(function_call &, handle) {}
  530. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
  531. static void precall(function_call &) {}
  532. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
  533. static void postcall(function_call &call, handle ret) {
  534. keep_alive_impl(Nurse, Patient, call, ret);
  535. }
  536. };
  537. /// Recursively iterate over variadic template arguments
  538. template <typename... Args>
  539. struct process_attributes {
  540. static void init(const Args &...args, function_record *r) {
  541. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
  542. PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
  543. using expander = int[];
  544. (void) expander{
  545. 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
  546. }
  547. static void init(const Args &...args, type_record *r) {
  548. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
  549. PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
  550. using expander = int[];
  551. (void) expander{0,
  552. (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
  553. }
  554. static void precall(function_call &call) {
  555. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
  556. using expander = int[];
  557. (void) expander{0,
  558. (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
  559. }
  560. static void postcall(function_call &call, handle fn_ret) {
  561. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
  562. PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
  563. using expander = int[];
  564. (void) expander{
  565. 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
  566. }
  567. };
  568. template <typename T>
  569. using is_call_guard = is_instantiation<call_guard, T>;
  570. /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
  571. template <typename... Extra>
  572. using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
  573. /// Check the number of named arguments at compile time
  574. template <typename... Extra,
  575. size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
  576. size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
  577. constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
  578. PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
  579. return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
  580. }
  581. PYBIND11_NAMESPACE_END(detail)
  582. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)