PageRenderTime 68ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/micronumpy/compile.py

https://bitbucket.org/pjenvey/pypy-mq
Python | 1102 lines | 1068 code | 28 blank | 6 comment | 18 complexity | e42cc23e108506a64ec7939ef75e2c6c MD5 | raw file
Possible License(s): Apache-2.0, AGPL-3.0, BSD-3-Clause
  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. if s == '__buffer__':
  318. # descr___buffer__ does not exist on W_Root
  319. return self.w_None
  320. return getattr(w_obj, 'descr_' + s)(self, *args)
  321. @specialize.arg(1)
  322. def interp_w(self, tp, what):
  323. assert isinstance(what, tp)
  324. return what
  325. def allocate_instance(self, klass, w_subtype):
  326. return instantiate(klass)
  327. def newtuple(self, list_w):
  328. return ListObject(list_w)
  329. def newdict(self, module=True):
  330. return DictObject({})
  331. def newint(self, i):
  332. if isinstance(i, IntObject):
  333. return i
  334. return IntObject(i)
  335. def setitem(self, obj, index, value):
  336. obj.items[index] = value
  337. def exception_match(self, w_exc_type, w_check_class):
  338. assert isinstance(w_exc_type, W_TypeObject)
  339. assert isinstance(w_check_class, W_TypeObject)
  340. return w_exc_type.name == w_check_class.name
  341. def warn(self, w_msg, w_warn_type):
  342. pass
  343. def is_root(w_obj):
  344. assert isinstance(w_obj, W_Root)
  345. is_root.expecting = W_Root
  346. class FloatObject(W_Root):
  347. tp = FakeSpace.w_float
  348. def __init__(self, floatval):
  349. self.floatval = floatval
  350. class BoolObject(W_Root):
  351. tp = FakeSpace.w_bool
  352. def __init__(self, boolval):
  353. self.intval = boolval
  354. FakeSpace.w_True = BoolObject(True)
  355. FakeSpace.w_False = BoolObject(False)
  356. class IntObject(W_Root):
  357. tp = FakeSpace.w_int
  358. def __init__(self, intval):
  359. self.intval = intval
  360. class LongObject(W_Root):
  361. tp = FakeSpace.w_long
  362. def __init__(self, intval):
  363. self.intval = intval
  364. class ListObject(W_Root):
  365. tp = FakeSpace.w_list
  366. def __init__(self, items):
  367. self.items = items
  368. class DictObject(W_Root):
  369. tp = FakeSpace.w_dict
  370. def __init__(self, items):
  371. self.items = items
  372. def getdict(self, space):
  373. return self.items
  374. def getdictvalue(self, space, key):
  375. return self.items[key]
  376. def descr_memoryview(self, space, buf):
  377. raise oefmt(space.w_TypeError, "error")
  378. class IterDictObject(W_Root):
  379. def __init__(self, space, w_dict):
  380. self.space = space
  381. self.items = w_dict.items.items()
  382. self.i = 0
  383. def __iter__(self):
  384. return self
  385. def next(self):
  386. space = self.space
  387. if self.i >= len(self.items):
  388. raise oefmt(space.w_StopIteration, "stop iteration")
  389. self.i += 1
  390. return self.items[self.i-1][0]
  391. class SliceObject(W_Root):
  392. tp = FakeSpace.w_slice
  393. def __init__(self, start, stop, step):
  394. self.start = start
  395. self.stop = stop
  396. self.step = step
  397. class StringObject(W_Root):
  398. tp = FakeSpace.w_str
  399. def __init__(self, v):
  400. self.v = v
  401. class ComplexObject(W_Root):
  402. tp = FakeSpace.w_complex
  403. def __init__(self, r, i):
  404. self.r = r
  405. self.i = i
  406. class InterpreterState(object):
  407. def __init__(self, code):
  408. self.code = code
  409. self.variables = {}
  410. self.results = []
  411. def run(self, space):
  412. self.space = space
  413. for stmt in self.code.statements:
  414. stmt.execute(self)
  415. class Node(object):
  416. def __eq__(self, other):
  417. return (self.__class__ == other.__class__ and
  418. self.__dict__ == other.__dict__)
  419. def __ne__(self, other):
  420. return not self == other
  421. def wrap(self, space):
  422. raise NotImplementedError
  423. def execute(self, interp):
  424. raise NotImplementedError
  425. class Assignment(Node):
  426. def __init__(self, name, expr):
  427. self.name = name
  428. self.expr = expr
  429. def execute(self, interp):
  430. interp.variables[self.name] = self.expr.execute(interp)
  431. def __repr__(self):
  432. return "%r = %r" % (self.name, self.expr)
  433. class ArrayAssignment(Node):
  434. def __init__(self, name, index, expr):
  435. self.name = name
  436. self.index = index
  437. self.expr = expr
  438. def execute(self, interp):
  439. arr = interp.variables[self.name]
  440. w_index = self.index.execute(interp)
  441. # cast to int
  442. if isinstance(w_index, FloatObject):
  443. w_index = IntObject(int(w_index.floatval))
  444. w_val = self.expr.execute(interp)
  445. assert isinstance(arr, W_NDimArray)
  446. arr.descr_setitem(interp.space, w_index, w_val)
  447. def __repr__(self):
  448. return "%s[%r] = %r" % (self.name, self.index, self.expr)
  449. class Variable(Node):
  450. def __init__(self, name):
  451. self.name = name.strip(" ")
  452. def execute(self, interp):
  453. if self.name == 'None':
  454. return None
  455. return interp.variables[self.name]
  456. def __repr__(self):
  457. return 'v(%s)' % self.name
  458. class Operator(Node):
  459. def __init__(self, lhs, name, rhs):
  460. self.name = name
  461. self.lhs = lhs
  462. self.rhs = rhs
  463. def execute(self, interp):
  464. w_lhs = self.lhs.execute(interp)
  465. if isinstance(self.rhs, SliceConstant):
  466. w_rhs = self.rhs.wrap(interp.space)
  467. else:
  468. w_rhs = self.rhs.execute(interp)
  469. if not isinstance(w_lhs, W_NDimArray):
  470. # scalar
  471. dtype = get_dtype_cache(interp.space).w_float64dtype
  472. w_lhs = W_NDimArray.new_scalar(interp.space, dtype, w_lhs)
  473. assert isinstance(w_lhs, W_NDimArray)
  474. if self.name == '+':
  475. w_res = w_lhs.descr_add(interp.space, w_rhs)
  476. elif self.name == '*':
  477. w_res = w_lhs.descr_mul(interp.space, w_rhs)
  478. elif self.name == '-':
  479. w_res = w_lhs.descr_sub(interp.space, w_rhs)
  480. elif self.name == '**':
  481. w_res = w_lhs.descr_pow(interp.space, w_rhs)
  482. elif self.name == '->':
  483. if isinstance(w_rhs, FloatObject):
  484. w_rhs = IntObject(int(w_rhs.floatval))
  485. assert isinstance(w_lhs, W_NDimArray)
  486. w_res = w_lhs.descr_getitem(interp.space, w_rhs)
  487. if isinstance(w_rhs, IntObject):
  488. if isinstance(w_res, boxes.W_Float64Box):
  489. print "access", w_lhs, "[", w_rhs.intval, "] => ", float(w_res.value)
  490. if isinstance(w_res, boxes.W_Float32Box):
  491. print "access", w_lhs, "[", w_rhs.intval, "] => ", float(w_res.value)
  492. if isinstance(w_res, boxes.W_Int64Box):
  493. print "access", w_lhs, "[", w_rhs.intval, "] => ", int(w_res.value)
  494. if isinstance(w_res, boxes.W_Int32Box):
  495. print "access", w_lhs, "[", w_rhs.intval, "] => ", int(w_res.value)
  496. else:
  497. raise NotImplementedError
  498. if (not isinstance(w_res, W_NDimArray) and
  499. not isinstance(w_res, boxes.W_GenericBox)):
  500. dtype = get_dtype_cache(interp.space).w_float64dtype
  501. w_res = W_NDimArray.new_scalar(interp.space, dtype, w_res)
  502. return w_res
  503. def __repr__(self):
  504. return '(%r %s %r)' % (self.lhs, self.name, self.rhs)
  505. class NumberConstant(Node):
  506. def __init__(self, v):
  507. if isinstance(v, int):
  508. self.v = v
  509. elif isinstance(v, float):
  510. self.v = v
  511. else:
  512. assert isinstance(v, str)
  513. assert len(v) > 0
  514. c = v[-1]
  515. if c == 'f':
  516. self.v = float(v[:-1])
  517. elif c == 'i':
  518. self.v = int(v[:-1])
  519. else:
  520. self.v = float(v)
  521. def __repr__(self):
  522. return "Const(%s)" % self.v
  523. def wrap(self, space):
  524. return space.wrap(self.v)
  525. def execute(self, interp):
  526. return interp.space.wrap(self.v)
  527. class ComplexConstant(Node):
  528. def __init__(self, r, i):
  529. self.r = float(r)
  530. self.i = float(i)
  531. def __repr__(self):
  532. return 'ComplexConst(%s, %s)' % (self.r, self.i)
  533. def wrap(self, space):
  534. return space.newcomplex(self.r, self.i)
  535. def execute(self, interp):
  536. return self.wrap(interp.space)
  537. class RangeConstant(Node):
  538. def __init__(self, v):
  539. self.v = int(v)
  540. def execute(self, interp):
  541. w_list = interp.space.newlist(
  542. [interp.space.wrap(float(i)) for i in range(self.v)]
  543. )
  544. dtype = get_dtype_cache(interp.space).w_float64dtype
  545. return array(interp.space, w_list, w_dtype=dtype, w_order=None)
  546. def __repr__(self):
  547. return 'Range(%s)' % self.v
  548. class Code(Node):
  549. def __init__(self, statements):
  550. self.statements = statements
  551. def __repr__(self):
  552. return "\n".join([repr(i) for i in self.statements])
  553. class ArrayConstant(Node):
  554. def __init__(self, items):
  555. self.items = items
  556. def wrap(self, space):
  557. return space.newlist([item.wrap(space) for item in self.items])
  558. def execute(self, interp):
  559. w_list = self.wrap(interp.space)
  560. return array(interp.space, w_list)
  561. def __repr__(self):
  562. return "[" + ", ".join([repr(item) for item in self.items]) + "]"
  563. class SliceConstant(Node):
  564. def __init__(self, start, stop, step):
  565. self.start = start
  566. self.stop = stop
  567. self.step = step
  568. def wrap(self, space):
  569. return SliceObject(self.start, self.stop, self.step)
  570. def execute(self, interp):
  571. return SliceObject(self.start, self.stop, self.step)
  572. def __repr__(self):
  573. return 'slice(%s,%s,%s)' % (self.start, self.stop, self.step)
  574. class ArrayClass(Node):
  575. def __init__(self):
  576. self.v = W_NDimArray
  577. def execute(self, interp):
  578. return self.v
  579. def __repr__(self):
  580. return '<class W_NDimArray>'
  581. class DtypeClass(Node):
  582. def __init__(self, dt):
  583. self.v = dt
  584. def execute(self, interp):
  585. if self.v == 'int':
  586. dtype = get_dtype_cache(interp.space).w_int64dtype
  587. elif self.v == 'int8':
  588. dtype = get_dtype_cache(interp.space).w_int8dtype
  589. elif self.v == 'int16':
  590. dtype = get_dtype_cache(interp.space).w_int16dtype
  591. elif self.v == 'int32':
  592. dtype = get_dtype_cache(interp.space).w_int32dtype
  593. elif self.v == 'uint':
  594. dtype = get_dtype_cache(interp.space).w_uint64dtype
  595. elif self.v == 'uint8':
  596. dtype = get_dtype_cache(interp.space).w_uint8dtype
  597. elif self.v == 'uint16':
  598. dtype = get_dtype_cache(interp.space).w_uint16dtype
  599. elif self.v == 'uint32':
  600. dtype = get_dtype_cache(interp.space).w_uint32dtype
  601. elif self.v == 'float':
  602. dtype = get_dtype_cache(interp.space).w_float64dtype
  603. elif self.v == 'float32':
  604. dtype = get_dtype_cache(interp.space).w_float32dtype
  605. else:
  606. raise BadToken('unknown v to dtype "%s"' % self.v)
  607. return dtype
  608. def __repr__(self):
  609. return '<class %s dtype>' % self.v
  610. class Execute(Node):
  611. def __init__(self, expr):
  612. self.expr = expr
  613. def __repr__(self):
  614. return repr(self.expr)
  615. def execute(self, interp):
  616. interp.results.append(self.expr.execute(interp))
  617. class FunctionCall(Node):
  618. def __init__(self, name, args):
  619. self.name = name.strip(" ")
  620. self.args = args
  621. def __repr__(self):
  622. return "%s(%s)" % (self.name, ", ".join([repr(arg)
  623. for arg in self.args]))
  624. def execute(self, interp):
  625. arr = self.args[0].execute(interp)
  626. if not isinstance(arr, W_NDimArray):
  627. raise ArgumentNotAnArray
  628. if self.name in SINGLE_ARG_FUNCTIONS:
  629. if len(self.args) != 1 and self.name != 'sum':
  630. raise ArgumentMismatch
  631. if self.name == "sum":
  632. if len(self.args)>1:
  633. var = self.args[1]
  634. if isinstance(var, DtypeClass):
  635. w_res = arr.descr_sum(interp.space, None, var.execute(interp))
  636. else:
  637. w_res = arr.descr_sum(interp.space,
  638. self.args[1].execute(interp))
  639. else:
  640. w_res = arr.descr_sum(interp.space)
  641. elif self.name == "prod":
  642. w_res = arr.descr_prod(interp.space)
  643. elif self.name == "max":
  644. w_res = arr.descr_max(interp.space)
  645. elif self.name == "min":
  646. w_res = arr.descr_min(interp.space)
  647. elif self.name == "any":
  648. w_res = arr.descr_any(interp.space)
  649. elif self.name == "all":
  650. w_res = arr.descr_all(interp.space)
  651. elif self.name == "cumsum":
  652. w_res = arr.descr_cumsum(interp.space)
  653. elif self.name == "logical_xor_reduce":
  654. logical_xor = ufuncs.get(interp.space).logical_xor
  655. w_res = logical_xor.reduce(interp.space, arr, None)
  656. elif self.name == "unegative":
  657. neg = ufuncs.get(interp.space).negative
  658. w_res = neg.call(interp.space, [arr], None, 'unsafe', None)
  659. elif self.name == "cos":
  660. cos = ufuncs.get(interp.space).cos
  661. w_res = cos.call(interp.space, [arr], None, 'unsafe', None)
  662. elif self.name == "flat":
  663. w_res = arr.descr_get_flatiter(interp.space)
  664. elif self.name == "argsort":
  665. w_res = arr.descr_argsort(interp.space)
  666. elif self.name == "tostring":
  667. arr.descr_tostring(interp.space)
  668. w_res = None
  669. else:
  670. assert False # unreachable code
  671. elif self.name in TWO_ARG_FUNCTIONS:
  672. if len(self.args) != 2:
  673. raise ArgumentMismatch
  674. arg = self.args[1].execute(interp)
  675. if not isinstance(arg, W_NDimArray):
  676. raise ArgumentNotAnArray
  677. if self.name == "dot":
  678. w_res = arr.descr_dot(interp.space, arg)
  679. elif self.name == 'multiply':
  680. w_res = arr.descr_mul(interp.space, arg)
  681. elif self.name == 'take':
  682. w_res = arr.descr_take(interp.space, arg)
  683. elif self.name == "searchsorted":
  684. w_res = arr.descr_searchsorted(interp.space, arg,
  685. interp.space.wrap('left'))
  686. else:
  687. assert False # unreachable code
  688. elif self.name in THREE_ARG_FUNCTIONS:
  689. if len(self.args) != 3:
  690. raise ArgumentMismatch
  691. arg1 = self.args[1].execute(interp)
  692. arg2 = self.args[2].execute(interp)
  693. if not isinstance(arg1, W_NDimArray):
  694. raise ArgumentNotAnArray
  695. if not isinstance(arg2, W_NDimArray):
  696. raise ArgumentNotAnArray
  697. if self.name == "where":
  698. w_res = where(interp.space, arr, arg1, arg2)
  699. else:
  700. assert False # unreachable code
  701. elif self.name in TWO_ARG_FUNCTIONS_OR_NONE:
  702. if len(self.args) != 2:
  703. raise ArgumentMismatch
  704. arg = self.args[1].execute(interp)
  705. if self.name == 'view':
  706. w_res = arr.descr_view(interp.space, arg)
  707. elif self.name == 'astype':
  708. w_res = arr.descr_astype(interp.space, arg)
  709. elif self.name == 'reshape':
  710. w_arg = self.args[1]
  711. assert isinstance(w_arg, ArrayConstant)
  712. order = -1
  713. w_res = arr.reshape(interp.space, w_arg.wrap(interp.space), order)
  714. else:
  715. assert False
  716. else:
  717. raise WrongFunctionName
  718. if isinstance(w_res, W_NDimArray):
  719. return w_res
  720. if isinstance(w_res, FloatObject):
  721. dtype = get_dtype_cache(interp.space).w_float64dtype
  722. elif isinstance(w_res, IntObject):
  723. dtype = get_dtype_cache(interp.space).w_int64dtype
  724. elif isinstance(w_res, BoolObject):
  725. dtype = get_dtype_cache(interp.space).w_booldtype
  726. elif isinstance(w_res, boxes.W_GenericBox):
  727. dtype = w_res.get_dtype(interp.space)
  728. else:
  729. dtype = None
  730. return W_NDimArray.new_scalar(interp.space, dtype, w_res)
  731. _REGEXES = [
  732. ('-?[\d\.]+(i|f)?', 'number'),
  733. ('\[', 'array_left'),
  734. (':', 'colon'),
  735. ('\w+', 'identifier'),
  736. ('\]', 'array_right'),
  737. ('(->)|[\+\-\*\/]+', 'operator'),
  738. ('=', 'assign'),
  739. (',', 'comma'),
  740. ('\|', 'pipe'),
  741. ('\(', 'paren_left'),
  742. ('\)', 'paren_right'),
  743. ]
  744. REGEXES = []
  745. for r, name in _REGEXES:
  746. REGEXES.append((re.compile(r' *(' + r + ')'), name))
  747. del _REGEXES
  748. class Token(object):
  749. def __init__(self, name, v):
  750. self.name = name
  751. self.v = v
  752. def __repr__(self):
  753. return '(%s, %s)' % (self.name, self.v)
  754. empty = Token('', '')
  755. class TokenStack(object):
  756. def __init__(self, tokens):
  757. self.tokens = tokens
  758. self.c = 0
  759. def pop(self):
  760. token = self.tokens[self.c]
  761. self.c += 1
  762. return token
  763. def get(self, i):
  764. if self.c + i >= len(self.tokens):
  765. return empty
  766. return self.tokens[self.c + i]
  767. def remaining(self):
  768. return len(self.tokens) - self.c
  769. def push(self):
  770. self.c -= 1
  771. def __repr__(self):
  772. return repr(self.tokens[self.c:])
  773. class Parser(object):
  774. def tokenize(self, line):
  775. tokens = []
  776. while True:
  777. for r, name in REGEXES:
  778. m = r.match(line)
  779. if m is not None:
  780. g = m.group(0)
  781. tokens.append(Token(name, g))
  782. line = line[len(g):]
  783. if not line:
  784. return TokenStack(tokens)
  785. break
  786. else:
  787. raise TokenizerError(line)
  788. def parse_number_or_slice(self, tokens):
  789. start_tok = tokens.pop()
  790. if start_tok.name == 'colon':
  791. start = 0
  792. else:
  793. if tokens.get(0).name != 'colon':
  794. return NumberConstant(start_tok.v)
  795. start = int(start_tok.v)
  796. tokens.pop()
  797. if not tokens.get(0).name in ['colon', 'number']:
  798. stop = -1
  799. step = 1
  800. else:
  801. next = tokens.pop()
  802. if next.name == 'colon':
  803. stop = -1
  804. step = int(tokens.pop().v)
  805. else:
  806. stop = int(next.v)
  807. if tokens.get(0).name == 'colon':
  808. tokens.pop()
  809. step = int(tokens.pop().v)
  810. else:
  811. step = 1
  812. return SliceConstant(start, stop, step)
  813. def parse_expression(self, tokens, accept_comma=False):
  814. stack = []
  815. while tokens.remaining():
  816. token = tokens.pop()
  817. if token.name == 'identifier':
  818. if tokens.remaining() and tokens.get(0).name == 'paren_left':
  819. stack.append(self.parse_function_call(token.v, tokens))
  820. elif token.v.strip(' ') == 'ndarray':
  821. stack.append(ArrayClass())
  822. elif token.v.strip(' ') == 'int':
  823. stack.append(DtypeClass('int'))
  824. elif token.v.strip(' ') == 'int8':
  825. stack.append(DtypeClass('int8'))
  826. elif token.v.strip(' ') == 'int16':
  827. stack.append(DtypeClass('int16'))
  828. elif token.v.strip(' ') == 'int32':
  829. stack.append(DtypeClass('int32'))
  830. elif token.v.strip(' ') == 'int64':
  831. stack.append(DtypeClass('int'))
  832. elif token.v.strip(' ') == 'uint':
  833. stack.append(DtypeClass('uint'))
  834. elif token.v.strip(' ') == 'uint8':
  835. stack.append(DtypeClass('uint8'))
  836. elif token.v.strip(' ') == 'uint16':
  837. stack.append(DtypeClass('uint16'))
  838. elif token.v.strip(' ') == 'uint32':
  839. stack.append(DtypeClass('uint32'))
  840. elif token.v.strip(' ') == 'uint64':
  841. stack.append(DtypeClass('uint'))
  842. elif token.v.strip(' ') == 'float':
  843. stack.append(DtypeClass('float'))
  844. elif token.v.strip(' ') == 'float32':
  845. stack.append(DtypeClass('float32'))
  846. elif token.v.strip(' ') == 'float64':
  847. stack.append(DtypeClass('float'))
  848. else:
  849. stack.append(Variable(token.v.strip(' ')))
  850. elif token.name == 'array_left':
  851. stack.append(ArrayConstant(self.parse_array_const(tokens)))
  852. elif token.name == 'operator':
  853. stack.append(Variable(token.v))
  854. elif token.name == 'number' or token.name == 'colon':
  855. tokens.push()
  856. stack.append(self.parse_number_or_slice(tokens))
  857. elif token.name == 'pipe':
  858. stack.append(RangeConstant(tokens.pop().v))
  859. end = tokens.pop()
  860. assert end.name == 'pipe'
  861. elif token.name == 'paren_left':
  862. stack.append(self.parse_complex_constant(tokens))
  863. elif accept_comma and token.name == 'comma':
  864. continue
  865. else:
  866. tokens.push()
  867. break
  868. if accept_comma:
  869. return stack
  870. stack.reverse()
  871. lhs = stack.pop()
  872. while stack:
  873. op = stack.pop()
  874. assert isinstance(op, Variable)
  875. rhs = stack.pop()
  876. lhs = Operator(lhs, op.name, rhs)
  877. return lhs
  878. def parse_function_call(self, name, tokens):
  879. args = []
  880. tokens.pop() # lparen
  881. while tokens.get(0).name != 'paren_right':
  882. args += self.parse_expression(tokens, accept_comma=True)
  883. return FunctionCall(name, args)
  884. def parse_complex_constant(self, tokens):
  885. r = tokens.pop()
  886. assert r.name == 'number'
  887. assert tokens.pop().name == 'comma'
  888. i = tokens.pop()
  889. assert i.name == 'number'
  890. assert tokens.pop().name == 'paren_right'
  891. return ComplexConstant(r.v, i.v)
  892. def parse_array_const(self, tokens):
  893. elems = []
  894. while True:
  895. token = tokens.pop()
  896. if token.name == 'number':
  897. elems.append(NumberConstant(token.v))
  898. elif token.name == 'array_left':
  899. elems.append(ArrayConstant(self.parse_array_const(tokens)))
  900. elif token.name == 'paren_left':
  901. elems.append(self.parse_complex_constant(tokens))
  902. else:
  903. raise BadToken()
  904. token = tokens.pop()
  905. if token.name == 'array_right':
  906. return elems
  907. assert token.name == 'comma'
  908. def parse_statement(self, tokens):
  909. if (tokens.get(0).name == 'identifier' and
  910. tokens.get(1).name == 'assign'):
  911. lhs = tokens.pop().v
  912. tokens.pop()
  913. rhs = self.parse_expression(tokens)
  914. return Assignment(lhs, rhs)
  915. elif (tokens.get(0).name == 'identifier' and
  916. tokens.get(1).name == 'array_left'):
  917. name = tokens.pop().v
  918. tokens.pop()
  919. index = self.parse_expression(tokens)
  920. tokens.pop()
  921. tokens.pop()
  922. return ArrayAssignment(name, index, self.parse_expression(tokens))
  923. return Execute(self.parse_expression(tokens))
  924. def parse(self, code):
  925. statements = []
  926. for line in code.split("\n"):
  927. if '#' in line:
  928. line = line.split('#', 1)[0]
  929. line = line.strip(" ")
  930. if line:
  931. tokens = self.tokenize(line)
  932. statements.append(self.parse_statement(tokens))
  933. return Code(statements)
  934. def numpy_compile(code):
  935. parser = Parser()
  936. return InterpreterState(parser.parse(code))