Assignments, numbers, funcalls

This commit is contained in:
2022-01-31 14:03:47 -06:00
parent ddc4dcd97c
commit 85d13bc26e
5 changed files with 171 additions and 0 deletions

5
rust/src/main.rs Normal file
View File

@@ -0,0 +1,5 @@
mod parser;
fn main() {
println!("Hello, world!");
}

95
rust/src/parser.rs Normal file
View File

@@ -0,0 +1,95 @@
#[derive(Debug,PartialEq)]
pub enum Statement {
Assignment(String, Expression),
Funcall(Funcall),
}
#[derive(Debug,PartialEq)]
pub enum Expression {
Id(String),
Num(f64),
Funcall(Funcall)
}
#[derive(Debug,PartialEq)]
pub struct Funcall {
id: String,
args: Vec<Expression>,
}
peg::parser! {
grammar deelang_parser() for str {
pub rule program() -> Vec<Statement>
= __* s:statement()* eof() { s }
pub rule statement() -> Statement
= i:id() "<-" _ e:expr() __* { Statement::Assignment(i, e) } /
f:funcall() __* { Statement::Funcall(f)}
rule expr() -> Expression
= f:funcall() _ { Expression::Funcall(f) } /
i:id() _ { Expression::Id(i) } /
n:num() _ { Expression::Num(n) }
rule id() -> String
= i:$(letter() (letter() / digit() / ['?'|'.'|'-'])*) _ { i.to_string() }
rule num() -> f64
= n:$(digit()+ "."? digit()* / "." digit()+) _ { n.to_string().parse().unwrap() }
rule funcall() -> Funcall
= i:id() "(" _ e:(expr() ** ("," _)) ")" _ { Funcall{id: i, args: e} }
rule letter()
= ['A'..='Z'] / ['a'..='z']
rule digit()
= ['0'..='9']
rule _ // Non-meaningful whitespace
= ['\t'|' ']*
rule __ // Blank lines and lines containing only comments
= comment() &eof() / comment() newline() / newline()
rule comment()
= "#" (!newline() [_])* &(newline() / eof())
rule newline()
= "\r\n" / "\r" / "\n"
rule eof()
= ![_]
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_comments() {
let expected = vec![];
let prgm = "## This is a comment";
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
}
#[test]
fn test_funcall() {
let expected = vec![
Statement::Funcall(Funcall{id: "pear".to_string(), args: vec![]}),
Statement::Funcall(Funcall {
id: "pear".to_string(),
args: vec![Expression::Id("x".to_string()), Expression::Id("y".to_string())],
})
];
let prgm = r"pear()
pear(x, y)";
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
}
#[test]
fn test_assignment() {
let prgm = r"apple <- 1
apple <- pear(x, y)";
let expected = vec![
Statement::Assignment("apple".to_string(),
Expression::Num(1.0)),
Statement::Assignment("apple".to_string(),
Expression::Funcall(Funcall {
id: "pear".to_string(),
args: vec![
Expression::Id("x".to_string()),
Expression::Id("y".to_string())
]}))];
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
}
}