PageRenderTime 61ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/micronumpy/compile.py

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