intuicio_parser/
lib.rs

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
pub mod alternation;
pub mod dynamic;
pub mod extendable;
pub mod extension;
pub mod generator;
pub mod inject;
pub mod inspect;
pub mod list;
pub mod literal;
pub mod map;
pub mod not;
pub mod one_or_more;
pub mod open_close;
pub mod optional;
pub mod pratt;
pub mod predict;
pub mod regex;
pub mod repeat;
pub mod sequence;
pub mod slot;
pub mod template;
pub mod zero_or_more;

pub mod shorthand {
    use super::*;

    pub use crate::{
        alternation::shorthand::*, dynamic::shorthand::*, extendable::shorthand::*,
        extension::shorthand::*, inject::shorthand::*, inspect::shorthand::*, list::shorthand::*,
        literal::shorthand::*, map::shorthand::*, not::shorthand::*, one_or_more::shorthand::*,
        open_close::shorthand::*, optional::shorthand::*, pratt::shorthand::*,
        predict::shorthand::*, regex::shorthand::*, repeat::shorthand::*, sequence::shorthand::*,
        slot::shorthand::*, template::shorthand::*, zero_or_more::shorthand::*,
    };

    pub fn eos() -> ParserHandle {
        EndOfSourceParser.into_handle()
    }

    pub fn source(parser: ParserHandle) -> ParserHandle {
        SourceParser::new(parser).into_handle()
    }

    pub fn debug(id: impl ToString, parser: ParserHandle) -> ParserHandle {
        DebugParser::new(id, parser).into_handle()
    }

    pub fn ignore() -> ParserHandle {
        ().into_handle()
    }
}

use intuicio_data::managed::DynamicManaged;
use std::{
    any::{Any, TypeId},
    collections::HashMap,
    error::Error,
    sync::Arc,
};

pub type ParserOutput = DynamicManaged;
pub type ParserHandle = Arc<dyn Parser>;
pub type ParseResult<'a> = Result<(&'a str, ParserOutput), Box<dyn Error>>;

pub struct ParserNoValue;

pub trait Parser: Send + Sync {
    fn parse<'a>(&self, registry: &ParserRegistry, input: &'a str) -> ParseResult<'a>;

    #[allow(unused_variables)]
    fn extend(&self, parser: ParserHandle) {}
}

pub trait ParserExt: Sized {
    fn into_handle(self) -> ParserHandle;
}

impl<T: Parser + 'static> ParserExt for T {
    fn into_handle(self) -> ParserHandle {
        Arc::new(self)
    }
}

impl Parser for () {
    fn parse<'a>(&self, _: &ParserRegistry, input: &'a str) -> ParseResult<'a> {
        Ok((input, ParserOutput::new(ParserNoValue).ok().unwrap()))
    }
}

pub struct EndOfSourceParser;

impl Parser for EndOfSourceParser {
    fn parse<'a>(&self, _: &ParserRegistry, input: &'a str) -> ParseResult<'a> {
        if input.is_empty() {
            Ok((input, ParserOutput::new(ParserNoValue).ok().unwrap()))
        } else {
            Err("Expected end of source".into())
        }
    }
}

pub struct SourceParser {
    parser: ParserHandle,
}

impl SourceParser {
    pub fn new(parser: ParserHandle) -> Self {
        Self { parser }
    }
}

impl Parser for SourceParser {
    fn parse<'a>(&self, registry: &ParserRegistry, input: &'a str) -> ParseResult<'a> {
        let before = input.len();
        let (new_input, _) = self.parser.parse(registry, input)?;
        let after = new_input.len();
        let size = before - after;
        Ok((
            new_input,
            ParserOutput::new(input[0..size].to_string()).ok().unwrap(),
        ))
    }
}

pub struct DebugParser {
    id: String,
    parser: ParserHandle,
}

impl DebugParser {
    pub fn new(id: impl ToString, parser: ParserHandle) -> Self {
        Self {
            id: id.to_string(),
            parser,
        }
    }
}

