oxdock-parser 0.28.0-alpha

Parser and AST definitions for the OxDock DSL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use crate::ast::{Arg, Expr, StepKind};
use crate::error::{ParseError, SpanContext};
use anyhow::{Result, anyhow, bail};

/// Metadata for a single command argument.
pub struct ArgSpec {
    pub name: &'static str,
    pub arg_type: ArgType,
    pub description: &'static str,
    pub io: IoDirection,
    pub index: usize,
    pub required: bool,
    pub fallback_stream: Option<Stream>,
}

/// Closed vocabulary for argument value types: every variant names a
/// type explicitly present in the app, so the reference table never
/// lists a type that does not exist. Shapes (`$var` targets, `KEY=value`
/// pairs) are not types: the central validator only checks value types
/// and arity, while each command's `lower` enforces its own shapes with
/// command-specific errors.
/// [`ArgType::Any`] is the single exception: it renders as `<any>`,
/// visibly a placeholder rather than a type name.
/// [`ArgType::OneOf`] renders its inline options, likewise self-describing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgType {
    String,
    Path,
    Int,
    Duration,
    /// A `$variable` that must hold a LIST at runtime. Non-variable
    /// expressions fail at lower time; renders linked as `LIST`.
    List,
    /// Any evaluated value (plus stream markers like `stdout` where the
    /// command accepts them). Renders unlinked as `<any>`, visibly a
    /// placeholder rather than a type name.
    Any,
    /// Inline alternation for one-off enums (e.g. `SNAPSHOT|LOCAL`).
    /// Self-describing, so it renders unlinked.
    OneOf(&'static [&'static str]),
    /// Trailing variadic repetition (e.g. `RUN`'s `string...`).
    Rest(&'static ArgType),
}

impl ArgType {
    /// Table-cell label for the argument table's Type column.
    /// Canonical value types use their descriptor names; `ANY` renders
    /// as `<any>` and inline alternations render their options, so
    /// neither reads as a standalone type. Shapes (`$var` targets,
    /// `KEY=value` pairs) are validated in each command's `lower`, and
    /// the shape requirement lives in the argument description and
    /// command syntax.
    pub fn label(&self) -> String {
        match self {
            ArgType::String => "STRING".to_string(),
            ArgType::Path => "PATH".to_string(),
            ArgType::Int => "INT".to_string(),
            ArgType::Duration => "DURATION".to_string(),
            ArgType::List => "LIST".to_string(),
            ArgType::Any => "<any>".to_string(),
            ArgType::OneOf(options) => options.join("|"),
            ArgType::Rest(inner) => format!("{}...", inner.label()),
        }
    }

    /// Anchor of the type's reference section. Only types with a value-type
    /// reference section link; `<any>` and inline alternations render
    /// unlinked.
    pub fn anchor(&self) -> Option<String> {
        match self {
            ArgType::String => Some(crate::value::type_anchor("STRING")),
            ArgType::Path => Some(crate::value::type_anchor("PATH")),
            ArgType::Int => Some(crate::value::type_anchor("INT")),
            ArgType::Duration => Some(crate::value::type_anchor("DURATION")),
            ArgType::List => Some(crate::value::type_anchor("LIST")),
            ArgType::Any => None,
            ArgType::OneOf(_) => None,
            ArgType::Rest(inner) => inner.anchor(),
        }
    }

    /// Validate a statically-known literal against this type.
    /// Templates and variables are never passed here : see `check_arg`.
    pub fn validate_literal(&self, literal: &str) -> Result<()> {
        match self {
            ArgType::String | ArgType::Path | ArgType::Any => Ok(()),
            ArgType::Int => strip_digit_separators(literal)
                .parse::<i64>()
                .map(|_| ())
                .map_err(|_| anyhow!("expected int, got {literal:?}")),
            ArgType::Duration => parse_duration(literal).map(|_| ()),
            ArgType::List => {
                if literal.starts_with('$') {
                    Ok(())
                } else {
                    bail!("expected $var, got {literal:?}")
                }
            }
            ArgType::OneOf(options) => {
                // Exact match only: lowercase spellings are rejected so
                // keyword arguments stay uppercase across the DSL.
                if options.contains(&literal) {
                    Ok(())
                } else {
                    bail!("expected one of {}, got {literal:?}", options.join("|"))
                }
            }
            ArgType::Rest(inner) => inner.validate_literal(literal),
        }
    }

