sapi_lite/stt/grammar/rule/
mod.rs1use std::borrow::Cow;
2use std::ops::{RangeInclusive, RangeToInclusive};
3
4use crate::stt::SemanticValue;
5
6mod arena;
7
8pub use arena::RuleArena;
9
10#[derive(Debug)]
12pub enum Rule<'a> {
13 Text(Cow<'a, str>),
15 Choice(Cow<'a, [&'a Rule<'a>]>),
17 Sequence(Cow<'a, [&'a Rule<'a>]>),
19 Repeat(RepeatRange, &'a Rule<'a>),
21 Semantic(SemanticValue<Cow<'a, str>>, &'a Rule<'a>),
23}
24
25impl<'a> Rule<'a> {
26 pub fn text<T: Into<Cow<'a, str>>>(text: T) -> Self {
28 Self::Text(text.into())
29 }
30
31 pub fn choice<L: Into<Cow<'a, [&'a Rule<'a>]>>>(options: L) -> Self {
33 Self::Choice(options.into())
34 }
35
36 pub fn sequence<L: Into<Cow<'a, [&'a Rule<'a>]>>>(parts: L) -> Self {
38 Self::Sequence(parts.into())
39 }
40
41 pub fn repeat<R: Into<RepeatRange>>(times: R, target: &'a Rule<'a>) -> Self {
43 Self::Repeat(times.into(), target)
44 }
45
46 pub fn semantic<V: Into<SemanticValue<Cow<'a, str>>>>(value: V, target: &'a Rule<'a>) -> Self {
49 Self::Semantic(value.into(), target)
50 }
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55pub struct RepeatRange {
56 pub min: usize,
58 pub max: usize,
60}
61
62impl From<usize> for RepeatRange {
63 fn from(source: usize) -> Self {
64 Self {
65 min: source,
66 max: source,
67 }
68 }
69}
70
71impl From<RangeInclusive<usize>> for RepeatRange {
72 fn from(source: RangeInclusive<usize>) -> Self {
73 Self {
74 min: *source.start(),
75 max: *source.end(),
76 }
77 }
78}
79
80impl From<RangeToInclusive<usize>> for RepeatRange {
81 fn from(source: RangeToInclusive<usize>) -> Self {
82 Self {
83 min: 0,
84 max: source.end,
85 }
86 }
87}