Skip to content

Commit

Permalink
Prettier parse error messages, floats
Browse files Browse the repository at this point in the history
  • Loading branch information
Quaqqer committed Jun 23, 2024
1 parent 25a35a0 commit 2f51314
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 7 deletions.
3 changes: 2 additions & 1 deletion src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ pub struct TrailBlock(pub Vec<Spanned<Stmt>>, pub Option<Box<Spanned<Expr>>>);

#[derive(Debug)]
pub enum Expr {
Int(i32),
Int(i64),
Float(f64),
Bool(bool),
Var(Spanned<String>),
Block(TrailBlock),
Expand Down
10 changes: 8 additions & 2 deletions src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use std::collections::HashMap;

use crate::{ast, span::Span};

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Int(i32),
Int(i64),
Float(f64),
Bool(bool),
Nil,
}
Expand All @@ -13,6 +14,7 @@ impl Value {
pub fn ty(&self) -> ValueType {
match self {
Value::Int(_) => ValueType::Int,
Value::Float(_) => ValueType::Float,
Value::Bool(_) => ValueType::Bool,
Value::Nil => ValueType::Nil,
}
Expand All @@ -21,6 +23,7 @@ impl Value {
pub fn repr(&self) -> String {
match self {
Value::Int(v) => format!("{}", v),
Value::Float(f) => format!("{}", f),
Value::Bool(v) => match v {
true => "true".to_string(),
false => "false".to_string(),
Expand All @@ -32,6 +35,7 @@ impl Value {

pub enum ValueType {
Int,
Float,
Bool,
Nil,
}
Expand All @@ -40,6 +44,7 @@ impl std::fmt::Display for ValueType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ValueType::Int => write!(f, "int"),
ValueType::Float => write!(f, "float"),
ValueType::Bool => write!(f, "bool"),
ValueType::Nil => write!(f, "nil"),
}
Expand Down Expand Up @@ -201,6 +206,7 @@ impl Evaluator {

Ok(match expr {
ast::Expr::Int(i) => Value::Int(*i),
ast::Expr::Float(f) => Value::Float(*f),
ast::Expr::Bool(b) => Value::Bool(*b),
ast::Expr::Var(ident) => match self.lookup(&ident.v) {
Some(val) => val.clone(),
Expand Down
3 changes: 3 additions & 0 deletions src/parser.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@ Term: ast::Expr = {

<int_s:r"[0-9]+">
=> ast::Expr::Int(int_s.parse().unwrap()),

<float_s:r"[0-9]+\.[0-9]*|[0-9]*\.[0-9]+">
=> ast::Expr::Float(float_s.parse().unwrap()),
}

Spanned<T>: Spanned<T>
Expand Down
31 changes: 27 additions & 4 deletions src/saft.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
parser::SpannedStmtOrExprParser,
span::{Span, Spanned},
};
use std::fmt::Write;

pub struct SaftError {
pub span: Span,
Expand Down Expand Up @@ -49,16 +50,16 @@ pub fn eval_stmt_or_expr(evaluator: &mut Evaluator, src: &str) -> Res<()> {
} => bail!(
s,
"Parse error",
"Got unexpected EOF, expected {:?}",
expected
"Got unexpected EOF, expected {}",
expected_list(expected)
),

lalrpop_util::ParseError::UnrecognizedToken { token, expected } => bail!(
s,
"Parse error",
"Got unexpected token '{}', expected {:?}",
"Got unexpected token '{}', expected {}",
token.1,
expected
expected_list(expected)
),
lalrpop_util::ParseError::ExtraToken { token } => {
bail!(s, "Parse error", "Unexpected extra token '{}'", token.1)
Expand Down Expand Up @@ -92,3 +93,25 @@ fn parse_error_span<T, E>(err: &lalrpop_util::ParseError<usize, T, E>) -> Span {
lalrpop_util::ParseError::User { .. } => unreachable!(),
}
}

fn expected_list(options: Vec<String>) -> String {
match &options[..] {
[] => unreachable!("Should be at least one expected item"),
[choice] => choice.to_string(),
[one, two] => format!("{} or {}", one, two),
many => {
let mut buf = String::new();
let last = many.len() - 1;
for (i, alt) in many.iter().enumerate() {
if i == 0 {
write!(buf, "{}", alt).unwrap();
} else if i == last {
write!(buf, ", or {}", alt).unwrap();
} else {
write!(buf, ", {}", alt).unwrap();
}
}
buf
}
}
}
1 change: 1 addition & 0 deletions src/sexpr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ impl From<&ast::Expr> for SExpr {
fn from(value: &ast::Expr) -> Self {
match value {
ast::Expr::Int(i) => format!("{}", i).into(),
ast::Expr::Float(f) => format!("{}", f).into(),
ast::Expr::Bool(b) => format!("{}", b).into(),
ast::Expr::Var(v) => v.v.clone().into(),
ast::Expr::Call { expr, args } => list!(
Expand Down

0 comments on commit 2f51314

Please sign in to comment.