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

[sc-483] Add an option to pass arguments to hvm-lang programs #217

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
52 changes: 26 additions & 26 deletions Cargo.lock

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

5 changes: 5 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ pub fn check_book(book: &mut Book) -> Result<(), Info> {
pub fn compile_book(book: &mut Book, opts: CompileOpts) -> Result<CompileResult, Info> {
let warns = desugar_book(book, opts)?;
let (nets, labels) = book_to_nets(book);

let mut core_book = nets_to_hvmc(nets)?;
if opts.pre_reduce {
pre_reduce_book(&mut core_book, book.hvmc_entrypoint())?;
Expand Down Expand Up @@ -184,7 +185,11 @@ pub fn run_book(
run_opts: RunOpts,
warning_opts: WarningOpts,
compile_opts: CompileOpts,
args: Option<Vec<Term>>,
developedby marked this conversation as resolved.
Show resolved Hide resolved
) -> Result<(Term, RunInfo), Info> {
let mut ctx = Ctx::new(&mut book);
ctx.set_entrypoint();
imaqtkatt marked this conversation as resolved.
Show resolved Hide resolved
ctx.book.apply_args(args)?;
let CompileResult { core_book, labels, warns } = compile_book(&mut book, compile_opts)?;

// Turn the book into an Arc so that we can use it for logging, debugging, etc.
Expand Down
10 changes: 9 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ enum Mode {
)]
comp_opts: Vec<OptArgs>,

#[arg(value_parser = |arg: &str| hvml::term::parser::parse_term(arg)
.map_err(|e| match e[0].reason() {
chumsky::error::RichReason::Many(errs) => format!("{}", &errs[0]),
_ => format!("{}", e[0].reason()),
}))]
arguments: Option<Vec<hvml::term::Term>>,

#[command(flatten)]
warn_opts: CliWarnOpts,
},
Expand Down Expand Up @@ -216,6 +223,7 @@ fn execute_cli_mode(mut cli: Cli) -> Result<(), Info> {
comp_opts,
warn_opts,
lazy_mode,
arguments,
} => {
if debug && lazy_mode {
return Err("Unsupported configuration, can not use debug mode `-d` with lazy mode `-L`".into());
Expand All @@ -235,7 +243,7 @@ fn execute_cli_mode(mut cli: Cli) -> Result<(), Info> {
let run_opts =
RunOpts { single_core, debug, linear, lazy_mode, max_memory: max_mem, max_rewrites: max_rwts };
let (res_term, RunInfo { stats, readback_errors, net, book: _, labels: _ }) =
run_book(book, max_mem as usize, run_opts, warning_opts, opts)?;
run_book(book, max_mem as usize, run_opts, warning_opts, opts, arguments)?;

let total_rewrites = stats.rewrites.total() as f64;
let rps = total_rewrites / stats.run_time / 1_000_000.0;
Expand Down
15 changes: 6 additions & 9 deletions src/term/check/set_entrypoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
NotFound(Name),
Multiple(Vec<Name>),
MultipleRules,
Arguments,
}

impl Display for EntryErr {
Expand All @@ -23,13 +22,17 @@
write!(f, "File has '{}', '{}' and '{}' definitions.", fnd[0], fnd[1], fnd[2])
}
EntryErr::MultipleRules => write!(f, "Main definition can't have more than one rule."),
EntryErr::Arguments => write!(f, "Main definition can't have any arguments."),
}
}
}

impl Ctx<'_> {
pub fn set_entrypoint(&mut self) {
// already setted

Check warning on line 31 in src/term/check/set_entrypoint.rs

View workflow job for this annotation

GitHub Actions / cspell

Unknown word (setted)
imaqtkatt marked this conversation as resolved.
Show resolved Hide resolved
if self.book.entrypoint.is_some() {
LunaAmora marked this conversation as resolved.
Show resolved Hide resolved
return;
}

let mut entrypoint = None;

let (custom, main, hvm1_main) = self.book.get_possible_entry_points();
Expand Down Expand Up @@ -69,13 +72,7 @@
}

fn validate_entry_point(entry: &Definition) -> Result<Name, EntryErr> {
if entry.rules.len() > 1 {
Err(EntryErr::MultipleRules)
} else if !entry.rules[0].pats.is_empty() {
Err(EntryErr::Arguments)
} else {
Ok(entry.name.clone())
}
if entry.rules.len() > 1 { Err(EntryErr::MultipleRules) } else { Ok(entry.name.clone()) }
}

