prism_parser/core/
state.rs

1use crate::core::cache::{Allocs, CacheKey, CacheVal, ParserCacheEntry};
2use crate::core::pos::Pos;
3use crate::error::ParseError;
4use std::collections::HashMap;
5
6pub struct ParserState<'arn, 'grm, E: ParseError> {
7    // Cache for parser_cache_recurse
8    cache: HashMap<CacheKey, ParserCacheEntry<CacheVal<'arn, 'grm, E>>>,
9    cache_stack: Vec<CacheKey>,
10    // For allocating things that might be in the result
11    pub alloc: Allocs<'arn>,
12    pub input: &'grm str,
13    // For generating guids
14    pub guid_counter: usize,
15    // For recovery
16    pub recovery_points: HashMap<Pos, Pos>,
17}
18
19impl<'arn, 'grm, E: ParseError> ParserState<'arn, 'grm, E> {
20    pub fn new(input: &'grm str, alloc: Allocs<'arn>) -> Self {
21        ParserState {
22            cache: HashMap::new(),
23            cache_stack: Vec::new(),
24            alloc,
25            input,
26            guid_counter: 0,
27            recovery_points: HashMap::new(),
28        }
29    }
30
31    pub(crate) fn cache_is_read(&self, key: CacheKey) -> Option<bool> {
32        self.cache.get(&key).map(|v| v.read)
33    }
34
35    pub(crate) fn cache_get(&mut self, key: &CacheKey) -> Option<&CacheVal<'arn, 'grm, E>> {
36        if let Some(v) = self.cache.get_mut(key) {
37            v.read = true;
38            Some(&v.value)
39        } else {
40            None
41        }
42    }
43
44    pub(crate) fn cache_insert(&mut self, key: CacheKey, value: CacheVal<'arn, 'grm, E>) {
45        self.cache
46            .insert(key.clone(), ParserCacheEntry { read: false, value });
47        self.cache_stack.push(key);
48    }
49
50    pub(crate) fn cache_state_get(&self) -> usize {
51        self.cache_stack.len()
52    }
53
54    pub(crate) fn cache_state_revert(&mut self, state: usize) {
55        self.cache_stack.drain(state..).for_each(|key| {
56            self.cache.remove(&key);
57        })
58    }
59
60    pub(crate) fn clear(&mut self) {
61        self.cache.clear();
62        self.cache_stack.clear();
63    }
64}