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