    /// Classify one positional arg for lower-time checking.
    /// `Static` literals validate now; templates, variables (except a
    /// `$var` where `List` is required), and mixed fragments defer to the
    /// runtime resolvers, which see interpolated values.
    pub fn check_arg(&self, arg: &Arg) -> Result<CheckOutcome> {
        match arg {
            Arg::String(s, _) if !s.contains("{{") => {
                self.validate_literal(s)?;
                Ok(CheckOutcome::Static)
            }
            Arg::String(_, _) => Ok(CheckOutcome::Deferred),
            Arg::Parts(_) => Ok(CheckOutcome::Deferred),
            Arg::Expr(Expr::Var(_)) => {
                if matches!(*self, ArgType::List) {
                    Ok(CheckOutcome::Static)
                } else {
                    Ok(CheckOutcome::Deferred)
                }
            }
            Arg::Expr(_) => {
                if matches!(*self, ArgType::List) {
                    bail!("expected $var, got expression {}", arg.render())
                } else {
                    Ok(CheckOutcome::Deferred)
                }
            }
        }
    }
}

/// Lower-time checking outcome for one positional arg.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckOutcome {
    /// Validated now; nothing deferred.
    Static,
    /// Unknowable until runtime (template, variable, or fragment);
    /// runtime resolvers enforce the type on the resolved value.
    Deferred,
}

/// Validate positional args against a command's declared specs.
/// Missing required positionals, statically-known type violations, and
/// trailing positionals beyond a fixed-arity spec all fail here;
/// templates, variables, and fragments defer to the runtime resolvers.
/// A trailing `Rest` spec absorbs any number of positionals.
pub fn validate_positionals_against_meta(
    cmd_name: &str,
    specs: &[ArgSpec],
    args: &[Arg],
) -> Result<(), ParseError> {
    let has_rest = specs
        .last()
        .is_some_and(|s| matches!(s.arg_type, ArgType::Rest(_)));

    if !has_rest && args.len() > specs.len() {
        return Err(ParseError::validation(
            cmd_name,
            format!(
                "invalid syntax for command {cmd_name}: expects at most {} positional argument(s), got {}",
                specs.len(),
                args.len()
            ),
            &SpanContext::line_only(0),
        ));
    }

    for spec in specs {
        if let ArgType::Rest(inner) = spec.arg_type {
            // Variadic tail: every trailing positional checks against
            // the inner type, not just the first.
            let tail = args.get(spec.index..).unwrap_or(&[]);
            if tail.is_empty() && spec.required {
                return Err(ParseError::validation(
                    cmd_name,
                    format!(
                        "invalid syntax for command {cmd_name}: requires argument `{}`",
                        spec.name
                    ),
                    &SpanContext::line_only(0),
                ));
            }
            for arg in tail {
                check_one(cmd_name, spec, inner, arg)?;
            }
            return Ok(());
        }
        match args.get(spec.index) {
            Some(arg) => check_one(cmd_name, spec, &spec.arg_type, arg)?,
            None if spec.required => {
                return Err(ParseError::validation(
                    cmd_name,
                    format!(
                        "invalid syntax for command {cmd_name}: requires argument `{}`",
                        spec.name
                    ),
                    &SpanContext::line_only(0),
                ));
            }
            None => {}
        }
    }
    Ok(())
}

