FusedNode.py 37 KB

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