sapi_lite/stt/grammar/rule/
arena.rs

1use std::borrow::Cow;
2
3use typed_arena::Arena;
4
5use crate::stt::SemanticValue;
6
7use super::{RepeatRange, Rule};
8
9/// Allocation arena for grammar rules.
10///
11/// Provides an easy way to allocate [`Rule`] instances while building a grammar. All of the rules
12/// owned by the arena will be dropped when the arena itself is dropped.
13pub struct RuleArena<'a> {
14    arena: Arena<Rule<'a>>,
15}
16
17impl<'a> RuleArena<'a> {
18    /// Construct a new arena.
19    pub fn new() -> Self {
20        Self {
21            arena: Arena::new(),
22        }
23    }
24
25    /// Take ownership of a constructed rule and keep it until the arena is destroyed.
26    pub fn alloc(&self, rule: Rule<'a>) -> &Rule<'a> {
27        self.arena.alloc(rule)
28    }
29
30    /// Allocate a rule that defines a sequence of words to be recognized.
31    pub fn text<T: Into<Cow<'a, str>>>(&self, text: T) -> &Rule<'a> {
32        self.alloc(Rule::text(text))
33    }
34
35    /// Allocate a rule that defines a set of alternatives to choose from.
36    pub fn choice<L: Into<Cow<'a, [&'a Rule<'a>]>>>(&self, options: L) -> &Rule<'a> {
37        self.alloc(Rule::choice(options))
38    }
39
40    /// Allocate a rule the defines a sequence of sub-rules that must be recognized in order.
41    pub fn sequence<L: Into<Cow<'a, [&'a Rule<'a>]>>>(&self, parts: L) -> &Rule<'a> {
42        self.alloc(Rule::sequence(parts))
43    }
44
45    /// Allocate a rule that recognizes a sub-rule repeated a certain number of times.
46    pub fn repeat<R: Into<RepeatRange>>(&self, times: R, target: &'a Rule<'a>) -> &Rule<'a> {
47        self.alloc(Rule::repeat(times, target))
48    }
49
50    /// Allocate a rule that produces a node in the resulting semantic tree when the given sub-rule
51    /// is recognized.
52    pub fn semantic<V: Into<SemanticValue<Cow<'a, str>>>>(
53        &self,
54        value: V,
55        target: &'a Rule<'a>,
56    ) -> &Rule<'a> {
57        self.alloc(Rule::semantic(value, target))
58    }
59}