예제 #1
0
파일: tchecker.py 프로젝트: euske/pyntch
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
예제 #2
0
 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
예제 #3
0
 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
예제 #4
0
파일: syntax.py 프로젝트: euske/pyntch
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)
예제 #5
0
def IterElement(frame0, anchor, target):
    frame1 = ExceptionCatcher(frame0)
    frame1.add_handler(StopIterationType.get_typeobj())
    return MethodCall(frame1, anchor, IterRef(frame0, anchor, target), 'next')
예제 #6
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
예제 #7
0
             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
 if showall:
     modules = Interpreter.get_all_modules()
 if ErrorConfig.unfound_modules:
     print >> sys.stderr, 'modules not found:', ', '.join(
         sorted(ErrorConfig.unfound_modules))
 TypeNode.run(iteration=iteration)
 TypeChecker.check()
 MustBeDefinedNode.check()
 ExceptionCatcher.check()
 TypeNode.run(iteration=iteration)
 if verbose:
     print >> sys.stderr, (
         'total files=%d, lines=%d in %.2fsec' %
         (Interpreter.files, Interpreter.lines, time.time() - t))
 outfp = sys.stdout
 if output:
     outfp = file(output, 'w')
 strm = IndentedStream(outfp)
 if format == 'xml': strm.write('<output>')
 for module in modules:
     if format == 'xml':
         module.showxml(strm)
     else:
         module.showtxt(strm)
예제 #8
0
파일: tchecker.py 프로젝트: euske/pyntch
     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
 if showall:
   modules = Interpreter.get_all_modules()
 if ErrorConfig.unfound_modules:
   print >>sys.stderr, 'modules not found:', ', '.join(sorted(ErrorConfig.unfound_modules))
 TypeNode.run(iteration=iteration)
 TypeChecker.check()
 MustBeDefinedNode.check()
 ExceptionCatcher.check()
 TypeNode.run(iteration=iteration)
 if verbose:
   print >>sys.stderr, ('total files=%d, lines=%d in %.2fsec' %
                        (Interpreter.files, Interpreter.lines, time.time()-t))
 outfp = sys.stdout
 if output:
   outfp = file(output, 'w')
 strm = IndentedStream(outfp)
 if format == 'xml': strm.write('<output>')
 for module in modules:
   if format == 'xml':
     module.showxml(strm)
   else:
     module.showtxt(strm)
 if format == 'xml': strm.write('</output>')
예제 #9
0
파일: expression.py 프로젝트: euske/pyntch
def IterElement(frame0, anchor, target):
  frame1 = ExceptionCatcher(frame0)
  frame1.add_handler(StopIterationType.get_typeobj())
  return MethodCall(frame1, anchor, IterRef(frame0, anchor, target), 'next')