fn check_one(
    cmd_name: &str,
    spec: &ArgSpec,
    arg_type: &ArgType,
    arg: &Arg,
) -> Result<(), ParseError> {
    match arg_type.check_arg(arg) {
        Ok(_) => Ok(()),
        Err(e) => Err(ParseError::validation(
            cmd_name,
            format!(
                "invalid syntax for command {cmd_name}: argument `{}` got {} — {e:#}",
                spec.name,
                arg.render()
            ),
            &SpanContext::line_only(0),
        )),
    }
}

/// Strip one layer of surrounding `"` or `'` quotes (both kinds, everywhere).
pub fn strip_surrounding_quotes(value: &str) -> &str {
    value
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| value.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')))
        .unwrap_or(value)
}

/// Single-token `KEY=value` split for direct `lower_command` callers and
/// exotic keys the grammar cannot classify (single tokens only : no whitespace
/// reassembly, so the quoted-space corruption class cannot arise here).
/// Returns `Ok(None)` when there is no `=`.
pub fn split_assignment(text: &str) -> Result<Option<(String, Arg)>> {
    let Some((key, raw)) = text.split_once('=') else {
        return Ok(None);
    };
    if key.is_empty() {
        bail!("assignment requires KEY=value format");
    }
    Ok(Some((
        key.to_string(),
        Arg::String(strip_surrounding_quotes(raw).to_string(), false),
    )))
}

/// Parse a TIMEOUT duration token (`500ms`, `10s`, `2m`, `1h`; a bare
/// number means seconds). One optional space may separate the number
/// from its unit (`30 s`), like byte counts: bare DSL tokens still
/// split upstream, so this covers quoted strings and variables.
pub fn parse_duration(s: &str) -> Result<std::time::Duration> {
    let s = join_single_space(s)?;
    let (digits, unit_ms): (&str, u64) = if let Some(v) = s.strip_suffix("ms") {
        (v, 1)
    } else if let Some(v) = s.strip_suffix('s') {
        (v, 1_000)
    } else if let Some(v) = s.strip_suffix('m') {
        (v, 60_000)
    } else if let Some(v) = s.strip_suffix('h') {
        (v, 3_600_000)
    } else {
        (s.as_str(), 1_000)
    };
    let n: u64 = digits
        .parse()
        .map_err(|_| anyhow!("invalid TIMEOUT duration: {s}"))?;
    let millis = n
        .checked_mul(unit_ms)
        .ok_or_else(|| anyhow!("TIMEOUT duration out of range: {s}"))?;
    if millis == 0 {
        bail!("TIMEOUT duration must be positive, got: {s}");
    }
    Ok(std::time::Duration::from_millis(millis))
}

/// Canonical display for a duration: largest exact unit (`500ms`, `10s`,
/// `2m`, `1h`), falling back to milliseconds. Round-trips through
/// [`parse_duration`].
pub fn format_duration(d: &std::time::Duration) -> String {
    let millis = d.as_millis();
    if millis.is_multiple_of(3_600_000) {
        format!("{}h", millis / 3_600_000)
    } else if millis.is_multiple_of(60_000) {
        format!("{}m", millis / 60_000)
    } else if millis.is_multiple_of(1_000) {
        format!("{}s", millis / 1_000)
    } else {
        format!("{millis}ms")
    }
}

/// Strip Rust-style `_` digit separators when well-formed (digits and
/// at most one `.`, separators only between digits, never leading,
/// trailing, or doubled, with an optional leading `+`/`-` sign passing
/// through for signed domains); otherwise return the text untouched so
/// the caller's own parse decides. The single rule behind every
/// string-to-number coercion (`INT` validation, assertion operands,
/// byte counts), so `1_000_000` and `-1_000` read identically everywhere
/// while `1__0` and `1_` never silently become numbers. Unsigned
/// callers still reject `-` at parse time; `+` parses like every other
/// Rust-parsed number in the DSL.
pub fn strip_digit_separators(text: &str) -> String {
    let body = text
        .strip_prefix('+')
        .or_else(|| text.strip_prefix('-'))
        .unwrap_or(text);
    let bytes = body.as_bytes();
    let well_formed = !body.is_empty()
        && bytes[0].is_ascii_digit()
        && bytes[bytes.len() - 1].is_ascii_digit()
        && bytes
            .iter()
            .all(|b| b.is_ascii_digit() || *b == b'_' || *b == b'.')
        && !body.contains("__")
        && body.bytes().filter(|b| *b == b'.').count() <= 1;
    if well_formed {
        text.replace('_', "")
    } else {
        text.to_string()
    }
}

