pddl-core 0.5.0

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

use std::borrow::Cow;
use std::fmt;
use std::ops::Range;

/// Maximum number of characters of the remaining input kept in a [`ParseError`].
const EXCERPT_CHARS: usize = 40;

/// An error returned by [`Parser::from_str`](crate::parsers::Parser::from_str).
///
/// Describes where parsing stopped and which input was found there. The
/// excerpt is bounded, so formatting the error never echoes the whole
/// remaining input.
///
/// With the `miette` feature, `ParseError` implements `miette::Diagnostic`.
/// Attach the parsed text to render the error with the offending input marked:
/// `miette::Report::new(error).with_source_code(input)`.
///
/// ## Example
/// ```
/// # use pddl::{Domain, Parser};
/// let error = Domain::from_str("(define (domain d)\n  (:bogus))").unwrap_err();
/// assert_eq!((error.line(), error.column()), (2, 3));
/// assert_eq!(error.span(), 21..28);
/// assert_eq!(error.found(), Some("(:bogus))"));
/// assert_eq!(error.reason(), Some("unknown section"));
/// assert_eq!(error.to_string(), "line 2, column 3: unknown section: unexpected `(:bogus))`");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError(Box<Details>);

/// The contents of a [`ParseError`], boxed so that a `Result` with it stays small.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Details {
    /// Byte offset of the error in the input.
    offset: usize,
    /// Length in bytes of the input the error covers; see [`ParseError::span`].
    len: usize,
    /// 1-based line of `offset`.
    line: usize,
    /// 1-based column of `offset`, in characters.
    column: usize,
    /// Sanitized excerpt of the input from `offset`, or `None` at the end of the input.
    found: Option<String>,
    /// Sanitized `:keyword` of the innermost form containing the error.
    keyword: Option<String>,
    /// Sanitized description of why parsing stopped.
    reason: Option<String>,
    /// Byte offset of the `(` that is never closed, for an error at the end of the input.
    #[cfg_attr(not(feature = "miette"), allow(dead_code))]
    unclosed: Option<usize>,
    /// A suggestion for fixing the mistake, e.g. "did you mean `:predicates`?".
    help: Option<String>,
}

impl ParseError {
    /// The byte offset into the input at which parsing stopped.
    #[must_use]
    pub const fn offset(&self) -> usize {
        self.0.offset
    }

    /// The byte range of the input that parsing stopped at: an atom, the start
    /// of a list up to its first atom (e.g. `(:bogus`), a single parenthesis,
    /// or an empty range at the end of the input.
    #[must_use]
    pub const fn span(&self) -> Range<usize> {
        self.0.offset..self.0.offset + self.0.len
    }

    /// The 1-based line at which parsing stopped.
    #[must_use]
    pub const fn line(&self) -> usize {
        self.0.line
    }

    /// The 1-based column (in characters) at which parsing stopped.
    #[must_use]
    pub const fn column(&self) -> usize {
        self.0.column
    }

    /// A short excerpt of the input at which parsing stopped,
    /// or `None` if the input ended early.
    #[must_use]
    pub fn found(&self) -> Option<&str> {
        self.0.found.as_deref()
    }

    /// The PDDL keyword of the innermost form in which parsing stopped, if known,
    /// e.g. `:precondition` for a mistake inside an action's precondition.
    ///
    /// Made safe for display like [`found`](Self::found): characters outside
    /// printable ASCII are escaped, and long values are cut and end in `...`.
    #[must_use]
    pub fn keyword(&self) -> Option<&str> {
        self.0.keyword.as_deref()
    }

    /// Why parsing stopped, if known, e.g. `duplicate section`, ``missing `:goal` ``
    /// or ``expected `)` `` for a form that isn't closed.
    ///
    /// Made safe for display like [`found`](Self::found): characters outside
    /// printable ASCII are escaped, and long values are cut and end in `...`.
    #[must_use]
    pub fn reason(&self) -> Option<&str> {
        self.0.reason.as_deref()
    }

    /// A suggestion for fixing the mistake, if one is known, e.g.
    /// ``did you mean `:predicates`?`` for `(:predicats ...)`.
    ///
    /// Given for misspelled keywords from a fixed set: section names, action
    /// keywords such as `:effect`, and keywords such as `start` or `minimize`.
    #[must_use]
    pub fn help(&self) -> Option<&str> {
        self.0.help.as_deref()
    }