impl Book {
Expand Down
27 changes: 27 additions & 0 deletions src/term/transform/apply_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use crate::term::{Book, Pattern, Term};

impl Book {
pub fn apply_args(&mut self, args: Option<Vec<Term>>) -> Result<(), String> {
imaqtkatt marked this conversation as resolved.
Show resolved Hide resolved
if let Some(entrypoint) = &self.entrypoint
&& let Some(args) = args
{
let main_def = &mut self.defs[entrypoint];
let expected = main_def.rules[0].pats.len();
let got = args.len();

if !main_def.rules[0].pats.iter().all(|pat| matches!(pat, Pattern::Var(Some(..)))) {
return Err("Definition '{entrypoint}' should contain only var patterns.".into());
}

if expected != got {
return Err(format!("Expected {expected} arguments, got {got}."));
}

main_def.convert_match_def_to_term();
let main_body = &mut self.defs[entrypoint].rule_mut().body;

*main_body = Term::call(main_body.clone(), args);
}
Ok(())
}
}
1 change: 1 addition & 0 deletions src/term/transform/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod apply_args;
pub mod definition_merge;
pub mod definition_pruning;
pub mod desugar_implicit_match_binds;
Expand Down
12 changes: 7 additions & 5 deletions tests/golden_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ fn linear_readback() {
RunOpts { linear: true, ..Default::default() },
WarningOpts::deny_all(),
CompileOpts::heavy(),
None,
)?;
Ok(format!("{}{}", display_readback_errors(&info.readback_errors), res))
});
Expand All @@ -143,14 +144,14 @@ fn run_file() {
let book = do_parse_book(code, path)?;
// 1 million nodes for the test runtime. Smaller doesn't seem to make it any faster
let (res, info) =
run_book(book, 1 << 24, RunOpts::lazy(), WarningOpts::deny_all(), CompileOpts::heavy())?;
run_book(book, 1 << 24, RunOpts::lazy(), WarningOpts::deny_all(), CompileOpts::heavy(), None)?;
Ok(format!("{}{}", display_readback_errors(&info.readback_errors), res))
}),
(&|code, path| {
let book = do_parse_book(code, path)?;
// 1 million nodes for the test runtime. Smaller doesn't seem to make it any faster
let (res, info) =
run_book(book, 1 << 24, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy())?;
run_book(book, 1 << 24, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy(), None)?;
Ok(format!("{}{}", display_readback_errors(&info.readback_errors), res))
}),
])
Expand All @@ -166,7 +167,7 @@ fn run_lazy() {
desugar_opts.lazy_mode();

// 1 million nodes for the test runtime. Smaller doesn't seem to make it any faster
let (res, info) = run_book(book, 1 << 24, run_opts, WarningOpts::deny_all(), desugar_opts)?;
let (res, info) = run_book(book, 1 << 24, run_opts, WarningOpts::deny_all(), desugar_opts, None)?;
Ok(format!("{}{}", display_readback_errors(&info.readback_errors), res))
})
}
Expand Down Expand Up @@ -273,7 +274,8 @@ fn hangs() {
let lck = Arc::new(RwLock::new(false));
let got = lck.clone();
std::thread::spawn(move || {
let _ = run_book(book, 1 << 20, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy());
let _ =
run_book(book, 1 << 20, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy(), None);
*got.write().unwrap() = true;
});
std::thread::sleep(std::time::Duration::from_secs(expected_normalization_time));
Expand All @@ -299,7 +301,7 @@ fn run_entrypoint() {
book.entrypoint = Some(Name::from("foo"));
// 1 million nodes for the test runtime. Smaller doesn't seem to make it any faster
let (res, info) =
run_book(book, 1 << 24, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy())?;
run_book(book, 1 << 24, RunOpts::default(), WarningOpts::deny_all(), CompileOpts::heavy(), None)?;
Ok(format!("{}{}", display_readback_errors(&info.readback_errors), res))
})
}
3 changes: 3 additions & 0 deletions tests/golden_tests/compile_file/add_args.hvm
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
add x y = (+ x y)

main x y = (add x y)
7 changes: 7 additions & 0 deletions tests/snapshots/compile_file__add_args.hvm.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
source: tests/golden_tests.rs
input_file: tests/golden_tests/compile_file/add_args.hvm
---
@add = (<+ a b> (a b))
@main = (a (b c))
& @add ~ (a (b c))
Loading