Compare commits

..

No commits in common. "7397ecc84bf051ec5cd7f0d427fa9023b85180df" and "f2b0e38464136291ed91a63fb73e4bf70a96e3c8" have entirely different histories.

5 changed files with 153 additions and 35 deletions

View File

@ -28,4 +28,3 @@ i <- 1
loop until i > 10
print(i)
i <- 1
## Loops

54
peg.txt Normal file
View File

@ -0,0 +1,54 @@
program := __* stmt*
stmt := assignment /
funcall stop /
conditional /
loop /
expr stop
expr := - _ expr /
expr "+" _ expr /
expr "-" - expr /
expr "*" _ expr /
expr "/" _ expr /
"(" _ expr ")" /
['"'] ((!['"'] [_] / #"\""#)*) ['"'] /
funcall /
fundef /
boolean /
id /
num
boolean := ("true" / "false") _
id := letter (letter / digit / ['?'|'.'|'-'])* _
num := (digit+ "."? digit* / "." digit+) _
assignment := id "<-" _ expr stop
funcall := id "(" _ expr ** ("," _) ")" _
funcdef := id? "->" _ block
conditional := if __* elif* __* else? __*
if := "if" _ expr block
elif := "elif" _ expr block
else := "else" _ block
loop := "loop" _ (until / over / block)
until := "until" _ expr block
over := "over"_ id "in" _ expr block
block := expr / indented_block
indented_block := stop indent __* stmt+ dedent
letter := ['A'..='Z'] / ['a'..='z']
digit := ['0'..='9']
stop := __+ / eof
indent := ">>>"
dedent := "<<<"
_ := ['\t'|' ']*
__ := comment? newline / comment &eof
comment := "#" (!newline [_])* &(newline / eof)
newline := "\r\n" \ "\r" \ "\n"
eof := ![_]

View File

@ -21,6 +21,7 @@ impl <'a> LexicalContext<'a> {
is_tail: false,
}
}
#[allow(dead_code)]
fn new(parent: &'a LexicalContext<'a>) -> Self {
LexicalContext {
parent: Some(parent),
@ -176,13 +177,43 @@ pub fn emit_expr(w: &mut dyn Write, expr: &parser::Expr, ctx: &mut LexicalContex
emit_all(w, body, &mut fun_ctx)?;
write!(w, "}}")?;
}
parser::Expr::BinaryOp(op, e1, e2) => {
parser::Expr::Plus(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " + ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Minus(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " - ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Mult(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " * ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Div(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " / ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Mod(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " % ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Equal(e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " == ")?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::Relop(op, e1, e2) => {
emit_expr(w, e1.as_ref(), ctx)?;
write!(w, " {} ", op)?;
emit_expr(w, e2.as_ref(), ctx)?;
}
parser::Expr::UnaryOp(op, e) => {
write!(w, "{}(", op)?;
parser::Expr::UnaryMinus(e) => {
write!(w, "-(")?;
emit_expr(w, e.as_ref(), ctx)?;
write!(w, ")")?;
}

View File

@ -13,18 +13,32 @@ use std::path::PathBuf;
#[clap(author, version, about = "Compiler for Deelang")]
struct Cli {
#[clap(help="Specify a file to compile")]
file: PathBuf,
file: Option<PathBuf>,
#[clap(short, long, help="Emit a parse tree")]
parse: bool,
#[clap(short, long, help="Cross compile to ECMAScript")]
#[clap(short, long, help="Cross-compile to ECMAScript")]
ecmascript: bool,
#[clap(long, help="Run the preprocessor")]
#[clap(long, help="Only run the pre-processor")]
preprocess: bool,
}
fn main() {
let cli = Cli::parse();
let mut file = File::open(&cli.file).expect("Couldn't read file");
fn repl(cli: &Cli) {
let mut toplevel = emitter::LexicalContext::toplevel();
let mut out = io::stdout();
loop {
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let tree = parser::parse_stmt(&line);
if cli.parse {
println!("{:#?}", tree);
} else if cli.ecmascript {
emitter::emit(&mut out, &tree, &mut toplevel).ok();
}
};
}
fn script(cli: &Cli) {
let mut file = File::open(cli.file.as_ref().unwrap()).expect("Could not read file");
let mut prgm = String::new();
file.read_to_string(&mut prgm).unwrap();
if cli.preprocess {
@ -41,3 +55,11 @@ fn main() {
emitter::emit_all(&mut out, &tree, &mut toplevel).ok();
}
}
fn main() {
let cli = Cli::parse();
match cli.file {
None => repl(&cli),
Some(_) => script(&cli),
}
}

View File

@ -14,8 +14,14 @@ pub enum Expr {
Atom(Atom),
Funcall(String, Vec<Expr>),
Funcdef(Option<String>, Block),
UnaryOp(String, Box<Expr>),
BinaryOp(String, Box<Expr>, Box<Expr>),
UnaryMinus(Box<Expr>),
Plus(Box<Expr>, Box<Expr>),
Minus(Box<Expr>, Box<Expr>),
Mult(Box<Expr>, Box<Expr>),
Div(Box<Expr>, Box<Expr>),
Mod(Box<Expr>, Box<Expr>),
Equal(Box<Expr>, Box<Expr>),
Relop(String, Box<Expr>, Box<Expr>),
}
pub type Block = Vec<Stmt>;
@ -50,18 +56,18 @@ peg::parser! {
l:_loop() { Stmt::Loop(l) } /
e:expr() stop() { Stmt::BareExpr(e) }
rule expr() -> Expr = precedence! {
e1:(@) "=" _ e2:@ { Expr::BinaryOp("=".to_string(), Box::new(e1), Box::new(e2))}
e1:(@) "=" _ e2:@ { Expr::Equal(Box::new(e1), Box::new(e2)) }
--
e1:(@) r:relop() e2:@ { Expr::BinaryOp(r, Box::new(e1), Box::new(e2)) }
e1:(@) r:relop() e2:@ { Expr::Relop(r, Box::new(e1), Box::new(e2)) }
--
"-" _ e1:@ { Expr::UnaryOp("-".to_string(), Box::new(e1)) }
"-" _ e1:@ { Expr::UnaryMinus(Box::new(e1)) }
--
e1:(@) "+" _ e2:@ { Expr::BinaryOp("+".to_string(), Box::new(e1), Box::new(e2)) }
e1:(@) "-" _ e2:@ { Expr::BinaryOp("-".to_string(), Box::new(e1), Box::new(e2)) }
e1:(@) "+" _ e2:@ { Expr::Plus(Box::new(e1), Box::new(e2)) }
e1:(@) "-" _ e2:@ { Expr::Minus(Box::new(e1), Box::new(e2)) }
--
e1:(@) "*" _ e2:@ { Expr::BinaryOp("*".to_string(), Box::new(e1), Box::new(e2)) }
e1:(@) "/" _ e2:@ { Expr::BinaryOp("/".to_string(), Box::new(e1), Box::new(e2)) }
e1:(@) "%" _ e2:@ { Expr::BinaryOp("%".to_string(), Box::new(e1), Box::new(e2)) }
e1:(@) "*" _ e2:@ { Expr::Mult(Box::new(e1), Box::new(e2)) }
e1:(@) "/" _ e2:@ { Expr::Div(Box::new(e1), Box::new(e2)) }
e1:(@) "%" _ e2:@ { Expr::Mod(Box::new(e1), Box::new(e2)) }
--
"(" _ e:expr() ")" _ { e }
['"'] s:$((!['"'] [_] / r#"\""#)*) ['"'] { Expr::Atom(Atom::String(s.to_string())) }
@ -192,6 +198,11 @@ pub fn parse(prgm: &str) -> Vec<Stmt> {
deelang_parser::program(&prgm).unwrap()
}
pub fn parse_stmt(stmt: &str) -> Stmt {
let stmt = preprocess(stmt);
deelang_parser::stmt(&stmt).unwrap()
}
impl fmt::Display for Stmt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@ -247,8 +258,15 @@ impl fmt::Display for Expr {
match self {
Expr::Atom(a) => write!(f, "{}", a),
Expr::Id(id) => write!(f, "{}", id),
Expr::BinaryOp(op, e1, e2) => write!(f, "{} {} {}", e1, op, e2),
Expr::UnaryOp(op, e) => write!(f, "{} {}", op, e),
Expr::Equal(e1, e2) => write!(f, "{} = {}", e1, e2),
Expr::Relop(op, e1, e2) => write!(f, "{} {} {}", e1, op, e2),
Expr::Plus(e1, e2) => write!(f, "{} + {}", e1, e2),
Expr::Minus(e1, e2) => write!(f, "{} - {}", e1, e2),
Expr::Div(e1, e2) => write!(f, "{} / {}", e1, e2),
Expr::Mult(e1, e2) => write!(f, "{} * {}", e1, e2),
Expr::Mod(e1, e2) => write!(f, "{} % {}", e1, e2),
Expr::UnaryMinus(e) => write!(f, "-{}", e),
Expr::Funcdef(_arg, _block) => todo!(),
Expr::Funcall(_id, _args) => todo!(),
}
@ -316,22 +334,18 @@ one <- 3 - 2
four <- (3 - 1) * 2";
let expected = vec![
Stmt::Assignment("three".to_string(),
Expr::BinaryOp(
"+".to_string(),
Expr::Plus(
Box::new(Expr::Atom(Atom::Num(1.0))),
Box::new(Expr::Atom(Atom::Num(2.0))),
)),
Stmt::Assignment("one".to_string(),
Expr::BinaryOp(
"-".to_string(),
Expr::Minus(
Box::new(Expr::Atom(Atom::Num(3.0))),
Box::new(Expr::Atom(Atom::Num(2.0))),
)),
Stmt::Assignment("four".to_string(),
Expr::BinaryOp(
"*".to_string(),
Box::new(Expr::BinaryOp(
"-".to_string(),
Expr::Mult(
Box::new(Expr::Minus(
Box::new(Expr::Atom(Atom::Num(3.0))),
Box::new(Expr::Atom(Atom::Num(1.0))),
)),
@ -346,8 +360,7 @@ four <- (3 - 1) * 2";
let prgm = "apple <- pear(x, y) + z";
let expected = vec![
Stmt::Assignment("apple".to_string(),
Expr::BinaryOp(
"+".to_string(),
Expr::Plus(
Box::new(Expr::Funcall(
"pear".to_string(),
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
@ -394,8 +407,7 @@ foo <- x -> y -> x * y";
Stmt::BareExpr(Expr::Funcdef(
Some("y".to_string()),
vec![
Stmt::BareExpr(Expr::BinaryOp(
"*".to_string(),
Stmt::BareExpr(Expr::Mult(
Box::new(Expr::Id("x".to_string())),
Box::new(Expr::Id("y".to_string())),
))
@ -437,7 +449,7 @@ else
fn test_loop() {
let prgm = r"loop until i > 100 a";
let expected = vec![Stmt::Loop(Loop::Until(GuardedBlock {
guard: Expr::BinaryOp(
guard: Expr::Relop(
">".to_string(),
Box::new(Expr::Id("i".to_string())),
Box::new(Expr::Atom(Atom::Num(100.0))),