PageRenderTime 64ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/pypy/module/micronumpy/compile.py

https://bitbucket.org/rlamy/pypy
Python | 834 lines | 708 code | 116 blank | 10 comment | 99 complexity | 9054b6a4c2bd2e1e95ec97ec7148508a 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. from pypy.interpreter import special
  6. from pypy.interpreter.baseobjspace import InternalSpaceCache, W_Root
  7. from pypy.interpreter.error import OperationError
  8. from rpython.rlib.objectmodel import specialize, instantiate
  9. from rpython.rlib.nonconst import NonConstant
  10. from pypy.module.micronumpy import boxes, ufuncs
  11. from pypy.module.micronumpy.arrayops import where
  12. from pypy.module.micronumpy.ndarray import W_NDimArray
  13. from pypy.module.micronumpy.ctors import array
  14. from pypy.module.micronumpy.descriptor import get_dtype_cache
  15. class BogusBytecode(Exception):
  16. pass
  17. class ArgumentMismatch(Exception):
  18. pass
  19. class ArgumentNotAnArray(Exception):
  20. pass
  21. class WrongFunctionName(Exception):
  22. pass
  23. class TokenizerError(Exception):
  24. pass
  25. class BadToken(Exception):
  26. pass
  27. SINGLE_ARG_FUNCTIONS = ["sum", "prod", "max", "min", "all", "any",
  28. "unegative", "flat", "tostring","count_nonzero",
  29. "argsort"]
  30. TWO_ARG_FUNCTIONS = ["dot", 'take', 'searchsorted']
  31. TWO_ARG_FUNCTIONS_OR_NONE = ['view', 'astype']
  32. THREE_ARG_FUNCTIONS = ['where']
  33. class W_TypeObject(W_Root):
  34. def __init__(self, name):
  35. self.name = name
  36. def lookup(self, name):
  37. return self.getdictvalue(self, name)
  38. class FakeSpace(object):
  39. w_ValueError = W_TypeObject("ValueError")
  40. w_TypeError = W_TypeObject("TypeError")
  41. w_IndexError = W_TypeObject("IndexError")
  42. w_OverflowError = W_TypeObject("OverflowError")
  43. w_NotImplementedError = W_TypeObject("NotImplementedError")
  44. w_AttributeError = W_TypeObject("AttributeError")
  45. w_None = None
  46. w_bool = W_TypeObject("bool")
  47. w_int = W_TypeObject("int")
  48. w_float = W_TypeObject("float")
  49. w_list = W_TypeObject("list")
  50. w_long = W_TypeObject("long")
  51. w_tuple = W_TypeObject('tuple')
  52. w_slice = W_TypeObject("slice")
  53. w_str = W_TypeObject("str")
  54. w_unicode = W_TypeObject("unicode")
  55. w_complex = W_TypeObject("complex")
  56. w_dict = W_TypeObject("dict")
  57. def __init__(self):
  58. """NOT_RPYTHON"""
  59. self.fromcache = InternalSpaceCache(self).getorbuild
  60. self.w_Ellipsis = special.Ellipsis()
  61. self.w_NotImplemented = special.NotImplemented()
  62. def _freeze_(self):
  63. return True
  64. def is_none(self, w_obj):
  65. return w_obj is None or w_obj is self.w_None
  66. def issequence_w(self, w_obj):
  67. return isinstance(w_obj, ListObject) or isinstance(w_obj, W_NDimArray)
  68. def len(self, w_obj):
  69. assert isinstance(w_obj, ListObject)
  70. return self.wrap(len(w_obj.items))
  71. def getattr(self, w_obj, w_attr):
  72. return StringObject(NonConstant('foo'))
  73. def isinstance_w(self, w_obj, w_tp):
  74. try:
  75. return w_obj.tp == w_tp
  76. except AttributeError:
  77. return False
  78. def decode_index4(self, w_idx, size):
  79. if isinstance(w_idx, IntObject):
  80. return (self.int_w(w_idx), 0, 0, 1)
  81. else:
  82. assert isinstance(w_idx, SliceObject)
  83. start, stop, step = w_idx.start, w_idx.stop, w_idx.step
  84. if step == 0:
  85. return (0, size, 1, size)
  86. if start < 0:
  87. start += size
  88. if stop < 0:
  89. stop += size + 1
  90. if step < 0:
  91. start, stop = stop, start
  92. start -= 1
  93. stop -= 1
  94. lgt = (stop - start + 1) / step + 1
  95. else:
  96. lgt = (stop - start - 1) / step + 1
  97. return (start, stop, step, lgt)
  98. @specialize.argtype(1)
  99. def wrap(self, obj):
  100. if isinstance(obj, float):
  101. return FloatObject(obj)
  102. elif isinstance(obj, bool):
  103. return BoolObject(obj)
  104. elif isinstance(obj, int):
  105. return IntObject(obj)
  106. elif isinstance(obj, long):
  107. return LongObject(obj)
  108. elif isinstance(obj, W_Root):
  109. return obj
  110. elif isinstance(obj, str):
  111. return StringObject(obj)
  112. raise NotImplementedError
  113. def newlist(self, items):
  114. return ListObject(items)
  115. def newcomplex(self, r, i):
  116. return ComplexObject(r, i)
  117. def getitem(self, obj, index):
  118. assert isinstance(obj, ListObject)
  119. assert isinstance(index, IntObject)
  120. return obj.items[index.intval]
  121. def listview(self, obj, number=-1):
  122. assert isinstance(obj, ListObject)
  123. if number != -1:
  124. assert number == 2
  125. return [obj.items[0], obj.items[1]]
  126. return obj.items
  127. fixedview = listview
  128. def float(self, w_obj):
  129. if isinstance(w_obj, FloatObject):
  130. return w_obj
  131. assert isinstance(w_obj, boxes.W_GenericBox)
  132. return self.float(w_obj.descr_float(self))
  133. def float_w(self, w_obj, allow_conversion=True):
  134. assert isinstance(w_obj, FloatObject)
  135. return w_obj.floatval
  136. def int_w(self, w_obj, allow_conversion=True):
  137. if isinstance(w_obj, IntObject):
  138. return w_obj.intval
  139. elif isinstance(w_obj, FloatObject):
  140. return int(w_obj.floatval)
  141. elif isinstance(w_obj, SliceObject):
  142. raise OperationError(self.w_TypeError, self.wrap("slice."))
  143. raise NotImplementedError
  144. def unpackcomplex(self, w_obj):
  145. if isinstance(w_obj, ComplexObject):
  146. return w_obj.r, w_obj.i
  147. raise NotImplementedError
  148. def index(self, w_obj):
  149. return self.wrap(self.int_w(w_obj))
  150. def str_w(self, w_obj):
  151. if isinstance(w_obj, StringObject):
  152. return w_obj.v
  153. raise NotImplementedError
  154. def int(self, w_obj):
  155. if isinstance(w_obj, IntObject):
  156. return w_obj
  157. assert isinstance(w_obj, boxes.W_GenericBox)
  158. return self.int(w_obj.descr_int(self))
  159. def str(self, w_obj):
  160. if isinstance(w_obj, StringObject):
  161. return w_obj
  162. assert isinstance(w_obj, boxes.W_GenericBox)
  163. return self.str(w_obj.descr_str(self))
  164. def is_true(self, w_obj):
  165. assert isinstance(w_obj, BoolObject)
  166. return bool(w_obj.intval)
  167. def is_w(self, w_obj, w_what):
  168. return w_obj is w_what
  169. def eq_w(self, w_obj, w_what):
  170. return w_obj == w_what
  171. def issubtype(self, w_type1, w_type2):
  172. return BoolObject(True)
  173. def type(self, w_obj):
  174. if self.is_none(w_obj):
  175. return self.w_None
  176. try:
  177. return w_obj.tp
  178. except AttributeError:
  179. if isinstance(w_obj, W_NDimArray):
  180. return W_NDimArray
  181. return self.w_None
  182. def lookup(self, w_obj, name):
  183. w_type = self.type(w_obj)
  184. if not self.is_none(w_type):
  185. return w_type.lookup(name)
  186. def gettypefor(self, w_obj):
  187. return W_TypeObject(w_obj.typedef.name)
  188. def call_function(self, tp, w_dtype):
  189. return w_dtype
  190. def call_method(self, w_obj, s, *args):
  191. # XXX even the hacks have hacks
  192. return None
  193. #return getattr(w_obj, 'descr_' + s)(self, *args)
  194. @specialize.arg(1)
  195. def interp_w(self, tp, what):
  196. assert isinstance(what, tp)
  197. return what
  198. def allocate_instance(self, klass, w_subtype):
  199. return instantiate(klass)
  200. def newtuple(self, list_w):
  201. return ListObject(list_w)
  202. def newdict(self):
  203. return {}
  204. def setitem(self, dict, item, value):
  205. dict[item] = value
  206. def len_w(self, w_obj):
  207. if isinstance(w_obj, ListObject):
  208. return len(w_obj.items)
  209. # XXX array probably
  210. assert False
  211. def exception_match(self, w_exc_type, w_check_class):
  212. # Good enough for now
  213. raise NotImplementedError
  214. class FloatObject(W_Root):
  215. tp = FakeSpace.w_float
  216. def __init__(self, floatval):
  217. self.floatval = floatval
  218. class BoolObject(W_Root):
  219. tp = FakeSpace.w_bool
  220. def __init__(self, boolval):
  221. self.intval = boolval
  222. class IntObject(W_Root):
  223. tp = FakeSpace.w_int
  224. def __init__(self, intval):
  225. self.intval = intval
  226. class LongObject(W_Root):
  227. tp = FakeSpace.w_long
  228. def __init__(self, intval):
  229. self.intval = intval
  230. class ListObject(W_Root):
  231. tp = FakeSpace.w_list
  232. def __init__(self, items):
  233. self.items = items
  234. class SliceObject(W_Root):
  235. tp = FakeSpace.w_slice
  236. def __init__(self, start, stop, step):
  237. self.start = start
  238. self.stop = stop
  239. self.step = step
  240. class StringObject(W_Root):
  241. tp = FakeSpace.w_str
  242. def __init__(self, v):
  243. self.v = v
  244. class ComplexObject(W_Root):
  245. tp = FakeSpace.w_complex
  246. def __init__(self, r, i):
  247. self.r = r
  248. self.i = i
  249. class InterpreterState(object):
  250. def __init__(self, code):
  251. self.code = code
  252. self.variables = {}
  253. self.results = []
  254. def run(self, space):
  255. self.space = space
  256. for stmt in self.code.statements:
  257. stmt.execute(self)
  258. class Node(object):
  259. def __eq__(self, other):
  260. return (self.__class__ == other.__class__ and
  261. self.__dict__ == other.__dict__)
  262. def __ne__(self, other):
  263. return not self == other
  264. def wrap(self, space):
  265. raise NotImplementedError
  266. def execute(self, interp):
  267. raise NotImplementedError
  268. class Assignment(Node):
  269. def __init__(self, name, expr):
  270. self.name = name
  271. self.expr = expr
  272. def execute(self, interp):
  273. interp.variables[self.name] = self.expr.execute(interp)
  274. def __repr__(self):
  275. return "%r = %r" % (self.name, self.expr)
  276. class ArrayAssignment(Node):
  277. def __init__(self, name, index, expr):
  278. self.name = name
  279. self.index = index
  280. self.expr = expr
  281. def execute(self, interp):
  282. arr = interp.variables[self.name]
  283. w_index = self.index.execute(interp)
  284. # cast to int
  285. if isinstance(w_index, FloatObject):
  286. w_index = IntObject(int(w_index.floatval))
  287. w_val = self.expr.execute(interp)
  288. assert isinstance(arr, W_NDimArray)
  289. arr.descr_setitem(interp.space, w_index, w_val)
  290. def __repr__(self):
  291. return "%s[%r] = %r" % (self.name, self.index, self.expr)
  292. class Variable(Node):
  293. def __init__(self, name):
  294. self.name = name.strip(" ")
  295. def execute(self, interp):
  296. if self.name == 'None':
  297. return None
  298. return interp.variables[self.name]
  299. def __repr__(self):
  300. return 'v(%s)' % self.name
  301. class Operator(Node):
  302. def __init__(self, lhs, name, rhs):
  303. self.name = name
  304. self.lhs = lhs
  305. self.rhs = rhs
  306. def execute(self, interp):
  307. w_lhs = self.lhs.execute(interp)
  308. if isinstance(self.rhs, SliceConstant):
  309. w_rhs = self.rhs.wrap(interp.space)
  310. else:
  311. w_rhs = self.rhs.execute(interp)
  312. if not isinstance(w_lhs, W_NDimArray):
  313. # scalar
  314. dtype = get_dtype_cache(interp.space).w_float64dtype
  315. w_lhs = W_NDimArray.new_scalar(interp.space, dtype, w_lhs)
  316. assert isinstance(w_lhs, W_NDimArray)
  317. if self.name == '+':
  318. w_res = w_lhs.descr_add(interp.space, w_rhs)
  319. elif self.name == '*':
  320. w_res = w_lhs.descr_mul(interp.space, w_rhs)
  321. elif self.name == '-':
  322. w_res = w_lhs.descr_sub(interp.space, w_rhs)
  323. elif self.name == '**':
  324. w_res = w_lhs.descr_pow(interp.space, w_rhs)
  325. elif self.name == '->':
  326. if isinstance(w_rhs, FloatObject):
  327. w_rhs = IntObject(int(w_rhs.floatval))
  328. assert isinstance(w_lhs, W_NDimArray)
  329. w_res = w_lhs.descr_getitem(interp.space, w_rhs)
  330. else:
  331. raise NotImplementedError
  332. if (not isinstance(w_res, W_NDimArray) and
  333. not isinstance(w_res, boxes.W_GenericBox)):
  334. dtype = get_dtype_cache(interp.space).w_float64dtype
  335. w_res = W_NDimArray.new_scalar(interp.space, dtype, w_res)
  336. return w_res
  337. def __repr__(self):
  338. return '(%r %s %r)' % (self.lhs, self.name, self.rhs)
  339. class FloatConstant(Node):
  340. def __init__(self, v):
  341. self.v = float(v)
  342. def __repr__(self):
  343. return "Const(%s)" % self.v
  344. def wrap(self, space):
  345. return space.wrap(self.v)
  346. def execute(self, interp):
  347. return interp.space.wrap(self.v)
  348. class ComplexConstant(Node):
  349. def __init__(self, r, i):
  350. self.r = float(r)
  351. self.i = float(i)
  352. def __repr__(self):
  353. return 'ComplexConst(%s, %s)' % (self.r, self.i)
  354. def wrap(self, space):
  355. return space.newcomplex(self.r, self.i)
  356. def execute(self, interp):
  357. return self.wrap(interp.space)
  358. class RangeConstant(Node):
  359. def __init__(self, v):
  360. self.v = int(v)
  361. def execute(self, interp):
  362. w_list = interp.space.newlist(
  363. [interp.space.wrap(float(i)) for i in range(self.v)]
  364. )
  365. dtype = get_dtype_cache(interp.space).w_float64dtype
  366. return array(interp.space, w_list, w_dtype=dtype, w_order=None)
  367. def __repr__(self):
  368. return 'Range(%s)' % self.v
  369. class Code(Node):
  370. def __init__(self, statements):
  371. self.statements = statements
  372. def __repr__(self):
  373. return "\n".join([repr(i) for i in self.statements])
  374. class ArrayConstant(Node):
  375. def __init__(self, items):
  376. self.items = items
  377. def wrap(self, space):
  378. return space.newlist([item.wrap(space) for item in self.items])
  379. def execute(self, interp):
  380. w_list = self.wrap(interp.space)
  381. return array(interp.space, w_list)
  382. def __repr__(self):
  383. return "[" + ", ".join([repr(item) for item in self.items]) + "]"
  384. class SliceConstant(Node):
  385. def __init__(self, start, stop, step):
  386. self.start = start
  387. self.stop = stop
  388. self.step = step
  389. def wrap(self, space):
  390. return SliceObject(self.start, self.stop, self.step)
  391. def execute(self, interp):
  392. return SliceObject(self.start, self.stop, self.step)
  393. def __repr__(self):
  394. return 'slice(%s,%s,%s)' % (self.start, self.stop, self.step)
  395. class ArrayClass(Node):
  396. def __init__(self):
  397. self.v = W_NDimArray
  398. def execute(self, interp):
  399. return self.v
  400. def __repr__(self):
  401. return '<class W_NDimArray>'
  402. class DtypeClass(Node):
  403. def __init__(self, dt):
  404. self.v = dt
  405. def execute(self, interp):
  406. if self.v == 'int':
  407. dtype = get_dtype_cache(interp.space).w_int64dtype
  408. elif self.v == 'float':
  409. dtype = get_dtype_cache(interp.space).w_float64dtype
  410. else:
  411. raise BadToken('unknown v to dtype "%s"' % self.v)
  412. return dtype
  413. def __repr__(self):
  414. return '<class %s dtype>' % self.v
  415. class Execute(Node):
  416. def __init__(self, expr):
  417. self.expr = expr
  418. def __repr__(self):
  419. return repr(self.expr)
  420. def execute(self, interp):
  421. interp.results.append(self.expr.execute(interp))
  422. class FunctionCall(Node):
  423. def __init__(self, name, args):
  424. self.name = name.strip(" ")
  425. self.args = args
  426. def __repr__(self):
  427. return "%s(%s)" % (self.name, ", ".join([repr(arg)
  428. for arg in self.args]))
  429. def execute(self, interp):
  430. arr = self.args[0].execute(interp)
  431. if not isinstance(arr, W_NDimArray):
  432. raise ArgumentNotAnArray
  433. if self.name in SINGLE_ARG_FUNCTIONS:
  434. if len(self.args) != 1 and self.name != 'sum':
  435. raise ArgumentMismatch
  436. if self.name == "sum":
  437. if len(self.args)>1:
  438. w_res = arr.descr_sum(interp.space,
  439. self.args[1].execute(interp))
  440. else:
  441. w_res = arr.descr_sum(interp.space)
  442. elif self.name == "prod":
  443. w_res = arr.descr_prod(interp.space)
  444. elif self.name == "max":
  445. w_res = arr.descr_max(interp.space)
  446. elif self.name == "min":
  447. w_res = arr.descr_min(interp.space)
  448. elif self.name == "any":
  449. w_res = arr.descr_any(interp.space)
  450. elif self.name == "all":
  451. w_res = arr.descr_all(interp.space)
  452. elif self.name == "unegative":
  453. neg = ufuncs.get(interp.space).negative
  454. w_res = neg.call(interp.space, [arr])
  455. elif self.name == "cos":
  456. cos = ufuncs.get(interp.space).cos
  457. w_res = cos.call(interp.space, [arr])
  458. elif self.name == "flat":
  459. w_res = arr.descr_get_flatiter(interp.space)
  460. elif self.name == "argsort":
  461. w_res = arr.descr_argsort(interp.space)
  462. elif self.name == "tostring":
  463. arr.descr_tostring(interp.space)
  464. w_res = None
  465. else:
  466. assert False # unreachable code
  467. elif self.name in TWO_ARG_FUNCTIONS:
  468. if len(self.args) != 2:
  469. raise ArgumentMismatch
  470. arg = self.args[1].execute(interp)
  471. if not isinstance(arg, W_NDimArray):
  472. raise ArgumentNotAnArray
  473. if self.name == "dot":
  474. w_res = arr.descr_dot(interp.space, arg)
  475. elif self.name == 'take':
  476. w_res = arr.descr_take(interp.space, arg)
  477. elif self.name == "searchsorted":
  478. w_res = arr.descr_searchsorted(interp.space, arg,
  479. interp.space.wrap('left'))
  480. else:
  481. assert False # unreachable code
  482. elif self.name in THREE_ARG_FUNCTIONS:
  483. if len(self.args) != 3:
  484. raise ArgumentMismatch
  485. arg1 = self.args[1].execute(interp)
  486. arg2 = self.args[2].execute(interp)
  487. if not isinstance(arg1, W_NDimArray):
  488. raise ArgumentNotAnArray
  489. if not isinstance(arg2, W_NDimArray):
  490. raise ArgumentNotAnArray
  491. if self.name == "where":
  492. w_res = where(interp.space, arr, arg1, arg2)
  493. else:
  494. assert False
  495. elif self.name in TWO_ARG_FUNCTIONS_OR_NONE:
  496. if len(self.args) != 2:
  497. raise ArgumentMismatch
  498. arg = self.args[1].execute(interp)
  499. if self.name == 'view':
  500. w_res = arr.descr_view(interp.space, arg)
  501. elif self.name == 'astype':
  502. w_res = arr.descr_astype(interp.space, arg)
  503. else:
  504. assert False
  505. else:
  506. raise WrongFunctionName
  507. if isinstance(w_res, W_NDimArray):
  508. return w_res
  509. if isinstance(w_res, FloatObject):
  510. dtype = get_dtype_cache(interp.space).w_float64dtype
  511. elif isinstance(w_res, IntObject):
  512. dtype = get_dtype_cache(interp.space).w_int64dtype
  513. elif isinstance(w_res, BoolObject):
  514. dtype = get_dtype_cache(interp.space).w_booldtype
  515. elif isinstance(w_res, boxes.W_GenericBox):
  516. dtype = w_res.get_dtype(interp.space)
  517. else:
  518. dtype = None
  519. return W_NDimArray.new_scalar(interp.space, dtype, w_res)
  520. _REGEXES = [
  521. ('-?[\d\.]+', 'number'),
  522. ('\[', 'array_left'),
  523. (':', 'colon'),
  524. ('\w+', 'identifier'),
  525. ('\]', 'array_right'),
  526. ('(->)|[\+\-\*\/]+', 'operator'),
  527. ('=', 'assign'),
  528. (',', 'comma'),
  529. ('\|', 'pipe'),
  530. ('\(', 'paren_left'),
  531. ('\)', 'paren_right'),
  532. ]
  533. REGEXES = []
  534. for r, name in _REGEXES:
  535. REGEXES.append((re.compile(r' *(' + r + ')'), name))
  536. del _REGEXES
  537. class Token(object):
  538. def __init__(self, name, v):
  539. self.name = name
  540. self.v = v
  541. def __repr__(self):
  542. return '(%s, %s)' % (self.name, self.v)
  543. empty = Token('', '')
  544. class TokenStack(object):
  545. def __init__(self, tokens):
  546. self.tokens = tokens
  547. self.c = 0
  548. def pop(self):
  549. token = self.tokens[self.c]
  550. self.c += 1
  551. return token
  552. def get(self, i):
  553. if self.c + i >= len(self.tokens):
  554. return empty
  555. return self.tokens[self.c + i]
  556. def remaining(self):
  557. return len(self.tokens) - self.c
  558. def push(self):
  559. self.c -= 1
  560. def __repr__(self):
  561. return repr(self.tokens[self.c:])
  562. class Parser(object):
  563. def tokenize(self, line):
  564. tokens = []
  565. while True:
  566. for r, name in REGEXES:
  567. m = r.match(line)
  568. if m is not None:
  569. g = m.group(0)
  570. tokens.append(Token(name, g))
  571. line = line[len(g):]
  572. if not line:
  573. return TokenStack(tokens)
  574. break
  575. else:
  576. raise TokenizerError(line)
  577. def parse_number_or_slice(self, tokens):
  578. start_tok = tokens.pop()
  579. if start_tok.name == 'colon':
  580. start = 0
  581. else:
  582. if tokens.get(0).name != 'colon':
  583. return FloatConstant(start_tok.v)
  584. start = int(start_tok.v)
  585. tokens.pop()
  586. if not tokens.get(0).name in ['colon', 'number']:
  587. stop = -1
  588. step = 1
  589. else:
  590. next = tokens.pop()
  591. if next.name == 'colon':
  592. stop = -1
  593. step = int(tokens.pop().v)
  594. else:
  595. stop = int(next.v)
  596. if tokens.get(0).name == 'colon':
  597. tokens.pop()
  598. step = int(tokens.pop().v)
  599. else:
  600. step = 1
  601. return SliceConstant(start, stop, step)
  602. def parse_expression(self, tokens, accept_comma=False):
  603. stack = []
  604. while tokens.remaining():
  605. token = tokens.pop()
  606. if token.name == 'identifier':
  607. if tokens.remaining() and tokens.get(0).name == 'paren_left':
  608. stack.append(self.parse_function_call(token.v, tokens))
  609. elif token.v.strip(' ') == 'ndarray':
  610. stack.append(ArrayClass())
  611. elif token.v.strip(' ') == 'int':
  612. stack.append(DtypeClass('int'))
  613. elif token.v.strip(' ') == 'float':
  614. stack.append(DtypeClass('float'))
  615. else:
  616. stack.append(Variable(token.v.strip(' ')))
  617. elif token.name == 'array_left':
  618. stack.append(ArrayConstant(self.parse_array_const(tokens)))
  619. elif token.name == 'operator':
  620. stack.append(Variable(token.v))
  621. elif token.name == 'number' or token.name == 'colon':
  622. tokens.push()
  623. stack.append(self.parse_number_or_slice(tokens))
  624. elif token.name == 'pipe':
  625. stack.append(RangeConstant(tokens.pop().v))
  626. end = tokens.pop()
  627. assert end.name == 'pipe'
  628. elif token.name == 'paren_left':
  629. stack.append(self.parse_complex_constant(tokens))
  630. elif accept_comma and token.name == 'comma':
  631. continue
  632. else:
  633. tokens.push()
  634. break
  635. if accept_comma:
  636. return stack
  637. stack.reverse()
  638. lhs = stack.pop()
  639. while stack:
  640. op = stack.pop()
  641. assert isinstance(op, Variable)
  642. rhs = stack.pop()
  643. lhs = Operator(lhs, op.name, rhs)
  644. return lhs
  645. def parse_function_call(self, name, tokens):
  646. args = []
  647. tokens.pop() # lparen
  648. while tokens.get(0).name != 'paren_right':
  649. args += self.parse_expression(tokens, accept_comma=True)
  650. return FunctionCall(name, args)
  651. def parse_complex_constant(self, tokens):
  652. r = tokens.pop()
  653. assert r.name == 'number'
  654. assert tokens.pop().name == 'comma'
  655. i = tokens.pop()
  656. assert i.name == 'number'
  657. assert tokens.pop().name == 'paren_right'
  658. return ComplexConstant(r.v, i.v)
  659. def parse_array_const(self, tokens):
  660. elems = []
  661. while True:
  662. token = tokens.pop()
  663. if token.name == 'number':
  664. elems.append(FloatConstant(token.v))
  665. elif token.name == 'array_left':
  666. elems.append(ArrayConstant(self.parse_array_const(tokens)))
  667. elif token.name == 'paren_left':
  668. elems.append(self.parse_complex_constant(tokens))
  669. else:
  670. raise BadToken()
  671. token = tokens.pop()
  672. if token.name == 'array_right':
  673. return elems
  674. assert token.name == 'comma'
  675. def parse_statement(self, tokens):
  676. if (tokens.get(0).name == 'identifier' and
  677. tokens.get(1).name == 'assign'):
  678. lhs = tokens.pop().v
  679. tokens.pop()
  680. rhs = self.parse_expression(tokens)
  681. return Assignment(lhs, rhs)
  682. elif (tokens.get(0).name == 'identifier' and
  683. tokens.get(1).name == 'array_left'):
  684. name = tokens.pop().v
  685. tokens.pop()
  686. index = self.parse_expression(tokens)
  687. tokens.pop()
  688. tokens.pop()
  689. return ArrayAssignment(name, index, self.parse_expression(tokens))
  690. return Execute(self.parse_expression(tokens))
  691. def parse(self, code):
  692. statements = []
  693. for line in code.split("\n"):
  694. if '#' in line:
  695. line = line.split('#', 1)[0]
  696. line = line.strip(" ")
  697. if line:
  698. tokens = self.tokenize(line)
  699. statements.append(self.parse_statement(tokens))
  700. return Code(statements)
  701. def numpy_compile(code):
  702. parser = Parser()
  703. return InterpreterState(parser.parse(code))