future.py 1.8 KB

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