]>
Witch of Git - ess/blob - src/lib.rs
1 //! A lightweight S-expression parser intended for language implementation.
3 // #![warn(missing_docs)]
8 /// A type representing arbitrary symbolic expressions. `Sexp` carries the
9 /// source code location it came from along with it for later diagnostic
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.
19 /// A value representing an integer. Any number containing no decimal point
20 /// will be parsed as an `Int`.
22 /// A value representing a floating point number. Any number containing a
23 /// decimal point will be parsed as a `Float`.
25 /// A list of subexpressions.
26 List(Vec
<Sexp
<'a
, Loc
>>, Loc
),
29 impl<'a
, Loc
> Sexp
<'a
, Loc
> where Loc
: Span
{
30 pub fn get_loc(&self) -> &Loc
{
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
,
41 pub fn get_loc_mut(&mut self) -> &mut Loc
{
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
,
54 // General Parsing Types ///////////////////////////////////////////////////////
59 fn offset(&self, begin
: Self::Begin
) -> Self;
60 fn begin(&self) -> Self::Begin
;
61 fn union(&self, other
: &Self) -> Self;
64 #[derive(Debug, PartialEq, Eq, Clone)]
65 pub enum ParseResult
<'a
, T
, E
> {
73 // Specific Parsing Types (ParseError, ByteSpan) ///////////////////////////////
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.
80 Symbol(Box
<ParseError
>, Loc
),
81 Number(Box
<ParseError
>, Loc
),
82 Unexpected(char, Loc
::Begin
),
86 type ByteSpan
= (usize, usize);
88 impl Span
for ByteSpan
{
91 fn offset(&self, begin
: Self::Begin
) -> Self {
92 (self.0 + begin
, self.1 + begin
)
95 fn begin(&self) -> Self::Begin
{
99 fn union(&self, other
: &Self) -> Self {
100 use std
::cmp
::{min
, max
};
101 (min(self.0, other
.0), max(self.1, other
.1))
107 // Parsing Utilities ///////////////////////////////////////////////////////////
110 fn is_delimiter(&self) -> bool
;
113 impl IsDelimeter
for char {
114 fn is_delimiter(&self) -> bool
{
115 self.is
_wh
itespace
() || *self == '
;'
116 || *self == '
('
|| *self == '
)'
117 || *self == '
['
|| *self == '
]'
118 || *self == '
{'
|| *self == '
}'
119 || *self == '
"' || *self == '\''
120 || *self == '`' || *self == ','
125 // Parsers /////////////////////////////////////////////////////////////////////
127 // pub fn parse_one(input: &str) -> Result<Sexp, ParseError>;
129 // pub fn parse(input: &str) -> Result<Vec<Sexp>, ParseError>;
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()) {
136 return Error(ParseError::Number(
137 Box::new(ParseError::UnexpectedEof),
138 (input.len(), input.len()).offset(start_loc)));
141 let input = &input[end_of_white..];
142 let start_loc = start_loc + end_of_white;
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)));
150 None => return Error(ParseError::Number(
151 Box::new(ParseError::UnexpectedEof),
152 (0, 0).offset(start_loc))),
159 // Before the decimal point
160 for (i, c) in input.char_indices() {
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)));
172 if !c.is_digit(base) {
173 return Error(ParseError::Number(
174 Box::new(ParseError::Unexpected(c, i)),
175 (i, i).offset(start_loc)));
178 end = i + c.len_utf8();
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)));
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)));
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)));
202 Done(&input[input.len()..],
203 Sexp::Float(input.parse().expect("Already matched digits
.digits
"),
204 (0, input.len()).offset(start_loc)))
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()) {
211 return Error(ParseError::Symbol(
212 Box::new(ParseError::UnexpectedEof),
213 (input.len(), input.len()).offset(start_loc)));
216 let input = &input[end_of_white..];
217 let start_loc = start_loc + end_of_white;
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))),
229 None => unreachable!(),
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)));
239 Done(&input[input.len()..],
240 Sexp::Sym(input.into(), (0, input.len()).offset(start_loc)))
244 // Tests ///////////////////////////////////////////////////////////////////////
249 use super::ParseResult::*;
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))));
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))));
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))));
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))));
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))));
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())));
296 // assert!(string(r#""hi"#).is_err());
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('\\')));
306 // assert!(character("#").is_incomplete());
307 // assert!(character("a").is_err());
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![
320 // Sexp::Sym("a".into()),
326 // fn test_parse_only_one() {
327 // assert!(parse_one("1 2").is_err());
332 // fn test_parse_expression() {
333 // assert_eq!(parse_one(r#"
335 // (print (str "say " #\" "Hello, World" #\" " today!")))
337 // Ok(Sexp::List(vec![
338 // Sexp::Sym("def".into()),
340 // vec![Sexp::Sym("main".into())]
343 // Sexp::Sym("print".into()),
345 // Sexp::Sym("str".into()),
346 // Sexp::Str("say ".into()),
348 // Sexp::Str("Hello, World".into()),
350 // Sexp::Str(" today!".into()),
358 // fn test_parse_multi() {
359 // assert_eq!(parse(" 1 2 3 "),
360 // Ok(vec![Sexp::Int(1), Sexp::Int(2), Sexp::Int(3)]));