meta.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # -*- coding: utf-8 -*-
  2. """Functions that expose information about templates that might be
  3. interesting for introspection.
  4. """
  5. from . import nodes
  6. from ._compat import iteritems
  7. from ._compat import string_types
  8. from .compiler import CodeGenerator
  9. class TrackingCodeGenerator(CodeGenerator):
  10. """We abuse the code generator for introspection."""
  11. def __init__(self, environment):
  12. CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")
  13. self.undeclared_identifiers = set()
  14. def write(self, x):
  15. """Don't write."""
  16. def enter_frame(self, frame):
  17. """Remember all undeclared identifiers."""
  18. CodeGenerator.enter_frame(self, frame)
  19. for _, (action, param) in iteritems(frame.symbols.loads):
  20. if action == "resolve" and param not in self.environment.globals:
  21. self.undeclared_identifiers.add(param)
  22. def find_undeclared_variables(ast):
  23. """Returns a set of all variables in the AST that will be looked up from
  24. the context at runtime. Because at compile time it's not known which
  25. variables will be used depending on the path the execution takes at
  26. runtime, all variables are returned.
  27. >>> from jinja2 import Environment, meta
  28. >>> env = Environment()
  29. >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
  30. >>> meta.find_undeclared_variables(ast) == set(['bar'])
  31. True
  32. .. admonition:: Implementation
  33. Internally the code generator is used for finding undeclared variables.
  34. This is good to know because the code generator might raise a
  35. :exc:`TemplateAssertionError` during compilation and as a matter of
  36. fact this function can currently raise that exception as well.
  37. """
  38. codegen = TrackingCodeGenerator(ast.environment)
  39. codegen.visit(ast)
  40. return codegen.undeclared_identifiers
  41. def find_referenced_templates(ast):
  42. """Finds all the referenced templates from the AST. This will return an
  43. iterator over all the hardcoded template extensions, inclusions and
  44. imports. If dynamic inheritance or inclusion is used, `None` will be
  45. yielded.
  46. >>> from jinja2 import Environment, meta
  47. >>> env = Environment()
  48. >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
  49. >>> list(meta.find_referenced_templates(ast))
  50. ['layout.html', None]
  51. This function is useful for dependency tracking. For example if you want
  52. to rebuild parts of the website after a layout template has changed.
  53. """
  54. for node in ast.find_all(
  55. (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)
  56. ):
  57. if not isinstance(node.template, nodes.Const):
  58. # a tuple with some non consts in there
  59. if isinstance(node.template, (nodes.Tuple, nodes.List)):
  60. for template_name in node.template.items:
  61. # something const, only yield the strings and ignore
  62. # non-string consts that really just make no sense
  63. if isinstance(template_name, nodes.Const):
  64. if isinstance(template_name.value, string_types):
  65. yield template_name.value
  66. # something dynamic in there
  67. else:
  68. yield None
  69. # something dynamic we don't know about here
  70. else:
  71. yield None
  72. continue
  73. # constant is a basestring, direct template name
  74. if isinstance(node.template.value, string_types):
  75. yield node.template.value
  76. # a tuple or list (latter *should* not happen) made of consts,
  77. # yield the consts that are strings. We could warn here for
  78. # non string values
  79. elif isinstance(node, nodes.Include) and isinstance(
  80. node.template.value, (tuple, list)
  81. ):
  82. for template_name in node.template.value:
  83. if isinstance(template_name, string_types):
  84. yield template_name
  85. # something else we don't care about, we could warn here
  86. else:
  87. yield None