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