]>
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. A symbol is an atomic unit
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 float. Any number containing a decimal point will
23 /// 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 Number(Option
<Box
<ParseError
>>, Loc
),
81 Unexpected(char, Loc
::Begin
),
85 type ByteSpan
= (usize, usize);
87 impl Span
for ByteSpan
{
90 fn offset(&self, begin
: Self::Begin
) -> Self {
91 (self.0 + begin
, self.1 + begin
)
94 fn begin(&self) -> Self::Begin
{
98 fn union(&self, other
: &Self) -> Self {
99 use std
::cmp
::{min
, max
};
100 (min(self.0, other
.0), max(self.1, other
.1))
106 // Parsing Utilities ///////////////////////////////////////////////////////////
109 fn is_delimiter(&self) -> bool
;
112 impl IsDelimeter
for char {
113 fn is_delimiter(&self) -> bool
{
114 self.is
_wh
itespace
() || *self == '
;'
115 || *self == '
('
|| *self == '
)'
116 || *self == '
['
|| *self == '
]'
117 || *self == '
{'
|| *self == '
}'
118 || *self == '
"' || *self == '\''
119 || *self == '`' || *self == ','
124 // Parsers /////////////////////////////////////////////////////////////////////
126 // pub fn parse_one(input: &str) -> Result<Sexp, ParseError>;
128 // pub fn parse(input: &str) -> Result<Vec<Sexp>, ParseError>;
130 pub fn parse_number(input: &str, start_loc: usize) -> ParseResult<Sexp, ParseError> {
131 // Consume all the whitespace at the beginning of the string
132 let end_of_white = if let Some(pos) = input.find(|c: char| !c.is_whitespace()) {
135 return Error(ParseError::Number(
136 Some(Box::new(ParseError::UnexpectedEof)),
137 (input.len(), input.len()).offset(start_loc)));
140 let input = &input[end_of_white..];
141 let start_loc = start_loc + end_of_white;
143 match input.chars().next() {
144 Some(c) if !c.is_digit(10) => {
145 return Error(ParseError::Number(
146 Some(Box::new(ParseError::Unexpected(c, 0))),
147 (0, c.len_utf8()).offset(start_loc)));
149 None => return Error(ParseError::Number(
150 Some(Box::new(ParseError::UnexpectedEof)),
151 (0, 0).offset(start_loc))),
158 // Before the decimal point
159 for (i, c) in input.char_indices() {
165 if c.is_delimiter() {
166 return Done(&input[i..],
167 Sexp::Int(input[..i].parse().expect("Already matched digits
"),
168 (0, i).offset(start_loc)));
171 if !c.is_digit(base) {
172 return Error(ParseError::Number(
173 Some(Box::new(ParseError::Unexpected(c, i))),
174 (i, i).offset(start_loc)));
177 end = i + c.len_utf8();
180 if input[end..].is_empty() {
181 return Done(&input[end..],
182 Sexp::Int(input.parse().expect("Already matched digits
"),
183 (0, end).offset(start_loc)));
186 // After the decimal point
187 for (i, c) in input[end..].char_indices() {
188 if c.is_delimiter() {
189 return Done(&input[i+end..],
190 Sexp::Float(input[..end+i].parse().expect("Already matched digits
.digits
"),
191 (0, end+i).offset(start_loc)));
194 if !c.is_digit(base) {
195 return Error(ParseError::Number(
196 Some(Box::new(ParseError::Unexpected(c, i + end))),
197 (i+end, i+end).offset(start_loc)));
201 Done(&input[input.len()..],
202 Sexp::Float(input.parse().expect("Already matched digits
.digits
"),
203 (0, input.len()).offset(start_loc)))
207 // Tests ///////////////////////////////////////////////////////////////////////
212 use super::ParseResult::*;
215 fn test_parse_number() {
216 assert_eq!(parse_number("1", 0), Done("", Sexp::Int(1, (0, 1))));
217 assert_eq!(parse_number(" 13", 0), Done("", Sexp::Int(13, (1, 3))));
218 assert_eq!(parse_number("1.2", 0), Done("", Sexp::Float(1.2, (0, 3))));
219 assert_eq!(parse_number("\u{3000}4.2", 0), Done("", Sexp::Float(4.2, (0, 3).offset('\u{3000}'.len_utf8()))));
220 assert_eq!(parse_number(" 42 ", 0), Done(" ", Sexp::Int(42, (2, 4))));
221 assert_eq!(parse_number(" 4.2 ", 0), Done(" ", Sexp::Float(4.2, (1, 4))));
222 assert_eq!(parse_number("1()", 0), Done("()", Sexp::Int(1, (0, 1))));
223 assert_eq!(parse_number("3.6()", 0), Done("()", Sexp::Float(3.6, (0, 3))));
225 assert_eq!(parse_number("", 0), Error(ParseError::Number(Some(Box::new(ParseError::UnexpectedEof)), (0, 0))));
226 assert_eq!(parse_number("123a
", 0), Error(ParseError::Number(Some(Box::new(ParseError::Unexpected('a', 3))), (3, 3))));
227 assert_eq!(parse_number("66.6+", 0), Error(ParseError::Number(Some(Box::new(ParseError::Unexpected('+', 4))), (4, 4))));
233 // fn test_parse_ident() {
234 // assert_eq!(symbol("+"), IResult::Done("", Sexp::Sym("+".into())));
235 // assert_eq!(symbol(" nil?
"), IResult::Done("", Sexp::Sym("nil?
".into())));
236 // assert_eq!(symbol(" ->socket
"), IResult::Done("", Sexp::Sym("->socket
".into())));
237 // assert_eq!(symbol("fib("), IResult::Done("(", Sexp::Sym("fib
".into())));
239 // // We reserve #foo for the implementation to do as it wishes
240 // assert!(symbol("#hi").is_err());
242 // assert!(symbol("0").is_err());
243 // assert!(symbol("()").is_err());
244 // assert!(symbol("").is_incomplete());
249 // fn test_parse_string() {
250 // assert_eq!(string(r#""hello""#), IResult::Done("", Sexp::Str("hello".into())));
251 // assert_eq!(string(r#" "this is a nice string
252 // with 0123 things in it""#),
253 // IResult::Done("", Sexp::Str("this is a nice string\nwith 0123 things in it".into())));
255 // assert!(string(r#""hi"#).is_err());
260 // fn test_parse_char() {
261 // assert_eq!(character(r#"#\""#), IResult::Done("", Sexp::Char('"')));
262 // assert_eq!(character(r#"#\ "#), IResult::Done("", Sexp::Char(' ')));
263 // assert_eq!(character(r#" #\\"#), IResult::Done("", Sexp::Char('\\')));
265 // assert!(character("#").is_incomplete());
266 // assert!(character("a").is_err());
272 // fn test_parse_list() {
273 // assert_eq!(list("()"), IResult::Done("", vec![]));
274 // assert_eq!(list("(1)"), IResult::Done("", vec![Sexp::Int(1)]));
275 // assert_eq!(list(" ( 1 2 3 a )"), IResult::Done("", vec![
279 // Sexp::Sym("a".into()),
285 // fn test_parse_only_one() {
286 // assert!(parse_one("1 2").is_err());
291 // fn test_parse_expression() {
292 // assert_eq!(parse_one(r#"
294 // (print (str "say " #\" "Hello, World" #\" " today!")))
296 // Ok(Sexp::List(vec![
297 // Sexp::Sym("def".into()),
299 // vec![Sexp::Sym("main".into())]
302 // Sexp::Sym("print".into()),
304 // Sexp::Sym("str".into()),
305 // Sexp::Str("say ".into()),
307 // Sexp::Str("Hello, World".into()),
309 // Sexp::Str(" today!".into()),
317 // fn test_parse_multi() {
318 // assert_eq!(parse(" 1 2 3 "),
319 // Ok(vec![Sexp::Int(1), Sexp::Int(2), Sexp::Int(3)]));