You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

422 lines
16 KiB

8 years ago
  1. /*
  2. pybind11/pybind11.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 "cast.h"
  10. NAMESPACE_BEGIN(pybind11)
  11. /// \addtogroup annotations
  12. /// @{
  13. /// Annotation for methods
  14. struct is_method { handle class_; is_method(const handle &c) : class_(c) { } };
  15. /// Annotation for operators
  16. struct is_operator { };
  17. /// Annotation for parent scope
  18. struct scope { handle value; scope(const handle &s) : value(s) { } };
  19. /// Annotation for documentation
  20. struct doc { const char *value; doc(const char *value) : value(value) { } };
  21. /// Annotation for function names
  22. struct name { const char *value; name(const char *value) : value(value) { } };
  23. /// Annotation indicating that a function is an overload associated with a given "sibling"
  24. struct sibling { handle value; sibling(const handle &value) : value(value.ptr()) { } };
  25. /// Annotation indicating that a class derives from another given type
  26. template <typename T> struct base {
  27. PYBIND11_DEPRECATED("base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
  28. base() { }
  29. };
  30. /// Keep patient alive while nurse lives
  31. template <size_t Nurse, size_t Patient> struct keep_alive { };
  32. /// Annotation indicating that a class is involved in a multiple inheritance relationship
  33. struct multiple_inheritance { };
  34. /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
  35. struct dynamic_attr { };
  36. /// Annotation which enables the buffer protocol for a type
  37. struct buffer_protocol { };
  38. /// Annotation which requests that a special metaclass is created for a type
  39. struct metaclass {
  40. handle value;
  41. PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
  42. metaclass() = default;
  43. /// Override pybind11's default metaclass
  44. explicit metaclass(handle value) : value(value) { }
  45. };
  46. /// Annotation to mark enums as an arithmetic type
  47. struct arithmetic { };
  48. /// @} annotations
  49. NAMESPACE_BEGIN(detail)
  50. /* Forward declarations */
  51. enum op_id : int;
  52. enum op_type : int;
  53. struct undefined_t;
  54. template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t> struct op_;
  55. template <typename... Args> struct init;
  56. template <typename... Args> struct init_alias;
  57. inline void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
  58. /// Internal data structure which holds metadata about a keyword argument
  59. struct argument_record {
  60. const char *name; ///< Argument name
  61. const char *descr; ///< Human-readable version of the argument value
  62. handle value; ///< Associated Python object
  63. bool convert : 1; ///< True if the argument is allowed to convert when loading
  64. argument_record(const char *name, const char *descr, handle value, bool convert)
  65. : name(name), descr(descr), value(value), convert(convert) { }
  66. };
  67. /// Internal data structure which holds metadata about a bound function (signature, overloads, etc.)
  68. struct function_record {
  69. function_record()
  70. : is_constructor(false), is_stateless(false), is_operator(false),
  71. has_args(false), has_kwargs(false), is_method(false) { }
  72. /// Function name
  73. char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
  74. // User-specified documentation string
  75. char *doc = nullptr;
  76. /// Human-readable version of the function signature
  77. char *signature = nullptr;
  78. /// List of registered keyword arguments
  79. std::vector<argument_record> args;
  80. /// Pointer to lambda function which converts arguments and performs the actual call
  81. handle (*impl) (function_call &) = nullptr;
  82. /// Storage for the wrapped function pointer and captured data, if any
  83. void *data[3] = { };
  84. /// Pointer to custom destructor for 'data' (if needed)
  85. void (*free_data) (function_record *ptr) = nullptr;
  86. /// Return value policy associated with this function
  87. return_value_policy policy = return_value_policy::automatic;
  88. /// True if name == '__init__'
  89. bool is_constructor : 1;
  90. /// True if this is a stateless function pointer
  91. bool is_stateless : 1;
  92. /// True if this is an operator (__add__), etc.
  93. bool is_operator : 1;
  94. /// True if the function has a '*args' argument
  95. bool has_args : 1;
  96. /// True if the function has a '**kwargs' argument
  97. bool has_kwargs : 1;
  98. /// True if this is a method
  99. bool is_method : 1;
  100. /// Number of arguments (including py::args and/or py::kwargs, if present)
  101. std::uint16_t nargs;
  102. /// Python method object
  103. PyMethodDef *def = nullptr;
  104. /// Python handle to the parent scope (a class or a module)
  105. handle scope;
  106. /// Python handle to the sibling function representing an overload chain
  107. handle sibling;
  108. /// Pointer to next overload
  109. function_record *next = nullptr;
  110. };
  111. /// Special data structure which (temporarily) holds metadata about a bound class
  112. struct type_record {
  113. PYBIND11_NOINLINE type_record()
  114. : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false) { }
  115. /// Handle to the parent scope
  116. handle scope;
  117. /// Name of the class
  118. const char *name = nullptr;
  119. // Pointer to RTTI type_info data structure
  120. const std::type_info *type = nullptr;
  121. /// How large is the underlying C++ type?
  122. size_t type_size = 0;
  123. /// How large is pybind11::instance<type>?
  124. size_t instance_size = 0;
  125. /// The global operator new can be overridden with a class-specific variant
  126. void *(*operator_new)(size_t) = ::operator new;
  127. /// Function pointer to class_<..>::init_holder
  128. void (*init_holder)(PyObject *, const void *) = nullptr;
  129. /// Function pointer to class_<..>::dealloc
  130. void (*dealloc)(PyObject *) = nullptr;
  131. /// List of base classes of the newly created type
  132. list bases;
  133. /// Optional docstring
  134. const char *doc = nullptr;
  135. /// Custom metaclass (optional)
  136. handle metaclass;
  137. /// Multiple inheritance marker
  138. bool multiple_inheritance : 1;
  139. /// Does the class manage a __dict__?
  140. bool dynamic_attr : 1;
  141. /// Does the class implement the buffer protocol?
  142. bool buffer_protocol : 1;
  143. /// Is the default (unique_ptr) holder type used?
  144. bool default_holder : 1;
  145. PYBIND11_NOINLINE void add_base(const std::type_info *base, void *(*caster)(void *)) {
  146. auto base_info = detail::get_type_info(*base, false);
  147. if (!base_info) {
  148. std::string tname(base->name());
  149. detail::clean_type_id(tname);
  150. pybind11_fail("generic_type: type \"" + std::string(name) +
  151. "\" referenced unknown base type \"" + tname + "\"");
  152. }
  153. if (default_holder != base_info->default_holder) {
  154. std::string tname(base->name());
  155. detail::clean_type_id(tname);
  156. pybind11_fail("generic_type: type \"" + std::string(name) + "\" " +
  157. (default_holder ? "does not have" : "has") +
  158. " a non-default holder type while its base \"" + tname + "\" " +
  159. (base_info->default_holder ? "does not" : "does"));
  160. }
  161. bases.append((PyObject *) base_info->type);
  162. if (base_info->type->tp_dictoffset != 0)
  163. dynamic_attr = true;
  164. if (caster)
  165. base_info->implicit_casts.push_back(std::make_pair(type, caster));
  166. }
  167. };
  168. inline function_call::function_call(function_record &f, handle p) :
  169. func(f), parent(p) {
  170. args.reserve(f.nargs);
  171. args_convert.reserve(f.nargs);
  172. }
  173. /**
  174. * Partial template specializations to process custom attributes provided to
  175. * cpp_function_ and class_. These are either used to initialize the respective
  176. * fields in the type_record and function_record data structures or executed at
  177. * runtime to deal with custom call policies (e.g. keep_alive).
  178. */
  179. template <typename T, typename SFINAE = void> struct process_attribute;
  180. template <typename T> struct process_attribute_default {
  181. /// Default implementation: do nothing
  182. static void init(const T &, function_record *) { }
  183. static void init(const T &, type_record *) { }
  184. static void precall(function_call &) { }
  185. static void postcall(function_call &, handle) { }
  186. };
  187. /// Process an attribute specifying the function's name
  188. template <> struct process_attribute<name> : process_attribute_default<name> {
  189. static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
  190. };
  191. /// Process an attribute specifying the function's docstring
  192. template <> struct process_attribute<doc> : process_attribute_default<doc> {
  193. static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
  194. };
  195. /// Process an attribute specifying the function's docstring (provided as a C-style string)
  196. template <> struct process_attribute<const char *> : process_attribute_default<const char *> {
  197. static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
  198. static void init(const char *d, type_record *r) { r->doc = const_cast<char *>(d); }
  199. };
  200. template <> struct process_attribute<char *> : process_attribute<const char *> { };
  201. /// Process an attribute indicating the function's return value policy
  202. template <> struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
  203. static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
  204. };
  205. /// Process an attribute which indicates that this is an overloaded function associated with a given sibling
  206. template <> struct process_attribute<sibling> : process_attribute_default<sibling> {
  207. static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
  208. };
  209. /// Process an attribute which indicates that this function is a method
  210. template <> struct process_attribute<is_method> : process_attribute_default<is_method> {
  211. static void init(const is_method &s, function_record *r) { r->is_method = true; r->scope = s.class_; }
  212. };
  213. /// Process an attribute which indicates the parent scope of a method
  214. template <> struct process_attribute<scope> : process_attribute_default<scope> {
  215. static void init(const scope &s, function_record *r) { r->scope = s.value; }
  216. };
  217. /// Process an attribute which indicates that this function is an operator
  218. template <> struct process_attribute<is_operator> : process_attribute_default<is_operator> {
  219. static void init(const is_operator &, function_record *r) { r->is_operator = true; }
  220. };
  221. /// Process a keyword argument attribute (*without* a default value)
  222. template <> struct process_attribute<arg> : process_attribute_default<arg> {
  223. static void init(const arg &a, function_record *r) {
  224. if (r->is_method && r->args.empty())
  225. r->args.emplace_back("self", nullptr, handle(), true /*convert*/);
  226. r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert);
  227. }
  228. };
  229. /// Process a keyword argument attribute (*with* a default value)
  230. template <> struct process_attribute<arg_v> : process_attribute_default<arg_v> {
  231. static void init(const arg_v &a, function_record *r) {
  232. if (r->is_method && r->args.empty())
  233. r->args.emplace_back("self", nullptr /*descr*/, handle() /*parent*/, true /*convert*/);
  234. if (!a.value) {
  235. #if !defined(NDEBUG)
  236. std::string descr("'");
  237. if (a.name) descr += std::string(a.name) + ": ";
  238. descr += a.type + "'";
  239. if (r->is_method) {
  240. if (r->name)
  241. descr += " in method '" + (std::string) str(r->scope) + "." + (std::string) r->name + "'";
  242. else
  243. descr += " in method of '" + (std::string) str(r->scope) + "'";
  244. } else if (r->name) {
  245. descr += " in function '" + (std::string) r->name + "'";
  246. }
  247. pybind11_fail("arg(): could not convert default argument "
  248. + descr + " into a Python object (type not registered yet?)");
  249. #else
  250. pybind11_fail("arg(): could not convert default argument "
  251. "into a Python object (type not registered yet?). "
  252. "Compile in debug mode for more information.");
  253. #endif
  254. }
  255. r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert);
  256. }
  257. };
  258. /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees that)
  259. template <typename T>
  260. struct process_attribute<T, enable_if_t<is_pyobject<T>::value>> : process_attribute_default<handle> {
  261. static void init(const handle &h, type_record *r) { r->bases.append(h); }
  262. };
  263. /// Process a parent class attribute (deprecated, does not support multiple inheritance)
  264. template <typename T>
  265. struct process_attribute<base<T>> : process_attribute_default<base<T>> {
  266. static void init(const base<T> &, type_record *r) { r->add_base(&typeid(T), nullptr); }
  267. };
  268. /// Process a multiple inheritance attribute
  269. template <>
  270. struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
  271. static void init(const multiple_inheritance &, type_record *r) { r->multiple_inheritance = true; }
  272. };
  273. template <>
  274. struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
  275. static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
  276. };
  277. template <>
  278. struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
  279. static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
  280. };
  281. template <>
  282. struct process_attribute<metaclass> : process_attribute_default<metaclass> {
  283. static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
  284. };
  285. /// Process an 'arithmetic' attribute for enums (does nothing here)
  286. template <>
  287. struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
  288. /***
  289. * Process a keep_alive call policy -- invokes keep_alive_impl during the
  290. * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
  291. * otherwise
  292. */
  293. template <size_t Nurse, size_t Patient> struct process_attribute<keep_alive<Nurse, Patient>> : public process_attribute_default<keep_alive<Nurse, Patient>> {
  294. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
  295. static void precall(function_call &call) { keep_alive_impl(Nurse, Patient, call, handle()); }
  296. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
  297. static void postcall(function_call &, handle) { }
  298. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
  299. static void precall(function_call &) { }
  300. template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
  301. static void postcall(function_call &call, handle ret) { keep_alive_impl(Nurse, Patient, call, ret); }
  302. };
  303. /// Recursively iterate over variadic template arguments
  304. template <typename... Args> struct process_attributes {
  305. static void init(const Args&... args, function_record *r) {
  306. int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
  307. ignore_unused(unused);
  308. }
  309. static void init(const Args&... args, type_record *r) {
  310. int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::init(args, r), 0) ... };
  311. ignore_unused(unused);
  312. }
  313. static void precall(function_call &call) {
  314. int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::precall(call), 0) ... };
  315. ignore_unused(unused);
  316. }
  317. static void postcall(function_call &call, handle fn_ret) {
  318. int unused[] = { 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0) ... };
  319. ignore_unused(unused);
  320. }
  321. };
  322. /// Check the number of named arguments at compile time
  323. template <typename... Extra,
  324. size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
  325. size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
  326. constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
  327. return named == 0 || (self + named + has_args + has_kwargs) == nargs;
  328. }
  329. NAMESPACE_END(detail)
  330. NAMESPACE_END(pybind11)