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