attr.h 26 KB

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