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