1use crate::generate::{GenerateError, GeneratedFile};
12use crate::rust::naming;
13use include_dir::{Dir, include_dir};
14use minijinja::{Environment, Value};
15use serde::Serialize;
16use std::collections::{BTreeMap, BTreeSet, VecDeque};
17use std::path::Path;
18
19static TEMPLATES: Dir = include_dir!("$CARGO_MANIFEST_DIR/templates");
20
21pub const TEMPLATE_API: u32 = 1;
24
25pub const TEMPLATE_MANIFEST: &str = "roas-templates.toml";
27
28const BUILTIN: &str = "builtin/";
29
30#[derive(serde::Deserialize)]
31#[serde(deny_unknown_fields)]
32struct Manifest {
33 template_api: u32,
34}
35
36fn error(message: impl Into<String>) -> GenerateError {
37 GenerateError::Template(message.into())
38}
39
40fn embedded() -> Result<BTreeMap<String, String>, GenerateError> {
41 let mut files = Vec::new();
42 collect(&TEMPLATES, &mut files);
43 let mut out = BTreeMap::new();
44 for file in files {
45 let path = file.path().to_string_lossy().replace('\\', "/");
46 let source = file
47 .contents_utf8()
48 .ok_or_else(|| error(format!("{path} is not UTF-8")))?;
49 out.insert(path, source.to_owned());
50 }
51 Ok(out)
52}
53
54fn collect<'d>(dir: &'d Dir<'d>, out: &mut Vec<&'d include_dir::File<'d>>) {
55 for file in dir.files() {
56 if file.path().extension().is_some_and(|e| e == "jinja") {
57 out.push(file);
58 }
59 }
60 for sub in dir.dirs() {
61 collect(sub, out);
62 }
63}
64
65fn user_templates(dir: &Path) -> Result<BTreeMap<String, String>, GenerateError> {
68 let manifest_path = dir.join(TEMPLATE_MANIFEST);
69 let manifest = std::fs::read_to_string(&manifest_path).map_err(|e| {
70 error(format!(
71 "template directory {} needs a {TEMPLATE_MANIFEST} declaring `template_api = {TEMPLATE_API}`: {e}",
72 dir.display()
73 ))
74 })?;
75 let manifest: Manifest = toml::from_str(&manifest)
76 .map_err(|e| error(format!("{}: {e}", manifest_path.display())))?;
77 if manifest.template_api != TEMPLATE_API {
78 return Err(error(format!(
79 "{} declares `template_api = {}`, but this generator renders version {TEMPLATE_API}",
80 manifest_path.display(),
81 manifest.template_api
82 )));
83 }
84 let mut out = BTreeMap::new();
85 walk(dir, "", &mut out)?;
86 Ok(out)
87}
88
89fn walk(dir: &Path, prefix: &str, out: &mut BTreeMap<String, String>) -> Result<(), GenerateError> {
90 let entries = std::fs::read_dir(dir).map_err(|e| {
91 error(format!(
92 "cannot read template directory {}: {e}",
93 dir.display()
94 ))
95 })?;
96 let mut entries: Vec<_> = entries.collect::<Result<_, _>>().map_err(|e| {
97 error(format!(
98 "cannot read template directory {}: {e}",
99 dir.display()
100 ))
101 })?;
102 entries.sort_by_key(std::fs::DirEntry::file_name);
103 for entry in entries {
104 let name = entry.file_name();
105 if name.as_encoded_bytes().first() == Some(&b'.') {
108 continue;
109 }
110 let Some(name) = name.to_str() else {
111 return Err(error(format!(
112 "{} is not a UTF-8 name",
113 entry.path().display()
114 )));
115 };
116 let path = format!("{prefix}{name}");
117 let link = entry
118 .file_type()
119 .map_err(|e| error(format!("cannot read {}: {e}", entry.path().display())))?
120 .is_symlink();
121 let kind = match std::fs::metadata(entry.path()) {
122 Ok(kind) => kind,
123 Err(_) if link => continue,
125 Err(e) => {
126 return Err(error(format!(
127 "cannot read {}: {e}",
128 entry.path().display()
129 )));
130 }
131 };
132 if kind.is_dir() {
133 if link {
135 continue;
136 }
137 if path == "builtin" {
138 return Err(error(format!(
139 "{} is reserved: `builtin/` always names the embedded defaults",
140 entry.path().display()
141 )));
142 }
143 walk(&entry.path(), &format!("{path}/"), out)?;
144 } else if name.ends_with(".jinja") {
145 let source = std::fs::read_to_string(entry.path())
146 .map_err(|e| error(format!("cannot read {}: {e}", entry.path().display())))?;
147 out.insert(path, source);
148 }
149 }
150 Ok(())
151}
152
153#[derive(Debug, Default, PartialEq)]
156struct Shape {
157 extends: Option<String>,
159 top: Vec<String>,
162 all: Vec<String>,
164 includes: Vec<Include>,
166}
167
168#[derive(Debug, PartialEq)]
171struct Include {
172 name: Option<String>,
173 loops: Vec<String>,
174}
175
176fn shape(name: &str, source: &str) -> Result<Shape, String> {
177 use minijinja::machinery::{self, WhitespaceConfig, ast};
178 let parsed = machinery::parse(
179 source,
180 name,
181 Default::default(),
183 WhitespaceConfig::default(),
184 )
185 .map_err(|e| format!("{e:#}"))?;
186 struct Walk<'a, 's> {
187 source: &'s str,
188 shape: Shape,
189 parents: Vec<&'a ast::Expr<'a>>,
190 loops: Vec<String>,
191 }
192 fn string(expr: &ast::Expr<'_>) -> Option<String> {
193 match expr {
194 ast::Expr::Const(c) => c.value.as_str().map(str::to_owned),
195 _ => None,
196 }
197 }
198 fn walk<'a>(statements: &'a [ast::Stmt<'a>], depth: usize, w: &mut Walk<'a, '_>) {
199 for statement in statements {
200 match statement {
201 ast::Stmt::Template(t) => walk(&t.children, depth, w),
202 ast::Stmt::Extends(e) => w.parents.push(&e.name),
203 ast::Stmt::Block(b) => {
204 if depth == 0 {
205 w.shape.top.push(b.name.to_owned());
206 }
207 w.shape.all.push(b.name.to_owned());
208 walk(&b.body, depth + 1, w);
209 }
210 ast::Stmt::Include(i) => w.shape.includes.push(Include {
211 name: string(&i.name),
212 loops: w.loops.clone(),
213 }),
214 ast::Stmt::ForLoop(f) => {
215 let end = f.filter_expr.as_ref().unwrap_or(&f.iter).span().end_offset;
216 let header = w
217 .source
218 .get(f.target.span().start_offset as usize..end as usize)
219 .unwrap_or_default();
220 w.loops
221 .push(header.split_whitespace().collect::<Vec<_>>().join(" "));
222 walk(&f.body, depth, w);
223 w.loops.pop();
224 walk(&f.else_body, depth, w);
225 }
226 ast::Stmt::IfCond(i) => {
227 walk(&i.true_body, depth, w);
228 walk(&i.false_body, depth, w);
229 }
230 ast::Stmt::WithBlock(b) => walk(&b.body, depth, w),
231 ast::Stmt::SetBlock(s) => walk(&s.body, depth, w),
232 ast::Stmt::AutoEscape(a) => walk(&a.body, depth, w),
233 ast::Stmt::FilterBlock(f) => walk(&f.body, depth, w),
234 ast::Stmt::Macro(m) => walk(&m.body, depth, w),
235 ast::Stmt::CallBlock(c) => walk(&c.macro_decl.body, depth, w),
236 _ => {}
237 }
238 }
239 }
240 let mut w = Walk {
241 source,
242 shape: Shape::default(),
243 parents: Vec::new(),
244 loops: Vec::new(),
245 };
246 walk(std::slice::from_ref(&parsed), 0, &mut w);
247 let Walk {
248 mut shape, parents, ..
249 } = w;
250 match parents.as_slice() {
251 [] => {}
252 [expr] if string(expr).is_some() => shape.extends = string(expr),
253 [_, _, ..] => {
255 return Err("has more than one `extends`; one parent, named once, is what the block check can follow".into());
256 }
257 [_] => {
258 return Err(
259 "`extends` must name its template as one string literal, so its blocks can be checked"
260 .into(),
261 );
262 }
263 }
264 Ok(shape)
265}
266
267fn check_blocks(
271 user: &BTreeMap<String, String>,
272 defaults: &BTreeMap<String, String>,
273) -> Result<(), GenerateError> {
274 let resolve = |name: &str| -> Option<&String> {
275 match name.strip_prefix(BUILTIN) {
276 Some(rest) => defaults.get(rest),
277 None => user.get(name).or_else(|| defaults.get(name)),
278 }
279 };
280 for (name, source) in user {
281 let child = shape(name, source).map_err(|e| error(format!("{name}: {e}")))?;
282 let Some(mut parent) = child.extends else {
283 continue;
284 };
285 let mut declared = BTreeSet::new();
286 let mut seen = BTreeSet::new();
287 loop {
288 if !seen.insert(parent.clone()) {
289 return Err(error(format!(
290 "{name}: `extends` goes round in a circle through {parent}"
291 )));
292 }
293 let Some(parent_source) = resolve(&parent) else {
294 return Err(error(format!(
295 "{name} extends {parent:?}, which does not exist"
296 )));
297 };
298 let parent_shape =
299 shape(&parent, parent_source).map_err(|e| error(format!("{parent}: {e}")))?;
300 declared.extend(parent_shape.all);
301 match parent_shape.extends {
302 Some(next) => parent = next,
303 None => break,
304 }
305 }
306 for block in child.top {
307 if !declared.contains(&block) {
308 return Err(error(format!(
309 "{name} fills block `{block}`, which no template it extends declares, so it would never apply; it declares {}",
310 declared
311 .iter()
312 .map(String::as_str)
313 .collect::<Vec<_>>()
314 .join(", ")
315 )));
316 }
317 }
318 }
319 Ok(())
320}
321
322pub(crate) fn environment(
325 template_dir: Option<&Path>,
326) -> Result<Environment<'static>, GenerateError> {
327 let defaults = embedded()?;
328 let user = match template_dir {
329 Some(dir) => user_templates(dir)?,
330 None => BTreeMap::new(),
331 };
332 check_blocks(&user, &defaults)?;
333 let mut env = Environment::new();
334 env.set_keep_trailing_newline(true);
335 let add = |env: &mut Environment<'static>, name: String, source: String| {
336 env.add_template_owned(name.clone(), source)
337 .map_err(|e| error(format!("{name}: {e:#}")))
338 };
339 for (path, source) in &defaults {
340 add(&mut env, format!("{BUILTIN}{path}"), source.clone())?;
341 if !user.contains_key(path) {
342 add(&mut env, path.clone(), source.clone())?;
343 }
344 }
345 for (path, source) in user {
346 add(&mut env, path, source)?;
347 }
348 env.add_filter("pascal", |s: String| naming::pascal(&[s]));
349 env.add_filter("snake", |s: String| naming::snake(&[s]));
350 env.add_filter("camel", |s: String| naming::camel(&[s]));
351 env.add_filter("kebab", |s: String| naming::kebab(&[s]));
352 env.add_filter("screaming_snake", |s: String| naming::screaming_snake(&[s]));
353 env.add_filter("doc", |s: String, prefix: Option<String>| {
354 let prefix = prefix.unwrap_or_else(|| "/// ".to_owned());
355 s.lines()
356 .map(|l| format!("{prefix}{}", l.trim_end()))
357 .collect::<Vec<_>>()
358 .join("\n")
359 });
360 Ok(env)
361}
362
363pub(crate) fn scaffold(
371 entries: &[(&str, String)],
372 unused: &[&str],
373) -> Result<Vec<GeneratedFile>, GenerateError> {
374 scaffold_of(&embedded()?, entries, unused)
375}
376
377fn scaffold_of(
378 defaults: &BTreeMap<String, String>,
379 entries: &[(&str, String)],
380 unused: &[&str],
381) -> Result<Vec<GeneratedFile>, GenerateError> {
382 let mut roles: BTreeMap<String, Vec<String>> = BTreeMap::new();
383 let mut shapes = BTreeMap::new();
384 let mut queue = VecDeque::new();
385 for (name, what) in entries {
386 roles
387 .entry((*name).to_owned())
388 .or_default()
389 .push(format!("Renders {what}."));
390 queue.push_back((*name).to_owned());
391 }
392 while let Some(name) = queue.pop_front() {
393 if shapes.contains_key(&name) {
394 continue;
395 }
396 let source = defaults
397 .get(&name)
398 .ok_or_else(|| error(format!("there is no default template {name}")))?;
399 let parsed = shape(&name, source).map_err(|e| error(format!("{name}: {e}")))?;
400 for include in &parsed.includes {
401 let Some(included) = &include.name else {
402 return Err(error(format!(
403 "{name} includes a template named by an expression, which the scaffold cannot follow"
404 )));
405 };
406 if unused.contains(&included.as_str()) {
407 continue;
408 }
409 let role = match include.loops.as_slice() {
410 [] => format!("Included by {name}."),
411 loops => format!(
412 "Included by {name} inside `for {}`.",
413 loops.join("` and `for ")
414 ),
415 };
416 let seen = roles.entry(included.clone()).or_default();
417 if !seen.contains(&role) {
418 seen.push(role);
419 }
420 queue.push_back(included.clone());
421 }
422 shapes.insert(name, parsed);
423 }
424 let mut files = vec![GeneratedFile::new(
425 TEMPLATE_MANIFEST,
426 format!("template_api = {TEMPLATE_API}\n"),
427 )];
428 for (name, roles) in roles {
429 let shape = &shapes[&name];
430 let mut text = String::from("{#- ");
431 text.push_str(&name);
432 for role in &roles {
433 text.push_str("\n ");
434 text.push_str(role);
435 }
436 text.push_str(if roles.iter().any(|r| r.starts_with("Included")) {
437 "\n It sees the context where it is included, loop variables too."
438 } else {
439 "\n `--print-context` prints the full context."
440 });
441 let blocks = &shape.all;
443 text.push_str(if blocks.is_empty() {
444 "\n It declares no blocks: to change it, replace the `extends` line below\n with the whole template; anything written beside it is dropped."
445 } else {
446 "\n Each block renders the default through `super()`: change the ones\n you need, and delete the rest."
447 });
448 let mut text = text.replace("#}", "# }");
450 text.push_str(" #}\n{%- extends \"");
451 text.push_str(BUILTIN);
452 text.push_str(&name);
453 text.push_str("\" %}\n");
454 for block in blocks {
455 text.push_str("{%- block ");
456 text.push_str(block);
457 text.push_str(" %}{{ super() }}{% endblock %}\n");
458 }
459 files.push(GeneratedFile::new(name, text));
460 }
461 Ok(files)
462}
463
464pub(crate) const MARKER: &str = "// Code generated by roas. DO NOT EDIT.";
468
469pub(crate) struct Renderer {
471 env: Environment<'static>,
472}
473
474impl Renderer {
475 pub(crate) fn new(template_dir: Option<&Path>) -> Result<Renderer, GenerateError> {
476 Ok(Renderer {
477 env: environment(template_dir)?,
478 })
479 }
480
481 pub(crate) fn render(
484 &self,
485 entry: &str,
486 context: &impl Serialize,
487 separator: &str,
488 ) -> Result<String, GenerateError> {
489 let template = self
490 .env
491 .get_template(entry)
492 .map_err(|e| error(format!("{e:#}")))?;
493 let rendered = template
494 .render(Value::from_serialize(context))
495 .map_err(|e| error(format!("{e:#}")))?;
496 Ok(format!("{MARKER}\n{separator}{rendered}"))
497 }
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503
504 fn read(source: &str) -> Result<Shape, String> {
505 shape("t", source)
506 }
507
508 #[test]
509 fn templates_are_read_as_minijinja_reads_them() {
510 let s = read("{%- extends 'builtin/rust/struct.rs.jinja' %}{% block derives -%}x{% endblock %}{%+ block attrs %}{% endblock attrs %}").unwrap();
511 assert_eq!(s.extends.as_deref(), Some("builtin/rust/struct.rs.jinja"));
512 assert_eq!(s.top, ["derives", "attrs"]);
513 assert_eq!(read("{% include \"x\" %}").unwrap().extends, None);
514 assert!(read("{% extends p %}").is_err());
515 assert!(read("{% extends \"a\" if c else \"b\" %}").is_err());
516 assert!(
517 read("{% if c %}{% extends \"a\" %}{% else %}{% extends \"b\" %}{% endif %}").is_err()
518 );
519 let nested = read(
520 "{% block a %}{% block b %}{% endblock %}{% endblock a %}{% block c %}{% endblock %}",
521 )
522 .unwrap();
523 assert_eq!(nested.top, ["a", "c"]);
524 assert_eq!(nested.all, ["a", "b", "c"]);
525 let s = read("{# {% extends 'a' %}{% block old %} #}{% extends \"b\" %}{% raw %}{% it's %}{%~ endraw %}{% block raw %}{% endraw %}{{ {'a': {}} ~ '{#' }}{% block kept %}{% endblock %}{% set x = '%}{% block fake %}' %}").unwrap();
527 assert_eq!(s.extends.as_deref(), Some("b"));
528 assert_eq!(s.top, ["kept"]);
529 assert_eq!(
530 read("{%extends\"c\"%}").unwrap().extends.as_deref(),
531 Some("c")
532 );
533 assert_eq!(
534 read(r#"{% extends "builtin\/rust\/x.jinja" %}"#)
535 .unwrap()
536 .extends
537 .as_deref(),
538 Some("builtin/rust/x.jinja")
539 );
540 }
541
542 #[test]
543 fn includes_are_read_with_the_loops_around_them() {
544 let s = read("{% for t in types %}{% for f in t.fields\n if not f.skip %}{% include 'f' %}{% endfor %}{% else %}{% include \"e\" %}{% endfor %}{% include name %}").unwrap();
545 assert_eq!(
546 s.includes,
547 [
548 Include {
549 name: Some("f".into()),
550 loops: vec!["t in types".into(), "f in t.fields if not f.skip".into()],
551 },
552 Include {
553 name: Some("e".into()),
554 loops: Vec::new(),
555 },
556 Include {
557 name: None,
558 loops: Vec::new(),
559 },
560 ]
561 );
562 }
563
564 #[test]
565 fn the_scaffold_follows_includes_and_refuses_what_it_cannot() {
566 let defaults: BTreeMap<String, String> = [
567 ("a", "{% for x in '#}' %}{% include 'b' %}{% endfor %}{% include 'b' %}{% include 'b' %}"),
568 ("b", "{% block one %}{% block two %}{% endblock %}{% endblock %}"),
569 ("c", "{% include name %}"),
570 ("d", "{% include 'missing' %}"),
571 ("e", "{% block %}"),
572 ]
573 .into_iter()
574 .map(|(k, v)| (k.to_owned(), v.to_owned()))
575 .collect();
576 let files = scaffold_of(&defaults, &[("a", "`a.rs`".into())], &[]).unwrap();
577 let names: Vec<_> = files.iter().map(|f| f.path.to_str().unwrap()).collect();
578 assert_eq!(names, [TEMPLATE_MANIFEST, "a", "b"]);
579 assert!(
580 files[1].contents.contains("Renders `a.rs`."),
581 "{}",
582 files[1].contents
583 );
584 assert!(
585 files[1].contents.contains("declares no blocks"),
586 "{}",
587 files[1].contents
588 );
589 let b = &files[2].contents;
590 assert!(b.contains("inside `for x in '# }'`."), "{b}");
592 assert_eq!(b.matches("Included by a.").count(), 1, "{b}");
593 assert!(b.ends_with("{%- extends \"builtin/b\" %}\n{%- block one %}{{ super() }}{% endblock %}\n{%- block two %}{{ super() }}{% endblock %}\n"), "{b}");
594 for file in &files[1..] {
596 shape("t", &file.contents).unwrap();
597 }
598 for (entry, wanted) in [
599 ("c", "named by an expression"),
600 ("d", "no default template missing"),
601 ("e", "e:"),
602 ("nope", "no default template nope"),
603 ] {
604 let error = scaffold_of(&defaults, &[(entry, String::new())], &[]).unwrap_err();
605 assert!(error.to_string().contains(wanted), "{error}");
606 }
607 }
608
609 #[test]
610 fn every_default_template_parses_and_declares_its_blocks() {
611 let env = environment(None).unwrap();
612 for (path, source) in embedded().unwrap() {
613 env.get_template(&path).unwrap();
614 env.get_template(&format!("builtin/{path}")).unwrap();
615 assert_eq!(
616 shape(&path, &source).unwrap().extends,
617 None,
618 "{path} extends nothing"
619 );
620 }
621 }
622}