FusedNode.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. from __future__ import absolute_import
  2. import copy
  3. from . import (ExprNodes, PyrexTypes, MemoryView,
  4. ParseTreeTransforms, StringEncoding, Errors)
  5. from .ExprNodes import CloneNode, ProxyNode, TupleNode
  6. from .Nodes import FuncDefNode, CFuncDefNode, StatListNode, DefNode
  7. from ..Utils import OrderedSet
  8. class FusedCFuncDefNode(StatListNode):
  9. """
  10. This node replaces a function with fused arguments. It deep-copies the
  11. function for every permutation of fused types, and allocates a new local
  12. scope for it. It keeps track of the original function in self.node, and
  13. the entry of the original function in the symbol table is given the
  14. 'fused_cfunction' attribute which points back to us.
  15. Then when a function lookup occurs (to e.g. call it), the call can be
  16. dispatched to the right function.
  17. node FuncDefNode the original function
  18. nodes [FuncDefNode] list of copies of node with different specific types
  19. py_func DefNode the fused python function subscriptable from
  20. Python space
  21. __signatures__ A DictNode mapping signature specialization strings
  22. to PyCFunction nodes
  23. resulting_fused_function PyCFunction for the fused DefNode that delegates
  24. to specializations
  25. fused_func_assignment Assignment of the fused function to the function name
  26. defaults_tuple TupleNode of defaults (letting PyCFunctionNode build
  27. defaults would result in many different tuples)
  28. specialized_pycfuncs List of synthesized pycfunction nodes for the
  29. specializations
  30. code_object CodeObjectNode shared by all specializations and the
  31. fused function
  32. fused_compound_types All fused (compound) types (e.g. floating[:])
  33. """
  34. __signatures__ = None
  35. resulting_fused_function = None
  36. fused_func_assignment = None
  37. defaults_tuple = None
  38. decorators = None
  39. child_attrs = StatListNode.child_attrs + [
  40. '__signatures__', 'resulting_fused_function', 'fused_func_assignment']
  41. def __init__(self, node, env):
  42. super(FusedCFuncDefNode, self).__init__(node.pos)
  43. self.nodes = []
  44. self.node = node
  45. is_def = isinstance(self.node, DefNode)
  46. if is_def:
  47. # self.node.decorators = []
  48. self.copy_def(env)
  49. else:
  50. self.copy_cdef(env)
  51. # Perform some sanity checks. If anything fails, it's a bug
  52. for n in self.nodes:
  53. assert not n.entry.type.is_fused
  54. assert not n.local_scope.return_type.is_fused
  55. if node.return_type.is_fused:
  56. assert not n.return_type.is_fused
  57. if not is_def and n.cfunc_declarator.optional_arg_count:
  58. assert n.type.op_arg_struct
  59. node.entry.fused_cfunction = self
  60. # Copy the nodes as AnalyseDeclarationsTransform will prepend
  61. # self.py_func to self.stats, as we only want specialized
  62. # CFuncDefNodes in self.nodes
  63. self.stats = self.nodes[:]
  64. def copy_def(self, env):
  65. """
  66. Create a copy of the original def or lambda function for specialized
  67. versions.
  68. """
  69. fused_compound_types = PyrexTypes.unique(
  70. [arg.type for arg in self.node.args if arg.type.is_fused])
  71. fused_types = self._get_fused_base_types(fused_compound_types)
  72. permutations = PyrexTypes.get_all_specialized_permutations(fused_types)
  73. self.fused_compound_types = fused_compound_types
  74. if self.node.entry in env.pyfunc_entries:
  75. env.pyfunc_entries.remove(self.node.entry)
  76. for cname, fused_to_specific in permutations:
  77. copied_node = copy.deepcopy(self.node)
  78. # keep signature object identity for special casing in DefNode.analyse_declarations()
  79. copied_node.entry.signature = self.node.entry.signature
  80. self._specialize_function_args(copied_node.args, fused_to_specific)
  81. copied_node.return_type = self.node.return_type.specialize(
  82. fused_to_specific)
  83. copied_node.analyse_declarations(env)
  84. # copied_node.is_staticmethod = self.node.is_staticmethod
  85. # copied_node.is_classmethod = self.node.is_classmethod
  86. self.create_new_local_scope(copied_node, env, fused_to_specific)
  87. self.specialize_copied_def(copied_node, cname, self.node.entry,
  88. fused_to_specific, fused_compound_types)
  89. PyrexTypes.specialize_entry(copied_node.entry, cname)
  90. copied_node.entry.used = True
  91. env.entries[copied_node.entry.name] = copied_node.entry
  92. if not self.replace_fused_typechecks(copied_node):
  93. break
  94. self.orig_py_func = self.node
  95. self.py_func = self.make_fused_cpdef(self.node, env, is_def=True)
  96. def copy_cdef(self, env):
  97. """
  98. Create a copy of the original c(p)def function for all specialized
  99. versions.
  100. """
  101. permutations = self.node.type.get_all_specialized_permutations()
  102. # print 'Node %s has %d specializations:' % (self.node.entry.name,
  103. # len(permutations))
  104. # import pprint; pprint.pprint([d for cname, d in permutations])
  105. # Prevent copying of the python function
  106. self.orig_py_func = orig_py_func = self.node.py_func
  107. self.node.py_func = None
  108. if orig_py_func:
  109. env.pyfunc_entries.remove(orig_py_func.entry)
  110. fused_types = self.node.type.get_fused_types()
  111. self.fused_compound_types = fused_types
  112. new_cfunc_entries = []
  113. for cname, fused_to_specific in permutations:
  114. copied_node = copy.deepcopy(self.node)
  115. # Make the types in our CFuncType specific.
  116. type = copied_node.type.specialize(fused_to_specific)
  117. entry = copied_node.entry
  118. type.specialize_entry(entry, cname)
  119. # Reuse existing Entries (e.g. from .pxd files).
  120. for i, orig_entry in enumerate(env.cfunc_entries):
  121. if entry.cname == orig_entry.cname and type.same_as_resolved_type(orig_entry.type):
  122. copied_node.entry = env.cfunc_entries[i]
  123. if not copied_node.entry.func_cname:
  124. copied_node.entry.func_cname = entry.func_cname
  125. entry = copied_node.entry
  126. type = entry.type
  127. break
  128. else:
  129. new_cfunc_entries.append(entry)
  130. copied_node.type = type
  131. entry.type, type.entry = type, entry
  132. entry.used = (entry.used or
  133. self.node.entry.defined_in_pxd or
  134. env.is_c_class_scope or
  135. entry.is_cmethod)
  136. if self.node.cfunc_declarator.optional_arg_count:
  137. self.node.cfunc_declarator.declare_optional_arg_struct(
  138. type, env, fused_cname=cname)
  139. copied_node.return_type = type.return_type
  140. self.create_new_local_scope(copied_node, env, fused_to_specific)
  141. # Make the argument types in the CFuncDeclarator specific
  142. self._specialize_function_args(copied_node.cfunc_declarator.args,
  143. fused_to_specific)
  144. # If a cpdef, declare all specialized cpdefs (this
  145. # also calls analyse_declarations)
  146. copied_node.declare_cpdef_wrapper(env)
  147. if copied_node.py_func:
  148. env.pyfunc_entries.remove(copied_node.py_func.entry)
  149. self.specialize_copied_def(
  150. copied_node.py_func, cname, self.node.entry.as_variable,
  151. fused_to_specific, fused_types)
  152. if not self.replace_fused_typechecks(copied_node):
  153. break
  154. # replace old entry with new entries
  155. if self.node.entry in env.cfunc_entries:
  156. cindex = env.cfunc_entries.index(self.node.entry)
  157. env.cfunc_entries[cindex:cindex+1] = new_cfunc_entries
  158. else:
  159. env.cfunc_entries.extend(new_cfunc_entries)
  160. if orig_py_func:
  161. self.py_func = self.make_fused_cpdef(orig_py_func, env,
  162. is_def=False)
  163. else:
  164. self.py_func = orig_py_func
  165. def _get_fused_base_types(self, fused_compound_types):
  166. """
  167. Get a list of unique basic fused types, from a list of
  168. (possibly) compound fused types.
  169. """
  170. base_types = []
  171. seen = set()
  172. for fused_type in fused_compound_types:
  173. fused_type.get_fused_types(result=base_types, seen=seen)
  174. return base_types
  175. def _specialize_function_args(self, args, fused_to_specific):
  176. for arg in args:
  177. if arg.type.is_fused:
  178. arg.type = arg.type.specialize(fused_to_specific)
  179. if arg.type.is_memoryviewslice:
  180. arg.type.validate_memslice_dtype(arg.pos)
  181. def create_new_local_scope(self, node, env, f2s):
  182. """
  183. Create a new local scope for the copied node and append it to
  184. self.nodes. A new local scope is needed because the arguments with the
  185. fused types are already in the local scope, and we need the specialized
  186. entries created after analyse_declarations on each specialized version
  187. of the (CFunc)DefNode.
  188. f2s is a dict mapping each fused type to its specialized version
  189. """
  190. node.create_local_scope(env)
  191. node.local_scope.fused_to_specific = f2s
  192. # This is copied from the original function, set it to false to
  193. # stop recursion
  194. node.has_fused_arguments = False
  195. self.nodes.append(node)
  196. def specialize_copied_def(self, node, cname, py_entry, f2s, fused_compound_types):
  197. """Specialize the copy of a DefNode given the copied node,
  198. the specialization cname and the original DefNode entry"""
  199. fused_types = self._get_fused_base_types(fused_compound_types)
  200. type_strings = [
  201. PyrexTypes.specialization_signature_string(fused_type, f2s)
  202. for fused_type in fused_types
  203. ]
  204. node.specialized_signature_string = '|'.join(type_strings)
  205. node.entry.pymethdef_cname = PyrexTypes.get_fused_cname(
  206. cname, node.entry.pymethdef_cname)
  207. node.entry.doc = py_entry.doc
  208. node.entry.doc_cname = py_entry.doc_cname
  209. def replace_fused_typechecks(self, copied_node):
  210. """
  211. Branch-prune fused type checks like
  212. if fused_t is int:
  213. ...
  214. Returns whether an error was issued and whether we should stop in
  215. in order to prevent a flood of errors.
  216. """
  217. num_errors = Errors.num_errors
  218. transform = ParseTreeTransforms.ReplaceFusedTypeChecks(
  219. copied_node.local_scope)
  220. transform(copied_node)
  221. if Errors.num_errors > num_errors:
  222. return False
  223. return True
  224. def _fused_instance_checks(self, normal_types, pyx_code, env):
  225. """
  226. Generate Cython code for instance checks, matching an object to
  227. specialized types.
  228. """
  229. for specialized_type in normal_types:
  230. # all_numeric = all_numeric and specialized_type.is_numeric
  231. pyx_code.context.update(
  232. py_type_name=specialized_type.py_type_name(),
  233. specialized_type_name=specialized_type.specialization_string,
  234. )
  235. pyx_code.put_chunk(
  236. u"""
  237. if isinstance(arg, {{py_type_name}}):
  238. dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'; break
  239. """)
  240. def _dtype_name(self, dtype):
  241. if dtype.is_typedef:
  242. return '___pyx_%s' % dtype
  243. return str(dtype).replace(' ', '_')
  244. def _dtype_type(self, dtype):
  245. if dtype.is_typedef:
  246. return self._dtype_name(dtype)
  247. return str(dtype)
  248. def _sizeof_dtype(self, dtype):
  249. if dtype.is_pyobject:
  250. return 'sizeof(void *)'
  251. else:
  252. return "sizeof(%s)" % self._dtype_type(dtype)
  253. def _buffer_check_numpy_dtype_setup_cases(self, pyx_code):
  254. "Setup some common cases to match dtypes against specializations"
  255. if pyx_code.indenter("if kind in b'iu':"):
  256. pyx_code.putln("pass")
  257. pyx_code.named_insertion_point("dtype_int")
  258. pyx_code.dedent()
  259. if pyx_code.indenter("elif kind == b'f':"):
  260. pyx_code.putln("pass")
  261. pyx_code.named_insertion_point("dtype_float")
  262. pyx_code.dedent()
  263. if pyx_code.indenter("elif kind == b'c':"):
  264. pyx_code.putln("pass")
  265. pyx_code.named_insertion_point("dtype_complex")
  266. pyx_code.dedent()
  267. if pyx_code.indenter("elif kind == b'O':"):
  268. pyx_code.putln("pass")
  269. pyx_code.named_insertion_point("dtype_object")
  270. pyx_code.dedent()
  271. match = "dest_sig[{{dest_sig_idx}}] = '{{specialized_type_name}}'"
  272. no_match = "dest_sig[{{dest_sig_idx}}] = None"
  273. def _buffer_check_numpy_dtype(self, pyx_code, specialized_buffer_types, pythran_types):
  274. """
  275. Match a numpy dtype object to the individual specializations.
  276. """
  277. self._buffer_check_numpy_dtype_setup_cases(pyx_code)
  278. for specialized_type in pythran_types+specialized_buffer_types:
  279. final_type = specialized_type
  280. if specialized_type.is_pythran_expr:
  281. specialized_type = specialized_type.org_buffer
  282. dtype = specialized_type.dtype
  283. pyx_code.context.update(
  284. itemsize_match=self._sizeof_dtype(dtype) + " == itemsize",
  285. signed_match="not (%s_is_signed ^ dtype_signed)" % self._dtype_name(dtype),
  286. dtype=dtype,
  287. specialized_type_name=final_type.specialization_string)
  288. dtypes = [
  289. (dtype.is_int, pyx_code.dtype_int),
  290. (dtype.is_float, pyx_code.dtype_float),
  291. (dtype.is_complex, pyx_code.dtype_complex)
  292. ]
  293. for dtype_category, codewriter in dtypes:
  294. if dtype_category:
  295. cond = '{{itemsize_match}} and (<Py_ssize_t>arg.ndim) == %d' % (
  296. specialized_type.ndim,)
  297. if dtype.is_int:
  298. cond += ' and {{signed_match}}'
  299. if final_type.is_pythran_expr:
  300. cond += ' and arg_is_pythran_compatible'
  301. if codewriter.indenter("if %s:" % cond):
  302. #codewriter.putln("print 'buffer match found based on numpy dtype'")
  303. codewriter.putln(self.match)
  304. codewriter.putln("break")
  305. codewriter.dedent()
  306. def _buffer_parse_format_string_check(self, pyx_code, decl_code,
  307. specialized_type, env):
  308. """
  309. For each specialized type, try to coerce the object to a memoryview
  310. slice of that type. This means obtaining a buffer and parsing the
  311. format string.
  312. TODO: separate buffer acquisition from format parsing
  313. """
  314. dtype = specialized_type.dtype
  315. if specialized_type.is_buffer:
  316. axes = [('direct', 'strided')] * specialized_type.ndim
  317. else:
  318. axes = specialized_type.axes
  319. memslice_type = PyrexTypes.MemoryViewSliceType(dtype, axes)
  320. memslice_type.create_from_py_utility_code(env)
  321. pyx_code.context.update(
  322. coerce_from_py_func=memslice_type.from_py_function,
  323. dtype=dtype)
  324. decl_code.putln(
  325. "{{memviewslice_cname}} {{coerce_from_py_func}}(object, int)")
  326. pyx_code.context.update(
  327. specialized_type_name=specialized_type.specialization_string,
  328. sizeof_dtype=self._sizeof_dtype(dtype))
  329. pyx_code.put_chunk(
  330. u"""
  331. # try {{dtype}}
  332. if itemsize == -1 or itemsize == {{sizeof_dtype}}:
  333. memslice = {{coerce_from_py_func}}(arg, 0)
  334. if memslice.memview:
  335. __PYX_XDEC_MEMVIEW(&memslice, 1)
  336. # print 'found a match for the buffer through format parsing'
  337. %s
  338. break
  339. else:
  340. __pyx_PyErr_Clear()
  341. """ % self.match)
  342. def _buffer_checks(self, buffer_types, pythran_types, pyx_code, decl_code, env):
  343. """
  344. Generate Cython code to match objects to buffer specializations.
  345. First try to get a numpy dtype object and match it against the individual
  346. specializations. If that fails, try naively to coerce the object
  347. to each specialization, which obtains the buffer each time and tries
  348. to match the format string.
  349. """
  350. # The first thing to find a match in this loop breaks out of the loop
  351. pyx_code.put_chunk(
  352. u"""
  353. """ + (u"arg_is_pythran_compatible = False" if pythran_types else u"") + u"""
  354. if ndarray is not None:
  355. if isinstance(arg, ndarray):
  356. dtype = arg.dtype
  357. """ + (u"arg_is_pythran_compatible = True" if pythran_types else u"") + u"""
  358. elif __pyx_memoryview_check(arg):
  359. arg_base = arg.base
  360. if isinstance(arg_base, ndarray):
  361. dtype = arg_base.dtype
  362. else:
  363. dtype = None
  364. else:
  365. dtype = None
  366. itemsize = -1
  367. if dtype is not None:
  368. itemsize = dtype.itemsize
  369. kind = ord(dtype.kind)
  370. dtype_signed = kind == 'i'
  371. """)
  372. pyx_code.indent(2)
  373. if pythran_types:
  374. pyx_code.put_chunk(
  375. u"""
  376. # Pythran only supports the endianness of the current compiler
  377. byteorder = dtype.byteorder
  378. if byteorder == "<" and not __Pyx_Is_Little_Endian():
  379. arg_is_pythran_compatible = False
  380. elif byteorder == ">" and __Pyx_Is_Little_Endian():
  381. arg_is_pythran_compatible = False
  382. if arg_is_pythran_compatible:
  383. cur_stride = itemsize
  384. shape = arg.shape
  385. strides = arg.strides
  386. for i in range(arg.ndim-1, -1, -1):
  387. if (<Py_ssize_t>strides[i]) != cur_stride:
  388. arg_is_pythran_compatible = False
  389. break
  390. cur_stride *= <Py_ssize_t> shape[i]
  391. else:
  392. arg_is_pythran_compatible = not (arg.flags.f_contiguous and (<Py_ssize_t>arg.ndim) > 1)
  393. """)
  394. pyx_code.named_insertion_point("numpy_dtype_checks")
  395. self._buffer_check_numpy_dtype(pyx_code, buffer_types, pythran_types)
  396. pyx_code.dedent(2)
  397. for specialized_type in buffer_types:
  398. self._buffer_parse_format_string_check(
  399. pyx_code, decl_code, specialized_type, env)
  400. def _buffer_declarations(self, pyx_code, decl_code, all_buffer_types, pythran_types):
  401. """
  402. If we have any buffer specializations, write out some variable
  403. declarations and imports.
  404. """
  405. decl_code.put_chunk(
  406. u"""
  407. ctypedef struct {{memviewslice_cname}}:
  408. void *memview
  409. void __PYX_XDEC_MEMVIEW({{memviewslice_cname}} *, int have_gil)
  410. bint __pyx_memoryview_check(object)
  411. """)
  412. pyx_code.local_variable_declarations.put_chunk(
  413. u"""
  414. cdef {{memviewslice_cname}} memslice
  415. cdef Py_ssize_t itemsize
  416. cdef bint dtype_signed
  417. cdef char kind
  418. itemsize = -1
  419. """)
  420. if pythran_types:
  421. pyx_code.local_variable_declarations.put_chunk(u"""
  422. cdef bint arg_is_pythran_compatible
  423. cdef Py_ssize_t cur_stride
  424. """)
  425. pyx_code.imports.put_chunk(
  426. u"""
  427. cdef type ndarray
  428. ndarray = __Pyx_ImportNumPyArrayTypeIfAvailable()
  429. """)
  430. seen_typedefs = set()
  431. seen_int_dtypes = set()
  432. for buffer_type in all_buffer_types:
  433. dtype = buffer_type.dtype
  434. dtype_name = self._dtype_name(dtype)
  435. if dtype.is_typedef:
  436. if dtype_name not in seen_typedefs:
  437. seen_typedefs.add(dtype_name)
  438. decl_code.putln(
  439. 'ctypedef %s %s "%s"' % (dtype.resolve(), dtype_name,
  440. dtype.empty_declaration_code()))
  441. if buffer_type.dtype.is_int:
  442. if str(dtype) not in seen_int_dtypes:
  443. seen_int_dtypes.add(str(dtype))
  444. pyx_code.context.update(dtype_name=dtype_name,
  445. dtype_type=self._dtype_type(dtype))
  446. pyx_code.local_variable_declarations.put_chunk(
  447. u"""
  448. cdef bint {{dtype_name}}_is_signed
  449. {{dtype_name}}_is_signed = not (<{{dtype_type}}> -1 > 0)
  450. """)
  451. def _split_fused_types(self, arg):
  452. """
  453. Specialize fused types and split into normal types and buffer types.
  454. """
  455. specialized_types = PyrexTypes.get_specialized_types(arg.type)
  456. # Prefer long over int, etc by sorting (see type classes in PyrexTypes.py)
  457. specialized_types.sort()
  458. seen_py_type_names = set()
  459. normal_types, buffer_types, pythran_types = [], [], []
  460. has_object_fallback = False
  461. for specialized_type in specialized_types:
  462. py_type_name = specialized_type.py_type_name()
  463. if py_type_name:
  464. if py_type_name in seen_py_type_names:
  465. continue
  466. seen_py_type_names.add(py_type_name)
  467. if py_type_name == 'object':
  468. has_object_fallback = True
  469. else:
  470. normal_types.append(specialized_type)
  471. elif specialized_type.is_pythran_expr:
  472. pythran_types.append(specialized_type)
  473. elif specialized_type.is_buffer or specialized_type.is_memoryviewslice:
  474. buffer_types.append(specialized_type)
  475. return normal_types, buffer_types, pythran_types, has_object_fallback
  476. def _unpack_argument(self, pyx_code):
  477. pyx_code.put_chunk(
  478. u"""
  479. # PROCESSING ARGUMENT {{arg_tuple_idx}}
  480. if {{arg_tuple_idx}} < len(<tuple>args):
  481. arg = (<tuple>args)[{{arg_tuple_idx}}]
  482. elif kwargs is not None and '{{arg.name}}' in <dict>kwargs:
  483. arg = (<dict>kwargs)['{{arg.name}}']
  484. else:
  485. {{if arg.default}}
  486. arg = (<tuple>defaults)[{{default_idx}}]
  487. {{else}}
  488. {{if arg_tuple_idx < min_positional_args}}
  489. raise TypeError("Expected at least %d argument%s, got %d" % (
  490. {{min_positional_args}}, {{'"s"' if min_positional_args != 1 else '""'}}, len(<tuple>args)))
  491. {{else}}
  492. raise TypeError("Missing keyword-only argument: '%s'" % "{{arg.default}}")
  493. {{endif}}
  494. {{endif}}
  495. """)
  496. def make_fused_cpdef(self, orig_py_func, env, is_def):
  497. """
  498. This creates the function that is indexable from Python and does
  499. runtime dispatch based on the argument types. The function gets the
  500. arg tuple and kwargs dict (or None) and the defaults tuple
  501. as arguments from the Binding Fused Function's tp_call.
  502. """
  503. from . import TreeFragment, Code, UtilityCode
  504. fused_types = self._get_fused_base_types([
  505. arg.type for arg in self.node.args if arg.type.is_fused])
  506. context = {
  507. 'memviewslice_cname': MemoryView.memviewslice_cname,
  508. 'func_args': self.node.args,
  509. 'n_fused': len(fused_types),
  510. 'min_positional_args':
  511. self.node.num_required_args - self.node.num_required_kw_args
  512. if is_def else
  513. sum(1 for arg in self.node.args if arg.default is None),
  514. 'name': orig_py_func.entry.name,
  515. }
  516. pyx_code = Code.PyxCodeWriter(context=context)
  517. decl_code = Code.PyxCodeWriter(context=context)
  518. decl_code.put_chunk(
  519. u"""
  520. cdef extern from *:
  521. void __pyx_PyErr_Clear "PyErr_Clear" ()
  522. type __Pyx_ImportNumPyArrayTypeIfAvailable()
  523. int __Pyx_Is_Little_Endian()
  524. """)
  525. decl_code.indent()
  526. pyx_code.put_chunk(
  527. u"""
  528. def __pyx_fused_cpdef(signatures, args, kwargs, defaults):
  529. # FIXME: use a typed signature - currently fails badly because
  530. # default arguments inherit the types we specify here!
  531. dest_sig = [None] * {{n_fused}}
  532. if kwargs is not None and not kwargs:
  533. kwargs = None
  534. cdef Py_ssize_t i
  535. # instance check body
  536. """)
  537. pyx_code.indent() # indent following code to function body
  538. pyx_code.named_insertion_point("imports")
  539. pyx_code.named_insertion_point("func_defs")
  540. pyx_code.named_insertion_point("local_variable_declarations")
  541. fused_index = 0
  542. default_idx = 0
  543. all_buffer_types = OrderedSet()
  544. seen_fused_types = set()
  545. for i, arg in enumerate(self.node.args):
  546. if arg.type.is_fused:
  547. arg_fused_types = arg.type.get_fused_types()
  548. if len(arg_fused_types) > 1:
  549. raise NotImplementedError("Determination of more than one fused base "
  550. "type per argument is not implemented.")
  551. fused_type = arg_fused_types[0]
  552. if arg.type.is_fused and fused_type not in seen_fused_types:
  553. seen_fused_types.add(fused_type)
  554. context.update(
  555. arg_tuple_idx=i,
  556. arg=arg,
  557. dest_sig_idx=fused_index,
  558. default_idx=default_idx,
  559. )
  560. normal_types, buffer_types, pythran_types, has_object_fallback = self._split_fused_types(arg)
  561. self._unpack_argument(pyx_code)
  562. # 'unrolled' loop, first match breaks out of it
  563. if pyx_code.indenter("while 1:"):
  564. if normal_types:
  565. self._fused_instance_checks(normal_types, pyx_code, env)
  566. if buffer_types or pythran_types:
  567. env.use_utility_code(Code.UtilityCode.load_cached("IsLittleEndian", "ModuleSetupCode.c"))
  568. self._buffer_checks(buffer_types, pythran_types, pyx_code, decl_code, env)
  569. if has_object_fallback:
  570. pyx_code.context.update(specialized_type_name='object')
  571. pyx_code.putln(self.match)
  572. else:
  573. pyx_code.putln(self.no_match)
  574. pyx_code.putln("break")
  575. pyx_code.dedent()
  576. fused_index += 1
  577. all_buffer_types.update(buffer_types)
  578. all_buffer_types.update(ty.org_buffer for ty in pythran_types)
  579. if arg.default:
  580. default_idx += 1
  581. if all_buffer_types:
  582. self._buffer_declarations(pyx_code, decl_code, all_buffer_types, pythran_types)
  583. env.use_utility_code(Code.UtilityCode.load_cached("Import", "ImportExport.c"))
  584. env.use_utility_code(Code.UtilityCode.load_cached("ImportNumPyArray", "ImportExport.c"))
  585. pyx_code.put_chunk(
  586. u"""
  587. candidates = []
  588. for sig in <dict>signatures:
  589. match_found = False
  590. src_sig = sig.strip('()').split('|')
  591. for i in range(len(dest_sig)):
  592. dst_type = dest_sig[i]
  593. if dst_type is not None:
  594. if src_sig[i] == dst_type:
  595. match_found = True
  596. else:
  597. match_found = False
  598. break
  599. if match_found:
  600. candidates.append(sig)
  601. if not candidates:
  602. raise TypeError("No matching signature found")
  603. elif len(candidates) > 1:
  604. raise TypeError("Function call with ambiguous argument types")
  605. else:
  606. return (<dict>signatures)[candidates[0]]
  607. """)
  608. fragment_code = pyx_code.getvalue()
  609. # print decl_code.getvalue()
  610. # print fragment_code
  611. from .Optimize import ConstantFolding
  612. fragment = TreeFragment.TreeFragment(
  613. fragment_code, level='module', pipeline=[ConstantFolding()])
  614. ast = TreeFragment.SetPosTransform(self.node.pos)(fragment.root)
  615. UtilityCode.declare_declarations_in_scope(
  616. decl_code.getvalue(), env.global_scope())
  617. ast.scope = env
  618. # FIXME: for static methods of cdef classes, we build the wrong signature here: first arg becomes 'self'
  619. ast.analyse_declarations(env)
  620. py_func = ast.stats[-1] # the DefNode
  621. self.fragment_scope = ast.scope
  622. if isinstance(self.node, DefNode):
  623. py_func.specialized_cpdefs = self.nodes[:]
  624. else:
  625. py_func.specialized_cpdefs = [n.py_func for n in self.nodes]
  626. return py_func
  627. def update_fused_defnode_entry(self, env):
  628. copy_attributes = (
  629. 'name', 'pos', 'cname', 'func_cname', 'pyfunc_cname',
  630. 'pymethdef_cname', 'doc', 'doc_cname', 'is_member',
  631. 'scope'
  632. )
  633. entry = self.py_func.entry
  634. for attr in copy_attributes:
  635. setattr(entry, attr,
  636. getattr(self.orig_py_func.entry, attr))
  637. self.py_func.name = self.orig_py_func.name
  638. self.py_func.doc = self.orig_py_func.doc
  639. env.entries.pop('__pyx_fused_cpdef', None)
  640. if isinstance(self.node, DefNode):
  641. env.entries[entry.name] = entry
  642. else:
  643. env.entries[entry.name].as_variable = entry
  644. env.pyfunc_entries.append(entry)
  645. self.py_func.entry.fused_cfunction = self
  646. for node in self.nodes:
  647. if isinstance(self.node, DefNode):
  648. node.fused_py_func = self.py_func
  649. else:
  650. node.py_func.fused_py_func = self.py_func
  651. node.entry.as_variable = entry
  652. self.synthesize_defnodes()
  653. self.stats.append(self.__signatures__)
  654. def analyse_expressions(self, env):
  655. """
  656. Analyse the expressions. Take care to only evaluate default arguments
  657. once and clone the result for all specializations
  658. """
  659. for fused_compound_type in self.fused_compound_types:
  660. for fused_type in fused_compound_type.get_fused_types():
  661. for specialization_type in fused_type.types:
  662. if specialization_type.is_complex:
  663. specialization_type.create_declaration_utility_code(env)
  664. if self.py_func:
  665. self.__signatures__ = self.__signatures__.analyse_expressions(env)
  666. self.py_func = self.py_func.analyse_expressions(env)
  667. self.resulting_fused_function = self.resulting_fused_function.analyse_expressions(env)
  668. self.fused_func_assignment = self.fused_func_assignment.analyse_expressions(env)
  669. self.defaults = defaults = []
  670. for arg in self.node.args:
  671. if arg.default:
  672. arg.default = arg.default.analyse_expressions(env)
  673. defaults.append(ProxyNode(arg.default))
  674. else:
  675. defaults.append(None)
  676. for i, stat in enumerate(self.stats):
  677. stat = self.stats[i] = stat.analyse_expressions(env)
  678. if isinstance(stat, FuncDefNode):
  679. for arg, default in zip(stat.args, defaults):
  680. if default is not None:
  681. arg.default = CloneNode(default).coerce_to(arg.type, env)
  682. if self.py_func:
  683. args = [CloneNode(default) for default in defaults if default]
  684. self.defaults_tuple = TupleNode(self.pos, args=args)
  685. self.defaults_tuple = self.defaults_tuple.analyse_types(env, skip_children=True).coerce_to_pyobject(env)
  686. self.defaults_tuple = ProxyNode(self.defaults_tuple)
  687. self.code_object = ProxyNode(self.specialized_pycfuncs[0].code_object)
  688. fused_func = self.resulting_fused_function.arg
  689. fused_func.defaults_tuple = CloneNode(self.defaults_tuple)
  690. fused_func.code_object = CloneNode(self.code_object)
  691. for i, pycfunc in enumerate(self.specialized_pycfuncs):
  692. pycfunc.code_object = CloneNode(self.code_object)
  693. pycfunc = self.specialized_pycfuncs[i] = pycfunc.analyse_types(env)
  694. pycfunc.defaults_tuple = CloneNode(self.defaults_tuple)
  695. return self
  696. def synthesize_defnodes(self):
  697. """
  698. Create the __signatures__ dict of PyCFunctionNode specializations.
  699. """
  700. if isinstance(self.nodes[0], CFuncDefNode):
  701. nodes = [node.py_func for node in self.nodes]
  702. else:
  703. nodes = self.nodes
  704. signatures = [StringEncoding.EncodedString(node.specialized_signature_string)
  705. for node in nodes]
  706. keys = [ExprNodes.StringNode(node.pos, value=sig)
  707. for node, sig in zip(nodes, signatures)]
  708. values = [ExprNodes.PyCFunctionNode.from_defnode(node, binding=True)
  709. for node in nodes]
  710. self.__signatures__ = ExprNodes.DictNode.from_pairs(self.pos, zip(keys, values))
  711. self.specialized_pycfuncs = values
  712. for pycfuncnode in values:
  713. pycfuncnode.is_specialization = True
  714. def generate_function_definitions(self, env, code):
  715. if self.py_func:
  716. self.py_func.pymethdef_required = True
  717. self.fused_func_assignment.generate_function_definitions(env, code)
  718. for stat in self.stats:
  719. if isinstance(stat, FuncDefNode) and stat.entry.used:
  720. code.mark_pos(stat.pos)
  721. stat.generate_function_definitions(env, code)
  722. def generate_execution_code(self, code):
  723. # Note: all def function specialization are wrapped in PyCFunction
  724. # nodes in the self.__signatures__ dictnode.
  725. for default in self.defaults:
  726. if default is not None:
  727. default.generate_evaluation_code(code)
  728. if self.py_func:
  729. self.defaults_tuple.generate_evaluation_code(code)
  730. self.code_object.generate_evaluation_code(code)
  731. for stat in self.stats:
  732. code.mark_pos(stat.pos)
  733. if isinstance(stat, ExprNodes.ExprNode):
  734. stat.generate_evaluation_code(code)
  735. else:
  736. stat.generate_execution_code(code)
  737. if self.__signatures__:
  738. self.resulting_fused_function.generate_evaluation_code(code)
  739. code.putln(
  740. "((__pyx_FusedFunctionObject *) %s)->__signatures__ = %s;" %
  741. (self.resulting_fused_function.result(),
  742. self.__signatures__.result()))
  743. code.put_giveref(self.__signatures__.result())
  744. self.__signatures__.generate_post_assignment_code(code)
  745. self.__signatures__.free_temps(code)
  746. self.fused_func_assignment.generate_execution_code(code)
  747. # Dispose of results
  748. self.resulting_fused_function.generate_disposal_code(code)
  749. self.resulting_fused_function.free_temps(code)
  750. self.defaults_tuple.generate_disposal_code(code)
  751. self.defaults_tuple.free_temps(code)
  752. self.code_object.generate_disposal_code(code)
  753. self.code_object.free_temps(code)
  754. for default in self.defaults:
  755. if default is not None:
  756. default.generate_disposal_code(code)
  757. default.free_temps(code)
  758. def annotate(self, code):
  759. for stat in self.stats:
  760. stat.annotate(code)