optimizer.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # -*- coding: utf-8 -*-
  2. """The optimizer tries to constant fold expressions and modify the AST
  3. in place so that it should be faster to evaluate.
  4. Because the AST does not contain all the scoping information and the
  5. compiler has to find that out, we cannot do all the optimizations we
  6. want. For example, loop unrolling doesn't work because unrolled loops
  7. would have a different scope. The solution would be a second syntax tree
  8. that stored the scoping rules.
  9. """
  10. from . import nodes
  11. from .visitor import NodeTransformer
  12. def optimize(node, environment):
  13. """The context hint can be used to perform an static optimization
  14. based on the context given."""
  15. optimizer = Optimizer(environment)
  16. return optimizer.visit(node)
  17. class Optimizer(NodeTransformer):
  18. def __init__(self, environment):
  19. self.environment = environment
  20. def generic_visit(self, node, *args, **kwargs):
  21. node = super(Optimizer, self).generic_visit(node, *args, **kwargs)
  22. # Do constant folding. Some other nodes besides Expr have
  23. # as_const, but folding them causes errors later on.
  24. if isinstance(node, nodes.Expr):
  25. try:
  26. return nodes.Const.from_untrusted(
  27. node.as_const(args[0] if args else None),
  28. lineno=node.lineno,
  29. environment=self.environment,
  30. )
  31. except nodes.Impossible:
  32. pass
  33. return node