Compare commits
21 Commits
25fe7933f2
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 7397ecc84b | |||
| b5ee47d2c8 | |||
| 782c1c93f0 | |||
| 488d7b1edb | |||
| f2b0e38464 | |||
| 1e2c107c1b | |||
| c29d463adf | |||
| 5f57c5aed3 | |||
| c345ac4fe5 | |||
| 7f241523d4 | |||
| 08cab74fb5 | |||
| c9295b5777 | |||
| 03b140189c | |||
| 7213f4a487 | |||
| 5fdd28fe0e | |||
| 74f1fdc5ea | |||
| 9291e65c11 | |||
| d0de70eb54 | |||
| 26bff70b1f | |||
| 8259b57a46 | |||
| 0524efef03 |
14
dee-mode.el
14
dee-mode.el
@@ -2,12 +2,6 @@
|
||||
|
||||
(add-to-list 'auto-mode-alist '("\\.dee\\'" . dee-mode))
|
||||
|
||||
(defface dee-function-param-face
|
||||
'((t . (:slant italic
|
||||
:weight bold
|
||||
:foreground "orange")))
|
||||
"A face to help identify function parameter in Deelang.")
|
||||
|
||||
(defcustom dee-indent-offset 4
|
||||
"Default indentation offset for Deelang."
|
||||
:group 'dee
|
||||
@@ -34,14 +28,14 @@
|
||||
(defvar dee-font-lock-keywords
|
||||
`(,(rx symbol-start
|
||||
(or
|
||||
"if" "elif" "else" "")
|
||||
"if" "elif" "else" "loop" "until" "over" "in" "")
|
||||
symbol-end)
|
||||
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "<-")
|
||||
(1 font-lock-variable-name-face))
|
||||
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "->")
|
||||
(1 'dee-function-param-face))
|
||||
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "(")
|
||||
(1 font-lock-function-name-face))))
|
||||
(1 font-lock-function-name-face))
|
||||
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "->")
|
||||
(1 font-lock-constant-face))))
|
||||
|
||||
(defun dee-indent-line-function ()
|
||||
'noindent) ;TODO
|
||||
|
||||
@@ -2,7 +2,6 @@ fun <- ->
|
||||
do-something()
|
||||
do-something-else()
|
||||
|
||||
|
||||
foo <- ->
|
||||
bar <- ->
|
||||
baz <- ->
|
||||
@@ -11,8 +10,7 @@ foo <- ->
|
||||
|
||||
foo() ## Inside foo but not in baz or bar
|
||||
|
||||
add <- x -> y ->
|
||||
return x + y ## Multivariable functions by currying
|
||||
add <- x -> y -> x + y ## Multivariable functions by currying
|
||||
|
||||
add(x) ## Returns a _function_
|
||||
add(x, y) ## This is equivalent to add(x)(y)
|
||||
add(x, y) ## This is equivalent to add(x)(y)
|
||||
|
||||
@@ -7,7 +7,7 @@ foo <- -> bar() ## function definitions
|
||||
foo <- ->
|
||||
bar()
|
||||
baz()
|
||||
## functions with block statements
|
||||
# functions with block statements
|
||||
foo <- x -> y -> x * y + 7 ## Multiple argument functions
|
||||
if test?()
|
||||
do-something()
|
||||
@@ -24,8 +24,8 @@ else
|
||||
do-a-real-bad-thing()
|
||||
## Nested blocks
|
||||
|
||||
obj <- {
|
||||
field <- "hello"
|
||||
method <- x -> x * 2
|
||||
}
|
||||
## Object creation
|
||||
i <- 1
|
||||
loop until i > 10
|
||||
print(i)
|
||||
i <- 1
|
||||
## Loops
|
||||
|
||||
@@ -1,24 +1,11 @@
|
||||
## By the end of the book I want to have an interpreter
|
||||
## for this little language, maybe a compiler too
|
||||
|
||||
print(1 + 1) ## 2
|
||||
print("Hello world!") ## Hello world
|
||||
|
||||
name <- read()
|
||||
print("Hi there $name") ## Hi there <name>
|
||||
|
||||
have <- 10
|
||||
want <- 11
|
||||
need <- have - want ## This is subtraction
|
||||
have-want <- 1 ## This is a variable named "have-want"
|
||||
|
||||
print(HaVe-WAnt) ## 1 (case doesn't matter)
|
||||
%%option meaningful-casing
|
||||
Apples <- 1
|
||||
print(apples) ## <undef> (or maybe it does)
|
||||
|
||||
print("one fish"); print("two fish") ## Two statements on the same line
|
||||
|
||||
say-hi <- -> print("Hi from inside a function")
|
||||
say-hi() ## Hi from inside a function
|
||||
|
||||
@@ -31,8 +18,8 @@ duck <- {
|
||||
eats? <- food -> food = "bread"
|
||||
} ## Objects created on the fly
|
||||
|
||||
print duck.eats?("bread") ## true
|
||||
print duck.eats?("corn") ## false
|
||||
print(duck.eats?("bread")) ## true
|
||||
print(duck.eats?("corn")) ## false
|
||||
|
||||
cow <- {
|
||||
talk <- print("Moo")
|
||||
@@ -43,15 +30,15 @@ human <- {
|
||||
eats? <- _ -> true
|
||||
}
|
||||
|
||||
print cow.eats?("grass") ## true
|
||||
print cow.eats?("corn") ## true
|
||||
print(cow.eats?("grass")) ## true
|
||||
print(cow.eats?("corn")) ## true
|
||||
|
||||
talk-or-pass-wind <- character ->
|
||||
if character has talk then
|
||||
if character has talk
|
||||
character.talk()
|
||||
else
|
||||
print("*Fart*")
|
||||
|
||||
talk-or-pass-wind(duck) ## "Quack"
|
||||
talk-or-pass-wind(cow) ## "Moo"
|
||||
talk-or-pass-wind(human) ## "*Fart*"
|
||||
talk-or-pass-wind(human) ## "*Fart*"
|
||||
|
||||
18
demo/real.dee
Normal file
18
demo/real.dee
Normal file
@@ -0,0 +1,18 @@
|
||||
## Obligatory
|
||||
fizzbuzz <- ->
|
||||
loop over x in range(100)
|
||||
if x % 15 = 0 print("fizzbuzz")
|
||||
elif x % 3 = 0 print("fizz")
|
||||
elif x % 5 = 0 print("buzz")
|
||||
else print(x)
|
||||
|
||||
fizzbuzz()
|
||||
|
||||
print()
|
||||
|
||||
ack <- m -> n ->
|
||||
if m = 0 n + 1
|
||||
elif n = 0 ack(m - 1, 1)
|
||||
else ack(m - 1, ack(m, n - 1))
|
||||
|
||||
print(ack(3, 4)) ## 125
|
||||
49
peg.txt
49
peg.txt
@@ -1,49 +0,0 @@
|
||||
program := __* stmt*
|
||||
|
||||
stmt := assignment /
|
||||
funcall stop /
|
||||
conditional /
|
||||
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
|
||||
|
||||
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 := ![_]
|
||||
123
src/emitter.rs
123
src/emitter.rs
@@ -3,6 +3,10 @@ use std::collections::HashSet;
|
||||
|
||||
use crate::parser;
|
||||
|
||||
fn munge(s: &str) -> String {
|
||||
s.replace("?", "p").replace("-", "_")
|
||||
}
|
||||
|
||||
pub struct LexicalContext<'a> {
|
||||
parent: Option<&'a LexicalContext<'a>>,
|
||||
local: HashSet<String>,
|
||||
@@ -17,12 +21,11 @@ impl <'a> LexicalContext<'a> {
|
||||
is_tail: false,
|
||||
}
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
fn new(parent: &'a LexicalContext<'a>) -> Self {
|
||||
LexicalContext {
|
||||
parent: Some(parent),
|
||||
local: HashSet::new(),
|
||||
is_tail: false,
|
||||
is_tail: parent.is_tail,
|
||||
}
|
||||
}
|
||||
fn contains(&self, s: &str) -> bool {
|
||||
@@ -33,32 +36,46 @@ impl <'a> LexicalContext<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn emit_all(w: &mut dyn Write, ast: &Vec<parser::Stmt>, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||
for stmt in ast {
|
||||
emit(w, stmt, ctx)?;
|
||||
/// Embeds the pre-written js
|
||||
pub fn emit_injector(w: &mut dyn Write) -> std::io::Result<()>{
|
||||
let bytes = include_bytes!("./js/deeinject.js");
|
||||
write!(w, "{}", String::from_utf8_lossy(bytes))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn emit_all(w: &mut dyn Write, ast: &[parser::Stmt], ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||
let is_tail = ctx.is_tail;
|
||||
ctx.is_tail = false;
|
||||
if let Some((last, butlast)) = ast.split_last() {
|
||||
for stmt in butlast {
|
||||
emit(w, stmt, ctx)?;
|
||||
}
|
||||
ctx.is_tail = is_tail;
|
||||
emit(w, last, ctx)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||
match &stmt {
|
||||
parser::Stmt::ReplPrint(expr) => {
|
||||
write!(w, "console.log((")?;
|
||||
parser::Stmt::BareExpr(expr) => {
|
||||
if ctx.is_tail {
|
||||
write!(w, "return ")?;
|
||||
}
|
||||
emit_expr(w, expr, ctx)?;
|
||||
writeln!(w, "));")?;
|
||||
writeln!(w, ";")?;
|
||||
}
|
||||
parser::Stmt::Assignment(id, expr) => {
|
||||
if !ctx.contains(id) {
|
||||
ctx.insert(id.clone());
|
||||
write!(w, "let ")?;
|
||||
}
|
||||
write!(w, "{} = ", id)?;
|
||||
write!(w, "{} = ", munge(id))?;
|
||||
emit_expr(w, expr, ctx)?;
|
||||
writeln!(w, ";")?;
|
||||
}
|
||||
parser::Stmt::Funcall(call) => {
|
||||
emit_expr(w, call, ctx)?;
|
||||
writeln!(w, ";")?;
|
||||
if ctx.is_tail {
|
||||
writeln!(w, "return;")?;
|
||||
}
|
||||
}
|
||||
parser::Stmt::Conditional(if_blocks, else_block) => {
|
||||
let mut first_block = true;
|
||||
@@ -66,22 +83,52 @@ pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) ->
|
||||
if first_block {
|
||||
write!(w, "if (")?;
|
||||
} else {
|
||||
write!(w, " else if(")?;
|
||||
write!(w, "else if(")?;
|
||||
}
|
||||
first_block = false;
|
||||
emit_expr(w, &if_block.guard, ctx)?;
|
||||
writeln!(w, ") {{")?;
|
||||
let mut block_ctx = LexicalContext::new(ctx);
|
||||
emit_expr(w, &if_block.block, &mut block_ctx)?;
|
||||
emit_all(w, &if_block.block, &mut block_ctx)?;
|
||||
writeln!(w, "}}")?;
|
||||
}
|
||||
if let Some(block) = else_block {
|
||||
writeln!(w, "else {{")?;
|
||||
let mut block_ctx = LexicalContext::new(ctx);
|
||||
emit_expr(w, block, &mut block_ctx)?;
|
||||
emit_all(w, block, &mut block_ctx)?;
|
||||
writeln!(w, "}}")?;
|
||||
}
|
||||
}
|
||||
parser::Stmt::Loop(eloop) => {
|
||||
let is_tail = ctx.is_tail;
|
||||
ctx.is_tail = false;
|
||||
match &eloop {
|
||||
parser::Loop::Over(id, expr, block) => {
|
||||
write!(w, "for (let {} of ", id)?;
|
||||
emit_expr(w, expr, ctx)?;
|
||||
writeln!(w, ") {{")?;
|
||||
let mut block_ctx = LexicalContext::new(ctx);
|
||||
emit_all(w, block, &mut block_ctx)?;
|
||||
writeln!(w, "}}")?;
|
||||
ctx.is_tail = is_tail;
|
||||
}
|
||||
parser::Loop::Until(guarded_block) => {
|
||||
write!(w, "while (!(")?;
|
||||
emit_expr(w, &guarded_block.guard, ctx)?;
|
||||
write!(w, ")) {{")?;
|
||||
let mut block_ctx = LexicalContext::new(ctx);
|
||||
emit_all(w, &guarded_block.block, &mut block_ctx)?;
|
||||
writeln!(w, "}}")?;
|
||||
}
|
||||
parser::Loop::Bare(block) => {
|
||||
write!(w, "for(;;){{")?;
|
||||
let mut block_ctx = LexicalContext::new(ctx);
|
||||
emit_all(w, block, &mut block_ctx)?;
|
||||
writeln!(w, "}}")?;
|
||||
}
|
||||
}
|
||||
ctx.is_tail = is_tail;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -89,21 +136,34 @@ pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) ->
|
||||
pub fn emit_expr(w: &mut dyn Write, expr: &parser::Expr, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||
match &expr {
|
||||
parser::Expr::Id(id) => {
|
||||
write!(w, "{}", id)?;
|
||||
write!(w, "{}", munge(id))?;
|
||||
}
|
||||
parser::Expr::Atom(atom) => {
|
||||
write!(w, "{}", atom)?;
|
||||
}
|
||||
parser::Expr::Funcall(id, args) => {
|
||||
write!(w, "{}", id)?;
|
||||
write!(w, "{}", munge(id))?;
|
||||
if args.is_empty() {
|
||||
write!(w, "()")?;
|
||||
}
|
||||
for arg in args {
|
||||
} else if ctx.contains(id) {
|
||||
// Use deelang calling semantics
|
||||
for arg in args {
|
||||
write!(w, "(")?;
|
||||
emit_expr(w, arg, ctx)?;
|
||||
write!(w, ")")?
|
||||
}
|
||||
} else {
|
||||
// Use JS calling semantics
|
||||
write!(w, "(")?;
|
||||
emit_expr(w, arg, ctx)?;
|
||||
let (last, butlast) = args.split_last().unwrap();
|
||||
for arg in butlast {
|
||||
emit_expr(w, arg, ctx)?;
|
||||
write!(w, ",")?
|
||||
}
|
||||
emit_expr(w, last, ctx)?;
|
||||
write!(w, ")")?;
|
||||
}
|
||||
|
||||
}
|
||||
parser::Expr::Funcdef(arg, body) => {
|
||||
if let Some(arg) = arg {
|
||||
@@ -113,24 +173,19 @@ pub fn emit_expr(w: &mut dyn Write, expr: &parser::Expr, ctx: &mut LexicalContex
|
||||
}
|
||||
let mut fun_ctx = LexicalContext::new(ctx);
|
||||
fun_ctx.is_tail = true;
|
||||
emit_expr(w, body.as_ref(), &mut fun_ctx)?;
|
||||
emit_all(w, body, &mut fun_ctx)?;
|
||||
write!(w, "}}")?;
|
||||
}
|
||||
parser::Expr::Block(stmts) => {
|
||||
let mut peek_iter = stmts.iter().peekable();
|
||||
while let Some(stmt) = peek_iter.next() {
|
||||
if peek_iter.peek().is_none() {
|
||||
write!(w, "return ")?;
|
||||
}
|
||||
emit(w, stmt, ctx)?;
|
||||
}
|
||||
}
|
||||
parser::Expr::Plus(e1, e2) => {
|
||||
parser::Expr::BinaryOp(op, e1, e2) => {
|
||||
emit_expr(w, e1.as_ref(), ctx)?;
|
||||
write!(w, " + ")?;
|
||||
write!(w, " {} ", op)?;
|
||||
emit_expr(w, e2.as_ref(), ctx)?;
|
||||
}
|
||||
_ => todo!(),
|
||||
parser::Expr::UnaryOp(op, e) => {
|
||||
write!(w, "{}(", op)?;
|
||||
emit_expr(w, e.as_ref(), ctx)?;
|
||||
write!(w, ")")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
139
src/evaluator.rs
139
src/evaluator.rs
@@ -1,139 +0,0 @@
|
||||
use std::ops;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::parser::{self, GuardedBlock};
|
||||
use parser::Atom;
|
||||
|
||||
pub struct Env<'a> {
|
||||
pub parent: Option<&'a Env<'a>>,
|
||||
pub values: HashMap<String, Atom>
|
||||
}
|
||||
|
||||
impl<'a> Env<'a> {
|
||||
pub fn global() -> Self {
|
||||
Env {
|
||||
parent: None,
|
||||
values: HashMap::new(),
|
||||
}
|
||||
}
|
||||
pub fn child(parent: &'a Env<'a>) -> Self {
|
||||
Env {
|
||||
parent: Some(parent),
|
||||
values: HashMap::new(),
|
||||
}
|
||||
}
|
||||
pub fn lookup(&self, id: &str) -> Atom {
|
||||
if let Some(a) = self.values.get(id) {
|
||||
a.clone()
|
||||
} else if let Some(parent) = self.parent {
|
||||
parent.lookup(id)
|
||||
} else {
|
||||
panic!("Variable {} not in scope.", id)
|
||||
}
|
||||
}
|
||||
pub fn set(&mut self, id: String, atom: Atom) {
|
||||
self.values.insert(id, atom);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval(ast: &parser::Stmt, env: &mut Env) {
|
||||
match &ast {
|
||||
parser::Stmt::ReplPrint(expr) =>
|
||||
println!("{}", eval_expr(expr, env)),
|
||||
parser::Stmt::Assignment(id, expr) =>
|
||||
env.set(id.clone(), eval_expr(expr, env)),
|
||||
parser::Stmt::Conditional(guarded_blocks, default_block) => {
|
||||
let mut matched = false;
|
||||
for GuardedBlock { guard, block } in guarded_blocks {
|
||||
let res = eval_expr(guard, env);
|
||||
match res {
|
||||
Atom::Bool(true) => {
|
||||
matched = true;
|
||||
if let parser::Expr::Block(block) = block {
|
||||
for stmt in block {
|
||||
eval(stmt, env);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
Atom::Bool(false) => continue,
|
||||
_ => panic!("Conditional expression does not evaluate to a bool"),
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
if let Some(block) = default_block {
|
||||
eval_expr(block, env);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => todo!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn eval_expr(ast: &parser::Expr, env: &Env) -> Atom {
|
||||
match ast {
|
||||
parser::Expr::Id(a) => env.lookup(a),
|
||||
parser::Expr::Atom(a) => a.clone(),
|
||||
parser::Expr::UnaryMinus(a) => -eval_expr(a, env),
|
||||
parser::Expr::Plus(a, b) => eval_expr(a, env) + eval_expr(b, env),
|
||||
parser::Expr::Minus(a, b) => eval_expr(a, env) - eval_expr(b, env),
|
||||
parser::Expr::Mult(a, b) => eval_expr(a, env) * eval_expr(b, env),
|
||||
parser::Expr::Div(a, b) => eval_expr(a, env) / eval_expr(b, env),
|
||||
_ => panic!("Couldn't evalute expression {{ {:?} }}", ast),
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Neg for Atom {
|
||||
type Output = Self;
|
||||
|
||||
fn neg(self) -> Self {
|
||||
match self {
|
||||
Atom::Num(a) => Atom::Num(-a),
|
||||
_ => panic!("Can't negate non-numeral type!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Add for Atom {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, other: Self) -> Self {
|
||||
match (self, other) {
|
||||
(Atom::Num(a), Atom::Num(b)) => Atom::Num(a + b),
|
||||
_ => panic!("Can't add non-numeral types!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Sub for Atom {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, other: Self) -> Self {
|
||||
match (self, other) {
|
||||
(Atom::Num(a), Atom::Num(b)) => Atom::Num(a - b),
|
||||
_ => panic!("Can't subtract non-numeral types!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Mul for Atom {
|
||||
type Output = Self;
|
||||
|
||||
fn mul(self, other: Self) -> Self {
|
||||
match (self, other) {
|
||||
(Atom::Num(a), Atom::Num(b)) => Atom::Num(a * b),
|
||||
_ => panic!("Can't multiply non-numeral types!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ops::Div for Atom {
|
||||
type Output = Self;
|
||||
|
||||
fn div(self, other: Self) -> Self {
|
||||
match (self, other) {
|
||||
(Atom::Num(a), Atom::Num(b)) => Atom::Num(a / b),
|
||||
_ => panic!("Can't divide non-numeral types!"),
|
||||
}
|
||||
}
|
||||
}
|
||||
3
src/internal.rs
Normal file
3
src/internal.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
//! Internal compiler steps, expansion, cps, optimization.
|
||||
|
||||
|
||||
10
src/js/deeinject.js
Normal file
10
src/js/deeinject.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const print = console.log
|
||||
|
||||
function range(x) {
|
||||
const ret = []
|
||||
for (let i = 0; i < x; i++) {
|
||||
ret.push(i);
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
68
src/main.rs
68
src/main.rs
@@ -1,6 +1,6 @@
|
||||
mod parser;
|
||||
mod evaluator;
|
||||
mod emitter;
|
||||
mod internal;
|
||||
|
||||
use clap::Parser;
|
||||
|
||||
@@ -10,54 +10,34 @@ use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[clap(author, version, about = "Interpreter for Deelang")]
|
||||
#[clap(author, version, about = "Compiler for Deelang")]
|
||||
struct Cli {
|
||||
#[clap(help="Specify a file to run")]
|
||||
file: Option<PathBuf>,
|
||||
#[clap(short, long, help="Only parse, do not evaluate")]
|
||||
parse_only: bool,
|
||||
#[clap(short, long, help="Cross-compile to ECMAScript")]
|
||||
#[clap(help="Specify a file to compile")]
|
||||
file: PathBuf,
|
||||
#[clap(short, long, help="Emit a parse tree")]
|
||||
parse: bool,
|
||||
#[clap(short, long, help="Cross compile to ECMAScript")]
|
||||
ecmascript: bool,
|
||||
}
|
||||
|
||||
fn repl(cli: &Cli) {
|
||||
let mut global = evaluator::Env::global();
|
||||
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_only {
|
||||
println!("{:#?}", tree);
|
||||
} else if cli.ecmascript {
|
||||
emitter::emit(&mut out, &tree, &mut toplevel).ok();
|
||||
} else {
|
||||
evaluator::eval(&tree, &mut global);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
let tree = parser::parse(&prgm);
|
||||
if cli.parse_only {
|
||||
println!("{:#?}", tree);
|
||||
} else if cli.ecmascript {
|
||||
let mut out = io::stdout();
|
||||
let mut toplevel = emitter::LexicalContext::toplevel();
|
||||
emitter::emit_all(&mut out, &tree, &mut toplevel).ok();
|
||||
} else {
|
||||
todo!();
|
||||
}
|
||||
#[clap(long, help="Run the preprocessor")]
|
||||
preprocess: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
match cli.file {
|
||||
None => repl(&cli),
|
||||
Some(_) => script(&cli),
|
||||
let mut file = File::open(&cli.file).expect("Couldn't read file");
|
||||
let mut prgm = String::new();
|
||||
file.read_to_string(&mut prgm).unwrap();
|
||||
if cli.preprocess {
|
||||
println!("{}", parser::preprocess(&prgm));
|
||||
return;
|
||||
}
|
||||
let tree = parser::parse(&prgm);
|
||||
if cli.parse {
|
||||
println!("{:#?}", tree);
|
||||
} else if cli.ecmascript {
|
||||
let mut out = io::stdout();
|
||||
emitter::emit_injector(&mut out).ok();
|
||||
let mut toplevel = emitter::LexicalContext::toplevel();
|
||||
emitter::emit_all(&mut out, &tree, &mut toplevel).ok();
|
||||
}
|
||||
}
|
||||
|
||||
257
src/parser.rs
257
src/parser.rs
@@ -3,9 +3,9 @@ use std::fmt;
|
||||
#[derive(Debug,PartialEq,Clone)]
|
||||
pub enum Stmt {
|
||||
Assignment(String, Expr),
|
||||
Funcall(Expr),
|
||||
Conditional(Vec<GuardedBlock>, Option<Expr>),
|
||||
ReplPrint(Expr),
|
||||
Conditional(Vec<GuardedBlock>, Option<Block>),
|
||||
Loop(Loop),
|
||||
BareExpr(Expr),
|
||||
}
|
||||
|
||||
#[derive(Debug,PartialEq,Clone)]
|
||||
@@ -13,16 +13,13 @@ pub enum Expr {
|
||||
Id(String),
|
||||
Atom(Atom),
|
||||
Funcall(String, Vec<Expr>),
|
||||
Funcdef(Option<String>, 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>),
|
||||
Block(Vec<Stmt>),
|
||||
Object(Vec<Stmt>),
|
||||
Funcdef(Option<String>, Block),
|
||||
UnaryOp(String, Box<Expr>),
|
||||
BinaryOp(String, Box<Expr>, Box<Expr>),
|
||||
}
|
||||
|
||||
pub type Block = Vec<Stmt>;
|
||||
|
||||
#[derive(Debug,PartialEq,Clone)]
|
||||
pub enum Atom {
|
||||
String(String),
|
||||
@@ -30,20 +27,17 @@ pub enum Atom {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
impl fmt::Display for Atom {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Atom::String(a) => write!(f, "\"{}\"", a),
|
||||
Atom::Num(a) => write!(f, "{}", a),
|
||||
Atom::Bool(a) => write!(f, "{}", a),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,PartialEq,Clone)]
|
||||
pub struct GuardedBlock {
|
||||
pub guard: Expr,
|
||||
pub block: Expr,
|
||||
pub block: Block,
|
||||
}
|
||||
|
||||
#[derive(Debug,PartialEq,Clone)]
|
||||
pub enum Loop {
|
||||
Bare(Block),
|
||||
Until(GuardedBlock),
|
||||
Over(String, Expr, Block),
|
||||
}
|
||||
|
||||
peg::parser! {
|
||||
@@ -52,24 +46,28 @@ peg::parser! {
|
||||
= __* s:stmt()* { s }
|
||||
pub rule stmt() -> Stmt
|
||||
= a:assignment() { a } /
|
||||
f:funcall() stop() { Stmt::Funcall(f) } /
|
||||
c:conditional() { c } /
|
||||
e:expr() stop() { Stmt::ReplPrint(e) }
|
||||
l:_loop() { Stmt::Loop(l) } /
|
||||
e:expr() stop() { Stmt::BareExpr(e) }
|
||||
rule expr() -> Expr = precedence! {
|
||||
"-" _ e1:@ { Expr::UnaryMinus(Box::new(e1)) }
|
||||
e1:(@) "=" _ e2:@ { Expr::BinaryOp("=".to_string(), Box::new(e1), Box::new(e2))}
|
||||
--
|
||||
e1:(@) r:relop() e2:@ { Expr::BinaryOp(r, Box::new(e1), Box::new(e2)) }
|
||||
--
|
||||
"-" _ e1:@ { Expr::UnaryOp("-".to_string(), Box::new(e1)) }
|
||||
--
|
||||
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::Mult(Box::new(e1), Box::new(e2)) }
|
||||
e1:(@) "/" _ e2:@ { Expr::Div(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)) }
|
||||
--
|
||||
"(" _ e:expr() ")" _ { e }
|
||||
['"'] s:$((!['"'] [_] / r#"\""#)*) ['"'] { Expr::Atom(Atom::String(s.to_string())) }
|
||||
f:funcall() { f }
|
||||
f:funcdef() { f }
|
||||
b:boolean() _ { Expr::Atom(Atom::Bool(b)) }
|
||||
o:object() { o }
|
||||
i:id() _ { Expr::Id(i) }
|
||||
n:num() _ { Expr::Atom(Atom::Num(n)) }
|
||||
|
||||
@@ -81,17 +79,16 @@ peg::parser! {
|
||||
= i:$(letter() (letter() / digit() / ['?'|'.'|'-'])*) _ { i.to_string() }
|
||||
rule assignment() -> Stmt
|
||||
= i:id() "<-" _ e:expr() stop() { Stmt::Assignment(i, e) }
|
||||
rule relop() -> String
|
||||
= r:$("<" / ">" / "<=" / ">=") _ { r.to_string() }
|
||||
rule num() -> f64
|
||||
= n:$(digit()+ "."? digit()* / "." digit()+) _ { n.parse().unwrap() }
|
||||
rule funcall() -> Expr
|
||||
= i:id() "(" _ e:(expr() ** ("," _)) ")" _ { Expr::Funcall(i, e) }
|
||||
= i:id() "(" _ e:(expr() ** ("," _)) __* ")" _ { Expr::Funcall(i, e) }
|
||||
rule funcdef() -> Expr
|
||||
= i:id()? "->" _ e:(expr() / block()) { Expr::Funcdef(i, Box::new(e)) }
|
||||
= i:id()? "->" _ b:(block()) { Expr::Funcdef(i, b) }
|
||||
rule conditional() -> Stmt
|
||||
= i:_if() __* ei:elif()* __* e:_else()? __* { Stmt::Conditional([vec![i], ei].concat(), e) }
|
||||
rule object() -> Expr
|
||||
= "{" _ stop() indent() __* a:assignment()+ dedent() __* "}" _ { Expr::Object(a) }
|
||||
|
||||
= i:_if() __* ei:elif()* e:_else()? __* { Stmt::Conditional([vec![i], ei].concat(), e) }
|
||||
rule _if() -> GuardedBlock
|
||||
= "if" _ g:expr() b:block() {
|
||||
GuardedBlock {
|
||||
@@ -100,17 +97,29 @@ peg::parser! {
|
||||
}
|
||||
}
|
||||
rule elif() -> GuardedBlock
|
||||
= "elif" _ g:expr() b:block() {
|
||||
= "elif" _ g:expr() b:block() __* {
|
||||
GuardedBlock {
|
||||
guard: g,
|
||||
block: b
|
||||
}
|
||||
}
|
||||
rule _else() -> Expr
|
||||
rule _else() -> Block
|
||||
= "else" _ b:block() { b }
|
||||
rule block() -> Expr
|
||||
= i:indented_block() { Expr::Block(i) }
|
||||
rule indented_block() -> Vec<Stmt>
|
||||
rule _loop() -> Loop
|
||||
= "loop" _ "until" _ e:expr() b:block() __* {
|
||||
Loop::Until(GuardedBlock{
|
||||
guard:e,
|
||||
block: b,
|
||||
})
|
||||
} /
|
||||
"loop" _ "over" _ i:id() "in" _ e:expr() b:block() __* {
|
||||
Loop::Over(i, e, b)
|
||||
} /
|
||||
"loop" _ b:block() __* { Loop::Bare(b) }
|
||||
rule block() -> Block
|
||||
= i:indented_block() { i } /
|
||||
e:expr() { vec![Stmt::BareExpr(e)] }
|
||||
rule indented_block() -> Block
|
||||
= stop() indent() __* s:stmt()+ dedent() { s }
|
||||
|
||||
rule letter()
|
||||
@@ -136,7 +145,7 @@ peg::parser! {
|
||||
}
|
||||
}
|
||||
|
||||
fn preprocess(input: &str) -> String {
|
||||
pub fn preprocess(input: &str) -> String {
|
||||
let mut stack = vec![0];
|
||||
let mut output = String::new();
|
||||
for line in input.lines() {
|
||||
@@ -169,6 +178,12 @@ fn preprocess(input: &str) -> String {
|
||||
output.push_str(line.trim());
|
||||
output.push('\n');
|
||||
}
|
||||
while stack.len() > 1 {
|
||||
// place any dedents needed to balance the program
|
||||
output.push_str("<<<");
|
||||
output.push('\n');
|
||||
stack.pop();
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
@@ -177,9 +192,77 @@ 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 {
|
||||
Stmt::Assignment(id, expr) => writeln!(f, "{} <- {}", id, expr),
|
||||
Stmt::BareExpr(expr) => writeln!(f, "{}", expr),
|
||||
Stmt::Conditional(guarded_blocks, else_block) => {
|
||||
let (if_block, elif_blocks) = guarded_blocks.split_first().unwrap();
|
||||
write!(f, "if {}", if_block.guard)?;
|
||||
write_block(f, &if_block.block)?;
|
||||
for elif_block in elif_blocks {
|
||||
write!(f, "elif {}", elif_block.guard)?;
|
||||
write_block(f, &if_block.block)?;
|
||||
}
|
||||
if let Some(block) = else_block {
|
||||
write!(f, "else")?;
|
||||
write_block(f, block)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Loop(loop_inner) => match &loop_inner {
|
||||
Loop::Bare(block) => {
|
||||
write!(f, "loop")?;
|
||||
write_block(f, block)
|
||||
}
|
||||
Loop::Over(id, pred, block) => {
|
||||
write!(f, "loop over {} in {}", id, pred)?;
|
||||
write_block(f, block)
|
||||
}
|
||||
Loop::Until(guarded_block) => {
|
||||
write!(f, "loop until {}", guarded_block.guard)?;
|
||||
write_block(f, &guarded_block.block)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_block (f: &mut fmt::Formatter<'_>, block: &Block) -> fmt::Result {
|
||||
if block.len() == 1 {
|
||||
writeln!(f, " {}", block[0])
|
||||
} else {
|
||||
writeln!(f)?;
|
||||
writeln!(f, ">>>")?;
|
||||
for stmt in block {
|
||||
write!(f, "{}", stmt)?;
|
||||
}
|
||||
writeln!(f, "<<<")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Expr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
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::Funcdef(_arg, _block) => todo!(),
|
||||
Expr::Funcall(_id, _args) => todo!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Atom {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Atom::String(a) => write!(f, "\"{}\"", a),
|
||||
Atom::Num(a) => write!(f, "{}", a),
|
||||
Atom::Bool(a) => write!(f, "{}", a),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -199,8 +282,8 @@ apple <- 1 ## This is too
|
||||
#[test]
|
||||
fn test_funcall() {
|
||||
let expected = vec![
|
||||
Stmt::Funcall(Expr::Funcall("pear".to_string(), vec![])),
|
||||
Stmt::Funcall(Expr::Funcall("pear".to_string(),
|
||||
Stmt::BareExpr(Expr::Funcall("pear".to_string(), vec![])),
|
||||
Stmt::BareExpr(Expr::Funcall("pear".to_string(),
|
||||
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
||||
))
|
||||
];
|
||||
@@ -233,18 +316,22 @@ one <- 3 - 2
|
||||
four <- (3 - 1) * 2";
|
||||
let expected = vec![
|
||||
Stmt::Assignment("three".to_string(),
|
||||
Expr::Plus(
|
||||
Expr::BinaryOp(
|
||||
"+".to_string(),
|
||||
Box::new(Expr::Atom(Atom::Num(1.0))),
|
||||
Box::new(Expr::Atom(Atom::Num(2.0))),
|
||||
)),
|
||||
Stmt::Assignment("one".to_string(),
|
||||
Expr::Minus(
|
||||
Expr::BinaryOp(
|
||||
"-".to_string(),
|
||||
Box::new(Expr::Atom(Atom::Num(3.0))),
|
||||
Box::new(Expr::Atom(Atom::Num(2.0))),
|
||||
)),
|
||||
Stmt::Assignment("four".to_string(),
|
||||
Expr::Mult(
|
||||
Box::new(Expr::Minus(
|
||||
Expr::BinaryOp(
|
||||
"*".to_string(),
|
||||
Box::new(Expr::BinaryOp(
|
||||
"-".to_string(),
|
||||
Box::new(Expr::Atom(Atom::Num(3.0))),
|
||||
Box::new(Expr::Atom(Atom::Num(1.0))),
|
||||
)),
|
||||
@@ -259,7 +346,8 @@ four <- (3 - 1) * 2";
|
||||
let prgm = "apple <- pear(x, y) + z";
|
||||
let expected = vec![
|
||||
Stmt::Assignment("apple".to_string(),
|
||||
Expr::Plus(
|
||||
Expr::BinaryOp(
|
||||
"+".to_string(),
|
||||
Box::new(Expr::Funcall(
|
||||
"pear".to_string(),
|
||||
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
||||
@@ -285,36 +373,37 @@ foo <- x -> y -> x * y";
|
||||
"foo".to_string(),
|
||||
Expr::Funcdef(
|
||||
None,
|
||||
Box::new(Expr::Funcall("bar".to_string(), vec![])),
|
||||
)
|
||||
vec![Stmt::BareExpr(Expr::Funcall("bar".to_string(), vec![]))],
|
||||
),
|
||||
),
|
||||
Stmt::Assignment(
|
||||
"foo".to_string(),
|
||||
Expr::Funcdef(
|
||||
None,
|
||||
Box::new(Expr::Block(vec![
|
||||
Stmt::Funcall(Expr::Funcall("bar".to_string(), vec![])),
|
||||
Stmt::Funcall(Expr::Funcall("baz".to_string(), vec![])),
|
||||
]))
|
||||
)
|
||||
vec![
|
||||
Stmt::BareExpr(Expr::Funcall("bar".to_string(), vec![])),
|
||||
Stmt::BareExpr(Expr::Funcall("baz".to_string(), vec![])),
|
||||
],
|
||||
)
|
||||
),
|
||||
Stmt::Assignment(
|
||||
"foo".to_string(),
|
||||
Expr::Funcdef(
|
||||
Some("x".to_string()),
|
||||
Box::new(
|
||||
Expr::Funcdef(
|
||||
vec![
|
||||
Stmt::BareExpr(Expr::Funcdef(
|
||||
Some("y".to_string()),
|
||||
Box::new(
|
||||
Expr::Mult(
|
||||
vec![
|
||||
Stmt::BareExpr(Expr::BinaryOp(
|
||||
"*".to_string(),
|
||||
Box::new(Expr::Id("x".to_string())),
|
||||
Box::new(Expr::Id("y".to_string())),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
))
|
||||
],
|
||||
))
|
||||
],
|
||||
)
|
||||
)
|
||||
),
|
||||
];
|
||||
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
|
||||
}
|
||||
@@ -333,34 +422,30 @@ else
|
||||
vec![
|
||||
GuardedBlock {
|
||||
guard: Expr::Id("foo".to_string()),
|
||||
block: Expr::Block(vec![Stmt::Funcall(Expr::Funcall("bar".to_string(), vec![]))])
|
||||
block: vec![Stmt::BareExpr(Expr::Funcall("bar".to_string(), vec![]))]
|
||||
},
|
||||
GuardedBlock {
|
||||
guard: Expr::Id("baz".to_string()),
|
||||
block: Expr::Block(vec![Stmt::Funcall(Expr::Funcall("foobar".to_string(), vec![]))])
|
||||
block: vec![Stmt::BareExpr(Expr::Funcall("foobar".to_string(), vec![]))],
|
||||
},
|
||||
],
|
||||
Some(Expr::Block(vec![Stmt::Funcall(Expr::Funcall("quux".to_string(), vec![]))])),
|
||||
Some(vec![Stmt::BareExpr(Expr::Funcall("quux".to_string(), vec![]))]),
|
||||
)];
|
||||
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
|
||||
}
|
||||
#[test]
|
||||
fn test_object() {
|
||||
let prgm = r"fruit <- {
|
||||
>>>apple <- 1
|
||||
pear <- 2
|
||||
<<<
|
||||
}";
|
||||
let expected = vec![Stmt::Assignment(
|
||||
"fruit".to_string(),
|
||||
Expr::Object(vec![
|
||||
Stmt::Assignment("apple".to_string(), Expr::Atom(Atom::Num(1.0))),
|
||||
Stmt::Assignment("pear".to_string(), Expr::Atom(Atom::Num(2.0))),
|
||||
]),
|
||||
)];
|
||||
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
|
||||
fn test_loop() {
|
||||
let prgm = r"loop until i > 100 a";
|
||||
let expected = vec![Stmt::Loop(Loop::Until(GuardedBlock {
|
||||
guard: Expr::BinaryOp(
|
||||
">".to_string(),
|
||||
Box::new(Expr::Id("i".to_string())),
|
||||
Box::new(Expr::Atom(Atom::Num(100.0))),
|
||||
),
|
||||
block: vec![Stmt::BareExpr(Expr::Id("a".to_string()))],
|
||||
}))];
|
||||
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_preprocess() {
|
||||
let prgm = r"
|
||||
|
||||
Reference in New Issue
Block a user