]> Witch of Git - ess/blob - src/lib.rs
Add parsing for symbols
[ess] / src / lib.rs
1 //! A lightweight S-expression parser intended for language implementation.
2
3 // #![warn(missing_docs)]
4 #![deny(unsafe_code)]
5
6 use std::borrow::Cow;
7
8 /// A type representing arbitrary symbolic expressions. `Sexp` carries the
9 /// source code location it came from along with it for later diagnostic
10 /// purposes.
11 #[derive(Debug, PartialEq, Clone, PartialOrd)]
12 pub enum Sexp<'a, Loc=ByteSpan> where Loc: Span {
13 /// A value representing a symbol.
14 Sym(Cow<'a, str>, Loc),
15 /// A value representing a string literal.
16 Str(Cow<'a, str>, Loc),
17 /// A value representing a single character.
18 Char(char, Loc),
19 /// A value representing an integer. Any number containing no decimal point
20 /// will be parsed as an `Int`.
21 Int(i64, Loc),
22 /// A value representing a floating point number. Any number containing a
23 /// decimal point will be parsed as a `Float`.
24 Float(f64, Loc),
25 /// A list of subexpressions.
26 List(Vec<Sexp<'a, Loc>>, Loc),
27 }
28
29 impl<'a, Loc> Sexp<'a, Loc> where Loc: Span {
30 pub fn get_loc(&self) -> &Loc {
31 match *self {
32 Sexp::Sym(.., ref l) => l,
33 Sexp::Str(.., ref l) => l,
34 Sexp::Char(.., ref l) => l,
35 Sexp::Int(.., ref l) => l,
36 Sexp::Float(.., ref l) => l,
37 Sexp::List(.., ref l) => l,
38 }
39 }
40
41 pub fn get_loc_mut(&mut self) -> &mut Loc {
42 match *self {
43 Sexp::Sym(.., ref mut l) => l,
44 Sexp::Str(.., ref mut l) => l,
45 Sexp::Char(.., ref mut l) => l,
46 Sexp::Int(.., ref mut l) => l,
47 Sexp::Float(.., ref mut l) => l,
48 Sexp::List(.., ref mut l) => l,
49 }
50 }
51 }
52
53 \f
54 // General Parsing Types ///////////////////////////////////////////////////////
55
56 pub trait Span {
57 type Begin;
58
59 fn offset(&self, begin: Self::Begin) -> Self;
60 fn begin(&self) -> Self::Begin;
61 fn union(&self, other: &Self) -> Self;
62 }
63
64 #[derive(Debug, PartialEq, Eq, Clone)]
65 pub enum ParseResult<'a, T, E> {
66 Done(&'a str, T),
67 Error(E),
68 }
69
70 use ParseResult::*;
71
72 \f
73 // Specific Parsing Types (ParseError, ByteSpan) ///////////////////////////////
74
75 /// Indicates how parsing failed.
76 #[derive(Debug, PartialEq, Eq, Clone)]
77 pub enum ParseError<Loc=ByteSpan> where Loc: Span {
78 /// We can't explain how the parsing failed.
79 UnexpectedEof,
80 Symbol(Box<ParseError>, Loc),
81 Number(Box<ParseError>, Loc),
82 Unexpected(char, Loc::Begin),
83 Unimplemented,
84 }
85
86 type ByteSpan = (usize, usize);
87
88 impl Span for ByteSpan {
89 type Begin = usize;
90
91 fn offset(&self, begin: Self::Begin) -> Self {
92 (self.0 + begin, self.1 + begin)
93 }
94
95 fn begin(&self) -> Self::Begin {
96 self.0
97 }
98
99 fn union(&self, other: &Self) -> Self {
100 use std::cmp::{min, max};
101 (min(self.0, other.0), max(self.1, other.1))
102 }
103 }
104
105
106 \f
107 // Parsing Utilities ///////////////////////////////////////////////////////////
108
109 trait IsDelimeter {
110 fn is_delimiter(&self) -> bool;
111 }
112
113 impl IsDelimeter for char {
114 fn is_delimiter(&self) -> bool {
115 self.is_whitespace() || *self == ';'
116 || *self == '(' || *self == ')'
117 || *self == '[' || *self == ']'
118 || *self == '{' || *self == '}'
119 || *self == '"' || *self == '\''
120 || *self == '`' || *self == ','
121 }
122 }
123
124 \f
125 // Parsers /////////////////////////////////////////////////////////////////////
126
127 // pub fn parse_one(input: &str) -> Result<Sexp, ParseError>;
128
129 // pub fn parse(input: &str) -> Result<Vec<Sexp>, ParseError>;
130
131 pub fn parse_number(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
132 // Consume all the whitespace at the beginning of the string
133 let end_of_white = if let Some(pos) = input.find(|c: char| !c.is_whitespace()) {
134 pos
135 } else {
136 return Error(ParseError::Number(
137 Box::new(ParseError::UnexpectedEof),
138 (input.len(), input.len()).offset(start_loc)));
139 };
140
141 let input = &input[end_of_white..];
142 let start_loc = start_loc + end_of_white;
143
144 match input.chars().next() {
145 Some(c) if !c.is_digit(10) => {
146 return Error(ParseError::Number(
147 Box::new(ParseError::Unexpected(c, 0)),
148 (0, c.len_utf8()).offset(start_loc)));
149 }
150 None => return Error(ParseError::Number(
151 Box::new(ParseError::UnexpectedEof),
152 (0, 0).offset(start_loc))),
153 _ => (),
154 }
155
156 let base = 10;
157
158 let mut end = 0;
159 // Before the decimal point
160 for (i, c) in input.char_indices() {
161 if c == '.' {
162 end = i + 1;
163 break;
164 }
165
166 if c.is_delimiter() {
167 return Done(&input[i..],
168 Sexp::Int(input[..i].parse().expect("Already matched digits"),
169 (0, i).offset(start_loc)));
170 }
171
172 if !c.is_digit(base) {
173 return Error(ParseError::Number(
174 Box::new(ParseError::Unexpected(c, i)),
175 (i, i).offset(start_loc)));
176 }
177
178 end = i + c.len_utf8();
179 }
180
181 if input[end..].is_empty() {
182 return Done(&input[end..],
183 Sexp::Int(input.parse().expect("Already matched digits"),
184 (0, end).offset(start_loc)));
185 }
186
187 // After the decimal point
188 for (i, c) in input[end..].char_indices() {
189 if c.is_delimiter() {
190 return Done(&input[i+end..],
191 Sexp::Float(input[..end+i].parse().expect("Already matched digits.digits"),
192 (0, end+i).offset(start_loc)));
193 }
194
195 if !c.is_digit(base) {
196 return Error(ParseError::Number(
197 Box::new(ParseError::Unexpected(c, i + end)),
198 (i+end, i+end).offset(start_loc)));
199 }
200 }
201
202 Done(&input[input.len()..],
203 Sexp::Float(input.parse().expect("Already matched digits.digits"),
204 (0, input.len()).offset(start_loc)))
205 }
206
207 pub fn parse_symbol(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
208 let end_of_white = if let Some(pos) = input.find(|c: char| !c.is_whitespace()) {
209 pos
210 } else {
211 return Error(ParseError::Symbol(
212 Box::new(ParseError::UnexpectedEof),
213 (input.len(), input.len()).offset(start_loc)));
214 };
215
216 let input = &input[end_of_white..];
217 let start_loc = start_loc + end_of_white;
218
219 match input.chars().next() {
220 Some(c@'#') | Some(c@':') | Some(c@'0'...'9') =>
221 return Error(ParseError::Symbol(
222 Box::new(ParseError::Unexpected(c, start_loc)),
223 (0, 0).offset(start_loc))),
224 Some(c) if c.is_delimiter() =>
225 return Error(ParseError::Symbol(
226 Box::new(ParseError::Unexpected(c, start_loc)),
227 (0, 0).offset(start_loc))),
228 Some(_) => (),
229 None => unreachable!(),
230 }
231
232 for (i, c) in input.char_indices() {
233 if c.is_delimiter() {
234 return Done(&input[i..],
235 Sexp::Sym(input[..i].into(), (0, i).offset(start_loc)));
236 }
237 }
238
239 Done(&input[input.len()..],
240 Sexp::Sym(input.into(), (0, input.len()).offset(start_loc)))
241 }
242
243 \f
244 // Tests ///////////////////////////////////////////////////////////////////////
245
246 #[cfg(test)]
247 mod test {
248 use super::*;
249 use super::ParseResult::*;
250
251 #[test]
252 fn test_parse_number() {
253 assert_eq!(parse_number("1", 0), Done("", Sexp::Int(1, (0, 1))));
254 assert_eq!(parse_number(" 13", 0), Done("", Sexp::Int(13, (1, 3))));
255 assert_eq!(parse_number("1.2", 0), Done("", Sexp::Float(1.2, (0, 3))));
256 assert_eq!(parse_number("\u{3000}4.2", 0), Done("", Sexp::Float(4.2, (0, 3).offset('\u{3000}'.len_utf8()))));
257 assert_eq!(parse_number(" 42 ", 0), Done(" ", Sexp::Int(42, (2, 4))));
258 assert_eq!(parse_number(" 4.2 ", 0), Done(" ", Sexp::Float(4.2, (1, 4))));
259 assert_eq!(parse_number("1()", 0), Done("()", Sexp::Int(1, (0, 1))));
260 assert_eq!(parse_number("3.6()", 0), Done("()", Sexp::Float(3.6, (0, 3))));
261
262 assert_eq!(parse_number("", 0), Error(ParseError::Number(Box::new(ParseError::UnexpectedEof), (0, 0))));
263 assert_eq!(parse_number("123a", 0), Error(ParseError::Number(Box::new(ParseError::Unexpected('a', 3)), (3, 3))));
264 assert_eq!(parse_number("66.6+", 0), Error(ParseError::Number(Box::new(ParseError::Unexpected('+', 4)), (4, 4))));
265 }
266
267 #[test]
268 fn test_parse_ident() {
269 assert_eq!(parse_symbol("+", 0), Done("", Sexp::Sym("+".into(), (0, 1))));
270 assert_eq!(parse_symbol(" nil?", 0), Done("", Sexp::Sym("nil?".into(), (1, 5))));
271 assert_eq!(parse_symbol(" ->socket", 0), Done("", Sexp::Sym("->socket".into(), (1, 9))));
272 assert_eq!(parse_symbol("fib(", 0), Done("(", Sexp::Sym("fib".into(), (0, 3))));
273 assert_eq!(parse_symbol("foo2", 0), Done("", Sexp::Sym("foo2".into(), (0, 4))));
274
275 // We reserve #foo for the implementation to do as it wishes
276 assert_eq!(parse_symbol("#hi", 0), Error(ParseError::Symbol(Box::new(ParseError::Unexpected('#', 0)), (0, 0))));
277 // We reserve :foo for keywords
278 assert_eq!(parse_symbol(":hi", 0), Error(ParseError::Symbol(Box::new(ParseError::Unexpected(':', 0)), (0, 0))));
279
280 assert_eq!(parse_symbol("", 0), Error(ParseError::Symbol(Box::new(ParseError::UnexpectedEof), (0, 0))));
281 assert_eq!(parse_symbol("0", 0), Error(ParseError::Symbol(Box::new(ParseError::Unexpected('0', 0)), (0, 0))));
282 assert_eq!(parse_symbol("()", 0), Error(ParseError::Symbol(Box::new(ParseError::Unexpected('(', 0)), (0, 0))));
283 }
284 }
285
286 // #[cfg(test)]
287
288 // #[cfg(test)]
289 // #[test]
290 // fn test_parse_string() {
291 // assert_eq!(string(r#""hello""#), IResult::Done("", Sexp::Str("hello".into())));
292 // assert_eq!(string(r#" "this is a nice string
293 // with 0123 things in it""#),
294 // IResult::Done("", Sexp::Str("this is a nice string\nwith 0123 things in it".into())));
295
296 // assert!(string(r#""hi"#).is_err());
297 // }
298
299 // #[cfg(test)]
300 // #[test]
301 // fn test_parse_char() {
302 // assert_eq!(character(r#"#\""#), IResult::Done("", Sexp::Char('"')));
303 // assert_eq!(character(r#"#\ "#), IResult::Done("", Sexp::Char(' ')));
304 // assert_eq!(character(r#" #\\"#), IResult::Done("", Sexp::Char('\\')));
305
306 // assert!(character("#").is_incomplete());
307 // assert!(character("a").is_err());
308 // }
309
310
311 // #[cfg(test)]
312 // #[test]
313 // fn test_parse_list() {
314 // assert_eq!(list("()"), IResult::Done("", vec![]));
315 // assert_eq!(list("(1)"), IResult::Done("", vec![Sexp::Int(1)]));
316 // assert_eq!(list(" ( 1 2 3 a )"), IResult::Done("", vec![
317 // Sexp::Int(1),
318 // Sexp::Int(2),
319 // Sexp::Int(3),
320 // Sexp::Sym("a".into()),
321 // ]));
322 // }
323
324 // #[cfg(test)]
325 // #[test]
326 // fn test_parse_only_one() {
327 // assert!(parse_one("1 2").is_err());
328 // }
329
330 // #[cfg(test)]
331 // #[test]
332 // fn test_parse_expression() {
333 // assert_eq!(parse_one(r#"
334 // (def (main)
335 // (print (str "say " #\" "Hello, World" #\" " today!")))
336 // "#),
337 // Ok(Sexp::List(vec![
338 // Sexp::Sym("def".into()),
339 // Sexp::List(
340 // vec![Sexp::Sym("main".into())]
341 // ),
342 // Sexp::List(vec![
343 // Sexp::Sym("print".into()),
344 // Sexp::List(vec![
345 // Sexp::Sym("str".into()),
346 // Sexp::Str("say ".into()),
347 // Sexp::Char('"'),
348 // Sexp::Str("Hello, World".into()),
349 // Sexp::Char('"'),
350 // Sexp::Str(" today!".into()),
351 // ])
352 // ])
353 // ])));
354 // }
355
356 // #[cfg(test)]
357 // #[test]
358 // fn test_parse_multi() {
359 // assert_eq!(parse(" 1 2 3 "),
360 // Ok(vec![Sexp::Int(1), Sexp::Int(2), Sexp::Int(3)]));
361 // }