Skip to main content

decl_lang/
render.rs

1//! The renderer (docs/tooling/05_render.md): the form a module declares
2//! for an output with `@render` — a format and a layout, a template, a
3//! destination, a fan-out — read from the annotation (§3), the structured
4//! text of a document in that form (§4), and the templates (§5) and the
5//! fan-out (§6) that turn one evaluated root into text or files. The
6//! command line, the REPL, the library, and the editor preview all emit
7//! through here, so that the three implementations print the same bytes.
8//! A port of the reference's render.ts.
9use crate::ast::{Decl, Expr};
10use crate::semantics::{Locals, Num, Value, R};
11use crate::yaml::{to_json, to_yaml};
12use regex::Regex;
13use std::sync::LazyLock;
14
15/// a template's delimiters (§5.2): each an opener and a closer
16#[derive(Debug, Clone, PartialEq)]
17pub struct Delimiters {
18    /// `{= =}`
19    pub value: (String, String),
20    /// `{% %}`
21    pub statement: (String, String),
22    /// `{# #}`
23    pub comment: (String, String),
24}
25impl Default for Delimiters {
26    fn default() -> Self {
27        Delimiters {
28            value: ("{=".into(), "=}".into()),
29            statement: ("{%".into(), "%}".into()),
30            comment: ("{#".into(), "#}".into()),
31        }
32    }
33}
34
35/// the declared form of a root (§3): what `@render` says, every key optional
36#[derive(Debug, Clone, PartialEq, Default)]
37pub struct Form {
38    /// `"yaml"`, else JSON
39    pub yaml: bool,
40    /// the layout (§4)
41    pub indent: Option<usize>,
42    /// a template file (§5), relative to the module's directory
43    pub template: Option<String>,
44    /// the default destination (§3.2)
45    pub file: Option<String>,
46    /// fan-out (§6)
47    pub each: Option<String>,
48    /// the template's delimiters
49    pub delimiters: Option<Delimiters>,
50}
51
52const FORM_KEYS: [&str; 6] = ["format", "indent", "template", "file", "each", "delimiters"];
53
54// a literal value in an annotation argument: a string, an integer, a
55// bool, or null (a negative integer is a unary minus over a literal)
56fn literal(e: &Expr) -> Option<Value> {
57    match e {
58        Expr::Lit(v) => Some(v.clone()),
59        Expr::Un { op, x } if op == "-" => match &**x {
60            Expr::Lit(Value::Int(i)) => Some(Value::Int(-i.clone())),
61            _ => None,
62        },
63        _ => None,
64    }
65}
66
67/// the form `@render` declares on a declaration (§3), or the E7004 message
68/// naming what is wrong with it; a declaration without one is canonical JSON
69pub fn declared_form(decl: &Decl) -> Result<Form, String> {
70    let anns: Vec<_> = decl
71        .annotations
72        .iter()
73        .filter(|a| a.name == "render")
74        .collect();
75    if anns.is_empty() {
76        return Ok(Form::default());
77    }
78    if anns.len() > 1 {
79        return Err("more than one @render".into());
80    }
81    let a = anns[0];
82    let entries = match a.args.as_slice() {
83        [arg] => match &**arg {
84            Expr::Obj(entries) => entries,
85            _ => return Err("@render takes one object literal".into()),
86        },
87        _ => return Err("@render takes one object literal".into()),
88    };
89    let mut form = Form::default();
90    let mut seen: Vec<&str> = vec![];
91    for (key, val) in entries.iter() {
92        if !FORM_KEYS.contains(&key.as_str()) {
93            return Err(format!("@render: unknown key {key}"));
94        }
95        if seen.contains(&key.as_str()) {
96            return Err(format!("@render: key {key} repeats"));
97        }
98        seen.push(key);
99        let lit = literal(val);
100        match key.as_str() {
101            "format" => match lit {
102                Some(Value::Str(s)) if &*s == "json" => form.yaml = false,
103                Some(Value::Str(s)) if &*s == "yaml" => form.yaml = true,
104                _ => return Err("@render: format must be \"json\" or \"yaml\"".into()),
105            },
106            "indent" => match lit {
107                Some(Value::Int(i)) if i >= Num::from(0) && i <= Num::from(16) => {
108                    form.indent = Some(i.to_usize().unwrap())
109                }
110                _ => return Err("@render: indent must be an integer in 0..16".into()),
111            },
112            "template" | "file" | "each" => match lit {
113                Some(Value::Str(s)) if !s.is_empty() => match key.as_str() {
114                    "template" => form.template = Some(s.to_string()),
115                    "file" => form.file = Some(s.to_string()),
116                    _ => form.each = Some(s.to_string()),
117                },
118                _ => return Err(format!("@render: {key} must be a non-empty string")),
119            },
120            _ => form.delimiters = Some(delimiters(val).map_err(|m| format!("@render: {m}"))?),
121        }
122    }
123    Ok(form)
124}
125
126fn delimiters(e: &Expr) -> Result<Delimiters, String> {
127    let Expr::Obj(entries) = e else {
128        return Err("delimiters must be an object of three pairs".into());
129    };
130    let mut out = Delimiters::default();
131    let mut seen: Vec<&str> = vec![];
132    for (key, val) in entries.iter() {
133        if !["value", "statement", "comment"].contains(&key.as_str()) {
134            return Err(format!("delimiters: unknown key {key}"));
135        }
136        if seen.contains(&key.as_str()) {
137            return Err(format!("delimiters: key {key} repeats"));
138        }
139        seen.push(key);
140        let Expr::Arr(items) = &**val else {
141            return Err(format!("delimiters: {key} must be a pair of strings"));
142        };
143        if items.len() != 2 || items.iter().any(|(spread, _)| *spread) {
144            return Err(format!("delimiters: {key} must be a pair of strings"));
145        }
146        let mut pair: Vec<String> = vec![];
147        for (_, it) in items.iter() {
148            match literal(it) {
149                Some(Value::Str(s)) if !s.is_empty() => pair.push(s.to_string()),
150                _ => {
151                    return Err(format!(
152                        "delimiters: {key} must be a pair of non-empty strings"
153                    ))
154                }
155            }
156        }
157        let p = (pair[0].clone(), pair[1].clone());
158        match key.as_str() {
159            "value" => out.value = p,
160            "statement" => out.statement = p,
161            _ => out.comment = p,
162        }
163    }
164    let openers = [&out.value.0, &out.statement.0, &out.comment.0];
165    if openers[0] == openers[1] || openers[0] == openers[2] || openers[1] == openers[2] {
166        return Err("delimiters: the three openers must differ".into());
167    }
168    Ok(out)
169}
170
171/// the structured text of a document (read_json's shape) in a format and layout (§4), one trailing newline
172pub fn layout(raw: &Value, yaml: bool, indent: Option<usize>) -> String {
173    if yaml {
174        to_yaml(raw, indent.unwrap_or(2)) + "\n"
175    } else {
176        to_json(raw, indent.unwrap_or(0)) + "\n"
177    }
178}
179
180// ---------------- templates (§5) ----------------
181// A template is text with tags in it: `{= expr =}` places the text form of
182// a Decl expression, `{% stmt %}` is a statement, `{# … #}` a comment,
183// `{% raw %}…{% endraw %}` verbatim text. The dialect is fixed here and
184// implemented three times; expressions are the language's, evaluated by
185// its engine over the root's document (§5.4).
186
187use crate::engine::{fmt_f, Engine, Inst};
188use crate::parse::{json_unquote, parse_expr_text};
189use crate::semantics::{
190    path_str, read_json, rec_members, Diag, Env, EvalErr, Fail, MKind, Scope, Seg, SlotState,
191};
192use rustc_hash::FxHashMap;
193use std::collections::{HashMap, HashSet};
194use std::rc::Rc;
195
196/// a rendering diagnostic: the code, the message, and where — `L:C` of the tag, or a document path
197#[derive(Debug, Clone)]
198pub struct RenderError {
199    /// the code (§5.8)
200    pub code: String,
201    /// the message
202    pub message: String,
203    /// `L:C` of the tag, or a document path
204    pub at: String,
205    /// the file the diagnostic is reported against: the template's path as given, or None for the module's
206    pub file: Option<String>,
207}
208impl RenderError {
209    fn new(
210        code: &str,
211        message: impl Into<String>,
212        at: impl Into<String>,
213        file: Option<&str>,
214    ) -> Self {
215        RenderError {
216            code: code.to_string(),
217            message: message.into(),
218            at: at.into(),
219            file: file.map(str::to_string),
220        }
221    }
222    /// the diagnostic (§12.2)
223    pub fn diag(&self) -> Diag {
224        Diag::error(self.message.clone(), self.at.clone(), Some(&self.code))
225    }
226}
227type RR<T> = Result<T, RenderError>;
228
229#[derive(Debug, Clone, Copy)]
230struct Pos {
231    line: usize,
232    col: usize,
233}
234impl Pos {
235    fn at(&self) -> String {
236        format!("{}:{}", self.line, self.col)
237    }
238}
239#[derive(Debug, Clone)]
240enum Node {
241    Text(String),
242    Value {
243        expr: Rc<Expr>,
244        at: Pos,
245    },
246    If {
247        arms: Vec<(Option<Rc<Expr>>, Vec<Node>, Pos)>,
248    },
249    For {
250        vars: Vec<String>,
251        iter: Rc<Expr>,
252        filter: Option<Rc<Expr>>,
253        body: Vec<Node>,
254        empty: Option<Vec<Node>>,
255        at: Pos,
256    },
257    Set {
258        name: String,
259        expr: Rc<Expr>,
260        at: Pos,
261    },
262    Include {
263        path: String,
264        at: Pos,
265    },
266}
267
268/// a parsed template: its path as given (diagnostics), its directory (includes), its nodes
269#[derive(Debug, Clone)]
270pub struct Template {
271    /// the path as given
272    pub path: String,
273    /// the absolute directory its includes resolve from
274    pub dir: String,
275    nodes: Vec<Node>,
276}
277
278enum Tok {
279    Text(String),
280    Tag { stmt: bool, text: String, at: Pos },
281}
282
283fn pos_of(src: &[char], k: usize) -> Pos {
284    let mut line = 1;
285    let mut last: isize = -1;
286    for (j, c) in src.iter().enumerate().take(k) {
287        if *c == '\n' {
288            line += 1;
289            last = j as isize;
290        }
291    }
292    Pos {
293        line,
294        col: (k as isize - last) as usize,
295    }
296}
297fn starts_with(src: &[char], i: usize, pat: &[char]) -> bool {
298    i + pat.len() <= src.len() && src[i..i + pat.len()] == *pat
299}
300fn escape_re(s: &str) -> String {
301    regex::escape(s)
302}
303
304// the lexer: text and tags, with the whitespace rules of §5.2 applied —
305// trim_blocks and lstrip_blocks on for statements, `-` and `+` overriding
306fn lex(src: &[char], path: &str, d: &Delimiters) -> RR<Vec<Tok>> {
307    let chars = |s: &str| s.chars().collect::<Vec<char>>();
308    let mut openers: Vec<(Vec<char>, usize)> = vec![
309        (chars(&d.value.0), 0),
310        (chars(&d.statement.0), 1),
311        (chars(&d.comment.0), 2),
312    ];
313    openers.sort_by_key(|o| std::cmp::Reverse(o.0.len())); // longest first at every position
314    let closers = [
315        chars(&d.value.1),
316        chars(&d.statement.1),
317        chars(&d.comment.1),
318    ];
319    let mut out: Vec<Tok> = vec![];
320    let mut i = 0;
321    let mut text = String::new(); // the text since the last tag
322    let mut after: u8; // what the last tag asks of the text after it: 0 none, 1 trim, 2 strip
323    let mut first = true; // no tag yet: the text starts the template
324    let fail = |code: &str, message: String, k: usize| -> RenderError {
325        RenderError::new(code, message, pos_of(src, k).at(), Some(path))
326    };
327    while i < src.len() {
328        let Some((opener, kind)) = openers.iter().find(|(o, _)| starts_with(src, i, o)) else {
329            text.push(src[i]);
330            i += 1;
331            continue;
332        };
333        let kind = *kind;
334        let start = i;
335        let mut j = i + opener.len();
336        // the modifier after the opener
337        let mut left: Option<char> = None;
338        if kind != 2 && matches!(src.get(j), Some('-') | Some('+')) {
339            left = Some(src[j]);
340            j += 1;
341        }
342        let closer = &closers[kind];
343        // the tag's end: the closer, possibly preceded by a modifier
344        let mut end: Option<usize> = None;
345        let mut right: Option<char> = None;
346        let mut k = j;
347        while k + closer.len() <= src.len() {
348            if starts_with(src, k, closer) {
349                if kind != 2 && k > j && matches!(src[k - 1], '-' | '+') {
350                    right = Some(src[k - 1]);
351                    end = Some(k - 1);
352                } else {
353                    end = Some(k);
354                }
355                break;
356            }
357            k += 1;
358        }
359        let opener_s: String = opener.iter().collect();
360        let Some(end) = end else {
361            return Err(fail("E7001", format!("unclosed {opener_s} tag"), start));
362        };
363        let body: String = src[j..end].iter().collect();
364        let mut next = end + usize::from(right.is_some()) + closer.len();
365        // the text before the tag: `-` strips all white space, a statement's
366        // default strips the indentation of its line (lstrip_blocks), `+` keeps
367        let mut before = text.clone();
368        if left == Some('-') {
369            before = before.trim_end().to_string();
370        } else if kind == 1 && left != Some('+') {
371            let trimmed = before.trim_end_matches([' ', '\t']);
372            if trimmed.ends_with('\n') || (first && trimmed.is_empty()) {
373                before = trimmed.to_string();
374            }
375        }
376        if !before.is_empty() {
377            out.push(Tok::Text(before));
378        }
379        text.clear();
380        first = false;
381        if kind == 2 {
382            after = 0;
383        } else if kind == 1 && body.trim() == "raw" {
384            // verbatim text to the matching endraw, which may carry modifiers
385            let re = Regex::new(&format!(
386                "{}[-+]?\\s*endraw\\s*[-+]?{}",
387                escape_re(&d.statement.0),
388                escape_re(&d.statement.1)
389            ))
390            .unwrap();
391            let rest: String = src[next..].iter().collect();
392            let Some(m) = re.find(&rest) else {
393                return Err(fail("E7001", "unclosed {% raw %}".into(), start));
394            };
395            let mut raw = rest[..m.start()].to_string();
396            if right == Some('-') {
397                raw = raw.trim_start().to_string();
398            } else if right != Some('+') {
399                raw = raw
400                    .strip_prefix("\r\n")
401                    .or_else(|| raw.strip_prefix('\n'))
402                    .unwrap_or(&raw)
403                    .to_string();
404            }
405            let end_tag: Vec<char> = m.as_str().chars().collect();
406            let end_left = end_tag[d.statement.0.chars().count()];
407            let end_right = end_tag[end_tag.len() - d.statement.1.chars().count() - 1];
408            if end_left == '-' {
409                raw = raw.trim_end().to_string();
410            } else if end_left != '+' {
411                let t = raw.trim_end_matches([' ', '\t']);
412                if t.ends_with('\n') {
413                    raw = t.to_string();
414                }
415            }
416            out.push(Tok::Text(raw));
417            next += rest[..m.end()].chars().count();
418            after = match end_right {
419                '-' => 2,
420                '+' => 0,
421                _ => 1,
422            };
423        } else {
424            out.push(Tok::Tag {
425                stmt: kind == 1,
426                text: body,
427                at: pos_of(src, start),
428            });
429            after = match right {
430                Some('-') => 2,
431                Some('+') => 0,
432                _ => {
433                    if kind == 1 {
434                        1
435                    } else {
436                        0
437                    }
438                }
439            };
440        }
441        i = next;
442        // the text after the tag: `-` strips all white space, a statement's
443        // default drops the line break that follows it (trim_blocks)
444        if after == 2 {
445            while i < src.len() && src[i].is_whitespace() {
446                i += 1;
447            }
448        } else if after == 1 {
449            if src.get(i) == Some(&'\n') {
450                i += 1;
451            } else if src.get(i) == Some(&'\r') && src.get(i + 1) == Some(&'\n') {
452                i += 2;
453            }
454        }
455    }
456    if !text.is_empty() {
457        out.push(Tok::Text(text));
458    }
459    Ok(out)
460}
461
462// the parser: statements nest, every `if` and `for` closes
463struct Parser<'a> {
464    toks: Vec<Tok>,
465    k: usize,
466    path: &'a str,
467}
468impl Parser<'_> {
469    fn fail(&self, message: impl Into<String>, at: Pos) -> RenderError {
470        RenderError::new("E7001", message, at.at(), Some(self.path))
471    }
472    fn expr(&self, text: &str, at: Pos) -> RR<Rc<Expr>> {
473        parse_expr_text(text)
474            .ok_or_else(|| self.fail(format!("expression does not parse: {}", text.trim()), at))
475    }
476    // `for x in e if c`: the filter is the last top-level `if` whose two
477    // sides both parse; an `if` inside brackets or a string is the expression's
478    fn iter_and_filter(&self, text: &str, at: Pos) -> RR<(Rc<Expr>, Option<Rc<Expr>>)> {
479        let cs: Vec<char> = text.chars().collect();
480        let mut cands: Vec<usize> = vec![];
481        let mut depth = 0i32;
482        let mut quote: Option<char> = None;
483        let mut i = 0;
484        while i < cs.len() {
485            let c = cs[i];
486            if let Some(q) = quote {
487                if c == '\\' {
488                    i += 1;
489                } else if c == q {
490                    quote = None;
491                }
492                i += 1;
493                continue;
494            }
495            if c == '"' || c == '\'' || c == '`' {
496                quote = Some(c);
497            } else if "([{".contains(c) {
498                depth += 1;
499            } else if ")]}".contains(c) {
500                depth -= 1;
501            } else if depth == 0
502                && (i == 0 || cs[i - 1].is_whitespace())
503                && c == 'i'
504                && cs.get(i + 1) == Some(&'f')
505                && cs.get(i + 2).is_some_and(|x| x.is_whitespace())
506            {
507                cands.push(i);
508            }
509            i += 1;
510        }
511        for i in cands.into_iter().rev() {
512            let a: String = cs[..i].iter().collect();
513            let b: String = cs[i + 2..].iter().collect();
514            if let (Some(x), Some(y)) = (parse_expr_text(&a), parse_expr_text(&b)) {
515                return Ok((x, Some(y)));
516            }
517        }
518        Ok((self.expr(text, at)?, None))
519    }
520    // a body up to one of the closers: (nodes, the closer, its position, its rest)
521    fn body(
522        &mut self,
523        closers: &[&str],
524        opened: &str,
525        at: Pos,
526    ) -> RR<(Vec<Node>, String, Pos, String)> {
527        let mut nodes: Vec<Node> = vec![];
528        while self.k < self.toks.len() {
529            let tok = &self.toks[self.k];
530            self.k += 1;
531            let (stmt, text, tat) = match tok {
532                Tok::Text(s) => {
533                    nodes.push(Node::Text(s.clone()));
534                    continue;
535                }
536                Tok::Tag { stmt, text, at } => (*stmt, text.clone(), *at),
537            };
538            if !stmt {
539                nodes.push(Node::Value {
540                    expr: self.expr(&text, tat)?,
541                    at: tat,
542                });
543                continue;
544            }
545            let t = text.trim();
546            let word: String = t
547                .chars()
548                .take_while(|c| c.is_ascii_alphanumeric() || *c == '_')
549                .collect();
550            if word.is_empty() || !word.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
551                return Err(self.fail("empty statement", tat));
552            }
553            let rest = t[word.len()..].trim().to_string();
554            if closers.contains(&word.as_str()) {
555                return Ok((nodes, word, tat, rest));
556            }
557            match word.as_str() {
558                "if" => {
559                    let mut arms: Vec<(Option<Rc<Expr>>, Vec<Node>, Pos)> = vec![];
560                    let mut cond: Option<Rc<Expr>> = Some(self.expr(&rest, tat)?);
561                    let mut arm_at = tat;
562                    loop {
563                        let (b, closer, c_at, c_rest) =
564                            self.body(&["elif", "else", "endif"], "if", arm_at)?;
565                        arms.push((cond.clone(), b, arm_at));
566                        if closer == "endif" {
567                            if !c_rest.is_empty() {
568                                return Err(self.fail("{% endif %} takes nothing", c_at));
569                            }
570                            break;
571                        }
572                        if closer == "else" {
573                            if !c_rest.is_empty() {
574                                return Err(self.fail("{% else %} takes nothing", c_at));
575                            }
576                            if cond.is_none() {
577                                return Err(self.fail("{% else %} after {% else %}", c_at));
578                            }
579                            cond = None;
580                        } else {
581                            if cond.is_none() {
582                                return Err(self.fail("{% elif %} after {% else %}", c_at));
583                            }
584                            cond = Some(self.expr(&c_rest, c_at)?);
585                        }
586                        arm_at = c_at;
587                    }
588                    nodes.push(Node::If { arms });
589                }
590                "for" => {
591                    static RE_FOR: LazyLock<Regex> = LazyLock::new(|| {
592                        Regex::new(r"(?s)^([A-Za-z_][A-Za-z0-9_]*)\s*(?:,\s*([A-Za-z_][A-Za-z0-9_]*))?\s+in\s+(.+)$").unwrap()
593                    });
594                    let Some(m) = RE_FOR.captures(&rest) else {
595                        return Err(self.fail("{% for %} expects `x in e` or `k, v in e`", tat));
596                    };
597                    let mut vars = vec![m[1].to_string()];
598                    if let Some(v) = m.get(2) {
599                        vars.push(v.as_str().to_string());
600                    }
601                    let (iter, filter) = self.iter_and_filter(&m[3], tat)?;
602                    let (b, closer, c_at, c_rest) = self.body(&["else", "endfor"], "for", tat)?;
603                    if !c_rest.is_empty() {
604                        return Err(self.fail(format!("{{% {closer} %}} takes nothing"), c_at));
605                    }
606                    let mut empty = None;
607                    if closer == "else" {
608                        let (e, c2, c2_at, c2_rest) = self.body(&["endfor"], "for", c_at)?;
609                        if !c2_rest.is_empty() {
610                            return Err(self.fail(format!("{{% {c2} %}} takes nothing"), c2_at));
611                        }
612                        empty = Some(e);
613                    }
614                    nodes.push(Node::For {
615                        vars,
616                        iter,
617                        filter,
618                        body: b,
619                        empty,
620                        at: tat,
621                    });
622                }
623                "set" => {
624                    static RE_SET: LazyLock<Regex> = LazyLock::new(|| {
625                        Regex::new(r"(?s)^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$").unwrap()
626                    });
627                    let Some(m) = RE_SET.captures(&rest) else {
628                        return Err(self.fail("{% set %} expects `x = e`", tat));
629                    };
630                    nodes.push(Node::Set {
631                        name: m[1].to_string(),
632                        expr: self.expr(&m[2], tat)?,
633                        at: tat,
634                    });
635                }
636                "include" => {
637                    static RE_INC: LazyLock<Regex> =
638                        LazyLock::new(|| Regex::new(r#"^"((?:[^"\\]|\\.)*)"$"#).unwrap());
639                    let Some(m) = RE_INC.captures(&rest) else {
640                        return Err(self.fail("{% include %} expects a quoted path", tat));
641                    };
642                    let path = json_unquote(&format!("\"{}\"", &m[1]))
643                        .map_err(|_| self.fail("{% include %} expects a quoted path", tat))?;
644                    nodes.push(Node::Include { path, at: tat });
645                }
646                "elif" | "else" | "endif" | "endfor" | "endraw" => {
647                    let opener = match word.as_str() {
648                        "endfor" => "{% for %}",
649                        "endraw" => "{% raw %}",
650                        _ => "{% if %}",
651                    };
652                    return Err(self.fail(format!("{{% {word} %}} without {opener}"), tat));
653                }
654                _ => return Err(self.fail(format!("unknown tag {{% {word} %}}"), tat)),
655            }
656        }
657        if !opened.is_empty() {
658            return Err(self.fail(format!("unclosed {{% {opened} %}}"), at));
659        }
660        Ok((nodes, String::new(), at, String::new()))
661    }
662}
663
664/// parse a template's text (§5.2–5.3); E7001 for what does not parse. `path`
665/// is the template's path as given (its diagnostics name it); `dir` is where
666/// its includes resolve, the absolute directory it was read from
667pub fn parse_template(
668    text: &str,
669    path: &str,
670    delimiters: &Delimiters,
671    dir: Option<&str>,
672) -> RR<Template> {
673    let src: Vec<char> = text.chars().collect();
674    let toks = lex(&src, path, delimiters)?;
675    let mut p = Parser { toks, k: 0, path };
676    let (nodes, _, _, _) = p.body(&[], "", Pos { line: 1, col: 1 })?;
677    let dir = match dir {
678        Some(d) => d.to_string(),
679        None => parent_of(&absolute(path)),
680    };
681    Ok(Template {
682        path: path.to_string(),
683        dir,
684        nodes,
685    })
686}
687
688/// an absolute, normalized path (`.` and `..` resolved), as the reference's host resolves one
689pub fn absolute(p: &str) -> String {
690    let joined = std::path::absolute(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
691    normalize_path(&joined.to_string_lossy())
692}
693/// `dir/rel` absolute and normalized (an absolute `rel` wins)
694pub fn resolve_in(dir: &str, rel: &str) -> String {
695    if rel.starts_with('/') {
696        normalize_path(rel)
697    } else {
698        absolute(&format!("{dir}/{rel}"))
699    }
700}
701fn normalize_path(p: &str) -> String {
702    let abs = p.starts_with('/');
703    let mut out: Vec<&str> = vec![];
704    for seg in p.split('/') {
705        if seg.is_empty() || seg == "." {
706            continue;
707        }
708        if seg == ".." {
709            if !out.is_empty() && *out.last().unwrap() != ".." {
710                out.pop();
711            } else if !abs {
712                out.push("..");
713            }
714        } else {
715            out.push(seg);
716        }
717    }
718    let body = out.join("/");
719    if abs {
720        format!("/{body}")
721    } else if body.is_empty() {
722        ".".into()
723    } else {
724        body
725    }
726}
727fn parent_of(p: &str) -> String {
728    match p.trim_end_matches('/').rfind('/') {
729        None => ".".into(),
730        Some(0) => "/".into(),
731        Some(i) => p[..i].to_string(),
732    }
733}
734fn base_of(p: &str) -> String {
735    let n = p.trim_end_matches('/');
736    n.rsplit('/').next().unwrap_or(n).to_string()
737}
738
739/// what a template renders over (§5.4)
740pub struct Context<'a> {
741    /// the engine of the run
742    pub eng: Rc<Engine>,
743    /// the entry module's environment: its consts and funcs are in scope
744    pub menv: Rc<Env>,
745    /// the root's name
746    pub root_name: String,
747    /// the root's document, bound to the root's name
748    pub root: Value,
749    /// a fan-out element and its key (§6), when rendering one element
750    pub item: Option<(Value, Value)>,
751    /// the text of another template file by absolute path, or None when it cannot be read
752    pub read_template: &'a dyn Fn(&str) -> Option<String>,
753    /// the template's delimiters
754    pub delimiters: Delimiters,
755}
756
757/// the text form of a value (§5.5); Err((code, message)) when it has none
758pub fn text_form(eng: &Engine, v: &Value, root_name: &str) -> Result<String, (String, String)> {
759    let no = |what: &str| Err(("E7002".to_string(), format!("value has no text form{what}")));
760    match v {
761        Value::Str(s) => Ok(s.to_string()),
762        Value::Int(i) => Ok(i.to_string()),
763        Value::Float(f) => Ok(fmt_f(*f)),
764        Value::Bool(b) => Ok(b.to_string()),
765        Value::Null => Ok("null".into()),
766        Value::Absent | Value::Undef => no(": absent"),
767        Value::Clo(_) | Value::Nat(_) | Value::Std(_) | Value::NsRef(_) => no(": a function"),
768        Value::Q(q) => {
769            let unit = eng
770                .env
771                .base_unit_of
772                .borrow()
773                .get(q.dim.as_str())
774                .cloned()
775                .unwrap_or_else(|| q.dim.as_ref().clone());
776            Ok(format!("{} {unit}", fmt_f(q.value)))
777        }
778        Value::Ref(segs) => Ok(path_str(segs, Some(root_name))),
779        Value::Arr(_) | Value::Map(_) | Value::Rec(_) => Ok(eng.serialize(v, root_name, false)),
780        _ => no(""),
781    }
782}
783
784fn eval_err(msg: impl Into<String>) -> Fail {
785    Fail::Eval(EvalErr {
786        msg: msg.into(),
787        code: None,
788    })
789}
790// the `render` namespace (§5.6): json, yaml, indent
791fn render_namespace(eng: Rc<Engine>, root_name: &str) -> Value {
792    let raw = {
793        let eng = eng.clone();
794        let root = root_name.to_string();
795        move |v: &Value| -> R<Value> {
796            read_json(&eng.serialize(v, &root, false)).map_err(|_| eval_err("render: not data"))
797        }
798    };
799    let raw = Rc::new(raw);
800    let indent_arg = |a: &[Value], i: usize| -> R<i64> {
801        match a.get(i) {
802            None => Ok(-1),
803            Some(Value::Int(n)) if *n >= Num::from(0) && *n <= Num::from(16) => {
804                Ok(n.to_i64().unwrap())
805            }
806            _ => Err(eval_err("render: indent must be an integer in 0..16")),
807        }
808    };
809    let json = {
810        let raw = raw.clone();
811        Value::native(move |a: &[Value]| -> R<Value> {
812            if a.is_empty() {
813                return Err(eval_err("render.json expects a value"));
814            }
815            let n = indent_arg(a, 1)?.max(0) as usize;
816            Ok(Value::Str(to_json(&raw(&a[0])?, n).into()))
817        })
818    };
819    let yaml = {
820        let raw = raw.clone();
821        Value::native(move |a: &[Value]| -> R<Value> {
822            if a.is_empty() {
823                return Err(eval_err("render.yaml expects a value"));
824            }
825            let n = indent_arg(a, 1)?;
826            let n = if n < 0 { 2 } else { n as usize };
827            Ok(Value::Str(to_yaml(&raw(&a[0])?, n).into()))
828        })
829    };
830    let indent = Value::native(|a: &[Value]| -> R<Value> {
831        match (a.first(), a.get(1)) {
832            (Some(Value::Str(s)), Some(Value::Int(n))) if *n >= Num::from(0) => Ok(Value::Str(
833                s.replace('\n', &format!("\n{}", " ".repeat(n.to_usize().unwrap())))
834                    .into(),
835            )),
836            _ => Err(eval_err("render.indent expects a string and a count")),
837        }
838    });
839    Value::PreObj(Rc::new(vec![
840        ("json".into(), json),
841        ("yaml".into(), yaml),
842        ("indent".into(), indent),
843    ]))
844}
845
846// the members of a record in canonical order (§7.2), as the serializer walks them
847fn record_entries(eng: &Engine, inst: &Inst) -> R<Vec<(String, Value)>> {
848    let names: Vec<String> = {
849        let b = inst.borrow();
850        let mut out: Vec<String> = vec![];
851        let mut done: HashSet<String> = HashSet::new();
852        for n in b.entry_order.iter() {
853            done.insert(n.clone());
854            if b.extra(n).is_some() {
855                continue;
856            }
857            let Some(s) = b.slot(n) else { continue };
858            if s.hidden
859                || matches!(s.state, SlotState::Invalid | SlotState::Absent)
860                || s.kind == MKind::Der
861            {
862                continue;
863            }
864            out.push(n.clone());
865        }
866        for m in rec_members(&b.rt).iter() {
867            if done.contains(&m.name) && m.kind != MKind::Der {
868                continue;
869            }
870            let Some(s) = b.slot(&m.name) else { continue };
871            if s.hidden
872                || matches!(
873                    s.state,
874                    SlotState::Invalid | SlotState::Absent | SlotState::Unforced
875                )
876            {
877                continue;
878            }
879            out.push(m.name.clone());
880        }
881        out
882    };
883    let rec = Value::Rec(inst.clone());
884    let mut out = vec![];
885    for n in names {
886        out.push((n.clone(), eng.access(&rec, &n)?));
887    }
888    Ok(out)
889}
890// the absent members of a record: bound to Absent so that `??` can supply a text
891fn absent_members(inst: &Inst) -> Vec<String> {
892    inst.borrow()
893        .slots
894        .iter()
895        .filter(|(_, s)| s.state == SlotState::Absent)
896        .map(|(n, _)| n.to_string())
897        .collect()
898}
899
900// the language's code for an evaluation failure inside a template
901fn code_of(e: &EvalErr) -> String {
902    e.code.clone().unwrap_or_else(|| {
903        if e.msg.starts_with("unknown name") {
904            "E3003".into()
905        } else {
906            "E4001".into()
907        }
908    })
909}
910
911/// render a parsed template over a context (§5); a RenderError carries the diagnostic
912pub fn render_template(tpl: &Template, cx: &Context) -> RR<String> {
913    let mut locals: FxHashMap<String, Value> = FxHashMap::default();
914    locals.insert(cx.root_name.clone(), cx.root.clone());
915    let members = |v: &Value, locals: &mut FxHashMap<String, Value>| -> RR<()> {
916        if let Value::Rec(inst) = v {
917            for (n, x) in record_entries(&cx.eng, inst).map_err(|f| fail_of(f, "", None))? {
918                locals.insert(n, x);
919            }
920            for n in absent_members(inst) {
921                locals.entry(n).or_insert(Value::Absent);
922            }
923        }
924        Ok(())
925    };
926    if let Some((item, key)) = &cx.item {
927        locals.insert("item".into(), item.clone());
928        locals.insert("key".into(), key.clone());
929        members(item, &mut locals)?;
930    } else {
931        members(&cx.root, &mut locals)?;
932    }
933    locals.insert(
934        "render".into(),
935        render_namespace(cx.eng.clone(), &cx.root_name),
936    );
937    let mut parsed: HashMap<String, Rc<Template>> = HashMap::new();
938    let mut stack: Vec<String> = vec![resolve_in(&tpl.dir, &base_of(&tpl.path))];
939    render_nodes(tpl, &tpl.nodes, locals, cx, &mut parsed, &mut stack)
940}
941
942fn fail_of(f: Fail, at: &str, file: Option<&str>) -> RenderError {
943    match f {
944        Fail::Eval(e) => RenderError::new(&code_of(&e), e.msg.clone(), at, file),
945        _ => RenderError::new("E4001", "expression cannot be evaluated", at, file),
946    }
947}
948
949fn render_nodes(
950    tpl: &Template,
951    nodes: &[Node],
952    mut locals: FxHashMap<String, Value>,
953    cx: &Context,
954    parsed: &mut HashMap<String, Rc<Template>>,
955    stack: &mut Vec<String>,
956) -> RR<String> {
957    let eng = &cx.eng;
958    let scope = |locals: &FxHashMap<String, Value>| Scope {
959        inst: None,
960        locals: Locals::from_map(locals),
961        root_name: Rc::from(cx.root_name.as_str()),
962        menv: Some(cx.menv.clone()),
963    };
964    let eval_at = |e: &Rc<Expr>, locals: &FxHashMap<String, Value>, p: Pos| -> RR<Value> {
965        let sc = scope(locals);
966        let r = (|| -> R<Value> {
967            let v = eng.ev(e, &sc)?;
968            let v = eng.materialize(v, &[Seg::Name("_".into())])?;
969            eng.force_all(&v);
970            Ok(v)
971        })();
972        r.map_err(|f| fail_of(f, &p.at(), Some(&tpl.path)))
973    };
974    let declare = |name: &str, locals: &FxHashMap<String, Value>, p: Pos| -> RR<()> {
975        if locals.contains_key(name)
976            || cx.menv.consts.borrow().contains_key(name)
977            || cx.menv.funcs.borrow().contains_key(name)
978        {
979            return Err(RenderError::new(
980                "E3019",
981                format!("{name} shadows a name in scope"),
982                p.at(),
983                Some(&tpl.path),
984            ));
985        }
986        Ok(())
987    };
988    let mut out = String::new();
989    for n in nodes {
990        match n {
991            Node::Text(s) => out.push_str(s),
992            Node::Value { expr, at } => {
993                let v = eval_at(expr, &locals, *at)?;
994                match text_form(eng, &v, &cx.root_name) {
995                    Ok(t) => out.push_str(&t),
996                    Err((code, message)) => {
997                        return Err(RenderError::new(&code, message, at.at(), Some(&tpl.path)))
998                    }
999                }
1000            }
1001            Node::If { arms } => {
1002                for (cond, body, at) in arms {
1003                    let taken = match cond {
1004                        None => true,
1005                        Some(c) => match eval_at(c, &locals, *at)? {
1006                            Value::Bool(b) => b,
1007                            _ => {
1008                                return Err(RenderError::new(
1009                                    "E4001",
1010                                    "condition is not a bool",
1011                                    at.at(),
1012                                    Some(&tpl.path),
1013                                ))
1014                            }
1015                        },
1016                    };
1017                    if taken {
1018                        out.push_str(&render_nodes(tpl, body, locals.clone(), cx, parsed, stack)?);
1019                        break;
1020                    }
1021                }
1022            }
1023            Node::For {
1024                vars,
1025                iter,
1026                filter,
1027                body,
1028                empty,
1029                at,
1030            } => {
1031                for v in vars {
1032                    declare(v, &locals, *at)?;
1033                }
1034                if vars.len() == 2 && vars[0] == vars[1] {
1035                    return Err(RenderError::new(
1036                        "E3019",
1037                        format!("{} shadows a name in scope", vars[0]),
1038                        at.at(),
1039                        Some(&tpl.path),
1040                    ));
1041                }
1042                let coll = eval_at(iter, &locals, *at)?;
1043                let mut pairs: Vec<(Value, Value)> = if vars.len() == 1 {
1044                    match eng.iterate(&coll) {
1045                        Ok(items) => items.into_iter().map(|x| (x, Value::Undef)).collect(),
1046                        Err(_) => {
1047                            return Err(RenderError::new(
1048                                "E4001",
1049                                "for over a value that is not an array",
1050                                at.at(),
1051                                Some(&tpl.path),
1052                            ))
1053                        }
1054                    }
1055                } else {
1056                    match &coll {
1057                        Value::Rec(inst) => record_entries(eng, inst)
1058                            .map_err(|f| fail_of(f, &at.at(), Some(&tpl.path)))?
1059                            .into_iter()
1060                            .map(|(k, v)| (Value::Str(k.into()), v))
1061                            .collect(),
1062                        Value::Map(m) => m
1063                            .borrow()
1064                            .entries
1065                            .iter()
1066                            .map(|(k, v)| (Value::Str(k.clone().into()), v.clone()))
1067                            .collect(),
1068                        _ => {
1069                            return Err(RenderError::new(
1070                                "E4001",
1071                                "for k, v over a value that is not an object or a map",
1072                                at.at(),
1073                                Some(&tpl.path),
1074                            ))
1075                        }
1076                    }
1077                };
1078                if let Some(f) = filter {
1079                    let mut kept = vec![];
1080                    for (a, b) in pairs {
1081                        let mut l2 = locals.clone();
1082                        l2.insert(vars[0].clone(), a.clone());
1083                        if vars.len() == 2 {
1084                            l2.insert(vars[1].clone(), b.clone());
1085                        }
1086                        let c = eng
1087                            .ev(f, &scope(&l2))
1088                            .map_err(|fl| fail_of(fl, &at.at(), Some(&tpl.path)))?;
1089                        match c {
1090                            Value::Bool(true) => kept.push((a, b)),
1091                            Value::Bool(false) => {}
1092                            _ => {
1093                                return Err(RenderError::new(
1094                                    "E4001",
1095                                    "filter is not a bool",
1096                                    at.at(),
1097                                    Some(&tpl.path),
1098                                ))
1099                            }
1100                        }
1101                    }
1102                    pairs = kept;
1103                }
1104                if pairs.is_empty() {
1105                    if let Some(e) = empty {
1106                        out.push_str(&render_nodes(tpl, e, locals.clone(), cx, parsed, stack)?);
1107                    }
1108                    continue;
1109                }
1110                let len = pairs.len();
1111                for (i, (a, b)) in pairs.into_iter().enumerate() {
1112                    let mut l2 = locals.clone();
1113                    l2.insert(vars[0].clone(), a);
1114                    if vars.len() == 2 {
1115                        l2.insert(vars[1].clone(), b);
1116                    }
1117                    l2.insert(
1118                        "loop".into(),
1119                        Value::PreObj(Rc::new(vec![
1120                            ("index".into(), Value::Int(Num::from(i + 1))),
1121                            ("index0".into(), Value::Int(Num::from(i))),
1122                            ("first".into(), Value::Bool(i == 0)),
1123                            ("last".into(), Value::Bool(i == len - 1)),
1124                            ("length".into(), Value::Int(Num::from(len))),
1125                        ])),
1126                    );
1127                    out.push_str(&render_nodes(tpl, body, l2, cx, parsed, stack)?);
1128                }
1129            }
1130            Node::Set { name, expr, at } => {
1131                declare(name, &locals, *at)?;
1132                if name == "loop" {
1133                    return Err(RenderError::new(
1134                        "E3019",
1135                        "loop cannot be assigned",
1136                        at.at(),
1137                        Some(&tpl.path),
1138                    ));
1139                }
1140                let v = eval_at(expr, &locals, *at)?;
1141                locals.insert(name.clone(), v);
1142            }
1143            Node::Include { path, at } => {
1144                let abs = resolve_in(&tpl.dir, path);
1145                if stack.contains(&abs) {
1146                    let chain: Vec<String> =
1147                        stack.iter().chain([&abs]).map(|p| base_of(p)).collect();
1148                    return Err(RenderError::new(
1149                        "E7001",
1150                        format!("include cycle: {}", chain.join(" -> ")),
1151                        at.at(),
1152                        Some(&tpl.path),
1153                    ));
1154                }
1155                let sub = match parsed.get(&abs) {
1156                    Some(t) => t.clone(),
1157                    None => {
1158                        let Some(text) = (cx.read_template)(&abs) else {
1159                            return Err(RenderError::new(
1160                                "E7003",
1161                                format!("template cannot be read: {path}"),
1162                                at.at(),
1163                                Some(&tpl.path),
1164                            ));
1165                        };
1166                        let t = Rc::new(parse_template(
1167                            &text,
1168                            path,
1169                            &cx.delimiters,
1170                            Some(&parent_of(&abs)),
1171                        )?);
1172                        parsed.insert(abs.clone(), t.clone());
1173                        t
1174                    }
1175                };
1176                stack.push(abs);
1177                let r = render_nodes(&sub, &sub.nodes, locals.clone(), cx, parsed, stack);
1178                stack.pop();
1179                out.push_str(&r?);
1180            }
1181        }
1182    }
1183    Ok(out)
1184}
1185
1186// ---------------- emission: one root in its form (§3, §6) ----------------
1187
1188/// the text a root is emitted as: one text, or the files of a fan-out (§6), path by path
1189#[derive(Debug, Clone)]
1190pub enum Emitted {
1191    /// one text
1192    One(String),
1193    /// one file per element, in element order
1194    Many(Vec<(String, String)>),
1195}
1196
1197/// what emits one root: its value, its form with the invocation's overrides, and the template's text when there is one
1198pub struct Emission<'a> {
1199    /// the engine of the run
1200    pub eng: Rc<Engine>,
1201    /// the entry module's environment
1202    pub menv: Rc<Env>,
1203    /// the root's name
1204    pub root_name: String,
1205    /// the root's value
1206    pub value: Value,
1207    /// the declared form
1208    pub form: Form,
1209    /// `--format yaml` / `--format json`
1210    pub yaml: Option<bool>,
1211    /// `--indent n`
1212    pub indent: Option<usize>,
1213    /// the template's path as given, its text, and the absolute directory its includes resolve from
1214    pub template: Option<(String, String, String)>,
1215    /// the text of a template file by absolute path
1216    pub read_template: &'a dyn Fn(&str) -> Option<String>,
1217}
1218
1219// a fan-out element's file path (§6): a string, relative, `/`-separated,
1220// not leaving the directory, distinct — else E7005 at the element's path
1221fn fan_out_path(
1222    each: &str,
1223    elem: &Value,
1224    key: &Value,
1225    at: &str,
1226    seen: &mut HashSet<String>,
1227) -> RR<String> {
1228    let e7005 = |m: String| RenderError::new("E7005", m, at, None);
1229    let p: Value = if each == "$key" {
1230        match key {
1231            Value::Str(_) => key.clone(),
1232            _ => {
1233                return Err(e7005(
1234                    "fan-out path: $key names no key (the root is an array)".into(),
1235                ))
1236            }
1237        }
1238    } else {
1239        let Value::Rec(inst) = elem else {
1240            return Err(e7005(format!(
1241                "fan-out path: the element has no member {each}"
1242            )));
1243        };
1244        let b = inst.borrow();
1245        let Some(s) = b.slot(each) else {
1246            return Err(e7005(format!(
1247                "fan-out path: the element has no member {each}"
1248            )));
1249        };
1250        if s.state == SlotState::Absent {
1251            Value::Absent
1252        } else {
1253            s.value.clone()
1254        }
1255    };
1256    let Value::Str(p) = p else {
1257        return Err(e7005("fan-out path is not a string".into()));
1258    };
1259    if p.is_empty() {
1260        return Err(e7005("fan-out path is empty".into()));
1261    }
1262    if p.starts_with('/') {
1263        return Err(e7005(format!("fan-out path is absolute: {p}")));
1264    }
1265    if p.contains('\\') {
1266        return Err(e7005(format!("fan-out path uses \\: {p}")));
1267    }
1268    if p.split('/').any(|s| s == ".." || s == "." || s.is_empty()) {
1269        return Err(e7005(format!(
1270            "fan-out path leaves the destination directory: {p}"
1271        )));
1272    }
1273    if seen.contains(&*p) {
1274        return Err(e7005(format!("fan-out path repeats: {p}")));
1275    }
1276    seen.insert(p.to_string());
1277    Ok(p.to_string())
1278}
1279
1280/// Whether a root's text is the engine's compact JSON and nothing else: no
1281/// template, no fan-out, no layout pass, and a container, whose
1282/// serialization always has text. Such a root can go to a file in pieces.
1283pub fn emits_in_pieces(e: &Emission) -> bool {
1284    e.template.is_none()
1285        && e.form.each.is_none()
1286        && !e.yaml.unwrap_or(e.form.yaml)
1287        && e.indent.or(e.form.indent).unwrap_or(0) == 0
1288        && matches!(
1289            e.value,
1290            Value::Arr(_) | Value::Map(_) | Value::Rec(_) | Value::JObj(_) | Value::JArr(_)
1291        )
1292}
1293
1294/// Emit such a root to a writer without building its text whole; the bytes
1295/// are [`emit_root`]'s.
1296pub fn emit_root_to(e: &Emission, to: &mut dyn std::io::Write) -> std::io::Result<()> {
1297    e.eng.serialize_to(&e.value, &e.root_name, false, to)?;
1298    to.write_all(b"\n")
1299}
1300
1301/// emit one root (§3.1): its structured text or its template's text, as one text or one file per element
1302pub fn emit_root(e: &Emission) -> RR<Emitted> {
1303    let yaml = e.yaml.unwrap_or(e.form.yaml);
1304    let indent = e.indent.or(e.form.indent);
1305    let structured = |v: &Value| -> String {
1306        let mut text = e.eng.serialize(v, &e.root_name, false);
1307        // Serialization already produces canonical compact JSON. Reuse its
1308        // bytes instead of allocating a second document and encoding it again.
1309        // An unsupported public Value can serialize to empty text; preserve
1310        // the existing canonical-JSON failure for that case below.
1311        if !yaml && indent.unwrap_or(0) == 0 && !text.is_empty() {
1312            text.push('\n');
1313            text
1314        } else {
1315            layout(
1316                &read_json(&text).ok().expect("canonical JSON"),
1317                yaml,
1318                indent,
1319            )
1320        }
1321    };
1322    let delimiters = e.form.delimiters.clone().unwrap_or_default();
1323    let tpl = match &e.template {
1324        Some((path, text, dir)) => Some(parse_template(text, path, &delimiters, Some(dir))?),
1325        None => None,
1326    };
1327    let cx = |item: Option<(Value, Value)>| Context {
1328        eng: e.eng.clone(),
1329        menv: e.menv.clone(),
1330        root_name: e.root_name.clone(),
1331        root: e.value.clone(),
1332        item,
1333        read_template: e.read_template,
1334        delimiters: delimiters.clone(),
1335    };
1336    let Some(each) = &e.form.each else {
1337        return Ok(Emitted::One(match &tpl {
1338            Some(t) => render_template(t, &cx(None))?,
1339            None => structured(&e.value),
1340        }));
1341    };
1342    // fan-out: every element of the array or map to its own file
1343    let elems: Vec<(Value, Value, Seg)> = match &e.value {
1344        Value::Arr(a) => a
1345            .borrow()
1346            .items
1347            .iter()
1348            .enumerate()
1349            .map(|(i, v)| (v.clone(), Value::Int(Num::from(i)), Seg::Idx(i)))
1350            .collect(),
1351        Value::Map(m) => m
1352            .borrow()
1353            .entries
1354            .iter()
1355            .map(|(k, v)| {
1356                (
1357                    v.clone(),
1358                    Value::Str(k.clone().into()),
1359                    Seg::Key(Rc::from(k.clone())),
1360                )
1361            })
1362            .collect(),
1363        _ => {
1364            return Err(RenderError::new(
1365                "E7004",
1366                "@render: each on a root that is neither an array nor a map",
1367                e.root_name.clone(),
1368                None,
1369            ))
1370        }
1371    };
1372    let mut seen: HashSet<String> = HashSet::new();
1373    let mut paths = vec![];
1374    for (v, k, seg) in &elems {
1375        let at = path_str(
1376            &[Seg::Name(Rc::from(e.root_name.clone())), seg.clone()],
1377            None,
1378        );
1379        paths.push(fan_out_path(each, v, k, &at, &mut seen)?);
1380    }
1381    let mut files = vec![];
1382    for (i, (v, k, _)) in elems.into_iter().enumerate() {
1383        let text = match &tpl {
1384            Some(t) => render_template(t, &cx(Some((v, k))))?,
1385            None => structured(&v),
1386        };
1387        files.push((paths[i].clone(), text));
1388    }
1389    Ok(Emitted::Many(files))
1390}