PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/micronumpy/compile.py

https://bitbucket.org/pypy/pypy/
Python | 1097 lines | 1062 code | 29 blank | 6 comment | 18 complexity | a27e7e2978f21b455d0a63774e96dbe4 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. """ This is a set of tools for standalone compiling of numpy expressions.
  2. It should not be imported by the module itself
  3. """
  4. import re
  5. import py
  6. from pypy.interpreter import special
  7. from pypy.interpreter.baseobjspace import InternalSpaceCache, W_Root, ObjSpace
  8. from pypy.interpreter.error import oefmt
  9. from rpython.rlib.objectmodel import specialize, instantiate
  10. from rpython.rlib.nonconst import NonConstant
  11. from rpython.rlib.rarithmetic import base_int
  12. from pypy.module.micronumpy import boxes, ufuncs
  13. from pypy.module.micronumpy.arrayops import where
  14. from pypy.module.micronumpy.ndarray import W_NDimArray
  15. from pypy.module.micronumpy.ctors import array
  16. from pypy.module.micronumpy.descriptor import get_dtype_cache
  17. from pypy.interpreter.miscutils import ThreadLocals, make_weak_value_dictionary
  18. from pypy.interpreter.executioncontext import (ExecutionContext, ActionFlag,
  19. UserDelAction)
  20. from pypy.interpreter.pyframe import PyFrame
  21. class BogusBytecode(Exception):
  22. pass
  23. class ArgumentMismatch(Exception):
  24. pass
  25. class ArgumentNotAnArray(Exception):
  26. pass
  27. class WrongFunctionName(Exception):
  28. pass
  29. class TokenizerError(Exception):
  30. pass
  31. class BadToken(Exception):
  32. pass
  33. SINGLE_ARG_FUNCTIONS = ["sum", "prod", "max", "min", "all", "any",
  34. "unegative", "flat", "tostring", "count_nonzero",
  35. "argsort", "cumsum", "logical_xor_reduce"]
  36. TWO_ARG_FUNCTIONS = ["dot", 'take', 'searchsorted', 'multiply']
  37. TWO_ARG_FUNCTIONS_OR_NONE = ['view', 'astype', 'reshape']
  38. THREE_ARG_FUNCTIONS = ['where']
  39. class W_TypeObject(W_Root):
  40. def __init__(self, name):
  41. self.name = name
  42. def lookup(self, name):
  43. return self.getdictvalue(self, name)
  44. def getname(self, space):
  45. return self.name
  46. class FakeSpace(ObjSpace):
  47. w_ValueError = W_TypeObject("ValueError")
  48. w_TypeError = W_TypeObject("TypeError")
  49. w_IndexError = W_TypeObject("IndexError")
  50. w_OverflowError = W_TypeObject("OverflowError")
  51. w_NotImplementedError = W_TypeObject("NotImplementedError")
  52. w_AttributeError = W_TypeObject("AttributeError")
  53. w_StopIteration = W_TypeObject("StopIteration")
  54. w_KeyError = W_TypeObject("KeyError")
  55. w_SystemExit = W_TypeObject("SystemExit")
  56. w_KeyboardInterrupt = W_TypeObject("KeyboardInterrupt")
  57. w_VisibleDeprecationWarning = W_TypeObject("VisibleDeprecationWarning")
  58. w_None = None
  59. w_bool = W_TypeObject("bool")
  60. w_int = W_TypeObject("int")
  61. w_float = W_TypeObject("float")
  62. w_list = W_TypeObject("list")
  63. w_long = W_TypeObject("long")
  64. w_tuple = W_TypeObject('tuple')
  65. w_slice = W_TypeObject("slice")
  66. w_str = W_TypeObject("str")
  67. w_unicode = W_TypeObject("unicode")
  68. w_complex = W_TypeObject("complex")
  69. w_dict = W_TypeObject("dict")
  70. w_object = W_TypeObject("object")
  71. w_buffer = W_TypeObject("buffer")
  72. w_type = W_TypeObject("type")
  73. def __init__(self, config=None):
  74. """NOT_RPYTHON"""
  75. self.fromcache = InternalSpaceCache(self).getorbuild
  76. self.w_Ellipsis = special.Ellipsis()
  77. self.w_NotImplemented = special.NotImplemented()
  78. if config is None:
  79. from pypy.config.pypyoption import get_pypy_config
  80. config = get_pypy_config(translating=False)
  81. self.config = config
  82. self.interned_strings = make_weak_value_dictionary(self, str, W_Root)
  83. self.builtin = DictObject({})
  84. self.FrameClass = PyFrame
  85. self.threadlocals = ThreadLocals()
  86. self.actionflag = ActionFlag() # changed by the signal module
  87. self.check_signal_action = None # changed by the signal module
  88. def _freeze_(self):
  89. return True
  90. def is_none(self, w_obj):
  91. return w_obj is None or w_obj is self.w_None
  92. def issequence_w(self, w_obj):
  93. return isinstance(w_obj, ListObject) or isinstance(w_obj, W_NDimArray)
  94. def len(self, w_obj):
  95. if isinstance(w_obj, ListObject):
  96. return self.wrap(len(w_obj.items))
  97. elif isinstance(w_obj, DictObject):
  98. return self.wrap(len(w_obj.items))
  99. raise NotImplementedError
  100. def getattr(self, w_obj, w_attr):
  101. assert isinstance(w_attr, StringObject)
  102. if isinstance(w_obj, DictObject):
  103. return w_obj.getdictvalue(self, w_attr)
  104. return None
  105. def issubtype_w(self, w_sub, w_type):
  106. is_root(w_type)
  107. return NonConstant(True)
  108. def isinstance_w(self, w_obj, w_tp):
  109. try:
  110. return w_obj.tp == w_tp
  111. except AttributeError:
  112. return False
  113. def iter(self, w_iter):
  114. if isinstance(w_iter, ListObject):
  115. raise NotImplementedError
  116. #return IterObject(space, w_iter.items)
  117. elif isinstance(w_iter, DictObject):
  118. return IterDictObject(self, w_iter)
  119. def next(self, w_iter):
  120. return w_iter.next()
  121. def contains(self, w_iter, w_key):
  122. if isinstance(w_iter, DictObject):
  123. return self.wrap(w_key in w_iter.items)
  124. raise NotImplementedError
  125. def decode_index4(self, w_idx, size):
  126. if isinstance(w_idx, IntObject):
  127. return (self.int_w(w_idx), 0, 0, 1)
  128. else:
  129. assert isinstance(w_idx, SliceObject)
  130. start, stop, step = w_idx.start, w_idx.stop, w_idx.step
  131. if step == 0:
  132. return (0, size, 1, size)
  133. if start < 0:
  134. start += size
  135. if stop < 0:
  136. stop += size + 1
  137. if step < 0:
  138. start, stop = stop, start
  139. start -= 1
  140. stop -= 1
  141. lgt = (stop - start + 1) / step + 1
  142. else:
  143. lgt = (stop - start - 1) / step + 1
  144. return (start, stop, step, lgt)
  145. def unicode_from_object(self, w_item):
  146. # XXX
  147. return StringObject("")
  148. @specialize.argtype(1)
  149. def wrap(self, obj):
  150. if isinstance(obj, float):
  151. return FloatObject(obj)
  152. elif isinstance(obj, bool):
  153. return BoolObject(obj)
  154. elif isinstance(obj, int):
  155. return IntObject(obj)
  156. elif isinstance(obj, base_int):
  157. return LongObject(obj)
  158. elif isinstance(obj, W_Root):
  159. return obj
  160. elif isinstance(obj, str):
  161. return StringObject(obj)
  162. raise NotImplementedError
  163. def newlist(self, items):
  164. return ListObject(items)
  165. def newcomplex(self, r, i):
  166. return ComplexObject(r, i)
  167. def newfloat(self, f):
  168. return self.float(f)
  169. def newslice(self, start, stop, step):
  170. return SliceObject(self.int_w(start), self.int_w(stop),
  171. self.int_w(step))
  172. def le(self, w_obj1, w_obj2):
  173. assert isinstance(w_obj1, boxes.W_GenericBox)
  174. assert isinstance(w_obj2, boxes.W_GenericBox)
  175. return w_obj1.descr_le(self, w_obj2)
  176. def lt(self, w_obj1, w_obj2):
  177. assert isinstance(w_obj1, boxes.W_GenericBox)
  178. assert isinstance(w_obj2, boxes.W_GenericBox)
  179. return w_obj1.descr_lt(self, w_obj2)
  180. def ge(self, w_obj1, w_obj2):
  181. assert isinstance(w_obj1, boxes.W_GenericBox)
  182. assert isinstance(w_obj2, boxes.W_GenericBox)
  183. return w_obj1.descr_ge(self, w_obj2)
  184. def add(self, w_obj1, w_obj2):
  185. assert isinstance(w_obj1, boxes.W_GenericBox)
  186. assert isinstance(w_obj2, boxes.W_GenericBox)
  187. return w_obj1.descr_add(self, w_obj2)
  188. def sub(self, w_obj1, w_obj2):
  189. return self.wrap(1)
  190. def mul(self, w_obj1, w_obj2):
  191. assert isinstance(w_obj1, boxes.W_GenericBox)
  192. assert isinstance(w_obj2, boxes.W_GenericBox)
  193. return w_obj1.descr_mul(self, w_obj2)
  194. def pow(self, w_obj1, w_obj2, _):
  195. return self.wrap(1)
  196. def neg(self, w_obj1):
  197. return self.wrap(0)
  198. def repr(self, w_obj1):
  199. return self.wrap('fake')
  200. def getitem(self, obj, index):
  201. if isinstance(obj, DictObject):
  202. w_dict = obj.getdict(self)
  203. if w_dict is not None:
  204. try:
  205. return w_dict[index]
  206. except KeyError as e:
  207. raise oefmt(self.w_KeyError, "key error")
  208. assert isinstance(obj, ListObject)
  209. assert isinstance(index, IntObject)
  210. return obj.items[index.intval]
  211. def listview(self, obj, number=-1):
  212. assert isinstance(obj, ListObject)
  213. if number != -1:
  214. assert number == 2
  215. return [obj.items[0], obj.items[1]]
  216. return obj.items
  217. fixedview = listview
  218. def float(self, w_obj):
  219. if isinstance(w_obj, FloatObject):
  220. return w_obj
  221. assert isinstance(w_obj, boxes.W_GenericBox)
  222. return self.float(w_obj.descr_float(self))
  223. def float_w(self, w_obj, allow_conversion=True):
  224. assert isinstance(w_obj, FloatObject)
  225. return w_obj.floatval
  226. def int_w(self, w_obj, allow_conversion=True):
  227. if isinstance(w_obj, IntObject):
  228. return w_obj.intval
  229. elif isinstance(w_obj, FloatObject):
  230. return int(w_obj.floatval)
  231. elif isinstance(w_obj, SliceObject):
  232. raise oefmt(self.w_TypeError, "slice.")
  233. raise NotImplementedError
  234. def unpackcomplex(self, w_obj):
  235. if isinstance(w_obj, ComplexObject):
  236. return w_obj.r, w_obj.i
  237. raise NotImplementedError
  238. def index(self, w_obj):
  239. return self.wrap(self.int_w(w_obj))
  240. def str_w(self, w_obj):
  241. if isinstance(w_obj, StringObject):
  242. return w_obj.v
  243. raise NotImplementedError
  244. def unicode_w(self, w_obj):
  245. # XXX
  246. if isinstance(w_obj, StringObject):
  247. return unicode(w_obj.v)
  248. raise NotImplementedError
  249. def int(self, w_obj):
  250. if isinstance(w_obj, IntObject):
  251. return w_obj
  252. assert isinstance(w_obj, boxes.W_GenericBox)
  253. return self.int(w_obj.descr_int(self))
  254. def long(self, w_obj):
  255. if isinstance(w_obj, LongObject):
  256. return w_obj
  257. assert isinstance(w_obj, boxes.W_GenericBox)
  258. return self.int(w_obj.descr_long(self))
  259. def str(self, w_obj):
  260. if isinstance(w_obj, StringObject):
  261. return w_obj
  262. assert isinstance(w_obj, boxes.W_GenericBox)
  263. return self.str(w_obj.descr_str(self))
  264. def is_true(self, w_obj):
  265. assert isinstance(w_obj, BoolObject)
  266. return bool(w_obj.intval)
  267. def gt(self, w_lhs, w_rhs):
  268. return BoolObject(self.int_w(w_lhs) > self.int_w(w_rhs))
  269. def lt(self, w_lhs, w_rhs):
  270. return BoolObject(self.int_w(w_lhs) < self.int_w(w_rhs))
  271. def is_w(self, w_obj, w_what):
  272. return w_obj is w_what
  273. def eq_w(self, w_obj, w_what):
  274. return w_obj == w_what
  275. def issubtype(self, w_type1, w_type2):
  276. return BoolObject(True)
  277. def type(self, w_obj):
  278. if self.is_none(w_obj):
  279. return self.w_None
  280. try:
  281. return w_obj.tp
  282. except AttributeError:
  283. if isinstance(w_obj, W_NDimArray):
  284. return W_NDimArray
  285. return self.w_None
  286. def lookup(self, w_obj, name):
  287. w_type = self.type(w_obj)
  288. if not self.is_none(w_type):
  289. return w_type.lookup(name)
  290. def gettypefor(self, w_obj):
  291. return W_TypeObject(w_obj.typedef.name)
  292. def call_function(self, tp, w_dtype, *args):
  293. if tp is self.w_float:
  294. if isinstance(w_dtype, boxes.W_Float64Box):
  295. return FloatObject(float(w_dtype.value))
  296. if isinstance(w_dtype, boxes.W_Float32Box):
  297. return FloatObject(float(w_dtype.value))
  298. if isinstance(w_dtype, boxes.W_Int64Box):
  299. return FloatObject(float(int(w_dtype.value)))
  300. if isinstance(w_dtype, boxes.W_Int32Box):
  301. return FloatObject(float(int(w_dtype.value)))
  302. if isinstance(w_dtype, boxes.W_Int16Box):
  303. return FloatObject(float(int(w_dtype.value)))
  304. if isinstance(w_dtype, boxes.W_Int8Box):
  305. return FloatObject(float(int(w_dtype.value)))
  306. if isinstance(w_dtype, IntObject):
  307. return FloatObject(float(w_dtype.intval))
  308. if tp is self.w_int:
  309. if isinstance(w_dtype, FloatObject):
  310. return IntObject(int(w_dtype.floatval))
  311. return w_dtype
  312. @specialize.arg(2)
  313. def call_method(self, w_obj, s, *args):
  314. # XXX even the hacks have hacks
  315. if s == 'size': # used in _array() but never called by tests
  316. return IntObject(0)
  317. return getattr(w_obj, 'descr_' + s)(self, *args)
  318. @specialize.arg(1)
  319. def interp_w(self, tp, what):
  320. assert isinstance(what, tp)
  321. return what
  322. def allocate_instance(self, klass, w_subtype):
  323. return instantiate(klass)
  324. def newtuple(self, list_w):
  325. return ListObject(list_w)
  326. def newdict(self, module=True):
  327. return DictObject({})
  328. def newint(self, i):
  329. if isinstance(i, IntObject):
  330. return i
  331. return IntObject(i)
  332. def setitem(self, obj, index, value):
  333. obj.items[index] = value
  334. def exception_match(self, w_exc_type, w_check_class):
  335. assert isinstance(w_exc_type, W_TypeObject)
  336. assert isinstance(w_check_class, W_TypeObject)
  337. return w_exc_type.name == w_check_class.name
  338. def warn(self, w_msg, w_warn_type):
  339. pass
  340. def is_root(w_obj):
  341. assert isinstance(w_obj, W_Root)
  342. is_root.expecting = W_Root
  343. class FloatObject(W_Root):
  344. tp = FakeSpace.w_float
  345. def __init__(self, floatval):
  346. self.floatval = floatval
  347. class BoolObject(W_Root):
  348. tp = FakeSpace.w_bool
  349. def __init__(self, boolval):
  350. self.intval = boolval
  351. FakeSpace.w_True = BoolObject(True)
  352. FakeSpace.w_False = BoolObject(False)
  353. class IntObject(W_Root):
  354. tp = FakeSpace.w_int
  355. def __init__(self, intval):
  356. self.intval = intval
  357. class LongObject(W_Root):
  358. tp = FakeSpace.w_long
  359. def __init__(self, intval):
  360. self.intval = intval
  361. class ListObject(W_Root):
  362. tp = FakeSpace.w_list
  363. def __init__(self, items):
  364. self.items = items
  365. class DictObject(W_Root):
  366. tp = FakeSpace.w_dict
  367. def __init__(self, items):
  368. self.items = items
  369. def getdict(self, space):
  370. return self.items
  371. def getdictvalue(self, space, key):
  372. return self.items[key]
  373. class IterDictObject(W_Root):
  374. def __init__(self, space, w_dict):
  375. self.space = space
  376. self.items = w_dict.items.items()
  377. self.i = 0
  378. def __iter__(self):
  379. return self
  380. def next(self):
  381. space = self.space
  382. if self.i >= len(self.items):
  383. raise oefmt(space.w_StopIteration, "stop iteration")
  384. self.i += 1
  385. return self.items[self.i-1][0]
  386. class SliceObject(W_Root):
  387. tp = FakeSpace.w_slice
  388. def __init__(self, start, stop, step):
  389. self.start = start
  390. self.stop = stop
  391. self.step = step
  392. class StringObject(W_Root):
  393. tp = FakeSpace.w_str
  394. def __init__(self, v):
  395. self.v = v
  396. class ComplexObject(W_Root):
  397. tp = FakeSpace.w_complex
  398. def __init__(self, r, i):
  399. self.r = r
  400. self.i = i
  401. class InterpreterState(object):
  402. def __init__(self, code):
  403. self.code = code
  404. self.variables = {}
  405. self.results = []
  406. def run(self, space):
  407. self.space = space
  408. for stmt in self.code.statements:
  409. stmt.execute(self)
  410. class Node(object):
  411. def __eq__(self, other):
  412. return (self.__class__ == other.__class__ and
  413. self.__dict__ == other.__dict__)
  414. def __ne__(self, other):
  415. return not self == other
  416. def wrap(self, space):
  417. raise NotImplementedError
  418. def execute(self, interp):
  419. raise NotImplementedError
  420. class Assignment(Node):
  421. def __init__(self, name, expr):
  422. self.name = name
  423. self.expr = expr
  424. def execute(self, interp):
  425. interp.variables[self.name] = self.expr.execute(interp)
  426. def __repr__(self):
  427. return "%r = %r" % (self.name, self.expr)
  428. class ArrayAssignment(Node):
  429. def __init__(self, name, index, expr):
  430. self.name = name
  431. self.index = index
  432. self.expr = expr
  433. def execute(self, interp):
  434. arr = interp.variables[self.name]
  435. w_index = self.index.execute(interp)
  436. # cast to int
  437. if isinstance(w_index, FloatObject):
  438. w_index = IntObject(int(w_index.floatval))
  439. w_val = self.expr.execute(interp)
  440. assert isinstance(arr, W_NDimArray)
  441. arr.descr_setitem(interp.space, w_index, w_val)
  442. def __repr__(self):
  443. return "%s[%r] = %r" % (self.name, self.index, self.expr)
  444. class Variable(Node):
  445. def __init__(self, name):
  446. self.name = name.strip(" ")
  447. def execute(self, interp):
  448. if self.name == 'None':
  449. return None
  450. return interp.variables[self.name]
  451. def __repr__(self):
  452. return 'v(%s)' % self.name
  453. class Operator(Node):
  454. def __init__(self, lhs, name, rhs):
  455. self.name = name
  456. self.lhs = lhs
  457. self.rhs = rhs
  458. def execute(self, interp):
  459. w_lhs = self.lhs.execute(interp)
  460. if isinstance(self.rhs, SliceConstant):
  461. w_rhs = self.rhs.wrap(interp.space)
  462. else:
  463. w_rhs = self.rhs.execute(interp)
  464. if not isinstance(w_lhs, W_NDimArray):
  465. # scalar
  466. dtype = get_dtype_cache(interp.space).w_float64dtype
  467. w_lhs = W_NDimArray.new_scalar(interp.space, dtype, w_lhs)
  468. assert isinstance(w_lhs, W_NDimArray)
  469. if self.name == '+':
  470. w_res = w_lhs.descr_add(interp.space, w_rhs)
  471. elif self.name == '*':
  472. w_res = w_lhs.descr_mul(interp.space, w_rhs)
  473. elif self.name == '-':
  474. w_res = w_lhs.descr_sub(interp.space, w_rhs)
  475. elif self.name == '**':
  476. w_res = w_lhs.descr_pow(interp.space, w_rhs)
  477. elif self.name == '->':
  478. if isinstance(w_rhs, FloatObject):
  479. w_rhs = IntObject(int(w_rhs.floatval))
  480. assert isinstance(w_lhs, W_NDimArray)
  481. w_res = w_lhs.descr_getitem(interp.space, w_rhs)
  482. if isinstance(w_rhs, IntObject):
  483. if isinstance(w_res, boxes.W_Float64Box):
  484. print "access", w_lhs, "[", w_rhs.intval, "] => ", float(w_res.value)
  485. if isinstance(w_res, boxes.W_Float32Box):
  486. print "access", w_lhs, "[", w_rhs.intval, "] => ", float(w_res.value)
  487. if isinstance(w_res, boxes.W_Int64Box):
  488. print "access", w_lhs, "[", w_rhs.intval, "] => ", int(w_res.value)
  489. if isinstance(w_res, boxes.W_Int32Box):
  490. print "access", w_lhs, "[", w_rhs.intval, "] => ", int(w_res.value)
  491. else:
  492. raise NotImplementedError
  493. if (not isinstance(w_res, W_NDimArray) and
  494. not isinstance(w_res, boxes.W_GenericBox)):
  495. dtype = get_dtype_cache(interp.space).w_float64dtype
  496. w_res = W_NDimArray.new_scalar(interp.space, dtype, w_res)
  497. return w_res
  498. def __repr__(self):
  499. return '(%r %s %r)' % (self.lhs, self.name, self.rhs)
  500. class NumberConstant(Node):
  501. def __init__(self, v):
  502. if isinstance(v, int):
  503. self.v = v
  504. elif isinstance(v, float):
  505. self.v = v
  506. else:
  507. assert isinstance(v, str)
  508. assert len(v) > 0
  509. c = v[-1]
  510. if c == 'f':
  511. self.v = float(v[:-1])
  512. elif c == 'i':
  513. self.v = int(v[:-1])
  514. else:
  515. self.v = float(v)
  516. def __repr__(self):
  517. return "Const(%s)" % self.v
  518. def wrap(self, space):
  519. return space.wrap(self.v)
  520. def execute(self, interp):
  521. return interp.space.wrap(self.v)
  522. class ComplexConstant(Node):
  523. def __init__(self, r, i):
  524. self.r = float(r)
  525. self.i = float(i)
  526. def __repr__(self):
  527. return 'ComplexConst(%s, %s)' % (self.r, self.i)
  528. def wrap(self, space):
  529. return space.newcomplex(self.r, self.i)
  530. def execute(self, interp):
  531. return self.wrap(interp.space)
  532. class RangeConstant(Node):
  533. def __init__(self, v):
  534. self.v = int(v)
  535. def execute(self, interp):
  536. w_list = interp.space.newlist(
  537. [interp.space.wrap(float(i)) for i in range(self.v)]
  538. )
  539. dtype = get_dtype_cache(interp.space).w_float64dtype
  540. return array(interp.space, w_list, w_dtype=dtype, w_order=None)
  541. def __repr__(self):
  542. return 'Range(%s)' % self.v
  543. class Code(Node):
  544. def __init__(self, statements):
  545. self.statements = statements
  546. def __repr__(self):
  547. return "\n".join([repr(i) for i in self.statements])
  548. class ArrayConstant(Node):
  549. def __init__(self, items):
  550. self.items = items
  551. def wrap(self, space):
  552. return space.newlist([item.wrap(space) for item in self.items])
  553. def execute(self, interp):
  554. w_list = self.wrap(interp.space)
  555. return array(interp.space, w_list)
  556. def __repr__(self):
  557. return "[" + ", ".join([repr(item) for item in self.items]) + "]"
  558. class SliceConstant(Node):
  559. def __init__(self, start, stop, step):
  560. self.start = start
  561. self.stop = stop
  562. self.step = step
  563. def wrap(self, space):
  564. return SliceObject(self.start, self.stop, self.step)
  565. def execute(self, interp):
  566. return SliceObject(self.start, self.stop, self.step)
  567. def __repr__(self):
  568. return 'slice(%s,%s,%s)' % (self.start, self.stop, self.step)
  569. class ArrayClass(Node):
  570. def __init__(self):
  571. self.v = W_NDimArray
  572. def execute(self, interp):
  573. return self.v
  574. def __repr__(self):
  575. return '<class W_NDimArray>'
  576. class DtypeClass(Node):
  577. def __init__(self, dt):
  578. self.v = dt
  579. def execute(self, interp):
  580. if self.v == 'int':
  581. dtype = get_dtype_cache(interp.space).w_int64dtype
  582. elif self.v == 'int8':
  583. dtype = get_dtype_cache(interp.space).w_int8dtype
  584. elif self.v == 'int16':
  585. dtype = get_dtype_cache(interp.space).w_int16dtype
  586. elif self.v == 'int32':
  587. dtype = get_dtype_cache(interp.space).w_int32dtype
  588. elif self.v == 'uint':
  589. dtype = get_dtype_cache(interp.space).w_uint64dtype
  590. elif self.v == 'uint8':
  591. dtype = get_dtype_cache(interp.space).w_uint8dtype
  592. elif self.v == 'uint16':
  593. dtype = get_dtype_cache(interp.space).w_uint16dtype
  594. elif self.v == 'uint32':
  595. dtype = get_dtype_cache(interp.space).w_uint32dtype
  596. elif self.v == 'float':
  597. dtype = get_dtype_cache(interp.space).w_float64dtype
  598. elif self.v == 'float32':
  599. dtype = get_dtype_cache(interp.space).w_float32dtype
  600. else:
  601. raise BadToken('unknown v to dtype "%s"' % self.v)
  602. return dtype
  603. def __repr__(self):
  604. return '<class %s dtype>' % self.v
  605. class Execute(Node):
  606. def __init__(self, expr):
  607. self.expr = expr
  608. def __repr__(self):
  609. return repr(self.expr)
  610. def execute(self, interp):
  611. interp.results.append(self.expr.execute(interp))
  612. class FunctionCall(Node):
  613. def __init__(self, name, args):
  614. self.name = name.strip(" ")
  615. self.args = args
  616. def __repr__(self):
  617. return "%s(%s)" % (self.name, ", ".join([repr(arg)
  618. for arg in self.args]))
  619. def execute(self, interp):
  620. arr = self.args[0].execute(interp)
  621. if not isinstance(arr, W_NDimArray):
  622. raise ArgumentNotAnArray
  623. if self.name in SINGLE_ARG_FUNCTIONS:
  624. if len(self.args) != 1 and self.name != 'sum':
  625. raise ArgumentMismatch
  626. if self.name == "sum":
  627. if len(self.args)>1:
  628. var = self.args[1]
  629. if isinstance(var, DtypeClass):
  630. w_res = arr.descr_sum(interp.space, None, var.execute(interp))
  631. else:
  632. w_res = arr.descr_sum(interp.space,
  633. self.args[1].execute(interp))
  634. else:
  635. w_res = arr.descr_sum(interp.space)
  636. elif self.name == "prod":
  637. w_res = arr.descr_prod(interp.space)
  638. elif self.name == "max":
  639. w_res = arr.descr_max(interp.space)
  640. elif self.name == "min":
  641. w_res = arr.descr_min(interp.space)
  642. elif self.name == "any":
  643. w_res = arr.descr_any(interp.space)
  644. elif self.name == "all":
  645. w_res = arr.descr_all(interp.space)
  646. elif self.name == "cumsum":
  647. w_res = arr.descr_cumsum(interp.space)
  648. elif self.name == "logical_xor_reduce":
  649. logical_xor = ufuncs.get(interp.space).logical_xor
  650. w_res = logical_xor.reduce(interp.space, arr, None)
  651. elif self.name == "unegative":
  652. neg = ufuncs.get(interp.space).negative
  653. w_res = neg.call(interp.space, [arr], None, 'unsafe', None)
  654. elif self.name == "cos":
  655. cos = ufuncs.get(interp.space).cos
  656. w_res = cos.call(interp.space, [arr], None, 'unsafe', None)
  657. elif self.name == "flat":
  658. w_res = arr.descr_get_flatiter(interp.space)
  659. elif self.name == "argsort":
  660. w_res = arr.descr_argsort(interp.space)
  661. elif self.name == "tostring":
  662. arr.descr_tostring(interp.space)
  663. w_res = None
  664. else:
  665. assert False # unreachable code
  666. elif self.name in TWO_ARG_FUNCTIONS:
  667. if len(self.args) != 2:
  668. raise ArgumentMismatch
  669. arg = self.args[1].execute(interp)
  670. if not isinstance(arg, W_NDimArray):
  671. raise ArgumentNotAnArray
  672. if self.name == "dot":
  673. w_res = arr.descr_dot(interp.space, arg)
  674. elif self.name == 'multiply':
  675. w_res = arr.descr_mul(interp.space, arg)
  676. elif self.name == 'take':
  677. w_res = arr.descr_take(interp.space, arg)
  678. elif self.name == "searchsorted":
  679. w_res = arr.descr_searchsorted(interp.space, arg,
  680. interp.space.wrap('left'))
  681. else:
  682. assert False # unreachable code
  683. elif self.name in THREE_ARG_FUNCTIONS:
  684. if len(self.args) != 3:
  685. raise ArgumentMismatch
  686. arg1 = self.args[1].execute(interp)
  687. arg2 = self.args[2].execute(interp)
  688. if not isinstance(arg1, W_NDimArray):
  689. raise ArgumentNotAnArray
  690. if not isinstance(arg2, W_NDimArray):
  691. raise ArgumentNotAnArray
  692. if self.name == "where":
  693. w_res = where(interp.space, arr, arg1, arg2)
  694. else:
  695. assert False # unreachable code
  696. elif self.name in TWO_ARG_FUNCTIONS_OR_NONE:
  697. if len(self.args) != 2:
  698. raise ArgumentMismatch
  699. arg = self.args[1].execute(interp)
  700. if self.name == 'view':
  701. w_res = arr.descr_view(interp.space, arg)
  702. elif self.name == 'astype':
  703. w_res = arr.descr_astype(interp.space, arg)
  704. elif self.name == 'reshape':
  705. w_arg = self.args[1]
  706. assert isinstance(w_arg, ArrayConstant)
  707. order = -1
  708. w_res = arr.reshape(interp.space, w_arg.wrap(interp.space), order)
  709. else:
  710. assert False
  711. else:
  712. raise WrongFunctionName
  713. if isinstance(w_res, W_NDimArray):
  714. return w_res
  715. if isinstance(w_res, FloatObject):
  716. dtype = get_dtype_cache(interp.space).w_float64dtype
  717. elif isinstance(w_res, IntObject):
  718. dtype = get_dtype_cache(interp.space).w_int64dtype
  719. elif isinstance(w_res, BoolObject):
  720. dtype = get_dtype_cache(interp.space).w_booldtype
  721. elif isinstance(w_res, boxes.W_GenericBox):
  722. dtype = w_res.get_dtype(interp.space)
  723. else:
  724. dtype = None
  725. return W_NDimArray.new_scalar(interp.space, dtype, w_res)
  726. _REGEXES = [
  727. ('-?[\d\.]+(i|f)?', 'number'),
  728. ('\[', 'array_left'),
  729. (':', 'colon'),
  730. ('\w+', 'identifier'),
  731. ('\]', 'array_right'),
  732. ('(->)|[\+\-\*\/]+', 'operator'),
  733. ('=', 'assign'),
  734. (',', 'comma'),
  735. ('\|', 'pipe'),
  736. ('\(', 'paren_left'),
  737. ('\)', 'paren_right'),
  738. ]
  739. REGEXES = []
  740. for r, name in _REGEXES:
  741. REGEXES.append((re.compile(r' *(' + r + ')'), name))
  742. del _REGEXES
  743. class Token(object):
  744. def __init__(self, name, v):
  745. self.name = name
  746. self.v = v
  747. def __repr__(self):
  748. return '(%s, %s)' % (self.name, self.v)
  749. empty = Token('', '')
  750. class TokenStack(object):
  751. def __init__(self, tokens):
  752. self.tokens = tokens
  753. self.c = 0
  754. def pop(self):
  755. token = self.tokens[self.c]
  756. self.c += 1
  757. return token
  758. def get(self, i):
  759. if self.c + i >= len(self.tokens):
  760. return empty
  761. return self.tokens[self.c + i]
  762. def remaining(self):
  763. return len(self.tokens) - self.c
  764. def push(self):
  765. self.c -= 1
  766. def __repr__(self):
  767. return repr(self.tokens[self.c:])
  768. class Parser(object):
  769. def tokenize(self, line):
  770. tokens = []
  771. while True:
  772. for r, name in REGEXES:
  773. m = r.match(line)
  774. if m is not None:
  775. g = m.group(0)
  776. tokens.append(Token(name, g))
  777. line = line[len(g):]
  778. if not line:
  779. return TokenStack(tokens)
  780. break
  781. else:
  782. raise TokenizerError(line)
  783. def parse_number_or_slice(self, tokens):
  784. start_tok = tokens.pop()
  785. if start_tok.name == 'colon':
  786. start = 0
  787. else:
  788. if tokens.get(0).name != 'colon':
  789. return NumberConstant(start_tok.v)
  790. start = int(start_tok.v)
  791. tokens.pop()
  792. if not tokens.get(0).name in ['colon', 'number']:
  793. stop = -1
  794. step = 1
  795. else:
  796. next = tokens.pop()
  797. if next.name == 'colon':
  798. stop = -1
  799. step = int(tokens.pop().v)
  800. else:
  801. stop = int(next.v)
  802. if tokens.get(0).name == 'colon':
  803. tokens.pop()
  804. step = int(tokens.pop().v)
  805. else:
  806. step = 1
  807. return SliceConstant(start, stop, step)
  808. def parse_expression(self, tokens, accept_comma=False):
  809. stack = []
  810. while tokens.remaining():
  811. token = tokens.pop()
  812. if token.name == 'identifier':
  813. if tokens.remaining() and tokens.get(0).name == 'paren_left':
  814. stack.append(self.parse_function_call(token.v, tokens))
  815. elif token.v.strip(' ') == 'ndarray':
  816. stack.append(ArrayClass())
  817. elif token.v.strip(' ') == 'int':
  818. stack.append(DtypeClass('int'))
  819. elif token.v.strip(' ') == 'int8':
  820. stack.append(DtypeClass('int8'))
  821. elif token.v.strip(' ') == 'int16':
  822. stack.append(DtypeClass('int16'))
  823. elif token.v.strip(' ') == 'int32':
  824. stack.append(DtypeClass('int32'))
  825. elif token.v.strip(' ') == 'int64':
  826. stack.append(DtypeClass('int'))
  827. elif token.v.strip(' ') == 'uint':
  828. stack.append(DtypeClass('uint'))
  829. elif token.v.strip(' ') == 'uint8':
  830. stack.append(DtypeClass('uint8'))
  831. elif token.v.strip(' ') == 'uint16':
  832. stack.append(DtypeClass('uint16'))
  833. elif token.v.strip(' ') == 'uint32':
  834. stack.append(DtypeClass('uint32'))
  835. elif token.v.strip(' ') == 'uint64':
  836. stack.append(DtypeClass('uint'))
  837. elif token.v.strip(' ') == 'float':
  838. stack.append(DtypeClass('float'))
  839. elif token.v.strip(' ') == 'float32':
  840. stack.append(DtypeClass('float32'))
  841. elif token.v.strip(' ') == 'float64':
  842. stack.append(DtypeClass('float'))
  843. else:
  844. stack.append(Variable(token.v.strip(' ')))
  845. elif token.name == 'array_left':
  846. stack.append(ArrayConstant(self.parse_array_const(tokens)))
  847. elif token.name == 'operator':
  848. stack.append(Variable(token.v))
  849. elif token.name == 'number' or token.name == 'colon':
  850. tokens.push()
  851. stack.append(self.parse_number_or_slice(tokens))
  852. elif token.name == 'pipe':
  853. stack.append(RangeConstant(tokens.pop().v))
  854. end = tokens.pop()
  855. assert end.name == 'pipe'
  856. elif token.name == 'paren_left':
  857. stack.append(self.parse_complex_constant(tokens))
  858. elif accept_comma and token.name == 'comma':
  859. continue
  860. else:
  861. tokens.push()
  862. break
  863. if accept_comma:
  864. return stack
  865. stack.reverse()
  866. lhs = stack.pop()
  867. while stack:
  868. op = stack.pop()
  869. assert isinstance(op, Variable)
  870. rhs = stack.pop()
  871. lhs = Operator(lhs, op.name, rhs)
  872. return lhs
  873. def parse_function_call(self, name, tokens):
  874. args = []
  875. tokens.pop() # lparen
  876. while tokens.get(0).name != 'paren_right':
  877. args += self.parse_expression(tokens, accept_comma=True)
  878. return FunctionCall(name, args)
  879. def parse_complex_constant(self, tokens):
  880. r = tokens.pop()
  881. assert r.name == 'number'
  882. assert tokens.pop().name == 'comma'
  883. i = tokens.pop()
  884. assert i.name == 'number'
  885. assert tokens.pop().name == 'paren_right'
  886. return ComplexConstant(r.v, i.v)
  887. def parse_array_const(self, tokens):
  888. elems = []
  889. while True:
  890. token = tokens.pop()
  891. if token.name == 'number':
  892. elems.append(NumberConstant(token.v))
  893. elif token.name == 'array_left':
  894. elems.append(ArrayConstant(self.parse_array_const(tokens)))
  895. elif token.name == 'paren_left':
  896. elems.append(self.parse_complex_constant(tokens))
  897. else:
  898. raise BadToken()
  899. token = tokens.pop()
  900. if token.name == 'array_right':
  901. return elems
  902. assert token.name == 'comma'
  903. def parse_statement(self, tokens):
  904. if (tokens.get(0).name == 'identifier' and
  905. tokens.get(1).name == 'assign'):
  906. lhs = tokens.pop().v
  907. tokens.pop()
  908. rhs = self.parse_expression(tokens)
  909. return Assignment(lhs, rhs)
  910. elif (tokens.get(0).name == 'identifier' and
  911. tokens.get(1).name == 'array_left'):
  912. name = tokens.pop().v
  913. tokens.pop()
  914. index = self.parse_expression(tokens)
  915. tokens.pop()
  916. tokens.pop()
  917. return ArrayAssignment(name, index, self.parse_expression(tokens))
  918. return Execute(self.parse_expression(tokens))
  919. def parse(self, code):
  920. statements = []
  921. for line in code.split("\n"):
  922. if '#' in line:
  923. line = line.split('#', 1)[0]
  924. line = line.strip(" ")
  925. if line:
  926. tokens = self.tokenize(line)
  927. statements.append(self.parse_statement(tokens))
  928. return Code(statements)
  929. def numpy_compile(code):
  930. parser = Parser()
  931. return InterpreterState(parser.parse(code))