    /// Describes `error` within `input`.
    pub(crate) fn new(input: &str, error: &Error) -> Self {
        Self::with_lines(&Lines::new(input), error)
    }

    /// Describes `error` within the input of `lines`, which can be shared by many errors.
    pub(crate) fn with_lines(lines: &Lines<'_>, error: &Error) -> Self {
        let input = lines.input;
        let offset = error.offset.min(input.len());
        let (line, column) = lines.position(offset);
        let rest = &input[offset..];
        Self(Box::new(Details {
            offset,
            len: error.len.min(rest.len()),
            line,
            column,
            found: (!rest.is_empty()).then(|| sanitize(rest)),
            keyword: error.keyword.as_deref().map(sanitize),
            reason: error.reason.map(sanitize),
            unclosed: error.unclosed,
            help: error
                .suggestion
                .map(|word| format!("did you mean `{word}`?")),
        }))
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {}, column {}: ", self.0.line, self.0.column)?;
        if let Some(keyword) = &self.0.keyword {
            write!(f, "in `{keyword}`: ")?;
        }
        if let Some(reason) = &self.0.reason {
            write!(f, "{reason}: ")?;
        }
        match &self.0.found {
            Some(found) => write!(f, "unexpected `{found}`"),
            None => f.write_str("unexpected end of input"),
        }
    }
}

impl std::error::Error for ParseError {}

#[cfg(feature = "miette")]
#[cfg_attr(docsrs, doc(cfg(feature = "miette")))]
impl miette::Diagnostic for ParseError {
    fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        Some(Box::new("pddl::parse"))
    }

    fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
        self.0
            .help
            .as_ref()
            .map(|help| Box::new(help) as Box<dyn fmt::Display>)
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
        let text = self
            .0
            .reason
            .clone()
            .unwrap_or_else(|| match &self.0.found {
                Some(_) => "unexpected".to_string(),
                None => "unexpected end of input".to_string(),
            });
        let label = miette::LabeledSpan::new_primary_with_span(Some(text), self.span());
        // An error at the end of the input has an empty span, which a report can't mark;
        // the `(` that is never closed shows where the missing `)` belongs.
        let unclosed = self.0.unclosed.map(|offset| {
            miette::LabeledSpan::new_with_span(
                Some("this `(` is never closed".to_string()),
                offset..offset + 1,
            )
        });
        Some(Box::new(std::iter::once(label).chain(unclosed)))
    }
}

/// Makes text that may come from untrusted input safe for an error message.
///
/// Printable ASCII is kept, ASCII whitespace becomes a space, and every other
/// character is shown as an escape such as `\u{202e}`. Nothing can then alter
/// or hide what a terminal or log shows (ANSI escapes, bidi overrides,
/// zero-width or tag characters, ...); PDDL itself is pure ASCII. The result
/// covers at most [`EXCERPT_CHARS`] characters of `text`, followed by `...`
/// if it was cut.
fn sanitize(text: &str) -> String {
    let mut safe = String::new();
    for c in text.chars().take(EXCERPT_CHARS) {
        if c.is_ascii_graphic() || c == ' ' {
            safe.push(c);
        } else if c.is_ascii_whitespace() {
            safe.push(' ');
        } else {
            safe.extend(c.escape_unicode());
        }
    }
    if text.chars().nth(EXCERPT_CHARS).is_some() {
        safe.push_str("...");
    }
    safe
}

/// The byte offsets at which the lines of an input start, to find the line and
/// column of many offsets without scanning the input again for each.
///
/// A line ends at `\n`, `\r\n` or a lone `\r`, as a comment does.
pub(crate) struct Lines<'a> {
    /// The input the offsets refer to.
    input: &'a str,
    /// The byte offset of each line's first character, sorted ascending; starts with `0`.
    starts: Vec<usize>,
}