/// Join a numeric token whose unit may ride separated by one space
/// (`1 GB`, `30 s`): surrounding whitespace trims, and exactly two
/// whitespace-separated parts rejoin digit-run plus unit. Anything else
/// (three parts, a split digit run like `1 0`, an empty string) fails:
/// the space may only separate the number from its unit, never split
/// the digits themselves.
fn join_single_space(s: &str) -> Result<String> {
    let mut parts = s.split_whitespace();
    let (first, second) = (parts.next(), parts.next());
    if parts.next().is_some() {
        bail!("invalid numeric token: {s}");
    }
    match (first, second) {
        (Some(digits), None) => Ok(digits.to_string()),
        (Some(digits), Some(unit))
            if digits
                .strip_prefix('+')
                .unwrap_or(digits)
                .bytes()
                .all(|b| b.is_ascii_digit() || b == b'_')
                && unit.bytes().all(|b| b.is_ascii_alphabetic()) =>
        {
            Ok(format!("{digits}{unit}"))
        }
        _ => bail!("invalid numeric token: {s}"),
    }
}

/// Parse a byte-count token (`500`, `500B`, `10KB`, `2MB`, `1GB`, `1TB`
/// decimal; `10KIB`, `2MIB`, `1GIB`, `1TIB` binary; a bare number means
/// bytes). Digit runs may group with `_` separators (`1_000_000`),
/// Rust-literal style: leading, trailing, and doubled separators fail.
/// One optional space may separate the number from its unit (`1 GB`);
/// anything more stays rejected, and bare DSL tokens still split
/// upstream (this covers quoted strings, variables, and flag values).
/// Fractions stay rejected by design (`1.5GB` fails: float parsing
/// cannot hold exact byte boundaries past 2^53, and every sub-unit has
/// an exact integer spelling like `1500MB`). Matching is
/// case-insensitive (`1gb`, `1GB`, and `1Gb` agree), mirroring
/// [`parse_duration`]: digits only, no fractions, no signs.
pub fn parse_byte_count(s: &str) -> Result<u64> {
    let compact = join_single_space(s)?;
    let s = compact.as_str();
    let lower = s.to_ascii_lowercase();
    let (digits, unit): (&str, u64) = if let Some(v) = lower.strip_suffix("kib") {
        (v, 1 << 10)
    } else if let Some(v) = lower.strip_suffix("mib") {
        (v, 1 << 20)
    } else if let Some(v) = lower.strip_suffix("gib") {
        (v, 1 << 30)
    } else if let Some(v) = lower.strip_suffix("tib") {
        (v, 1 << 40)
    } else if let Some(v) = lower.strip_suffix("kb") {
        (v, 1_000)
    } else if let Some(v) = lower.strip_suffix("mb") {
        (v, 1_000_000)
    } else if let Some(v) = lower.strip_suffix("gb") {
        (v, 1_000_000_000)
    } else if let Some(v) = lower.strip_suffix("tb") {
        (v, 1_000_000_000_000)
    } else if let Some(v) = lower.strip_suffix('b') {
        (v, 1)
    } else {
        (lower.as_str(), 1)
    };
    // Suffixes strip from the lowercased copy; slice the original at
    // the same boundary so errors echo the caller's spelling.
    // Separators follow the shared rule, so `1_0KB` parses while
    // `1__0KB` fails like everywhere else. A leading `+` strips before
    // the unsigned parse (`u64` rejects it; `-` still fails below).
    let digits = strip_digit_separators(&s[..digits.len()]);
    let digits = digits.strip_prefix('+').unwrap_or(&digits);
    let n: u64 = digits
        .parse()
        .map_err(|_| anyhow!("invalid byte count: {s}"))?;
    let bytes = n
        .checked_mul(unit)
        .ok_or_else(|| anyhow!("byte count out of range: {s}"))?;
    if bytes == 0 {
        bail!("byte count must be positive, got: {s}");
    }
    Ok(bytes)
}

