2022-07-20 17:56:00 -05:00
|
|
|
use crate::{lexer::Token, list::List, value::Value};
|
|
|
|
use chumsky::{prelude::*, Stream};
|
|
|
|
use logos::{Lexer, Logos};
|
2022-07-02 02:25:43 -05:00
|
|
|
|
2022-07-20 17:56:00 -05:00
|
|
|
/// Parse source string into a value
|
|
|
|
pub fn read(src: &str) -> Result<Vec<Value>, Vec<Simple<Token<'_>>>> {
|
|
|
|
parser().parse(stream_of_lexer(Token::lexer(src)))
|
|
|
|
}
|
|
|
|
|
2022-07-20 18:42:25 -05:00
|
|
|
fn parser<'a>() -> impl Parser<Token<'a>, Vec<Value<'a>>, Error = Simple<Token<'a>>> {
|
2022-07-20 17:56:00 -05:00
|
|
|
recursive(|value| {
|
|
|
|
let atom = select! {
|
|
|
|
Token::Symbol("true") => Value::Bool(true),
|
|
|
|
Token::Symbol("false") => Value::Bool(false),
|
|
|
|
Token::Symbol("nil") => Value::Nil,
|
2022-07-20 18:42:25 -05:00
|
|
|
Token::Symbol(s) => Value::Symbol(s.into()),
|
|
|
|
Token::Keyword(k) => Value::Keyword(k.into()),
|
|
|
|
Token::String(s) => Value::String(s.into()),
|
2022-07-20 17:56:00 -05:00
|
|
|
Token::Number(n) => Value::Number(n),
|
|
|
|
};
|
|
|
|
|
|
|
|
let list = value
|
|
|
|
.clone()
|
|
|
|
.repeated()
|
|
|
|
.map(List::from_vec)
|
|
|
|
.map(Box::new)
|
|
|
|
.map(Value::List)
|
|
|
|
.delimited_by(just(Token::LeftParen), just(Token::RightParen));
|
|
|
|
|
|
|
|
let vector = value
|
|
|
|
.clone()
|
|
|
|
.repeated()
|
|
|
|
.map(Value::Vector)
|
|
|
|
.delimited_by(just(Token::LeftBracket), just(Token::RightBracket));
|
2022-07-02 02:25:43 -05:00
|
|
|
|
2022-07-20 18:08:40 -05:00
|
|
|
let map = value
|
|
|
|
.clone()
|
|
|
|
.then(value.clone())
|
2022-07-21 05:32:24 -05:00
|
|
|
.repeated()
|
2022-07-20 18:08:40 -05:00
|
|
|
.collect()
|
|
|
|
.map(Value::Map)
|
|
|
|
.delimited_by(just(Token::LeftCurly), just(Token::RightCurly));
|
|
|
|
|
2022-07-20 17:56:00 -05:00
|
|
|
let quote = just(Token::Quote).ignore_then(value).map(|value| {
|
|
|
|
Value::List(Box::new(List::Cons(
|
2022-07-20 18:42:25 -05:00
|
|
|
Value::Symbol("quote".into()),
|
2022-07-20 17:56:00 -05:00
|
|
|
Box::new(List::Cons(value, Box::new(List::Nil))),
|
|
|
|
)))
|
|
|
|
});
|
2022-07-02 02:25:43 -05:00
|
|
|
|
2022-07-20 18:08:40 -05:00
|
|
|
atom.or(list).or(vector).or(map).or(quote)
|
2022-07-20 17:56:00 -05:00
|
|
|
})
|
|
|
|
.repeated()
|
2022-07-20 18:08:40 -05:00
|
|
|
.then_ignore(end())
|
2022-07-02 02:25:43 -05:00
|
|
|
}
|
|
|
|
|
2022-07-20 17:56:00 -05:00
|
|
|
/// Convert Logos' Lexer into Chumsky'a Stream
|
|
|
|
fn stream_of_lexer<'a>(
|
|
|
|
lexer: Lexer<'a, Token<'a>>,
|
|
|
|
) -> Stream<'_, Token<'_>, logos::Span, logos::SpannedIter<'_, Token<'_>>> {
|
|
|
|
let len = lexer.source().len();
|
|
|
|
Stream::from_iter(len..len + 1, lexer.spanned())
|
2022-07-02 02:25:43 -05:00
|
|
|
}
|