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

15 changes: 12 additions & 3 deletions src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use crate::term::{
},
display::DisplayFn,
transform::{
encode_pattern_matching::MatchErr, resolve_refs::ReferencedMainErr, simplify_ref_to_ref::CyclicDefErr,
apply_args::ArgError, encode_pattern_matching::MatchErr, resolve_refs::ReferencedMainErr,
simplify_ref_to_ref::CyclicDefErr,
},
Name,
};
Expand Down Expand Up @@ -59,8 +60,8 @@ impl Info {
self.err_counter = 0;
}

/// Checks if any error was emitted since the start of the pass,
/// Returning all the current information as a `Err(Info)`, replacing `&mut self` with an empty one.
/// Checks if any error was emitted since the start of the pass,
/// Returning all the current information as a `Err(Info)`, replacing `&mut self` with an empty one.
/// Otherwise, returns the given arg as an `Ok(T)`.
pub fn fatal<T>(&mut self, t: T) -> Result<T, Info> {
if self.err_counter == 0 { Ok(t) } else { Err(std::mem::take(self)) }
Expand Down Expand Up @@ -110,6 +111,7 @@ pub enum Error {
EntryPoint(EntryErr),
TopLevel(TopLevelErr),
Custom(String),
ArgError(ArgError),
}

impl Display for Error {
Expand All @@ -129,6 +131,7 @@ impl Error {
Error::EntryPoint(err) => write!(f, "{err}"),
Error::TopLevel(err) => write!(f, "{err}"),
Error::Custom(err) => write!(f, "{err}"),
Error::ArgError(err) => write!(f, "{err}"),
})
}
}
Expand Down Expand Up @@ -175,6 +178,12 @@ impl From<TopLevelErr> for Error {
}
}

impl From<ArgError> for Error {
fn from(value: ArgError) -> Self {
Self::ArgError(value)
}
}

#[derive(Debug, Clone)]
pub enum Warning {
MatchOnlyVars(Name),
Expand Down
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.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 @@ pub enum EntryErr {
NotFound(Name),
Multiple(Vec<Name>),
MultipleRules,
Arguments,
}

impl Display for EntryErr {
Expand All @@ -23,13 +22,17 @@ 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."),
}
}
}

impl Ctx<'_> {
pub fn set_entrypoint(&mut self) {
// already set
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 @@ impl Ctx<'_> {
}

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
50 changes: 50 additions & 0 deletions src/term/transform/apply_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use std::fmt::Display;

use crate::{
diagnostics::Info,
term::{Ctx, Pattern, Term},
};

#[derive(Clone, Debug)]
pub enum ArgError {
PatternArgError,
ArityArgError { expected: usize, got: usize },
}

impl Display for ArgError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArgError::PatternArgError => write!(f, ""),
ArgError::ArityArgError { expected, got } => write!(f, "Expected {expected} arguments, got {got}."),
}
}
}

impl Ctx<'_> {
pub fn apply_args(&mut self, args: Option<Vec<Term>>) -> Result<(), Info> {
self.info.start_pass();

if let Some(entrypoint) = &self.book.entrypoint
&& let Some(args) = args
{
let main_def = &mut self.book.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(..)))) {
self.info.def_error(entrypoint.clone(), ArgError::PatternArgError);
}

if expected != got {
self.info.error(ArgError::ArityArgError { expected, got });
}

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

*main_body = Term::call(main_body.clone(), args);
}

self.info.fatal(())
}
}
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