mod llvm;
use indicatif::ProgressBar;
use lazy_static::lazy_static;
use regex::{Regex, Split};
use std::{collections::HashMap, str::SplitWhitespace};
#[derive(Debug, PartialEq, Clone)]
pub struct Number(pub f64);
impl Number {
pub fn new(s: &str) -> Result<Self, String> {
match s.parse::<f64>() {
Ok(n) => Ok(Self(n)),
Err(_) => Err(format!("Invalid number: {s}")),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Op {
Add,
Sub,
Mul,
Div,
Gt,
Lt,
Mod,
Eqt,
}
impl Op {
pub fn new(s: &str) -> Self {
match s {
"+" => Self::Add,
"-" => Self::Sub,
"*" => Self::Mul,
"/" => Self::Div,
">" => Self::Gt,
"<" => Self::Lt,
"%" => Self::Mod,
"==" => Self::Eqt,
_ => log_and_exit!("Invalid operator"),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct BinaryExpr {
pub op: Op,
pub lhs: Vec<Node>,
pub rhs: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct BindExpr {
pub name: String,
pub value: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct ReturnExpr {
pub value: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct MutateExpr {
pub name: String,
pub value: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct WhileExpr {
pub condition: Vec<Node>,
pub body: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct IfExpr {
pub condition: Vec<Node>,
pub body: Vec<Node>,
pub else_body: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct FnExpr {
pub name: String,
pub args: Vec<Node>,
pub body: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct FnCallExpr {
pub name: String,
pub args: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub struct PrintStdoutExpr {
pub value: Vec<Node>,
}
#[derive(Debug, PartialEq, Clone)]
pub enum Node {
Number(Number),
BinaryExpr(BinaryExpr),
BindExpr(BindExpr),
Variable(String),
ReturnExpr(ReturnExpr),
MutateExpr(MutateExpr),
WhileExpr(WhileExpr),
IfExpr(IfExpr),
FnExpr(FnExpr),
FnCallExpr(FnCallExpr),
PrintStdoutExpr(PrintStdoutExpr),
}
lazy_static! {
static ref RE: Regex = Regex::new(r"[;\n]").unwrap();
}
pub fn lex(s: &str) -> regex::Split<'static, '_> {
RE.split(s)
}
pub fn parse(
tokens: &mut Split<'static, '_>,
functions: &mut HashMap<String, FnExpr>,
) -> Vec<Node> {
let mut nodes = Vec::new();
while let Some(token) = tokens.next() {
if token.trim() == "end" {
break;
}
if let Ok(mut new_nodes) = parse_sentence(&mut token.split_whitespace(), functions) {
nodes.append(&mut new_nodes);
}
if let Some(Node::WhileExpr(e)) = nodes.last_mut() {
if e.body.is_empty() {
e.body = parse(tokens, functions);
}
}
if let Some(Node::IfExpr(e)) = nodes.last_mut() {
if e.body.is_empty() {
let body = parse(tokens, functions);
let mut body = body.split(|n| n == &Node::Variable("else".to_string()));
e.body = body.next().unwrap().to_vec();
e.else_body = body.next().unwrap_or(&Vec::new()).to_vec();
}
}
if let Some(Node::FnExpr(e)) = nodes.last_mut() {
if e.body.is_empty() {
e.body = parse(tokens, functions);
}
}
}
nodes
}
fn parse_sentence(
tokens: &mut SplitWhitespace,
functions: &mut HashMap<String, FnExpr>,
) -> Result<Vec<Node>, String> {
let mut nodes = Vec::new();
match tokens.next() {
Some(t) => match t {
"+" | "-" | "*" | "/" | ">" | "<" | "%" | "==" => {
nodes.push(Node::BinaryExpr(BinaryExpr {
op: Op::new(t),
lhs: parse_sentence(tokens, functions).unwrap(),
rhs: parse_sentence(tokens, functions).unwrap(),
}));
}
"let" => {
let name = tokens.next().unwrap();
let value = parse_sentence(tokens, functions).unwrap();
nodes.push(Node::BindExpr(BindExpr {
name: name.to_string(),
value,
}));
}
"//" => {
return Ok(nodes);
}
"return" => {
nodes.push(Node::ReturnExpr(ReturnExpr {
value: parse_sentence(tokens, functions).unwrap(),
}));
}
":=" => {
let name = tokens.next().unwrap();
let value = parse_sentence(tokens, functions).unwrap();
nodes.push(Node::MutateExpr(MutateExpr {
name: name.to_string(),
value,
}));
}
"while" => {
let condition = parse_sentence(tokens, functions).unwrap();
let body = Vec::new();
nodes.push(Node::WhileExpr(WhileExpr { condition, body }));
}
"if" => {
let condition = parse_sentence(tokens, functions).unwrap();
let body = Vec::new();
let else_body = Vec::new();
nodes.push(Node::IfExpr(IfExpr {
condition,
body,
else_body,
}));
}
"fn" => {
let name = tokens.next().unwrap();
let args = parse_args(tokens.collect::<Vec<_>>().join(" "), functions);
let body = Vec::new();
let expr = FnExpr {
name: name.to_string(),
args,
body,
};
functions.insert(name.to_string(), expr.clone());
nodes.push(Node::FnExpr(expr));
}
"print" => {
nodes.push(Node::PrintStdoutExpr(PrintStdoutExpr {
value: parse_sentence(tokens, functions).unwrap(),
}));
}
_ => {
if let Some(_f) = functions.get(t) {
let args = parse_args(tokens.collect::<Vec<_>>().join(" "), functions);
nodes.push(Node::FnCallExpr(FnCallExpr {
name: t.to_string(),
args,
}));
} else {
match Number::new(t) {
Ok(n) => nodes.push(Node::Number(n)),
Err(_) => nodes.push(Node::Variable(t.to_string())),
}
}
}
},
None => {
log::warn!("No tokens found in statement");
return Err("No tokens found".to_string())
},
}
Ok(nodes)
}
fn parse_args(tokens: String, functions: &mut HashMap<String, FnExpr>) -> Vec<Node> {
let mut nodes = Vec::new();
let mut tokens = tokens;
if !tokens.starts_with('(') && !tokens.ends_with(')') {
log_and_exit!("Invalid function arguments. Must be in the form (arg1 arg2 ...)");
}
tokens.remove(0);
tokens.pop();
let tokens = tokens.split_whitespace();
for token in tokens {
if let Ok(mut new_nodes) = parse_sentence(&mut token.split_whitespace(), functions) {
nodes.append(&mut new_nodes);
}
}
nodes
}
pub fn eval(
ast: &Vec<Node>,
globals: &mut HashMap<String, f64>,
functions: &mut HashMap<String, FnExpr>,
) -> f64 {
let mut return_val: Option<f64> = None;
let mut last_val: f64 = 0.0;
for node in ast {
last_val = match node {
Node::Number(n) => n.0,
Node::BinaryExpr(e) => {
let lhs = eval(&e.lhs, globals, functions);
let rhs = eval(&e.rhs, globals, functions);
match e.op {
Op::Add => lhs + rhs,
Op::Sub => lhs - rhs,
Op::Mul => lhs * rhs,
Op::Div => lhs / rhs,
Op::Gt => (lhs > rhs) as i32 as f64,
Op::Lt => (lhs < rhs) as i32 as f64,
Op::Mod => lhs % rhs,
Op::Eqt => (lhs == rhs) as i32 as f64,
}
}
Node::BindExpr(e) => {
let value = eval(&e.value, globals, functions);
globals.insert(e.name.clone(), value);
value
}
Node::Variable(v) => match globals.get(v) {
Some(n) => *n,
None => log_and_exit!("Variable not found: {v}"),
},
Node::ReturnExpr(e) => {
return_val = Some(eval(&e.value, globals, functions));
0.0 }
Node::MutateExpr(e) => {
let value = eval(&e.value, globals, functions);
if let Some(n) = globals.get_mut(&e.name) {
*n = value;
} else {
log_and_exit!("Variable not found: {}", e.name);
}
value
}
Node::WhileExpr(e) => {
while eval(&e.condition, globals, functions) != 0.0 {
eval(&e.body, globals, functions);
}
0.0
}
Node::IfExpr(e) => {
if eval(&e.condition, globals, functions) != 0.0 {
eval(&e.body, globals, functions)
} else {
eval(&e.else_body, globals, functions)
}
}
Node::FnExpr(e) => {
functions.insert(e.name.clone(), e.clone());
0.0
}
Node::FnCallExpr(e) => {
if let Some(f) = functions.get(&e.name).cloned() {
let mut local_scope = HashMap::new();
for (param, arg) in f.args.iter().zip(&e.args) {
let v = eval(&vec![arg.clone()], globals, functions);
let k = match param {
Node::Variable(v) => v,
_ => log_and_exit!("Invalid function argument"),
};
local_scope.insert(k.clone(), v);
}
eval(&f.body, &mut local_scope, functions)
} else {
log_and_exit!("Function not found: {}", e.name);
}
}
Node::PrintStdoutExpr(e) => {
let value = eval(&e.value, globals, functions);
println!("{}", value);
0.0
}
};
}
return_val.unwrap_or(last_val)
}
pub struct CompileConfig {
pub use_jit: bool,
pub show_ir: bool,
pub optimization_level: u8,
pub name: String,
pub progress: ProgressBar,
}
impl CompileConfig {
pub fn from(use_jit: bool, show_ir: bool) -> Self {
Self {
use_jit,
show_ir,
optimization_level: 1,
name: String::from("main"),
progress: ProgressBar::new(0),
}
}
}
pub trait Compile {
type Output;
fn from_ast(nodes: Vec<Node>, config: &CompileConfig) -> Self::Output;
fn from_source(source: &str, config: &CompileConfig) -> Self::Output {
config.progress.set_message("Lexing source");
let mut tokens = lex(source);
log::trace!("tokens: {:?}", lex(source).collect::<Vec<_>>());
config.progress.inc(1);
config.progress.set_message("Parsing tokens");
let nodes = parse(&mut tokens, &mut HashMap::new());
log::debug!("ast: {:?}", nodes);
config.progress.inc(1);
config.progress.set_message("Evaluating AST");
Self::from_ast(nodes, config)
}
fn from_file(path: &str, config: &CompileConfig) -> Self::Output {
config.progress.set_message("Reading file");
let source = std::fs::read_to_string(path).unwrap();
config.progress.inc(1);
Self::from_source(&source, config)
}
}
pub type Compiler<'a> = llvm::LLVMCompiler<'a, 'a>;
pub struct Interpreter;
impl Compile for Interpreter {
type Output = f64;
fn from_ast(nodes: Vec<Node>, _config: &CompileConfig) -> Self::Output {
eval(&nodes, &mut HashMap::new(), &mut HashMap::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_number() {
assert_eq!(Number::new("1.0").unwrap(), Number(1.0));
assert_eq!(Number::new("4").unwrap(), Number(4.0));
}
#[test]
fn parse_add() {
assert_eq!(Op::new("+"), Op::Add);
}
#[test]
fn parse_sub() {
assert_eq!(Op::new("-"), Op::Sub);
}
#[test]
fn parse_mul() {
assert_eq!(Op::new("*"), Op::Mul);
}
#[test]
fn parse_div() {
assert_eq!(Op::new("/"), Op::Div);
}
#[test]
fn parse_gt() {
assert_eq!(Op::new(">"), Op::Gt);
}
#[test]
fn parse_lt() {
assert_eq!(Op::new("<"), Op::Lt);
}
#[test]
fn parse_expr() {
let mut tokens = lex("+ * -2 3 - 2 3.5");
let nodes = parse(&mut tokens, &mut HashMap::new());
assert_eq!(
nodes,
vec![Node::BinaryExpr(BinaryExpr {
op: Op::Add,
lhs: vec![Node::BinaryExpr(BinaryExpr {
op: Op::Mul,
lhs: vec![Node::Number(Number(-2.0))],
rhs: vec![Node::Number(Number(3.0))],
})],
rhs: vec![Node::BinaryExpr(BinaryExpr {
op: Op::Sub,
lhs: vec![Node::Number(Number(2.0))],
rhs: vec![Node::Number(Number(3.5))],
})],
}),]
)
}
#[test]
fn eval_expr() {
let mut tokens = lex("return + * -2 3 - 2 3.5");
let nodes = parse(&mut tokens, &mut HashMap::new());
assert_eq!(eval(&nodes, &mut HashMap::new(), &mut HashMap::new()), -7.5);
}
#[test]
fn interpret() {
let config = CompileConfig::from(true, false);
assert_eq!(Interpreter::from_source("+ * -2 3 - 2 3.5", &config), -7.5);
}
#[test]
fn define_variable() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
let x 1
"#,
&config
),
1.0
);
}
#[test]
fn variable_arithmetic() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
"let x 2;
let y 1;
+ x y;",
&config
),
3.0
);
}
#[test]
fn variable_arithmetic_complex() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
"let x 2;
let y 1;
let z + x * y 2;
z;",
&config
),
4.0
);
}
#[test]
fn return_only() {
let config = CompileConfig::from(true, false);
assert_eq!(Interpreter::from_source("+ 2 3;return 1;", &config), 1.0);
}
#[test]
fn while_loop() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
let x 0;
// let y 0;
while < x 1000
let i 0;
while < i 100
:= x + x 1;
:= i + i 1;
end
end
return + x i;
"#,
&config
),
1100.0
);
}
#[test]
fn if_else() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
let x 0;
if < x 1
return 1;
else
return 2;
end
"#,
&config
),
1.0
);
}
#[test]
fn only_if() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
let x 10;
let y 2
if < x y
return y
end
return x
"#,
&config
),
10.0
);
}
#[test]
fn function_call() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
fn sum (x y)
return + x y;
end
let i 10;
let d 2;
let z sum (i d);
return z
"#,
&config
),
12.0
);
}
#[test]
fn collatz_conjecture() {
let config = CompileConfig::from(true, false);
assert_eq!(
Interpreter::from_source(
r#"
fn collatz (n)
while > n 1
if == % n 2 0
:= n / n 2
else
:= n + * 3 n 1
end
print n
end
return n
end
return collatz (123)
"#,
&config
),
1.0
);
}
#[test]
fn read_from_file() {
let config = CompileConfig::from(true, false);
assert_eq!(Interpreter::from_file("examples/test.laspa", &config), 1.0);
}
#[test]
fn llvm_jit_operations() {
let config = CompileConfig::from(true, false);
assert_eq!(
llvm::LLVMCompiler::from_source("+ 1 2", &config).unwrap(),
3.0
);
}
#[test]
fn llvm_jit_bind_val() {
let config = CompileConfig::from(true, false);
assert_eq!(
llvm::LLVMCompiler::from_source("let x 10", &config).unwrap(),
0.0
);
}
#[test]
fn llvm_jit_variables() {
let config = CompileConfig::from(true, false);
assert_eq!(
llvm::LLVMCompiler::from_source("let x 10; + x 2", &config).unwrap(),
12.0
);
}
#[test]
fn llvm_jit_return() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source("let x 10; + x 2;return x", &config).unwrap(),
10.0
);
}
#[test]
fn llvm_jit_mutate() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source("let x 10;:= x + x 2;return x", &config).unwrap(),
12.0
);
}
#[test]
fn llvm_jit_while() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
let x 0;
// let y 0;
while < x 1000
let i 0;
while < i 100
:= x + x 1;
:= i + i 1;
end
end
return + x i;
"#,
&config
)
.unwrap(),
1100.0
);
}
#[test]
fn llvm_jit_if_else() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
let x 0;
if < x 1
return 1;
else
return 2;
end
"#,
&config
)
.unwrap(),
1.0
);
}
#[test]
fn llvm_jit_only_if() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
let x 10;
let y 2
if < x y
return y
end
return x
"#,
&config
)
.unwrap(),
10.0
);
}
#[test]
fn llvm_jit_function_call() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
fn sum (x y)
return + x y;
end
let i 10;
let d 2;
let z sum (i d);
return z
"#,
&config
)
.unwrap(),
12.0
);
}
#[test]
fn llvm_jit_collatz_conjecture() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
fn collatz (n)
while > n 1
if == % n 2 0
:= n / n 2
else
:= n + * 3 n 1
end
// cannot print in llvm jit
// print n
end
return n
end
return collatz (123)
"#,
&config
)
.unwrap(),
1.0
);
}
#[test]
fn llvm_jit_precision() {
let config = CompileConfig::from(true, true);
assert_eq!(
llvm::LLVMCompiler::from_source(
r#"
return % 3 2
"#,
&config
)
.unwrap(),
1.0
);
}
}