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