impl Parser for DebugParser {
    fn parse<'a>(&self, registry: &ParserRegistry, input: &'a str) -> ParseResult<'a> {
        static mut IDENT: usize = 0;
        unsafe {
            IDENT += 1;
        }
        let ident = " ".repeat(unsafe { IDENT });
        println!("{}< DEBUG `{}` | Before: {:?}", ident, self.id, input);
        match self.parser.parse(registry, input) {
            Ok((input, result)) => {
                println!("{}> DEBUG `{}` | OK After: {:?}", ident, self.id, input);
                unsafe {
                    IDENT -= 1;
                }
                Ok((input, result))
            }
            Err(error) => {
                println!(
                    "{}> DEBUG `{}` | ERR After: {:?} | ERROR: {:?}",
                    ident, self.id, input, error
                );
                unsafe {
                    IDENT -= 1;
                }
                Err(error)
            }
        }
    }
}

#[derive(Default)]
pub struct ParserRegistry {
    parsers: HashMap<String, ParserHandle>,
    extensions: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}

impl ParserRegistry {
    pub fn with_parser(mut self, id: impl ToString, parser: ParserHandle) -> Self {
        self.add_parser(id, parser);
        self
    }

    pub fn with_extension<T: Send + Sync + 'static>(mut self, data: T) -> Self {
        self.add_extension::<T>(data);
        self
    }

    pub fn add_parser(&mut self, id: impl ToString, parser: ParserHandle) {
        self.parsers.insert(id.to_string(), parser);
    }

    pub fn remove_parser(&mut self, id: impl AsRef<str>) -> Option<ParserHandle> {
        self.parsers.remove(id.as_ref())
    }

    pub fn get_parser(&self, id: impl AsRef<str>) -> Option<ParserHandle> {
        self.parsers.get(id.as_ref()).cloned()
    }

    pub fn parse<'a>(&self, id: impl AsRef<str>, input: &'a str) -> ParseResult<'a> {
        if let Some(parser) = self.get_parser(id.as_ref()) {
            parser.parse(self, input)
        } else {
            Err(format!("Parser `{}` not found in registry", id.as_ref()).into())
        }
    }

    pub fn extend(&self, id: impl AsRef<str>, parser: ParserHandle) -> Result<(), Box<dyn Error>> {
        if let Some(extendable) = self.get_parser(id.as_ref()) {
            extendable.extend(parser);
            Ok(())
        } else {
            Err(format!("Parser '{}' not found in registry", id.as_ref()).into())
        }
    }

    pub fn add_extension<T: Send + Sync + 'static>(&mut self, data: T) -> bool {
        self.extensions.insert(TypeId::of::<T>(), Arc::new(data));
        true
    }

    pub fn remove_extension<T: 'static>(&mut self) -> bool {
        self.extensions.remove(&TypeId::of::<T>());
        true
    }

    pub fn extension<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.extensions
            .get(&TypeId::of::<T>())?
            .clone()
            .downcast::<T>()
            .ok()
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        shorthand::{eos, ignore, lit, number_int, seq, source},
        EndOfSourceParser, ParserRegistry, SourceParser,
    };

    fn is_async<T: Send + Sync>() {}

    #[test]
    fn test_end_of_source() {
        is_async::<EndOfSourceParser>();

        let registry = ParserRegistry::default();
        let sentence = seq([lit("foo"), eos()]);
        let (rest, _) = sentence.parse(&registry, "foo").unwrap();
        assert_eq!(rest, "");
        let sentence = eos();
        assert!(sentence.parse(&registry, "foo").is_err());
    }

    #[test]
    fn test_source() {
        is_async::<SourceParser>();

        let registry = ParserRegistry::default();
        let sentence = source(number_int());
        let (rest, result) = sentence.parse(&registry, "42 bar").unwrap();
        assert_eq!(rest, " bar");
        assert_eq!(result.read::<String>().unwrap().as_str(), "42");
    }

    #[test]
    fn test_ignore() {
        is_async::<()>();

        let registry = ParserRegistry::default();
        let sentence = ignore();
        let (rest, _) = sentence.parse(&registry, "foo").unwrap();
        assert_eq!(rest, "foo");
    }
}