Skip to main content

eta_core/
human.rs

1
2
3use alloc::{format, rc::Rc, string::String};
4use core::{fmt::Display, iter::Peekable, str};
5use hashbrown::HashMap;
6use thiserror::Error;
7
8use crate::theory::{ID, Kind};
9
10pub struct Dict {
11    map: HashMap< Rc<String>, ID>,
12    rev: HashMap<ID, Rc<String>>,
13    i: ID
14}
15impl Dict {
16    pub fn new() -> Self { Self {map: HashMap::new(), rev: HashMap::new(), i: 0} }
17    pub fn get(&mut self, name: String) -> Option<ID> {
18        match self.map.get(&name) {
19            Some(id) => Some(*id),
20            None => {
21                let owd: Rc<String> = Rc::from(name);
22                self.map.insert(owd.clone(), self.i);
23                self.rev.insert(self.i, owd);
24
25                let ret = self.i;
26                match self.i.checked_add(1) {
27                    Some(ni) => {
28                        self.i = ni;
29                        Some(ret)
30                    },
31                    None => None,
32                }
33            },
34        }
35    }
36    /* expensive (kinda) */
37    pub fn get_name(&self, id: ID) -> Option<&str> {
38        self.rev.get(&id).map(Rc::as_ref).map(|x| x.as_str())
39    }
40}
41
42/* parse errors */
43#[derive(Debug, Error)]
44pub enum ParserErr {
45    #[error("expected '{what}' at {pos}")]
46    Expected { what: char, pos: usize },
47
48    #[error("expected an atom at {pos}")]
49    NeedAtom { pos: usize },
50
51    #[error("namespace full while at {pos}")]
52    NamespaceFull { pos: usize },
53
54    #[error("end of input at {pos}")]
55    EndOfInput { pos: usize },
56
57    #[error("pair has more than 2 members at {pos}")]
58    PairHasMore { pos: usize },
59}
60type PrsErr = ParserErr;
61
62struct Prsable<It: Iterator<Item = char>> {
63    inner: Peekable<It>,
64    pos: usize
65}
66impl<It: Iterator<Item = char>> Prsable<It> {
67    fn new(it: It) -> Self { Self { inner: it.peekable(), pos: 0 }}
68    fn next(&mut self) -> Option<char> {
69        let n = self.inner.next()?;
70        self.pos += 1;
71        Some(n)
72    }
73    fn peek(&mut self) -> Option<char> { self.inner.peek().copied() }
74}
75
76/* parser: binary s-expressions (s-pairs) */
77pub struct Parser<It: Iterator<Item = char>> {
78    it: Prsable<It>
79}
80
81type Prsr<It> = Parser<It>;
82impl<It: Iterator<Item = char>> Prsr<It> {
83    pub fn new(it: It) -> Self { Self { it: Prsable::new(it) }}
84
85    fn skip_ws(&mut self) {
86        while let Some(b) = self.it.peek() {
87            match b {
88                ' ' | '\t' | '\r' | '\n' => { self.it.next(); },
89                ';' => { /* comment to end-of-line */
90                    while let Some(c) = self.it.next() {
91                        if c == '\n' {
92                            self.it.next(); /* eat \n */
93                            break
94                        }
95                    }
96                }
97                _ => break,
98            }
99        }
100    }
101
102    fn expect(&mut self, want: char) -> Result<(), PrsErr> {
103        self.skip_ws();
104        match self.it.next() {
105            Some(got) if got == want => Ok(()),
106            _ => Err(PrsErr::Expected { what: want, pos: self.it.pos }),
107        }
108    }
109
110    fn is_sym_char(b: char) -> bool {
111        !matches!(b, ' ' | '\t' | '\r' | '\n' | '(' | ')' | ';')
112    }
113
114    pub fn parse_atom(&mut self, dict: &mut Dict) -> Result<Kind, PrsErr> {
115        self.skip_ws();
116        let mut st = String::new();
117        let start = self.it.pos;
118
119        while let Some(b) = self.it.peek() {
120            if Self::is_sym_char(b) {
121                self.it.next(); /* consume */
122                st.push(b);
123            } else { break; }
124        }
125
126        if self.it.pos == start {
127            return Err(PrsErr::NeedAtom { pos: self.it.pos });
128        }
129
130        match dict.get(st) {
131            Some(sy) => Ok(Kind::from(sy)),
132            None => Err(PrsErr::NamespaceFull { pos: self.it.pos }),
133        }
134    }
135
136    pub fn parse_expr(&mut self, dict: &mut Dict) -> Result<Kind, PrsErr> {
137        self.skip_ws();
138        match self.it.peek() {
139            Some('(') => self.parse_spair(dict),
140            Some(_) => self.parse_atom(dict),
141            None => Err(PrsErr::EndOfInput { pos: self.it.pos }),
142        }
143    }
144
145    // '(' expr expr ')', exactly two.
146    pub fn parse_spair(&mut self, dict: &mut Dict) -> Result<Kind, PrsErr> {
147        self.expect('(')?;
148        let l = self.parse_expr(dict)?;
149        let r = self.parse_expr(dict)?;
150        self.skip_ws();
151
152        match self.it.peek() {
153            Some(')') => {
154                self.it.next(); /* consume */
155                Ok(Kind::from((l, r)))
156            }
157            Some(_) => Err(PrsErr::PairHasMore { pos: self.it.pos }),
158            None => Err(PrsErr::Expected { what: ')', pos: self.it.pos }),
159        }
160    }
161}
162
163pub fn unparse(root: &Kind, dict: &Dict) -> String {
164    match root {
165        Kind::Alp { id } => match dict.get_name(*id) {
166            Some(name) => name.into(),
167            None => format!("#{root:?}"),
168        },
169        Kind::Zta { sid, .. } => match *sid {
170            None => format!("#{root:?}"),
171            Some(id) => match dict.get_name(id) {
172                Some(name) => name.into(),
173                None => format!("#{root:?}"),
174            },
175        }
176        Kind::Pir { l, r } => format!(
177            "({} {})",
178            unparse(l, dict), unparse(r, dict)
179        )
180    }
181}
182
183pub struct View<'a> {
184    root: &'a Kind,
185    dict: &'a Dict
186}
187impl<'a> View<'a> {
188    pub fn new(root: &'a Kind, dict: &'a Dict) -> Self { Self { root, dict } }
189}
190
191impl<'a> Display for View<'a> {
192    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
193        match self.root {
194            Kind::Alp { id } => match self.dict.get_name(*id) {
195                Some(name) => write!(f, "{name}"),
196                None => write!(f, "#{:?}", self.root),
197            },
198            Kind::Zta { sid, .. } => match *sid {
199                None => write!(f, "#{:?}", self.root),
200                Some(id) => match self.dict.get_name(id) {
201                    Some(name) => write!(f, "{name}"),
202                    None => write!(f, "#{:?}", self.root),
203                },
204            }
205            Kind::Pir { l, r } => write!(
206                f, "({} {})",
207                View::new(l, self.dict),
208                View::new(r, self.dict)
209            )
210        }
211    }
212}