impl<'a> Lines<'a> {
    /// Finds the line starts of `input`, in one pass.
    pub(crate) fn new(input: &'a str) -> Self {
        let bytes = input.as_bytes();
        let breaks = bytes
            .iter()
            .enumerate()
            .filter(|&(i, &b)| b == b'\n' || (b == b'\r' && bytes.get(i + 1) != Some(&b'\n')));
        let starts = std::iter::once(0)
            .chain(breaks.map(|(i, _)| i + 1))
            .collect();
        Self { input, starts }
    }

    /// The 1-based line and column (in characters) of the byte `offset`, which
    /// must be at most the input's length and on a character boundary.
    ///
    /// Takes logarithmic time in the number of lines plus linear time in the
    /// length of `offset`'s line.
    fn position(&self, offset: usize) -> (usize, usize) {
        let line = self.starts.partition_point(|&start| start <= offset);
        let start = self.starts[line - 1];
        (line, self.input[start..offset].chars().count() + 1)
    }
}

/// A grammar error: where it happened and, if known, in which form and why.
///
/// [`Parser::from_str`](crate::parsers::Parser::from_str) turns it into a [`ParseError`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Error {
    /// Byte offset of the error in the input.
    pub offset: usize,
    /// Length in bytes of the input the error covers.
    pub len: usize,
    /// The `:keyword` of the innermost form the error is in, such as `:action`.
    pub keyword: Option<Cow<'static, str>>,
    /// Why parsing failed, such as `duplicate section`.
    pub reason: Option<&'static str>,
    /// A fatal error ends parsing; otherwise the grammar may try another alternative.
    /// Errors inside a `:keyword` form are fatal: nothing else can start with it.
    pub fatal: bool,
    /// Byte offset of the `(` that is never closed, for an error at the end of the input.
    pub unclosed: Option<usize>,
    /// A keyword that was probably meant instead of the input at the error.
    pub suggestion: Option<&'static str>,
}

/// The result of a grammar rule.
pub(crate) type R<T> = Result<T, Error>;

impl Error {
    /// An error covering `len` bytes at `offset`.
    pub const fn at(offset: usize, len: usize) -> Self {
        Self {
            offset,
            len,
            keyword: None,
            reason: None,
            fatal: false,
            unclosed: None,
            suggestion: None,
        }
    }

