def create_attr(self, frame, anchor, name):
     if name == 'add':
         return self.SequenceAppender('set.add', self, args=[ANY])
     elif name == 'clear':
         return BuiltinConstMethod('set.clear', NoneType.get_object())
     elif name == 'difference_update':
         return BuiltinConstMethod('set.difference_update',
                                   NoneType.get_object(), [[ANY]])
     elif name == 'discard':
         return BuiltinConstMethod('set.discard', NoneType.get_object(),
                                   [ANY])
     elif name == 'intersection_update':
         return BuiltinConstMethod('set.intersection_update',
                                   NoneType.get_object(), [[ANY]])
     elif name == 'pop':
         return BuiltinConstMethod(
             'set.pop',
             NoneType.get_object(),
             expts=[ErrorConfig.MaybeElementNotRemovable()])
     elif name == 'remove':
         return BuiltinConstMethod(
             'set.remove',
             NoneType.get_object(), [ANY],
             expts=[ErrorConfig.MaybeElementNotFound()])
     elif name == 'symmetric_difference_update':
         return self.SequenceExtender('set.symmetric_difference_update',
                                      self,
                                      args=[ANY])
     elif name == 'update':
         return self.SequenceExtender('set.update', self, self, [ANY])
     return FrozenSetObject.create_attr(self, frame, anchor, name)
 def create_attr(self, frame, anchor, name):
     if name == 'append':
         return self.SequenceAppender('list.append', self, args=[ANY])
     elif name == 'count':
         return BuiltinConstMethod('list.count', IntType.get_object(),
                                   [ANY])
     elif name == 'extend':
         return self.SequenceExtender('list.extend', self, args=[ANY])
     elif name == 'index':
         return BuiltinConstMethod(
             'list.index',
             IntType.get_object(), [ANY], [IntType, IntType],
             expts=[ErrorConfig.MaybeElementNotFound()])
     elif name == 'insert':
         return self.InsertMethod('list.insert', self, [IntType, ANY])
     elif name == 'pop':
         return BuiltinConstMethod(
             'list.pop',
             self.elemall, [], [IntType],
             expts=[ErrorConfig.MaybeElementNotRemovable()])
     elif name == 'remove':
         return BuiltinConstMethod(
             'list.remove',
             NoneType.get_object(), [ANY],
             expts=[ErrorConfig.MaybeElementNotRemovable()])
     elif name == 'reverse':
         return BuiltinConstMethod('list.remove', NoneType.get_object())
     elif name == 'sort':
         return self.SortMethod('list.sort', self)
     raise NodeAttrError(name)
Beispiel #3
0
def main(argv):
  import getopt
  def usage():
    print 'usage: %s [-d] [-q] [-a] [-i iteration] [-c config] [-C key=val] [-D] [-p pythonpath] [-P stubpath] [-o output] [-t format] [file ...]' % argv[0]
    return 100
  try:
    (opts, args) = getopt.getopt(argv[1:], 'dqai:c:CDp:P:o:t:')
  except getopt.GetoptError:
    return usage()
  if not args:
    return usage()
  stubdir = os.path.join(os.path.dirname(pyntch.__file__), 'stub')
  debug = 0
  defaultpath = True
  showall = False
  format = 'txt'
  verbose = 1
  iteration = sys.maxint
  modpath = []
  stubpath = [stubdir]
  output = None
  for (k, v) in opts:
    if k == '-d': debug += 1
    elif k == '-q': verbose -= 1
    elif k == '-a': showall = True
    elif k == '-i': iteration = int(v)
    elif k == '-c': ErrorConfig.load(v)
    elif k == '-C':
      (k,v) = v.split('=')
      ErrorConfig.set(k, eval(v))
    elif k == '-D': defaultpath = False
    elif k == '-p': modpath.extend(v.split(':'))
    elif k == '-P': stubpath.extend(v.split(':'))
    elif k == '-o':
      output = v
      if v.endswith('.xml'):
        format = 'xml'
    elif k == '-t': format = v
  if defaultpath:
    modpath.extend(sys.path)
  TypeNode.debug = debug
  TypeNode.verbose = verbose
  Interpreter.debug = debug
  Interpreter.verbose = verbose
  Interpreter.initialize(stubpath)
  TypeChecker.reset()
  MustBeDefinedNode.reset()
  ExceptionCatcher.reset()
  t = time.time()
  modules = []
  for name in args:
    try:
      if name.endswith('.py'):
        path = name
        (name,_) = os.path.splitext(os.path.basename(name))
        modules.append(Interpreter.load_file(name, path, modpath))
      else:
        modules.append(Interpreter.load_module(name, modpath)[-1])
    except ModuleNotFound, e:
      print >>sys.stderr, 'module not found:', name
