paul@0 | 1 | """Parser for future statements |
paul@0 | 2 | |
paul@0 | 3 | """ |
paul@0 | 4 | |
paul@0 | 5 | from compiler import ast, walk |
paul@0 | 6 | |
paul@0 | 7 | def is_future(stmt): |
paul@0 | 8 | """Return true if statement is a well-formed future statement""" |
paul@0 | 9 | if not isinstance(stmt, ast.From): |
paul@0 | 10 | return 0 |
paul@0 | 11 | if stmt.modname == "__future__": |
paul@0 | 12 | return 1 |
paul@0 | 13 | else: |
paul@0 | 14 | return 0 |
paul@0 | 15 | |
paul@0 | 16 | class FutureParser: |
paul@0 | 17 | |
paul@0 | 18 | features = ("nested_scopes", "generators", "division", |
paul@0 | 19 | "absolute_import", "with_statement", "print_function", |
paul@0 | 20 | "unicode_literals") |
paul@0 | 21 | |
paul@0 | 22 | def __init__(self): |
paul@0 | 23 | self.found = {} # set |
paul@0 | 24 | |
paul@0 | 25 | def visitModule(self, node): |
paul@0 | 26 | stmt = node.node |
paul@0 | 27 | for s in stmt.nodes: |
paul@0 | 28 | if not self.check_stmt(s): |
paul@0 | 29 | break |
paul@0 | 30 | |
paul@0 | 31 | def check_stmt(self, stmt): |
paul@0 | 32 | if is_future(stmt): |
paul@0 | 33 | for name, asname in stmt.names: |
paul@0 | 34 | if name in self.features: |
paul@0 | 35 | self.found[name] = 1 |
paul@0 | 36 | else: |
paul@0 | 37 | raise SyntaxError, \ |
paul@0 | 38 | "future feature %s is not defined" % name |
paul@0 | 39 | stmt.valid_future = 1 |
paul@0 | 40 | return 1 |
paul@0 | 41 | return 0 |
paul@0 | 42 | |
paul@0 | 43 | def get_features(self): |
paul@0 | 44 | """Return list of features enabled by future statements""" |
paul@0 | 45 | return self.found.keys() |
paul@0 | 46 | |
paul@0 | 47 | class BadFutureParser: |
paul@0 | 48 | """Check for invalid future statements""" |
paul@0 | 49 | |
paul@0 | 50 | def visitFrom(self, node): |
paul@0 | 51 | if hasattr(node, 'valid_future'): |
paul@0 | 52 | return |
paul@0 | 53 | if node.modname != "__future__": |
paul@0 | 54 | return |
paul@0 | 55 | raise SyntaxError, "invalid future statement " + repr(node) |
paul@0 | 56 | |
paul@0 | 57 | def find_futures(node): |
paul@0 | 58 | p1 = FutureParser() |
paul@0 | 59 | p2 = BadFutureParser() |
paul@0 | 60 | walk(node, p1) |
paul@0 | 61 | walk(node, p2) |
paul@0 | 62 | return p1.get_features() |
paul@0 | 63 | |
paul@0 | 64 | if __name__ == "__main__": |
paul@0 | 65 | import sys |
paul@0 | 66 | from compiler import parseFile, walk |
paul@0 | 67 | |
paul@0 | 68 | for file in sys.argv[1:]: |
paul@0 | 69 | print file |
paul@0 | 70 | tree = parseFile(file) |
paul@0 | 71 | v = FutureParser() |
paul@0 | 72 | walk(tree, v) |
paul@0 | 73 | print v.found |
paul@0 | 74 | print |