Skip to content

Commit

Permalink
Merge pull request #15 from calcit-lang/update-bincode
Browse files Browse the repository at this point in the history
update bincode usage
  • Loading branch information
NoEgAm authored Jan 17, 2024
2 parents 24845c0 + 48c23d9 commit f8892ad
Show file tree
Hide file tree
Showing 16 changed files with 350 additions and 209 deletions.
14 changes: 7 additions & 7 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ jobs:
toolchain: nightly
components: clippy

- run: cargo run -- -s examples/hello.cirru
- run: cargo run -- -s examples/sum.cirru
- run: cargo run -- -s examples/assert.cirru
- run: cargo run -- -s examples/nested.cirru
- run: cargo run -- -s examples/named.cirru
- run: cargo run -- examples/recur.cirru
- run: cargo run -- --emit-binary target/a.calx examples/named.cirru && cargo run -- --eval-binary target/a.calx
- run: cargo run -- -s demos/hello.cirru
- run: cargo run -- -s demos/sum.cirru
- run: cargo run -- -s demos/assert.cirru
- run: cargo run -- -s demos/nested.cirru
- run: cargo run -- -s demos/named.cirru
- run: cargo run -- demos/recur.cirru
- run: cargo run -- --emit-binary target/a.calx demos/named.cirru && cargo run -- --eval-binary target/a.calx

# - run: cargo test

Expand Down
14 changes: 7 additions & 7 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@ jobs:
toolchain: nightly
components: clippy

- run: cargo run -- -s examples/hello.cirru
- run: cargo run -- -s examples/sum.cirru
- run: cargo run -- -s examples/assert.cirru
- run: cargo run -- -s examples/nested.cirru
- run: cargo run -- -s examples/named.cirru
- run: cargo run -- examples/recur.cirru
- run: cargo run -- --emit-binary target/a.calx examples/named.cirru && cargo run -- --eval-binary target/a.calx
- run: cargo run -- -s demos/hello.cirru
- run: cargo run -- -s demos/sum.cirru
- run: cargo run -- -s demos/assert.cirru
- run: cargo run -- -s demos/nested.cirru
- run: cargo run -- -s demos/named.cirru
- run: cargo run -- demos/recur.cirru
- run: cargo run -- --emit-binary target/a.calx demos/named.cirru && cargo run -- --eval-binary target/a.calx

