meta.py 4.3 KB

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