/// Canonical display for a byte count: largest exact unit (`500B`,
/// `10KB`, `2MB`, `1GB`, binary `10KIB` and friends), falling back to
/// bytes. Round-trips through [`parse_byte_count`].
pub fn format_byte_count(n: u64) -> String {
    const TIB: u64 = 1 << 40;
    const TB: u64 = 1_000_000_000_000;
    const GIB: u64 = 1 << 30;
    const GB: u64 = 1_000_000_000;
    const MIB: u64 = 1 << 20;
    const MB: u64 = 1_000_000;
    const KIB: u64 = 1 << 10;
    const KB: u64 = 1_000;
    if n >= TIB && n.is_multiple_of(TIB) {
        format!("{}TiB", n / TIB)
    } else if n >= TB && n.is_multiple_of(TB) {
        format!("{}TB", n / TB)
    } else if n >= GIB && n.is_multiple_of(GIB) {
        format!("{}GiB", n / GIB)
    } else if n >= GB && n.is_multiple_of(GB) {
        format!("{}GB", n / GB)
    } else if n >= MIB && n.is_multiple_of(MIB) {
        format!("{}MiB", n / MIB)
    } else if n >= MB && n.is_multiple_of(MB) {
        format!("{}MB", n / MB)
    } else if n >= KIB && n.is_multiple_of(KIB) {
        format!("{}KiB", n / KIB)
    } else if n >= KB && n.is_multiple_of(KB) {
        format!("{}KB", n / KB)
    } else {
        format!("{n}B")
    }
}

/// Data direction for an argument.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IoDirection {
    Read,
    Write,
}

/// Stream type for fallback or default output.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Stream {
    Stdin,
    Stdout,
    Stderr,
}

/// Metadata for a single flag.
pub struct FlagSpec {
    pub name: &'static str,
    pub long: &'static str,
    pub value_type: FlagValueType,
    pub required: bool,
    pub description: &'static str,
}

/// Type of value a flag accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlagValueType {
    /// Boolean flag (no value required).
    Flag,
    /// String-valued flag.
    String,
    /// Integer-valued flag.
    Int,
}

impl FlagValueType {
    /// Display label using the type vocabulary. A bare `Flag`
    /// switch carries no value; `BOOL` names what its presence asserts.
    pub fn label(&self) -> &'static str {
        match self {
            FlagValueType::Flag => "BOOL",
            FlagValueType::String => "STRING",
            FlagValueType::Int => "INT",
        }
    }
}

/// Complete metadata for a command.
pub struct CommandMeta {
    pub name: &'static str,
    pub syntax: &'static str,
    pub summary: &'static str,
    pub description: &'static str,
    pub args: &'static [ArgSpec],
    pub flags: &'static [FlagSpec],
    pub default_output: Option<Stream>,
    pub examples: &'static [Example],
}

/// An executable example for a command or function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Example {
    pub name: &'static str,
    pub fence_meta: Option<&'static str>,
    pub code: &'static str,
}

/// Trait for command metadata and lowering. No execution types.
///
/// This trait lives in `oxdock-parser` and has zero dependencies on
/// `oxdock-core`. Execution dispatch is handled separately by the
/// `define_pipeline!` macro in `oxdock-core`.
pub trait CommandSpec {
    const NAME: &'static str;

    fn metadata() -> CommandMeta;
    fn lower(flags: Vec<(String, Arg)>, args: Vec<Arg>) -> Result<StepKind>;
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Expr;

    fn lit(text: &str) -> Arg {
        Arg::String(text.to_string(), false)
    }

    fn var(name: &str) -> Arg {
        Arg::Expr(Expr::Var(name.to_string()))
    }

