alith_client/components/grammar/
boolean.rs1use super::{Grammar, GrammarError, GrammarSetterTrait};
2use std::cell::RefCell;
3
4#[derive(Clone, Default, PartialEq)]
5pub struct BooleanGrammar {
6 pub stop_word_done: Option<String>,
7 pub stop_word_no_result: Option<String>,
8 grammar_string: RefCell<Option<String>>,
9}
10
11impl BooleanGrammar {
12 #[inline]
13 pub fn wrap(self) -> Grammar {
14 Grammar::Boolean(self)
15 }
16
17 pub fn grammar_string(&self) -> String {
18 let mut grammar_string = self.grammar_string.borrow_mut();
19 if grammar_string.is_none() {
20 *grammar_string = Some(boolean_grammar(
21 &self.stop_word_done,
22 &self.stop_word_no_result,
23 ));
24 }
25 grammar_string.as_ref().unwrap().clone()
26 }
27
28 #[inline]
29 pub fn validate_clean(&self, content: &str) -> Result<String, GrammarError> {
30 boolean_validate_clean(content)
31 }
32
33 #[inline]
34 pub fn grammar_parse(&self, content: &str) -> Result<bool, GrammarError> {
35 boolean_parse(content)
36 }
37}
38
39impl GrammarSetterTrait for BooleanGrammar {
40 fn stop_word_done_mut(&mut self) -> &mut Option<String> {
41 &mut self.stop_word_done
42 }
43
44 fn stop_word_no_result_mut(&mut self) -> &mut Option<String> {
45 &mut self.stop_word_no_result
46 }
47}
48
49pub fn boolean_grammar<T: AsRef<str>>(
50 stop_word_done: &Option<T>,
51 stop_word_no_result: &Option<T>,
52) -> String {
53 match (stop_word_done, stop_word_no_result) {
54 (Some(stop_word_done), Some(stop_word_no_result)) => format!(
55 "root ::= \" \" ( \"true\" | \"false\" | \"{}\" ) \" {}\"",
56 stop_word_no_result.as_ref(),
57 stop_word_done.as_ref()
58 ),
59 (None, Some(stop_word_no_result)) => {
60 format!(
61 "root ::= \" \" ( \"true\" | \"false\" | \"{}\" ) ",
62 stop_word_no_result.as_ref()
63 )
64 }
65 (Some(stop_word_done), None) => {
66 format!(
67 "root ::= \" \" ( \"true\" | \"false\" ) \" {}\"",
68 stop_word_done.as_ref()
69 )
70 }
71 (None, None) => "root ::= \" \" ( \"true\" | \"false\" )".to_owned(),
72 }
73}
74
75pub fn boolean_validate_clean(content: &str) -> Result<String, GrammarError> {
76 let content = content.trim();
77 if boolean_parse(content).is_ok() {
78 Ok(content.to_string())
79 } else {
80 Err(GrammarError::ParseValueError {
81 content: content.to_string(),
82 parse_type: "boolean".to_string(),
83 })
84 }
85}
86
87pub fn boolean_parse(content: &str) -> Result<bool, GrammarError> {
88 content
89 .trim()
90 .parse::<bool>()
91 .map_err(|_| GrammarError::ParseValueError {
92 content: content.to_string(),
93 parse_type: "boolean".to_string(),
94 })
95}