oxdock-parser 0.10.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
use crate::ast::{Arg, Expr, StepKind};
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.
///
/// The closed enum keeps the vocabulary compiler-checked and lets
/// docs-gen link each type cell to its reference section instead of
/// printing bare words like `duration` with no explanation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgType {
    String,
    Path,
    Int,
    Duration,
    Var,
    KeyValue,
    /// 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 {
    /// The documented types, in reference-section order.
    pub const CANONICAL: &[ArgType] = &[
        ArgType::String,
        ArgType::Path,
        ArgType::Int,
        ArgType::Duration,
        ArgType::Var,
        ArgType::KeyValue,
    ];

    /// Table-cell label, e.g. `duration` or `SNAPSHOT|LOCAL`.
    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::Var => "$var".to_string(),
            ArgType::KeyValue => "KEY=value".to_string(),
            ArgType::OneOf(options) => options.join("|"),
            ArgType::Rest(inner) => format!("{}...", inner.label()),
        }
    }

    /// Anchor of the type's reference section (`### Value type: <label>`),
    /// or `None` for self-describing inline alternations.
    pub fn anchor(&self) -> Option<&'static str> {
        match self {
            ArgType::String => Some("value-type-string"),
            ArgType::Path => Some("value-type-path"),
            ArgType::Int => Some("value-type-int"),
            ArgType::Duration => Some("value-type-duration"),
            ArgType::Var => Some("value-type-var"),
            // Slugger strips `=` rather than hyphenating it: the heading
            // `### Value type: KEY=value` anchors as `value-type-keyvalue`.
            ArgType::KeyValue => Some("value-type-keyvalue"),
            ArgType::OneOf(_) => None,
            ArgType::Rest(inner) => inner.anchor(),
        }
    }

    /// Reference-section (title, body) for the canonical types.
    pub fn doc(&self) -> Option<(&'static str, &'static str)> {
        match self {
            ArgType::String => Some((
                "Value type: string",
                "Arbitrary text under the unified string-value rules: quotes keep exact bytes, a lone `$var` evaluates, and `{{ ... }}` placeholders interpolate.",
            )),
            ArgType::Path => Some((
                "Value type: path",
                "Workspace path, resolved against the current working directory and guarded against escaping the workspace.",
            )),
            ArgType::Int => Some(("Value type: int", "Integer, e.g. an exit code.")),
            ArgType::Duration => Some((
                "Value type: duration",
                "Positive time span: a number with an `ms`, `s`, `m`, or `h` suffix — a bare number means seconds — e.g. `500ms`, `10s`, `2m`.",
            )),
            ArgType::Var => Some((
                "Value type: $var",
                "Script variable reference. The `$` sigil is mandatory.",
            )),
            ArgType::KeyValue => Some((
                "Value type: KEY=value",
                "`KEY=value` assignment splitting on the first `=` (`KEY=a=b` stores `a=b`). Values follow the unified string-value rules.",
            )),
            ArgType::OneOf(_) | ArgType::Rest(_) => None,
        }
    }

    /// 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 => Ok(()),
            ArgType::Int => literal
                .parse::<i32>()
                .map(|_| ())
                .map_err(|_| anyhow!("expected int, got {literal:?}")),
            ArgType::Duration => parse_duration(literal).map(|_| ()),
            ArgType::Var => {
                if literal.starts_with('$') {
                    Ok(())
                } else {
                    bail!("expected $var, got {literal:?}")
                }
            }
            ArgType::KeyValue => match split_assignment(literal)? {
                Some(_) => Ok(()),
                None => bail!("expected KEY=value, got {literal:?}"),
            },
            ArgType::OneOf(options) => {
                // Match the lower-time normalization: bare lowercase
                // spellings are accepted alongside exact options.
                if options
                    .iter()
                    .any(|o| *o == literal || o.to_lowercase() == 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 `Var` 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 *self == ArgType::Var {
                    Ok(CheckOutcome::Static)
                } else {
                    Ok(CheckOutcome::Deferred)
                }
            }
            Arg::Expr(_) => {
                if *self == ArgType::Var {
                    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<()> {
    let has_rest = specs
        .last()
        .is_some_and(|s| matches!(s.arg_type, ArgType::Rest(_)));

    if !has_rest && args.len() > specs.len() {
        bail!(
            "invalid syntax for command {cmd_name}: expects at most {} positional argument(s), got {}",
            specs.len(),
            args.len()
        );
    }

    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 {
                bail!(
                    "invalid syntax for command {cmd_name}: requires argument `{}`",
                    spec.name
                )
            }
            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 => {
                bail!(
                    "invalid syntax for command {cmd_name}: requires argument `{}`",
                    spec.name
                )
            }
            None => {}
        }
    }
    Ok(())
}

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

/// 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).
pub fn parse_duration(s: &str) -> Result<std::time::Duration> {
    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, 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")
    }
}

/// 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,
}

/// 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.
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::Var.check_arg(&lit("$x")).unwrap();
        assert!(ArgType::Var.check_arg(&lit("x")).is_err());
        ArgType::KeyValue.check_arg(&lit("K=v")).unwrap();
        ArgType::KeyValue.check_arg(&lit("K=a=b")).unwrap();
        assert!(ArgType::KeyValue.check_arg(&lit("no-equals")).is_err());
        assert!(ArgType::KeyValue.check_arg(&lit("=v")).is_err());
        ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
            .check_arg(&lit("LOCAL"))
            .unwrap();
        // Lowercase spellings stay accepted (WORKSPACE parity).
        ArgType::OneOf(&["SNAPSHOT", "LOCAL"])
            .check_arg(&lit("local"))
            .unwrap();
        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 Var statically and defer for everything else.
        assert_eq!(
            ArgType::Var.check_arg(&var("x")).unwrap(),
            CheckOutcome::Static
        );
        assert_eq!(
            ArgType::Duration.check_arg(&var("d")).unwrap(),
            CheckOutcome::Deferred
        );
        // Non-variable expressions where Var is required fail at lower.
        let list = Arg::Expr(Expr::List(vec![]));
        assert!(ArgType::Var.check_arg(&list).is_err());
        assert_eq!(
            ArgType::String.check_arg(&list).unwrap(),
            CheckOutcome::Deferred
        );
    }

    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:#}"
        );
    }
}