    #[test]
    fn validate_literal_covers_each_variant() {
        ArgType::String.check_arg(&lit("anything at all")).unwrap();
        ArgType::Path.check_arg(&lit("a/b/../c")).unwrap();
        ArgType::Int.check_arg(&lit("3")).unwrap();
        assert!(ArgType::Int.check_arg(&lit("banana")).is_err());
        ArgType::Duration.check_arg(&lit("10s")).unwrap();
        ArgType::Duration.check_arg(&lit("30")).unwrap();
        assert!(ArgType::Duration.check_arg(&lit("banana")).is_err());
        assert!(ArgType::Duration.check_arg(&lit("0s")).is_err());
        ArgType::List.check_arg(&lit("$x")).unwrap();
        assert!(ArgType::List.check_arg(&lit("x")).is_err());
        // Only app types plus the visibly-marked placeholder remain.
        assert_eq!(ArgType::Any.label(), "<any>");
        ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
            .check_arg(&lit("LOCAL"))
            .unwrap();
        // Lowercase spellings are rejected: keyword arguments stay uppercase.
        assert!(
            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
                .check_arg(&lit("local"))
                .is_err()
        );
        assert!(
            ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
                .check_arg(&lit("REMOTE"))
                .is_err()
        );
    }

    #[test]
    fn check_arg_defers_dynamics_and_enforces_var() {
        // Templates defer: their values only exist after interpolation.
        assert_eq!(
            ArgType::Duration.check_arg(&lit("{{ $d }}")).unwrap(),
            CheckOutcome::Deferred
        );
        // Variables satisfy List statically and defer for everything else.
        assert_eq!(
            ArgType::List.check_arg(&var("x")).unwrap(),
            CheckOutcome::Static
        );
        assert_eq!(
            ArgType::Duration.check_arg(&var("d")).unwrap(),
            CheckOutcome::Deferred
        );
        // Non-variable expressions where a $var is required fail at lower.
        let list = Arg::Expr(Expr::List(vec![]));
        assert!(ArgType::List.check_arg(&list).is_err());
        assert_eq!(
            ArgType::String.check_arg(&list).unwrap(),
            CheckOutcome::Deferred
        );
        assert_eq!(ArgType::List.label(), "LIST");
        // `$var` shapes are enforced per command in `lower`, not here:
        // a bare word passes the String check and fails lowering.
        assert_eq!(
            ArgType::String.check_arg(&lit("x")).unwrap(),
            CheckOutcome::Static
        );
    }

    fn spec(index: usize, required: bool, arg_type: ArgType) -> ArgSpec {
        ArgSpec {
            name: "p",
            arg_type,
            description: "",
            io: IoDirection::Write,
            index,
            required,
            fallback_stream: None,
        }
    }

    #[test]
    fn positionals_enforce_required_and_rest_tails() {
        let specs = [spec(0, true, ArgType::Int)];
        assert!(validate_positionals_against_meta("T", &specs, &[]).is_err());
        assert!(validate_positionals_against_meta("T", &specs, &[lit("3")]).is_ok());
        assert!(validate_positionals_against_meta("T", &specs, &[lit("banana")]).is_err());

        // Rest validates EVERY trailing positional, not just the first.
        let specs = [ArgSpec {
            arg_type: ArgType::Rest(&ArgType::Int),
            ..spec(0, true, ArgType::Int)
        }];
        assert!(
            validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2"), lit("banana")])
                .is_err()
        );
        assert!(validate_positionals_against_meta("T", &specs, &[lit("1"), lit("2")]).is_ok());
        // Extras beyond fixed-arity specs fail (no silent truncation).
        let specs = [spec(0, true, ArgType::Int)];
        let err = validate_positionals_against_meta("T", &specs, &[lit("1"), lit("extra")])
            .expect_err("extras must fail");
        assert!(
            err.to_string().contains("at most 1"),
            "unexpected error: {err:#}"
        );
    }
}