PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/micronumpy/compile.py

https://bitbucket.org/kaiquewdev/pypy
Python | 677 lines | 575 code | 93 blank | 9 comment | 76 complexity | 317d6d8548733c388eced0e9c802f6d7 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","count_nonzero"]
  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. elif self.name == "count_nonzero":
  362. w_res = arr.descr_count_nonzero(interp.space)
  363. else:
  364. assert False # unreachable code
  365. elif self.name in TWO_ARG_FUNCTIONS:
  366. if len(self.args) != 2:
  367. raise ArgumentMismatch
  368. arg = self.args[1].execute(interp)
  369. if not isinstance(arg, BaseArray):
  370. raise ArgumentNotAnArray
  371. if self.name == "dot":
  372. w_res = arr.descr_dot(interp.space, arg)
  373. elif self.name == 'take':
  374. w_res = arr.descr_take(interp.space, arg)
  375. else:
  376. assert False # unreachable code
  377. elif self.name in THREE_ARG_FUNCTIONS:
  378. if len(self.args) != 3:
  379. raise ArgumentMismatch
  380. arg1 = self.args[1].execute(interp)
  381. arg2 = self.args[2].execute(interp)
  382. if not isinstance(arg1, BaseArray):
  383. raise ArgumentNotAnArray
  384. if not isinstance(arg2, BaseArray):
  385. raise ArgumentNotAnArray
  386. if self.name == "where":
  387. w_res = where(interp.space, arr, arg1, arg2)
  388. else:
  389. assert False
  390. else:
  391. raise WrongFunctionName
  392. if isinstance(w_res, BaseArray):
  393. return w_res
  394. if isinstance(w_res, FloatObject):
  395. dtype = get_dtype_cache(interp.space).w_float64dtype
  396. elif isinstance(w_res, IntObject):
  397. dtype = get_dtype_cache(interp.space).w_int64dtype
  398. elif isinstance(w_res, BoolObject):
  399. dtype = get_dtype_cache(interp.space).w_booldtype
  400. elif isinstance(w_res, interp_boxes.W_GenericBox):
  401. dtype = w_res.get_dtype(interp.space)
  402. else:
  403. dtype = None
  404. return scalar_w(interp.space, dtype, w_res)
  405. _REGEXES = [
  406. ('-?[\d\.]+', 'number'),
  407. ('\[', 'array_left'),
  408. (':', 'colon'),
  409. ('\w+', 'identifier'),
  410. ('\]', 'array_right'),
  411. ('(->)|[\+\-\*\/]', 'operator'),
  412. ('=', 'assign'),
  413. (',', 'comma'),
  414. ('\|', 'pipe'),
  415. ('\(', 'paren_left'),
  416. ('\)', 'paren_right'),
  417. ]
  418. REGEXES = []
  419. for r, name in _REGEXES:
  420. REGEXES.append((re.compile(r' *(' + r + ')'), name))
  421. del _REGEXES
  422. class Token(object):
  423. def __init__(self, name, v):
  424. self.name = name
  425. self.v = v
  426. def __repr__(self):
  427. return '(%s, %s)' % (self.name, self.v)
  428. empty = Token('', '')
  429. class TokenStack(object):
  430. def __init__(self, tokens):
  431. self.tokens = tokens
  432. self.c = 0
  433. def pop(self):
  434. token = self.tokens[self.c]
  435. self.c += 1
  436. return token
  437. def get(self, i):
  438. if self.c + i >= len(self.tokens):
  439. return empty
  440. return self.tokens[self.c + i]
  441. def remaining(self):
  442. return len(self.tokens) - self.c
  443. def push(self):
  444. self.c -= 1
  445. def __repr__(self):
  446. return repr(self.tokens[self.c:])
  447. class Parser(object):
  448. def tokenize(self, line):
  449. tokens = []
  450. while True:
  451. for r, name in REGEXES:
  452. m = r.match(line)
  453. if m is not None:
  454. g = m.group(0)
  455. tokens.append(Token(name, g))
  456. line = line[len(g):]
  457. if not line:
  458. return TokenStack(tokens)
  459. break
  460. else:
  461. raise TokenizerError(line)
  462. def parse_number_or_slice(self, tokens):
  463. start_tok = tokens.pop()
  464. if start_tok.name == 'colon':
  465. start = 0
  466. else:
  467. if tokens.get(0).name != 'colon':
  468. return FloatConstant(start_tok.v)
  469. start = int(start_tok.v)
  470. tokens.pop()
  471. if not tokens.get(0).name in ['colon', 'number']:
  472. stop = -1
  473. step = 1
  474. else:
  475. next = tokens.pop()
  476. if next.name == 'colon':
  477. stop = -1
  478. step = int(tokens.pop().v)
  479. else:
  480. stop = int(next.v)
  481. if tokens.get(0).name == 'colon':
  482. tokens.pop()
  483. step = int(tokens.pop().v)
  484. else:
  485. step = 1
  486. return SliceConstant(start, stop, step)
  487. def parse_expression(self, tokens, accept_comma=False):
  488. stack = []
  489. while tokens.remaining():
  490. token = tokens.pop()
  491. if token.name == 'identifier':
  492. if tokens.remaining() and tokens.get(0).name == 'paren_left':
  493. stack.append(self.parse_function_call(token.v, tokens))
  494. else:
  495. stack.append(Variable(token.v))
  496. elif token.name == 'array_left':
  497. stack.append(ArrayConstant(self.parse_array_const(tokens)))
  498. elif token.name == 'operator':
  499. stack.append(Variable(token.v))
  500. elif token.name == 'number' or token.name == 'colon':
  501. tokens.push()
  502. stack.append(self.parse_number_or_slice(tokens))
  503. elif token.name == 'pipe':
  504. stack.append(RangeConstant(tokens.pop().v))
  505. end = tokens.pop()
  506. assert end.name == 'pipe'
  507. elif accept_comma and token.name == 'comma':
  508. continue
  509. else:
  510. tokens.push()
  511. break
  512. if accept_comma:
  513. return stack
  514. stack.reverse()
  515. lhs = stack.pop()
  516. while stack:
  517. op = stack.pop()
  518. assert isinstance(op, Variable)
  519. rhs = stack.pop()
  520. lhs = Operator(lhs, op.name, rhs)
  521. return lhs
  522. def parse_function_call(self, name, tokens):
  523. args = []
  524. tokens.pop() # lparen
  525. while tokens.get(0).name != 'paren_right':
  526. args += self.parse_expression(tokens, accept_comma=True)
  527. return FunctionCall(name, args)
  528. def parse_array_const(self, tokens):
  529. elems = []
  530. while True:
  531. token = tokens.pop()
  532. if token.name == 'number':
  533. elems.append(FloatConstant(token.v))
  534. elif token.name == 'array_left':
  535. elems.append(ArrayConstant(self.parse_array_const(tokens)))
  536. else:
  537. raise BadToken()
  538. token = tokens.pop()
  539. if token.name == 'array_right':
  540. return elems
  541. assert token.name == 'comma'
  542. def parse_statement(self, tokens):
  543. if (tokens.get(0).name == 'identifier' and
  544. tokens.get(1).name == 'assign'):
  545. lhs = tokens.pop().v
  546. tokens.pop()
  547. rhs = self.parse_expression(tokens)
  548. return Assignment(lhs, rhs)
  549. elif (tokens.get(0).name == 'identifier' and
  550. tokens.get(1).name == 'array_left'):
  551. name = tokens.pop().v
  552. tokens.pop()
  553. index = self.parse_expression(tokens)
  554. tokens.pop()
  555. tokens.pop()
  556. return ArrayAssignment(name, index, self.parse_expression(tokens))
  557. return Execute(self.parse_expression(tokens))
  558. def parse(self, code):
  559. statements = []
  560. for line in code.split("\n"):
  561. if '#' in line:
  562. line = line.split('#', 1)[0]
  563. line = line.strip(" ")
  564. if line:
  565. tokens = self.tokenize(line)
  566. statements.append(self.parse_statement(tokens))
  567. return Code(statements)
  568. def numpy_compile(code):
  569. parser = Parser()
  570. return InterpreterState(parser.parse(code))