Example #1
0
    def call(self, args, kwargs):
        self.rval = None
        self._myglobals = {}
        for name in self.names:
            #print 'name', name
            try:
                self._myglobals[name] = self.func.func_globals[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        self._locals = [None] * len(self.fco.co_varnames)
        for i, name in enumerate(self.argnames):
            #print 'i', args, self.argnames, self.fco.co_varnames
            self._locals[i] = args[i]

        self.code_iter = itercode(self.costr)
        jmp = None
        while True:
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            #print 'OP: ', i, name
            jmp = getattr(self, 'op_' + name)(i, op, arg)

        return self.rval
Example #2
0
File: ad.py Project: ASPP/numba
    def call(self, args, kwargs):
        self.rval = None
        self._myglobals = {}
        for name in self.names:
            #print 'name', name
            try:
                self._myglobals[name] = self.func.__globals__[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        self._locals = [None] * len(self.fco.co_varnames)
        for i, name in enumerate(self.argnames):
            #print 'i', args, self.argnames, self.fco.co_varnames
            self._locals[i] = args[i]

        self.code_iter = itercode(self.costr)
        jmp = None
        while True:
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            #print 'OP: ', i, name
            jmp = getattr(self, 'op_' + name)(i, op, arg)

        return self.rval
Example #3
0
def decode_function(encoded_function):
  func_data, builtin = marshal.loads(encoded_function)
  if not builtin:
    func_code, func_globals = func_data
    func_globals = recover_globals(func_globals)
    return types.FunctionType(func_code, func_globals)
  else:
    return __builtin__.__getattribute__(func_data)
Example #4
0
    def __init__(self, func):
        self.func = func
        self.fco = func.func_code
        self.names = self.fco.co_names
        self.varnames = self.fco.co_varnames
        self.constants = self.fco.co_consts
        self.costr = func.func_code.co_code
        # Just the globals we will use
        self._myglobals = {}
        for name in self.names:
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                self._myglobals[name] = __builtin__.__getattribute__(name)

        self.mod = lc.Module.new(func.func_name + '_mod')

        self._delaylist = [range, xrange, enumerate]
        self.setup_func()
Example #5
0
    def __init__(self, func):
        self.func = func
        self.fco = func.func_code
        self.names = self.fco.co_names
        self.varnames = self.fco.co_varnames
        self.constants = self.fco.co_consts
        self.costr = func.func_code.co_code
        # Just the globals we will use
        self._myglobals = {}
        for name in self.names:
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                self._myglobals[name] = __builtin__.__getattribute__(name)

        self.mod = lc.Module.new(func.func_name+'_mod')        

        self._delaylist = [range, xrange, enumerate]
        self.setup_func()
Example #6
0
    def call(self, args, kwargs):
        if not isinstance(args, tuple):
            raise TypeError('vm.call: args must be tuple', args)
        if not isinstance(kwargs, dict):
            raise TypeError('vm.call: kwargs must be dict', kwargs)

        func = self.func

        if isinstance(func, type) and issubclass(func, BaseException):
            # XXX not shadowing exception creation, because exceptions
            # do not have func_code. Is this OK? can we do better?
            return func(*args, **kwargs)

        func_code = self.func.func_code

        self._myglobals = {}
        self._locals = []

        for name in func_code.co_names:
            #print 'name', name
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        # get function arguments
        argspec = inspect.getargspec(func)

        # match function arguments to passed parameters
        callargs = orderedcallargs(func, *args, **kwargs)

        # named args => locals
        self._locals.extend(callargs[arg] for arg in argspec.args)

        # *args => locals
        if argspec.varargs:
            self._locals.append(callargs[argspec.varargs])

        # **kwargs => locals
        if argspec.keywords:
            self._locals.append(callargs[argspec.keywords])

        # other vars => locals
        no_unbound_args = len(func_code.co_varnames) - len(self._locals)
        self._locals.extend([Unassigned] * no_unbound_args)

        # shadow arguments
        for val in flat_from_doc(callargs):
            if id(val) not in self.watcher:
                self.add_shadow(val)

        self.code_iter = itercode(func_code.co_code)
        jmp = None
        while not hasattr(self, 'rval'):
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            # method names can't have '+' in them
            name = {'SLICE+0': 'SLICE_PLUS_0',
                    'SLICE+1': 'SLICE_PLUS_1',
                    'SLICE+2': 'SLICE_PLUS_2',
                    'SLICE+3': 'SLICE_PLUS_3',
                    'STORE_SLICE+0': 'STORE_SLICE_PLUS_0',
                    'STORE_SLICE+1': 'STORE_SLICE_PLUS_1',
                    'STORE_SLICE+2': 'STORE_SLICE_PLUS_2',
                    'STORE_SLICE+3': 'STORE_SLICE_PLUS_3',
                    }.get(name, name)
            if self.print_ops:
                print 'OP: ', i, name
            if self.print_stack:
                print self.stack
            try:
                op_method = getattr(self, 'op_' + name)
            except AttributeError:
                raise AttributeError('FrameVM does not have a method defined '
                                     'for \'op_{0}\''.format(name))
            except:
                raise
            jmp = op_method(i, op, arg)

        return self.rval
Example #7
0
    def call(self, args, kwargs):
        if not isinstance(args, tuple):
            raise TypeError('vm.call: args must be tuple', args)
        if not isinstance(kwargs, dict):
            raise TypeError('vm.call: kwargs must be dict', kwargs)

        func = self.func

        if isinstance(func, type) and issubclass(func, BaseException):
            # XXX not shadowing exception creation, because exceptions
            # do not have func_code. Is this OK? can we do better?
            return func(*args, **kwargs)

        func_code = self.func.func_code

        self._myglobals = {}
        self._locals = []

        for name in func_code.co_names:
            #print 'name', name
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        # get function arguments
        argspec = inspect.getargspec(func)

        # match function arguments to passed parameters
        callargs = orderedcallargs(func, *args, **kwargs)

        # named args => locals
        self._locals.extend(callargs[arg] for arg in argspec.args)

        # *args => locals
        if argspec.varargs:
            self._locals.append(callargs[argspec.varargs])

        # **kwargs => locals
        if argspec.keywords:
            self._locals.append(callargs[argspec.keywords])

        # other vars => locals
        no_unbound_args = len(func_code.co_varnames) - len(self._locals)
        self._locals.extend([Unassigned] * no_unbound_args)

        # shadow arguments
        for val in flat_from_doc(callargs):
            if id(val) not in self.watcher:
                self.add_shadow(val)

        self.code_iter = itercode(func_code.co_code)
        jmp = None
        while not hasattr(self, 'rval'):
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            # method names can't have '+' in them
            name = {
                'SLICE+0': 'SLICE_PLUS_0',
                'SLICE+1': 'SLICE_PLUS_1',
                'SLICE+2': 'SLICE_PLUS_2',
                'SLICE+3': 'SLICE_PLUS_3',
                'STORE_SLICE+0': 'STORE_SLICE_PLUS_0',
                'STORE_SLICE+1': 'STORE_SLICE_PLUS_1',
                'STORE_SLICE+2': 'STORE_SLICE_PLUS_2',
                'STORE_SLICE+3': 'STORE_SLICE_PLUS_3',
            }.get(name, name)
            if self.print_ops:
                print 'OP: ', i, name
            if self.print_stack:
                print self.stack
            try:
                op_method = getattr(self, 'op_' + name)
            except AttributeError:
                raise AttributeError('FrameVM does not have a method defined '
                                     'for \'op_{0}\''.format(name))
            except:
                raise
            jmp = op_method(i, op, arg)

        return self.rval
Example #8
0
    def call(self, args, kwargs):

        func = self.func
        func_code = self.func.func_code
        co_varnames = self.func.func_code.co_varnames
        co_argcount = self.func.func_code.co_argcount

        self._myglobals = {}
        self._locals = [Unassigned] * len(co_varnames)

        _locals = self._locals
        if hasattr(func, 'im_self'):
            _locals[0] = func.im_self
            bind_varnames = co_varnames[1:]
            bind_offset = 1
            if id(func.im_self) in self.watchers.svars:
                raise NotImplementedError('bound method on shadowed var: %s' %
                        func.__name__)
        else:
            bind_varnames = co_varnames
            bind_offset = 0

        for name in func_code.co_names:
            #print 'name', name
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        extra_args_ok = bool(func_code.co_flags & 0x04)
        extra_kwargs_ok = bool(func_code.co_flags & 0x08)

        # -- assert that my understanding of calling protocol is correct
        #
        # param_names: the sequence of function parameter names
        # args_param: [optional] the name of the *vargs parameter
        # kwargs_param: [optional] the name of the **kwargs parameter
        # pos_params: sequence of potentially-positional parameter names
        try:
            if extra_args_ok and extra_kwargs_ok:
                assert len(bind_varnames) >= co_argcount + 2
                param_names = bind_varnames[:co_argcount + 2]
                args_param = param_names[co_argcount]
                kwargs_param = param_names[co_argcount + 1]
                pos_params = param_names[:co_argcount]
            elif extra_kwargs_ok:
                assert len(bind_varnames) >= co_argcount + 1
                param_names = bind_varnames[:co_argcount + 1]
                kwargs_param = param_names[co_argcount]
                pos_params = param_names[:co_argcount]
            elif extra_args_ok:
                assert len(bind_varnames) >= co_argcount + 1
                param_names = bind_varnames[:co_argcount + 1]
                args_param = param_names[co_argcount]
                pos_params = param_names[:co_argcount]
            else:
                assert len(bind_varnames) >= co_argcount
                param_names = bind_varnames[:co_argcount]
                pos_params = param_names[:co_argcount]
        except AssertionError:
            print 'YIKES: MISUNDERSTANDING OF CALL PROTOCOL:',
            print co_argcount,
            print bind_varnames,
            print '%x' % func_code.co_flags
            raise

        if len(args) > co_argcount and not extra_args_ok:
            raise TypeError('Argument count exceeds number of positional params')

        # -- bind positional arguments
        for i, (param_i, arg_i) in enumerate(zip(param_names, args)):
            assert bind_varnames[i] == param_i
            _locals[i + bind_offset] = arg_i

        if extra_args_ok:
            _locals[co_varnames.index(args_param)] == args[co_argcount:]

        # -- bind keyword arguments
        if extra_kwargs_ok:
            kwargs_pos = co_varnames.index(kwargs_param)
            _locals[kwargs_pos] == {}

        for aname, aval in kwargs.items():
            try:
                pos = pos_params.index(aname) + bind_offset
            except ValueError:
                if extra_kwargs_ok:
                    _locals[kwargs_pos][aname] = aval
                    continue
                else:
                    raise TypeError('Unrecognized keyword argument', aname)
            if _locals[pos] == Unassigned:
                _locals[pos] = aval
            else:
                raise TypeError('Duplicate argument for parameter', aname)

        # -- find default values
        if func.func_defaults:
            defaults = func.func_defaults
            for ii, val in enumerate(defaults):
                if _locals[co_argcount - len(defaults) + ii] is Unassigned:
                   _locals[co_argcount - len(defaults) + ii] = val

        # print 'BINDING'
        for name, lval in zip(co_varnames, _locals):
            if (isinstance(lval, np.ndarray)
                    and not id(lval) in self.watcher.svars):
                self.add_shadow(lval)
            #print '  locals:', name, lval, id(lval)

        self.code_iter = itercode(func_code.co_code)
        jmp = None
        while not hasattr(self, 'rval'):
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            name = {
                    'SLICE+0': 'SLICE_PLUS_0',
                    'SLICE+1': 'SLICE_PLUS_1',
                    'SLICE+2': 'SLICE_PLUS_2',
                    'SLICE+3': 'SLICE_PLUS_3',
                    }.get(name, name)
            if self.print_ops:
                print 'OP: ', i, name
            if self.print_stack:
                print self.stack
            jmp = getattr(self, 'op_' + name)(i, op, arg)

        return self.rval
Example #9
0
    def call(self, args, kwargs):
        if type(args) != tuple:
            raise TypeError('vm.call: args must be tuple', args)
        if type(kwargs) != dict:
            raise TypeError('vm.call: kwargs must be dict', kwargs)

        func = self.func
        if isinstance(func, type) and issubclass(func, BaseException):
            # XXX not shadowing exception creation, because exceptions
            # do not have func_code. Is this OK? can we do better?
            return func(*args, **kwargs)

        func_code = self.func.func_code
        co_varnames = self.func.func_code.co_varnames
        co_argcount = self.func.func_code.co_argcount

        self._myglobals = {}
        self._locals = [Unassigned] * len(co_varnames)

        _locals = self._locals
        if hasattr(func, 'im_self'):
            _locals[0] = func.im_self
            bind_varnames = co_varnames[1:]
            bind_offset = 1
            if id(func.im_self) in self.watchers.svars:
                raise NotImplementedError('bound method on shadowed var: %s' %
                        func.__name__)
        else:
            bind_varnames = co_varnames
            bind_offset = 0

        for name in func_code.co_names:
            #print 'name', name
            try:
                self._myglobals[name] = func.func_globals[name]
            except KeyError:
                try:
                    self._myglobals[name] = __builtin__.__getattribute__(name)
                except AttributeError:
                    #print 'WARNING: name lookup failed', name
                    pass

        extra_args_ok = bool(func_code.co_flags & 0x04)
        extra_kwargs_ok = bool(func_code.co_flags & 0x08)

        # -- assert that my understanding of calling protocol is correct
        #
        # param_names: the sequence of function parameter names
        # args_param: [optional] the name of the *vargs parameter
        # kwargs_param: [optional] the name of the **kwargs parameter
        # pos_params: sequence of potentially-positional parameter names
        try:
            if extra_args_ok and extra_kwargs_ok:
                assert len(bind_varnames) >= co_argcount + 2
                param_names = bind_varnames[:co_argcount + 2]
                args_param = param_names[co_argcount]
                kwargs_param = param_names[co_argcount + 1]
                pos_params = param_names[:co_argcount]
            elif extra_kwargs_ok:
                assert len(bind_varnames) >= co_argcount + 1
                param_names = bind_varnames[:co_argcount + 1]
                kwargs_param = param_names[co_argcount]
                pos_params = param_names[:co_argcount]
            elif extra_args_ok:
                assert len(bind_varnames) >= co_argcount + 1
                param_names = bind_varnames[:co_argcount + 1]
                args_param = param_names[co_argcount]
                pos_params = param_names[:co_argcount]
            else:
                assert len(bind_varnames) >= co_argcount
                param_names = bind_varnames[:co_argcount]
                pos_params = param_names[:co_argcount]
        except AssertionError:
            print 'YIKES: MISUNDERSTANDING OF CALL PROTOCOL:',
            print co_argcount,
            print bind_varnames,
            print '%x' % func_code.co_flags
            raise

        if len(args) > co_argcount and not extra_args_ok:
            raise TypeError('Argument count exceeds number of positional params')

        # -- bind positional arguments
        for i, (param_i, arg_i) in enumerate(zip(param_names, args)):
            assert bind_varnames[i] == param_i
            _locals[i + bind_offset] = arg_i

        if extra_args_ok:
            _locals[co_varnames.index(args_param)] == args[co_argcount:]

        # -- bind keyword arguments
        if extra_kwargs_ok:
            kwargs_pos = co_varnames.index(kwargs_param)
            _locals[kwargs_pos] == {}

        for aname, aval in kwargs.items():
            try:
                pos = pos_params.index(aname) + bind_offset
            except ValueError:
                if extra_kwargs_ok:
                    _locals[kwargs_pos][aname] = aval
                    continue
                else:
                    raise TypeError('Unrecognized keyword argument', aname)
            if _locals[pos] == Unassigned:
                _locals[pos] = aval
            else:
                raise TypeError('Duplicate argument for parameter', aname)

        # -- find default values
        if func.func_defaults:
            defaults = func.func_defaults
            for ii, val in enumerate(defaults):
                if _locals[co_argcount - len(defaults) + ii] is Unassigned:
                   _locals[co_argcount - len(defaults) + ii] = val

        # print 'BINDING'
        for name, lval in zip(co_varnames, _locals):
            if (isinstance(lval, np.ndarray)
                    and not id(lval) in self.watcher.svars):
                self.add_shadow(lval)
            #print '  locals:', name, lval, id(lval)

        self.code_iter = itercode(func_code.co_code)
        jmp = None
        while not hasattr(self, 'rval'):
            try:
                i, op, arg = self.code_iter.send(jmp)
            except StopIteration:
                break
            name = opcode.opname[op]
            name = {
                    'SLICE+0': 'SLICE_PLUS_0',
                    'SLICE+1': 'SLICE_PLUS_1',
                    'SLICE+2': 'SLICE_PLUS_2',
                    'SLICE+3': 'SLICE_PLUS_3',
                    }.get(name, name)
            if self.print_ops:
                print 'OP: ', i, name
            if self.print_stack:
                print self.stack
            jmp = getattr(self, 'op_' + name)(i, op, arg)

        return self.rval