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)))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn parser<'a>() -> impl Parser<Token<'a>, Vec<Value>, Error = Simple<Token<'a>>> {
|
|
|
|
recursive(|value| {
|
|
|
|
let atom = select! {
|
|
|
|
Token::Symbol("true") => Value::Bool(true),
|
|
|
|
Token::Symbol("false") => Value::Bool(false),
|
|
|
|
Token::Symbol("nil") => Value::Nil,
|
|
|
|
Token::Symbol(s) => Value::Symbol(s.to_owned()),
|
|
|
|
Token::Keyword(k) => Value::Keyword(k.to_owned()),
|
|
|
|
Token::String(s) => Value::String(s.to_owned()),
|
|
|
|
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())
|
|
|
|
.separated_by(just(Token::Comma))
|
|
|
|
.allow_trailing()
|
|
|
|
.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(
|
|
|
|
Value::Symbol("quote".to_owned()),
|
|
|
|
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
|
|
|
}
|