Skip to main content

icedwright_types/input/
grammar.rs

1//! The chord grammar, shared by `str::parse` at run time and the `chord!` macro at compile time.
2//!
3//! A chord is terms joined by `+`, with optional whitespace around each: any number of
4//! modifiers, then exactly one key.
5//!
6//! - Modifiers: `Shift`, `Ctrl` or `Control`, `Alt` or `Option`, `Meta`, `Super`, `Logo` or
7//!   `Command`, and `ControlOrMeta`.
8//! - A named key such as `Enter`, `ArrowLeft` or `F5`, or `Key(Shift)` for a key whose name is
9//!   also a modifier.
10//! - A physical key, `Code(KeyK)`.
11//! - A single letter or digit, such as `K` or `1`, meaning that character.
12//! - A quoted character such as `"é"`, with Rust's escapes (`\"`, `\\`, `\n`, `\u{..}`).
13//! - `Plus` for the `+` key.
14//!
15//! Errors carry a byte range into the input, so a macro can point at the offending token.
16
17use core::fmt::{self, Write as _};
18use core::ops::Range;
19
20use super::{Chord, KeyCode, Keystroke, Modifier, ModifierSet, NamedKey};
21use crate::suggest;
22
23/// Every modifier name the grammar accepts, aliases included.
24pub const MODIFIER_NAMES: &[(&str, Modifier)] = &[
25    ("Shift", Modifier::Shift),
26    ("Ctrl", Modifier::Control),
27    ("Control", Modifier::Control),
28    ("Alt", Modifier::Alt),
29    ("Option", Modifier::Alt),
30    ("Meta", Modifier::Meta),
31    ("Super", Modifier::Meta),
32    ("Logo", Modifier::Meta),
33    ("Command", Modifier::Meta),
34    ("ControlOrMeta", Modifier::ControlOrMeta),
35];
36
37const PLUS: &str = "Plus";
38
39/// The modifier with this name, aliases included.
40#[must_use]
41pub fn modifier_named(name: &str) -> Option<Modifier> {
42    MODIFIER_NAMES
43        .iter()
44        .find(|(alias, _)| *alias == name)
45        .map(|(_, modifier)| *modifier)
46}
47
48/// The named keys that can be written bare, which is every one whose name is not also a
49/// modifier. The rest are written `Key(..)`.
50pub fn bare_key_names() -> impl Iterator<Item = &'static str> {
51    NamedKey::ALL
52        .iter()
53        .map(|key| key.name())
54        .filter(|name| modifier_named(name).is_none())
55}
56
57/// Parses a chord such as `Control+Shift+K`.
58pub fn parse_chord(input: &str) -> Result<Chord, ChordError> {
59    let parts = Lexer::new(input)
60        .chord_terms()?
61        .into_iter()
62        .map(|term| term.resolve(input))
63        .collect::<Result<Vec<_>, _>>()?;
64
65    let Some((last, held)) = parts.split_last() else {
66        return Err(ChordError::new(ChordErrorKind::Empty, 0..input.len()));
67    };
68    let key = last.as_key()?;
69
70    let mut modifiers = ModifierSet::NONE;
71    let mut first_key: Option<&Part> = None;
72    for part in held.iter().chain(core::iter::once(last)) {
73        if let Some(earlier) = first_key {
74            return Err(ChordError::new(
75                ChordErrorKind::TwoKeys {
76                    first: earlier.text.clone(),
77                    second: part.text.clone(),
78                },
79                part.span.clone(),
80            ));
81        }
82        let PartKind::Modifier(modifier) = part.kind else {
83            first_key = Some(part);
84            continue;
85        };
86        if modifiers.has(modifier) {
87            return Err(ChordError::new(
88                ChordErrorKind::RepeatedModifier { modifier },
89                part.span.clone(),
90            ));
91        }
92        modifiers = modifiers.with(modifier);
93    }
94    Ok(Chord::new(modifiers, key))
95}
96
97/// Parses one key with no modifiers, such as `K`, `Enter` or `Key(Shift)`.
98pub fn parse_keystroke(input: &str) -> Result<Keystroke, ChordError> {
99    let mut lexer = Lexer::new(input);
100    lexer.skip_whitespace();
101    if lexer.at_end() {
102        return Err(ChordError::new(ChordErrorKind::Empty, 0..input.len()));
103    }
104    let term = lexer.term(None)?;
105    lexer.skip_whitespace();
106    if let Some(found) = lexer.peek() {
107        return Err(ChordError::new(
108            ChordErrorKind::ExpectedEnd { found },
109            lexer.char_span(),
110        ));
111    }
112    term.resolve(input)?.as_key()
113}
114
115/// Writes the canonical form of a key, which [`parse_keystroke`] reads back.
116pub(crate) fn write_keystroke(f: &mut fmt::Formatter<'_>, key: Keystroke) -> fmt::Result {
117    match key {
118        Keystroke::Named(named) if modifier_named(named.name()).is_some() => {
119            write!(f, "Key({named})")
120        }
121        Keystroke::Named(named) => f.write_str(named.name()),
122        Keystroke::Code(code) => write!(f, "Code({code})"),
123        Keystroke::Character(c @ 'a'..='z') => f.write_char(c.to_ascii_uppercase()),
124        Keystroke::Character(c @ '0'..='9') => f.write_char(c),
125        Keystroke::Character('+') => f.write_str(PLUS),
126        Keystroke::Character(c) => {
127            f.write_char('"')?;
128            match c {
129                '"' => f.write_str("\\\"")?,
130                '\\' => f.write_str("\\\\")?,
131                c if c.is_control() => write!(f, "\\u{{{:x}}}", u32::from(c))?,
132                c => f.write_char(c)?,
133            }
134            f.write_char('"')
135        }
136    }
137}
138
139/// A chord or keystroke that does not parse, with the byte range of the offending input.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ChordError {
142    kind: ChordErrorKind,
143    span: Range<usize>,
144}
145
146impl ChordError {
147    fn new(kind: ChordErrorKind, span: Range<usize>) -> Self {
148        Self { kind, span }
149    }
150
151    /// What went wrong.
152    #[must_use]
153    pub fn kind(&self) -> &ChordErrorKind {
154        &self.kind
155    }
156
157    /// The byte range of the input at fault. Empty only for an empty input.
158    #[must_use]
159    pub fn span(&self) -> Range<usize> {
160        self.span.clone()
161    }
162}
163
164impl fmt::Display for ChordError {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        fmt::Display::fmt(&self.kind, f)
167    }
168}
169
170impl std::error::Error for ChordError {}
171
172/// The ways a chord can fail to parse.
173#[derive(Debug, Clone, PartialEq, Eq)]
174#[non_exhaustive]
175pub enum ChordErrorKind {
176    /// Nothing but whitespace.
177    Empty,
178    /// A `+` with nothing on one side.
179    MissingTerm,
180    /// Two terms not joined by `+`.
181    ExpectedPlus {
182        /// The character found instead.
183        found: char,
184    },
185    /// Something after a single keystroke.
186    ExpectedEnd {
187        /// The character found.
188        found: char,
189    },
190    /// A character that cannot start a term.
191    UnexpectedCharacter {
192        /// The character.
193        found: char,
194    },
195    /// A quoted character with no closing quote.
196    UnterminatedQuote,
197    /// Quotes holding no character or more than one.
198    QuotedLength {
199        /// How many characters the quotes held.
200        count: usize,
201    },
202    /// A backslash escape that is not recognised.
203    BadEscape {
204        /// The escape as written.
205        escape: String,
206    },
207    /// `Code(` or `Key(` without a name and a closing parenthesis.
208    MalformedForm {
209        /// `Code` or `Key`.
210        head: String,
211    },
212    /// A name followed by parentheses that is neither `Code` nor `Key`.
213    UnknownForm {
214        /// The name before the parenthesis.
215        name: String,
216    },
217    /// A bare name that is no modifier or key.
218    UnknownName {
219        /// The name.
220        name: String,
221        /// The nearest names, nearest first.
222        suggestions: Vec<&'static str>,
223    },
224    /// A name inside `Code(..)` that is no key code.
225    UnknownCode {
226        /// The name.
227        name: String,
228        /// The nearest codes, nearest first.
229        suggestions: Vec<&'static str>,
230    },
231    /// A name inside `Key(..)` that is no named key.
232    UnknownNamedKey {
233        /// The name.
234        name: String,
235        /// The nearest named keys, nearest first.
236        suggestions: Vec<&'static str>,
237    },
238    /// A modifier where the key should be.
239    ModifierLast {
240        /// The modifier as written.
241        name: String,
242        /// The modifier, whose own key can be written `Key(..)`.
243        modifier: Modifier,
244    },
245    /// A key followed by another term.
246    TwoKeys {
247        /// The first key as written.
248        first: String,
249        /// The term after it as written.
250        second: String,
251    },
252    /// A modifier given twice, under any of its names.
253    RepeatedModifier {
254        /// The modifier.
255        modifier: Modifier,
256    },
257}
258
259impl fmt::Display for ChordErrorKind {
260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261        match self {
262            ChordErrorKind::Empty => {
263                f.write_str("empty chord; expected modifiers and a key, such as `Control+S`")
264            }
265            ChordErrorKind::MissingTerm => f.write_str(
266                "expected a modifier or key on both sides of `+`; write `Plus` for the + key",
267            ),
268            ChordErrorKind::ExpectedPlus { found } => {
269                write!(
270                    f,
271                    "expected `+` between the parts of a chord, found `{found}`"
272                )
273            }
274            ChordErrorKind::ExpectedEnd { found } => {
275                write!(f, "a keystroke is a single key, but `{found}` follows it")
276            }
277            ChordErrorKind::UnexpectedCharacter { found } => write!(
278                f,
279                "unexpected `{found}`; write a character key in quotes, such as `\"{}\"`",
280                found.escape_default()
281            ),
282            ChordErrorKind::UnterminatedQuote => {
283                f.write_str("quoted character has no closing `\"`")
284            }
285            ChordErrorKind::QuotedLength { count } => write!(
286                f,
287                "quotes must hold exactly one character, but these hold {count}"
288            ),
289            ChordErrorKind::BadEscape { escape } => {
290                write!(f, "unknown escape `{escape}` in a quoted character")
291            }
292            ChordErrorKind::MalformedForm { head } => {
293                write!(f, "expected a name and `)` in `{head}(..)`")
294            }
295            ChordErrorKind::UnknownForm { name } => {
296                write!(f, "unknown `{name}(..)`; expected `Code(..)` or `Key(..)`")
297            }
298            ChordErrorKind::UnknownName { name, suggestions } => write!(
299                f,
300                "unknown key or modifier `{name}`{}",
301                suggest::did_you_mean(suggestions)
302            ),
303            ChordErrorKind::UnknownCode { name, suggestions } => write!(
304                f,
305                "unknown key code `{name}`{}",
306                suggest::did_you_mean(suggestions)
307            ),
308            ChordErrorKind::UnknownNamedKey { name, suggestions } => write!(
309                f,
310                "unknown named key `{name}`{}",
311                suggest::did_you_mean(suggestions)
312            ),
313            ChordErrorKind::ModifierLast { name, modifier } => {
314                write!(f, "`{name}` is a modifier, and a chord must end with a key")?;
315                match modifier.key() {
316                    Some(key) => write!(f, "; write `Key({key})` for the {key} key itself"),
317                    None => Ok(()),
318                }
319            }
320            ChordErrorKind::TwoKeys { first, second } => write!(
321                f,
322                "a chord has one key, after its modifiers, but `{second}` follows the key `{first}`"
323            ),
324            ChordErrorKind::RepeatedModifier { modifier } => {
325                write!(f, "the {modifier} modifier is given twice")
326            }
327        }
328    }
329}
330
331#[derive(Debug)]
332enum Term {
333    Ident {
334        span: Range<usize>,
335    },
336    Form {
337        head: Range<usize>,
338        inner: Range<usize>,
339        span: Range<usize>,
340    },
341    Quoted {
342        character: char,
343        span: Range<usize>,
344    },
345}
346
347#[derive(Debug)]
348enum PartKind {
349    Modifier(Modifier),
350    Key(Keystroke),
351}
352
353#[derive(Debug)]
354struct Part {
355    kind: PartKind,
356    text: String,
357    span: Range<usize>,
358}
359
360impl Part {
361    fn as_key(&self) -> Result<Keystroke, ChordError> {
362        match self.kind {
363            PartKind::Key(key) => Ok(key),
364            PartKind::Modifier(modifier) => Err(ChordError::new(
365                ChordErrorKind::ModifierLast {
366                    name: self.text.clone(),
367                    modifier,
368                },
369                self.span.clone(),
370            )),
371        }
372    }
373}
374
375impl Term {
376    fn resolve(self, input: &str) -> Result<Part, ChordError> {
377        let text = |range: &Range<usize>| input.get(range.clone()).unwrap_or_default().to_owned();
378        match self {
379            Term::Quoted { character, span } => Ok(Part {
380                kind: PartKind::Key(Keystroke::Character(character)),
381                text: text(&span),
382                span,
383            }),
384            Term::Ident { span } => {
385                let name = text(&span);
386                let kind = resolve_bare(&name).ok_or_else(|| {
387                    ChordError::new(
388                        ChordErrorKind::UnknownName {
389                            suggestions: suggest::nearest(&name, bare_names()),
390                            name: name.clone(),
391                        },
392                        span.clone(),
393                    )
394                })?;
395                Ok(Part {
396                    kind,
397                    text: name,
398                    span,
399                })
400            }
401            Term::Form { head, inner, span } => {
402                let head_name = text(&head);
403                let inner_name = text(&inner);
404                let key = match head_name.as_str() {
405                    "Code" => KeyCode::from_name(&inner_name)
406                        .map(Keystroke::Code)
407                        .ok_or_else(|| {
408                            ChordError::new(
409                                ChordErrorKind::UnknownCode {
410                                    suggestions: suggest::nearest(
411                                        &inner_name,
412                                        KeyCode::ALL.iter().map(|code| code.name()),
413                                    ),
414                                    name: inner_name.clone(),
415                                },
416                                inner.clone(),
417                            )
418                        })?,
419                    "Key" => NamedKey::from_name(&inner_name)
420                        .map(Keystroke::Named)
421                        .ok_or_else(|| {
422                            ChordError::new(
423                                ChordErrorKind::UnknownNamedKey {
424                                    suggestions: suggest::nearest(
425                                        &inner_name,
426                                        NamedKey::ALL.iter().map(|key| key.name()),
427                                    ),
428                                    name: inner_name.clone(),
429                                },
430                                inner.clone(),
431                            )
432                        })?,
433                    _ => {
434                        return Err(ChordError::new(
435                            ChordErrorKind::UnknownForm { name: head_name },
436                            head,
437                        ));
438                    }
439                };
440                Ok(Part {
441                    kind: PartKind::Key(key),
442                    text: text(&span),
443                    span,
444                })
445            }
446        }
447    }
448}
449
450fn resolve_bare(name: &str) -> Option<PartKind> {
451    if let Some(modifier) = modifier_named(name) {
452        return Some(PartKind::Modifier(modifier));
453    }
454    if name == PLUS {
455        return Some(PartKind::Key(Keystroke::Character('+')));
456    }
457    let mut chars = name.chars();
458    if let (Some(only), None) = (chars.next(), chars.next())
459        && only.is_ascii_alphanumeric()
460    {
461        return Some(PartKind::Key(Keystroke::Character(
462            only.to_ascii_lowercase(),
463        )));
464    }
465    NamedKey::from_name(name).map(|key| PartKind::Key(Keystroke::Named(key)))
466}
467
468fn bare_names() -> impl Iterator<Item = &'static str> {
469    MODIFIER_NAMES
470        .iter()
471        .map(|(name, _)| *name)
472        .chain(core::iter::once(PLUS))
473        .chain(bare_key_names())
474}
475
476struct Lexer<'a> {
477    input: &'a str,
478    pos: usize,
479}
480
481impl<'a> Lexer<'a> {
482    fn new(input: &'a str) -> Self {
483        Self { input, pos: 0 }
484    }
485
486    fn peek(&self) -> Option<char> {
487        self.input.get(self.pos..)?.chars().next()
488    }
489
490    fn bump(&mut self) -> Option<char> {
491        let c = self.peek()?;
492        self.pos += c.len_utf8();
493        Some(c)
494    }
495
496    fn at_end(&self) -> bool {
497        self.pos >= self.input.len()
498    }
499
500    fn char_span(&self) -> Range<usize> {
501        let width = self.peek().map_or(0, char::len_utf8);
502        self.pos..self.pos + width
503    }
504
505    fn skip_whitespace(&mut self) {
506        while self.peek().is_some_and(char::is_whitespace) {
507            self.bump();
508        }
509    }
510
511    fn chord_terms(mut self) -> Result<Vec<Term>, ChordError> {
512        self.skip_whitespace();
513        if self.at_end() {
514            return Err(ChordError::new(ChordErrorKind::Empty, 0..self.input.len()));
515        }
516        let mut terms = Vec::new();
517        let mut last_plus = None;
518        loop {
519            self.skip_whitespace();
520            terms.push(self.term(last_plus.take())?);
521            self.skip_whitespace();
522            match self.peek() {
523                None => return Ok(terms),
524                Some('+') => {
525                    last_plus = Some(self.char_span());
526                    self.bump();
527                }
528                Some(found) => {
529                    return Err(ChordError::new(
530                        ChordErrorKind::ExpectedPlus { found },
531                        self.char_span(),
532                    ));
533                }
534            }
535        }
536    }
537
538    /// One term. `after` is the `+` before it, which an error at the end of input points at.
539    fn term(&mut self, after: Option<Range<usize>>) -> Result<Term, ChordError> {
540        match self.peek() {
541            None => Err(ChordError::new(
542                ChordErrorKind::MissingTerm,
543                after.unwrap_or(self.pos..self.pos),
544            )),
545            Some('+') => Err(ChordError::new(
546                ChordErrorKind::MissingTerm,
547                self.char_span(),
548            )),
549            Some('"') => self.quoted(),
550            Some(c) if is_ident(c) => self.ident_or_form(),
551            Some(found) => Err(ChordError::new(
552                ChordErrorKind::UnexpectedCharacter { found },
553                self.char_span(),
554            )),
555        }
556    }
557
558    fn ident(&mut self) -> Range<usize> {
559        let start = self.pos;
560        while self.peek().is_some_and(is_ident) {
561            self.bump();
562        }
563        start..self.pos
564    }
565
566    fn ident_or_form(&mut self) -> Result<Term, ChordError> {
567        let head = self.ident();
568        let before_paren = self.pos;
569        self.skip_whitespace();
570        if self.peek() != Some('(') {
571            self.pos = before_paren;
572            return Ok(Term::Ident { span: head });
573        }
574        self.bump();
575        let malformed = |lexer: &Self| {
576            ChordError::new(
577                ChordErrorKind::MalformedForm {
578                    head: lexer.input.get(head.clone()).unwrap_or_default().to_owned(),
579                },
580                head.start..lexer.char_span().end.max(lexer.pos),
581            )
582        };
583        self.skip_whitespace();
584        if !self.peek().is_some_and(is_ident) {
585            return Err(malformed(self));
586        }
587        let inner = self.ident();
588        self.skip_whitespace();
589        if self.peek() != Some(')') {
590            return Err(malformed(self));
591        }
592        self.bump();
593        Ok(Term::Form {
594            span: head.start..self.pos,
595            head,
596            inner,
597        })
598    }
599
600    fn quoted(&mut self) -> Result<Term, ChordError> {
601        let start = self.pos;
602        self.bump();
603        let mut characters = Vec::new();
604        loop {
605            let at = self.pos;
606            let Some(c) = self.bump() else {
607                return Err(ChordError::new(
608                    ChordErrorKind::UnterminatedQuote,
609                    start..self.input.len(),
610                ));
611            };
612            match c {
613                '"' => break,
614                '\\' => characters.push(self.escape(at)?),
615                other => characters.push(other),
616            }
617        }
618        let span = start..self.pos;
619        match characters.as_slice() {
620            [character] => Ok(Term::Quoted {
621                character: *character,
622                span,
623            }),
624            _ => Err(ChordError::new(
625                ChordErrorKind::QuotedLength {
626                    count: characters.len(),
627                },
628                span,
629            )),
630        }
631    }
632
633    /// The character for an escape whose backslash is at `at`.
634    fn escape(&mut self, at: usize) -> Result<char, ChordError> {
635        let simple = match self.bump() {
636            Some('\\') => Some('\\'),
637            Some('"') => Some('"'),
638            Some('\'') => Some('\''),
639            Some('n') => Some('\n'),
640            Some('r') => Some('\r'),
641            Some('t') => Some('\t'),
642            Some('0') => Some('\0'),
643            Some('u') => None,
644            _ => return Err(self.bad_escape(at)),
645        };
646        if let Some(c) = simple {
647            return Ok(c);
648        }
649        if self.bump() != Some('{') {
650            return Err(self.bad_escape(at));
651        }
652        let digits_start = self.pos;
653        while self.peek().is_some_and(|c| c.is_ascii_hexdigit()) {
654            self.bump();
655        }
656        let digits = self.input.get(digits_start..self.pos).unwrap_or_default();
657        if digits.is_empty() || digits.len() > 6 || self.bump() != Some('}') {
658            return Err(self.bad_escape(at));
659        }
660        u32::from_str_radix(digits, 16)
661            .ok()
662            .and_then(char::from_u32)
663            .ok_or_else(|| self.bad_escape(at))
664    }
665
666    fn bad_escape(&self, at: usize) -> ChordError {
667        ChordError::new(
668            ChordErrorKind::BadEscape {
669                escape: self.input.get(at..self.pos).unwrap_or_default().to_owned(),
670            },
671            at..self.pos,
672        )
673    }
674}
675
676fn is_ident(c: char) -> bool {
677    c.is_ascii_alphanumeric() || c == '_'
678}
679
680#[cfg(test)]
681mod tests {
682    use super::*;
683
684    type TestResult = Result<(), ChordError>;
685
686    fn chord(modifiers: ModifierSet, key: impl Into<Keystroke>) -> Chord {
687        Chord::new(modifiers, key.into())
688    }
689
690    fn error(input: &str) -> Option<ChordError> {
691        parse_chord(input).err()
692    }
693
694    fn kind(input: &str) -> Option<ChordErrorKind> {
695        error(input).map(|e| e.kind().clone())
696    }
697
698    fn span(input: &str) -> Option<Range<usize>> {
699        error(input).map(|e| e.span())
700    }
701
702    #[test]
703    fn every_modifier_alias() -> TestResult {
704        for (name, modifier) in MODIFIER_NAMES {
705            let parsed = parse_chord(&format!("{name}+K"))?;
706            assert_eq!(parsed, chord(ModifierSet::only(*modifier), 'k'), "{name}");
707        }
708        assert_eq!(parse_chord("Ctrl+K")?, parse_chord("Control+K")?);
709        assert_eq!(parse_chord("Option+K")?, parse_chord("Alt+K")?);
710        for alias in ["Super", "Logo", "Command"] {
711            assert_eq!(parse_chord(&format!("{alias}+K"))?, parse_chord("Meta+K")?);
712        }
713        Ok(())
714    }
715
716    #[test]
717    fn control_or_meta_stays_symbolic() -> TestResult {
718        let parsed = parse_chord("ControlOrMeta+A")?;
719        assert_eq!(parsed, chord(ModifierSet::CONTROL_OR_META, 'a'));
720        assert_eq!(parsed.to_string(), "ControlOrMeta+A");
721        assert_ne!(parsed, parse_chord("Control+A")?);
722        assert_eq!(
723            parse_chord("ControlOrMeta+Control+A")?.modifiers(),
724            ModifierSet::CONTROL_OR_META | ModifierSet::CONTROL
725        );
726        Ok(())
727    }
728
729    #[test]
730    fn plus_is_the_plus_key() -> TestResult {
731        assert_eq!(parse_chord("Ctrl+Plus")?, chord(ModifierSet::CONTROL, '+'));
732        assert_eq!(parse_chord("Ctrl+\"+\"")?, chord(ModifierSet::CONTROL, '+'));
733        assert_eq!(parse_chord("Ctrl+Plus")?.to_string(), "Control+Plus");
734        Ok(())
735    }
736
737    #[test]
738    fn named_keys() -> TestResult {
739        assert_eq!(
740            parse_chord("Enter")?,
741            chord(ModifierSet::NONE, NamedKey::Enter)
742        );
743        assert_eq!(
744            parse_chord("ArrowLeft")?,
745            chord(ModifierSet::NONE, NamedKey::ArrowLeft)
746        );
747        assert_eq!(
748            parse_chord("Shift+F5")?,
749            chord(ModifierSet::SHIFT, NamedKey::F5)
750        );
751        assert_eq!(
752            parse_chord("Escape")?,
753            chord(ModifierSet::NONE, NamedKey::Escape)
754        );
755        assert_eq!(
756            parse_chord("Key11")?,
757            chord(ModifierSet::NONE, NamedKey::Key11)
758        );
759        assert_eq!(
760            parse_chord("Hyper")?,
761            chord(ModifierSet::NONE, NamedKey::Hyper)
762        );
763        Ok(())
764    }
765
766    #[test]
767    fn modifier_keys_themselves_use_key_form() -> TestResult {
768        assert_eq!(
769            parse_chord("Key(Shift)")?,
770            chord(ModifierSet::NONE, NamedKey::Shift)
771        );
772        assert_eq!(
773            parse_chord("Ctrl+Key(Shift)")?.to_string(),
774            "Control+Key(Shift)"
775        );
776        assert_eq!(parse_chord("Key(Enter)")?, parse_chord("Enter")?);
777        assert_eq!(parse_chord("Key(Enter)")?.to_string(), "Enter");
778        Ok(())
779    }
780
781    #[test]
782    fn codes() -> TestResult {
783        assert_eq!(
784            parse_chord("Code(KeyK)")?,
785            chord(ModifierSet::NONE, KeyCode::KeyK)
786        );
787        assert_eq!(
788            parse_chord("Shift + Code ( Digit1 )")?,
789            chord(ModifierSet::SHIFT, KeyCode::Digit1)
790        );
791        assert_eq!(parse_chord("Code(Digit1)")?.to_string(), "Code(Digit1)");
792        Ok(())
793    }
794
795    #[test]
796    fn letters_and_digits() -> TestResult {
797        assert_eq!(parse_chord("K")?, chord(ModifierSet::NONE, 'k'));
798        assert_eq!(parse_chord("k")?, chord(ModifierSet::NONE, 'k'));
799        assert_eq!(parse_chord("1")?, chord(ModifierSet::NONE, '1'));
800        assert_eq!(parse_chord("k")?.to_string(), "K");
801        Ok(())
802    }
803
804    #[test]
805    fn quoted_characters_and_escapes() -> TestResult {
806        assert_eq!(parse_chord("Shift+\"é\"")?, chord(ModifierSet::SHIFT, 'é'));
807        assert_eq!(parse_chord("\"K\"")?, chord(ModifierSet::NONE, 'K'));
808        assert_eq!(parse_chord("\" \"")?, chord(ModifierSet::NONE, ' '));
809        for (written, expected) in [
810            (r#""\"""#, '"'),
811            (r#""\\""#, '\\'),
812            (r#""\'""#, '\''),
813            (r#""\n""#, '\n'),
814            (r#""\r""#, '\r'),
815            (r#""\t""#, '\t'),
816            (r#""\0""#, '\0'),
817            (r#""\u{e9}""#, 'é'),
818            (r#""\u{1F600}""#, '\u{1F600}'),
819        ] {
820            assert_eq!(
821                parse_chord(written)?,
822                chord(ModifierSet::NONE, expected),
823                "{written}"
824            );
825        }
826        assert_eq!(parse_chord("\"K\"")?.to_string(), "\"K\"");
827        assert_eq!(parse_chord(r#""\"""#)?.to_string(), r#""\"""#);
828        assert_eq!(parse_chord(r#""\n""#)?.to_string(), r#""\u{a}""#);
829        Ok(())
830    }
831
832    #[test]
833    fn whitespace_is_allowed_around_terms() -> TestResult {
834        assert_eq!(
835            parse_chord("  Ctrl +  Shift+K ")?,
836            chord(ModifierSet::CONTROL | ModifierSet::SHIFT, 'k')
837        );
838        assert_eq!(
839            parse_chord("Control+Shift+K")?.to_string(),
840            "Control+Shift+K"
841        );
842        Ok(())
843    }
844
845    #[test]
846    fn display_orders_modifiers_canonically() -> TestResult {
847        assert_eq!(parse_chord("Shift+Ctrl+K")?.to_string(), "Control+Shift+K");
848        assert_eq!(
849            parse_chord("Meta+Shift+Alt+Ctrl+ControlOrMeta+K")?.to_string(),
850            "ControlOrMeta+Control+Alt+Shift+Meta+K"
851        );
852        Ok(())
853    }
854
855    #[test]
856    fn empty_input() {
857        assert_eq!(kind(""), Some(ChordErrorKind::Empty));
858        assert_eq!(kind("   "), Some(ChordErrorKind::Empty));
859        assert_eq!(span("   "), Some(0..3));
860        assert_eq!(
861            error("").map(|e| e.to_string()).as_deref(),
862            Some("empty chord; expected modifiers and a key, such as `Control+S`")
863        );
864    }
865
866    #[test]
867    fn empty_and_doubled_plus() {
868        assert_eq!(kind("Ctrl++K"), Some(ChordErrorKind::MissingTerm));
869        assert_eq!(span("Ctrl++K"), Some(5..6));
870        assert_eq!(kind("+K"), Some(ChordErrorKind::MissingTerm));
871        assert_eq!(span("+K"), Some(0..1));
872        assert_eq!(kind("Ctrl+"), Some(ChordErrorKind::MissingTerm));
873        assert_eq!(span("Ctrl+"), Some(4..5));
874        assert_eq!(span("Ctrl +  "), Some(5..6));
875        assert!(error("Ctrl++K").is_some_and(|e| e.to_string().contains("`Plus`")));
876    }
877
878    #[test]
879    fn modifier_last() {
880        assert_eq!(
881            kind("Ctrl+Shift"),
882            Some(ChordErrorKind::ModifierLast {
883                name: "Shift".into(),
884                modifier: Modifier::Shift
885            })
886        );
887        assert_eq!(span("Ctrl+Shift"), Some(5..10));
888        assert_eq!(
889            error("Ctrl").map(|e| e.to_string()).as_deref(),
890            Some(
891                "`Ctrl` is a modifier, and a chord must end with a key; write `Key(Control)` for the Control key itself"
892            )
893        );
894        assert_eq!(
895            error("ControlOrMeta").map(|e| e.to_string()).as_deref(),
896            Some("`ControlOrMeta` is a modifier, and a chord must end with a key")
897        );
898    }
899
900    #[test]
901    fn two_keys() {
902        assert_eq!(
903            kind("Ctrl+K+J"),
904            Some(ChordErrorKind::TwoKeys {
905                first: "K".into(),
906                second: "J".into()
907            })
908        );
909        assert_eq!(span("Ctrl+K+J"), Some(7..8));
910        assert_eq!(
911            error("A+Shift+B").map(|e| e.to_string()).as_deref(),
912            Some("a chord has one key, after its modifiers, but `Shift` follows the key `A`")
913        );
914    }
915
916    #[test]
917    fn repeated_modifiers() {
918        assert_eq!(
919            kind("Ctrl+Control+K"),
920            Some(ChordErrorKind::RepeatedModifier {
921                modifier: Modifier::Control
922            })
923        );
924        assert_eq!(span("Ctrl+Control+K"), Some(5..12));
925        assert_eq!(
926            error("Shift+Shift+K").map(|e| e.to_string()).as_deref(),
927            Some("the Shift modifier is given twice")
928        );
929    }
930
931    #[test]
932    fn misspelt_names_suggest_the_nearest() {
933        assert_eq!(
934            kind("Ctrl+Entr"),
935            Some(ChordErrorKind::UnknownName {
936                name: "Entr".into(),
937                suggestions: vec!["Enter"]
938            })
939        );
940        assert_eq!(span("Ctrl+Entr"), Some(5..9));
941        assert_eq!(
942            error("Shfit+K").map(|e| e.to_string()).as_deref(),
943            Some("unknown key or modifier `Shfit`; did you mean `Shift`?")
944        );
945        assert_eq!(
946            error("enter").map(|e| e.to_string()).as_deref(),
947            Some("unknown key or modifier `enter`; did you mean `Enter`?")
948        );
949        assert_eq!(
950            error("Qqqqqqqq").map(|e| e.to_string()).as_deref(),
951            Some("unknown key or modifier `Qqqqqqqq`")
952        );
953        assert_eq!(
954            kind("Code(KeyKK)"),
955            Some(ChordErrorKind::UnknownCode {
956                name: "KeyKK".into(),
957                suggestions: vec!["KeyK"]
958            })
959        );
960        assert_eq!(span("Code(KeyKK)"), Some(5..10));
961        assert_eq!(
962            error("Key(Shiftt)").map(|e| e.to_string()).as_deref(),
963            Some("unknown named key `Shiftt`; did you mean `Shift`?")
964        );
965    }
966
967    #[test]
968    fn malformed_forms() {
969        assert_eq!(
970            kind("Code(KeyK"),
971            Some(ChordErrorKind::MalformedForm {
972                head: "Code".into()
973            })
974        );
975        assert_eq!(
976            kind("Code()"),
977            Some(ChordErrorKind::MalformedForm {
978                head: "Code".into()
979            })
980        );
981        assert_eq!(
982            kind("Code(KeyK KeyJ)"),
983            Some(ChordErrorKind::MalformedForm {
984                head: "Code".into()
985            })
986        );
987        assert_eq!(
988            kind("Foo(KeyK)"),
989            Some(ChordErrorKind::UnknownForm { name: "Foo".into() })
990        );
991        assert_eq!(span("Foo(KeyK)"), Some(0..3));
992    }
993
994    #[test]
995    fn stray_characters() {
996        assert_eq!(
997            kind("Ctrl-K"),
998            Some(ChordErrorKind::ExpectedPlus { found: '-' })
999        );
1000        assert_eq!(span("Ctrl-K"), Some(4..5));
1001        assert_eq!(
1002            kind("Ctrl Shift"),
1003            Some(ChordErrorKind::ExpectedPlus { found: 'S' })
1004        );
1005        assert_eq!(
1006            kind("Ctrl+,"),
1007            Some(ChordErrorKind::UnexpectedCharacter { found: ',' })
1008        );
1009        assert_eq!(
1010            error("Ctrl+,").map(|e| e.to_string()).as_deref(),
1011            Some("unexpected `,`; write a character key in quotes, such as `\",\"`")
1012        );
1013        assert_eq!(span("Ctrl+é"), Some(5..7));
1014    }
1015
1016    #[test]
1017    fn bad_quotes() {
1018        assert_eq!(
1019            kind("\"ab\""),
1020            Some(ChordErrorKind::QuotedLength { count: 2 })
1021        );
1022        assert_eq!(
1023            kind("\"\""),
1024            Some(ChordErrorKind::QuotedLength { count: 0 })
1025        );
1026        assert_eq!(kind("Ctrl+\"a"), Some(ChordErrorKind::UnterminatedQuote));
1027        assert_eq!(span("Ctrl+\"a"), Some(5..7));
1028        assert_eq!(
1029            kind("\"\\"),
1030            Some(ChordErrorKind::BadEscape {
1031                escape: "\\".into()
1032            })
1033        );
1034        for bad in [
1035            r#""\q""#,
1036            r#""\u{}""#,
1037            r#""\u{d800}""#,
1038            r#""\u{1234567}""#,
1039            r#""\u12""#,
1040        ] {
1041            assert!(
1042                matches!(kind(bad), Some(ChordErrorKind::BadEscape { .. })),
1043                "{bad}"
1044            );
1045        }
1046        assert_eq!(span(r#"A+"\q""#), Some(3..5));
1047    }
1048
1049    #[test]
1050    fn keystrokes() -> TestResult {
1051        assert_eq!(parse_keystroke("K")?, Keystroke::Character('k'));
1052        assert_eq!(
1053            parse_keystroke(" Enter ")?,
1054            Keystroke::Named(NamedKey::Enter)
1055        );
1056        assert_eq!(
1057            parse_keystroke("Key(Shift)")?,
1058            Keystroke::Named(NamedKey::Shift)
1059        );
1060        assert_eq!(
1061            "Code(KeyA)".parse::<Keystroke>()?,
1062            Keystroke::Code(KeyCode::KeyA)
1063        );
1064        assert_eq!(Keystroke::Named(NamedKey::Shift).to_string(), "Key(Shift)");
1065        assert_eq!(
1066            parse_keystroke("Ctrl+K").err().map(|e| e.kind().clone()),
1067            Some(ChordErrorKind::ExpectedEnd { found: '+' })
1068        );
1069        assert_eq!(
1070            parse_keystroke("Shift").err().map(|e| e.kind().clone()),
1071            Some(ChordErrorKind::ModifierLast {
1072                name: "Shift".into(),
1073                modifier: Modifier::Shift
1074            })
1075        );
1076        assert_eq!(
1077            parse_keystroke("").err().map(|e| e.kind().clone()),
1078            Some(ChordErrorKind::Empty)
1079        );
1080        Ok(())
1081    }
1082
1083    #[test]
1084    fn from_str_gives_the_same_message() {
1085        let via_from_str = "Ctrl+Entr".parse::<Chord>().err().map(|e| e.to_string());
1086        let via_parse = error("Ctrl+Entr").map(|e| e.to_string());
1087        assert_eq!(via_from_str, via_parse);
1088    }
1089
1090    #[test]
1091    fn bare_key_names_exclude_modifiers() {
1092        let names: Vec<&str> = bare_key_names().collect();
1093        for modifier_name in ["Shift", "Control", "Alt", "Meta", "Super"] {
1094            assert!(!names.contains(&modifier_name));
1095        }
1096        assert!(names.contains(&"Enter"));
1097        assert_eq!(names.len(), NamedKey::ALL.len() - 5);
1098    }
1099
1100    #[test]
1101    fn every_error_points_inside_the_input() {
1102        for input in [
1103            "",
1104            " ",
1105            "+",
1106            "Ctrl+",
1107            "Ctrl++K",
1108            "K+J",
1109            "Ctrl",
1110            "Entr",
1111            "Code(X)",
1112            "Key(X)",
1113            "Foo(X)",
1114            "Code(",
1115            "\"",
1116            "\"ab\"",
1117            "\"\\q\"",
1118            "Ctrl-K",
1119            ",",
1120            "Shift+Shift+K",
1121            "é",
1122        ] {
1123            let Some(e) = error(input) else {
1124                continue;
1125            };
1126            assert!(e.span().end <= input.len(), "{input:?} {:?}", e.span());
1127            assert!(e.span().start <= e.span().end, "{input:?}");
1128            assert!(
1129                input.get(e.span()).is_some(),
1130                "{input:?} splits a character"
1131            );
1132            assert!(input.trim().is_empty() || !e.span().is_empty(), "{input:?}");
1133        }
1134    }
1135
1136    mod properties {
1137        use super::*;
1138        use proptest::prelude::*;
1139        use proptest::sample::{select, subsequence};
1140        use proptest::test_runner::RngSeed;
1141
1142        /// A fixed seed from the test name, as `icedwright_explore::seeded` gives, which this
1143        /// crate cannot depend on: FNV-1a of the name.
1144        fn seeded(name: &str) -> ProptestConfig {
1145            let seed = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
1146                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
1147            });
1148            ProptestConfig {
1149                rng_seed: RngSeed::Fixed(seed),
1150                cases: 1024,
1151                ..ProptestConfig::default()
1152            }
1153        }
1154
1155        fn keystroke() -> impl Strategy<Value = Keystroke> {
1156            prop_oneof![
1157                select(NamedKey::ALL).prop_map(Keystroke::Named),
1158                select(KeyCode::ALL).prop_map(Keystroke::Code),
1159                any::<char>().prop_map(Keystroke::Character),
1160                select(&['a', 'z', 'A', '0', '+', '"', '\\', ' ', '\n'][..])
1161                    .prop_map(Keystroke::Character),
1162            ]
1163        }
1164
1165        fn chord_strategy() -> impl Strategy<Value = Chord> {
1166            (
1167                subsequence(Modifier::ALL, 0..=Modifier::ALL.len()),
1168                keystroke(),
1169            )
1170                .prop_map(|(modifiers, key)| Chord::new(modifiers.into_iter().collect(), key))
1171        }
1172
1173        proptest! {
1174            #![proptest_config(seeded("input::grammar::properties::chords_round_trip"))]
1175            #[test]
1176            fn chords_round_trip(chord in chord_strategy()) {
1177                let printed = chord.to_string();
1178                prop_assert_eq!(parse_chord(&printed), Ok(chord));
1179                prop_assert_eq!(parse_keystroke(&chord.key().to_string()), Ok(chord.key()));
1180            }
1181        }
1182
1183        proptest! {
1184            #![proptest_config(seeded("input::grammar::properties::errors_point_inside_the_input"))]
1185            #[test]
1186            fn errors_point_inside_the_input(input in "\\PC{0,12}|[A-Za-z+ \"()\\\\]{0,16}") {
1187                if let Err(e) = parse_chord(&input) {
1188                    prop_assert!(input.get(e.span()).is_some());
1189                    prop_assert!(!e.to_string().is_empty());
1190                }
1191                if let Ok(chord) = parse_chord(&input) {
1192                    prop_assert_eq!(parse_chord(&chord.to_string()), Ok(chord));
1193                }
1194            }
1195        }
1196    }
1197
1198    /// Every valid chord in the corpus prints and parses back to an equal chord.
1199    #[test]
1200    fn corpus_round_trips() -> TestResult {
1201        for input in [
1202            "Control+Shift+K",
1203            "Ctrl + Shift + K",
1204            "ControlOrMeta+A",
1205            "Shift+\"é\"",
1206            "Ctrl+Plus",
1207            "Enter",
1208            "F5",
1209            "Code(KeyK)",
1210            "Alt+Code(Digit1)",
1211            "1",
1212            "Key(Meta)",
1213            "\"\\\\\"",
1214            "\"\\\"\"",
1215            "\"\\u{7f}\"",
1216            "Meta+Option+Escape",
1217        ] {
1218            let parsed = parse_chord(input)?;
1219            assert_eq!(parse_chord(&parsed.to_string())?, parsed, "{input}");
1220        }
1221        Ok(())
1222    }
1223}