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) 2010 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
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 pull_locals(self, frame):
29        """Remember all undeclared identifiers."""
30        self.undeclared_identifiers.update(frame.identifiers.undeclared)
31
32
33def find_undeclared_variables(ast):
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)
43    set(['bar'])
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)
53    codegen.visit(ast)
54    return codegen.undeclared_identifiers
55
56
57def find_referenced_templates(ast):
58    """Finds all the referenced templates from the AST.  This will return an
59    iterator over all the hardcoded template extensions, inclusions and
60    imports.  If dynamic inheritance or inclusion is used, `None` will be
61    yielded.
62
63    >>> from jinja2 import Environment, meta
64    >>> env = Environment()
65    >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
66    >>> list(meta.find_referenced_templates(ast))
67    ['layout.html', None]
68
69    This function is useful for dependency tracking.  For example if you want
70    to rebuild parts of the website after a layout template has changed.
71    """
72    for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
73                              nodes.Include)):
74        if not isinstance(node.template, nodes.Const):
75            # a tuple with some non consts in there
76            if isinstance(node.template, (nodes.Tuple, nodes.List)):
77                for template_name in node.template.items:
78                    # something const, only yield the strings and ignore
79                    # non-string consts that really just make no sense
80                    if isinstance(template_name, nodes.Const):
81                        if isinstance(template_name.value, string_types):
82                            yield template_name.value
83                    # something dynamic in there
84                    else:
85                        yield None
86            # something dynamic we don't know about here
87            else:
88                yield None
89            continue
90        # constant is a basestring, direct template name
91        if isinstance(node.template.value, string_types):
92            yield node.template.value
93        # a tuple or list (latter *should* not happen) made of consts,
94        # yield the consts that are strings.  We could warn here for
95        # non string values
96        elif isinstance(node, nodes.Include) and \
97             isinstance(node.template.value, (tuple, list)):
98            for template_name in node.template.value:
99                if isinstance(template_name, string_types):
100                    yield template_name
101        # something else we don't care about, we could warn here
102        else:
103            yield None
104