-
-
Notifications
You must be signed in to change notification settings - Fork 78
/
meta.rs
293 lines (277 loc) · 10.1 KB
/
meta.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
//! Provides meta utilities for working with templates.
//!
//! The meta API has some uses for limited introspection that can help optimize
//! how templates are interacted with. For instance it can be used to detect
//! which templates are reachable from a set of known templates so that the
//! environment can be appropriately initialized. Likewise it can be used to
//! identify variables that need to be supplied into the context based on what
//! templates are using.
use std::collections::HashSet;
use crate::ast;
use crate::error::Error;
use crate::parser::parse;
#[cfg(test)]
use similar_asserts::assert_eq;
/// Given a template source returns a set of undeclared variables.
///
/// Returns a set of all variables in the template that will be looked up from
/// the context at runtime. Because at compile time it’s not known which
/// variables will be used depending on the path the execution takes at runtime,
/// all variables are returned. Only variables that are known to be declared
/// in the template itself are not returned.
///
/// # Example
///
/// ```rust
/// # use minijinja::meta::find_undeclared_variables;
/// let names = find_undeclared_variables(r#"
/// {% for item in seq %}{{ loop.index}}: {{ item }} ({{ hint }}){% endfor %}
/// "#).unwrap();
/// assert!(names.contains("hint"));
/// assert!(!names.contains("item"));
/// assert!(!names.contains("loop"));
/// assert!(names.contains("seq"));
/// ```
pub fn find_undeclared_variables(source: &str) -> Result<HashSet<String>, Error> {
struct State {
out: HashSet<String>,
assigned: Vec<HashSet<String>>,
}
impl State {
fn is_assigned(&self, name: &str) -> bool {
self.assigned.iter().any(|x| x.contains(name))
}
fn assign(&mut self, name: &str) {
self.assigned.last_mut().unwrap().insert(name.to_string());
}
fn push(&mut self) {
self.assigned.push(Default::default());
}
fn pop(&mut self) {
self.assigned.pop();
}
}
fn visit_expr(expr: &ast::Expr, state: &mut State) {
match expr {
ast::Expr::Var(var) => {
if !state.is_assigned(var.id) {
state.out.insert(var.id.to_string());
state.assign(var.id);
}
}
ast::Expr::Const(_) => {}
ast::Expr::UnaryOp(expr) => visit_expr(&expr.expr, state),
ast::Expr::BinOp(expr) => {
visit_expr(&expr.left, state);
visit_expr(&expr.right, state);
}
ast::Expr::IfExpr(expr) => {
visit_expr(&expr.test_expr, state);
visit_expr(&expr.true_expr, state);
if let Some(ref false_expr) = expr.false_expr {
visit_expr(false_expr, state);
}
}
ast::Expr::Filter(expr) => {
if let Some(ref expr) = expr.expr {
visit_expr(expr, state);
}
for arg in &expr.args {
visit_expr(arg, state);
}
}
ast::Expr::Test(expr) => {
visit_expr(&expr.expr, state);
for arg in &expr.args {
visit_expr(arg, state);
}
}
ast::Expr::GetAttr(expr) => {
visit_expr(&expr.expr, state);
}
ast::Expr::GetItem(expr) => {
visit_expr(&expr.expr, state);
visit_expr(&expr.subscript_expr, state);
}
ast::Expr::Call(expr) => {
visit_expr(&expr.expr, state);
for arg in &expr.args {
visit_expr(arg, state);
}
}
ast::Expr::List(expr) => {
for value in &expr.items {
visit_expr(value, state);
}
}
ast::Expr::Map(expr) => {
for (key, value) in expr.keys.iter().zip(expr.values.iter()) {
visit_expr(key, state);
visit_expr(value, state);
}
}
}
}
fn assign_nested(expr: &ast::Expr, state: &mut State) {
match expr {
ast::Expr::Var(var) => {
state.assign(var.id);
}
ast::Expr::List(list) => {
for expr in &list.items {
assign_nested(expr, state);
}
}
_ => {}
}
}
fn walk(node: &ast::Stmt, state: &mut State) {
match node {
ast::Stmt::Template(stmt) => {
state.assign("self");
stmt.children.iter().for_each(|x| walk(x, state));
}
ast::Stmt::EmitExpr(expr) => visit_expr(&expr.expr, state),
ast::Stmt::EmitRaw(_) | ast::Stmt::Extends(_) | ast::Stmt::Include(_) => {}
ast::Stmt::ForLoop(stmt) => {
state.push();
state.assign("loop");
visit_expr(&stmt.iter, state);
assign_nested(&stmt.target, state);
if let Some(ref filter_expr) = stmt.filter_expr {
visit_expr(filter_expr, state);
}
stmt.body.iter().for_each(|x| walk(x, state));
state.pop();
state.push();
stmt.else_body.iter().for_each(|x| walk(x, state));
state.pop();
}
ast::Stmt::IfCond(stmt) => {
visit_expr(&stmt.expr, state);
state.push();
stmt.true_body.iter().for_each(|x| walk(x, state));
state.pop();
state.push();
stmt.false_body.iter().for_each(|x| walk(x, state));
state.pop();
}
ast::Stmt::WithBlock(stmt) => {
state.push();
for (target, expr) in &stmt.assignments {
assign_nested(target, state);
visit_expr(expr, state);
}
stmt.body.iter().for_each(|x| walk(x, state));
state.pop();
}
ast::Stmt::Set(stmt) => {
assign_nested(&stmt.target, state);
visit_expr(&stmt.expr, state);
}
ast::Stmt::Block(stmt) => {
state.push();
state.assign("super");
stmt.body.iter().for_each(|x| walk(x, state));
state.pop();
}
ast::Stmt::AutoEscape(stmt) => {
state.push();
stmt.body.iter().for_each(|x| walk(x, state));
state.pop();
}
ast::Stmt::FilterBlock(stmt) => {
state.push();
stmt.body.iter().for_each(|x| walk(x, state));
state.pop();
}
}
}
let ast = parse(source, "<string>")?;
let mut state = State {
out: HashSet::new(),
assigned: vec![Default::default()],
};
walk(&ast, &mut state);
Ok(state.out)
}
/// Given a template source returns a set of referenced templates by name.
///
/// This parses the given template and returns a hash set of all referenced
/// templates. These are templates referenced by `{% extends %}` and
/// `{% include %}`. Note that since both of those blocks support variables
/// this function cannot always return all templates. If a variable or
/// complex expression is used to reference a template then the string
/// `"*"` is also included.
///
/// # Example
///
/// ```rust
/// # use minijinja::meta::find_referenced_templates;
/// let names = find_referenced_templates(r#"
/// {% extends "layout.html" %}{% include helper %}
/// "#).unwrap();
/// assert!(names.contains("layout.html"));
/// assert!(names.contains("*"));
/// ```
pub fn find_referenced_templates(source: &str) -> Result<HashSet<String>, Error> {
fn record_reference(expr: &ast::Expr, out: &mut HashSet<String>) {
if let ast::Expr::Const(val) = expr {
if let Some(s) = val.value.as_str() {
out.insert(s.to_string());
return;
}
}
out.insert("*".into());
}
fn walk(node: &ast::Stmt, out: &mut HashSet<String>) {
match node {
ast::Stmt::Template(stmt) => stmt.children.iter().for_each(|x| walk(x, out)),
ast::Stmt::EmitExpr(_) | ast::Stmt::EmitRaw(_) | ast::Stmt::Set(_) => {}
ast::Stmt::ForLoop(stmt) => stmt
.body
.iter()
.chain(stmt.else_body.iter())
.for_each(|x| walk(x, out)),
ast::Stmt::IfCond(stmt) => stmt
.true_body
.iter()
.chain(stmt.false_body.iter())
.for_each(|x| walk(x, out)),
ast::Stmt::WithBlock(stmt) => stmt.body.iter().for_each(|x| walk(x, out)),
ast::Stmt::Block(stmt) => stmt.body.iter().for_each(|x| walk(x, out)),
ast::Stmt::Extends(stmt) => record_reference(&stmt.name, out),
ast::Stmt::Include(stmt) => record_reference(&stmt.name, out),
ast::Stmt::AutoEscape(stmt) => stmt.body.iter().for_each(|x| walk(x, out)),
ast::Stmt::FilterBlock(stmt) => stmt.body.iter().for_each(|x| walk(x, out)),
}
}
let ast = parse(source, "<string>")?;
let mut rv = HashSet::new();
walk(&ast, &mut rv);
Ok(rv)
}
#[test]
fn test_find_undeclared_variables() {
let names = find_undeclared_variables(
r#"{% with foo = 42 %}{{ foo }} {{ bar }} {{ bar(baz) }}{% endwith %}"#,
)
.unwrap();
assert_eq!(names, {
let mut s = HashSet::new();
s.insert("bar".to_string());
s.insert("baz".to_string());
s
});
}
#[test]
fn test_find_referenced_templates() {
let names =
find_referenced_templates(r#"{% extends "layout.html" %}{% include helper %}"#).unwrap();
assert_eq!(names, {
let mut s = HashSet::new();
s.insert("*".to_string());
s.insert("layout.html".to_string());
s
});
}