    /// Suggests the candidate closest to `word`, if one is a likely misspelling of it.
    pub fn suggest(mut self, word: &str, candidates: &[&'static str]) -> Self {
        self.suggestion = crate::parsers::suggest::suggest(word, candidates);
        self
    }

    /// Sets why parsing failed.
    pub fn reason(mut self, reason: &'static str) -> Self {
        self.reason = Some(reason);
        self
    }

    /// Sets the `:keyword` of the form the error is in.
    pub fn keyword(mut self, keyword: impl Into<Cow<'static, str>>) -> Self {
        self.keyword = Some(keyword.into());
        self
    }

    /// Makes the error fatal, so no alternative is tried after it.
    pub const fn fatal(mut self) -> Self {
        self.fatal = true;
        self
    }

    /// When all alternatives failed, keeps the error that got furthest into
    /// the input: that alternative most likely was the one intended. On a tie,
    /// prefers the error that knows more about why it failed, then the later one,
    /// and keeps a suggestion or unclosed `(` that only the other one found.
    pub fn or(self, other: Self) -> Self {
        let rank = |e: &Self| {
            let described = e.reason.is_some() || e.keyword.is_some();
            (e.offset, described)
        };
        let (mut kept, dropped) = if rank(&self) > rank(&other) {
            (self, other)
        } else {
            (other, self)
        };
        if kept.offset == dropped.offset {
            kept.suggestion = kept.suggestion.or(dropped.suggestion);
            kept.unclosed = kept.unclosed.or(dropped.unclosed);
        }
        kept
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Domain, Parser, PddlFile, Problem};
    use assert2::check;

    /// Typical mistakes are reported at the mistake itself, with the enclosing
    /// keyword and a reason where known.
    #[test]
    fn typical_mistakes_are_reported_where_they_are() {
        // (label, parser, input, expected start of the error message)
        type Case<'a> = (&'a str, &'a dyn Fn(&str) -> ParseError, String, &'a str);
        const HEAD: &str = "(define (domain d) (:requirements :strips) (:predicates (p ?x) (q))\n";
        let action = |body: &str| format!("{HEAD}  (:action a {body}))");
        let domain = |s: &str| Domain::from_str(s).unwrap_err();
        let problem = |s: &str| Problem::from_str(s).unwrap_err();
        let file = |s: &str| PddlFile::from_str(s).unwrap_err();

        let cases: [Case; 11] = [
            (
                "incomplete typed parameter",
                &domain,
                action(":parameters (?x - ) :precondition (p ?x) :effect (q)"),
                "line 2, column 32: in `:parameters`: unexpected `) :precondition",
            ),
            (
                "bad element in a precondition",
                &domain,
                action(":parameters (?x) :precondition (and (p ?x) 5) :effect (q)"),
                "line 2, column 57: in `:precondition`: unexpected `5) :effect",
            ),
            (
                "misspelled action keyword",
                &domain,
                action(":parameters (?x) :precondition (p ?x) :efect (q)"),
                "line 2, column 52: in `:action`: expected `)`: unexpected `:efect (q)",
            ),
            (
                "unclosed action followed by another section",
                &domain,
                format!("{HEAD}  (:action a :parameters () :effect (q)\n  (:predicates (r)))"),
                "line 3, column 3: in `:action`: expected `)`: unexpected `(:predicates (r)",
            ),
            (
                "requirement without colon",
                &domain,
                "(define (domain d) (:requirements strips))".to_string(),
                "line 1, column 35: in `:requirements`: unexpected `strips))`",
            ),
            (
                "duplicate section",
                &domain,
                "(define (domain d) (:predicates (p)) (:predicates (q)))".to_string(),
                "line 1, column 38: duplicate section: unexpected `(:predicates (q)",
            ),
            (
                "unknown section",
                &domain,
                "(define (domain d) (:predicats (p)))".to_string(),
                "line 1, column 20: unknown section: unexpected `(:predicats",
            ),
            (
                "missing :goal",
                &problem,
                "(define (problem p) (:domain d) (:init (p a))\n)".to_string(),
                "line 2, column 1: missing `:goal`: unexpected `)`",
            ),
            (
                "section written without parentheses",
                &problem,
                "(define (problem p) (:domain d) (:init) :goal (and))".to_string(),
                "line 1, column 41: unexpected `:goal (and))`",
            ),
            (
                "bad init element",
                &problem,
                "(define (problem p) (:domain d) (:init (p a) 5) (:goal (p a)))".to_string(),
                "line 1, column 46: in `:init`: unexpected `5) (:goal",
            ),
            (
                "domain read as part of a file",
                &file,
                format!(
                    "(define (problem q) (:domain d) (:init) (:goal (q)))\n{}",
                    action(":parameters (?x - ) :effect (q)")
                ),
                "line 3, column 32: in `:parameters`: unexpected `) :effect",
            ),
        ];
        for (label, parse, input, expected) in cases {
            let message = parse(&input).to_string();
            check!(
                message.starts_with(expected),
                "{label}:\n  got {message}\n want {expected}"
            );
        }
    }

    /// The structured accessors match what `Display` shows.
    #[test]
    fn keyword_and_reason_accessors() {
        let error = Domain::from_str(
            "(define (domain d) (:predicates (p)) (:action a :parameters () :effect (p)",
        )
        .unwrap_err();
        check!(error.keyword() == Some(":action"));
        check!(error.reason() == Some("expected `)`"));
        check!(error.found() == None);

        let error = Domain::from_str("(define (domain d) (:predicates (p)) (:predicates (q)))")
            .unwrap_err();
        check!(error.keyword() == None);
        check!(error.reason() == Some("duplicate section"));
    }

    /// Keywords and reasons are sanitized like the excerpt.
    #[test]
    fn keyword_and_reason_are_sanitized() {
        let error = Error::at(0, 1)
            .reason("bad\x1b[2J\nreason")
            .keyword(":act\x07ion");
        let parsed = ParseError::new("x", &error);
        check!(parsed.keyword() == Some(r":act\u{7}ion"));
        check!(parsed.reason() == Some(r"bad\u{1b}[2J reason"));
        check!(
            !parsed.to_string().chars().any(char::is_control),
            "{parsed}"
        );
    }