Beispiel #4
0
 def get_attr(self, frame, anchor, name, write=False):
     from pyntch.aggregate_types import ListType
     if write: raise NodeAssignError(name)
     if name == 'close':
         return BuiltinConstMethod('file.close', NoneType.get_object())
     elif name == 'closed':
         return BoolType.get_object()
     elif name == 'encoding':
         return StrType.get_object()
     elif name == 'fileno':
         return BuiltinConstMethod('file.fileno', IntType.get_object())
     elif name == 'flush':
         return BuiltinConstMethod('file.flush', NoneType.get_object())
     elif name == 'isatty':
         return BuiltinConstMethod('file.isatty', BoolType.get_object())
     elif name == 'mode':
         return StrType.get_object()
     elif name == 'name':
         return StrType.get_object()
     elif name == 'newlines':
         return NoneType.get_object()
     elif name == 'next':
         return BuiltinConstMethod('file.next', StrType.get_object())
     elif name == 'read':
         return BuiltinConstMethod('file.read', StrType.get_object(), [],
                                   [IntType], [ErrorConfig.MaybeEOFError()])
     elif name == 'readline':
         return BuiltinConstMethod('file.readline', StrType.get_object(),
                                   [], [IntType],
                                   [ErrorConfig.MaybeEOFError()])
     elif name == 'readlines':
         return BuiltinConstMethod(
             'file.readlines', ListType.create_list(StrType.get_object()),
             [], [IntType], [ErrorConfig.MaybeEOFError()])
     elif name == 'seek':
         return BuiltinConstMethod('file.seek', NoneType.get_object(),
                                   [IntType], [IntType],
                                   [ErrorConfig.MaybeEOFError()])
     elif name == 'softspace':
         return IntType.get_object()
     elif name == 'tell':
         return BuiltinConstMethod(
             'file.tell',
             IntType.get_object(),
             expts=[ErrorConfig.MaybeFileIllegalSeek()])
     elif name == 'truncate':
         return BuiltinConstMethod('file.truncate', NoneType.get_object(),
                                   [], [IntType])
     elif name == 'write':
         return BuiltinConstMethod('file.write', NoneType.get_object(),
                                   [BaseStringType])
     elif name == 'writelines':
         return BuiltinConstMethod('file.writestrings',
                                   NoneType.get_object(),
                                   [[BaseStringType]])
     elif name == 'xreadlines':
         return self
     raise NodeAttrError(name)
Beispiel #5
0
 def call(self, frame, anchor, args, kwargs):
     if kwargs:
         frame.raise_expt(ErrorConfig.NoKeywordArgs())
         return UndefinedTypeNode.get_object()
     if len(args) < self.minargs:
         frame.raise_expt(
             ErrorConfig.InvalidNumOfArgs(self.minargs, len(args)))
         return UndefinedTypeNode.get_object()
     return self.MapCaller(frame, anchor, args[0], args[1:])
