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 4 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.

24 changes: 18 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,18 @@ pub fn create_host(book: Arc<Book>, labels: Arc<Labels>, compile_opts: CompileOp
pub fn check_book(book: &mut Book) -> Result<(), Info> {
// TODO: Do the checks without having to do full compilation
// TODO: Shouldn't the check mode show warnings?
compile_book(book, CompileOpts::light())?;
compile_book(book, None, CompileOpts::light())?;
Ok(())
}

pub fn compile_book(book: &mut Book, opts: CompileOpts) -> Result<CompileResult, Info> {
let warns = desugar_book(book, opts)?;
pub fn compile_book(
book: &mut Book,
args: Option<Vec<Term>>,
imaqtkatt marked this conversation as resolved.
Show resolved Hide resolved
opts: CompileOpts,
) -> Result<CompileResult, Info> {
let warns = desugar_book(book, args, 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 All @@ -112,11 +117,17 @@ pub fn compile_book(book: &mut Book, opts: CompileOpts) -> Result<CompileResult,
Ok(CompileResult { core_book, labels, warns })
}

pub fn desugar_book(book: &mut Book, opts: CompileOpts) -> Result<Vec<Warning>, Info> {
pub fn desugar_book(
book: &mut Book,
args: Option<Vec<Term>>,
imaqtkatt marked this conversation as resolved.
Show resolved Hide resolved
opts: CompileOpts,
) -> Result<Vec<Warning>, Info> {
let mut ctx = Ctx::new(book);

ctx.check_shared_names();
ctx.set_entrypoint();
ctx.set_entrypoint(if let Some(args) = &args { args.len() } else { 0 });

ctx.book.apply_args(args)?;

ctx.book.encode_adts(opts.adt_encoding);
ctx.book.encode_builtins();
Expand Down Expand Up @@ -184,8 +195,9 @@ 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 CompileResult { core_book, labels, warns } = compile_book(&mut book, compile_opts)?;
let CompileResult { core_book, labels, warns } = compile_book(&mut book, args, compile_opts)?;

// Turn the book into an Arc so that we can use it for logging, debugging, etc.
// from anywhere else in the program
Expand Down
14 changes: 11 additions & 3 deletions 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 @@ -192,7 +199,7 @@ fn execute_cli_mode(mut cli: Cli) -> Result<(), Info> {
}

let mut book = load_book(&path)?;
let compiled = compile_book(&mut book, opts)?;
let compiled = compile_book(&mut book, None, opts)?;
println!("{}", compiled.display_with_warns(warning_opts)?);
}
Mode::Desugar { path, comp_opts, lazy_mode } => {
Expand All @@ -202,7 +209,7 @@ fn execute_cli_mode(mut cli: Cli) -> Result<(), Info> {
}
let mut book = load_book(&path)?;
// TODO: Shouldn't the desugar have `warn_opts` too? maybe WarningOpts::allow_all() by default
let _warns = desugar_book(&mut book, opts)?;
let _warns = desugar_book(&mut book, None, opts)?;
println!("{}", book);
}
Mode::Run {
Expand All @@ -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
20 changes: 11 additions & 9 deletions src/term/check/set_entrypoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub enum EntryErr {
NotFound(Name),
Multiple(Vec<Name>),
MultipleRules,
Arguments,
Arguments(usize, usize),
}

impl Display for EntryErr {
Expand All @@ -23,19 +23,21 @@ impl Display for EntryErr {
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."),
EntryErr::Arguments(expected, got) => {
write!(f, "Main definition expects {expected} arguments, got {got}.")
}
}
}
}

impl Ctx<'_> {
pub fn set_entrypoint(&mut self) {
pub fn set_entrypoint(&mut self, given_arguments: usize) {
let mut entrypoint = None;

let (custom, main, hvm1_main) = self.book.get_possible_entry_points();
match (custom, main, hvm1_main) {
(Some(entry), None, None) | (None, Some(entry), None) | (None, None, Some(entry)) => {
match validate_entry_point(entry) {
match validate_entry_point(entry, given_arguments) {
Ok(name) => entrypoint = Some(name),
Err(err) => self.info.error(err),
}
Expand All @@ -44,7 +46,7 @@ impl Ctx<'_> {
(Some(a), Some(b), None) | (None, Some(a), Some(b)) | (Some(a), None, Some(b)) => {
self.info.error(EntryErr::Multiple(vec![a.name.clone(), b.name.clone()]));

match validate_entry_point(a) {
match validate_entry_point(a, given_arguments) {
Ok(name) => entrypoint = Some(name),
Err(err) => self.info.error(err),
}
Expand All @@ -53,7 +55,7 @@ impl Ctx<'_> {
(Some(a), Some(b), Some(c)) => {
self.info.error(EntryErr::Multiple(vec![a.name.clone(), b.name.clone(), c.name.clone()]));

match validate_entry_point(a) {
match validate_entry_point(a, given_arguments) {
Ok(name) => entrypoint = Some(name),
Err(err) => self.info.error(err),
}
Expand All @@ -68,11 +70,11 @@ impl Ctx<'_> {
}
}

fn validate_entry_point(entry: &Definition) -> Result<Name, EntryErr> {
fn validate_entry_point(entry: &Definition, given_arguments: usize) -> Result<Name, EntryErr> {
if entry.rules.len() > 1 {
Err(EntryErr::MultipleRules)
} else if !entry.rules[0].pats.is_empty() {
Err(EntryErr::Arguments)
} else if entry.rules[0].pats.len() != given_arguments {
Err(EntryErr::Arguments(entry.rules[0].pats.len(), given_arguments))
} else {
Ok(entry.name.clone())
}
Expand Down
21 changes: 21 additions & 0 deletions src/term/transform/apply_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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(main) = &self.entrypoint
&& let Some(args) = args
{
let main_def = &mut self.defs[main];

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

main_def.convert_match_def_to_term();
let main_body = &mut self.defs[main].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
Loading
Loading