Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor to CalcitErr #104

Merged
merged 5 commits into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@

max_width = 120
max_width = 136
tab_spaces = 2
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "calcit_runner"
version = "0.5.0-a5"
version = "0.5.0-a6"
authors = ["jiyinyiyong <jiyinyiyong@gmail.com>"]
edition = "2018"
license = "MIT"
Expand All @@ -20,7 +20,7 @@ exclude = [
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
cirru_edn = "0.2.0-a1"
cirru_edn = "0.2.0"
cirru_parser = "0.1.8"
clap = "2.33.3"
dirs = "4.0.0"
Expand Down
4 changes: 2 additions & 2 deletions calcit/calcit.cirru

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion calcit/compact.cirru
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
defn demos () (echo "\"demo")
echo $ &+ 2 2
echo "\"f1" $ f1
echo-values 1 "\"1" :a $ [] 1 2
print-values 1 "\"1" :a $ [] 1 2
echo $ &{} :a 1 :b 2
echo $ #{} 1 2 3 |four
lib/f2
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@calcit/procs",
"version": "0.5.0-a5",
"version": "0.5.0-a6",
"main": "./lib/calcit.procs.js",
"devDependencies": {
"@types/node": "^16.9.6",
Expand Down
45 changes: 23 additions & 22 deletions src/bin/cr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() -> Result<(), String> {

// get dirty functions injected
#[cfg(not(target_arch = "wasm32"))]
builtins::register_import_proc("&call-dylib-edn", injection::call_dylib_edn);
injection::inject_platform_apis();

let cli_matches = cli_args::parse_cli();
let settings = ProgramSettings {
Expand Down Expand Up @@ -79,14 +79,8 @@ fn main() -> Result<(), String> {
}
}
}
let init_fn = cli_matches
.value_of("init-fn")
.or(Some(&snapshot.configs.init_fn))
.unwrap();
let reload_fn = cli_matches
.value_of("reload-fn")
.or(Some(&snapshot.configs.reload_fn))
.unwrap();
let init_fn = cli_matches.value_of("init-fn").or(Some(&snapshot.configs.init_fn)).unwrap();
let reload_fn = cli_matches.value_of("reload-fn").or(Some(&snapshot.configs.reload_fn)).unwrap();

// attach core
for (k, v) in core_snapshot.files {
Expand All @@ -104,7 +98,8 @@ fn main() -> Result<(), String> {
calcit_runner::primes::BUILTIN_CLASSES_ENTRY,
None,
check_warnings,
)?;
)
.map_err(|e| e.msg)?;

let task = if settings.emit_js {
run_codegen(init_fn, reload_fn, &program_code, &settings.emit_path, false)
Expand All @@ -113,7 +108,12 @@ fn main() -> Result<(), String> {
} else {
let started_time = Instant::now();

let v = calcit_runner::run_program(init_fn, im::vector![], &program_code)?;
let v = calcit_runner::run_program(init_fn, im::vector![], &program_code).map_err(|e| {
for w in e.warnings {
println!("{}", w);
}
e.msg
})?;

let duration = Instant::now().duration_since(started_time);
println!("took {}ms: {}", duration.as_micros() as f64 / 1000.0, v);
Expand Down Expand Up @@ -215,7 +215,12 @@ fn recall_program(
} else {
// run from `reload_fn` after reload
let started_time = Instant::now();
let v = calcit_runner::run_program(reload_fn, im::vector![], &new_code)?;
let v = calcit_runner::run_program(reload_fn, im::vector![], &new_code).map_err(|e| {
for w in e.warnings {
println!("{}", w);
}
e.msg
})?;
let duration = Instant::now().duration_since(started_time);
println!("took {}ms: {}", duration.as_micros() as f64 / 1000.0, v);
Ok(())
Expand Down Expand Up @@ -266,17 +271,16 @@ fn run_codegen(
Ok(_) => (),
Err(failure) => {
println!("\nfailed preprocessing, {}", failure);
call_stack::display_stack(&failure)?;
call_stack::display_stack(&failure.msg)?;

let _ = fs::write(
&js_file_path,
format!(
"export default \"Preprocessing failed:\\n{}\";",
failure.trim().escape_default()
failure.msg.trim().escape_default()
),
);

return Err(failure);
return Err(failure.msg);
}
}

Expand All @@ -285,8 +289,8 @@ fn run_codegen(
Ok(_) => (),
Err(failure) => {
println!("\nfailed preprocessing, {}", failure);
call_stack::display_stack(&failure)?;
return Err(failure);
call_stack::display_stack(&failure.msg)?;
return Err(failure.msg);
}
}
let warnings = check_warnings.to_owned().into_inner();
Expand All @@ -297,10 +301,7 @@ fn run_codegen(
content = format!("{}\n{}", content, message);
}

let _ = fs::write(
&js_file_path,
format!("export default \"{}\";", content.trim().escape_default()),
);
let _ = fs::write(&js_file_path, format!("export default \"{}\";", content.trim().escape_default()));
return Err(format!(
"Found {} warnings, codegen blocked. errors in {}.js",
warnings.len(),
Expand Down
38 changes: 30 additions & 8 deletions src/bin/injection/mod.rs
Original file line number Diff line number Diff line change
@@ -1,43 +1,65 @@
use cirru_edn::Edn;

use calcit_runner::{
builtins,
data::edn::{calcit_to_edn, edn_to_calcit},
primes::{Calcit, CalcitItems, CrListWrap},
primes::{Calcit, CalcitErr, CalcitItems, CrListWrap},
};

/// FFI protocol types
type EdnFfi = fn(args: Vec<Edn>) -> Result<Edn, String>;

pub fn inject_platform_apis() {
builtins::register_import_proc("&call-dylib-edn", call_dylib_edn);
builtins::register_import_proc("echo", echo);
builtins::register_import_proc("println", echo);
}

// &call-dylib-edn
pub fn call_dylib_edn(xs: &CalcitItems) -> Result<Calcit, String> {
pub fn call_dylib_edn(xs: &CalcitItems) -> Result<Calcit, CalcitErr> {
if xs.is_empty() {
return Err(format!(
return Err(CalcitErr::use_string(format!(
"&call-dylib-edn expected >2 arguments, got {}",
CrListWrap(xs.to_owned())
));
)));
}
let lib_name = if let Calcit::Str(s) = &xs[0] {
s.to_owned()
} else {
return Err(format!("&call-dylib-edn expected a lib_name, got {}", xs[0]));
return Err(CalcitErr::use_string(format!("&call-dylib-edn expected a lib_name, got {}", xs[0])));
};

let method: String = if let Calcit::Str(s) = &xs[1] {
s.to_owned()
} else {
return Err(format!("&call-dylib-edn expected a method name, got {}", xs[1]));
return Err(CalcitErr::use_string(format!(
"&call-dylib-edn expected a method name, got {}",
xs[1]
)));
};
let mut ys: Vec<Edn> = vec![];
for (idx, v) in xs.iter().enumerate() {
if idx > 1 {
ys.push(calcit_to_edn(v)?);
ys.push(calcit_to_edn(v).map_err(CalcitErr::use_string)?);
}
}

unsafe {
let lib = libloading::Library::new(&lib_name).expect("dylib not found");
let func: libloading::Symbol<EdnFfi> = lib.get(method.as_bytes()).expect("dy function not found");
let ret = func(ys.to_owned())?;
let ret = func(ys.to_owned()).map_err(CalcitErr::use_string)?;
Ok(edn_to_calcit(&ret))
}
}

pub fn echo(xs: &CalcitItems) -> Result<Calcit, CalcitErr> {
let mut s = String::from("");
for (idx, x) in xs.iter().enumerate() {
if idx > 0 {
s.push(' ');
}
s.push_str(&x.turn_string());
}
println!("{}", s);
Ok(Calcit::Nil)
}
16 changes: 5 additions & 11 deletions src/builtins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ mod syntax;
use std::collections::HashMap;
use std::sync::RwLock;

use crate::primes::{Calcit, CalcitItems, CalcitScope, CalcitSyntax};
use crate::primes::{Calcit, CalcitErr, CalcitItems, CalcitScope, CalcitSyntax};
use crate::program::ProgramCodeData;

pub type FnType = fn(xs: &CalcitItems) -> Result<Calcit, String>;
pub type FnType = fn(xs: &CalcitItems) -> Result<Calcit, CalcitErr>;

lazy_static! {
static ref IMPORTED_PROCS: RwLock<HashMap<String, FnType>> = RwLock::new(HashMap::new());
Expand Down Expand Up @@ -45,9 +45,6 @@ pub fn is_proc_name(s: &str) -> bool {
| "&tuple:assoc"
// effects
| "&display-stack"
| "echo"
| "println" // alias for echo
| "echo-values"
| "raise"
| "quit!"
| "get-env"
Expand Down Expand Up @@ -193,7 +190,7 @@ pub fn is_proc_name(s: &str) -> bool {
}
}

pub fn handle_proc(name: &str, args: &CalcitItems) -> Result<Calcit, String> {
pub fn handle_proc(name: &str, args: &CalcitItems) -> Result<Calcit, CalcitErr> {
match name {
// meta
"type-of" => meta::type_of(args),
Expand All @@ -214,9 +211,6 @@ pub fn handle_proc(name: &str, args: &CalcitItems) -> Result<Calcit, String> {
"&tuple:assoc" => meta::assoc(args),
// effects
"&display-stack" => meta::display_stack(args),
"echo" => effects::echo(args),
"println" => effects::echo(args), // alias
"echo-values" => effects::echo_values(args),
"raise" => effects::raise(args),
"quit!" => effects::quit(args),
"get-env" => effects::get_env(args),
Expand Down Expand Up @@ -359,7 +353,7 @@ pub fn handle_proc(name: &str, args: &CalcitItems) -> Result<Calcit, String> {
let f = ps[name];
f(args)
} else {
Err(format!("No such proc: {}", a))
Err(CalcitErr::use_string(format!("No such proc: {}", a)))
}
}
}
Expand All @@ -377,7 +371,7 @@ pub fn handle_syntax(
scope: &CalcitScope,
file_ns: &str,
program: &ProgramCodeData,
) -> Result<Calcit, String> {
) -> Result<Calcit, CalcitErr> {
match name {
CalcitSyntax::Defn => syntax::defn(nodes, scope, file_ns, program),
CalcitSyntax::Eval => syntax::eval(nodes, scope, file_ns, program),
Expand Down
Loading