Skip to main content

oxdock_parser/
command.rs

1use crate::ast::{Arg, Expr, StepKind};
2use crate::diagnostics as dsl_diag;
3use crate::error::{ParseError, ParseErrorKind, ParseResult, SpanContext};
4use crate::{
5    BOOL_TYPE_NAME, DURATION_TYPE_NAME, INT_TYPE_NAME, LIST_TYPE_NAME, PATH_TYPE_NAME,
6    STRING_TYPE_NAME,
7};
8use oxdock_diagnostics::DiagnosticResult;
9
10/// Metadata for a single command argument.
11pub struct ArgSpec {
12    pub name: &'static str,
13    pub arg_type: ArgType,
14    pub description: &'static str,
15    pub io: IoDirection,
16    pub index: usize,
17    pub required: bool,
18    pub fallback_stream: Option<Stream>,
19}
20
21/// Closed vocabulary for argument value types: every variant names a
22/// type explicitly present in the app, so the reference table never
23/// lists a type that does not exist. Shapes (`$var` targets, `KEY=value`
24/// pairs) are not types: the central validator only checks value types
25/// and arity, while each command's `lower` enforces its own shapes with
26/// command-specific errors.
27/// [`ArgType::Any`] is the single exception: it renders as `<any>`,
28/// visibly a placeholder rather than a type name.
29/// [`ArgType::OneOf`] renders its inline options, likewise self-describing.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ArgType {
32    String,
33    Path,
34    Int,
35    Duration,
36    /// A `$variable` that must hold a LIST at runtime. Non-variable
37    /// expressions fail at lower time; renders linked as `LIST`.
38    List,
39    /// Any evaluated value (plus stream markers like `stdout` where the
40    /// command accepts them). Renders unlinked as `<any>`, visibly a
41    /// placeholder rather than a type name.
42    Any,
43    /// Inline alternation for one-off enums (e.g. `SNAPSHOT|LOCAL`).
44    /// Self-describing, so it renders unlinked.
45    OneOf(&'static [&'static str]),
46    /// Trailing variadic repetition (e.g. `RUN`'s `string...`).
47    Rest(&'static ArgType),
48}
49
50impl ArgType {
51    /// Table-cell label for the argument table's Type column.
52    /// Canonical value types use their descriptor names; `ANY` renders
53    /// as `<any>` and inline alternations render their options, so
54    /// neither reads as a standalone type. Shapes (`$var` targets,
55    /// `KEY=value` pairs) are validated in each command's `lower`, and
56    /// the shape requirement lives in the argument description and
57    /// command syntax.
58    pub fn label(&self) -> String {
59        match self {
60            ArgType::String => STRING_TYPE_NAME.to_string(),
61            ArgType::Path => PATH_TYPE_NAME.to_string(),
62            ArgType::Int => INT_TYPE_NAME.to_string(),
63            ArgType::Duration => DURATION_TYPE_NAME.to_string(),
64            ArgType::List => LIST_TYPE_NAME.to_string(),
65            ArgType::Any => "<any>".to_string(),
66            ArgType::OneOf(options) => options.join("|"),
67            ArgType::Rest(inner) => format!("{}...", inner.label()),
68        }
69    }
70
71    /// Anchor of the type's reference section. Only types with a value-type
72    /// reference section link; `<any>` and inline alternations render
73    /// unlinked.
74    pub fn anchor(&self) -> Option<String> {
75        match self {
76            ArgType::String => Some(crate::value::type_anchor(STRING_TYPE_NAME)),
77            ArgType::Path => Some(crate::value::type_anchor(PATH_TYPE_NAME)),
78            ArgType::Int => Some(crate::value::type_anchor(INT_TYPE_NAME)),
79            ArgType::Duration => Some(crate::value::type_anchor(DURATION_TYPE_NAME)),
80            ArgType::List => Some(crate::value::type_anchor(LIST_TYPE_NAME)),
81            ArgType::Any => None,
82            ArgType::OneOf(_) => None,
83            ArgType::Rest(inner) => inner.anchor(),
84        }
85    }
86
87    /// Validate a statically-known literal against this type.
88    /// Templates and variables are never passed here : see `check_arg`.
89    pub fn validate_literal(&self, literal: &str) -> DiagnosticResult<()> {
90        match self {
91            ArgType::String | ArgType::Path | ArgType::Any => Ok(()),
92            ArgType::Int => strip_digit_separators(literal)
93                .parse::<i64>()
94                .map(|_| ())
95                .map_err(|_| dsl_diag::expected_int(literal)),
96            ArgType::Duration => parse_duration(literal).map(|_| ()),
97            ArgType::List => {
98                if literal.starts_with('$') {
99                    Ok(())
100                } else {
101                    Err(dsl_diag::expected_var(literal))
102                }
103            }
104            ArgType::OneOf(options) => {
105                // Exact match only: lowercase spellings are rejected so
106                // keyword arguments stay uppercase across the DSL.
107                if options.contains(&literal) {
108                    Ok(())
109                } else {
110                    Err(dsl_diag::expected_one_of(options, literal))
111                }
112            }
113            ArgType::Rest(inner) => inner.validate_literal(literal),
114        }
115    }
116
117    /// Classify one positional arg for lower-time checking.
118    /// `Static` literals validate now; templates, variables (except a
119    /// `$var` where `List` is required), and mixed fragments defer to the
120    /// runtime resolvers, which see interpolated values.
121    pub fn check_arg(&self, arg: &Arg) -> DiagnosticResult<CheckOutcome> {
122        match arg {
123            Arg::String(s, _) if !s.contains("{{") => {
124                self.validate_literal(s)?;
125                Ok(CheckOutcome::Static)
126            }
127            Arg::String(_, _) => Ok(CheckOutcome::Deferred),
128            Arg::Parts(_) => Ok(CheckOutcome::Deferred),
129            Arg::Expr(Expr::Var { .. }) => {
130                if matches!(*self, ArgType::List) {
131                    Ok(CheckOutcome::Static)
132                } else {
133                    Ok(CheckOutcome::Deferred)
134                }
135            }
136            Arg::Expr(_) => {
137                if matches!(*self, ArgType::List) {
138                    Err(dsl_diag::expected_var_expression(&arg.render()))
139                } else {
140                    Ok(CheckOutcome::Deferred)
141                }
142            }
143        }
144    }
145}
146
147/// Lower-time checking outcome for one positional arg.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum CheckOutcome {
150    /// Validated now; nothing deferred.
151    Static,
152    /// Unknowable until runtime (template, variable, or fragment);
153    /// runtime resolvers enforce the type on the resolved value.
154    Deferred,
155}
156
157/// Validate positional args against a command's declared specs.
158/// Missing required positionals, statically-known type violations, and
159/// trailing positionals beyond a fixed-arity spec all fail here;
160/// templates, variables, and fragments defer to the runtime resolvers.
161/// A trailing `Rest` spec absorbs any number of positionals.
162pub fn validate_positionals_against_meta(
163    cmd_name: &str,
164    specs: &[ArgSpec],
165    args: &[Arg],
166) -> ParseResult<()> {
167    let has_rest = specs
168        .last()
169        .is_some_and(|s| matches!(s.arg_type, ArgType::Rest(_)));
170
171    if !has_rest && args.len() > specs.len() {
172        return Err(ParseError::from_diagnostic(
173            ParseErrorKind::Validation {
174                command: cmd_name.to_string(),
175            },
176            dsl_diag::too_many_positionals(cmd_name, specs.len(), args.len()),
177            &SpanContext::line_only(0),
178        ));
179    }
180
181    for spec in specs {
182        if let ArgType::Rest(inner) = spec.arg_type {
183            // Variadic tail: every trailing positional checks against
184            // the inner type, not just the first.
185            let tail = args.get(spec.index..).unwrap_or(&[]);
186            if tail.is_empty() && spec.required {
187                return Err(ParseError::from_diagnostic(
188                    ParseErrorKind::Validation {
189                        command: cmd_name.to_string(),
190                    },
191                    dsl_diag::missing_argument(cmd_name, spec.name),
192                    &SpanContext::line_only(0),
193                ));
194            }
195            for arg in tail {
196                check_one(cmd_name, spec, inner, arg)?;
197            }
198            return Ok(());
199        }
200        match args.get(spec.index) {
201            Some(arg) => check_one(cmd_name, spec, &spec.arg_type, arg)?,
202            None if spec.required => {
203                return Err(ParseError::from_diagnostic(
204                    ParseErrorKind::Validation {
205                        command: cmd_name.to_string(),
206                    },
207                    dsl_diag::missing_argument(cmd_name, spec.name),
208                    &SpanContext::line_only(0),
209                ));
210            }
211            None => {}
212        }
213    }
214    Ok(())
215}
216
217fn check_one(cmd_name: &str, spec: &ArgSpec, arg_type: &ArgType, arg: &Arg) -> ParseResult<()> {
218    match arg_type.check_arg(arg) {
219        Ok(_) => Ok(()),
220        Err(e) => Err(ParseError::from_diagnostic(
221            ParseErrorKind::Validation {
222                command: cmd_name.to_string(),
223            },
224            dsl_diag::arg_type_mismatch(cmd_name, spec.name, &arg.render(), e),
225            &SpanContext::line_only(0),
226        )),
227    }
228}
229
230/// Strip one layer of surrounding quotes (`"`, `'`, or `"""` block).
231/// Block delimiters strip without dedenting: callers holding a block
232/// spelling route through [`lower_block_string`] instead.
233pub fn strip_surrounding_quotes(value: &str) -> &str {
234    if let Some(inner) = value
235        .strip_prefix("\"\"\"")
236        .and_then(|s| s.strip_suffix("\"\"\""))
237    {
238        return inner;
239    }
240    value
241        .strip_prefix('"')
242        .and_then(|s| s.strip_suffix('"'))
243        .or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
244        .unwrap_or(value)
245}
246
247/// Lower a `"""..."""` block literal to its string value. Escapes and
248/// `{{ }}` pass through verbatim for runtime `expand_string`. Steps:
249/// 1. Strip the delimiters, normalize `\r\n` and lone `\r` to `\n`.
250/// 2. Leading newline: if the opening `"""` is followed only by
251///    spaces/tabs then a newline, drop through that newline
252///    (`split_leading_newline`). Otherwise the opening line holds
253///    inline text (`"""text`), kept verbatim at zero indent and
254///    excluded from prefix computation.
255/// 3. Closing line: if the text holds a newline and the last line is
256///    whitespace-only, the closing `"""` sits on its own line. Pop
257///    that line (with its newline) and seat its whitespace as the
258///    indentation baseline among the prefix candidates.
259/// 4. Common prefix: longest shared leading-whitespace run across all
260///    non-blank content lines. Blank lines never vote. No qualifying
261///    line means an empty value.
262/// 5. Strip the prefix from every non-blank line. The inline first
263///    line and blank lines pass through untouched.
264/// 6. Rejoin the lines with `\n`.
265pub fn lower_block_string(s: &str) -> String {
266    let inner = s.strip_prefix("\"\"\"").unwrap_or(s);
267    let inner = inner.strip_suffix("\"\"\"").unwrap_or(inner);
268    let norm = inner.replace("\r\n", "\n").replace('\r', "\n");
269    let (body, inline_first) = match split_leading_newline(&norm) {
270        Some(rest) => (rest.to_string(), false),
271        None => (norm.clone(), true),
272    };
273    if body.is_empty() {
274        return String::new();
275    }
276    let mut lines: Vec<&str> = body.split('\n').collect();
277    let closing_own_line = norm.contains('\n') && lines.last().is_some_and(|l| l.trim().is_empty());
278    let closing_indent = if closing_own_line {
279        lines.pop().unwrap_or("").to_string()
280    } else {
281        String::new()
282    };
283    let content: &[&str] = if inline_first && !lines.is_empty() {
284        &lines[1..]
285    } else {
286        &lines[..]
287    };
288    if inline_first && lines.len() == 1 && lines[0].trim().is_empty() {
289        return String::new();
290    }
291    if !(inline_first && !lines.is_empty() && !lines[0].trim().is_empty())
292        && !content.iter().any(|l| !l.trim().is_empty())
293    {
294        return String::new();
295    }
296    let mut candidates: Vec<&str> = Vec::new();
297    if closing_own_line {
298        candidates.push(closing_indent.as_str());
299    }
300    for line in content {
301        if line.trim().is_empty() {
302            continue;
303        }
304        let len = line
305            .char_indices()
306            .find(|(_, c)| *c != ' ' && *c != '\t')
307            .map(|(i, _)| i)
308            .unwrap_or(line.len());
309        candidates.push(&line[..len]);
310    }
311    let mut prefix = candidates.first().copied().unwrap_or("").to_string();
312    for indent in candidates.iter().skip(1) {
313        prefix = common_prefix(&prefix, indent);
314    }
315    let mut out: Vec<&str> = Vec::with_capacity(lines.len());
316    for (idx, line) in lines.iter().enumerate() {
317        if (inline_first && idx == 0) || line.trim().is_empty() {
318            out.push(line);
319        } else {
320            out.push(line.strip_prefix(prefix.as_str()).unwrap_or(line));
321        }
322    }
323    out.join("\n")
324}
325
326/// Split one leading newline preceded only by spaces/tabs.
327fn split_leading_newline(s: &str) -> Option<&str> {
328    let trimmed = s.trim_start_matches([' ', '\t']);
329    trimmed.strip_prefix('\n')
330}
331
332/// Longest shared prefix of two indent strings.
333fn common_prefix(a: &str, b: &str) -> String {
334    a.chars()
335        .zip(b.chars())
336        .take_while(|(x, y)| x == y)
337        .map(|(x, _)| x)
338        .collect()
339}
340
341/// Single-token `KEY=value` split for direct `lower_command` callers and
342/// exotic keys the grammar cannot classify (single tokens only : no whitespace
343/// reassembly, so the quoted-space corruption class cannot arise here).
344/// Returns `Ok(None)` when there is no `=`.
345pub fn split_assignment(text: &str) -> DiagnosticResult<Option<(String, Arg)>> {
346    let Some((key, raw)) = text.split_once('=') else {
347        return Ok(None);
348    };
349    if key.is_empty() {
350        return Err(dsl_diag::assignment_requires_key_value());
351    }
352    Ok(Some((
353        key.to_string(),
354        Arg::String(strip_surrounding_quotes(raw).to_string(), false),
355    )))
356}
357
358/// Parse a TIMEOUT duration token (`500ms`, `10s`, `2m`, `1h`; a bare
359/// number means seconds). One optional space may separate the number
360/// from its unit (`30 s`), like byte counts: bare DSL tokens still
361/// split upstream, so this covers quoted strings and variables.
362pub fn parse_duration(s: &str) -> DiagnosticResult<std::time::Duration> {
363    let s = join_single_space(s)?;
364    let (digits, unit_ms): (&str, u64) = if let Some(v) = s.strip_suffix("ms") {
365        (v, 1)
366    } else if let Some(v) = s.strip_suffix('s') {
367        (v, 1_000)
368    } else if let Some(v) = s.strip_suffix('m') {
369        (v, 60_000)
370    } else if let Some(v) = s.strip_suffix('h') {
371        (v, 3_600_000)
372    } else {
373        (s.as_str(), 1_000)
374    };
375    let n: u64 = digits
376        .parse()
377        .map_err(|_| dsl_diag::invalid_timeout_duration(&s))?;
378    let millis = n
379        .checked_mul(unit_ms)
380        .ok_or_else(|| dsl_diag::timeout_duration_out_of_range(&s))?;
381    if millis == 0 {
382        return Err(dsl_diag::timeout_duration_not_positive(&s));
383    }
384    Ok(std::time::Duration::from_millis(millis))
385}
386
387/// Canonical display for a duration: largest exact unit (`500ms`, `10s`,
388/// `2m`, `1h`), falling back to milliseconds. Round-trips through
389/// [`parse_duration`].
390pub fn format_duration(d: &std::time::Duration) -> String {
391    let millis = d.as_millis();
392    if millis.is_multiple_of(3_600_000) {
393        format!("{}h", millis / 3_600_000)
394    } else if millis.is_multiple_of(60_000) {
395        format!("{}m", millis / 60_000)
396    } else if millis.is_multiple_of(1_000) {
397        format!("{}s", millis / 1_000)
398    } else {
399        format!("{millis}ms")
400    }
401}
402
403/// Strip Rust-style `_` digit separators when well-formed (digits and
404/// at most one `.`, separators only between digits, never leading,
405/// trailing, or doubled, with an optional leading `+`/`-` sign passing
406/// through for signed domains); otherwise return the text untouched so
407/// the caller's own parse decides. The single rule behind every
408/// string-to-number coercion (`INT` validation, assertion operands,
409/// byte counts), so `1_000_000` and `-1_000` read identically everywhere
410/// while `1__0` and `1_` never silently become numbers. Unsigned
411/// callers still reject `-` at parse time; `+` parses like every other
412/// Rust-parsed number in the DSL.
413pub fn strip_digit_separators(text: &str) -> String {
414    let body = text
415        .strip_prefix('+')
416        .or_else(|| text.strip_prefix('-'))
417        .unwrap_or(text);
418    let bytes = body.as_bytes();
419    let well_formed = !body.is_empty()
420        && bytes[0].is_ascii_digit()
421        && bytes[bytes.len() - 1].is_ascii_digit()
422        && bytes
423            .iter()
424            .all(|b| b.is_ascii_digit() || *b == b'_' || *b == b'.')
425        && !body.contains("__")
426        && body.bytes().filter(|b| *b == b'.').count() <= 1;
427    if well_formed {
428        text.replace('_', "")
429    } else {
430        text.to_string()
431    }
432}
433
434/// Join a numeric token whose unit may ride separated by one space
435/// (`1 GB`, `30 s`): surrounding whitespace trims, and exactly two
436/// whitespace-separated parts rejoin digit-run plus unit. Anything else
437/// (three parts, a split digit run like `1 0`, an empty string) fails:
438/// the space may only separate the number from its unit, never split
439/// the digits themselves.
440fn join_single_space(s: &str) -> DiagnosticResult<String> {
441    let mut parts = s.split_whitespace();
442    let (first, second) = (parts.next(), parts.next());
443    if parts.next().is_some() {
444        return Err(dsl_diag::invalid_numeric_token(s));
445    }
446    match (first, second) {
447        (Some(digits), None) => Ok(digits.to_string()),
448        (Some(digits), Some(unit))
449            if digits
450                .strip_prefix('+')
451                .unwrap_or(digits)
452                .bytes()
453                .all(|b| b.is_ascii_digit() || b == b'_')
454                && unit.bytes().all(|b| b.is_ascii_alphabetic()) =>
455        {
456            Ok(format!("{digits}{unit}"))
457        }
458        _ => Err(dsl_diag::invalid_numeric_token(s)),
459    }
460}
461
462/// Parse a byte-count token (`500`, `500B`, `10KB`, `2MB`, `1GB`, `1TB`
463/// decimal; `10KIB`, `2MIB`, `1GIB`, `1TIB` binary; a bare number means
464/// bytes). Digit runs may group with `_` separators (`1_000_000`),
465/// Rust-literal style: leading, trailing, and doubled separators fail.
466/// One optional space may separate the number from its unit (`1 GB`);
467/// anything more stays rejected, and bare DSL tokens still split
468/// upstream (this covers quoted strings, variables, and flag values).
469/// Fractions stay rejected by design (`1.5GB` fails: float parsing
470/// cannot hold exact byte boundaries past 2^53, and every sub-unit has
471/// an exact integer spelling like `1500MB`). Matching is
472/// case-insensitive (`1gb`, `1GB`, and `1Gb` agree), mirroring
473/// [`parse_duration`]: digits only, no fractions, no signs.
474pub fn parse_byte_count(s: &str) -> DiagnosticResult<u64> {
475    let compact = join_single_space(s)?;
476    let s = compact.as_str();
477    let lower = s.to_ascii_lowercase();
478    let (digits, unit): (&str, u64) = if let Some(v) = lower.strip_suffix("kib") {
479        (v, 1 << 10)
480    } else if let Some(v) = lower.strip_suffix("mib") {
481        (v, 1 << 20)
482    } else if let Some(v) = lower.strip_suffix("gib") {
483        (v, 1 << 30)
484    } else if let Some(v) = lower.strip_suffix("tib") {
485        (v, 1 << 40)
486    } else if let Some(v) = lower.strip_suffix("kb") {
487        (v, 1_000)
488    } else if let Some(v) = lower.strip_suffix("mb") {
489        (v, 1_000_000)
490    } else if let Some(v) = lower.strip_suffix("gb") {
491        (v, 1_000_000_000)
492    } else if let Some(v) = lower.strip_suffix("tb") {
493        (v, 1_000_000_000_000)
494    } else if let Some(v) = lower.strip_suffix('b') {
495        (v, 1)
496    } else {
497        (lower.as_str(), 1)
498    };
499    // Suffixes strip from the lowercased copy; slice the original at
500    // the same boundary so errors echo the caller's spelling.
501    // Separators follow the shared rule, so `1_0KB` parses while
502    // `1__0KB` fails like everywhere else. A leading `+` strips before
503    // the unsigned parse (`u64` rejects it; `-` still fails below).
504    let digits = strip_digit_separators(&s[..digits.len()]);
505    let digits = digits.strip_prefix('+').unwrap_or(&digits);
506    let n: u64 = digits
507        .parse()
508        .map_err(|_| dsl_diag::invalid_byte_count(s))?;
509    let bytes = n
510        .checked_mul(unit)
511        .ok_or_else(|| dsl_diag::byte_count_out_of_range(s))?;
512    if bytes == 0 {
513        return Err(dsl_diag::byte_count_not_positive(s));
514    }
515    Ok(bytes)
516}
517
518/// Canonical display for a byte count: largest exact unit (`500B`,
519/// `10KB`, `2MB`, `1GB`, binary `10KIB` and friends), falling back to
520/// bytes. Round-trips through [`parse_byte_count`].
521pub fn format_byte_count(n: u64) -> String {
522    const TIB: u64 = 1 << 40;
523    const TB: u64 = 1_000_000_000_000;
524    const GIB: u64 = 1 << 30;
525    const GB: u64 = 1_000_000_000;
526    const MIB: u64 = 1 << 20;
527    const MB: u64 = 1_000_000;
528    const KIB: u64 = 1 << 10;
529    const KB: u64 = 1_000;
530    if n >= TIB && n.is_multiple_of(TIB) {
531        format!("{}TiB", n / TIB)
532    } else if n >= TB && n.is_multiple_of(TB) {
533        format!("{}TB", n / TB)
534    } else if n >= GIB && n.is_multiple_of(GIB) {
535        format!("{}GiB", n / GIB)
536    } else if n >= GB && n.is_multiple_of(GB) {
537        format!("{}GB", n / GB)
538    } else if n >= MIB && n.is_multiple_of(MIB) {
539        format!("{}MiB", n / MIB)
540    } else if n >= MB && n.is_multiple_of(MB) {
541        format!("{}MB", n / MB)
542    } else if n >= KIB && n.is_multiple_of(KIB) {
543        format!("{}KiB", n / KIB)
544    } else if n >= KB && n.is_multiple_of(KB) {
545        format!("{}KB", n / KB)
546    } else {
547        format!("{n}B")
548    }
549}
550
551/// Data direction for an argument.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub enum IoDirection {
554    Read,
555    Write,
556}
557
558/// Stream type for fallback or default output.
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum Stream {
561    Stdin,
562    Stdout,
563    Stderr,
564}
565
566/// Metadata for a single flag.
567pub struct FlagSpec {
568    pub name: &'static str,
569    pub long: &'static str,
570    pub value_type: FlagValueType,
571    pub required: bool,
572    pub description: &'static str,
573}
574
575/// Type of value a flag accepts.
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub enum FlagValueType {
578    /// Boolean flag (no value required).
579    Flag,
580    /// String-valued flag.
581    String,
582    /// Integer-valued flag.
583    Int,
584}
585
586impl FlagValueType {
587    /// Display label using the type vocabulary. A bare `Flag`
588    /// switch carries no value; `BOOL` names what its presence asserts.
589    pub fn label(&self) -> &'static str {
590        match self {
591            FlagValueType::Flag => BOOL_TYPE_NAME,
592            FlagValueType::String => STRING_TYPE_NAME,
593            FlagValueType::Int => INT_TYPE_NAME,
594        }
595    }
596}
597
598/// Complete metadata for a command.
599pub struct CommandMeta {
600    pub name: &'static str,
601    pub syntax: &'static str,
602    pub summary: &'static str,
603    pub description: &'static str,
604    pub args: &'static [ArgSpec],
605    pub flags: &'static [FlagSpec],
606    pub default_output: Option<Stream>,
607    pub examples: &'static [Example],
608    /// Whether the entry lists in the command index table. Structural
609    /// pseudo-entries with no typable keyword (e.g. `MUTATION` for
610    /// `$var = <expr>`) document in the body but stay out of the index.
611    pub in_index: bool,
612}
613
614/// An executable example for a command or function.
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
616pub struct Example {
617    pub name: &'static str,
618    pub fence_meta: Option<&'static str>,
619    pub code: &'static str,
620}
621
622/// Trait for command metadata and lowering. No execution types.
623///
624/// This trait lives in `oxdock-parser` and has zero dependencies on
625/// `oxdock-core`. Execution dispatch is handled separately by the
626/// `define_pipeline!` macro in `oxdock-core`.
627pub trait CommandSpec {
628    const NAME: &'static str;
629
630    fn metadata() -> CommandMeta;
631    fn lower(flags: Vec<(String, Arg)>, args: Vec<Arg>) -> ParseResult<StepKind>;
632}
633
634#[cfg(test)]
635mod tests {
636    use super::*;
637    use crate::ast::Expr;
638
639    fn lit(text: &str) -> Arg {
640        Arg::String(text.to_string(), false)
641    }
642
643    fn var(name: &str) -> Arg {
644        Arg::Expr(Expr::Var {
645            name: name.to_string(),
646        })
647    }
648
649    #[test]
650    fn validate_literal_covers_each_variant() {
651        ArgType::String.check_arg(&lit("anything at all")).unwrap();
652        ArgType::Path.check_arg(&lit("a/b/../c")).unwrap();
653        ArgType::Int.check_arg(&lit("3")).unwrap();
654        assert!(ArgType::Int.check_arg(&lit("banana")).is_err());
655        ArgType::Duration.check_arg(&lit("10s")).unwrap();
656        ArgType::Duration.check_arg(&lit("30")).unwrap();
657        assert!(ArgType::Duration.check_arg(&lit("banana")).is_err());
658        assert!(ArgType::Duration.check_arg(&lit("0s")).is_err());
659        ArgType::List.check_arg(&lit("$x")).unwrap();
660        assert!(ArgType::List.check_arg(&lit("x")).is_err());
661        // Only app types plus the visibly-marked placeholder remain.
662        assert_eq!(ArgType::Any.label(), "<any>");
663        ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
664            .check_arg(&lit("LOCAL"))
665            .unwrap();
666        // Lowercase spellings are rejected: keyword arguments stay uppercase.
667        assert!(
668            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
669                .check_arg(&lit("local"))
670                .is_err()
671        );
672        assert!(
673            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
674                .check_arg(&lit("REMOTE"))
675                .is_err()
676        );
677    }
678
679    #[test]
680    fn check_arg_defers_dynamics_and_enforces_var() {
681        // Templates defer: their values only exist after interpolation.
682        assert_eq!(
683            ArgType::Duration.check_arg(&lit("{{ $d }}")).unwrap(),
684            CheckOutcome::Deferred
685        );
686        // Variables satisfy List statically and defer for everything else.
687        assert_eq!(
688            ArgType::List.check_arg(&var("x")).unwrap(),
689            CheckOutcome::Static
690        );
691        assert_eq!(
692            ArgType::Duration.check_arg(&var("d")).unwrap(),
693            CheckOutcome::Deferred
694        );
695        // Non-variable expressions where a $var is required fail at lower.
696        let list = Arg::Expr(Expr::List(vec![]));
697        assert!(ArgType::List.check_arg(&list).is_err());
698        assert_eq!(
699            ArgType::String.check_arg(&list).unwrap(),
700            CheckOutcome::Deferred
701        );
702        assert_eq!(ArgType::List.label(), "LIST");
703        // `$var` shapes are enforced per command in `lower`, not here:
704        // a bare word passes the String check and fails lowering.
705        assert_eq!(
706            ArgType::String.check_arg(&lit("x")).unwrap(),
707            CheckOutcome::Static
708        );
709    }
710
711    fn spec(index: usize, required: bool, arg_type: ArgType) -> ArgSpec {
712        ArgSpec {
713            name: "p",
714            arg_type,
715            description: "",
716            io: IoDirection::Write,
717            index,
718            required,
719            fallback_stream: None,
720        }
721    }
722
723    #[test]
724    fn positionals_enforce_required_and_rest_tails() {
725        let specs = [spec(0, true, ArgType::Int)];
726        assert!(validate_positionals_against_meta("T", &specs, &[]).is_err());
727        assert!(validate_positionals_against_meta("T", &specs, &[lit("3")]).is_ok());
728        assert!(validate_positionals_against_meta("T", &specs, &[lit("banana")]).is_err());
729
730        // Rest validates EVERY trailing positional, not just the first.
731        let specs = [ArgSpec {
732            arg_type: ArgType::Rest(&ArgType::Int),
733            ..spec(0, true, ArgType::Int)
734        }];
735        assert!(
736            validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2"), lit("banana")])
737                .is_err()
738        );
739        assert!(validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2")]).is_ok());
740        // Extras beyond fixed-arity specs fail (no silent truncation).
741        let specs = [spec(0, true, ArgType::Int)];
742        let err = validate_positionals_against_meta("T", &specs, &[lit("1"), lit("extra")])
743            .expect_err("extras must fail");
744        assert!(
745            err.to_string().contains("at most 1"),
746            "unexpected error: {err:#}"
747        );
748    }
749}