Skip to main content

oxdock_process/
expand.rs

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