optimizer.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.optimizer
  4. ~~~~~~~~~~~~~~~~
  5. The jinja optimizer is currently trying to constant fold a few expressions
  6. and modify the AST in place so that it should be easier to evaluate it.
  7. Because the AST does not contain all the scoping information and the
  8. compiler has to find that out, we cannot do all the optimizations we
  9. want. For example loop unrolling doesn't work because unrolled loops would
  10. have a different scoping.
  11. The solution would be a second syntax tree that has the scoping rules stored.
  12. :copyright: (c) 2010 by the Jinja Team.
  13. :license: BSD.
  14. """
  15. from jinja2 import nodes
  16. from jinja2.visitor import NodeTransformer
  17. def optimize(node, environment):
  18. """The context hint can be used to perform an static optimization
  19. based on the context given."""
  20. optimizer = Optimizer(environment)
  21. return optimizer.visit(node)
  22. class Optimizer(NodeTransformer):
  23. def __init__(self, environment):
  24. self.environment = environment
  25. def visit_If(self, node):
  26. """Eliminate dead code."""
  27. # do not optimize ifs that have a block inside so that it doesn't
  28. # break super().
  29. if node.find(nodes.Block) is not None:
  30. return self.generic_visit(node)
  31. try:
  32. val = self.visit(node.test).as_const()
  33. except nodes.Impossible:
  34. return self.generic_visit(node)
  35. if val:
  36. body = node.body
  37. else:
  38. body = node.else_
  39. result = []
  40. for node in body:
  41. result.extend(self.visit_list(node))
  42. return result
  43. def fold(self, node):
  44. """Do constant folding."""
  45. node = self.generic_visit(node)
  46. try:
  47. return nodes.Const.from_untrusted(node.as_const(),
  48. lineno=node.lineno,
  49. environment=self.environment)
  50. except nodes.Impossible:
  51. return node
  52. visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
  53. visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
  54. visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
  55. visit_Filter = visit_Test = visit_CondExpr = fold
  56. del fold