]>
jfr.im git - dlqueue.git/blob - venv/lib/python3.11/site-packages/jinja2/meta.py
1 """Functions that expose information about templates that might be
2 interesting for introspection.
7 from .compiler
import CodeGenerator
8 from .compiler
import Frame
11 from .environment
import Environment
14 class TrackingCodeGenerator(CodeGenerator
):
15 """We abuse the code generator for introspection."""
17 def __init__(self
, environment
: "Environment") -> None:
18 super().__init
__(environment
, "<introspection>", "<introspection>")
19 self
.undeclared_identifiers
: t
.Set
[str] = set()
21 def write(self
, x
: str) -> None:
24 def enter_frame(self
, frame
: Frame
) -> None:
25 """Remember all undeclared identifiers."""
26 super().enter_frame(frame
)
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
)
33 def 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.
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'}
45 .. admonition:: Implementation
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.
52 codegen
= TrackingCodeGenerator(ast
.environment
) # type: ignore
54 return codegen
.undeclared_identifiers
57 _ref_types
= (nodes
.Extends
, nodes
.FromImport
, nodes
.Import
, nodes
.Include
)
58 _RefType
= t
.Union
[nodes
.Extends
, nodes
.FromImport
, nodes
.Import
, nodes
.Include
]
61 def 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
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))
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.
78 for node
in ast
.find_all(_ref_types
):
79 template
: nodes
.Expr
= node
.template
# type: ignore
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
93 # something dynamic we don't know about here
97 # constant is a basestring, direct template name
98 if isinstance(template
.value
, str):
100 # a tuple or list (latter *should* not happen) made of consts,
101 # yield the consts that are strings. We could warn here for
103 elif isinstance(node
, nodes
.Include
) and isinstance(
104 template
.value
, (tuple, list)
106 for template_name
in template
.value
:
107 if isinstance(template_name
, str):
109 # something else we don't care about, we could warn here