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::Invalid(_) => {
459            return Err(expand_diag::invalid_placeholder_format(key));
460        }
461        PlaceholderKey::Var(name) | PlaceholderKey::Bare(name) => {
462            if !name.is_empty()
463                && name
464                    .chars()
465                    .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
466            {
467                let suggest = if vars.contains_key(name) {
468                    Some(expand_diag::OverrideSuggest::ScriptVar)
469                } else if env.contains_key(name) {
470                    Some(expand_diag::OverrideSuggest::EnvVar)
471                } else {
472                    None
473                };
474                return Err(expand_diag::missing_step_override(name, suggest));
475            }
476        }
477        PlaceholderKey::ScriptEnv(name) => {
478            // Empty names bail explicitly; non-empty `script_env:`
479            // has no meaning here and falls through to the invalid
480            // placeholder error below, as before.
481            if name.trim().is_empty() {
482                return Err(expand_diag::undefined_env_var("", false));
483            }
484        }
485        PlaceholderKey::Empty => {}
486    }
487    Err(expand_diag::invalid_placeholder_format(key))
488}
489
490/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
491/// outside the streaming expander. Returns `None` when the body is not
492/// call shaped, so plain keys keep their own handling. Single grammar
493/// behind every phase: classifies through the shared
494/// `oxdock_parser::template::classify_placeholder_key`, so runtime
495/// dispatch and parse-time qualification can never disagree on what
496/// counts as one call.
497pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
498    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key};
499    let PlaceholderKey::Call(call) = classify_placeholder_key(key.trim()) else {
500        return None;
501    };
502    let module = call.module?.to_string();
503    let args = oxdock_parser::template::split_placeholder_args(call.args_raw);
504    Some((module, call.name.to_string(), args))
505}
506
507/// Maximum nesting for map and list literals in placeholder call
508/// args: the parser's shared argument depth budget.
509const MAX_LITERAL_DEPTH: usize = oxdock_parser::template::MAX_TEMPLATE_ARG_DEPTH;
510
511/// Resolve one placeholder call argument against script variables for
512/// call resolution outside the streaming expander. Same grammar there:
513/// `$var.path`, string, int, float, and bool literals, plus `{...}`
514/// and `[...]` literals holding those shapes nested.
515pub fn resolve_placeholder_arg(
516    src: &str,
517    vars: &HashMap<String, oxdock_parser::Value>,
518) -> DiagnosticResult<oxdock_parser::Value> {
519    resolve_call_arg(src, vars)
520}
521
522/// Resolve one call argument to a value: `$var.path` from vars, a
523/// string, int, float, or bool literal, or a `{key: value}` map or
524/// `[item]` list literal holding those same shapes nested.
525fn resolve_call_arg(
526    src: &str,
527    vars: &HashMap<String, oxdock_parser::Value>,
528) -> DiagnosticResult<oxdock_parser::Value> {
529    resolve_call_value(src, vars, 0)
530}
531
532fn resolve_call_value(
533    src: &str,
534    vars: &HashMap<String, oxdock_parser::Value>,
535    depth: usize,
536) -> DiagnosticResult<oxdock_parser::Value> {
537    use oxdock_parser::template::{
538        ScalarLit, TemplateArg, classify_template_arg, parse_scalar_literal, parse_string_literal,
539        parse_var_path,
540    };
541    if depth > MAX_LITERAL_DEPTH {
542        return Err(expand_diag::call_arg_too_deep(MAX_LITERAL_DEPTH));
543    }
544    match classify_template_arg(src) {
545        TemplateArg::Dollar(rest) => {
546            let Some(parts) = parse_var_path(rest) else {
547                // `$` refs split through the single template owner; the
548                // empty check below keeps the historical
549                // malformed-argument error.
550                return Err(expand_diag::call_arg_empty_var());
551            };
552            return resolve_value_path(&parts, vars);
553        }
554        TemplateArg::Str(literal_src) => {
555            if let Some(literal) = parse_string_literal(literal_src) {
556                return literal.map(oxdock_parser::Value::string);
557            }
558        }
559        TemplateArg::Map(inner) => {
560            return resolve_call_map(inner, vars, depth);
561        }
562        TemplateArg::List(inner) => {
563            return resolve_call_list(inner, vars, depth);
564        }
565        TemplateArg::Scalar(scalar_src) => match parse_scalar_literal(scalar_src) {
566            Some(ScalarLit::Bool(value)) => return Ok(oxdock_parser::Value::bool(value)),
567            Some(ScalarLit::Int(value)) => return Ok(oxdock_parser::Value::int(value)),
568            Some(ScalarLit::Float(value)) => return Ok(oxdock_parser::Value::float(value)),
569            None => {}
570        },
571        // CONST shapes never resolve in override expansion (no CONST
572        // store here); fall through to the invalid-argument error
573        // below like any other unresolvable shape. `$ALIAS::NAME`
574        // is invalid here like everywhere.
575        TemplateArg::DollarQualified { .. } => {}
576        TemplateArg::ConstRef { .. } | TemplateArg::KeyPath { .. } | TemplateArg::Var(_) => {}
577        TemplateArg::Invalid(_) => {}
578    }
579    Err(expand_diag::call_arg_invalid(src))
580}
581
582/// Resolve a `{key: value}` map literal. Keys validate through the
583/// shared key parser; values recurse through [`resolve_call_value`].
584fn resolve_call_map(
585    inner: &str,
586    vars: &HashMap<String, oxdock_parser::Value>,
587    depth: usize,
588) -> DiagnosticResult<oxdock_parser::Value> {
589    use oxdock_parser::template::{parse_map_key, split_map_entry, split_top_level};
590    let mut entries = std::collections::BTreeMap::new();
591    if inner.trim().is_empty() {
592        return Ok(oxdock_parser::Value::map(entries));
593    }
594    for entry in split_top_level(inner, ',') {
595        let Some((key_src, value_src)) = split_map_entry(&entry) else {
596            return Err(expand_diag::map_entry_invalid(&entry));
597        };
598        let key = parse_map_key(&key_src)?;
599        if entries.contains_key(&key) {
600            return Err(expand_diag::map_duplicate_key(&key));
601        }
602        let value = resolve_call_value(&value_src, vars, depth + 1)?;
603        entries.insert(key, value);
604    }
605    Ok(oxdock_parser::Value::map(entries))
606}
607
608/// Resolve a `[item]` list literal, elements recursing through
609/// [`resolve_call_value`].
610fn resolve_call_list(
611    inner: &str,
612    vars: &HashMap<String, oxdock_parser::Value>,
613    depth: usize,
614) -> DiagnosticResult<oxdock_parser::Value> {
615    let mut items = Vec::new();
616    if inner.trim().is_empty() {
617        return Ok(oxdock_parser::Value::list(items));
618    }
619    for item in oxdock_parser::template::split_top_level(inner, ',') {
620        items.push(resolve_call_value(&item, vars, depth + 1)?);
621    }
622    Ok(oxdock_parser::Value::list(items))
623}
624
625/// Resolve a dotted path against vars, cloning the value for the caller.
626/// Mirrors `resolve_key_path_strict` but returns the value instead of
627/// its string form so calls receive typed arguments.
628fn resolve_value_path(
629    parts: &[String],
630    vars: &HashMap<String, oxdock_parser::Value>,
631) -> DiagnosticResult<oxdock_parser::Value> {
632    if parts.is_empty() || parts[0].is_empty() {
633        return Err(expand_diag::call_arg_empty_var());
634    }
635    let root_key = parts[0].as_str();
636    let mut current = vars
637        .get(root_key)
638        .ok_or_else(|| expand_diag::undefined_script_var(root_key, None))?
639        .clone();
640    for segment in &parts[1..] {
641        if segment.contains('(') || segment.contains(')') {
642            return Err(expand_diag::call_arg_nested_calls());
643        }
644        if let Some(map) = current.as_map() {
645            current = map
646                .get(segment)
647                .ok_or_else(|| expand_diag::key_path_missing_property(root_key, segment))?
648                .clone();
649        } else if let Some(list) = current.as_list() {
650            let idx: usize = segment
651                .parse()
652                .map_err(|_| expand_diag::key_path_bad_index(root_key, segment))?;
653            current = list
654                .get(idx)
655                .ok_or_else(|| {
656                    expand_diag::key_path_index_out_of_bounds(root_key, idx, list.len())
657                })?
658                .clone();
659        } else {
660            return Err(expand_diag::key_path_on_primitive(root_key, segment));
661        }
662    }
663    Ok(current)
664}
665
666/// Resolve nested key-paths against the vars map.
667///
668/// Fails explicitly on missing object keys, out-of-bounds array indices,
669/// or type mismatches (e.g. trying to access a property on a primitive).
670fn resolve_key_path_strict(
671    parts: &[String],
672    vars: &HashMap<String, oxdock_parser::Value>,
673) -> DiagnosticResult<String> {
674    let root_key = parts[0].as_str();
675    let mut current = vars
676        .get(root_key)
677        .ok_or_else(|| expand_diag::undefined_script_var(root_key, None))?;
678
679    for segment in &parts[1..] {
680        if let Some(map) = current.as_map() {
681            current = map
682                .get(segment)
683                .ok_or_else(|| expand_diag::key_path_missing_property(root_key, segment))?;
684        } else if let Some(list) = current.as_list() {
685            let idx: usize = segment
686                .parse()
687                .map_err(|_| expand_diag::key_path_bad_index(root_key, segment))?;
688            current = list.get(idx).ok_or_else(|| {
689                expand_diag::key_path_index_out_of_bounds(root_key, idx, list.len())
690            })?;
691        } else {
692            return Err(expand_diag::key_path_on_primitive(root_key, segment));
693        }
694    }
695
696    format_value_for_string(current)
697}
698
699/// Format a Value as a string for inline interpolation.
700/// Render a script value as inline text: the single renderer behind
701/// placeholder expansion everywhere (streaming file templates and
702/// engine string expansion alike), so one value renders one way in
703/// every context. Pipes are refused: they carry streams between
704/// steps, not text, and silently rendering a handle hides a bug.
705///
706/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
707/// `f64` already produces the shortest round-trip decimal (Ryū since
708/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
709/// `3.140000`) with no extra dependency.
710pub fn format_value_for_string(val: &oxdock_parser::Value) -> DiagnosticResult<String> {
711    if let Some(s) = val.as_str() {
712        return Ok(s.to_string());
713    }
714    if let Some(i) = val.as_i64() {
715        return Ok(i.to_string());
716    }
717    if let Some(f) = val.as_f64() {
718        return Ok(f.to_string());
719    }
720    if let Some(b) = val.as_bool() {
721        return Ok(b.to_string());
722    }
723    if val.as_pipe_handle().is_some() {
724        return Err(expand_diag::render_pipe());
725    }
726    if val.as_semaphore().is_some() {
727        return Err(expand_diag::render_semaphore());
728    }
729    if val.as_permit().is_some() {
730        return Err(expand_diag::render_permit());
731    }
732    if let Some(d) = val.as_duration() {
733        return Ok(oxdock_parser::command::format_duration(&d));
734    }
735    if let Some(p) = val.as_path() {
736        return Ok(p.to_string_lossy().to_string());
737    }
738    if let Some(items) = val.as_list() {
739        let parts: Vec<String> = items
740            .iter()
741            .map(format_value_for_string)
742            .collect::<DiagnosticResult<_>>()?;
743        return Ok(parts.join(" "));
744    }
745    if let Some(map) = val.as_map() {
746        let mut parts = Vec::with_capacity(map.len());
747        for (k, v) in map.iter() {
748            parts.push(format!("\"{}\": {}", k, format_value_for_string(v)?));
749        }
750        return Ok(parts.join(", "));
751    }
752    if let Some(id) = val.as_handle() {
753        return Ok(format!("task#{}", id));
754    }
755    Ok(format!("{}", val))
756}
757
758// Legacy functions for backward compatibility
759
760pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
761where
762    F: FnMut(&str) -> Option<String>,
763{
764    let mut out = String::with_capacity(input.len());
765    let mut chars = input.chars().peekable();
766    while let Some(c) = chars.next() {
767        if c == '{' {
768            if let Some(&'{') = chars.peek() {
769                chars.next(); // consume second '{'
770                let mut content = String::new();
771                let mut closed = false;
772                // Look ahead for closing }}
773                let mut inner_chars = chars.clone();
774                while let Some(ch) = inner_chars.next() {
775                    if ch == '}'
776                        && let Some(&'}') = inner_chars.peek()
777                    {
778                        closed = true;
779                        break;
780                    }
781                    content.push(ch);
782                }
783
784                if closed {
785                    // Advance main iterator past content and closing braces.
786                    // Count chars, not bytes: content may contain multi-byte
787                    // UTF-8 (e.g. non-ASCII placeholder names).
788                    for _ in 0..content.chars().count() {
789                        chars.next();
790                    }
791                    chars.next(); // first }
792                    chars.next(); // second }
793
794                    let key = content.trim();
795                    if !key.is_empty() {
796                        out.push_str(&lookup_fn(key).unwrap_or_default());
797                    }
798                } else {
799                    out.push('{');
800                    out.push('{');
801                }
802            } else {
803                out.push('{');
804            }
805        } else {
806            out.push(c);
807        }
808    }
809    out
810}
811
812pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
813    expand_with_lookup(input, |name| {
814        if let Some(key) = name.strip_prefix("env:") {
815            script_envs
816                .get(key)
817                .cloned()
818                .or_else(|| std::env::var(key).ok())
819        } else {
820            None
821        }
822    })
823}
824
825pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
826    expand_with_lookup(input, |name| {
827        if let Some(key) = name.strip_prefix("env:") {
828            ctx.envs().get(key).cloned()
829        } else {
830            None
831        }
832    })
833}
834
835#[cfg(test)]
836mod tests {
837    use super::*;
838    use oxdock_diagnostics::Diagnostic;
839    use std::collections::HashMap;
840
841    #[test]
842    fn basic_expansion() {
843        let mut env = HashMap::new();
844        env.insert("NAME".into(), "World".into());
845        let expander = StreamingExpand::new(&[], &env);
846        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
847        assert_eq!(result, "Hello World");
848    }
849
850    #[test]
851    fn multiple_vars() {
852        let mut env = HashMap::new();
853        env.insert("A".into(), "X".into());
854        env.insert("B".into(), "Y".into());
855        let expander = StreamingExpand::new(&[], &env);
856        let result = expander
857            .expand_string("{{ env:A }} and {{ env:B }}")
858            .unwrap();
859        assert_eq!(result, "X and Y");
860    }
861
862    #[test]
863    fn missing_var() {
864        let env = HashMap::new();
865        let expander = StreamingExpand::new(&[], &env);
866        let result = expander.expand_string("{{ env:MISSING }}");
867        assert!(result.is_err());
868        assert!(
869            result
870                .unwrap_err()
871                .to_string()
872                .contains("undefined environment variable"),
873            "error should mention undefined environment variable"
874        );
875    }
876
877    #[test]
878    fn spaced_env_name_resolves_trimmed() {
879        // `{{ env: FOO }}` looks up `FOO` on every layer: the lookup
880        // trims up front like the static gate and the script engine,
881        // instead of missing on the padded spelling.
882        let mut env = HashMap::new();
883        env.insert("FOO".into(), "bar".into());
884        let expander = StreamingExpand::new(&[], &env);
885        assert_eq!(expander.expand_string("{{ env: FOO }}").unwrap(), "bar");
886    }
887
888    #[test]
889    fn empty_env_names_bail() {
890        // Empty `env:` / `script_env:` names never interpolate empty:
891        // every layer rejects them, matching the static gate and the
892        // script-engine expansion.
893        let env = HashMap::new();
894        for text in ["{{ env: }}", "{{ script_env: }}", "{{ script_env:   }}"] {
895            let expander = StreamingExpand::new(&[], &env);
896            let result = expander.expand_string(text);
897            assert!(result.is_err(), "{text:?} must fail");
898        }
899    }
900
901    #[test]
902    fn no_placeholders() {
903        let env = HashMap::new();
904        let expander = StreamingExpand::new(&[], &env);
905        let result = expander.expand_string("plain text").unwrap();
906        assert_eq!(result, "plain text");
907    }
908
909    #[test]
910    fn empty_input() {
911        let env = HashMap::new();
912        let expander = StreamingExpand::new(&[], &env);
913        let result = expander.expand_string("").unwrap();
914        assert_eq!(result, "");
915    }
916
917    #[test]
918    fn override_precedence() {
919        let mut env = HashMap::new();
920        env.insert("KEY".into(), "envval".into());
921        let overrides = vec![("KEY".into(), "override".into())];
922        let expander = StreamingExpand::new(&overrides, &env);
923        let result = expander.expand_string("{{ env:KEY }}").unwrap();
924        assert_eq!(result, "override");
925    }
926
927    #[test]
928    fn override_with_namespace() {
929        let mut env = HashMap::new();
930        env.insert("CRATE".into(), "envval".into());
931        let overrides = vec![("CRATE".into(), "override".into())];
932        let expander = StreamingExpand::new(&overrides, &env);
933        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
934        assert_eq!(result, "override");
935    }
936
937    #[test]
938    fn override_raw_key_match() {
939        let mut env = HashMap::new();
940        env.insert("CRATE".into(), "envval".into());
941        let overrides = vec![("env:CRATE".into(), "override".into())];
942        let expander = StreamingExpand::new(&overrides, &env);
943        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
944        assert_eq!(result, "override");
945    }
946
947    #[test]
948    fn unclosed_placeholder() {
949        let env = HashMap::new();
950        let expander = StreamingExpand::new(&[], &env);
951        let result = expander.expand_string("{{ env:KEY").unwrap();
952        assert_eq!(result, "{{ env:KEY");
953    }
954
955    #[test]
956    fn unclosed_with_prefix() {
957        let env = HashMap::new();
958        let expander = StreamingExpand::new(&[], &env);
959        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
960        assert_eq!(result, "Hello {{ env:KEY");
961    }
962
963    #[test]
964    fn buffer_limit_exceeded() {
965        let env = HashMap::new();
966        let expander = StreamingExpand::new(&[], &env);
967        // Create input with `{{` followed by >1024 bytes without `}}`
968        let mut input = b"{{ ".to_vec();
969        input.extend(std::iter::repeat_n(b'x', 2000));
970        let result = expander
971            .expand_string(&String::from_utf8_lossy(&input))
972            .unwrap();
973        // Should flush as literal with `{{` prefix
974        assert!(result.starts_with("{{ "));
975        assert!(result.len() > 1024);
976    }
977
978    #[test]
979    fn escaped_opener_emits_literal() {
980        let mut env = HashMap::new();
981        env.insert("PROJECT".into(), "OxDock".into());
982        let expander = StreamingExpand::new(&[], &env);
983        let result = expander
984            .expand_string("Built with \\{{ env:PROJECT }}")
985            .unwrap();
986        assert_eq!(result, "Built with {{ env:PROJECT }}");
987    }
988
989    /// Stub resolver echoing `upper` over one string arg, for call tests.
990    fn shout_resolver() -> PlaceholderCall {
991        Arc::new(|module, func, args| {
992            if module == "T" && func == "SHOUT" && args.len() == 1 {
993                let s = args[0].as_str().ok_or_else(|| {
994                    Diagnostic::new(
995                        "test.expand.shout_type",
996                        "SHOUT expects a string".to_string(),
997                        Diagnostic::make_fields(&[]),
998                    )
999                })?;
1000                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
1001            }
1002            Err(Diagnostic::new(
1003                "test.expand.unknown_function",
1004                format!("unknown placeholder function '{module}::{func}'"),
1005                Diagnostic::make_fields(&[]),
1006            ))
1007        })
1008    }
1009
1010    #[test]
1011    fn placeholder_call_with_var_arg() {
1012        let env = HashMap::new();
1013        let mut vars = HashMap::new();
1014        vars.insert(
1015            "who".to_string(),
1016            oxdock_parser::Value::string("bob".to_string()),
1017        );
1018        let expander = StreamingExpand::new(&[], &env)
1019            .with_vars(&vars)
1020            .with_call_resolver(shout_resolver());
1021        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
1022        assert_eq!(result, "hi BOB!");
1023    }
1024
1025    #[test]
1026    fn placeholder_call_with_literal_args() {
1027        let env = HashMap::new();
1028        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1029        let result = expander
1030            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
1031            .unwrap();
1032        assert_eq!(result, "BOB ANN");
1033    }
1034
1035    #[test]
1036    fn placeholder_call_output_stays_literal() {
1037        // Call output containing `{{ }}` is terminal text, never re-expanded.
1038        let env = HashMap::new();
1039        let mut vars = HashMap::new();
1040        vars.insert(
1041            "any".to_string(),
1042            oxdock_parser::Value::string("v".to_string()),
1043        );
1044        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
1045            Ok(oxdock_parser::Value::string(
1046                "x {{ env:NOPE }} y".to_string(),
1047            ))
1048        });
1049        let expander = StreamingExpand::new(&[], &env)
1050            .with_vars(&vars)
1051            .with_call_resolver(resolver);
1052        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
1053        assert_eq!(result, "x {{ env:NOPE }} y");
1054    }
1055
1056    #[test]
1057    fn placeholder_call_unknown_function_fails() {
1058        let env = HashMap::new();
1059        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
1060        let result = expander.expand_string("{{ T::NOPE($x) }}");
1061        assert!(result.is_err());
1062    }
1063
1064    #[test]
1065    fn placeholder_call_without_resolver_fails() {
1066        let env = HashMap::new();
1067        let expander = StreamingExpand::new(&[], &env);
1068        let result = expander.expand_string("{{ T::SHOUT($x) }}");
1069        assert!(result.is_err());
1070    }
1071
1072    #[test]
1073    fn escaped_opener_across_chunks() {
1074        let mut env = HashMap::new();
1075        env.insert("PROJECT".into(), "OxDock".into());
1076        let mut expander = StreamingExpand::new(&[], &env);
1077        let mut out = Vec::new();
1078
1079        // Split `\` / `{{ env:PROJECT }}` across chunks
1080        expander.process_bytes(b"Built with \\", &mut out).unwrap();
1081        expander
1082            .process_bytes(b"{{ env:PROJECT }}", &mut out)
1083            .unwrap();
1084        expander.flush(&mut out).unwrap();
1085
1086        assert_eq!(
1087            String::from_utf8_lossy(&out),
1088            "Built with {{ env:PROJECT }}"
1089        );
1090    }
1091
1092    #[test]
1093    fn double_backslash_then_placeholder_expands() {
1094        let mut env = HashMap::new();
1095        env.insert("PROJECT".into(), "OxDock".into());
1096        let expander = StreamingExpand::new(&[], &env);
1097        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
1098        assert_eq!(result, "\\OxDock");
1099    }
1100
1101    #[test]
1102    fn trailing_backslash_flushes_literal() {
1103        let env = HashMap::new();
1104        let expander = StreamingExpand::new(&[], &env);
1105        let result = expander.expand_string("end\\").unwrap();
1106        assert_eq!(result, "end\\");
1107    }
1108
1109    #[test]
1110    fn backslash_before_other_text_is_literal() {
1111        let env = HashMap::new();
1112        let expander = StreamingExpand::new(&[], &env);
1113        let result = expander.expand_string("a\\b \\{ once }").unwrap();
1114        assert_eq!(result, "a\\b \\{ once }");
1115    }
1116
1117    #[test]
1118    fn escaped_pair_split_across_chunks() {
1119        let mut env = HashMap::new();
1120        env.insert("PROJECT".into(), "OxDock".into());
1121        let mut expander = StreamingExpand::new(&[], &env);
1122        let mut out = Vec::new();
1123
1124        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
1125        // completes to one backslash, then the placeholder expands
1126        expander.process_bytes(b"\\", &mut out).unwrap();
1127        expander
1128            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
1129            .unwrap();
1130        expander.flush(&mut out).unwrap();
1131
1132        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
1133    }
1134
1135    #[test]
1136    fn partial_across_chunks() {
1137        let mut env = HashMap::new();
1138        env.insert("NAME".into(), "World".into());
1139        let mut expander = StreamingExpand::new(&[], &env);
1140        let mut out = Vec::new();
1141
1142        // Split `{{ env:NA` / `ME }}` across chunks
1143        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
1144        expander.process_bytes(b"ME }}", &mut out).unwrap();
1145        expander.flush(&mut out).unwrap();
1146
1147        assert_eq!(String::from_utf8_lossy(&out), "World");
1148    }
1149
1150    #[test]
1151    fn trailing_brace_across_chunks() {
1152        let mut env = HashMap::new();
1153        env.insert("NAME".into(), "World".into());
1154        let mut expander = StreamingExpand::new(&[], &env);
1155        let mut out = Vec::new();
1156
1157        // Split `...{` / `{env:NAME}}` across chunks
1158        expander.process_bytes(b"...", &mut out).unwrap();
1159        expander.process_bytes(b"{", &mut out).unwrap();
1160        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
1161        expander.flush(&mut out).unwrap();
1162
1163        assert_eq!(String::from_utf8_lossy(&out), "...World");
1164    }
1165
1166    #[test]
1167    fn trailing_brace_at_eof() {
1168        let env = HashMap::new();
1169        let mut expander = StreamingExpand::new(&[], &env);
1170        let mut out = Vec::new();
1171
1172        expander.process_bytes(b"hello{", &mut out).unwrap();
1173        expander.flush(&mut out).unwrap();
1174
1175        assert_eq!(String::from_utf8_lossy(&out), "hello{");
1176    }
1177
1178    #[test]
1179    fn immediate_flush_guarantee() {
1180        let env = HashMap::new();
1181        let mut expander = StreamingExpand::new(&[], &env);
1182        let mut out = Vec::new();
1183
1184        // 1MB of plain text with no placeholders
1185        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
1186        expander.process_bytes(&input, &mut out).unwrap();
1187        expander.flush(&mut out).unwrap();
1188
1189        assert_eq!(out.len(), 1024 * 1024);
1190    }
1191
1192    #[test]
1193    fn nested_braces() {
1194        let mut env = HashMap::new();
1195        env.insert("KEY{1}".into(), "val".into());
1196        let expander = StreamingExpand::new(&[], &env);
1197        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
1198        assert_eq!(result, "val");
1199    }
1200
1201    #[test]
1202    fn split_close_delimiter_across_chunks() {
1203        let mut env = HashMap::new();
1204        env.insert("NAME".into(), "World".into());
1205        let mut expander = StreamingExpand::new(&[], &env);
1206        let mut out = Vec::new();
1207
1208        // Split `}}` across chunks: `{{ env:NAME` / `}}`
1209        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1210        expander.process_bytes(b"}}", &mut out).unwrap();
1211        expander.flush(&mut out).unwrap();
1212
1213        assert_eq!(String::from_utf8_lossy(&out), "World");
1214    }
1215
1216    #[test]
1217    fn split_close_delimiter_with_trailing_content() {
1218        let mut env = HashMap::new();
1219        env.insert("NAME".into(), "World".into());
1220        let mut expander = StreamingExpand::new(&[], &env);
1221        let mut out = Vec::new();
1222
1223        // Split `}}` across chunks with content after
1224        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1225        expander.process_bytes(b"}} rest", &mut out).unwrap();
1226        expander.flush(&mut out).unwrap();
1227
1228        assert_eq!(String::from_utf8_lossy(&out), "World rest");
1229    }
1230
1231    #[test]
1232    fn empty_input_preserves_pending_state() {
1233        let mut env = HashMap::new();
1234        env.insert("NAME".into(), "World".into());
1235        let mut expander = StreamingExpand::new(&[], &env);
1236        let mut out = Vec::new();
1237
1238        // End chunk with closing byte, then empty input, then confirm
1239        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
1240        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
1241        expander.process_bytes(b"}}", &mut out).unwrap();
1242        expander.flush(&mut out).unwrap();
1243
1244        assert_eq!(String::from_utf8_lossy(&out), "World");
1245    }
1246
1247    #[test]
1248    fn missing_env_var_errors() {
1249        let env = HashMap::new();
1250        let expander = StreamingExpand::new(&[], &env);
1251        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
1252        assert!(result.is_err());
1253        let msg = result.unwrap_err().to_string();
1254        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1255        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
1256    }
1257
1258    #[test]
1259    fn missing_script_var_errors() {
1260        let env = HashMap::new();
1261        let expander = StreamingExpand::new(&[], &env);
1262        let result = expander.expand_string("{{ $undefined_var }}");
1263        assert!(result.is_err());
1264        let msg = result.unwrap_err().to_string();
1265        assert!(msg.contains("undefined script variable"), "got: {msg}");
1266        assert!(msg.contains("$undefined_var"), "got: {msg}");
1267    }
1268
1269    #[test]
1270    fn missing_key_in_map_errors() {
1271        let mut vars = HashMap::new();
1272        vars.insert(
1273            "cfg".into(),
1274            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1275                "server".into(),
1276                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
1277                    "port".into(),
1278                    oxdock_parser::Value::int(8080),
1279                )])),
1280            )])),
1281        );
1282        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1283        let result = expander.expand_string("{{ $cfg.missing_key }}");
1284        assert!(result.is_err());
1285        let msg = result.unwrap_err().to_string();
1286        assert!(
1287            msg.contains("property 'missing_key' not found"),
1288            "got: {msg}"
1289        );
1290    }
1291
1292    #[test]
1293    fn out_of_bounds_array_index_errors() {
1294        let mut vars = HashMap::new();
1295        vars.insert(
1296            "arr".into(),
1297            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
1298        );
1299        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1300        let result = expander.expand_string("{{ $arr.5 }}");
1301        assert!(result.is_err());
1302        let msg = result.unwrap_err().to_string();
1303        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
1304    }
1305
1306    #[test]
1307    fn type_mismatch_navigation_errors() {
1308        let mut vars = HashMap::new();
1309        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
1310        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1311        let result = expander.expand_string("{{ $name.sub_field }}");
1312        assert!(result.is_err());
1313        let msg = result.unwrap_err().to_string();
1314        assert!(
1315            msg.contains("cannot access property 'sub_field' on primitive"),
1316            "got: {msg}"
1317        );
1318    }
1319
1320    #[test]
1321    fn unprefixed_identifier_errors() {
1322        let env = HashMap::new();
1323        let expander = StreamingExpand::new(&[], &env);
1324        let result = expander.expand_string("{{ bare_word }}");
1325        assert!(result.is_err());
1326        let msg = result.unwrap_err().to_string();
1327        assert!(msg.contains("missing required step override"), "got: {msg}");
1328    }
1329
1330    // ── Strict namespace isolation tests ─────────────────────────────────────
1331
1332    #[test]
1333    fn script_var_does_not_fall_back_to_env() {
1334        let mut env = HashMap::new();
1335        env.insert("WHO".into(), "from-env".into());
1336        let expander = StreamingExpand::new(&[], &env);
1337        // $WHO queries vars, NOT env : should error even though env has WHO
1338        let result = expander.expand_string("{{ $WHO }}");
1339        assert!(result.is_err());
1340        let msg = result.unwrap_err().to_string();
1341        assert!(msg.contains("undefined script variable"), "got: {msg}");
1342        assert!(
1343            msg.contains("did you mean 'env:WHO'"),
1344            "hint should suggest env: prefix, got: {msg}"
1345        );
1346    }
1347
1348    #[test]
1349    fn env_var_does_not_fall_back_to_vars() {
1350        let mut vars = HashMap::new();
1351        vars.insert(
1352            "HOST".into(),
1353            oxdock_parser::Value::string("from-var".into()),
1354        );
1355        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1356        // env:HOST queries env, NOT vars : should error even though vars has HOST
1357        let result = expander.expand_string("{{ env:HOST }}");
1358        assert!(result.is_err());
1359        let msg = result.unwrap_err().to_string();
1360        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1361        assert!(
1362            msg.contains("did you mean '$HOST'"),
1363            "hint should suggest $ prefix, got: {msg}"
1364        );
1365    }
1366
1367    #[test]
1368    fn step_override_does_not_fall_back_to_vars() {
1369        let mut vars = HashMap::new();
1370        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
1371        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1372        // PORT (bare) queries overrides, NOT vars : should error
1373        let result = expander.expand_string("{{ PORT }}");
1374        assert!(result.is_err());
1375        let msg = result.unwrap_err().to_string();
1376        assert!(msg.contains("missing required step override"), "got: {msg}");
1377        assert!(
1378            msg.contains("did you mean '$PORT'"),
1379            "hint should suggest $ prefix, got: {msg}"
1380        );
1381    }
1382
1383    #[test]
1384    fn env_prefix_isolated_from_script_vars() {
1385        let mut vars = HashMap::new();
1386        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
1387        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
1388        // env:MODE looks in env, not vars : should error
1389        let result = expander.expand_string("{{ env:MODE }}");
1390        assert!(result.is_err());
1391        let msg = result.unwrap_err().to_string();
1392        assert!(msg.contains("undefined environment variable"), "got: {msg}");
1393        assert!(
1394            msg.contains("did you mean '$MODE'"),
1395            "hint should suggest $ prefix, got: {msg}"
1396        );
1397    }
1398
1399    #[test]
1400    fn dollar_prefix_isolated_from_env() {
1401        let mut env = HashMap::new();
1402        env.insert("PORT".into(), "3000".into());
1403        let expander = StreamingExpand::new(&[], &env);
1404        // $PORT looks in vars, not env : should error
1405        let result = expander.expand_string("{{ $PORT }}");
1406        assert!(result.is_err());
1407        let msg = result.unwrap_err().to_string();
1408        assert!(msg.contains("undefined script variable"), "got: {msg}");
1409        assert!(
1410            msg.contains("did you mean 'env:PORT'"),
1411            "hint should suggest env: prefix, got: {msg}"
1412        );
1413    }
1414
1415    #[test]
1416    fn empty_placeholder_errors() {
1417        let expander = StreamingExpand::new(&[], &HashMap::new());
1418        let result = expander.expand_string("{{ }}");
1419        assert!(result.is_err());
1420        let msg = result.unwrap_err().to_string();
1421        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1422    }
1423
1424    #[test]
1425    fn malformed_symbol_placeholder_errors() {
1426        let expander = StreamingExpand::new(&[], &HashMap::new());
1427        let result = expander.expand_string("{{ @invalid! }}");
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    #[test]
1434    fn bare_call_head_fails_as_invalid_placeholder() {
1435        // Directive 3: bare `FUNC(...)` has no registry entry in
1436        // override expansion. The `Call` arm handles `module == None`
1437        // explicitly instead of silently falling through.
1438        let expander = StreamingExpand::new(&[], &HashMap::new());
1439        let result = expander.expand_string("{{ FOO() }}");
1440        assert!(result.is_err());
1441        let msg = result.unwrap_err().to_string();
1442        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
1443    }
1444
1445    /// Feed input in fixed-size chunks, then flush: exercises every
1446    /// chunk-boundary alignment for the given split size.
1447    fn render_split(
1448        input: &[u8],
1449        size: usize,
1450        env: &HashMap<String, String>,
1451    ) -> Result<String, anyhow::Error> {
1452        let mut expander = StreamingExpand::new(&[], env);
1453        let mut out = Vec::new();
1454        for chunk in input.chunks(size) {
1455            expander.process_bytes(chunk, &mut out)?;
1456        }
1457        expander.flush(&mut out)?;
1458        Ok(String::from_utf8_lossy(&out).into_owned())
1459    }
1460
1461    #[test]
1462    fn escaped_opener_one_byte_chunks_stays_literal() {
1463        let mut env = HashMap::new();
1464        env.insert("NAME".into(), "World".into());
1465        // Every byte arrives alone: `\` | `{` | `{` | ... must still
1466        // resolve to a literal opener, never an expansion.
1467        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
1468        assert_eq!(out, "{{ env:NAME }}");
1469    }
1470
1471    #[test]
1472    fn escaped_opener_two_byte_chunks_stays_literal() {
1473        let mut env = HashMap::new();
1474        env.insert("NAME".into(), "World".into());
1475        // Two-byte splits land `\{` and lone `{` at chunk ends.
1476        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
1477        assert_eq!(out, "a{{ env:NAME }}b");
1478    }
1479
1480    #[test]
1481    fn escaped_opener_split_variants_stay_literal() {
1482        let mut env = HashMap::new();
1483        env.insert("NAME".into(), "World".into());
1484        for chunks in [
1485            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
1486            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
1487            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
1488        ] {
1489            let mut expander = StreamingExpand::new(&[], &env);
1490            let mut out = Vec::new();
1491            for chunk in chunks {
1492                expander.process_bytes(chunk, &mut out).unwrap();
1493            }
1494            expander.flush(&mut out).unwrap();
1495            assert_eq!(
1496                String::from_utf8_lossy(&out),
1497                "{{ env:NAME }}",
1498                "chunks must not corrupt the escape"
1499            );
1500        }
1501    }
1502
1503    #[test]
1504    fn plain_opener_split_chunks_still_expands() {
1505        let mut env = HashMap::new();
1506        env.insert("NAME".into(), "World".into());
1507        // The fix must not swallow genuine openers fragmented the
1508        // same way: `{` | `{` opens, then the key resolves.
1509        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
1510        assert_eq!(out, "World");
1511    }
1512
1513    #[test]
1514    fn double_backslash_split_chunks_still_expands() {
1515        let mut env = HashMap::new();
1516        env.insert("NAME".into(), "World".into());
1517        // `\\` completes to one backslash; the opener after it expands.
1518        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
1519        assert_eq!(out, "\\World");
1520    }
1521
1522    #[test]
1523    fn trailing_escape_brace_flushes_literal() {
1524        let env = HashMap::new();
1525        let expander = StreamingExpand::new(&[], &env);
1526        let result = expander.expand_string("end\\{").unwrap();
1527        assert_eq!(result, "end\\{");
1528    }
1529
1530    // ── Single-pass substitution tests ────────────────────────────────────
1531    // Substituted values are emitted verbatim and never re-scanned for
1532    // `{{ ... }}`. These pin the top-level-only behavior: a value that
1533    // itself contains a placeholder stays literal instead of expanding.
1534
1535    #[test]
1536    fn substituted_override_value_is_not_rescanned() {
1537        let mut env = HashMap::new();
1538        env.insert("OTHER".into(), "world".into());
1539        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
1540        let expander = StreamingExpand::new(&overrides, &env);
1541        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
1542        assert_eq!(result, "Hello {{ env:OTHER }}");
1543    }
1544
1545    #[test]
1546    fn substituted_env_value_is_not_rescanned() {
1547        let mut env = HashMap::new();
1548        env.insert("NAME".into(), "{{ env:OTHER }}".into());
1549        env.insert("OTHER".into(), "world".into());
1550        let expander = StreamingExpand::new(&[], &env);
1551        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
1552        assert_eq!(result, "Hello {{ env:OTHER }}");
1553    }
1554
1555    #[test]
1556    fn substituted_script_var_value_is_not_rescanned() {
1557        let mut vars = HashMap::new();
1558        vars.insert(
1559            "inner".into(),
1560            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
1561        );
1562        let mut env = HashMap::new();
1563        env.insert("OTHER".into(), "world".into());
1564        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
1565        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
1566        assert_eq!(result, "Hello {{ env:OTHER }}");
1567    }
1568
1569    /// Echo resolver returning the debug shape of each argument, so
1570    /// literal parsing asserts on values instead of formatting.
1571    fn shape_resolver() -> PlaceholderCall {
1572        Arc::new(|module, func, args| {
1573            if module == "T" && func == "SHAPE" {
1574                let shape = args
1575                    .iter()
1576                    .map(|arg| arg.type_name().to_string())
1577                    .collect::<Vec<_>>()
1578                    .join(",");
1579                return Ok(oxdock_parser::Value::string(shape));
1580            }
1581            Err(Diagnostic::new(
1582                "test.expand.unknown_function",
1583                format!("unknown placeholder function '{module}::{func}'"),
1584                Diagnostic::make_fields(&[]),
1585            ))
1586        })
1587    }
1588
1589    #[test]
1590    fn placeholder_call_with_empty_map_literal() {
1591        let expander =
1592            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1593        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
1594        assert_eq!(result, "MAP");
1595    }
1596
1597    #[test]
1598    fn placeholder_call_with_map_and_list_literals() {
1599        let expander =
1600            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1601        let result = expander
1602            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
1603            .unwrap();
1604        assert_eq!(result, "MAP,LIST");
1605    }
1606
1607    #[test]
1608    fn placeholder_call_map_commas_nest_inside_literals() {
1609        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1610            let map = args[0].as_map().expect("map");
1611            let format = map
1612                .get("format")
1613                .and_then(|v| v.as_str())
1614                .expect("format string");
1615            Ok(oxdock_parser::Value::string(format.to_string()))
1616        });
1617        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
1618        let result = expander
1619            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
1620            .unwrap();
1621        assert_eq!(result, "a,b");
1622    }
1623
1624    #[test]
1625    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
1626        let mut vars = HashMap::new();
1627        vars.insert("depth".into(), oxdock_parser::Value::int(2));
1628        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1629            let map = args[0].as_map().expect("map");
1630            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
1631            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
1632            Ok(oxdock_parser::Value::string(format!(
1633                "{depth}:{}",
1634                tags.len()
1635            )))
1636        });
1637        let expander = StreamingExpand::new(&[], &HashMap::new())
1638            .with_vars(&vars)
1639            .with_call_resolver(resolver);
1640        let result = expander
1641            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
1642            .unwrap();
1643        assert_eq!(result, "2:2");
1644    }
1645
1646    #[test]
1647    fn placeholder_call_rejects_malformed_literals() {
1648        for bad in [
1649            "{{ T::SHAPE({a}) }}",
1650            "{{ T::SHAPE({a: 1, a: 2}) }}",
1651            "{{ T::SHAPE({\"a\": 1: 2}) }}",
1652            "{{ T::SHAPE([1) }}",
1653            "{{ T::SHAPE({a: 1) }}",
1654        ] {
1655            let expander =
1656                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1657            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1658        }
1659    }
1660
1661    #[test]
1662    fn placeholder_call_rejects_adjacent_string_literals() {
1663        // Missing commas and infix expressions must fail, never merge
1664        // into one string.
1665        for bad in [
1666            "{{ T::SHAPE(\"a\" \"b\") }}",
1667            "{{ T::SHAPE(\"a\" + \"b\") }}",
1668            "{{ T::SHAPE(\"foo\\\") }}",
1669        ] {
1670            let expander =
1671                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
1672            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
1673        }
1674    }
1675
1676    #[test]
1677    fn placeholder_call_brackets_inside_block_strings_resolve() {
1678        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1679            let first = &args[0];
1680            if let Some(items) = first.as_list() {
1681                return Ok(oxdock_parser::Value::string(
1682                    items[0].as_str().unwrap_or("?").to_string(),
1683                ));
1684            }
1685            if let Some(entries) = first.as_map() {
1686                return Ok(oxdock_parser::Value::string(
1687                    entries
1688                        .get("k")
1689                        .and_then(|v| v.as_str())
1690                        .unwrap_or("?")
1691                        .to_string(),
1692                ));
1693            }
1694            Err(Diagnostic::new(
1695                "test.expand.expected_collection",
1696                "expected list or map".to_string(),
1697                Diagnostic::make_fields(&[]),
1698            ))
1699        });
1700        let list = StreamingExpand::new(&[], &HashMap::new())
1701            .with_call_resolver(resolver.clone())
1702            .expand_string("{{ T::ECHO([\"\"\"a]b\"\"\"]) }}")
1703            .unwrap();
1704        assert_eq!(list, "a]b");
1705        let map = StreamingExpand::new(&[], &HashMap::new())
1706            .with_call_resolver(resolver.clone())
1707            .expand_string("{{ T::ECHO({k: \"\"\"a}b\"\"\"}) }}")
1708            .unwrap();
1709        assert_eq!(map, "a}b");
1710    }
1711
1712    #[test]
1713    fn placeholder_call_single_quotes_match_double_quotes() {
1714        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1715            Ok(oxdock_parser::Value::string(
1716                args.iter()
1717                    .map(|a| a.as_str().unwrap_or("?").to_string())
1718                    .collect::<Vec<_>>()
1719                    .join("|"),
1720            ))
1721        });
1722        for (double, single) in [
1723            ("{{ T::ECHO(\"hi\") }}", "{{ T::ECHO('hi') }}"),
1724            ("{{ T::ECHO(\"a,b\") }}", "{{ T::ECHO('a,b') }}"),
1725            ("{{ T::ECHO({k: \"v\"}) }}", "{{ T::ECHO({k: 'v'}) }}"),
1726            ("{{ T::ECHO({\"k\": \"v\"}) }}", "{{ T::ECHO({'k': 'v'}) }}"),
1727            ("{{ T::ECHO([\"a\"]) }}", "{{ T::ECHO(['a']) }}"),
1728        ] {
1729            let left = StreamingExpand::new(&[], &HashMap::new())
1730                .with_call_resolver(resolver.clone())
1731                .expand_string(double)
1732                .unwrap();
1733            let right = StreamingExpand::new(&[], &HashMap::new())
1734                .with_call_resolver(resolver.clone())
1735                .expand_string(single)
1736                .unwrap();
1737            assert_eq!(
1738                left, right,
1739                "quote style must not matter: {double} vs {single}"
1740            );
1741        }
1742    }
1743
1744    #[test]
1745    fn malformed_qualified_placeholders_fail_closed() {
1746        // `PlaceholderKey::Invalid` never resolves and never falls
1747        // through silently: every malformed `$ALIAS::NAME` tail fails
1748        // with the invalid-format diagnostic, mirroring the `Dollar`
1749        // arm above.
1750        for bad in ["{{ $LIB::M. }}", "{{ $LIB::M.bad-seg }}", "{{ $LIB:: }}"] {
1751            let expander = StreamingExpand::new(&[], &HashMap::new());
1752            let err = expander.expand_string(bad).expect_err("must fail");
1753            assert_eq!(err.key(), "proc.expand.invalid_placeholder_format", "{bad}");
1754            assert!(
1755                err.to_string().contains("invalid placeholder format"),
1756                "{err}"
1757            );
1758        }
1759    }
1760
1761    #[test]
1762    fn placeholder_call_triple_quoted_matches_single_line() {
1763        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
1764            Ok(oxdock_parser::Value::string(
1765                args[0].as_str().unwrap_or("?").to_string(),
1766            ))
1767        });
1768        let plain = StreamingExpand::new(&[], &HashMap::new())
1769            .with_call_resolver(resolver.clone())
1770            .expand_string("{{ T::ECHO(\"Release installs\") }}")
1771            .unwrap();
1772        let block = StreamingExpand::new(&[], &HashMap::new())
1773            .with_call_resolver(resolver.clone())
1774            .expand_string("{{ T::ECHO(\"\"\"Release installs\"\"\") }}")
1775            .unwrap();
1776        assert_eq!(plain, block);
1777    }
1778}