Beispiel #6
0
 def call(self, frame, anchor, args, kwargs):
   from pyntch.config import ErrorConfig
   if len(args) < self.minargs:
     frame.raise_expt(ErrorConfig.InvalidNumOfArgs(self.minargs, len(args)))
     return UndefinedTypeNode.get_object()
   if len(self.args) < len(args):
     frame.raise_expt(ErrorConfig.InvalidNumOfArgs(len(self.args), len(args)))
     return UndefinedTypeNode.get_object()
   return self.process_args(frame, anchor, args, kwargs)
Beispiel #7
0
 def import_all(self, space):
   from pyntch.config import ErrorConfig
   if space.all_names:
     names = space.all_names
   else:
     names = [ k for k in space.vars.iterkeys() if not k.startswith('_') ]
   for k in names:
     try:
       self.vars[k] = space.vars[k]
     except KeyError:
       ErrorConfig.module_not_found(k)
   return
Beispiel #8
0
 def call(self, frame, anchor, args, kwargs):
     from pyntch.basic_types import StrType
     from pyntch.aggregate_types import DictType, TupleType
     from pyntch.expression import TupleUnpack, TupleSlice
     # Process keyword arguments first.
     varsleft = list(self.argvars)
     varikwargs = []
     for (kwname, kwvalue) in kwargs.iteritems():
         for var1 in varsleft:
             if isinstance(var1, Variable) and var1.name == kwname:
                 var1.bind(kwvalue)
                 # When a keyword argument is given, remove that name from the remaining arguments.
                 varsleft.remove(var1)
                 break
         else:
             if self.kwarg:
                 varikwargs.append(kwvalue)
             else:
                 frame.raise_expt(ErrorConfig.InvalidKeywordArgs(kwname))
     # Process standard arguments.
     variargs = []
     for arg1 in args:
         assert arg1 != None, args
         if varsleft:
             var1 = varsleft.pop(0)
             assign_arg(frame, anchor, var1, arg1)
         elif self.variarg:
             variargs.append(arg1)
         else:
             # Too many arguments.
             frame.raise_expt(
                 ErrorConfig.InvalidNumOfArgs(len(self.argvars), len(args)))
     if len(self.defaults) < len(varsleft):
         # Too few arguments.
         frame.raise_expt(
             ErrorConfig.InvalidNumOfArgs(len(self.argvars), len(args)))
     # Handle remaining arguments: kwargs and variargs.
     if self.variarg and variargs:
         self.space[self.variarg].bind(TupleType.create_tuple(variargs))
     if self.kwarg:
         if varikwargs:
             self.space[self.kwarg].bind(
                 DictType.create_dict(key=StrType.get_object(),
                                      value=varikwargs))
         else:
             self.space[self.kwarg].bind(DictType.create_null(
                 frame, anchor))
     # Remember where this is called from.
     self.frames.add(frame)
     # Propagate the exceptions upward.
     self.frame.connect(frame.recv)
     return self.body