- uses: giraffate/clippy-action@v1
with:
Expand Down
6 changes: 2 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "calx_vm"
version = "0.1.5"
version = "0.1.6"
authors = ["jiyinyiyong <[email protected]>"]
edition = "2021"
license = "MIT"
Expand All @@ -9,9 +9,7 @@ homepage = "https://github.com/calcit-lang/calx-vm"
documentation = "https://docs.rs/crate/calx_vm/"
repository = "https://github.com/calcit-lang/calx-vm.rs"
readme = "README.md"
exclude = [
"examples/*",
]
exclude = []

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ Calx Binary Edition `0.1`:
| `return` | | TODO |
| `fn $types $body` | | Global definition |
| `assert` | `quit(1)` if not `true` | for testing |
| `inspect | println inspection information | |

For `$types`, it can be `($t1 $t2 -> $t3 $t4)`, where supported types are:

Expand All @@ -146,6 +147,17 @@ For `$types`, it can be `($t1 $t2 -> $t3 $t4)`, where supported types are:
- list _TODO_
- link _TODO_

### Preprocess

Before Calx running the instructions, Calx performs preprocessing to them. There are several tasks:

- `block` and `loop` are expanded since there are `block-end` instructions
- `br` and `br-if` also expanded to `jmp` and `jmp-if` instructions, internally
- stack size is checked to ensure it's consistent among branches, and tidied up at function end
- local variables are renamed to indexes

these steps simplies debugging, although it's sure that's good features.

### License

MIT
File renamed without changes.
29 changes: 29 additions & 0 deletions demos/fibonacci.cirru
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

fn main ()
call fibo
const 34
echo

fn fibo (($x i64) -> i64)
block (->)
local.get $x
const 3
i.lt
br-if 0

local.get $x
const -1
i.add
call fibo

local.get $x
const -2
i.add
call fibo

i.add

return

const 1
return
File renamed without changes.
4 changes: 4 additions & 0 deletions examples/named.cirru → demos/named.cirru
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ fn f-add (($a i64) ($b i64) -> i64)
local.get $b
local.get $c
dup

inspect

echo
return

fn main ()
const 1
Expand Down
File renamed without changes.
File renamed without changes.
37 changes: 21 additions & 16 deletions examples/sum.cirru → demos/sum.cirru
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,48 @@ fn blocks (-> i64)
block (->) (br 0) (const 1.) (const 2.) (neg) (add) (echo)
, (const "|demo of string") (echo)
const 0
return

fn sum (-> i64)
local.new
block (-> i64)
const 0
local.set 0
const 0
loop (i64)
local.new $sum
const 0
local.set $sum

const 0
block (i64 -> i64)
loop (i64 -> i64)
;; "echo inspect i"
;; const |inspect
;; local.get $c
;; echo
;; dup
;; echo i

;; "i += 1"
;; "c += 1"
const 1
i.add

;; "acc += i"
dup
local.get 0

;; "acc += c"
local.get $sum
i.add
local.set 0
local.set $sum

;; "if >= 1M"
dup

;; "if >= 1M"
const 1000000
i.ge
br-if 1

br 0

drop
const "|check sum"

echo
local.get 0
const "|check sum"
local.get $sum
dup
echo
return

fn echos (-> i64)
const "|loading program"
Expand Down
14 changes: 14 additions & 0 deletions examples/fibo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//! fibonacci for comparisom
//! still orders in magnitude faster than Calx
fn fibo(n: i64) -> i64 {
if n < 3 {
1
} else {
fibo(n - 1) + fibo(n - 2)
}
}

fn main() {
println!("Result {}", fibo(40))
}
29 changes: 11 additions & 18 deletions src/bin/calx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use calx_vm::{log_calx_value, parse_function, Calx, CalxBinaryProgram, CalxFunc,
#[derive(Parser, Debug)]
#[command(name = "Calx VM")]
#[command(author = "Jon Chen <[email protected]>")]
#[command(version = "0.1.4")]
#[command(version = "0.1.6")]
#[command(about = "A toy VM", long_about = None)]
struct Args {
#[arg(short, long, value_name = "SHOW_CODE")]
Expand All @@ -20,6 +20,8 @@ struct Args {
disable_pre: bool,
#[arg(short, long, value_name = "EMIT_BINARY")]
emit_binary: Option<String>,
#[arg(short, long, value_name = "VERBOSE")]
verbose: bool,
#[arg(long, value_name = "EVAL_BINARY")]
eval_binary: bool,
#[arg(value_name = "SOURCE")]
Expand All @@ -38,7 +40,7 @@ fn main() -> Result<(), String> {
let mut fns: Vec<CalxFunc> = vec![];

if eval_binary {
let code = fs::read(source).expect("read binar from source file");
let code = fs::read(source).expect("read binary from source file");
let program: CalxBinaryProgram = bincode::decode_from_slice(&code, bincode::config::standard())
.expect("decode functions from binary")
.0;
Expand Down Expand Up @@ -66,26 +68,15 @@ fn main() -> Result<(), String> {
}

if emit_binary.is_some() {
let mut slice = [0u8; 10000];
let program = CalxBinaryProgram {
edition: CALX_BINARY_EDITION.to_string(),
fns,
};
let length = match bincode::encode_into_slice(&program, &mut slice, bincode::config::standard()) {
Ok(l) => {
println!("encoded binary length: {}", l);
l
}
Err(e) => panic!("failed on default length of 10000: {}", e),
};
let slice = &slice[..length];
let buf = bincode::encode_to_vec(program, bincode::config::standard()).map_err(|e| e.to_string())?;
let target_file = &emit_binary.unwrap();
match fs::write(target_file, slice) {
Ok(_) => println!("wrote binary to {}", target_file),
Err(e) => panic!("failed to write binary to {}: {}", target_file, e),
};
fs::write(target_file, buf).map_err(|e| e.to_string())?;
println!("wrote binary to {}", target_file);
return Ok(());
// println!("Bytes written: {:?}", slice);
}

let mut imports: CalxImportsDict = HashMap::new();
Expand All @@ -103,7 +94,8 @@ fn main() -> Result<(), String> {

let now = Instant::now();
if !disable_pre {
vm.preprocess()?;
println!("[calx] start preprocessing");
vm.preprocess(args.verbose)?;
} else {
println!("Preprocess disabled.")
}
Expand All @@ -114,11 +106,12 @@ fn main() -> Result<(), String> {
}
}

println!("[calx] start running");
match vm.run(vec![Calx::I64(1)]) {
Ok(ret) => {
let elapsed = now.elapsed();

println!("Took {:.3?}: {:?}", elapsed, ret);
println!("[calx] took {:.3?}: {:?}", elapsed, ret);
Ok(())
}
Err(e) => {
Expand Down
17 changes: 10 additions & 7 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

mod locals;

use std::rc::Rc;

use lazy_static::lazy_static;
use regex::Regex;

Expand Down Expand Up @@ -61,11 +63,11 @@ pub fn parse_function(nodes: &[Cirru]) -> Result<CalxFunc, String> {
}

Ok(CalxFunc {
name: name.to_string(),
params_types,
ret_types,
local_names: locals_collector.locals,
instrs: body,
name: Rc::new(name.to_string()),
params_types: params_types.into(),
ret_types: Rc::new(ret_types),
local_names: Rc::new(locals_collector.locals),
instrs: Rc::new(body),
})
}

Expand Down Expand Up @@ -257,6 +259,7 @@ pub fn parse_instr(ptr_base: usize, node: &Cirru, collector: &mut LocalsCollecto

Ok(vec![CalxInstr::Assert((*message).to_owned())])
}
"inspect" => Ok(vec![CalxInstr::Inspect]),
_ => Err(format!("unknown instruction: {}", name)),
},
}
Expand Down Expand Up @@ -345,8 +348,8 @@ pub fn parse_block(ptr_base: usize, xs: &[Cirru], looped: bool, collector: &mut
looped,
from: ptr_base + 1,
to: p,
params_types,
ret_types,
params_types: Rc::new(params_types),
ret_types: Rc::new(ret_types),
},
);
Ok(chunk)
Expand Down
Loading

0 comments on commit f8892ad

Please sign in to comment.