0001 """Parser for future statements 0002 0003 """ 0004 0005 from compiler import ast, walk 0006 0007 def is_future(stmt): 0008 """Return true if statement is a well-formed future statement""" 0009 if not isinstance(stmt, ast.From): 0010 return 0 0011 if stmt.modname == "__future__": 0012 return 1 0013 else: 0014 return 0 0015 0016 class FutureParser: 0017 0018 features = ("nested_scopes", "generators", "division") 0019 0020 def __init__(self): 0021 self.found = {} # set 0022 0023 def visitModule(self, node): 0024 stmt = node.node 0025 for s in stmt.nodes: 0026 if not self.check_stmt(s): 0027 break 0028 0029 def check_stmt(self, stmt): 0030 if is_future(stmt): 0031 for name, asname in stmt.names: 0032 if name in self.features: 0033 self.found[name] = 1 0034 else: 0035 raise SyntaxError, \ 0036 "future feature %s is not defined" % name 0037 stmt.valid_future = 1 0038 return 1 0039 return 0 0040 0041 def get_features(self): 0042 """Return list of features enabled by future statements""" 0043 return self.found.keys() 0044 0045 class BadFutureParser: 0046 """Check for invalid future statements""" 0047 0048 def visitFrom(self, node): 0049 if hasattr(node, 'valid_future'): 0050 return 0051 if node.modname != "__future__": 0052 return 0053 raise SyntaxError, "invalid future statement" 0054 0055 def find_futures(node): 0056 p1 = FutureParser() 0057 p2 = BadFutureParser() 0058 walk(node, p1) 0059 walk(node, p2) 0060 return p1.get_features() 0061 0062 if __name__ == "__main__": 0063 import sys 0064 from compiler import parseFile, walk 0065 0066 for file in sys.argv[1:]: 0067 print file 0068 tree = parseFile(file) 0069 v = FutureParser() 0070 walk(tree, v) 0071 print v.found 0072 print 0073
Generated by PyXR 0.9.4