    /// The keyword of an unclosed form comes from the input, so it is sanitized too.
    #[test]
    fn keyword_of_an_unclosed_form_is_sanitized() {
        let input = "(:\u{202E}x";
        let unclosed = crate::parsers::sexpr::read(input)
            .unwrap()
            .unbalanced
            .unwrap();
        let error = ParseError::new(input, &unclosed);
        check!(error.keyword() == Some(r":\u{202e}x"));
    }

    /// Bidi overrides, isolates and zero-width characters show up as escapes instead of
    /// spoofing the message.
    #[test]
    fn invisible_format_characters_are_escaped() {
        let input = "(define (domain d)\n(:\u{202E}evil\u{2066}\u{200B}\u{FEFF}))";
        let error = Domain::from_str(input).unwrap_err();
        let found = error.found().unwrap();
        check!(found.is_ascii(), "{found:?}");
        check!(found == r"(:\u{202e}evil\u{2066}\u{200b}\u{feff}))");
    }

    /// Characters a hand-written list would miss are escaped too.
    #[test]
    fn every_non_ascii_character_is_escaped() {
        let input = "(define (domain d)\n(:\u{E0041}\u{FFF9}\u{206A}\u{FE0F}\u{00A0}x))";
        let found = Domain::from_str(input)
            .unwrap_err()
            .found()
            .unwrap()
            .to_string();
        check!(found == r"(:\u{e0041}\u{fff9}\u{206a}\u{fe0f}\u{a0}x))");
    }

    /// Keywords and reasons are bounded like the excerpt.
    #[test]
    fn keyword_and_reason_are_bounded() {
        let long: &'static str = "x".repeat(10_000).leak();
        let parsed = ParseError::new("x", &Error::at(0, 1).reason(long).keyword(long));
        check!(parsed.keyword().unwrap().chars().count() == EXCERPT_CHARS + 3);
        check!(parsed.reason().unwrap().chars().count() == EXCERPT_CHARS + 3);
    }

    /// When alternatives fail at the same position, the one with a reason wins.
    #[test]
    fn or_prefers_the_furthest_then_the_described_error() {
        let plain = Error::at(3, 1);
        let described = Error::at(3, 1).reason("why");
        check!(plain.clone().or(described.clone()) == described);
        check!(described.clone().or(plain.clone()) == described);
        check!(described.or(Error::at(4, 1)) == Error::at(4, 1));
    }

    #[test]
    fn each_missing_required_problem_section_is_named() {
        for (input, reason) in [
            (
                "(define (problem p) (:init) (:goal (and)))",
                "missing `:domain`",
            ),
            (
                "(define (problem p) (:domain d) (:init))",
                "missing `:goal`",
            ),
        ] {
            let error = Problem::from_str(input).unwrap_err();
            check!(error.reason() == Some(reason), "{input}");
            check!(error.found() == Some(")"), "{input}");
        }
    }

    #[test]
    fn reports_line_column_and_bounded_excerpt() {
        let tail = "x".repeat(10_000);
        let input = format!("(define (domain d)\n  (:bogus {tail}))");
        let error = Domain::from_str(&input).unwrap_err();
        check!(error.line() == 2);
        check!(error.column() == 3);
        check!(error.offset() == 21);
        check!(error.span() == (21..28));
        let found = error.found().unwrap();
        check!(found.starts_with("(:bogus xxx"));
        check!(found.chars().count() == EXCERPT_CHARS + 3);
        check!(error.to_string().len() < 100);
    }

    #[test]
    fn excerpt_flattens_newlines() {
        let error = Domain::from_str("(define (domain d)\n(:bogus\n))").unwrap_err();
        check!(error.found() == Some("(:bogus ))"));
        check!(error.to_string() == "line 2, column 1: unknown section: unexpected `(:bogus ))`");
    }

    #[test]
    fn excerpt_escapes_control_characters() {
        let error = Domain::from_str("(define (domain d)\n(:\x1b[2J\0\x07))").unwrap_err();
        let found = error.found().unwrap();
        check!(!found.chars().any(char::is_control), "{found:?}");
        check!(found == r"(:\u{1b}[2J\u{0}\u{7}))");
    }

