Compare commits
19 Commits
8259b57a46
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 7397ecc84b | |||
| b5ee47d2c8 | |||
| 782c1c93f0 | |||
| 488d7b1edb | |||
| f2b0e38464 | |||
| 1e2c107c1b | |||
| c29d463adf | |||
| 5f57c5aed3 | |||
| c345ac4fe5 | |||
| 7f241523d4 | |||
| 08cab74fb5 | |||
| c9295b5777 | |||
| 03b140189c | |||
| 7213f4a487 | |||
| 5fdd28fe0e | |||
| 74f1fdc5ea | |||
| 9291e65c11 | |||
| d0de70eb54 | |||
| 26bff70b1f |
14
dee-mode.el
14
dee-mode.el
@@ -2,12 +2,6 @@
|
|||||||
|
|
||||||
(add-to-list 'auto-mode-alist '("\\.dee\\'" . dee-mode))
|
(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
|
(defcustom dee-indent-offset 4
|
||||||
"Default indentation offset for Deelang."
|
"Default indentation offset for Deelang."
|
||||||
:group 'dee
|
:group 'dee
|
||||||
@@ -34,14 +28,14 @@
|
|||||||
(defvar dee-font-lock-keywords
|
(defvar dee-font-lock-keywords
|
||||||
`(,(rx symbol-start
|
`(,(rx symbol-start
|
||||||
(or
|
(or
|
||||||
"if" "elif" "else" "")
|
"if" "elif" "else" "loop" "until" "over" "in" "")
|
||||||
symbol-end)
|
symbol-end)
|
||||||
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "<-")
|
(,(rx (group (regexp dee-font-lock-id-re)) (* space) "<-")
|
||||||
(1 font-lock-variable-name-face))
|
(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) "(")
|
(,(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 ()
|
(defun dee-indent-line-function ()
|
||||||
'noindent) ;TODO
|
'noindent) ;TODO
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ fun <- ->
|
|||||||
do-something()
|
do-something()
|
||||||
do-something-else()
|
do-something-else()
|
||||||
|
|
||||||
|
|
||||||
foo <- ->
|
foo <- ->
|
||||||
bar <- ->
|
bar <- ->
|
||||||
baz <- ->
|
baz <- ->
|
||||||
@@ -11,8 +10,7 @@ foo <- ->
|
|||||||
|
|
||||||
foo() ## Inside foo but not in baz or bar
|
foo() ## Inside foo but not in baz or bar
|
||||||
|
|
||||||
add <- x -> y ->
|
add <- x -> y -> x + y ## Multivariable functions by currying
|
||||||
return x + y ## Multivariable functions by currying
|
|
||||||
|
|
||||||
add(x) ## Returns a _function_
|
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 <- ->
|
foo <- ->
|
||||||
bar()
|
bar()
|
||||||
baz()
|
baz()
|
||||||
## functions with block statements
|
# functions with block statements
|
||||||
foo <- x -> y -> x * y + 7 ## Multiple argument functions
|
foo <- x -> y -> x * y + 7 ## Multiple argument functions
|
||||||
if test?()
|
if test?()
|
||||||
do-something()
|
do-something()
|
||||||
@@ -24,8 +24,8 @@ else
|
|||||||
do-a-real-bad-thing()
|
do-a-real-bad-thing()
|
||||||
## Nested blocks
|
## Nested blocks
|
||||||
|
|
||||||
obj <- {
|
i <- 1
|
||||||
field <- "hello"
|
loop until i > 10
|
||||||
method <- x -> x * 2
|
print(i)
|
||||||
}
|
i <- 1
|
||||||
## Object creation
|
## 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(1 + 1) ## 2
|
||||||
print("Hello world!") ## Hello world
|
print("Hello world!") ## Hello world
|
||||||
|
|
||||||
name <- read()
|
|
||||||
print("Hi there $name") ## Hi there <name>
|
|
||||||
|
|
||||||
have <- 10
|
have <- 10
|
||||||
want <- 11
|
want <- 11
|
||||||
need <- have - want ## This is subtraction
|
need <- have - want ## This is subtraction
|
||||||
have-want <- 1 ## This is a variable named "have-want"
|
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 <- -> print("Hi from inside a function")
|
||||||
say-hi() ## Hi from inside a function
|
say-hi() ## Hi from inside a function
|
||||||
|
|
||||||
@@ -31,8 +18,8 @@ duck <- {
|
|||||||
eats? <- food -> food = "bread"
|
eats? <- food -> food = "bread"
|
||||||
} ## Objects created on the fly
|
} ## Objects created on the fly
|
||||||
|
|
||||||
print duck.eats?("bread") ## true
|
print(duck.eats?("bread")) ## true
|
||||||
print duck.eats?("corn") ## false
|
print(duck.eats?("corn")) ## false
|
||||||
|
|
||||||
cow <- {
|
cow <- {
|
||||||
talk <- print("Moo")
|
talk <- print("Moo")
|
||||||
@@ -43,11 +30,11 @@ human <- {
|
|||||||
eats? <- _ -> true
|
eats? <- _ -> true
|
||||||
}
|
}
|
||||||
|
|
||||||
print cow.eats?("grass") ## true
|
print(cow.eats?("grass")) ## true
|
||||||
print cow.eats?("corn") ## true
|
print(cow.eats?("corn")) ## true
|
||||||
|
|
||||||
talk-or-pass-wind <- character ->
|
talk-or-pass-wind <- character ->
|
||||||
if character has talk then
|
if character has talk
|
||||||
character.talk()
|
character.talk()
|
||||||
else
|
else
|
||||||
print("*Fart*")
|
print("*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 := ![_]
|
|
||||||
100
src/emitter.rs
100
src/emitter.rs
@@ -3,6 +3,10 @@ use std::collections::HashSet;
|
|||||||
|
|
||||||
use crate::parser;
|
use crate::parser;
|
||||||
|
|
||||||
|
fn munge(s: &str) -> String {
|
||||||
|
s.replace("?", "p").replace("-", "_")
|
||||||
|
}
|
||||||
|
|
||||||
pub struct LexicalContext<'a> {
|
pub struct LexicalContext<'a> {
|
||||||
parent: Option<&'a LexicalContext<'a>>,
|
parent: Option<&'a LexicalContext<'a>>,
|
||||||
local: HashSet<String>,
|
local: HashSet<String>,
|
||||||
@@ -17,12 +21,11 @@ impl <'a> LexicalContext<'a> {
|
|||||||
is_tail: false,
|
is_tail: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[allow(dead_code)]
|
|
||||||
fn new(parent: &'a LexicalContext<'a>) -> Self {
|
fn new(parent: &'a LexicalContext<'a>) -> Self {
|
||||||
LexicalContext {
|
LexicalContext {
|
||||||
parent: Some(parent),
|
parent: Some(parent),
|
||||||
local: HashSet::new(),
|
local: HashSet::new(),
|
||||||
is_tail: false,
|
is_tail: parent.is_tail,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn contains(&self, s: &str) -> bool {
|
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<()> {
|
/// Embeds the pre-written js
|
||||||
for stmt in ast {
|
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)?;
|
emit(w, stmt, ctx)?;
|
||||||
}
|
}
|
||||||
|
ctx.is_tail = is_tail;
|
||||||
|
emit(w, last, ctx)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||||
match &stmt {
|
match &stmt {
|
||||||
parser::Stmt::BareExpr(expr) => {
|
parser::Stmt::BareExpr(expr) => {
|
||||||
write!(w, "console.log((")?;
|
if ctx.is_tail {
|
||||||
|
write!(w, "return ")?;
|
||||||
|
}
|
||||||
emit_expr(w, expr, ctx)?;
|
emit_expr(w, expr, ctx)?;
|
||||||
writeln!(w, "));")?;
|
writeln!(w, ";")?;
|
||||||
}
|
}
|
||||||
parser::Stmt::Assignment(id, expr) => {
|
parser::Stmt::Assignment(id, expr) => {
|
||||||
if !ctx.contains(id) {
|
if !ctx.contains(id) {
|
||||||
ctx.insert(id.clone());
|
ctx.insert(id.clone());
|
||||||
write!(w, "let ")?;
|
write!(w, "let ")?;
|
||||||
}
|
}
|
||||||
write!(w, "{} = ", id)?;
|
write!(w, "{} = ", munge(id))?;
|
||||||
emit_expr(w, expr, ctx)?;
|
emit_expr(w, expr, ctx)?;
|
||||||
writeln!(w, ";")?;
|
writeln!(w, ";")?;
|
||||||
|
if ctx.is_tail {
|
||||||
|
writeln!(w, "return;")?;
|
||||||
}
|
}
|
||||||
parser::Stmt::Funcall(call) => {
|
|
||||||
emit_expr(w, call, ctx)?;
|
|
||||||
writeln!(w, ";")?;
|
|
||||||
}
|
}
|
||||||
parser::Stmt::Conditional(if_blocks, else_block) => {
|
parser::Stmt::Conditional(if_blocks, else_block) => {
|
||||||
let mut first_block = true;
|
let mut first_block = true;
|
||||||
@@ -66,7 +83,7 @@ pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) ->
|
|||||||
if first_block {
|
if first_block {
|
||||||
write!(w, "if (")?;
|
write!(w, "if (")?;
|
||||||
} else {
|
} else {
|
||||||
write!(w, " else if(")?;
|
write!(w, "else if(")?;
|
||||||
}
|
}
|
||||||
first_block = false;
|
first_block = false;
|
||||||
emit_expr(w, &if_block.guard, ctx)?;
|
emit_expr(w, &if_block.guard, ctx)?;
|
||||||
@@ -82,6 +99,36 @@ pub fn emit(w: &mut dyn Write, stmt: &parser::Stmt, ctx: &mut LexicalContext) ->
|
|||||||
writeln!(w, "}}")?;
|
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(())
|
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<()> {
|
pub fn emit_expr(w: &mut dyn Write, expr: &parser::Expr, ctx: &mut LexicalContext) -> std::io::Result<()> {
|
||||||
match &expr {
|
match &expr {
|
||||||
parser::Expr::Id(id) => {
|
parser::Expr::Id(id) => {
|
||||||
write!(w, "{}", id)?;
|
write!(w, "{}", munge(id))?;
|
||||||
}
|
}
|
||||||
parser::Expr::Atom(atom) => {
|
parser::Expr::Atom(atom) => {
|
||||||
write!(w, "{}", atom)?;
|
write!(w, "{}", atom)?;
|
||||||
}
|
}
|
||||||
parser::Expr::Funcall(id, args) => {
|
parser::Expr::Funcall(id, args) => {
|
||||||
write!(w, "{}", id)?;
|
write!(w, "{}", munge(id))?;
|
||||||
if args.is_empty() {
|
if args.is_empty() {
|
||||||
write!(w, "()")?;
|
write!(w, "()")?;
|
||||||
}
|
} else if ctx.contains(id) {
|
||||||
|
// Use deelang calling semantics
|
||||||
for arg in args {
|
for arg in args {
|
||||||
write!(w, "(")?;
|
write!(w, "(")?;
|
||||||
emit_expr(w, arg, ctx)?;
|
emit_expr(w, arg, ctx)?;
|
||||||
|
write!(w, ")")?
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Use JS calling semantics
|
||||||
|
write!(w, "(")?;
|
||||||
|
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, ")")?;
|
write!(w, ")")?;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
parser::Expr::Funcdef(arg, body) => {
|
parser::Expr::Funcdef(arg, body) => {
|
||||||
if let Some(arg) = arg {
|
if let Some(arg) = arg {
|
||||||
@@ -113,15 +173,19 @@ pub fn emit_expr(w: &mut dyn Write, expr: &parser::Expr, ctx: &mut LexicalContex
|
|||||||
}
|
}
|
||||||
let mut fun_ctx = LexicalContext::new(ctx);
|
let mut fun_ctx = LexicalContext::new(ctx);
|
||||||
fun_ctx.is_tail = true;
|
fun_ctx.is_tail = true;
|
||||||
emit_all(w, body.as_ref(), &mut fun_ctx)?;
|
emit_all(w, body, &mut fun_ctx)?;
|
||||||
write!(w, "}}")?;
|
write!(w, "}}")?;
|
||||||
}
|
}
|
||||||
parser::Expr::Plus(e1, e2) => {
|
parser::Expr::BinaryOp(op, e1, e2) => {
|
||||||
emit_expr(w, e1.as_ref(), ctx)?;
|
emit_expr(w, e1.as_ref(), ctx)?;
|
||||||
write!(w, " + ")?;
|
write!(w, " {} ", op)?;
|
||||||
emit_expr(w, e2.as_ref(), ctx)?;
|
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(())
|
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::BareExpr(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;
|
|
||||||
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 {
|
|
||||||
for stmt in block {
|
|
||||||
eval(stmt, 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 parser;
|
||||||
mod evaluator;
|
|
||||||
mod emitter;
|
mod emitter;
|
||||||
|
mod internal;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
|
|
||||||
@@ -10,54 +10,34 @@ use std::fs::File;
|
|||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[clap(author, version, about = "Interpreter for Deelang")]
|
#[clap(author, version, about = "Compiler for Deelang")]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[clap(help="Specify a file to run")]
|
#[clap(help="Specify a file to compile")]
|
||||||
file: Option<PathBuf>,
|
file: PathBuf,
|
||||||
#[clap(short, long, help="Only parse, do not evaluate")]
|
#[clap(short, long, help="Emit a parse tree")]
|
||||||
parse_only: bool,
|
parse: bool,
|
||||||
#[clap(short, long, help="Cross-compile to ECMAScript")]
|
#[clap(short, long, help="Cross compile to ECMAScript")]
|
||||||
ecmascript: bool,
|
ecmascript: bool,
|
||||||
}
|
#[clap(long, help="Run the preprocessor")]
|
||||||
|
preprocess: 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!();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
match cli.file {
|
let mut file = File::open(&cli.file).expect("Couldn't read file");
|
||||||
None => repl(&cli),
|
let mut prgm = String::new();
|
||||||
Some(_) => script(&cli),
|
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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
190
src/parser.rs
190
src/parser.rs
@@ -3,8 +3,8 @@ use std::fmt;
|
|||||||
#[derive(Debug,PartialEq,Clone)]
|
#[derive(Debug,PartialEq,Clone)]
|
||||||
pub enum Stmt {
|
pub enum Stmt {
|
||||||
Assignment(String, Expr),
|
Assignment(String, Expr),
|
||||||
Funcall(Expr),
|
|
||||||
Conditional(Vec<GuardedBlock>, Option<Block>),
|
Conditional(Vec<GuardedBlock>, Option<Block>),
|
||||||
|
Loop(Loop),
|
||||||
BareExpr(Expr),
|
BareExpr(Expr),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,11 +14,8 @@ pub enum Expr {
|
|||||||
Atom(Atom),
|
Atom(Atom),
|
||||||
Funcall(String, Vec<Expr>),
|
Funcall(String, Vec<Expr>),
|
||||||
Funcdef(Option<String>, Block),
|
Funcdef(Option<String>, Block),
|
||||||
UnaryMinus(Box<Expr>),
|
UnaryOp(String, Box<Expr>),
|
||||||
Plus(Box<Expr>, Box<Expr>),
|
BinaryOp(String, Box<Expr>, Box<Expr>),
|
||||||
Minus(Box<Expr>, Box<Expr>),
|
|
||||||
Mult(Box<Expr>, Box<Expr>),
|
|
||||||
Div(Box<Expr>, Box<Expr>),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Block = Vec<Stmt>;
|
pub type Block = Vec<Stmt>;
|
||||||
@@ -30,39 +27,41 @@ pub enum Atom {
|
|||||||
Bool(bool),
|
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)]
|
#[derive(Debug,PartialEq,Clone)]
|
||||||
pub struct GuardedBlock {
|
pub struct GuardedBlock {
|
||||||
pub guard: Expr,
|
pub guard: Expr,
|
||||||
pub block: Block,
|
pub block: Block,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug,PartialEq,Clone)]
|
||||||
|
pub enum Loop {
|
||||||
|
Bare(Block),
|
||||||
|
Until(GuardedBlock),
|
||||||
|
Over(String, Expr, Block),
|
||||||
|
}
|
||||||
|
|
||||||
peg::parser! {
|
peg::parser! {
|
||||||
grammar deelang_parser() for str {
|
grammar deelang_parser() for str {
|
||||||
pub rule program() -> Vec<Stmt>
|
pub rule program() -> Vec<Stmt>
|
||||||
= __* s:stmt()* { s }
|
= __* s:stmt()* { s }
|
||||||
pub rule stmt() -> Stmt
|
pub rule stmt() -> Stmt
|
||||||
= a:assignment() { a } /
|
= a:assignment() { a } /
|
||||||
f:funcall() stop() { Stmt::Funcall(f) } /
|
|
||||||
c:conditional() { c } /
|
c:conditional() { c } /
|
||||||
|
l:_loop() { Stmt::Loop(l) } /
|
||||||
e:expr() stop() { Stmt::BareExpr(e) }
|
e:expr() stop() { Stmt::BareExpr(e) }
|
||||||
rule expr() -> Expr = precedence! {
|
rule expr() -> Expr = precedence! {
|
||||||
"-" _ e1:@ { Expr::UnaryMinus(Box::new(e1)) }
|
e1:(@) "=" _ e2:@ { Expr::BinaryOp("=".to_string(), Box::new(e1), Box::new(e2))}
|
||||||
--
|
--
|
||||||
e1:(@) "+" _ e2:@ { Expr::Plus(Box::new(e1), Box::new(e2)) }
|
e1:(@) r:relop() e2:@ { Expr::BinaryOp(r, Box::new(e1), Box::new(e2)) }
|
||||||
e1:(@) "-" _ e2:@ { Expr::Minus(Box::new(e1), Box::new(e2)) }
|
|
||||||
--
|
--
|
||||||
e1:(@) "*" _ e2:@ { Expr::Mult(Box::new(e1), Box::new(e2)) }
|
"-" _ e1:@ { Expr::UnaryOp("-".to_string(), Box::new(e1)) }
|
||||||
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)) }
|
||||||
|
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 }
|
"(" _ e:expr() ")" _ { e }
|
||||||
['"'] s:$((!['"'] [_] / r#"\""#)*) ['"'] { Expr::Atom(Atom::String(s.to_string())) }
|
['"'] s:$((!['"'] [_] / r#"\""#)*) ['"'] { Expr::Atom(Atom::String(s.to_string())) }
|
||||||
@@ -80,14 +79,16 @@ peg::parser! {
|
|||||||
= i:$(letter() (letter() / digit() / ['?'|'.'|'-'])*) _ { i.to_string() }
|
= i:$(letter() (letter() / digit() / ['?'|'.'|'-'])*) _ { i.to_string() }
|
||||||
rule assignment() -> Stmt
|
rule assignment() -> Stmt
|
||||||
= i:id() "<-" _ e:expr() stop() { Stmt::Assignment(i, e) }
|
= i:id() "<-" _ e:expr() stop() { Stmt::Assignment(i, e) }
|
||||||
|
rule relop() -> String
|
||||||
|
= r:$("<" / ">" / "<=" / ">=") _ { r.to_string() }
|
||||||
rule num() -> f64
|
rule num() -> f64
|
||||||
= n:$(digit()+ "."? digit()* / "." digit()+) _ { n.parse().unwrap() }
|
= n:$(digit()+ "."? digit()* / "." digit()+) _ { n.parse().unwrap() }
|
||||||
rule funcall() -> Expr
|
rule funcall() -> Expr
|
||||||
= i:id() "(" _ e:(expr() ** ("," _)) ")" _ { Expr::Funcall(i, e) }
|
= i:id() "(" _ e:(expr() ** ("," _)) __* ")" _ { Expr::Funcall(i, e) }
|
||||||
rule funcdef() -> Expr
|
rule funcdef() -> Expr
|
||||||
= i:id()? "->" _ b:(block()) { Expr::Funcdef(i, b) }
|
= i:id()? "->" _ b:(block()) { Expr::Funcdef(i, b) }
|
||||||
rule conditional() -> Stmt
|
rule conditional() -> Stmt
|
||||||
= i:_if() __* ei:elif()* __* e:_else()? __* { Stmt::Conditional([vec![i], ei].concat(), e) }
|
= i:_if() __* ei:elif()* e:_else()? __* { Stmt::Conditional([vec![i], ei].concat(), e) }
|
||||||
rule _if() -> GuardedBlock
|
rule _if() -> GuardedBlock
|
||||||
= "if" _ g:expr() b:block() {
|
= "if" _ g:expr() b:block() {
|
||||||
GuardedBlock {
|
GuardedBlock {
|
||||||
@@ -96,7 +97,7 @@ peg::parser! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
rule elif() -> GuardedBlock
|
rule elif() -> GuardedBlock
|
||||||
= "elif" _ g:expr() b:block() {
|
= "elif" _ g:expr() b:block() __* {
|
||||||
GuardedBlock {
|
GuardedBlock {
|
||||||
guard: g,
|
guard: g,
|
||||||
block: b
|
block: b
|
||||||
@@ -104,6 +105,17 @@ peg::parser! {
|
|||||||
}
|
}
|
||||||
rule _else() -> Block
|
rule _else() -> Block
|
||||||
= "else" _ b:block() { b }
|
= "else" _ b:block() { b }
|
||||||
|
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
|
rule block() -> Block
|
||||||
= i:indented_block() { i } /
|
= i:indented_block() { i } /
|
||||||
e:expr() { vec![Stmt::BareExpr(e)] }
|
e:expr() { vec![Stmt::BareExpr(e)] }
|
||||||
@@ -133,7 +145,7 @@ peg::parser! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn preprocess(input: &str) -> String {
|
pub fn preprocess(input: &str) -> String {
|
||||||
let mut stack = vec![0];
|
let mut stack = vec![0];
|
||||||
let mut output = String::new();
|
let mut output = String::new();
|
||||||
for line in input.lines() {
|
for line in input.lines() {
|
||||||
@@ -166,6 +178,12 @@ fn preprocess(input: &str) -> String {
|
|||||||
output.push_str(line.trim());
|
output.push_str(line.trim());
|
||||||
output.push('\n');
|
output.push('\n');
|
||||||
}
|
}
|
||||||
|
while stack.len() > 1 {
|
||||||
|
// place any dedents needed to balance the program
|
||||||
|
output.push_str("<<<");
|
||||||
|
output.push('\n');
|
||||||
|
stack.pop();
|
||||||
|
}
|
||||||
output
|
output
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -174,9 +192,77 @@ pub fn parse(prgm: &str) -> Vec<Stmt> {
|
|||||||
deelang_parser::program(&prgm).unwrap()
|
deelang_parser::program(&prgm).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_stmt(stmt: &str) -> Stmt {
|
impl fmt::Display for Stmt {
|
||||||
let stmt = preprocess(stmt);
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
deelang_parser::stmt(&stmt).unwrap()
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -196,8 +282,8 @@ apple <- 1 ## This is too
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_funcall() {
|
fn test_funcall() {
|
||||||
let expected = vec![
|
let expected = vec![
|
||||||
Stmt::Funcall(Expr::Funcall("pear".to_string(), vec![])),
|
Stmt::BareExpr(Expr::Funcall("pear".to_string(), vec![])),
|
||||||
Stmt::Funcall(Expr::Funcall("pear".to_string(),
|
Stmt::BareExpr(Expr::Funcall("pear".to_string(),
|
||||||
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
||||||
))
|
))
|
||||||
];
|
];
|
||||||
@@ -230,18 +316,22 @@ one <- 3 - 2
|
|||||||
four <- (3 - 1) * 2";
|
four <- (3 - 1) * 2";
|
||||||
let expected = vec![
|
let expected = vec![
|
||||||
Stmt::Assignment("three".to_string(),
|
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(1.0))),
|
||||||
Box::new(Expr::Atom(Atom::Num(2.0))),
|
Box::new(Expr::Atom(Atom::Num(2.0))),
|
||||||
)),
|
)),
|
||||||
Stmt::Assignment("one".to_string(),
|
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(3.0))),
|
||||||
Box::new(Expr::Atom(Atom::Num(2.0))),
|
Box::new(Expr::Atom(Atom::Num(2.0))),
|
||||||
)),
|
)),
|
||||||
Stmt::Assignment("four".to_string(),
|
Stmt::Assignment("four".to_string(),
|
||||||
Expr::Mult(
|
Expr::BinaryOp(
|
||||||
Box::new(Expr::Minus(
|
"*".to_string(),
|
||||||
|
Box::new(Expr::BinaryOp(
|
||||||
|
"-".to_string(),
|
||||||
Box::new(Expr::Atom(Atom::Num(3.0))),
|
Box::new(Expr::Atom(Atom::Num(3.0))),
|
||||||
Box::new(Expr::Atom(Atom::Num(1.0))),
|
Box::new(Expr::Atom(Atom::Num(1.0))),
|
||||||
)),
|
)),
|
||||||
@@ -256,7 +346,8 @@ four <- (3 - 1) * 2";
|
|||||||
let prgm = "apple <- pear(x, y) + z";
|
let prgm = "apple <- pear(x, y) + z";
|
||||||
let expected = vec![
|
let expected = vec![
|
||||||
Stmt::Assignment("apple".to_string(),
|
Stmt::Assignment("apple".to_string(),
|
||||||
Expr::Plus(
|
Expr::BinaryOp(
|
||||||
|
"+".to_string(),
|
||||||
Box::new(Expr::Funcall(
|
Box::new(Expr::Funcall(
|
||||||
"pear".to_string(),
|
"pear".to_string(),
|
||||||
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
vec![Expr::Id("x".to_string()), Expr::Id("y".to_string())],
|
||||||
@@ -290,8 +381,8 @@ foo <- x -> y -> x * y";
|
|||||||
Expr::Funcdef(
|
Expr::Funcdef(
|
||||||
None,
|
None,
|
||||||
vec![
|
vec![
|
||||||
Stmt::Funcall(Expr::Funcall("bar".to_string(), vec![])),
|
Stmt::BareExpr(Expr::Funcall("bar".to_string(), vec![])),
|
||||||
Stmt::Funcall(Expr::Funcall("baz".to_string(), vec![])),
|
Stmt::BareExpr(Expr::Funcall("baz".to_string(), vec![])),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
),
|
),
|
||||||
@@ -303,7 +394,8 @@ foo <- x -> y -> x * y";
|
|||||||
Stmt::BareExpr(Expr::Funcdef(
|
Stmt::BareExpr(Expr::Funcdef(
|
||||||
Some("y".to_string()),
|
Some("y".to_string()),
|
||||||
vec![
|
vec![
|
||||||
Stmt::BareExpr(Expr::Mult(
|
Stmt::BareExpr(Expr::BinaryOp(
|
||||||
|
"*".to_string(),
|
||||||
Box::new(Expr::Id("x".to_string())),
|
Box::new(Expr::Id("x".to_string())),
|
||||||
Box::new(Expr::Id("y".to_string())),
|
Box::new(Expr::Id("y".to_string())),
|
||||||
))
|
))
|
||||||
@@ -330,18 +422,30 @@ else
|
|||||||
vec![
|
vec![
|
||||||
GuardedBlock {
|
GuardedBlock {
|
||||||
guard: Expr::Id("foo".to_string()),
|
guard: Expr::Id("foo".to_string()),
|
||||||
block: vec![Stmt::Funcall(Expr::Funcall("bar".to_string(), vec![]))]
|
block: vec![Stmt::BareExpr(Expr::Funcall("bar".to_string(), vec![]))]
|
||||||
},
|
},
|
||||||
GuardedBlock {
|
GuardedBlock {
|
||||||
guard: Expr::Id("baz".to_string()),
|
guard: Expr::Id("baz".to_string()),
|
||||||
block: vec![Stmt::Funcall(Expr::Funcall("foobar".to_string(), vec![]))],
|
block: vec![Stmt::BareExpr(Expr::Funcall("foobar".to_string(), vec![]))],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
Some(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);
|
assert_eq!(deelang_parser::program(prgm).unwrap(), expected);
|
||||||
}
|
}
|
||||||
|
#[test]
|
||||||
|
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]
|
#[test]
|
||||||
fn test_preprocess() {
|
fn test_preprocess() {
|
||||||
let prgm = r"
|
let prgm = r"
|
||||||
|
|||||||
Reference in New Issue
Block a user