Beispiel #9
0
 def recv(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         if obj.is_type(BaseStringType.get_typeobj()):
             self.frame.raise_expt(
                 ErrorConfig.MaybeNotConvertable(self.TYPE_NAME))
         elif obj.is_type(SimpleNumberType.get_typeobj(),
                          BoolType.get_typeobj()):
             pass
         else:
             self.frame.raise_expt(
                 ErrorConfig.NotConvertable(self.TYPE_NAME))
     return
Beispiel #10
0
 def recv_target(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             seq = obj.get_slice(self.frame,
                                 self.anchor,
                                 self.subs,
                                 write=True)
             self.elemall.connect(seq.elemall.recv)
         except (NodeTypeError, NodeAttrError):
             self.raise_expt(ErrorConfig.NotSubscriptable(obj))
         except NodeAssignError:
             self.raise_expt(ErrorConfig.NotAssignable(obj))
     return
Beispiel #11
0
 def recv_target(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             self.value.connect(
                 obj.get_element(self.frame,
                                 self.anchor,
                                 self.sub,
                                 write=True).recv)
         except NodeTypeError:
             self.raise_expt(ErrorConfig.NotSubscriptable(obj))
         except NodeAssignError:
             self.raise_expt(ErrorConfig.NotAssignable(obj))
     return
Beispiel #12
0
 def get_attr(self, frame, anchor, name, write=False):
     if write: raise NodeAssignError(name)
     if name == 'translate':
         return BuiltinConstMethod('str.translate', self.get_object(),
                                   [BaseStringType], [BaseStringType],
                                   [ErrorConfig.MaybeTableInvalid()])
     return BaseStringType.get_attr(self, frame, anchor, name, write=write)
 def recv_pair(self, src):
     for obj in src:
         if obj.is_type(TupleType.get_typeobj()) and obj.elements:
             if len(obj.elements) == 2:
                 (k, v) = obj.elements
                 k.connect(self.target.key.recv)
                 v.connect(self.target.value.recv)
             else:
                 self.frame.raise_expt(
                     ErrorConfig.NotConvertable('(key,value)'))
             continue
         elem = IterElement(self.frame, self.anchor, obj)
         elem.connect(self.target.key.recv)
         elem.connect(self.target.value.recv)
         self.frame.raise_expt(ErrorConfig.NotConvertable('dict'))
     return
Beispiel #14
0
 def recv_func(self, src):
     for obj in src:
         try:
             obj.call(self.frame, self.anchor, (self.target.elemall, ))
         except NodeTypeError:
             self.frame.raise_expt(ErrorConfig.NotCallable(obj))
     return
 def process_args(self, frame, anchor, args, kwargs):
     if kwargs:
         frame.raise_expt(ErrorConfig.NoKeywordArgs())
         return UndefinedTypeNode.get_object()
     if args:
         return self.create_sequence(frame, anchor, args[0])
     return self.create_null(frame, anchor)
Beispiel #16
0
 def check_undefined(self):
     if not self.received: return
     for (lobj, robj) in self.received:
         if (lobj, robj) not in self.computed:
             self.raise_expt(
                 ErrorConfig.NotSupportedOperand(self.op, lobj, robj))
     return
Beispiel #17
0
 def call(self, frame, anchor, args, kwargs):
   from pyntch.config import ErrorConfig
   if len(args) == 0:
     frame.raise_expt(ErrorConfig.InvalidNumOfArgs(1, len(args)))
     return UndefinedTypeNode.get_object()
   arg0checker = TypeChecker(frame, [self.klass], 'arg0')
   args[0].connect(arg0checker.recv)
   return self.func.call(frame, anchor, args, kwargs)
 def process_args(self, frame, anchor, args, kwargs):
     if kwargs:
         frame.raise_expt(ErrorConfig.NoKeywordArgs())
         return UndefinedTypeNode.get_object()
     elemall = TupleType.create_tuple(
         [IntType.get_object(),
          IterElement(frame, anchor, args[0])])
     return IterObject(self.get_typeobj(), elemall=elemall)
Beispiel #19
0
 def recv_target(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             obj.get_iter(self.frame, self.anchor).connect(self.recv)
         except NodeTypeError:
             self.raise_expt(ErrorConfig.NotIterable(obj))
     return
Beispiel #20
0
 def process_args(self, frame, anchor, args, kwargs):
   from pyntch.config import ErrorConfig
   if kwargs:
     frame.raise_expt(ErrorConfig.NoKeywordArgs())
   for (i,arg1) in enumerate(args):
     assert isinstance(arg1, TypeNode)
     self.accept_arg(frame, anchor, i, arg1)
   for expt in self.expts:
     frame.raise_expt(expt)
   return self.retobj
Beispiel #21
0
 def recv_func(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         if not isinstance(obj, NoneType):
             try:
                 obj.call(self.frame, self.anchor, (self.elem, ), {})
             except NodeTypeError:
                 self.frame.raise_expt(ErrorConfig.NotCallable(obj))
     return
Beispiel #22
0
 def recv_func(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             obj.call(self.frame, self.anchor, self.args,
                      {}).connect(self.listobj.elemall.recv)
         except NodeTypeError:
             self.frame.raise_expt(ErrorConfig.NotCallable(obj))
     return
Beispiel #23
0
 def call(self, frame, anchor, args, kwargs):
     if kwargs:
         frame.raise_expt(ErrorConfig.NoKeywordArgs())
         return UndefinedTypeNode.get_object()
     elems = [CompoundTypeNode() for arg1 in args]
     zipelem = TupleType.create_tuple(elements=elems)
     seq = ListType.create_list(elemall=zipelem)
     for (i, arg1) in enumerate(args):
         IterElement(frame, anchor, arg1).connect(elems[i].recv)
     return seq
Beispiel #24
0
 def recv_target(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             obj.get_attr(self.frame, self.anchor,
                          self.attrname).connect(self.recv)
         except NodeAttrError:
             self.raise_expt(
                 ErrorConfig.AttributeNotFound(obj, self.attrname))
     return
 def recv_fkey(self, src):
     for obj in src:
         if obj in self.received_fkey: continue
         self.received_fkey.add(obj)
         try:
             obj.call(self.frame, self.anchor,
                      (self.target.elemall, ),
                      {}).connect(self.key.recv)
         except NodeTypeError:
             self.frame.raise_expt(ErrorConfig.NotCallable(obj))
     return
Beispiel #26
0
 def recv_target(self, src):
     from pyntch.aggregate_types import DictType
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         if obj.is_type(DictType.get_typeobj()):
             MethodCall(self.frame, self.anchor, obj,
                        'iteritems').connect(self.recv)
         else:
             self.raise_expt(ErrorConfig.TypeCheckerError(src, obj, 'dict'))
     return
 def process_args(self, frame, anchor, args, kwargs):
     params = dict.fromkeys(['cmp', 'key', 'reverse'])
     args = list(args)
     if args:
         params['cmp'] = args.pop(0)
     if args:
         params['key'] = args.pop(0)
     if args:
         params['reserved'] = args.pop(0)
     for (k, v) in kwargs.iteritems():
         if k in params:
             if params[k] != None:
                 frame.raise_expt(ErrorConfig.NoKeywordArg1(k))
             else:
                 params[k] = v
         else:
             frame.raise_expt(ErrorConfig.NoKeywordArg1(k))
     self.FuncChecker(frame, anchor, self.target, params['cmp'],
                      params['key'])
     return NoneType.get_object()
Beispiel #28
0
 def recv_func(self, _):
     for obj in self.func:
         for varargs in list(self.varargs):
             k = (obj, varargs)
             if k in self.received: continue
             self.received.add(k)
             try:
                 obj.call(self.frame, self.anchor, self.args + varargs,
                          self.kwargs).connect(self.recv)
             except NodeTypeError:
                 self.raise_expt(ErrorConfig.NotCallable(obj))
     return
Beispiel #29
0
 def recv(self, src):
   from pyntch.config import ErrorConfig
   from pyntch.aggregate_types import DictObject
   for obj in src:
     if obj in self.received: continue
     self.received.add(obj)
     if isinstance(obj, DictObject):
       obj.key.connect(self.keychecker.recv)
       obj.value.connect(self.valuechecker.recv)
     else:
       self.parent_frame.raise_expt(ErrorConfig.TypeCheckerError(self.blame, obj, 'dict'))
   return
Beispiel #30
0
 def call(self, frame, anchor, args, kwargs):
     if kwargs:
         frame.raise_expt(ErrorConfig.NoKeywordArgs())
         return UndefinedTypeNode.get_object()
     retobj = CompoundTypeNode()
     if len(args) == 1:
         IterElement(frame, anchor, args[0]).connect(retobj.recv)
     else:
         for arg1 in args:
             arg1.connect(retobj.recv)
     if 'key' in kwargs:
         IterFuncChecker(frame, anchor, retobj, kwargs['key'])
     return retobj
 def recv_target(self, src):
     for obj in src:
         if obj in self.received: continue
         self.received.add(obj)
         try:
             iterobj = obj.get_reversed(self.frame, self.anchor)
             frame1 = ExceptionCatcher(self.frame)
             frame1.add_handler(StopIterationType.get_typeobj())
             MethodCall(frame1, self.anchor, iterobj,
                        'next').connect(self.recv)
         except NodeTypeError:
             self.frame.raise_expt(ErrorConfig.NotIterable(obj))
     return
Beispiel #32
0
def build_stmt(reporter, frame, space, tree, evals, isfuncdef=False, parent_space=None):
  from pyntch.basic_types import NoneType, StrType
  from pyntch.module import ModuleNotFound
  from pyntch.config import ErrorConfig
  assert isinstance(frame, ExecutionFrame)

  if isinstance(tree, ast.Module):
    build_stmt(reporter, frame, space, tree.node, evals)
  
  # def
  elif isinstance(tree, ast.Function):
    name = tree.name
    defaults = [ build_expr(reporter, frame, space, value, evals) for value in tree.defaults ]
    parent_space = parent_space or space # class definition
    func = FuncType(reporter, frame, parent_space, tree, name, tree.argnames,
                    defaults, tree.varargs, tree.kwargs, tree)
    if tree.decorators:
      for node in tree.decorators:
        decor = build_expr(reporter, frame, space, node, evals)
        func = FunCall(ExecutionFrame(frame, node), node, decor, (func,))
    space[name].bind(func)

  # class
  elif isinstance(tree, ast.Class):
    name = tree.name
    bases = [ build_expr(reporter, frame, space, base, evals) for base in tree.bases ]
    klass = PythonClassType(reporter, frame, space, tree, name, bases, evals, tree)
    space[name].bind(klass)

  # assign
  elif isinstance(tree, ast.Assign):
    for n in tree.nodes:
      value = build_expr(reporter, frame, space, tree.expr, evals)
      build_assign(reporter, frame, space, n, value, evals)

  # augassign
  elif isinstance(tree, ast.AugAssign):
    left = build_expr(reporter, frame, space, tree.node, evals)
    if isinstance(left, UndefinedTypeNode):
      # ignore an undefined variable.
      pass
    else:
      right = build_expr(reporter, frame, space, tree.expr, evals)
      value = AssignOp(ExecutionFrame(frame, tree), tree, tree.op, left, right)
      build_assign(reporter, frame, space, tree.node, value, evals)

  # return
  elif isinstance(tree, ast.Return):
    value = build_expr(reporter, frame, space, tree.value, evals)
    evals.append(('r', value))
    return True

  # yield (for python 2.4)
  elif isinstance(tree, ast.Yield):
    value = build_expr(reporter, frame, space, tree.value, evals)
    evals.append(('y', value))
    return True

  # (mutliple statements)
  elif isinstance(tree, ast.Stmt):
    stmt = None
    exit = False
    for stmt in tree.nodes:
      exit = build_stmt(reporter, frame, space, stmt, evals, parent_space=parent_space)
    if isfuncdef and not exit:
      # if the last statement is not a Return or Raise
      value = NoneType.get_object()
      evals.append(('r', value))
    return exit

  # if, elif, else
  elif isinstance(tree, ast.If):
    for (expr,stmt) in tree.tests:
      value = build_expr(reporter, frame, space, expr, evals)
      exit = build_stmt(reporter, frame, space, stmt, evals)
    if tree.else_:
      exit = build_stmt(reporter, frame, space, tree.else_, evals) and exit
    else:
      exit = False
    return exit

  # for
  elif isinstance(tree, ast.For):
    seq = build_expr(reporter, frame, space, tree.list, evals)
    elem = IterElement(ExecutionFrame(frame, tree.list), tree.list, seq)
    build_assign(reporter, frame, space, tree.assign, elem, evals)
    exit = build_stmt(reporter, frame, space, tree.body, evals)
    if tree.else_:
      exit = build_stmt(reporter, frame, space, tree.else_, evals) and exit
    return exit

  # while
  elif isinstance(tree, ast.While):
    value = build_expr(reporter, frame, space, tree.test, evals)
    exit = build_stmt(reporter, frame, space, tree.body, evals)
    if tree.else_:
      exit = build_stmt(reporter, frame, space, tree.else_, evals) and exit
    return exit

  # try ... except
  elif isinstance(tree, ast.TryExcept):
    catcher = ExceptionCatcher(frame)
    for (expr,e,stmt) in tree.handlers:
      if expr:
        expts = build_expr(reporter, frame, space, expr, evals)
        handler = catcher.add_handler(expts)
        if e:
          build_assign(reporter, handler, space, e, handler.var, evals)
      else:
        handler = catcher.add_handler(None)
      exit = build_stmt(reporter, handler, space, stmt, evals)
    exit = build_stmt(reporter, catcher, space, tree.body, evals) and exit
    if tree.else_:
      exit = build_stmt(reporter, frame, space, tree.else_, evals) and exit
    return exit

  # try ... finally
  elif isinstance(tree, ast.TryFinally):
    exit = build_stmt(reporter, frame, space, tree.body, evals)
    exit = build_stmt(reporter, frame, space, tree.final, evals) and exit
    return exit

  # raise
  elif isinstance(tree, ast.Raise):
    # XXX ignoring tree.expr3 (what is this for anyway?)
    if tree.expr2:
      expttype = build_expr(reporter, frame, space, tree.expr1, evals)
      exptarg = build_expr(reporter, frame, space, tree.expr2, evals)
      ExceptionMaker(ExecutionFrame(frame, tree), tree, expttype, (exptarg,))
    elif tree.expr1:
      expttype = build_expr(reporter, frame, space, tree.expr1, evals)
      ExceptionMaker(ExecutionFrame(frame, tree), tree, expttype, ())
    else:
      # re-raise
      frame.set_reraise()
    return True

  # printnl
  elif isinstance(tree, (ast.Print, ast.Printnl)):
    for node in tree.nodes:
      value = build_expr(reporter, frame, space, node, evals)
      StrType.StrConverter(ExecutionFrame(frame, node), tree, value)

  # discard
  elif isinstance(tree, ast.Discard):
    value = build_expr(reporter, frame, space, tree.expr, evals)

  # pass, break, continue
  elif isinstance(tree, (ast.Pass, ast.Break, ast.Continue)):
    pass

  # import
  elif isinstance(tree, ast.Import):
    for (name,asname) in tree.names:
      try:
        modules = tree._module.load_module(name)
        if asname:
          space[asname].bind(modules[-1])
        else:
          asname = name.split('.')[0]
          space[asname].bind(modules[0])
      except ModuleNotFound, e:
        ErrorConfig.module_not_found(e.name)
Beispiel #33
0
          asname = name.split('.')[0]
          space[asname].bind(modules[0])
      except ModuleNotFound, e:
        ErrorConfig.module_not_found(e.name)
        
  elif isinstance(tree, ast.From):
    try:
      modname = tree.modname
      modules = tree._module.load_module(modname)
      for (name,asname) in tree.names:
        if name != '*':
          try:
            obj = modules[-1].import_object(name)
            space[asname or name].bind(obj)
          except ModuleNotFound, e:
            ErrorConfig.module_not_found(modname+'.'+e.name)
    except ModuleNotFound, e:
      ErrorConfig.module_not_found(e.name)
  
  # global
  elif isinstance(tree, ast.Global):
    pass

  # with (for __future__ python 2.5 or 2.6)
  elif isinstance(tree, ast.With):
    # XXX need to call __enter__ and __exit__
    value = build_expr(reporter, frame, space, tree.expr, evals)
    build_assign(reporter, frame, space, tree.vars, value, evals)
    build_stmt(reporter, frame, space, tree.body, evals)

  # del
Beispiel #34
0
  def register_names(self, tree):
    from pyntch.module import ModuleNotFound
    from pyntch.config import ErrorConfig

    if isinstance(tree, ast.Module):
      self.register_names(tree.node)
      
    # global
    elif isinstance(tree, ast.Global):
      for name in tree.names:
        self.vars[name] = self.global_space.register_var(name)

    # def
    elif isinstance(tree, ast.Function):
      self.register_var(tree.name)
      for value in tree.defaults:
        self.register_names(value)
    # class
    elif isinstance(tree, ast.Class):
      self.register_var(tree.name)
      for base in tree.bases:
        self.register_names(base)
    # assign
    elif isinstance(tree, ast.Assign):
      for node in tree.nodes:
        self.register_names(tree.expr)
        self.register_names(node)
    elif isinstance(tree, ast.AugAssign):
      self.register_names(tree.expr)
    elif isinstance(tree, ast.AssTuple):
      for c in tree.nodes:
        self.register_names(c)
    elif isinstance(tree, ast.AssList):
      for c in tree.nodes:
        self.register_names(c)
    elif isinstance(tree, ast.AssName):
      self.register_var(tree.name)
    elif isinstance(tree, ast.AssAttr):
      pass
    elif isinstance(tree, ast.Subscript):
      self.register_names(tree.expr)
      for sub in tree.subs:
        self.register_names(sub)

    # return
    elif isinstance(tree, ast.Return):
      self.register_names(tree.value)

    # yield (for both python 2.4 and 2.5)
    elif isinstance(tree, ast.Yield):
      self.register_names(tree.value)

    # with (for __future__ python 2.5 or 2.6)
    elif isinstance(tree, ast.With):
      self.register_names(tree.expr)
      self.register_names(tree.vars)
      self.register_names(tree.body)

    # (mutliple statements)
    elif isinstance(tree, ast.Stmt):
      for stmt in tree.nodes:
        self.register_names(stmt)

    # if, elif, else
    elif isinstance(tree, ast.If):
      for (expr,stmt) in tree.tests:
        self.register_names(expr)
        self.register_names(stmt)
      if tree.else_:
        self.register_names(tree.else_)

    # for
    elif isinstance(tree, ast.For):
      self.register_names(tree.list)
      self.register_names(tree.assign)
      self.register_names(tree.body)
      if tree.else_:
        self.register_names(tree.else_)

    # while
    elif isinstance(tree, ast.While):
      self.register_names(tree.test)
      self.register_names(tree.body)
      if tree.else_:
        self.register_names(tree.else_)

    # try ... except
    elif isinstance(tree, ast.TryExcept):
      self.register_names(tree.body)
      for (expr,e,stmt) in tree.handlers:
        if expr:
          self.register_names(expr)
        if e:
          self.register_names(e)
        self.register_names(stmt)
      if tree.else_:
        self.register_names(tree.else_)

    # try ... finally
    elif isinstance(tree, ast.TryFinally):
      self.register_names(tree.body)
      self.register_names(tree.final)

    # raise
    elif isinstance(tree, ast.Raise):
      if tree.expr1:
        self.register_names(tree.expr1)
      if tree.expr2:
        self.register_names(tree.expr2)
        
    # import
    elif isinstance(tree, ast.Import):
      for (name,asname) in tree.names:
        if asname:
          self.register_var(asname)
        else:
          name = name.split('.')[0]
          self.register_var(name)

    # from
    elif isinstance(tree, ast.From):
      for (name,asname) in tree.names:
        if name == '*':
          modname = tree.modname
          try:
            module = tree._module.load_module(modname)[-1]
            self.import_all(module.space)
          except ModuleNotFound, e:
            ErrorConfig.module_not_found(e.name)
        else:
          self.register_var(asname or name)