    #[test]
    fn end_of_input_has_no_excerpt() {
        let error = Domain::from_str("ab\n").unwrap_err();
        check!(error.found() == Some("ab "));
        let error = ParseError::new("ab\ncd", &Error::at(5, 0));
        check!((error.line(), error.column(), error.offset()) == (2, 3, 5));
        check!(error.found() == None);
        check!(error.span() == (5..5));
    }

    #[cfg(feature = "miette")]
    #[test]
    fn diagnostic_labels_the_span() {
        use miette::Diagnostic;
        let error = Domain::from_str("(define (domain d) (:bogus))").unwrap_err();
        let labels: Vec<_> = error.labels().unwrap().collect();
        check!(labels.len() == 1);
        check!((labels[0].offset(), labels[0].len()) == (19, 7));
        check!(labels[0].label() == Some("unknown section"));
        check!(error.code().unwrap().to_string() == "pddl::parse");
    }

    #[test]
    fn a_suggestion_survives_an_alternative_failing_at_the_same_place() {
        // The `(assign <function-term> undefined)` alternative suggests `undefined`
        // for `:undefined`; `(assign <function-term> <term>)` then fails at the
        // same atom without a suggestion.
        let error = crate::PrimitiveEffect::from_str("(assign (f) :undefined)").unwrap_err();
        check!(error.help() == Some("did you mean `undefined`?".to_owned()).as_deref());
    }

    /// Misspelled keywords from a fixed set get a suggestion; everything else doesn't.
    #[test]
    fn misspelled_keywords_get_a_suggestion() {
        use crate::{DurativeActionGoalDescription, Optimization};

        const HEAD: &str = "(define (domain d) (:predicates (p ?x)) ";
        let domain = |s: &str| Domain::from_str(s).unwrap_err().help().map(str::to_string);
        let problem = |s: &str| Problem::from_str(s).unwrap_err().help().map(str::to_string);
        let mean = |word: &str| Some(format!("did you mean `{word}`?"));

        // Sections, in any case.
        check!(domain("(define (domain d) (:predicats (p)))") == mean(":predicates"));
        check!(domain("(define (domain d) (:REQUIREMENT :strips))") == mean(":requirements"));
        check!(
            problem("(define (problem p) (:domian d) (:init) (:goal (and)))") == mean(":domain")
        );
        // Action keywords, required or optional.
        let action = |body: &str| domain(&format!("{HEAD}(:action a {body}))"));
        check!(action(":paramters (?x) :effect (p ?x)") == mean(":parameters"));
        check!(action(":parameters (?x) :precondtion (p ?x)") == mean(":precondition"));
        check!(action(":parameters (?x) :efect (p ?x)") == mean(":effect"));
        // Keywords inside forms, including a swapped pair of letters.
        let error = DurativeActionGoalDescription::from_str("(at strat (p))").unwrap_err();
        check!(error.help() == Some("did you mean `start`?"));
        check!(
            Optimization::from_str("minimise").unwrap_err().help()
                == Some("did you mean `minimize`?")
        );

        // No suggestion for distant words or a missing `)`.
        check!(domain("(define (domain d) (:bogus (p)))") == None);
        check!(action(":parameters (?x) :effect (p ?x) :foo 1") == None);
        check!(domain("(define (domain d) (:predicates (p)") == None);
    }

    /// The suggestion is part of the diagnostic, not of the message.
    #[test]
    fn the_message_does_not_include_the_suggestion() {
        let error = Domain::from_str("(define (domain d) (:predicats (p)))").unwrap_err();
        check!(!error.to_string().contains("did you mean"));
    }

    #[test]
    fn a_lone_carriage_return_ends_a_line() {
        let error = Domain::from_str("(define (domain d)\r  (:predicats (p)))").unwrap_err();
        check!((error.line(), error.column()) == (2, 3));
        // `\r\n` counts once.
        let error = Domain::from_str("(define (domain d)\r\n\r  (:predicats (p)))").unwrap_err();
        check!((error.line(), error.column()) == (3, 3));
    }

    #[test]
    fn column_counts_characters() {
        let error = ParseError::new("รค(x", &Error::at(3, 1));
        check!(error.column() == 3);
    }
}