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