Skip to main content

oxdock_parser/
diagnostics.rs

1//! DSL spelling diagnostics, owned by `oxdock-parser`.
2//!
3//! One constructor per diagnostic at the owning function. Each carries
4//! a stable `dsl.*` key, structured fields, and a whole-sentence
5//! template. Call sites pass decoded values, never `format!` strings
6//! and never raw mid-parse text containing `WS_SENTINEL`; the
7//! transport sanitizes any residual marker so untrusted input cannot
8//! crash release.
9
10use oxdock_diagnostics::Diagnostic;
11
12use crate::constants::{
13    KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS, KEYWORD_ASYNC,
14    KEYWORD_AWAIT, KEYWORD_CANCEL, KEYWORD_CONST, KEYWORD_COPY, KEYWORD_COPY_GIT, KEYWORD_ENV,
15    KEYWORD_EXIT, KEYWORD_EXPAND, KEYWORD_EXPORT, KEYWORD_FUNC, KEYWORD_INHERIT_ENV,
16    KEYWORD_INSTALL, KEYWORD_LET, KEYWORD_LIST_APPEND, KEYWORD_MKDIR, KEYWORD_PROMPT,
17    KEYWORD_READ_LINE, KEYWORD_REMOTE, KEYWORD_REMOVE, KEYWORD_RUN, KEYWORD_SET_EXECUTABLE,
18    KEYWORD_SLEEP, KEYWORD_SYMLINK, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_UNARCHIVE,
19    KEYWORD_WITH_IO, KEYWORD_WORKDIR, KEYWORD_WORKSPACE, KEYWORD_WRITE, SCRIPT_MODULE_NAME,
20};
21use crate::tag::{
22    BOOL_TYPE_NAME, FLOAT_TYPE_NAME, HANDLE_TYPE_NAME, INT_TYPE_NAME, LIST_TYPE_NAME,
23    STRING_TYPE_NAME,
24};
25
26/// Structured field keys. Single spelling for the whole module:
27/// constructors reference these, never literals, so a key rename is
28/// one edit. Keys used once or twice stay inline at their single use.
29const FIELD_COMMAND: &str = "command";
30const FIELD_RULE: &str = "rule";
31const FIELD_GOT: &str = "got";
32const FIELD_FOUND: &str = "found";
33const FIELD_REASON: &str = "reason";
34const FIELD_ALIAS: &str = "alias";
35const FIELD_ARGUMENT: &str = "argument";
36const FIELD_FIELD: &str = "field";
37const FIELD_FIRST: &str = "first";
38const FIELD_FLAG: &str = "flag";
39const FIELD_MAX: &str = "max";
40const FIELD_SECOND: &str = "second";
41const FIELD_SPELLING: &str = "spelling";
42const FIELD_LINE: &str = "line";
43const FIELD_KEY: &str = "key";
44
45/// Decode a mid-parse fragment for user output: the transient
46/// `WS_SENTINEL` boundary becomes a space. Single owner for the decode
47/// rule in this crate.
48pub fn decode_spelling_fragment(raw: &str) -> String {
49    raw.replace(crate::tag::WS_SENTINEL, " ")
50}
51
52/// Second `ALIAS` on the same field.
53pub fn alias_duplicate_on_field(field: &str, first: &str, second: &str) -> Diagnostic {
54    let message = format!(
55        "field `{field}` already has alias `{first}`, found second alias `{second}`: only one `ALIAS` per field"
56    );
57    Diagnostic::new(
58        "dsl.alias.duplicate_on_field",
59        message,
60        Diagnostic::make_fields(&[
61            (FIELD_FIELD, field),
62            (FIELD_FIRST, first),
63            (FIELD_SECOND, second),
64        ]),
65    )
66}
67
68/// `ALIAS` without a named field.
69pub fn alias_needs_field(got: &str) -> Diagnostic {
70    let message = format!("`ALIAS` needs a named field, found bare {got:?}");
71    Diagnostic::new(
72        "dsl.alias.needs_field",
73        message,
74        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
75    )
76}
77
78/// `ALIAS` without a lowercase alias name.
79pub fn alias_needs_name() -> Diagnostic {
80    Diagnostic::new(
81        "dsl.alias.needs_name",
82        "`ALIAS` needs a lowercase alias name".to_string(),
83        Diagnostic::make_fields(&[]),
84    )
85}
86
87/// `ALIAS` name must start lowercase. Takes the decoded offending
88/// character and the decoded spelling; the template owns quoting.
89pub fn alias_name_lowercase(found: &str, spelling: &str) -> Diagnostic {
90    let message = format!("`ALIAS` name must start lowercase, found {found:?} in {spelling:?}");
91    Diagnostic::new(
92        "dsl.alias.name_lowercase",
93        message,
94        Diagnostic::make_fields(&[(FIELD_FOUND, found), (FIELD_SPELLING, spelling)]),
95    )
96}
97
98/// Unexpected trailing text after a complete spelling.
99pub fn spelling_trailing_text(got: &str) -> Diagnostic {
100    let message = format!("unexpected trailing text in type spelling: {got:?}");
101    Diagnostic::new(
102        "dsl.spelling.trailing_text",
103        message,
104        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
105    )
106}
107
108/// Generic nesting deeper than the cap. Takes the numeric cap so no
109/// `format!` leaks to the call site.
110pub fn spelling_max_depth(max: usize, got: &str) -> Diagnostic {
111    let message = format!("type spelling exceeds maximum generic depth of {max}: {got:?}");
112    Diagnostic::new(
113        "dsl.spelling.max_depth",
114        message,
115        Diagnostic::make_fields(&[(FIELD_MAX, &max.to_string()), (FIELD_FOUND, got)]),
116    )
117}
118
119/// Expected a type name but found end of input.
120pub fn spelling_expected_type_name() -> Diagnostic {
121    Diagnostic::new(
122        "dsl.spelling.expected_type_name",
123        "expected type name, found end of spelling".to_string(),
124        Diagnostic::make_fields(&[]),
125    )
126}
127
128/// Expected an uppercase type name. Takes the decoded character.
129pub fn spelling_expected_uppercase(found: &str) -> Diagnostic {
130    let message = format!("expected uppercase type name, found {found:?}");
131    Diagnostic::new(
132        "dsl.spelling.expected_uppercase",
133        message,
134        Diagnostic::make_fields(&[(FIELD_FOUND, found)]),
135    )
136}
137
138/// Expected `,` or `>` to continue a generic spelling.
139pub fn spelling_expected_delimiter(got: &str) -> Diagnostic {
140    let message = format!("expected ',' or '>' in type spelling, found {got:?}");
141    Diagnostic::new(
142        "dsl.spelling.expected_delimiter",
143        message,
144        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
145    )
146}
147
148/// Unterminated quoted string default.
149pub fn spelling_unterminated_string(got: &str) -> Diagnostic {
150    let message = format!("unterminated string default in type spelling: {got:?}");
151    Diagnostic::new(
152        "dsl.spelling.unterminated_string",
153        message,
154        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
155    )
156}
157
158/// Expected a default literal.
159pub fn spelling_expected_literal(got: &str) -> Diagnostic {
160    let message = format!(
161        "expected default literal ({INT_TYPE_NAME}, {FLOAT_TYPE_NAME}, {BOOL_TYPE_NAME}, or quoted {STRING_TYPE_NAME}) in type spelling, found {got:?}"
162    );
163    Diagnostic::new(
164        "dsl.spelling.expected_literal",
165        message,
166        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
167    )
168}
169
170/// Float default that does not parse as finite.
171pub fn spelling_invalid_float(got: &str) -> Diagnostic {
172    let message = format!("bad float default in type spelling: {got:?}");
173    Diagnostic::new(
174        "dsl.spelling.invalid_float",
175        message,
176        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
177    )
178}
179
180/// Integer default that does not parse.
181pub fn spelling_invalid_int(got: &str) -> Diagnostic {
182    let message = format!("bad integer default in type spelling: {got:?}");
183    Diagnostic::new(
184        "dsl.spelling.invalid_int",
185        message,
186        Diagnostic::make_fields(&[(FIELD_FOUND, got)]),
187    )
188}
189
190/// Comment inside an `IMPORT`/`EXPORT` bracket name list. Takes the
191/// invoking command; one key for both lists since the rule is
192/// shared. Call sites pass the `KEYWORD_*` constant, never a
193/// literal.
194pub fn spelling_bracket_list_comment(command: &str) -> Diagnostic {
195    let message = format!(
196        "{command} lists do not allow comments inside the brackets: move the comment above the statement"
197    );
198    Diagnostic::new(
199        "dsl.spelling.bracket_list_comment",
200        message,
201        Diagnostic::make_fields(&[(FIELD_COMMAND, command)]),
202    )
203}
204
205/// Flag that requires a value but got none. `COMMAND`-lead per the
206/// unified contract; the flag is a DSL token in backticks.
207pub fn flag_missing_value(command: &str, flag: &str) -> Diagnostic {
208    let message = format!("{command} `{flag}` requires a value");
209    Diagnostic::new(
210        "dsl.validation.flag_missing_value",
211        message,
212        Diagnostic::make_fields(&[(FIELD_COMMAND, command), (FIELD_FLAG, flag)]),
213    )
214}
215
216/// Unknown flag for a known command.
217pub fn unknown_flag(command: &str, flag: &str) -> Diagnostic {
218    let message = format!("{command} unknown flag `{flag}`");
219    Diagnostic::new(
220        "dsl.validation.unknown_flag",
221        message,
222        Diagnostic::make_fields(&[(FIELD_COMMAND, command), (FIELD_FLAG, flag)]),
223    )
224}
225
226/// More positionals than the command spec allows.
227pub fn too_many_positionals(command: &str, max: usize, got: usize) -> Diagnostic {
228    let message = format!("{command} expects at most {max} positional arguments, got {got}");
229    Diagnostic::new(
230        "dsl.validation.too_many_positionals",
231        message,
232        Diagnostic::make_fields(&[
233            (FIELD_COMMAND, command),
234            (FIELD_MAX, &max.to_string()),
235            (FIELD_GOT, &got.to_string()),
236        ]),
237    )
238}
239
240/// Missing required positional argument.
241pub fn missing_argument(command: &str, name: &str) -> Diagnostic {
242    let message = format!("{command} requires argument `{name}`");
243    Diagnostic::new(
244        "dsl.validation.missing_argument",
245        message,
246        Diagnostic::make_fields(&[(FIELD_COMMAND, command), (FIELD_ARGUMENT, name)]),
247    )
248}
249
250/// Statically-known type violation for one positional. Takes the
251/// underlying diagnostic by value and inlines its message: parse
252/// errors render only the outer message, so the reason rides inline
253/// (never as a chained source) and stays visible in snapshots.
254pub fn arg_type_mismatch(command: &str, name: &str, got: &str, reason: Diagnostic) -> Diagnostic {
255    let reason_text = reason.to_string();
256    let message = format!("{command} argument `{name}` got {got:?}: {reason_text}");
257    Diagnostic::new(
258        "dsl.validation.arg_type_mismatch",
259        message,
260        Diagnostic::make_fields(&[
261            (FIELD_COMMAND, command),
262            (FIELD_ARGUMENT, name),
263            (FIELD_GOT, got),
264            (FIELD_REASON, &reason_text),
265        ]),
266    )
267}
268
269/// Command invoked with no value to join. Shared helper, so the
270/// command rides as a field and every caller shares one key.
271pub fn needs_value(command: &str) -> Diagnostic {
272    let message = format!("{command} requires at least one argument");
273    Diagnostic::new(
274        "dsl.validation.needs_value",
275        message,
276        Diagnostic::make_fields(&[(FIELD_COMMAND, command)]),
277    )
278}
279
280/// `ENV` without any `KEY=value` assignment.
281pub fn env_requires_assignment() -> Diagnostic {
282    Diagnostic::new(
283        "dsl.validation.env_requires_assignment",
284        format!("{KEYWORD_ENV} requires KEY=value"),
285        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ENV)]),
286    )
287}
288
289/// `ENV` assignment that is not `KEY=value` shaped.
290pub fn env_bad_format() -> Diagnostic {
291    Diagnostic::new(
292        "dsl.validation.env_bad_format",
293        format!("{KEYWORD_ENV} requires KEY=value format"),
294        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ENV)]),
295    )
296}
297
298/// `ENV` split failure passthrough. Takes the underlying diagnostic
299/// by value; its message renders verbatim, so the key carries the
300/// context while the text stays byte-identical. No source rides
301/// along: passthroughs never attach `with_source`.
302pub fn env_assignment_error(reason: Diagnostic) -> Diagnostic {
303    let reason_text = reason.to_string();
304    Diagnostic::new(
305        "dsl.validation.env_assignment_error",
306        reason_text.clone(),
307        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ENV), (FIELD_REASON, &reason_text)]),
308    )
309}
310
311/// `EXPAND` override that is not `KEY=value` shaped.
312pub fn expand_bad_override() -> Diagnostic {
313    Diagnostic::new(
314        "dsl.validation.expand_bad_override",
315        format!("{KEYWORD_EXPAND} requires KEY=value format for overrides"),
316        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPAND)]),
317    )
318}
319
320/// `EXPAND` split failure passthrough. Takes the underlying
321/// diagnostic by value; its message renders verbatim. No source
322/// rides along: passthroughs never attach `with_source`.
323pub fn expand_assignment_error(reason: Diagnostic) -> Diagnostic {
324    let reason_text = reason.to_string();
325    Diagnostic::new(
326        "dsl.validation.expand_assignment_error",
327        reason_text.clone(),
328        Diagnostic::make_fields(&[
329            (FIELD_COMMAND, KEYWORD_EXPAND),
330            (FIELD_REASON, &reason_text),
331        ]),
332    )
333}
334
335/// `EXPAND` path validation failure passthrough. Takes the
336/// underlying diagnostic by value; its message renders verbatim.
337/// No source rides along.
338pub fn expand_path_error(reason: Diagnostic) -> Diagnostic {
339    let reason_text = reason.to_string();
340    Diagnostic::new(
341        "dsl.validation.expand_path_error",
342        reason_text.clone(),
343        Diagnostic::make_fields(&[
344            (FIELD_COMMAND, KEYWORD_EXPAND),
345            (FIELD_REASON, &reason_text),
346        ]),
347    )
348}
349
350/// `EXPAND` with more than one path positional.
351pub fn expand_extra_path() -> Diagnostic {
352    Diagnostic::new(
353        "dsl.validation.expand_extra_path",
354        format!("{KEYWORD_EXPAND} accepts at most one path"),
355        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPAND)]),
356    )
357}
358
359/// `WORKDIR` without a path.
360pub fn workdir_requires_path() -> Diagnostic {
361    Diagnostic::new(
362        "dsl.validation.workdir_requires_path",
363        format!("{KEYWORD_WORKDIR} requires a path"),
364        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_WORKDIR)]),
365    )
366}
367
368/// `WORKSPACE` without a target.
369pub fn workspace_requires_target() -> Diagnostic {
370    Diagnostic::new(
371        "dsl.validation.workspace_requires_target",
372        format!("{KEYWORD_WORKSPACE} requires a target"),
373        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_WORKSPACE)]),
374    )
375}
376
377/// `WORKSPACE --local` without `CACHE`.
378pub fn workspace_local_needs_cache() -> Diagnostic {
379    Diagnostic::new(
380        "dsl.validation.workspace_local_needs_cache",
381        format!("{KEYWORD_WORKSPACE} --local requires CACHE"),
382        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_WORKSPACE)]),
383    )
384}
385
386/// Unknown `WORKSPACE` target. Takes the offending value; quoting
387/// lives here.
388pub fn workspace_unknown_target(other: &str) -> Diagnostic {
389    let message = format!("unknown workspace target {other:?}");
390    Diagnostic::new(
391        "dsl.validation.workspace_unknown_target",
392        message,
393        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_WORKSPACE), (FIELD_GOT, other)]),
394    )
395}
396
397/// Unknown `--from-workspace` source. Shared by `COPY` and `SYMLINK`:
398/// same failure mode, one key. Takes the invoking command for the
399/// structured `command` field; the message is command-free.
400pub fn unknown_workspace_source(command: &str, other: &str) -> Diagnostic {
401    let message = format!("unknown workspace source {other:?}");
402    Diagnostic::new(
403        "dsl.validation.unknown_workspace_source",
404        message,
405        Diagnostic::make_fields(&[(FIELD_COMMAND, command), (FIELD_GOT, other)]),
406    )
407}
408
409/// `COPY` without a source positional.
410pub fn copy_requires_source() -> Diagnostic {
411    Diagnostic::new(
412        "dsl.validation.copy_requires_source",
413        format!("{KEYWORD_COPY} requires a source"),
414        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY)]),
415    )
416}
417
418/// `COPY` without a destination positional.
419pub fn copy_requires_destination() -> Diagnostic {
420    Diagnostic::new(
421        "dsl.validation.copy_requires_destination",
422        format!("{KEYWORD_COPY} requires a destination"),
423        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY)]),
424    )
425}
426
427/// `COPY` with both host-transfer flags.
428pub fn copy_host_exclusion() -> Diagnostic {
429    Diagnostic::new(
430        "dsl.validation.copy_host_exclusion",
431        format!("{KEYWORD_COPY} --from-host and --to-host are mutually exclusive"),
432        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY)]),
433    )
434}
435
436/// `COPY_GIT` without a revision positional.
437pub fn copy_git_requires_revision() -> Diagnostic {
438    Diagnostic::new(
439        "dsl.validation.copy_git_requires_revision",
440        format!("{KEYWORD_COPY_GIT} requires a revision"),
441        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY_GIT)]),
442    )
443}
444
445/// `COPY_GIT` without a source positional.
446pub fn copy_git_requires_source() -> Diagnostic {
447    Diagnostic::new(
448        "dsl.validation.copy_git_requires_source",
449        format!("{KEYWORD_COPY_GIT} requires a source"),
450        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY_GIT)]),
451    )
452}
453
454/// `COPY_GIT` without a destination positional.
455pub fn copy_git_requires_destination() -> Diagnostic {
456    Diagnostic::new(
457        "dsl.validation.copy_git_requires_destination",
458        format!("{KEYWORD_COPY_GIT} requires a destination"),
459        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_COPY_GIT)]),
460    )
461}
462
463/// `SYMLINK` without a source positional.
464pub fn symlink_requires_source() -> Diagnostic {
465    Diagnostic::new(
466        "dsl.validation.symlink_requires_source",
467        format!("{KEYWORD_SYMLINK} requires a source"),
468        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_SYMLINK)]),
469    )
470}
471
472/// `SYMLINK` without a target positional.
473pub fn symlink_requires_target() -> Diagnostic {
474    Diagnostic::new(
475        "dsl.validation.symlink_requires_target",
476        format!("{KEYWORD_SYMLINK} requires a target"),
477        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_SYMLINK)]),
478    )
479}
480
481/// `MKDIR` without a path.
482pub fn mkdir_requires_path() -> Diagnostic {
483    Diagnostic::new(
484        "dsl.validation.mkdir_requires_path",
485        format!("{KEYWORD_MKDIR} requires a path"),
486        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_MKDIR)]),
487    )
488}
489
490/// `INSTALL` without a source positional.
491pub fn install_requires_source() -> Diagnostic {
492    Diagnostic::new(
493        "dsl.validation.install_requires_source",
494        format!("{KEYWORD_INSTALL} requires a source"),
495        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_INSTALL)]),
496    )
497}
498
499/// `INSTALL` without a destination positional.
500pub fn install_requires_destination() -> Diagnostic {
501    Diagnostic::new(
502        "dsl.validation.install_requires_destination",
503        format!("{KEYWORD_INSTALL} requires a destination"),
504        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_INSTALL)]),
505    )
506}
507
508/// `SET_EXECUTABLE` without a path.
509pub fn set_executable_requires_path() -> Diagnostic {
510    Diagnostic::new(
511        "dsl.validation.set_executable_requires_path",
512        format!("{KEYWORD_SET_EXECUTABLE} requires a path"),
513        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_SET_EXECUTABLE)]),
514    )
515}
516
517/// `ARCHIVE` without a source positional.
518pub fn archive_requires_source() -> Diagnostic {
519    Diagnostic::new(
520        "dsl.validation.archive_requires_source",
521        format!("{KEYWORD_ARCHIVE} requires a source"),
522        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ARCHIVE)]),
523    )
524}
525
526/// `ARCHIVE` without a destination positional.
527pub fn archive_requires_destination() -> Diagnostic {
528    Diagnostic::new(
529        "dsl.validation.archive_requires_destination",
530        format!("{KEYWORD_ARCHIVE} requires a destination"),
531        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ARCHIVE)]),
532    )
533}
534
535/// `UNARCHIVE` without an archive positional.
536pub fn unarchive_requires_archive() -> Diagnostic {
537    Diagnostic::new(
538        "dsl.validation.unarchive_requires_archive",
539        format!("{KEYWORD_UNARCHIVE} requires an archive"),
540        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_UNARCHIVE)]),
541    )
542}
543
544/// `UNARCHIVE` without a destination positional.
545pub fn unarchive_requires_destination() -> Diagnostic {
546    Diagnostic::new(
547        "dsl.validation.unarchive_requires_destination",
548        format!("{KEYWORD_UNARCHIVE} requires a destination"),
549        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_UNARCHIVE)]),
550    )
551}
552
553/// `UNARCHIVE` whose static `--max-bytes` token does not parse.
554/// Takes the underlying diagnostic by value; bare outer context
555/// plus the chained source, so the message never embeds the
556/// inner text twice. `{err:#}` renders the legacy shape.
557pub fn unarchive_bad_max_bytes(reason: Diagnostic) -> Diagnostic {
558    let reason_text = reason.to_string();
559    Diagnostic::new(
560        "dsl.validation.unarchive_bad_max_bytes",
561        format!("{KEYWORD_UNARCHIVE} --max-bytes"),
562        Diagnostic::make_fields(&[
563            (FIELD_COMMAND, KEYWORD_UNARCHIVE),
564            (FIELD_REASON, &reason_text),
565        ]),
566    )
567    .with_source(std::sync::Arc::new(reason))
568}
569
570/// `EXPORT` naming a function with no top-level `FUNC` or known module
571/// member. Takes the exported name; quoting lives here.
572pub fn export_unknown_func(name: &str) -> Diagnostic {
573    let message = format!(
574        "{KEYWORD_EXPORT} `{name}` does not match any top-level {KEYWORD_FUNC} or known module member"
575    );
576    Diagnostic::new(
577        "dsl.validation.export_unknown_func",
578        message,
579        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPORT), (FIELD_GOT, name)]),
580    )
581}
582
583/// `EXPORT TYPE` with a qualified `ALIAS::TYPE` name, which no
584/// downstream path serves. Takes the exported name.
585pub fn export_type_qualified(name: &str) -> Diagnostic {
586    let message = format!(
587        "{KEYWORD_EXPORT} {KEYWORD_TYPE} `{name}` must be bare: qualified ALIAS::{KEYWORD_TYPE} re-exports are not served; import the file and re-export the bare name"
588    );
589    Diagnostic::new(
590        "dsl.validation.export_type_qualified",
591        message,
592        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPORT), (FIELD_GOT, name)]),
593    )
594}
595
596/// `EXPORT TYPE` naming no top-level `TYPE` (and no imports to defer
597/// to). Takes the exported name.
598pub fn export_unknown_type(name: &str) -> Diagnostic {
599    let message = format!(
600        "{KEYWORD_EXPORT} {KEYWORD_TYPE} `{name}` does not match any top-level {KEYWORD_TYPE}"
601    );
602    Diagnostic::new(
603        "dsl.validation.export_unknown_type",
604        message,
605        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPORT), (FIELD_GOT, name)]),
606    )
607}
608
609/// `EXPORT CONST` through the `SCRIPT::` namespace, which never names
610/// a `CONST`. Takes the exported name.
611pub fn export_const_script_namespace(name: &str) -> Diagnostic {
612    let message = format!(
613        "{KEYWORD_EXPORT} {KEYWORD_CONST} `{name}` must name a top-level {KEYWORD_CONST} (`$NAME`) or `$ALIAS::NAME` for a visible import: `{SCRIPT_MODULE_NAME}::` is not a {KEYWORD_CONST} namespace"
614    );
615    Diagnostic::new(
616        "dsl.validation.export_const_script_namespace",
617        message,
618        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPORT), (FIELD_GOT, name)]),
619    )
620}
621
622/// `EXPORT CONST` forwarding through an alias with no visible import.
623/// Takes the exported name and the unknown alias.
624pub fn export_const_unknown_alias(name: &str, module: &str) -> Diagnostic {
625    let message = format!(
626        "{KEYWORD_EXPORT} {KEYWORD_CONST} `{name}` names unknown import alias `{module}`: import a file as `{module}` to re-export its CONSTs"
627    );
628    Diagnostic::new(
629        "dsl.validation.export_const_unknown_alias",
630        message,
631        Diagnostic::make_fields(&[
632            (FIELD_COMMAND, KEYWORD_EXPORT),
633            (FIELD_GOT, name),
634            (FIELD_ALIAS, module),
635        ]),
636    )
637}
638
639/// `EXPORT CONST` naming no top-level `CONST`. Takes the exported name.
640pub fn export_const_unknown(name: &str) -> Diagnostic {
641    let message = format!(
642        "{KEYWORD_EXPORT} {KEYWORD_CONST} `{name}` does not match any top-level {KEYWORD_CONST} ({KEYWORD_LET} bindings are never exportable)"
643    );
644    Diagnostic::new(
645        "dsl.validation.export_const_unknown",
646        message,
647        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXPORT), (FIELD_GOT, name)]),
648    )
649}
650
651/// Known command with malformed arguments (the lowering fallback).
652/// Takes the invoking command, the rendered args (`nothing` when
653/// empty), and an optional structural hint. One key: hinted and bare
654/// are the same failure mode, the hint is ancillary. Canonical form
655/// is `COMMAND`-lead with no legacy prefix and no trailing period;
656/// a hinted message is the hint itself (which already leads with the
657/// command), a bare one names what arrived.
658pub fn invalid_syntax(command: &str, got: &str, hint: Option<&str>) -> Diagnostic {
659    let message = match hint {
660        Some(hint) => hint.trim_end_matches('.').to_string(),
661        None => format!("{command} got {got}"),
662    };
663    Diagnostic::new(
664        "dsl.invalid_syntax.malformed",
665        message,
666        Diagnostic::make_fields(&[(FIELD_COMMAND, command), (FIELD_GOT, got)]),
667    )
668}
669
670/// Truly unknown command name. Takes the attempted name and an
671/// optional hint (structural or case hint). Canonical form quotes the
672/// found name with `{name:?}` and keeps the hint on its own line with
673/// no trailing period.
674pub fn unknown_command(name: &str, hint: Option<&str>) -> Diagnostic {
675    let message = match hint {
676        Some(hint) => format!("unknown command {name:?}\n{}", hint.trim_end_matches('.')),
677        None => format!("unknown command {name:?}"),
678    };
679    Diagnostic::new(
680        "dsl.unknown_command.unknown",
681        message,
682        Diagnostic::make_fields(&[(FIELD_FOUND, name)]),
683    )
684}
685
686/// `LET` capture running `ASYNC`/`AWAIT`/`CANCEL` inline. The capture
687/// sink cannot stage tasks; hoist first, then await.
688pub fn let_capture_async() -> Diagnostic {
689    let rule = KEYWORD_LET.to_lowercase();
690    Diagnostic::new(
691        "dsl.structural.let_capture_async",
692        format!(
693            "{KEYWORD_LET} capture cannot run {KEYWORD_ASYNC}/{KEYWORD_AWAIT}/{KEYWORD_CANCEL} inline; use {KEYWORD_LET} $t: {HANDLE_TYPE_NAME}<T> = {KEYWORD_ASYNC} ... then {KEYWORD_LET} $o: {STRING_TYPE_NAME} = {KEYWORD_AWAIT} $t"
694        ),
695        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
696    )
697}
698
699/// `LET` capture using `WITH_IO [stdout=$var]`. The capture sink owns
700/// stdout.
701pub fn let_capture_pipe_stdout() -> Diagnostic {
702    let rule = KEYWORD_LET.to_lowercase();
703    Diagnostic::new(
704        "dsl.structural.let_capture_pipe_stdout",
705        format!(
706            "{KEYWORD_LET} capture cannot use {KEYWORD_WITH_IO} [stdout=$var]; the capture sink owns stdout"
707        ),
708        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
709    )
710}
711
712/// `INHERIT_ENV` nested inside another command. The prelude directive
713/// only reads at statement level.
714pub fn nested_inherit_env() -> Diagnostic {
715    let rule = KEYWORD_INHERIT_ENV.to_lowercase();
716    Diagnostic::new(
717        "dsl.structural.nested_inherit_env",
718        format!("{KEYWORD_INHERIT_ENV} cannot be nested inside other commands"),
719        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
720    )
721}
722
723/// `WITH_IO [rows]`/`[cols]` without `[tty]`. Geometry without a
724/// terminal has nothing to size.
725pub fn tty_geometry_without_tty() -> Diagnostic {
726    let rule = KEYWORD_WITH_IO.to_lowercase();
727    Diagnostic::new(
728        "dsl.structural.tty_geometry_without_tty",
729        format!(
730            "{KEYWORD_WITH_IO} [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size"
731        ),
732        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
733    )
734}
735
736/// `WITH_IO [tty]` binding stderr. The pty master interleaves both
737/// streams, so they cannot demultiplex.
738pub fn tty_with_stderr() -> Diagnostic {
739    let rule = KEYWORD_WITH_IO.to_lowercase();
740    Diagnostic::new(
741        "dsl.structural.tty_with_stderr",
742        format!(
743            "{KEYWORD_WITH_IO} [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex"
744        ),
745        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
746    )
747}
748
749/// `WITH_IO [tty]` wrapping a non-`RUN` step. Terminal-unaware
750/// commands cannot run under the pty master.
751pub fn tty_wraps_non_run() -> Diagnostic {
752    let rule = KEYWORD_WITH_IO.to_lowercase();
753    Diagnostic::new(
754        "dsl.structural.tty_wraps_non_run",
755        format!(
756            "{KEYWORD_WITH_IO} [tty] only wraps a {KEYWORD_RUN} step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it"
757        ),
758        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
759    )
760}
761
762/// `WITH_IO` placed inside an `ASYNC` body. Pipe wiring belongs
763/// outside the task.
764pub fn with_io_in_async() -> Diagnostic {
765    let rule = KEYWORD_ASYNC.to_lowercase();
766    Diagnostic::new(
767        "dsl.structural.with_io_in_async",
768        format!(
769            "{KEYWORD_WITH_IO} cannot be placed inside {KEYWORD_ASYNC}. Place {KEYWORD_WITH_IO} outside {KEYWORD_ASYNC} instead (e.g. {KEYWORD_WITH_IO} [...] {KEYWORD_ASYNC} {KEYWORD_RUN} ...)"
770        ),
771        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
772    )
773}
774
775/// `COPY --from-host` / `--to-host` outside a `REMOTE` block. Transfer
776/// declarations only mean something where a session hoists them.
777pub fn copy_host_outside_remote() -> Diagnostic {
778    let rule = KEYWORD_COPY.to_lowercase();
779    Diagnostic::new(
780        "dsl.structural.copy_host_outside_remote",
781        format!(
782            "{KEYWORD_COPY} --from-host and --to-host are only valid inside a {KEYWORD_REMOTE} block"
783        ),
784        Diagnostic::make_fields(&[(FIELD_RULE, rule.as_str())]),
785    )
786}
787
788/// Staged `UnsignedIntBoundary` for `2^63` where unary `-` cannot
789/// consume it. Fixed value, parameterless. The `expr` rule is a
790/// parser-phase name, not a DSL command, so no `KEYWORD_*` applies.
791pub fn int_boundary_overflow() -> Diagnostic {
792    Diagnostic::new(
793        "dsl.structural.int_boundary_overflow",
794        "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
795        Diagnostic::make_fields(&[(FIELD_RULE, "expr")]),
796    )
797}
798
799/// Integer literal exceeding `i64::MAX` under unary `-`. Takes the
800/// offending value; quoting lives here.
801pub fn int_overflow(n: u64) -> Diagnostic {
802    let message = format!("integer overflow: {n} exceeds i64::MAX");
803    Diagnostic::new(
804        "dsl.structural.int_overflow",
805        message,
806        Diagnostic::make_fields(&[(FIELD_RULE, "expr"), (FIELD_GOT, &n.to_string())]),
807    )
808}
809
810/// `WRITE` without a path.
811pub fn write_requires_path() -> Diagnostic {
812    Diagnostic::new(
813        "dsl.validation.write_requires_path",
814        format!("{KEYWORD_WRITE} requires a path"),
815        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_WRITE)]),
816    )
817}
818
819/// `APPEND` without a path.
820pub fn append_requires_path() -> Diagnostic {
821    Diagnostic::new(
822        "dsl.validation.append_requires_path",
823        format!("{KEYWORD_APPEND} requires a path"),
824        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_APPEND)]),
825    )
826}
827
828/// `APPEND_LINE` without a path.
829pub fn append_line_requires_path() -> Diagnostic {
830    Diagnostic::new(
831        "dsl.validation.append_line_requires_path",
832        format!("{KEYWORD_APPEND_LINE} requires a path"),
833        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_APPEND_LINE)]),
834    )
835}
836
837/// `REMOVE` without a path.
838pub fn remove_requires_path() -> Diagnostic {
839    Diagnostic::new(
840        "dsl.validation.remove_requires_path",
841        format!("{KEYWORD_REMOVE} requires a path"),
842        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_REMOVE)]),
843    )
844}
845
846/// `READ_LINE` without a variable.
847pub fn read_line_requires_variable() -> Diagnostic {
848    Diagnostic::new(
849        "dsl.validation.read_line_requires_variable",
850        format!("{KEYWORD_READ_LINE} requires a variable"),
851        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_READ_LINE)]),
852    )
853}
854
855/// `READ_LINE` target without a `$` sigil. Takes the rendered
856/// argument; quoting lives here. (Renders the value, never the
857/// internal `Arg` debug shape.)
858pub fn read_line_requires_sigil(got: &str) -> Diagnostic {
859    let message = format!("{KEYWORD_READ_LINE} requires a $variable, found {got:?}");
860    Diagnostic::new(
861        "dsl.validation.read_line_requires_sigil",
862        message,
863        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_READ_LINE), (FIELD_GOT, got)]),
864    )
865}
866
867/// `PROMPT` without a variable.
868pub fn prompt_requires_variable() -> Diagnostic {
869    Diagnostic::new(
870        "dsl.validation.prompt_requires_variable",
871        format!("{KEYWORD_PROMPT} requires a variable"),
872        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_PROMPT)]),
873    )
874}
875
876/// `PROMPT` target without a `$` sigil. Takes the rendered argument.
877pub fn prompt_requires_sigil(got: &str) -> Diagnostic {
878    let message = format!("{KEYWORD_PROMPT} requires a $variable, found {got:?}");
879    Diagnostic::new(
880        "dsl.validation.prompt_requires_sigil",
881        message,
882        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_PROMPT), (FIELD_GOT, got)]),
883    )
884}
885
886/// `PROMPT` without a message.
887pub fn prompt_requires_message() -> Diagnostic {
888    Diagnostic::new(
889        "dsl.validation.prompt_requires_message",
890        format!("{KEYWORD_PROMPT} requires a message"),
891        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_PROMPT)]),
892    )
893}
894
895/// `ASSERT_CONTAINS` without a value.
896pub fn assert_contains_requires_value() -> Diagnostic {
897    Diagnostic::new(
898        "dsl.validation.assert_contains_requires_value",
899        format!("{KEYWORD_ASSERT_CONTAINS} requires a value"),
900        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ASSERT_CONTAINS)]),
901    )
902}
903
904/// `ASSERT_CONTAINS` without a needle.
905pub fn assert_contains_requires_needle() -> Diagnostic {
906    Diagnostic::new(
907        "dsl.validation.assert_contains_requires_needle",
908        format!("{KEYWORD_ASSERT_CONTAINS} requires a needle"),
909        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_ASSERT_CONTAINS)]),
910    )
911}
912
913/// `EXIT` without a code.
914pub fn exit_requires_code() -> Diagnostic {
915    Diagnostic::new(
916        "dsl.validation.exit_requires_code",
917        format!("{KEYWORD_EXIT} requires a code"),
918        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_EXIT)]),
919    )
920}
921
922/// `SLEEP` without a duration.
923pub fn sleep_requires_duration() -> Diagnostic {
924    Diagnostic::new(
925        "dsl.validation.sleep_requires_duration",
926        format!("{KEYWORD_SLEEP} requires a duration (e.g. {KEYWORD_SLEEP} 500ms)"),
927        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_SLEEP)]),
928    )
929}
930
931/// `SLEEP` with more than one argument.
932pub fn sleep_takes_one() -> Diagnostic {
933    Diagnostic::new(
934        "dsl.validation.sleep_takes_one",
935        format!("{KEYWORD_SLEEP} takes exactly one duration argument"),
936        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_SLEEP)]),
937    )
938}
939
940/// Numeric token with more than one whitespace-separated part or a
941/// non-numeric shape. Takes the raw token; quoting lives nowhere
942/// (bytes stay identical to the legacy bail). One key covers the
943/// too-many-parts and bad-shape arms: the failure mode is identical.
944pub fn invalid_numeric_token(got: &str) -> Diagnostic {
945    let message = format!("invalid numeric token: {got}");
946    Diagnostic::new(
947        "dsl.validation.invalid_numeric_token",
948        message,
949        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
950    )
951}
952
953/// `TIMEOUT` duration whose digits do not parse. Takes the compacted
954/// token; bytes stay identical to the legacy bail.
955pub fn invalid_timeout_duration(got: &str) -> Diagnostic {
956    let message = format!("invalid {KEYWORD_TIMEOUT} duration: {got}");
957    Diagnostic::new(
958        "dsl.validation.invalid_timeout_duration",
959        message,
960        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_TIMEOUT), (FIELD_GOT, got)]),
961    )
962}
963
964/// `TIMEOUT` duration overflowing `u64` milliseconds. Takes the
965/// compacted token.
966pub fn timeout_duration_out_of_range(got: &str) -> Diagnostic {
967    let message = format!("{KEYWORD_TIMEOUT} duration out of range: {got}");
968    Diagnostic::new(
969        "dsl.validation.timeout_duration_out_of_range",
970        message,
971        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_TIMEOUT), (FIELD_GOT, got)]),
972    )
973}
974
975/// `TIMEOUT` duration of zero. Takes the compacted token.
976pub fn timeout_duration_not_positive(got: &str) -> Diagnostic {
977    let message = format!("{KEYWORD_TIMEOUT} duration must be positive, got: {got}");
978    Diagnostic::new(
979        "dsl.validation.timeout_duration_not_positive",
980        message,
981        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_TIMEOUT), (FIELD_GOT, got)]),
982    )
983}
984
985/// Byte-count token whose digits do not parse. Takes the compacted
986/// token; bytes stay identical to the legacy bail.
987pub fn invalid_byte_count(got: &str) -> Diagnostic {
988    let message = format!("invalid byte count: {got}");
989    Diagnostic::new(
990        "dsl.validation.invalid_byte_count",
991        message,
992        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
993    )
994}
995
996/// Byte-count token overflowing `u64` bytes. Takes the compacted token.
997pub fn byte_count_out_of_range(got: &str) -> Diagnostic {
998    let message = format!("byte count out of range: {got}");
999    Diagnostic::new(
1000        "dsl.validation.byte_count_out_of_range",
1001        message,
1002        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
1003    )
1004}
1005
1006/// Byte-count token of zero. Takes the compacted token.
1007pub fn byte_count_not_positive(got: &str) -> Diagnostic {
1008    let message = format!("byte count must be positive, got: {got}");
1009    Diagnostic::new(
1010        "dsl.validation.byte_count_not_positive",
1011        message,
1012        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
1013    )
1014}
1015
1016/// Static literal that is not an integer. Takes the raw literal;
1017/// `Debug` rendering lives here. Bytes stay identical to the
1018/// legacy bail.
1019pub fn expected_int(got: &str) -> Diagnostic {
1020    let message = format!("expected int, got {got:?}");
1021    Diagnostic::new(
1022        "dsl.validation.expected_int",
1023        message,
1024        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
1025    )
1026}
1027
1028/// Static literal where a `$var` is required. Takes the raw
1029/// literal; `Debug` rendering lives here.
1030pub fn expected_var(got: &str) -> Diagnostic {
1031    let message = format!("expected $var, got {got:?}");
1032    Diagnostic::new(
1033        "dsl.validation.expected_var",
1034        message,
1035        Diagnostic::make_fields(&[(FIELD_GOT, got)]),
1036    )
1037}
1038
1039/// Static literal outside a closed option set. Takes the allowed
1040/// spellings plus the raw literal; the `|` join lives here so call
1041/// sites stay `format!`-free.
1042pub fn expected_one_of(options: &[&str], got: &str) -> Diagnostic {
1043    let joined = options.join("|");
1044    let message = format!("expected one of {joined}, got {got:?}");
1045    Diagnostic::new(
1046        "dsl.validation.expected_one_of",
1047        message,
1048        Diagnostic::make_fields(&[(FIELD_GOT, got), ("options", &joined)]),
1049    )
1050}
1051
1052/// Non-variable expression where a `$var` is required. Takes the
1053/// rendered expression, never the `format!` string.
1054pub fn expected_var_expression(rendered: &str) -> Diagnostic {
1055    let message = format!("expected $var, got expression {rendered}");
1056    Diagnostic::new(
1057        "dsl.validation.expected_var_expression",
1058        message,
1059        Diagnostic::make_fields(&[(FIELD_GOT, rendered)]),
1060    )
1061}
1062
1063/// Split text without `KEY=value` shape. Parameterless: the wording
1064/// is static.
1065pub fn assignment_requires_key_value() -> Diagnostic {
1066    Diagnostic::new(
1067        "dsl.validation.assignment_requires_key_value",
1068        "assignment requires KEY=value format".to_string(),
1069        Diagnostic::make_fields(&[]),
1070    )
1071}
1072
1073/// Value whose type has no DSL literal form. Takes the runtime type
1074/// name; wording lives here. Bytes stay identical to the legacy
1075/// bail.
1076pub fn render_no_literal_form(actual: &str) -> Diagnostic {
1077    let message = format!("value of type {actual} has no DSL literal form");
1078    Diagnostic::new(
1079        "dsl.render.no_literal_form",
1080        message,
1081        Diagnostic::make_fields(&[("actual", actual)]),
1082    )
1083}
1084
1085/// Non-finite float, which cannot round-trip through the parser.
1086/// Parameterless: the type name is a shared constant.
1087pub fn render_non_finite_float() -> Diagnostic {
1088    let message = format!("non-finite {FLOAT_TYPE_NAME} has no DSL literal form");
1089    Diagnostic::new(
1090        "dsl.render.non_finite_float",
1091        message,
1092        Diagnostic::make_fields(&[]),
1093    )
1094}
1095
1096/// `LIST_APPEND` without a LIST variable.
1097pub fn list_append_requires_list() -> Diagnostic {
1098    Diagnostic::new(
1099        "dsl.validation.list_append_requires_list",
1100        format!(
1101            "{KEYWORD_LIST_APPEND} requires a {LIST_TYPE_NAME} variable (e.g. {KEYWORD_LIST_APPEND} $items $x)"
1102        ),
1103        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_LIST_APPEND)]),
1104    )
1105}
1106
1107/// `LIST_APPEND` target without a `$` sigil. Takes the rendered
1108/// argument; quoting lives here.
1109pub fn list_append_requires_sigil(got: &str) -> Diagnostic {
1110    let message = format!("{KEYWORD_LIST_APPEND} requires a $variable, found {got:?}");
1111    Diagnostic::new(
1112        "dsl.validation.list_append_requires_sigil",
1113        message,
1114        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_LIST_APPEND), (FIELD_GOT, got)]),
1115    )
1116}
1117
1118/// `LIST_APPEND` without an item.
1119pub fn list_append_requires_item() -> Diagnostic {
1120    Diagnostic::new(
1121        "dsl.validation.list_append_requires_item",
1122        format!(
1123            "{KEYWORD_LIST_APPEND} requires an item to append (e.g. {KEYWORD_LIST_APPEND} $items $x)"
1124        ),
1125        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_LIST_APPEND)]),
1126    )
1127}
1128
1129/// `LIST_APPEND` with other than two arguments.
1130pub fn list_append_takes_two() -> Diagnostic {
1131    Diagnostic::new(
1132        "dsl.validation.list_append_takes_two",
1133        format!(
1134            "{KEYWORD_LIST_APPEND} takes exactly two arguments: {KEYWORD_LIST_APPEND} $list <item>"
1135        ),
1136        Diagnostic::make_fields(&[(FIELD_COMMAND, KEYWORD_LIST_APPEND)]),
1137    )
1138}
1139
1140/// `ASSERT_EQ` / `ASSERT_NE` without an actual value. Shared by both
1141/// commands: same failure mode, one key; the invoking command rides in
1142/// the structured `command` field and leads the message.
1143pub fn assert_equality_requires_value(command: &str) -> Diagnostic {
1144    let message = format!("{command} requires a value");
1145    Diagnostic::new(
1146        "dsl.validation.assert_equality_requires_value",
1147        message,
1148        Diagnostic::make_fields(&[(FIELD_COMMAND, command)]),
1149    )
1150}
1151
1152/// `ASSERT_EQ` / `ASSERT_NE` without an expected value (and no `--hash`).
1153/// Shared key; invoking command in the field.
1154pub fn assert_equality_requires_expected(command: &str) -> Diagnostic {
1155    let message = format!("{command} requires an expected value");
1156    Diagnostic::new(
1157        "dsl.validation.assert_equality_requires_expected",
1158        message,
1159        Diagnostic::make_fields(&[(FIELD_COMMAND, command)]),
1160    )
1161}
1162
1163/// `ASSERT_EQ` / `ASSERT_NE` combining `--hash` with a positional
1164/// expected value. Shared key; invoking command in the field.
1165pub fn assert_equality_hash_with_expected(command: &str) -> Diagnostic {
1166    let message = format!("{command} --hash cannot be combined with an expected value");
1167    Diagnostic::new(
1168        "dsl.validation.assert_equality_hash_with_expected",
1169        message,
1170        Diagnostic::make_fields(&[(FIELD_COMMAND, command)]),
1171    )
1172}
1173
1174/// Markdown code fence that never closes. Takes the 1-based line
1175/// number where the fence opens; the `markdown:{line}` prefix lives
1176/// here so call sites pass the line only.
1177pub fn markdown_unclosed_fence(line: usize) -> Diagnostic {
1178    let message = format!("markdown:{line}: code fence is never closed");
1179    Diagnostic::new(
1180        "dsl.markdown.unclosed_fence",
1181        message,
1182        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string())]),
1183    )
1184}
1185
1186/// Unexpected character in fence metadata. Takes the 1-based line
1187/// number and the character; quoting lives here.
1188pub fn markdown_metadata_unexpected_char(line: usize, ch: char) -> Diagnostic {
1189    let message = format!("markdown:{line}: unexpected character `{ch}` in fence metadata");
1190    Diagnostic::new(
1191        "dsl.markdown.metadata_unexpected_char",
1192        message,
1193        Diagnostic::make_fields(&[
1194            (FIELD_LINE, &line.to_string()),
1195            (FIELD_GOT, &ch.to_string()),
1196        ]),
1197    )
1198}
1199
1200/// Fence metadata item missing `:` after its key. Takes the 1-based
1201/// line number and the key; quoting lives here.
1202pub fn markdown_metadata_missing_colon(line: usize, key: &str) -> Diagnostic {
1203    let message =
1204        format!("markdown:{line}: fence metadata item `{key}` is missing ':' after its key");
1205    Diagnostic::new(
1206        "dsl.markdown.metadata_missing_colon",
1207        message,
1208        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string()), (FIELD_KEY, key)]),
1209    )
1210}
1211
1212/// Fence metadata item using `=` instead of `:`. Takes the 1-based
1213/// line number and the key; quoting lives here.
1214pub fn markdown_metadata_equals_syntax(line: usize, key: &str) -> Diagnostic {
1215    let message =
1216        format!("markdown:{line}: fence metadata item `{key}` must use `key:value` syntax");
1217    Diagnostic::new(
1218        "dsl.markdown.metadata_equals_syntax",
1219        message,
1220        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string()), (FIELD_KEY, key)]),
1221    )
1222}
1223
1224/// Unterminated double quote in fence metadata. Takes the 1-based
1225/// line number.
1226pub fn markdown_metadata_unterminated_quote(line: usize) -> Diagnostic {
1227    let message = format!("markdown:{line}: unterminated double quote in fence metadata");
1228    Diagnostic::new(
1229        "dsl.markdown.metadata_unterminated_quote",
1230        message,
1231        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string())]),
1232    )
1233}
1234
1235/// `env` metadata without `KEY=VALUE` shape. Takes the 1-based line
1236/// number.
1237pub fn markdown_metadata_env_shape(line: usize) -> Diagnostic {
1238    let message = format!("markdown:{line}: env metadata must be `env:KEY=VALUE`");
1239    Diagnostic::new(
1240        "dsl.markdown.metadata_env_shape",
1241        message,
1242        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string())]),
1243    )
1244}
1245
1246/// Unsupported `roots` metadata value. Takes the 1-based line number
1247/// and the value; quoting lives here.
1248pub fn markdown_metadata_roots_unsupported(line: usize, value: &str) -> Diagnostic {
1249    let message = format!(
1250        "markdown:{line}: unsupported roots metadata `{value}` (only `unified` is defined)"
1251    );
1252    Diagnostic::new(
1253        "dsl.markdown.metadata_roots_unsupported",
1254        message,
1255        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string()), (FIELD_GOT, value)]),
1256    )
1257}
1258
1259/// Duplicate `roots` metadata. Takes the 1-based line number.
1260pub fn markdown_metadata_roots_duplicate(line: usize) -> Diagnostic {
1261    let message = format!("markdown:{line}: roots metadata specified more than once");
1262    Diagnostic::new(
1263        "dsl.markdown.metadata_roots_duplicate",
1264        message,
1265        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string())]),
1266    )
1267}
1268
1269/// Duplicate `expect_error` metadata. Takes the 1-based line number.
1270pub fn markdown_metadata_expect_error_duplicate(line: usize) -> Diagnostic {
1271    let message = format!("markdown:{line}: expect_error metadata specified more than once");
1272    Diagnostic::new(
1273        "dsl.markdown.metadata_expect_error_duplicate",
1274        message,
1275        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string())]),
1276    )
1277}
1278
1279/// Unknown fence metadata key. Takes the 1-based line number and the
1280/// key; the supported-key list lives here.
1281pub fn markdown_metadata_unknown_key(line: usize, key: &str) -> Diagnostic {
1282    let message = format!(
1283        "markdown:{line}: unknown fence metadata key `{key}` (supported: env, roots, expect_error, mock_remote)"
1284    );
1285    Diagnostic::new(
1286        "dsl.markdown.metadata_unknown_key",
1287        message,
1288        Diagnostic::make_fields(&[(FIELD_LINE, &line.to_string()), (FIELD_KEY, key)]),
1289    )
1290}
1291
1292/// Text after a quoted string literal's closer. Takes the source;
1293/// `Debug` rendering lives here.
1294pub fn template_string_trailing_text(src: &str) -> Diagnostic {
1295    let message = format!("unexpected text after string literal: {src:?}");
1296    Diagnostic::new(
1297        "dsl.template.string_trailing_text",
1298        message,
1299        Diagnostic::make_fields(&[(FIELD_GOT, src)]),
1300    )
1301}
1302
1303/// Quoted string literal with no closer. Takes the source; `Debug`
1304/// rendering lives here.
1305pub fn template_string_unterminated(src: &str) -> Diagnostic {
1306    let message = format!("unterminated string literal: {src:?}");
1307    Diagnostic::new(
1308        "dsl.template.string_unterminated",
1309        message,
1310        Diagnostic::make_fields(&[(FIELD_GOT, src)]),
1311    )
1312}
1313
1314/// Text after a block string literal's closer. Takes the source;
1315/// `Debug` rendering lives here.
1316pub fn template_block_trailing_text(src: &str) -> Diagnostic {
1317    let message = format!("unexpected text after block string literal: {src:?}");
1318    Diagnostic::new(
1319        "dsl.template.block_trailing_text",
1320        message,
1321        Diagnostic::make_fields(&[(FIELD_GOT, src)]),
1322    )
1323}
1324
1325/// Block string literal with no closer triple. Takes the source;
1326/// `Debug` rendering lives here.
1327pub fn template_block_unterminated(src: &str) -> Diagnostic {
1328    let message = format!("unterminated block string literal: {src:?}");
1329    Diagnostic::new(
1330        "dsl.template.block_unterminated",
1331        message,
1332        Diagnostic::make_fields(&[(FIELD_GOT, src)]),
1333    )
1334}
1335
1336/// Placeholder string literal ending in a backslash. Parameterless:
1337/// the wording is fixed.
1338pub fn template_string_unterminated_escape() -> Diagnostic {
1339    Diagnostic::new(
1340        "dsl.template.string_unterminated_escape",
1341        "unterminated escape in placeholder string literal".to_string(),
1342        Diagnostic::make_fields(&[]),
1343    )
1344}
1345
1346/// Map literal key that is neither a bare name nor a string spelling.
1347/// Takes the source; quoting lives here.
1348pub fn template_map_key_invalid(src: &str) -> Diagnostic {
1349    let message =
1350        format!("invalid map literal key `{src}`: use a bare name or any string spelling");
1351    Diagnostic::new(
1352        "dsl.template.map_key_invalid",
1353        message,
1354        Diagnostic::make_fields(&[(FIELD_GOT, src)]),
1355    )
1356}
1357
1358/// `modules:` prefix holding a non-module token. Takes the rendered
1359/// token; quoting lives here.
1360pub fn macro_input_modules_prefix_other(other: &str) -> Diagnostic {
1361    let message = format!("modules: prefix holds module names, found `{other}`");
1362    Diagnostic::new(
1363        "dsl.macro_input.modules_prefix_other",
1364        message,
1365        Diagnostic::make_fields(&[(FIELD_GOT, other)]),
1366    )
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371    use super::*;
1372
1373    #[test]
1374    fn duplicate_names_both_spellings() {
1375        let d = alias_duplicate_on_field("h", "help", "h2");
1376        assert_eq!(d.key(), "dsl.alias.duplicate_on_field");
1377        assert!(d.message().contains("`h`"));
1378        assert!(d.message().contains("`help`"));
1379        assert!(d.message().contains("`h2`"));
1380    }
1381
1382    #[test]
1383    fn trailing_text_is_unexpected_not_expected() {
1384        let d = spelling_trailing_text("foo");
1385        assert_eq!(d.key(), "dsl.spelling.trailing_text");
1386        assert!(d.message().starts_with("unexpected trailing text"));
1387    }
1388
1389    #[test]
1390    fn bracket_list_comment_shares_one_key_across_invokers() {
1391        let export = spelling_bracket_list_comment("EXPORT");
1392        let import = spelling_bracket_list_comment("IMPORT");
1393        assert_eq!(export.key(), "dsl.spelling.bracket_list_comment");
1394        assert_eq!(import.key(), export.key());
1395        assert_eq!(
1396            export.message(),
1397            "EXPORT lists do not allow comments inside the brackets: move the comment above the statement"
1398        );
1399        assert_eq!(
1400            import.message(),
1401            "IMPORT lists do not allow comments inside the brackets: move the comment above the statement"
1402        );
1403    }
1404
1405    #[test]
1406    fn each_failure_has_a_distinct_key() {
1407        let keys = [
1408            spelling_trailing_text("x").key(),
1409            spelling_max_depth(8, "x").key(),
1410            spelling_expected_type_name().key(),
1411            spelling_expected_uppercase("a").key(),
1412            spelling_expected_delimiter("x").key(),
1413            spelling_unterminated_string("x").key(),
1414            spelling_expected_literal("x").key(),
1415            spelling_invalid_float("x").key(),
1416            spelling_invalid_int("x").key(),
1417            spelling_bracket_list_comment("EXPORT").key(),
1418            alias_needs_field("x").key(),
1419            alias_needs_name().key(),
1420            alias_name_lowercase("B", "B").key(),
1421            alias_duplicate_on_field("h", "a", "b").key(),
1422            flag_missing_value("CMD", "--flag").key(),
1423            unknown_flag("CMD", "--nope").key(),
1424            too_many_positionals("CMD", 1, 2).key(),
1425            missing_argument("CMD", "path").key(),
1426            arg_type_mismatch("CMD", "path", "3", expected_int("x")).key(),
1427            expected_int("3").key(),
1428            expected_var("3").key(),
1429            expected_one_of(&["A", "B"], "x").key(),
1430            expected_var_expression("f()").key(),
1431            assignment_requires_key_value().key(),
1432            render_no_literal_form("HANDLE").key(),
1433            render_non_finite_float().key(),
1434            needs_value("ECHO").key(),
1435            env_requires_assignment().key(),
1436            env_bad_format().key(),
1437            env_assignment_error(assignment_requires_key_value()).key(),
1438            expand_bad_override().key(),
1439            expand_assignment_error(assignment_requires_key_value()).key(),
1440            expand_path_error(expected_int("x")).key(),
1441            expand_extra_path().key(),
1442            workdir_requires_path().key(),
1443            workspace_requires_target().key(),
1444            workspace_local_needs_cache().key(),
1445            workspace_unknown_target("NOPE").key(),
1446            unknown_workspace_source("COPY", "NOPE").key(),
1447            copy_requires_source().key(),
1448            copy_requires_destination().key(),
1449            copy_host_exclusion().key(),
1450            copy_git_requires_revision().key(),
1451            copy_git_requires_source().key(),
1452            copy_git_requires_destination().key(),
1453            symlink_requires_source().key(),
1454            symlink_requires_target().key(),
1455            mkdir_requires_path().key(),
1456            install_requires_source().key(),
1457            install_requires_destination().key(),
1458            set_executable_requires_path().key(),
1459            archive_requires_source().key(),
1460            archive_requires_destination().key(),
1461            unarchive_requires_archive().key(),
1462            unarchive_requires_destination().key(),
1463            unarchive_bad_max_bytes(invalid_byte_count("abc")).key(),
1464            export_unknown_func("NOPE").key(),
1465            export_type_qualified("LIB::T").key(),
1466            export_unknown_type("NOPE").key(),
1467            export_const_script_namespace("SCRIPT::N").key(),
1468            export_const_unknown_alias("$LIB::N", "LIB").key(),
1469            export_const_unknown("$N").key(),
1470            invalid_syntax("WRITE", "nothing", None).key(),
1471            unknown_command("NOPE", None).key(),
1472            let_capture_async().key(),
1473            let_capture_pipe_stdout().key(),
1474            nested_inherit_env().key(),
1475            tty_geometry_without_tty().key(),
1476            tty_with_stderr().key(),
1477            tty_wraps_non_run().key(),
1478            with_io_in_async().key(),
1479            copy_host_outside_remote().key(),
1480            int_boundary_overflow().key(),
1481            int_overflow(42).key(),
1482            write_requires_path().key(),
1483            append_requires_path().key(),
1484            append_line_requires_path().key(),
1485            remove_requires_path().key(),
1486            read_line_requires_variable().key(),
1487            read_line_requires_sigil("reply").key(),
1488            prompt_requires_variable().key(),
1489            prompt_requires_sigil("reply").key(),
1490            prompt_requires_message().key(),
1491            assert_contains_requires_value().key(),
1492            assert_contains_requires_needle().key(),
1493            exit_requires_code().key(),
1494            sleep_requires_duration().key(),
1495            sleep_takes_one().key(),
1496            invalid_numeric_token("x").key(),
1497            invalid_timeout_duration("x").key(),
1498            timeout_duration_out_of_range("x").key(),
1499            timeout_duration_not_positive("x").key(),
1500            invalid_byte_count("x").key(),
1501            byte_count_out_of_range("x").key(),
1502            byte_count_not_positive("x").key(),
1503            list_append_requires_list().key(),
1504            list_append_requires_sigil("x").key(),
1505            list_append_requires_item().key(),
1506            list_append_takes_two().key(),
1507            assert_equality_requires_value("ASSERT_EQ").key(),
1508            assert_equality_requires_expected("ASSERT_EQ").key(),
1509            assert_equality_hash_with_expected("ASSERT_EQ").key(),
1510            markdown_unclosed_fence(3).key(),
1511            markdown_metadata_unexpected_char(3, '%').key(),
1512            markdown_metadata_missing_colon(3, "k").key(),
1513            markdown_metadata_equals_syntax(3, "k").key(),
1514            markdown_metadata_unterminated_quote(3).key(),
1515            markdown_metadata_env_shape(3).key(),
1516            markdown_metadata_roots_unsupported(3, "v").key(),
1517            markdown_metadata_roots_duplicate(3).key(),
1518            markdown_metadata_expect_error_duplicate(3).key(),
1519            markdown_metadata_unknown_key(3, "k").key(),
1520            template_string_trailing_text("x").key(),
1521            template_string_unterminated("x").key(),
1522            template_block_trailing_text("x").key(),
1523            template_block_unterminated("x").key(),
1524            template_string_unterminated_escape().key(),
1525            template_map_key_invalid("x").key(),
1526            macro_input_modules_prefix_other("x").key(),
1527        ];
1528        let mut seen = std::collections::HashSet::new();
1529        for k in keys {
1530            assert!(seen.insert(k), "duplicate key {k}");
1531        }
1532    }
1533
1534    #[test]
1535    fn markdown_template_macro_messages_match_canonical_wording() {
1536        assert_eq!(
1537            markdown_unclosed_fence(3).message(),
1538            "markdown:3: code fence is never closed"
1539        );
1540        assert_eq!(
1541            markdown_unclosed_fence(3).key(),
1542            "dsl.markdown.unclosed_fence"
1543        );
1544        assert_eq!(
1545            markdown_metadata_unknown_key(3, "bogus").message(),
1546            "markdown:3: unknown fence metadata key `bogus` (supported: env, roots, expect_error, mock_remote)"
1547        );
1548        assert_eq!(
1549            markdown_metadata_roots_unsupported(3, "squashed").message(),
1550            "markdown:3: unsupported roots metadata `squashed` (only `unified` is defined)"
1551        );
1552        assert_eq!(
1553            markdown_metadata_env_shape(3).message(),
1554            "markdown:3: env metadata must be `env:KEY=VALUE`"
1555        );
1556        assert_eq!(
1557            template_string_unterminated("abc").message(),
1558            "unterminated string literal: \"abc\""
1559        );
1560        assert_eq!(
1561            template_string_trailing_text("abc").message(),
1562            "unexpected text after string literal: \"abc\""
1563        );
1564        assert_eq!(
1565            template_map_key_invalid("a b").message(),
1566            "invalid map literal key `a b`: use a bare name or any string spelling"
1567        );
1568        assert_eq!(
1569            template_string_unterminated_escape().message(),
1570            "unterminated escape in placeholder string literal"
1571        );
1572        assert_eq!(
1573            macro_input_modules_prefix_other("foo").message(),
1574            "modules: prefix holds module names, found `foo`"
1575        );
1576    }
1577
1578    #[test]
1579    fn validation_messages_are_command_lead() {
1580        let d = unknown_flag("WRITE", "--nope");
1581        assert_eq!(d.key(), "dsl.validation.unknown_flag");
1582        assert_eq!(d.message(), "WRITE unknown flag `--nope`");
1583        let d = flag_missing_value("WRITE", "--path");
1584        assert_eq!(d.message(), "WRITE `--path` requires a value");
1585        let d = missing_argument("WRITE", "path");
1586        assert!(d.message().contains("requires argument `path`"));
1587        assert!(d.message().starts_with("WRITE"));
1588        let d = too_many_positionals("CMD", 1, 3);
1589        assert_eq!(
1590            d.message(),
1591            "CMD expects at most 1 positional arguments, got 3"
1592        );
1593        let d = arg_type_mismatch("CMD", "path", "3", expected_int("PATH"));
1594        assert_eq!(
1595            d.message(),
1596            "CMD argument `path` got \"3\": expected int, got \"PATH\""
1597        );
1598        assert_eq!(expected_int("3").message(), "expected int, got \"3\"");
1599        assert_eq!(expected_var("3").message(), "expected $var, got \"3\"");
1600        assert_eq!(
1601            expected_one_of(&["A", "B"], "x").message(),
1602            "expected one of A|B, got \"x\""
1603        );
1604        assert_eq!(
1605            expected_var_expression("f()").message(),
1606            "expected $var, got expression f()"
1607        );
1608        assert_eq!(
1609            assignment_requires_key_value().message(),
1610            "assignment requires KEY=value format"
1611        );
1612        assert_eq!(
1613            render_no_literal_form("HANDLE").message(),
1614            "value of type HANDLE has no DSL literal form"
1615        );
1616        assert_eq!(
1617            render_non_finite_float().message(),
1618            "non-finite FLOAT has no DSL literal form"
1619        );
1620    }
1621
1622    #[test]
1623    fn env_expand_messages_keep_legacy_wording() {
1624        assert_eq!(
1625            env_requires_assignment().message(),
1626            "ENV requires KEY=value"
1627        );
1628        assert_eq!(env_bad_format().message(), "ENV requires KEY=value format");
1629        assert_eq!(
1630            expand_bad_override().message(),
1631            "EXPAND requires KEY=value format for overrides"
1632        );
1633        assert_eq!(
1634            expand_extra_path().message(),
1635            "EXPAND accepts at most one path"
1636        );
1637        assert_eq!(
1638            needs_value("ECHO").message(),
1639            "ECHO requires at least one argument"
1640        );
1641        assert_eq!(
1642            env_assignment_error(assignment_requires_key_value()).message(),
1643            "assignment requires KEY=value format"
1644        );
1645    }
1646
1647    #[test]
1648    fn workspace_copy_messages_keep_legacy_wording() {
1649        assert_eq!(workdir_requires_path().message(), "WORKDIR requires a path");
1650        assert_eq!(
1651            workspace_requires_target().message(),
1652            "WORKSPACE requires a target"
1653        );
1654        assert_eq!(
1655            workspace_local_needs_cache().message(),
1656            "WORKSPACE --local requires CACHE"
1657        );
1658        assert_eq!(
1659            workspace_unknown_target("NOPE").message(),
1660            "unknown workspace target \"NOPE\""
1661        );
1662        assert_eq!(
1663            unknown_workspace_source("COPY", "NOPE").message(),
1664            "unknown workspace source \"NOPE\""
1665        );
1666        assert_eq!(copy_requires_source().message(), "COPY requires a source");
1667        assert_eq!(
1668            copy_requires_destination().message(),
1669            "COPY requires a destination"
1670        );
1671        assert_eq!(
1672            copy_host_exclusion().message(),
1673            "COPY --from-host and --to-host are mutually exclusive"
1674        );
1675        assert_eq!(
1676            copy_git_requires_revision().message(),
1677            "COPY_GIT requires a revision"
1678        );
1679        assert_eq!(
1680            copy_git_requires_source().message(),
1681            "COPY_GIT requires a source"
1682        );
1683        assert_eq!(
1684            copy_git_requires_destination().message(),
1685            "COPY_GIT requires a destination"
1686        );
1687        assert_eq!(
1688            symlink_requires_source().message(),
1689            "SYMLINK requires a source"
1690        );
1691        assert_eq!(
1692            symlink_requires_target().message(),
1693            "SYMLINK requires a target"
1694        );
1695    }
1696
1697    #[test]
1698    fn fs_path_messages_keep_legacy_wording() {
1699        assert_eq!(mkdir_requires_path().message(), "MKDIR requires a path");
1700        assert_eq!(
1701            install_requires_source().message(),
1702            "INSTALL requires a source"
1703        );
1704        assert_eq!(
1705            install_requires_destination().message(),
1706            "INSTALL requires a destination"
1707        );
1708        assert_eq!(
1709            set_executable_requires_path().message(),
1710            "SET_EXECUTABLE requires a path"
1711        );
1712        assert_eq!(
1713            archive_requires_source().message(),
1714            "ARCHIVE requires a source"
1715        );
1716        assert_eq!(
1717            archive_requires_destination().message(),
1718            "ARCHIVE requires a destination"
1719        );
1720        assert_eq!(
1721            unarchive_requires_archive().message(),
1722            "UNARCHIVE requires an archive"
1723        );
1724        assert_eq!(
1725            unarchive_requires_destination().message(),
1726            "UNARCHIVE requires a destination"
1727        );
1728        assert_eq!(
1729            unarchive_bad_max_bytes(invalid_byte_count("abc")).message(),
1730            "UNARCHIVE --max-bytes"
1731        );
1732        assert_eq!(
1733            format!(
1734                "{:#}",
1735                anyhow::Error::new(unarchive_bad_max_bytes(invalid_byte_count("abc")))
1736            ),
1737            "UNARCHIVE --max-bytes: invalid byte count: abc"
1738        );
1739        assert_eq!(write_requires_path().message(), "WRITE requires a path");
1740        assert_eq!(append_requires_path().message(), "APPEND requires a path");
1741        assert_eq!(
1742            append_line_requires_path().message(),
1743            "APPEND_LINE requires a path"
1744        );
1745        assert_eq!(remove_requires_path().message(), "REMOVE requires a path");
1746    }
1747
1748    #[test]
1749    fn export_messages() {
1750        assert_eq!(
1751            export_unknown_func("NOPE").message(),
1752            "EXPORT `NOPE` does not match any top-level FUNC or known module member"
1753        );
1754        assert_eq!(
1755            export_type_qualified("LIB::T").message(),
1756            "EXPORT TYPE `LIB::T` must be bare: qualified ALIAS::TYPE re-exports are not served; import the file and re-export the bare name"
1757        );
1758        assert_eq!(
1759            export_unknown_type("NOPE").message(),
1760            "EXPORT TYPE `NOPE` does not match any top-level TYPE"
1761        );
1762        assert_eq!(
1763            export_const_script_namespace("SCRIPT::N").message(),
1764            "EXPORT CONST `SCRIPT::N` must name a top-level CONST (`$NAME`) or `$ALIAS::NAME` for a visible import: `SCRIPT::` is not a CONST namespace"
1765        );
1766        assert_eq!(
1767            export_const_unknown_alias("$LIB::N", "LIB").message(),
1768            "EXPORT CONST `$LIB::N` names unknown import alias `LIB`: import a file as `LIB` to re-export its CONSTs"
1769        );
1770        assert_eq!(
1771            export_const_unknown("$N").message(),
1772            "EXPORT CONST `$N` does not match any top-level CONST (LET bindings are never exportable)"
1773        );
1774    }
1775
1776    #[test]
1777    fn invalid_syntax_and_unknown_command_messages() {
1778        assert_eq!(
1779            invalid_syntax("WRITE", "nothing", None).message(),
1780            "WRITE got nothing"
1781        );
1782        assert_eq!(
1783            invalid_syntax("WRITE", "`x`", Some("use WRITE <path>.")).message(),
1784            "use WRITE <path>"
1785        );
1786        assert_eq!(
1787            unknown_command("NOPE", None).message(),
1788            "unknown command \"NOPE\""
1789        );
1790        assert_eq!(
1791            unknown_command("WRIT", Some("did you mean WRITE?.")).message(),
1792            "unknown command \"WRIT\"\ndid you mean WRITE?"
1793        );
1794    }
1795
1796    #[test]
1797    fn structural_messages() {
1798        assert_eq!(
1799            let_capture_async().message(),
1800            "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE<T> = ASYNC ... then LET $o: STRING = AWAIT $t"
1801        );
1802        assert_eq!(
1803            let_capture_pipe_stdout().message(),
1804            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
1805        );
1806        assert_eq!(
1807            nested_inherit_env().message(),
1808            "INHERIT_ENV cannot be nested inside other commands"
1809        );
1810        assert_eq!(
1811            tty_geometry_without_tty().message(),
1812            "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size"
1813        );
1814        assert_eq!(
1815            tty_with_stderr().message(),
1816            "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex"
1817        );
1818        assert_eq!(
1819            tty_wraps_non_run().message(),
1820            "WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it"
1821        );
1822        assert_eq!(
1823            with_io_in_async().message(),
1824            "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)"
1825        );
1826        assert_eq!(
1827            copy_host_outside_remote().message(),
1828            "COPY --from-host and --to-host are only valid inside a REMOTE block"
1829        );
1830        assert_eq!(
1831            int_boundary_overflow().message(),
1832            "integer overflow: 9223372036854775808 exceeds i64::MAX"
1833        );
1834        assert_eq!(
1835            int_overflow(42).message(),
1836            "integer overflow: 42 exceeds i64::MAX"
1837        );
1838    }
1839
1840    #[test]
1841    fn read_line_prompt_messages_keep_legacy_shape() {
1842        assert_eq!(
1843            read_line_requires_variable().message(),
1844            "READ_LINE requires a variable"
1845        );
1846        assert_eq!(
1847            read_line_requires_sigil("reply").message(),
1848            "READ_LINE requires a $variable, found \"reply\""
1849        );
1850        assert_eq!(
1851            prompt_requires_variable().message(),
1852            "PROMPT requires a variable"
1853        );
1854        assert_eq!(
1855            prompt_requires_sigil("reply").message(),
1856            "PROMPT requires a $variable, found \"reply\""
1857        );
1858        assert_eq!(
1859            prompt_requires_message().message(),
1860            "PROMPT requires a message"
1861        );
1862    }
1863
1864    #[test]
1865    fn assert_exit_sleep_list_append_messages() {
1866        assert_eq!(
1867            assert_contains_requires_value().message(),
1868            "ASSERT_CONTAINS requires a value"
1869        );
1870        assert_eq!(
1871            assert_contains_requires_needle().message(),
1872            "ASSERT_CONTAINS requires a needle"
1873        );
1874        assert_eq!(exit_requires_code().message(), "EXIT requires a code");
1875        assert_eq!(
1876            sleep_requires_duration().message(),
1877            "SLEEP requires a duration (e.g. SLEEP 500ms)"
1878        );
1879        assert_eq!(
1880            sleep_takes_one().message(),
1881            "SLEEP takes exactly one duration argument"
1882        );
1883        assert_eq!(
1884            invalid_numeric_token("1 2 3").message(),
1885            "invalid numeric token: 1 2 3"
1886        );
1887        assert_eq!(
1888            invalid_timeout_duration("abc").message(),
1889            "invalid TIMEOUT duration: abc"
1890        );
1891        assert_eq!(
1892            timeout_duration_out_of_range("99999999999999999999h").message(),
1893            "TIMEOUT duration out of range: 99999999999999999999h"
1894        );
1895        assert_eq!(
1896            timeout_duration_not_positive("0s").message(),
1897            "TIMEOUT duration must be positive, got: 0s"
1898        );
1899        assert_eq!(
1900            invalid_byte_count("abc").message(),
1901            "invalid byte count: abc"
1902        );
1903        assert_eq!(
1904            byte_count_out_of_range("99999999999999999999GB").message(),
1905            "byte count out of range: 99999999999999999999GB"
1906        );
1907        assert_eq!(
1908            byte_count_not_positive("0").message(),
1909            "byte count must be positive, got: 0"
1910        );
1911        assert_eq!(
1912            list_append_requires_list().message(),
1913            "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)"
1914        );
1915        assert_eq!(
1916            list_append_requires_sigil("x").message(),
1917            "LIST_APPEND requires a $variable, found \"x\""
1918        );
1919        assert_eq!(
1920            list_append_requires_item().message(),
1921            "LIST_APPEND requires an item to append (e.g. LIST_APPEND $items $x)"
1922        );
1923        assert_eq!(
1924            list_append_takes_two().message(),
1925            "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>"
1926        );
1927    }
1928
1929    #[test]
1930    fn assert_equality_messages() {
1931        assert_eq!(
1932            assert_equality_requires_value("ASSERT_EQ").message(),
1933            "ASSERT_EQ requires a value"
1934        );
1935        assert_eq!(
1936            assert_equality_requires_value("ASSERT_NE").message(),
1937            "ASSERT_NE requires a value"
1938        );
1939        assert_eq!(
1940            assert_equality_requires_expected("ASSERT_EQ").message(),
1941            "ASSERT_EQ requires an expected value"
1942        );
1943        assert_eq!(
1944            assert_equality_hash_with_expected("ASSERT_NE").message(),
1945            "ASSERT_NE --hash cannot be combined with an expected value"
1946        );
1947    }
1948
1949    #[test]
1950    fn arg_mismatch_inlines_reason_verbatim() {
1951        // Parse errors render only the outer message, so the reason
1952        // rides inline (never as a chained source): the actionable
1953        // text stays visible in `parse_err` snapshots.
1954        let d = arg_type_mismatch("CMD", "path", "3", expected_int("PATH"));
1955        assert_eq!(
1956            d.message(),
1957            "CMD argument `path` got \"3\": expected int, got \"PATH\""
1958        );
1959        assert_eq!(
1960            d.fields().get("reason").map(String::as_str),
1961            Some("expected int, got \"PATH\"")
1962        );
1963    }
1964}