Skip to main content

oxdock_process/
expand.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::Result;
5use oxdock_diagnostics::DiagnosticResult;
6
7use crate::contract::CommandContext;
8use crate::diagnostics as expand_diag;
9
10/// Maximum bytes to buffer while scanning for closing delimiter.
11/// If exceeded without finding closing delimiter, buffered bytes are flushed as literals.
12const MAX_PLACEHOLDER_SCAN: usize = 1024;
13
14/// Configurable delimiter syntax for template expansion.
15pub struct TemplateDelimiters {
16    pub open: &'static [u8],
17    pub close: &'static [u8],
18}
19
20impl Default for TemplateDelimiters {
21    fn default() -> Self {
22        Self {
23            open: b"{{",
24            close: b"}}",
25        }
26    }
27}
28
29/// Resolver for `{{ MODULE::FUNC(args) }}` placeholder calls.
30///
31/// Receives the module name, function name, and already resolved argument
32/// values, and returns the call result. Only pure value returning host
33/// functions may back this: no handles, no pipes, no I/O. The resolver
34/// carries no formatting logic; formatting lives with the function.
35pub type PlaceholderCall = Arc<
36    dyn Fn(&str, &str, Vec<oxdock_parser::Value>) -> Result<oxdock_parser::Value> + Send + Sync,
37>;
38
39/// Streaming template expansion state machine.
40///
41/// Processes input bytes incrementally, expanding `{{ env:KEY }}` placeholders.
42/// At most `MAX_PLACEHOLDER_SCAN` bytes are held in buffer. Plain text streams
43/// flush immediately with zero buffering.
44pub struct StreamingExpand {
45    /// Bytes accumulated as key payload inside `{{ ... }}` (no open delimiter prefix).
46    buffer: Vec<u8>,
47    /// Explicit key=value overrides (take precedence over env).
48    overrides: HashMap<String, String>,
49    /// Environment variable lookup.
50    env: HashMap<String, String>,
51    /// Structured variable lookup (for key-path evaluation).
52    vars: HashMap<String, oxdock_parser::Value>,
53    /// Optional dispatcher for `{{ MODULE::FUNC(args) }}` calls. When set,
54    /// placeholders holding a call expression are evaluated through it.
55    /// Carries dispatch only; formatting stays with the callee.
56    call_resolver: Option<PlaceholderCall>,
57    /// State: are we currently inside a placeholder?
58    in_placeholder: bool,
59    /// Trailing opening byte from previous chunk : deferred across chunks.
60    pending_brace: bool,
61    /// Trailing closing byte from previous chunk : deferred across chunks.
62    pending_close_brace: bool,
63    /// Trailing backslash from previous chunk : deferred across chunks so
64    /// `\{{` split across a boundary still emits a literal opener.
65    pending_escape: bool,
66    /// Trailing `\` + `{` from previous chunk : deferred across chunks so
67    /// a `\{` split across a boundary still resolves as an escape pair.
68    pending_escape_brace: bool,
69    /// Configurable delimiter syntax.
70    delimiters: TemplateDelimiters,
71}
72
73impl StreamingExpand {
74    /// Create with env vars and optional explicit overrides.
75    /// Overrides take precedence over env vars.
76    pub fn new(overrides: &[(String, String)], env: &HashMap<String, String>) -> Self {
77        Self {
78            buffer: Vec::with_capacity(256),
79            overrides: overrides.iter().cloned().collect(),
80            env: env.clone(),
81            vars: HashMap::new(),
82            call_resolver: None,
83            in_placeholder: false,
84            pending_brace: false,
85            pending_close_brace: false,
86            pending_escape: false,
87            pending_escape_brace: false,
88            delimiters: TemplateDelimiters::default(),
89        }
90    }
91
92    /// Create with env vars, structured variables, and optional explicit overrides.
93    /// Enables key-path evaluation in template tags (e.g., `{{ pkg.package.name }}`).
94    pub fn with_vars(mut self, vars: &HashMap<String, oxdock_parser::Value>) -> Self {
95        self.vars = vars.clone();
96        self
97    }
98
99    /// Enable `{{ MODULE::FUNC(args) }}` calls, dispatched through `resolver`.
100    /// Args are `$var.path` references, string, int, float, and bool
101    /// literals, or `{key: value}` and `[item]` literals nesting those
102    /// same shapes. Unknown functions and bad arity fail strict at expansion.
103    pub fn with_call_resolver(mut self, resolver: PlaceholderCall) -> Self {
104        self.call_resolver = Some(resolver);
105        self
106    }
107
108    /// Process a chunk of input bytes, writing expanded output to `out`.
109    /// Returns early on empty input to preserve pending boundary state.
110    pub fn process_bytes(&mut self, input: &[u8], out: &mut Vec<u8>) -> DiagnosticResult<usize> {
111        if input.is_empty() {
112            return Ok(0);
113        }
114
115        let start_len = out.len();
116        let mut i = 0;
117
118        // Handle pending close brace from previous chunk
119        if self.pending_close_brace {
120            self.pending_close_brace = false;
121            if input[0] == self.delimiters.close[1] {
122                // Confirmed close delimiter across boundary : extract key, lookup, emit
123                let key = extract_key(&self.buffer);
124                let value = lookup(
125                    &key,
126                    &self.overrides,
127                    &self.env,
128                    &self.vars,
129                    self.call_resolver.as_ref(),
130                )?;
131                out.extend_from_slice(value.as_bytes());
132                self.buffer.clear();
133                self.in_placeholder = false;
134                i = self.delimiters.close.len() - 1; // Skip input[0] (the second byte)
135            } else {
136                // Lone closing byte : treat as literal part of key
137                // Push it to buffer, then let scan_placeholder process input[0]
138                self.buffer.push(self.delimiters.close[0]);
139                i = 0; // Do NOT skip input[0]: let scan_placeholder handle it
140            }
141        }
142
143        // Handle pending open brace from previous chunk
144        if self.pending_brace {
145            self.pending_brace = false;
146            if input[0] == self.delimiters.open[1] {
147                // Confirmed `{{` across boundary : enter PlaceholderScan
148                self.in_placeholder = true;
149                self.buffer.clear();
150                i = 1; // Skip the second open byte
151            } else {
152                // Single open byte was just a literal : flush it
153                out.push(self.delimiters.open[0]);
154            }
155        }
156
157        // Handle pending escape pair from previous chunk: a trailing `\{`
158        // combines with a leading `{` into a literal opener. Anything
159        // else means both bytes were literal; re-emit them, then let the
160        // scan below handle this chunk from the start.
161        if self.pending_escape_brace {
162            self.pending_escape_brace = false;
163            if !input.is_empty() && input[0] == self.delimiters.open[1] {
164                out.extend_from_slice(b"{{");
165                i = 1;
166            } else {
167                out.push(b'\\');
168                out.push(self.delimiters.open[0]);
169            }
170        }
171
172        // Handle pending escape from previous chunk: a lone trailing `\`
173        // combines with a leading `{{` into a literal opener, or with a
174        // leading `\` into a literal backslash (the pair is complete, so
175        // whatever follows processes normally). A lone trailing `{`
176        // cannot decide yet, so it joins the deferred pair above.
177        if self.pending_escape {
178            self.pending_escape = false;
179            if input.len() >= 2 && input[0] == b'{' && input[1] == b'{' {
180                out.extend_from_slice(b"{{");
181                i = 2;
182            } else if input.len() == 1 && input[0] == self.delimiters.open[0] {
183                self.pending_escape_brace = true;
184                i = 1;
185            } else if !input.is_empty() && input[0] == b'\\' {
186                out.push(b'\\');
187                i = 1;
188            } else {
189                // Not an escape : the backslash was literal; reprocess
190                // this chunk from the start (a lone `{` still defers via
191                // the pending_brace path below).
192                out.push(b'\\');
193            }
194        }
195
196        if self.in_placeholder {
197            // We're inside a placeholder : scan for closing delimiter
198            i = self.scan_placeholder(input, i, out)?;
199        }
200
201        // Normal state : scan for opening byte or flush literals
202        while i < input.len() {
203            if input[i] == b'\\' {
204                if i + 2 < input.len() && input[i + 1] == b'{' && input[i + 2] == b'{' {
205                    // Escaped opener : emit a literal `{{`, consume all three
206                    out.extend_from_slice(b"{{");
207                    i += 3;
208                } else if i + 2 == input.len() && input[i + 1] == self.delimiters.open[0] {
209                    // `\{` ends the chunk : defer the pair; the next
210                    // chunk decides literal `{{` vs literal `\` + `{`.
211                    self.pending_escape_brace = true;
212                    i += 2;
213                } else if i + 1 < input.len() && input[i + 1] == b'\\' {
214                    // Escaped backslash : emit one `\`, consume both (this
215                    // keeps `\\{{ ... }}` expanding, matching the lenient
216                    // interpolator used for command arguments)
217                    out.push(b'\\');
218                    i += 2;
219                } else if i + 1 == input.len() {
220                    // Trailing backslash : defer across the chunk boundary
221                    self.pending_escape = true;
222                    i += 1;
223                } else {
224                    // Ordinary backslash : literal, reprocess what follows
225                    out.push(b'\\');
226                    i += 1;
227                }
228            } else if input[i] == self.delimiters.open[0] {
229                if i + 1 < input.len() && input[i + 1] == self.delimiters.open[1] {
230                    // Found open delimiter : enter PlaceholderScan
231                    self.in_placeholder = true;
232                    self.buffer.clear();
233                    i += 2;
234                    i = self.scan_placeholder(input, i, out)?;
235                } else if i + 1 == input.len() {
236                    // Opening byte is the LAST byte of chunk : defer
237                    self.pending_brace = true;
238                    i += 1;
239                } else {
240                    // Single opening byte in the middle : flush as literal
241                    out.push(self.delimiters.open[0]);
242                    i += 1;
243                }
244            } else {
245                // Flush literal bytes until we find an opening byte, a
246                // backslash (potential `\{{` escape), or end of chunk
247                let start = i;
248                while i < input.len() && input[i] != self.delimiters.open[0] && input[i] != b'\\' {
249                    i += 1;
250                }
251                out.extend_from_slice(&input[start..i]);
252            }
253        }
254
255        Ok(out.len() - start_len)
256    }
257
258    /// Flush remaining buffer. Incomplete placeholders are treated as literals.
259    pub fn flush(mut self, out: &mut Vec<u8>) -> DiagnosticResult<()> {
260        // Emit deferred closing byte if present
261        if self.pending_close_brace {
262            self.buffer.push(self.delimiters.close[0]);
263            self.pending_close_brace = false;
264        }
265        // Emit deferred opening byte if present
266        if self.pending_brace {
267            out.push(self.delimiters.open[0]);
268            self.pending_brace = false;
269        }
270        // Emit deferred backslash if present
271        if self.pending_escape {
272            out.push(b'\\');
273            self.pending_escape = false;
274        }
275        // Emit deferred escape pair if present
276        if self.pending_escape_brace {
277            out.push(b'\\');
278            out.push(self.delimiters.open[0]);
279            self.pending_escape_brace = false;
280        }
281        // If inside placeholder, emit open delimiter prefix ONCE before buffer
282        if self.in_placeholder {
283            out.extend_from_slice(self.delimiters.open);
284            self.in_placeholder = false;
285        }
286        // Flush remaining buffer as literal text
287        out.extend_from_slice(&self.buffer);
288        self.buffer.clear();
289        Ok(())
290    }
291
292    /// Process a complete string (convenience for short command arguments).
293    pub fn expand_string(self, input: &str) -> DiagnosticResult<String> {
294        let mut out = Vec::with_capacity(input.len());
295        let mut expander = self;
296        expander.process_bytes(input.as_bytes(), &mut out)?;
297        expander.flush(&mut out)?;
298        Ok(String::from_utf8(out).unwrap_or_default())
299    }
300
301    /// Scan for closing delimiter starting at position `i`.
302    /// Returns the next position to process after the placeholder.
303    fn scan_placeholder(
304        &mut self,
305        input: &[u8],
306        mut i: usize,
307        out: &mut Vec<u8>,
308    ) -> DiagnosticResult<usize> {
309        while i < input.len() {
310            if input[i] == self.delimiters.close[0] {
311                if i + 1 < input.len() && input[i + 1] == self.delimiters.close[1] {
312                    // Found closing delimiter : extract key, lookup, emit expansion
313                    let key = extract_key(&self.buffer);
314                    let value = lookup(
315                        &key,
316                        &self.overrides,
317                        &self.env,
318                        &self.vars,
319                        self.call_resolver.as_ref(),
320                    )?;
321                    out.extend_from_slice(value.as_bytes());
322                    self.buffer.clear();
323                    self.in_placeholder = false;
324                    return Ok(i + 2);
325                }
326                if i + 1 == input.len() {
327                    // Closing byte is the LAST byte : defer to next chunk
328                    self.pending_close_brace = true;
329                    return Ok(i + 1);
330                }
331            }
332            self.buffer.push(input[i]);
333            i += 1;
334
335            // Buffer limit exceeded : flush as literal
336            if self.buffer.len() > MAX_PLACEHOLDER_SCAN {
337                out.extend_from_slice(self.delimiters.open);
338                out.extend_from_slice(&self.buffer);
339                self.buffer.clear();
340                self.in_placeholder = false;
341                return Ok(i);
342            }
343        }
344        Ok(i)
345    }
346}
347
348/// Extract and trim key from buffer content (the bytes between delimiters).
349fn extract_key(buffer: &[u8]) -> String {
350    String::from_utf8_lossy(buffer).trim().to_string()
351}
352
353/// Lookup a key in overrides and env, stripping namespace prefixes.
354///
355/// Strict resolution contract:
356/// - `{{ KEY }}` (bare) → overrides only
357/// - `{{ env:KEY }}` → overrides then env
358/// - `{{ $var }}` → script vars
359/// - `{{ $var.field }}` → script var key-path
360/// - `{{ MODULE::FUNC(args) }}` → placeholder call via `calls`
361///
362/// All missing or invalid references return an error.
363fn lookup(
364    raw_key: &str,
365    overrides: &HashMap<String, String>,
366    env: &HashMap<String, String>,
367    vars: &HashMap<String, oxdock_parser::Value>,
368    calls: Option<&PlaceholderCall>,
369) -> DiagnosticResult<String> {
370    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key, split_var_path};
371    let key = raw_key.trim();
372
373    // 1. Explicit overrides (command-level CLI flags: KEY=val)
374    if let Some(val) = overrides.get(key) {
375        return Ok(val.clone());
376    }
377
378    // Shapes below come from the single template owner: this keeps
379    // its own order (overrides first), sources, and errors.
380    match classify_placeholder_key(key) {
381        // 2. Environment variables: must be prefixed with "env:"
382        PlaceholderKey::Env(env_key) => {
383            // Trim once up front like the static gate and the
384            // script-engine expansion, so `{{ env: FOO }}` looks up
385            // `FOO` (never the padded spelling) on every layer.
386            let env_key = env_key.trim();
387            // Empty names bail explicitly (same message as the miss
388            // below) instead of relying on the lookup miss alone.
389            if env_key.is_empty() {
390                return Err(expand_diag::undefined_env_var("", false));
391            }
392            if let Some(val) = overrides.get(env_key).or_else(|| env.get(env_key)) {
393                return Ok(val.clone());
394            }
395            let suggest_script_var = vars.contains_key(env_key);
396            return Err(expand_diag::undefined_env_var(env_key, suggest_script_var));
397        }
398
399        // 3. Script variables: must be prefixed with "$". Path split
400        // through the single template owner; dotted paths traverse
401        // strictly, plain names read directly.
402        PlaceholderKey::Dollar(rest) => {
403            let parts = split_var_path(rest);
404            if parts.len() == 1 {
405                if let Some(val) = vars.get(&parts[0]) {
406                    return format_value_for_string(val);
407                }
408                let suggest = if env.contains_key(rest) {
409                    Some(expand_diag::ScriptSuggest::Env)
410                } else if overrides.contains_key(rest) {
411                    Some(expand_diag::ScriptSuggest::StepOverride)
412                } else {
413                    None
414                };
415                return Err(expand_diag::undefined_script_var(rest, suggest));
416            }
417            return resolve_key_path_strict(&parts, vars);
418        }
419
420        // 4. Placeholder calls: `MODULE::FUNC(args)` dispatches through
421        // the registered resolver. Without one, the shape falls through
422        // to the invalid placeholder error below. Bare heads are not
423        // resolvable here: they fail as invalid placeholders, never as
424        // missing keys.
425        PlaceholderKey::Call(call) => {
426            let Some(module) = call.module else {
427                // Bare `FUNC(...)` has no registry entry in override
428                // expansion: explicit invalid-format error, never silent
429                // fallthrough.
430                return Err(expand_diag::invalid_placeholder_format(key));
431            };
432            let (name, args_raw) = (call.name, call.args_raw);
433            let Some(resolver) = calls else {
434                return Err(expand_diag::call_without_registry(module, name));
435            };
436            let args_src = oxdock_parser::template::split_placeholder_args(args_raw);
437            let mut args = Vec::with_capacity(args_src.len());
438            for src in args_src {
439                args.push(resolve_call_arg(&src, vars)?);
440            }
441            let result = resolver(module, name, args).map_err(expand_diag::from_anyhow)?;
442            return format_value_for_string(&result);
443        }
444
445        // 5. Unprefixed key: could be a missing step override or invalid
446        // syntax. `script_env:` has no meaning in this context: it reads
447        // as invalid exactly like any other non-shape. Qualified CONST
448        // shapes never resolve here (no CONST store) and fall through
449        // to the invalid-format error below. Bare idents (`Var` and
450        // `Bare`) name missing overrides, exactly as before.
451        // `$ALIAS::NAME` is invalid here like everywhere: the split
452        // lives in the template owner.
453        PlaceholderKey::DollarQualified { .. } => {
454            return Err(expand_diag::invalid_placeholder_format(key));
455        }
456        PlaceholderKey::ConstRef { .. } | PlaceholderKey::KeyPath { .. } => {}
457        PlaceholderKey::Var(name) | PlaceholderKey::Bare(name) => {
458            if !name.is_empty()
459                && name
460                    .chars()
461                    .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
462            {
463                let suggest = if vars.contains_key(name) {
464                    Some(expand_diag::OverrideSuggest::ScriptVar)
465                } else if env.contains_key(name) {
466                    Some(expand_diag::OverrideSuggest::EnvVar)
467                } else {
468                    None
469                };
470                return Err(expand_diag::missing_step_override(name, suggest));
471            }
472        }
473        PlaceholderKey::ScriptEnv(name) => {
474            // Empty names bail explicitly; non-empty `script_env:`
475            // has no meaning here and falls through to the invalid
476            // placeholder error below, as before.
477            if name.trim().is_empty() {
478                return Err(expand_diag::undefined_env_var("", false));
479            }
480        }
481        PlaceholderKey::Empty => {}
482    }
483    Err(expand_diag::invalid_placeholder_format(key))
484}
485
486/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
487/// outside the streaming expander. Returns `None` when the body is not
488/// call shaped, so plain keys keep their own handling. Single grammar
489/// behind every phase: classifies through the shared
490/// `oxdock_parser::template::classify_placeholder_key`, so runtime
491/// dispatch and parse-time qualification can never disagree on what
492/// counts as one call.
493pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
494    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key};
495    let PlaceholderKey::Call(call) = classify_placeholder_key(key.trim()) else {
496        return None;
497    };
498    let module = call.module?.to_string();
499    let args = oxdock_parser::template::split_placeholder_args(call.args_raw);
500    Some((module, call.name.to_string(), args))
501}
502
503/// Maximum nesting for map and list literals in placeholder call
504/// args: the parser's shared argument depth budget.
505const MAX_LITERAL_DEPTH: usize = oxdock_parser::template::MAX_TEMPLATE_ARG_DEPTH;
506
507/// Resolve one placeholder call argument against script variables for
508/// call resolution outside the streaming expander. Same grammar there:
509/// `$var.path`, string, int, float, and bool literals, plus `{...}`
510/// and `[...]` literals holding those shapes nested.
511pub fn resolve_placeholder_arg(
512    src: &str,
513    vars: &HashMap<String, oxdock_parser::Value>,
514) -> DiagnosticResult<oxdock_parser::Value> {
515    resolve_call_arg(src, vars)
516}
517
518/// Resolve one call argument to a value: `$var.path` from vars, a
519/// string, int, float, or bool literal, or a `{key: value}` map or
520/// `[item]` list literal holding those same shapes nested.
521fn resolve_call_arg(
522    src: &str,
523    vars: &HashMap<String, oxdock_parser::Value>,
524) -> DiagnosticResult<oxdock_parser::Value> {
525    resolve_call_value(src, vars, 0)
526}
527
528fn resolve_call_value(
529    src: &str,
530    vars: &HashMap<String, oxdock_parser::Value>,
531    depth: usize,
532) -> DiagnosticResult<oxdock_parser::Value> {
533    use oxdock_parser::template::{
534        ScalarLit, TemplateArg, classify_template_arg, parse_scalar_literal, parse_string_literal,
535        parse_var_path,
536    };
537    if depth > MAX_LITERAL_DEPTH {
538        return Err(expand_diag::call_arg_too_deep(MAX_LITERAL_DEPTH));
539    }
540    match classify_template_arg(src) {
541        TemplateArg::Dollar(rest) => {
542            let Some(parts) = parse_var_path(rest) else {
543                // `$` refs split through the single template owner; the
544                // empty check below keeps the historical
545                // malformed-argument error.
546                return Err(expand_diag::call_arg_empty_var());
547            };
548            return resolve_value_path(&parts, vars);
549        }
550        TemplateArg::Str(literal_src) => {
551            if let Some(literal) = parse_string_literal(literal_src) {
552                return literal.map(oxdock_parser::Value::string);
553            }
554        }
555        TemplateArg::Map(inner) => {
556            return resolve_call_map(inner, vars, depth);
557        }
558        TemplateArg::List(inner) => {
559            return resolve_call_list(inner, vars, depth);
560        }
561        TemplateArg::Scalar(scalar_src) => match parse_scalar_literal(scalar_src) {
562            Some(ScalarLit::Bool(value)) => return Ok(oxdock_parser::Value::bool(value)),
563            Some(ScalarLit::Int(value)) => return Ok(oxdock_parser::Value::int(value)),
564            Some(ScalarLit::Float(value)) => return Ok(oxdock_parser::Value::float(value)),
565            None => {}
566        },
567        // CONST shapes never resolve in override expansion (no CONST
568        // store here); fall through to the invalid-argument error
569        // below like any other unresolvable shape. `$ALIAS::NAME`
570        // is invalid here like everywhere.
571        TemplateArg::DollarQualified { .. } => {}
572        TemplateArg::ConstRef { .. } | TemplateArg::KeyPath { .. } | TemplateArg::Var(_) => {}
573        TemplateArg::Invalid(_) => {}
574    }
575    Err(expand_diag::call_arg_invalid(src))
576}
577
578/// Resolve a `{key: value}` map literal. Keys validate through the
579/// shared key parser; values recurse through [`resolve_call_value`].
580fn resolve_call_map(
581    inner: &str,
582    vars: &HashMap<String, oxdock_parser::Value>,
583    depth: usize,
584) -> DiagnosticResult<oxdock_parser::Value> {
585    use oxdock_parser::template::{parse_map_key, split_map_entry, split_top_level};
586    let mut entries = std::collections::BTreeMap::new();
587    if inner.trim().is_empty() {
588        return Ok(oxdock_parser::Value::map(entries));
589    }
590    for entry in split_top_level(inner, ',') {
591        let Some((key_src, value_src)) = split_map_entry(&entry) else {
592            return Err(expand_diag::map_entry_invalid(&entry));
593        };
594        let key = parse_map_key(&key_src)?;
595        if entries.contains_key(&key) {
596            return Err(expand_diag::map_duplicate_key(&key));
597        }
598        let value = resolve_call_value(&value_src, vars, depth + 1)?;
599        entries.insert(key, value);
600    }
601    Ok(oxdock_parser::Value::map(entries))
602}
603
604/// Resolve a `[item]` list literal, elements recursing through
605/// [`resolve_call_value`].
606fn resolve_call_list(
607    inner: &str,
608    vars: &HashMap<String, oxdock_parser::Value>,
609    depth: usize,
610) -> DiagnosticResult<oxdock_parser::Value> {
611    let mut items = Vec::new();
612    if inner.trim().is_empty() {
613        return Ok(oxdock_parser::Value::list(items));
614    }
615    for item in oxdock_parser::template::split_top_level(inner, ',') {
616        items.push(resolve_call_value(&item, vars, depth + 1)?);
617    }
618    Ok(oxdock_parser::Value::list(items))
619}
620
621/// Resolve a dotted path against vars, cloning the value for the caller.
622/// Mirrors `resolve_key_path_strict` but returns the value instead of
623/// its string form so calls receive typed arguments.
624fn resolve_value_path(
625    parts: &[String],
626    vars: &HashMap<String, oxdock_parser::Value>,
627) -> DiagnosticResult<oxdock_parser::Value> {
628    if parts.is_empty() || parts[0].is_empty() {
629        return Err(expand_diag::call_arg_empty_var());
630    }
631    let root_key = parts[0].as_str();
632    let mut current = vars
633        .get(root_key)
634        .ok_or_else(|| expand_diag::undefined_script_var(root_key, None))?
635        .clone();
636    for segment in &parts[1..] {
637        if segment.contains('(') || segment.contains(')') {
638            return Err(expand_diag::call_arg_nested_calls());
639        }
640        if let Some(map) = current.as_map() {
641            current = map
642                .get(segment)
643                .ok_or_else(|| expand_diag::key_path_missing_property(root_key, segment))?
644                .clone();
645        } else if let Some(list) = current.as_list() {
646            let idx: usize = segment
647                .parse()
648                .map_err(|_| expand_diag::key_path_bad_index(root_key, segment))?;
649            current = list
650                .get(idx)
651                .ok_or_else(|| {
652                    expand_diag::key_path_index_out_of_bounds(root_key, idx, list.len())
653                })?
654                .clone();
655        } else {
656            return Err(expand_diag::key_path_on_primitive(root_key, segment));
657        }
658    }
659    Ok(current)
660}
661
662/// Resolve nested key-paths against the vars map.
663///
664/// Fails explicitly on missing object keys, out-of-bounds array indices,
665/// or type mismatches (e.g. trying to access a property on a primitive).
666fn resolve_key_path_strict(
667    parts: &[String],
668    vars: &HashMap<String, oxdock_parser::Value>,
669) -> DiagnosticResult<String> {
670    let root_key = parts[0].as_str();
671    let mut current = vars
672        .get(root_key)
673        .ok_or_else(|| expand_diag::undefined_script_var(root_key, None))?;
674
675    for segment in &parts[1..] {
676        if let Some(map) = current.as_map() {
677            current = map
678                .get(segment)
679                .ok_or_else(|| expand_diag::key_path_missing_property(root_key, segment))?;
680        } else if let Some(list) = current.as_list() {
681            let idx: usize = segment
682                .parse()
683                .map_err(|_| expand_diag::key_path_bad_index(root_key, segment))?;
684            current = list.get(idx).ok_or_else(|| {
685                expand_diag::key_path_index_out_of_bounds(root_key, idx, list.len())
686            })?;
687        } else {
688            return Err(expand_diag::key_path_on_primitive(root_key, segment));
689        }
690    }
691
692    format_value_for_string(current)
693}
694
695/// Format a Value as a string for inline interpolation.
696/// Render a script value as inline text: the single renderer behind
697/// placeholder expansion everywhere (streaming file templates and
698/// engine string expansion alike), so one value renders one way in
699/// every context. Pipes are refused: they carry streams between
700/// steps, not text, and silently rendering a handle hides a bug.
701///
702/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
703/// `f64` already produces the shortest round-trip decimal (Ryū since
704/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
705/// `3.140000`) with no extra dependency.
706pub fn format_value_for_string(val: &oxdock_parser::Value) -> DiagnosticResult<String> {
707    if let Some(s) = val.as_str() {
708        return Ok(s.to_string());
709    }
710    if let Some(i) = val.as_i64() {
711        return Ok(i.to_string());
712    }
713    if let Some(f) = val.as_f64() {
714        return Ok(f.to_string());
715    }
716    if let Some(b) = val.as_bool() {
717        return Ok(b.to_string());
718    }
719    if val.as_pipe_handle().is_some() {
720        return Err(expand_diag::render_pipe());
721    }
722    if val.as_semaphore().is_some() {
723        return Err(expand_diag::render_semaphore());
724    }
725    if val.as_permit().is_some() {
726        return Err(expand_diag::render_permit());
727    }
728    if let Some(d) = val.as_duration() {
729        return Ok(oxdock_parser::command::format_duration(&d));
730    }
731    if let Some(p) = val.as_path() {
732        return Ok(p.to_string_lossy().to_string());
733    }
734    if let Some(items) = val.as_list() {
735        let parts: Vec<String> = items
736            .iter()
737            .map(format_value_for_string)
738            .collect::<DiagnosticResult<_>>()?;
739        return Ok(parts.join(" "));
740    }
741    if let Some(map) = val.as_map() {
742        let mut parts = Vec::with_capacity(map.len());
743        for (k, v) in map.iter() {
744            parts.push(format!("\"{}\": {}", k, format_value_for_string(v)?));
745        }
746        return Ok(parts.join(", "));
747    }
748    if let Some(id) = val.as_handle() {
749        return Ok(format!("task#{}", id));
750    }
751    Ok(format!("{}", val))
752}
753
754// Legacy functions for backward compatibility
755
756pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
757where
758    F: FnMut(&str) -> Option<String>,
759{
760    let mut out = String::with_capacity(input.len());
761    let mut chars = input.chars().peekable();
762    while let Some(c) = chars.next() {
763        if c == '{' {
764            if let Some(&'{') = chars.peek() {
765                chars.next(); // consume second '{'
766                let mut content = String::new();
767                let mut closed = false;
768                // Look ahead for closing }}
769                let mut inner_chars = chars.clone();
770                while let Some(ch) = inner_chars.next() {
771                    if ch == '}'
772                        && let Some(&'}') = inner_chars.peek()
773                    {
774                        closed = true;
775                        break;
776                    }
777                    content.push(ch);
778                }
779
780                if closed {
781                    // Advance main iterator past content and closing braces.
782                    // Count chars, not bytes: content may contain multi-byte
783                    // UTF-8 (e.g. non-ASCII placeholder names).
784                    for _ in 0..content.chars().count() {
785                        chars.next();
786                    }
787                    chars.next(); // first }
788                    chars.next(); // second }
789
790                    let key = content.trim();
791                    if !key.is_empty() {
792                        out.push_str(&lookup_fn(key).unwrap_or_default());
793                    }
794                } else {
795                    out.push('{');
796                    out.push('{');
797                }
798            } else {
799                out.push('{');
800            }
801        } else {
802            out.push(c);
803        }
804    }
805    out
806}
807
808pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
809    expand_with_lookup(input, |name| {
810        if let Some(key) = name.strip_prefix("env:") {
811            script_envs
812                .get(key)
813                .cloned()
814                .or_else(|| std::env::var(key).ok())
815        } else {
816            None
817        }
818    })
819}
820
821pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
822    expand_with_lookup(input, |name| {
823        if let Some(key) = name.strip_prefix("env:") {
824            ctx.envs().get(key).cloned()
825        } else {
826            None
827        }
828    })
829}
830
831#[cfg(test)]
832mod tests {
833    use super::*;
834    use anyhow::{anyhow, bail};
835    use std::collections::HashMap;
836
837    #[test]
838    fn basic_expansion() {
839        let mut env = HashMap::new();
840        env.insert("NAME".into(), "World".into());
841        let expander = StreamingExpand::new(&[], &env);
842        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
843        assert_eq!(result, "Hello World");
844    }
845
846    #[test]
847    fn multiple_vars() {
848        let mut env = HashMap::new();
849        env.insert("A".into(), "X".into());
850        env.insert("B".into(), "Y".into());
851        let expander = StreamingExpand::new(&[], &env);
852        let result = expander
853            .expand_string("{{ env:A }} and {{ env:B }}")
854            .unwrap();
855        assert_eq!(result, "X and Y");
856    }
857
858    #[test]
859    fn missing_var() {
860        let env = HashMap::new();
861        let expander = StreamingExpand::new(&[], &env);
862        let result = expander.expand_string("{{ env:MISSING }}");
863        assert!(result.is_err());
864        assert!(
865            result
866                .unwrap_err()
867                .to_string()
868                .contains("undefined environment variable"),
869            "error should mention undefined environment variable"
870        );
871    }
872
873    #[test]
874    fn spaced_env_name_resolves_trimmed() {
875        // `{{ env: FOO }}` looks up `FOO` on every layer: the lookup
876        // trims up front like the static gate and the script engine,
877        // instead of missing on the padded spelling.
878        let mut env = HashMap::new();
879        env.insert("FOO".into(), "bar".into());
880        let expander = StreamingExpand::new(&[], &env);
881        assert_eq!(expander.expand_string("{{ env: FOO }}").unwrap(), "bar");
882    }
883
884    #[test]
885    fn empty_env_names_bail() {
886        // Empty `env:` / `script_env:` names never interpolate empty:
887        // every layer rejects them, matching the static gate and the
888        // script-engine expansion.
889        let env = HashMap::new();
890        for text in ["{{ env: }}", "{{ script_env: }}", "{{ script_env:   }}"] {
891            let expander = StreamingExpand::new(&[], &env);
892            let result = expander.expand_string(text);
893            assert!(result.is_err(), "{text:?} must fail");
894        }
895    }
896
897    #[test]
898    fn no_placeholders() {
899        let env = HashMap::new();
900        let expander = StreamingExpand::new(&[], &env);
901        let result = expander.expand_string("plain text").unwrap();
902        assert_eq!(result, "plain text");
903    }
904
905    #[test]
906    fn empty_input() {
907        let env = HashMap::new();
908        let expander = StreamingExpand::new(&[], &env);
909        let result = expander.expand_string("").unwrap();
910        assert_eq!(result, "");
911    }
912
913    #[test]
914    fn override_precedence() {
915        let mut env = HashMap::new();
916        env.insert("KEY".into(), "envval".into());
917        let overrides = vec![("KEY".into(), "override".into())];
918        let expander = StreamingExpand::new(&overrides, &env);
919        let result = expander.expand_string("{{ env:KEY }}").unwrap();
920        assert_eq!(result, "override");
921    }
922
923    #[test]
924    fn override_with_namespace() {
925        let mut env = HashMap::new();
926        env.insert("CRATE".into(), "envval".into());
927        let overrides = vec![("CRATE".into(), "override".into())];
928        let expander = StreamingExpand::new(&overrides, &env);
929        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
930        assert_eq!(result, "override");
931    }
932
933    #[test]
934    fn override_raw_key_match() {
935        let mut env = HashMap::new();
936        env.insert("CRATE".into(), "envval".into());
937        let overrides = vec![("env:CRATE".into(), "override".into())];
938        let expander = StreamingExpand::new(&overrides, &env);
939        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
940        assert_eq!(result, "override");
941    }
942
943    #[test]
944    fn unclosed_placeholder() {
945        let env = HashMap::new();
946        let expander = StreamingExpand::new(&[], &env);
947        let result = expander.expand_string("{{ env:KEY").unwrap();
948        assert_eq!(result, "{{ env:KEY");
949    }
950
951    #[test]
952    fn unclosed_with_prefix() {
953        let env = HashMap::new();
954        let expander = StreamingExpand::new(&[], &env);
955        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
956        assert_eq!(result, "Hello {{ env:KEY");
957    }
958
959    #[test]
960    fn buffer_limit_exceeded() {
961        let env = HashMap::new();
962        let expander = StreamingExpand::new(&[], &env);
963        // Create input with `{{` followed by >1024 bytes without `}}`
964        let mut input = b"{{ ".to_vec();
965        input.extend(std::iter::repeat_n(b'x', 2000));
966        let result = expander
967            .expand_string(&String::from_utf8_lossy(&input))
968            .unwrap();
969        // Should flush as literal with `{{` prefix
970        assert!(result.starts_with("{{ "));
971        assert!(result.len() > 1024);
972    }
973
974    #[test]
975    fn escaped_opener_emits_literal() {
976        let mut env = HashMap::new();
977        env.insert("PROJECT".into(), "OxDock".into());
978        let expander = StreamingExpand::new(&[], &env);
979        let result = expander
980            .expand_string("Built with \\{{ env:PROJECT }}")
981            .unwrap();
982        assert_eq!(result, "Built with {{ env:PROJECT }}");
983    }
984
985    /// Stub resolver echoing `upper` over one string arg, for call tests.
986    fn shout_resolver() -> PlaceholderCall {
987        Arc::new(|module, func, args| {
988            if module == "T" && func == "SHOUT" && args.len() == 1 {
989                let s = args[0]
990                    .as_str()
991                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
992                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
993            }
994            bail!("unknown placeholder function '{module}::{func}'")
995        })
996    }
997
998    #[test]
999    fn placeholder_call_with_var_arg() {
1000        let env = HashMap::new();
1001        let mut vars = HashMap::new();
1002        vars.insert(
1003            "who".to_string(),
1004            oxdock_parser::Value::string("bob".to_string()),
1005        );
1006        let expander = StreamingExpand::new(&[], &env)
1007            .with_vars(&vars)
1008            .with_call_resolver(shout_resolver());
1009        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1010        assert_eq!(result, "hi BOB!");
1011    }
1012
1013    #[test]
1014    fn placeholder_call_with_literal_args() {
1015        let env = HashMap::new();
1016        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1017        let result = expander
1018            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1019            .unwrap();
1020        assert_eq!(result, "BOB ANN");
1021    }
1022
1023    #[test]
1024    fn placeholder_call_output_stays_literal() {
1025        // Call output containing `{{ }}` is terminal text, never re-expanded.
1026        let env = HashMap::new();
1027        let mut vars = HashMap::new();
1028        vars.insert(
1029            "any".to_string(),
1030            oxdock_parser::Value::string("v".to_string()),
1031        );
1032        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1033            Ok(oxdock_parser::Value::string(
1034                "x {{ env:NOPE }} y".to_string(),
1035            ))
1036        });
1037        let expander = StreamingExpand::new(&[], &env)
1038            .with_vars(&vars)
1039            .with_call_resolver(resolver);
1040        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1041        assert_eq!(result, "x {{ env:NOPE }} y");
1042    }
1043
1044    #[test]
1045    fn placeholder_call_unknown_function_fails() {
1046        let env = HashMap::new();
1047        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1048        let result = expander.expand_string("{{ T::NOPE($x) }}");
1049        assert!(result.is_err());
1050    }
1051
1052    #[test]
1053    fn placeholder_call_without_resolver_fails() {
1054        let env = HashMap::new();
1055        let expander = StreamingExpand::new(&[], &env);
1056        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1057        assert!(result.is_err());
1058    }
1059
1060    #[test]
1061    fn escaped_opener_across_chunks() {
1062        let mut env = HashMap::new();
1063        env.insert("PROJECT".into(), "OxDock".into());
1064        let mut expander = StreamingExpand::new(&[], &env);
1065        let mut out = Vec::new();
1066
1067        // Split `\` / `{{ env:PROJECT }}` across chunks
1068        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1069        expander
1070            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1071            .unwrap();
1072        expander.flush(&mut out).unwrap();
1073
1074        assert_eq!(
1075            String::from_utf8_lossy(&out),
1076            "Built with {{ env:PROJECT }}"
1077        );
1078    }
1079
1080    #[test]
1081    fn double_backslash_then_placeholder_expands() {
1082        let mut env = HashMap::new();
1083        env.insert("PROJECT".into(), "OxDock".into());
1084        let expander = StreamingExpand::new(&[], &env);
1085        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1086        assert_eq!(result, "\\OxDock");
1087    }
1088
1089    #[test]
1090    fn trailing_backslash_flushes_literal() {
1091        let env = HashMap::new();
1092        let expander = StreamingExpand::new(&[], &env);
1093        let result = expander.expand_string("end\\").unwrap();
1094        assert_eq!(result, "end\\");
1095    }
1096
1097    #[test]
1098    fn backslash_before_other_text_is_literal() {
1099        let env = HashMap::new();
1100        let expander = StreamingExpand::new(&[], &env);
1101        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1102        assert_eq!(result, "a\\b \\{ once }");
1103    }
1104
1105    #[test]
1106    fn escaped_pair_split_across_chunks() {
1107        let mut env = HashMap::new();
1108        env.insert("PROJECT".into(), "OxDock".into());
1109        let mut expander = StreamingExpand::new(&[], &env);
1110        let mut out = Vec::new();
1111
1112        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1113        // completes to one backslash, then the placeholder expands
1114        expander.process_bytes(b"\\", &mut out).unwrap();
1115        expander
1116            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1117            .unwrap();
1118        expander.flush(&mut out).unwrap();
1119
1120        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1121    }
1122
1123    #[test]
1124    fn partial_across_chunks() {
1125        let mut env = HashMap::new();
1126        env.insert("NAME".into(), "World".into());
1127        let mut expander = StreamingExpand::new(&[], &env);
1128        let mut out = Vec::new();
1129
1130        // Split `{{ env:NA` / `ME }}` across chunks
1131        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1132        expander.process_bytes(b"ME }}", &mut out).unwrap();
1133        expander.flush(&mut out).unwrap();
1134
1135        assert_eq!(String::from_utf8_lossy(&out), "World");
1136    }
1137
1138    #[test]
1139    fn trailing_brace_across_chunks() {
1140        let mut env = HashMap::new();
1141        env.insert("NAME".into(), "World".into());
1142        let mut expander = StreamingExpand::new(&[], &env);
1143        let mut out = Vec::new();
1144
1145        // Split `...{` / `{env:NAME}}` across chunks
1146        expander.process_bytes(b"...", &mut out).unwrap();
1147        expander.process_bytes(b"{", &mut out).unwrap();
1148        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1149        expander.flush(&mut out).unwrap();
1150
1151        assert_eq!(String::from_utf8_lossy(&out), "...World");
1152    }
1153
1154    #[test]
1155    fn trailing_brace_at_eof() {
1156        let env = HashMap::new();
1157        let mut expander = StreamingExpand::new(&[], &env);
1158        let mut out = Vec::new();
1159
1160        expander.process_bytes(b"hello{", &mut out).unwrap();
1161        expander.flush(&mut out).unwrap();
1162
1163        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1164    }
1165
1166    #[test]
1167    fn immediate_flush_guarantee() {
1168        let env = HashMap::new();
1169        let mut expander = StreamingExpand::new(&[], &env);
1170        let mut out = Vec::new();
1171
1172        // 1MB of plain text with no placeholders
1173        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1174        expander.process_bytes(&input, &mut out).unwrap();
1175        expander.flush(&mut out).unwrap();
1176
1177        assert_eq!(out.len(), 1024 * 1024);
1178    }
1179
1180    #[test]
1181    fn nested_braces() {
1182        let mut env = HashMap::new();
1183        env.insert("KEY{1}".into(), "val".into());
1184        let expander = StreamingExpand::new(&[], &env);
1185        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1186        assert_eq!(result, "val");
1187    }
1188
1189    #[test]
1190    fn split_close_delimiter_across_chunks() {
1191        let mut env = HashMap::new();
1192        env.insert("NAME".into(), "World".into());
1193        let mut expander = StreamingExpand::new(&[], &env);
1194        let mut out = Vec::new();
1195
1196        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1197        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1198        expander.process_bytes(b"}}", &mut out).unwrap();
1199        expander.flush(&mut out).unwrap();
1200
1201        assert_eq!(String::from_utf8_lossy(&out), "World");
1202    }
1203
1204    #[test]
1205    fn split_close_delimiter_with_trailing_content() {
1206        let mut env = HashMap::new();
1207        env.insert("NAME".into(), "World".into());
1208        let mut expander = StreamingExpand::new(&[], &env);
1209        let mut out = Vec::new();
1210
1211        // Split `}}` across chunks with content after
1212        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1213        expander.process_bytes(b"}} rest", &mut out).unwrap();
1214        expander.flush(&mut out).unwrap();
1215
1216        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1217    }
1218
1219    #[test]
1220    fn empty_input_preserves_pending_state() {
1221        let mut env = HashMap::new();
1222        env.insert("NAME".into(), "World".into());
1223        let mut expander = StreamingExpand::new(&[], &env);
1224        let mut out = Vec::new();
1225
1226        // End chunk with closing byte, then empty input, then confirm
1227        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1228        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1229        expander.process_bytes(b"}}", &mut out).unwrap();
1230        expander.flush(&mut out).unwrap();
1231
1232        assert_eq!(String::from_utf8_lossy(&out), "World");
1233    }
1234
1235    #[test]
1236    fn missing_env_var_errors() {
1237        let env = HashMap::new();
1238        let expander = StreamingExpand::new(&[], &env);
1239        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1240        assert!(result.is_err());
1241        let msg = result.unwrap_err().to_string();
1242        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1243        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1244    }
1245
1246    #[test]
1247    fn missing_script_var_errors() {
1248        let env = HashMap::new();
1249        let expander = StreamingExpand::new(&[], &env);
1250        let result = expander.expand_string("{{ $undefined_var }}");
1251        assert!(result.is_err());
1252        let msg = result.unwrap_err().to_string();
1253        assert!(msg.contains("undefined script variable"), "got: {msg}");
1254        assert!(msg.contains("$undefined_var"), "got: {msg}");
1255    }
1256
1257    #[test]
1258    fn missing_key_in_map_errors() {
1259        let mut vars = HashMap::new();
1260        vars.insert(
1261            "cfg".into(),
1262            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1263                "server".into(),
1264                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1265                    "port".into(),
1266                    oxdock_parser::Value::int(8080),
1267                )])),
1268            )])),
1269        );
1270        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1271        let result = expander.expand_string("{{ $cfg.missing_key }}");
1272        assert!(result.is_err());
1273        let msg = result.unwrap_err().to_string();
1274        assert!(
1275            msg.contains("property 'missing_key' not found"),
1276            "got: {msg}"
1277        );
1278    }
1279
1280    #[test]
1281    fn out_of_bounds_array_index_errors() {
1282        let mut vars = HashMap::new();
1283        vars.insert(
1284            "arr".into(),
1285            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1286        );
1287        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1288        let result = expander.expand_string("{{ $arr.5 }}");
1289        assert!(result.is_err());
1290        let msg = result.unwrap_err().to_string();
1291        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1292    }
1293
1294    #[test]
1295    fn type_mismatch_navigation_errors() {
1296        let mut vars = HashMap::new();
1297        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1298        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1299        let result = expander.expand_string("{{ $name.sub_field }}");
1300        assert!(result.is_err());
1301        let msg = result.unwrap_err().to_string();
1302        assert!(
1303            msg.contains("cannot access property 'sub_field' on primitive"),
1304            "got: {msg}"
1305        );
1306    }
1307
1308    #[test]
1309    fn unprefixed_identifier_errors() {
1310        let env = HashMap::new();
1311        let expander = StreamingExpand::new(&[], &env);
1312        let result = expander.expand_string("{{ bare_word }}");
1313        assert!(result.is_err());
1314        let msg = result.unwrap_err().to_string();
1315        assert!(msg.contains("missing required step override"), "got: {msg}");
1316    }
1317
1318    // ── Strict namespace isolation tests ─────────────────────────────────────
1319
1320    #[test]
1321    fn script_var_does_not_fall_back_to_env() {
1322        let mut env = HashMap::new();
1323        env.insert("WHO".into(), "from-env".into());
1324        let expander = StreamingExpand::new(&[], &env);
1325        // $WHO queries vars, NOT env : should error even though env has WHO
1326        let result = expander.expand_string("{{ $WHO }}");
1327        assert!(result.is_err());
1328        let msg = result.unwrap_err().to_string();
1329        assert!(msg.contains("undefined script variable"), "got: {msg}");
1330        assert!(
1331            msg.contains("did you mean 'env:WHO'"),
1332            "hint should suggest env: prefix, got: {msg}"
1333        );
1334    }
1335
1336    #[test]
1337    fn env_var_does_not_fall_back_to_vars() {
1338        let mut vars = HashMap::new();
1339        vars.insert(
1340            "HOST".into(),
1341            oxdock_parser::Value::string("from-var".into()),
1342        );
1343        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1344        // env:HOST queries env, NOT vars : should error even though vars has HOST
1345        let result = expander.expand_string("{{ env:HOST }}");
1346        assert!(result.is_err());
1347        let msg = result.unwrap_err().to_string();
1348        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1349        assert!(
1350            msg.contains("did you mean '$HOST'"),
1351            "hint should suggest $ prefix, got: {msg}"
1352        );
1353    }
1354
1355    #[test]
1356    fn step_override_does_not_fall_back_to_vars() {
1357        let mut vars = HashMap::new();
1358        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1359        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1360        // PORT (bare) queries overrides, NOT vars : should error
1361        let result = expander.expand_string("{{ PORT }}");
1362        assert!(result.is_err());
1363        let msg = result.unwrap_err().to_string();
1364        assert!(msg.contains("missing required step override"), "got: {msg}");
1365        assert!(
1366            msg.contains("did you mean '$PORT'"),
1367            "hint should suggest $ prefix, got: {msg}"
1368        );
1369    }
1370
1371    #[test]
1372    fn env_prefix_isolated_from_script_vars() {
1373        let mut vars = HashMap::new();
1374        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1375        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1376        // env:MODE looks in env, not vars : should error
1377        let result = expander.expand_string("{{ env:MODE }}");
1378        assert!(result.is_err());
1379        let msg = result.unwrap_err().to_string();
1380        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1381        assert!(
1382            msg.contains("did you mean '$MODE'"),
1383            "hint should suggest $ prefix, got: {msg}"
1384        );
1385    }
1386
1387    #[test]
1388    fn dollar_prefix_isolated_from_env() {
1389        let mut env = HashMap::new();
1390        env.insert("PORT".into(), "3000".into());
1391        let expander = StreamingExpand::new(&[], &env);
1392        // $PORT looks in vars, not env : should error
1393        let result = expander.expand_string("{{ $PORT }}");
1394        assert!(result.is_err());
1395        let msg = result.unwrap_err().to_string();
1396        assert!(msg.contains("undefined script variable"), "got: {msg}");
1397        assert!(
1398            msg.contains("did you mean 'env:PORT'"),
1399            "hint should suggest env: prefix, got: {msg}"
1400        );
1401    }
1402
1403    #[test]
1404    fn empty_placeholder_errors() {
1405        let expander = StreamingExpand::new(&[], &HashMap::new());
1406        let result = expander.expand_string("{{ }}");
1407        assert!(result.is_err());
1408        let msg = result.unwrap_err().to_string();
1409        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1410    }
1411
1412    #[test]
1413    fn malformed_symbol_placeholder_errors() {
1414        let expander = StreamingExpand::new(&[], &HashMap::new());
1415        let result = expander.expand_string("{{ @invalid! }}");
1416        assert!(result.is_err());
1417        let msg = result.unwrap_err().to_string();
1418        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1419    }
1420
1421    #[test]
1422    fn bare_call_head_fails_as_invalid_placeholder() {
1423        // Directive 3: bare `FUNC(...)` has no registry entry in
1424        // override expansion. The `Call` arm handles `module == None`
1425        // explicitly instead of silently falling through.
1426        let expander = StreamingExpand::new(&[], &HashMap::new());
1427        let result = expander.expand_string("{{ FOO() }}");
1428        assert!(result.is_err());
1429        let msg = result.unwrap_err().to_string();
1430        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1431    }
1432
1433    /// Feed input in fixed-size chunks, then flush: exercises every
1434    /// chunk-boundary alignment for the given split size.
1435    fn render_split(
1436        input: &[u8],
1437        size: usize,
1438        env: &HashMap<String, String>,
1439    ) -> Result<String, anyhow::Error> {
1440        let mut expander = StreamingExpand::new(&[], env);
1441        let mut out = Vec::new();
1442        for chunk in input.chunks(size) {
1443            expander.process_bytes(chunk, &mut out)?;
1444        }
1445        expander.flush(&mut out)?;
1446        Ok(String::from_utf8_lossy(&out).into_owned())
1447    }
1448
1449    #[test]
1450    fn escaped_opener_one_byte_chunks_stays_literal() {
1451        let mut env = HashMap::new();
1452        env.insert("NAME".into(), "World".into());
1453        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1454        // resolve to a literal opener, never an expansion.
1455        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1456        assert_eq!(out, "{{ env:NAME }}");
1457    }
1458
1459    #[test]
1460    fn escaped_opener_two_byte_chunks_stays_literal() {
1461        let mut env = HashMap::new();
1462        env.insert("NAME".into(), "World".into());
1463        // Two-byte splits land `\{` and lone `{` at chunk ends.
1464        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1465        assert_eq!(out, "a{{ env:NAME }}b");
1466    }
1467
1468    #[test]
1469    fn escaped_opener_split_variants_stay_literal() {
1470        let mut env = HashMap::new();
1471        env.insert("NAME".into(), "World".into());
1472        for chunks in [
1473            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1474            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1475            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1476        ] {
1477            let mut expander = StreamingExpand::new(&[], &env);
1478            let mut out = Vec::new();
1479            for chunk in chunks {
1480                expander.process_bytes(chunk, &mut out).unwrap();
1481            }
1482            expander.flush(&mut out).unwrap();
1483            assert_eq!(
1484                String::from_utf8_lossy(&out),
1485                "{{ env:NAME }}",
1486                "chunks must not corrupt the escape"
1487            );
1488        }
1489    }
1490
1491    #[test]
1492    fn plain_opener_split_chunks_still_expands() {
1493        let mut env = HashMap::new();
1494        env.insert("NAME".into(), "World".into());
1495        // The fix must not swallow genuine openers fragmented the
1496        // same way: `{` | `{` opens, then the key resolves.
1497        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1498        assert_eq!(out, "World");
1499    }
1500
1501    #[test]
1502    fn double_backslash_split_chunks_still_expands() {
1503        let mut env = HashMap::new();
1504        env.insert("NAME".into(), "World".into());
1505        // `\\` completes to one backslash; the opener after it expands.
1506        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1507        assert_eq!(out, "\\World");
1508    }
1509
1510    #[test]
1511    fn trailing_escape_brace_flushes_literal() {
1512        let env = HashMap::new();
1513        let expander = StreamingExpand::new(&[], &env);
1514        let result = expander.expand_string("end\\{").unwrap();
1515        assert_eq!(result, "end\\{");
1516    }
1517
1518    // ── Single-pass substitution tests ────────────────────────────────────
1519    // Substituted values are emitted verbatim and never re-scanned for
1520    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1521    // itself contains a placeholder stays literal instead of expanding.
1522
1523    #[test]
1524    fn substituted_override_value_is_not_rescanned() {
1525        let mut env = HashMap::new();
1526        env.insert("OTHER".into(), "world".into());
1527        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1528        let expander = StreamingExpand::new(&overrides, &env);
1529        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1530        assert_eq!(result, "Hello {{ env:OTHER }}");
1531    }
1532
1533    #[test]
1534    fn substituted_env_value_is_not_rescanned() {
1535        let mut env = HashMap::new();
1536        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1537        env.insert("OTHER".into(), "world".into());
1538        let expander = StreamingExpand::new(&[], &env);
1539        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1540        assert_eq!(result, "Hello {{ env:OTHER }}");
1541    }
1542
1543    #[test]
1544    fn substituted_script_var_value_is_not_rescanned() {
1545        let mut vars = HashMap::new();
1546        vars.insert(
1547            "inner".into(),
1548            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1549        );
1550        let mut env = HashMap::new();
1551        env.insert("OTHER".into(), "world".into());
1552        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1553        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1554        assert_eq!(result, "Hello {{ env:OTHER }}");
1555    }
1556
1557    /// Echo resolver returning the debug shape of each argument, so
1558    /// literal parsing asserts on values instead of formatting.
1559    fn shape_resolver() -> PlaceholderCall {
1560        Arc::new(|module, func, args| {
1561            if module == "T" && func == "SHAPE" {
1562                let shape = args
1563                    .iter()
1564                    .map(|arg| arg.type_name().to_string())
1565                    .collect::<Vec<_>>()
1566                    .join(",");
1567                return Ok(oxdock_parser::Value::string(shape));
1568            }
1569            bail!("unknown placeholder function '{module}::{func}'")
1570        })
1571    }
1572
1573    #[test]
1574    fn placeholder_call_with_empty_map_literal() {
1575        let expander =
1576            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1577        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1578        assert_eq!(result, "MAP");
1579    }
1580
1581    #[test]
1582    fn placeholder_call_with_map_and_list_literals() {
1583        let expander =
1584            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1585        let result = expander
1586            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1587            .unwrap();
1588        assert_eq!(result, "MAP,LIST");
1589    }
1590
1591    #[test]
1592    fn placeholder_call_map_commas_nest_inside_literals() {
1593        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1594            let map = args[0].as_map().expect("map");
1595            let format = map
1596                .get("format")
1597                .and_then(|v| v.as_str())
1598                .expect("format string");
1599            Ok(oxdock_parser::Value::string(format.to_string()))
1600        });
1601        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1602        let result = expander
1603            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1604            .unwrap();
1605        assert_eq!(result, "a,b");
1606    }
1607
1608    #[test]
1609    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1610        let mut vars = HashMap::new();
1611        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1612        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1613            let map = args[0].as_map().expect("map");
1614            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1615            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1616            Ok(oxdock_parser::Value::string(format!(
1617                "{depth}:{}",
1618                tags.len()
1619            )))
1620        });
1621        let expander = StreamingExpand::new(&[], &HashMap::new())
1622            .with_vars(&vars)
1623            .with_call_resolver(resolver);
1624        let result = expander
1625            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1626            .unwrap();
1627        assert_eq!(result, "2:2");
1628    }
1629
1630    #[test]
1631    fn placeholder_call_rejects_malformed_literals() {
1632        for bad in [
1633            "{{ T::SHAPE({a}) }}",
1634            "{{ T::SHAPE({a: 1, a: 2}) }}",
1635            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1636            "{{ T::SHAPE([1) }}",
1637            "{{ T::SHAPE({a: 1) }}",
1638        ] {
1639            let expander =
1640                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1641            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1642        }
1643    }
1644
1645    #[test]
1646    fn placeholder_call_rejects_adjacent_string_literals() {
1647        // Missing commas and infix expressions must fail, never merge
1648        // into one string.
1649        for bad in [
1650            "{{ T::SHAPE(\"a\" \"b\") }}",
1651            "{{ T::SHAPE(\"a\" + \"b\") }}",
1652            "{{ T::SHAPE(\"foo\\\") }}",
1653        ] {
1654            let expander =
1655                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1656            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1657        }
1658    }
1659
1660    #[test]
1661    fn placeholder_call_brackets_inside_block_strings_resolve() {
1662        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1663            let first = &args[0];
1664            if let Some(items) = first.as_list() {
1665                return Ok(oxdock_parser::Value::string(
1666                    items[0].as_str().unwrap_or("?").to_string(),
1667                ));
1668            }
1669            if let Some(entries) = first.as_map() {
1670                return Ok(oxdock_parser::Value::string(
1671                    entries
1672                        .get("k")
1673                        .and_then(|v| v.as_str())
1674                        .unwrap_or("?")
1675                        .to_string(),
1676                ));
1677            }
1678            bail!("expected list or map")
1679        });
1680        let list = StreamingExpand::new(&[], &HashMap::new())
1681            .with_call_resolver(resolver.clone())
1682            .expand_string("{{ T::ECHO([\"\"\"a]b\"\"\"]) }}")
1683            .unwrap();
1684        assert_eq!(list, "a]b");
1685        let map = StreamingExpand::new(&[], &HashMap::new())
1686            .with_call_resolver(resolver.clone())
1687            .expand_string("{{ T::ECHO({k: \"\"\"a}b\"\"\"}) }}")
1688            .unwrap();
1689        assert_eq!(map, "a}b");
1690    }
1691
1692    #[test]
1693    fn placeholder_call_single_quotes_match_double_quotes() {
1694        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1695            Ok(oxdock_parser::Value::string(
1696                args.iter()
1697                    .map(|a| a.as_str().unwrap_or("?").to_string())
1698                    .collect::<Vec<_>>()
1699                    .join("|"),
1700            ))
1701        });
1702        for (double, single) in [
1703            ("{{ T::ECHO(\"hi\") }}", "{{ T::ECHO('hi') }}"),
1704            ("{{ T::ECHO(\"a,b\") }}", "{{ T::ECHO('a,b') }}"),
1705            ("{{ T::ECHO({k: \"v\"}) }}", "{{ T::ECHO({k: 'v'}) }}"),
1706            ("{{ T::ECHO({\"k\": \"v\"}) }}", "{{ T::ECHO({'k': 'v'}) }}"),
1707            ("{{ T::ECHO([\"a\"]) }}", "{{ T::ECHO(['a']) }}"),
1708        ] {
1709            let left = StreamingExpand::new(&[], &HashMap::new())
1710                .with_call_resolver(resolver.clone())
1711                .expand_string(double)
1712                .unwrap();
1713            let right = StreamingExpand::new(&[], &HashMap::new())
1714                .with_call_resolver(resolver.clone())
1715                .expand_string(single)
1716                .unwrap();
1717            assert_eq!(
1718                left, right,
1719                "quote style must not matter: {double} vs {single}"
1720            );
1721        }
1722    }
1723
1724    #[test]
1725    fn placeholder_call_triple_quoted_matches_single_line() {
1726        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1727            Ok(oxdock_parser::Value::string(
1728                args[0].as_str().unwrap_or("?").to_string(),
1729            ))
1730        });
1731        let plain = StreamingExpand::new(&[], &HashMap::new())
1732            .with_call_resolver(resolver.clone())
1733            .expand_string("{{ T::ECHO(\"Release installs\") }}")
1734            .unwrap();
1735        let block = StreamingExpand::new(&[], &HashMap::new())
1736            .with_call_resolver(resolver.clone())
1737            .expand_string("{{ T::ECHO(\"\"\"Release installs\"\"\") }}")
1738            .unwrap();
1739        assert_eq!(plain, block);
1740    }
1741}