From 0ba4c0e9c52a1b794ddd8da07df7bbd341ac7bab Mon Sep 17 00:00:00 2001 From: arty Date: Thu, 4 Jan 2024 10:04:46 -0800 Subject: [PATCH] fmt --- src/classic/bins/shrink.rs | 6 +- src/classic/clvm_tools/cmds.rs | 11 +- src/compiler/codegen.rs | 130 +++----- src/compiler/compiler.rs | 210 ++++++------ src/compiler/comptypes.rs | 243 ++++++++------ src/compiler/evaluate.rs | 20 +- src/compiler/frontend.rs | 91 +++--- src/compiler/inline.rs | 6 +- src/compiler/mod.rs | 3 +- src/compiler/optimize/above22.rs | 15 +- src/compiler/optimize/mod.rs | 15 +- src/compiler/optimize/strategy.rs | 15 +- src/compiler/preprocessor/mod.rs | 399 ++++++++++++----------- src/compiler/rename.rs | 2 +- src/compiler/repl.rs | 6 +- src/compiler/resolve.rs | 368 +++++++++++---------- src/compiler/typechia.rs | 7 +- src/tests/classic/stage_2.rs | 8 +- src/tests/compiler/compiler.rs | 19 +- src/tests/compiler/evaluate.rs | 10 +- src/tests/compiler/modules.rs | 115 +++---- src/tests/compiler/optimizer/bodyform.rs | 10 +- src/tests/compiler/optimizer/output.rs | 8 +- src/tests/compiler/preprocessor.rs | 24 +- src/tests/compiler/types/chialisp.rs | 6 +- 25 files changed, 951 insertions(+), 796 deletions(-) diff --git a/src/classic/bins/shrink.rs b/src/classic/bins/shrink.rs index 6b8e3e2e..b03ae8e9 100644 --- a/src/classic/bins/shrink.rs +++ b/src/classic/bins/shrink.rs @@ -30,7 +30,11 @@ fn main() { .err_into() .and_then(|parsed_program| frontend(opts.clone(), &parsed_program)) .and_then(|program| { - let e = Evaluator::new(opts.clone(), runner.clone(), program.compileform().helpers.clone()); + let e = Evaluator::new( + opts.clone(), + runner.clone(), + program.compileform().helpers.clone(), + ); e.shrink_bodyform( &mut allocator, program.compileform().args.clone(), diff --git a/src/classic/clvm_tools/cmds.rs b/src/classic/clvm_tools/cmds.rs index 8e410a33..998e3383 100644 --- a/src/classic/clvm_tools/cmds.rs +++ b/src/classic/clvm_tools/cmds.rs @@ -658,7 +658,9 @@ pub fn cldb(args: &[String]) { &mut includes, ); if do_optimize { - unopt_res.and_then(|x| run_optimizer(&mut allocator, runner.clone(), Rc::new(x.to_sexp()))) + unopt_res.and_then(|x| { + run_optimizer(&mut allocator, runner.clone(), Rc::new(x.to_sexp())) + }) } else { unopt_res.map(|x| Rc::new(x.to_sexp())) } @@ -931,7 +933,8 @@ fn perform_preprocessing( let (stepping_form_text, parsed) = parse_module_and_get_sigil(opts.clone(), input_file, program_text)?; let frontend = frontend(opts, &parsed)?; - let whole_mod = render_mod_with_sigil(input_file, &stepping_form_text, &frontend.compileform())?; + let whole_mod = + render_mod_with_sigil(input_file, &stepping_form_text, &frontend.compileform())?; stdout.write_str(&format!("{}", whole_mod)); Ok(()) @@ -1429,8 +1432,8 @@ pub fn launch_tool(stdout: &mut Stream, args: &[String], tool_name: &str, defaul .and_then(|pre_forms| { let context = standard_type_context(); let compileform = frontend(opts.clone(), &pre_forms)?; - let target_type = - context.typecheck_chialisp_program(opts.clone(), &compileform.compileform())?; + let target_type = context + .typecheck_chialisp_program(opts.clone(), &compileform.compileform())?; Ok(context.reify(&target_type, None)) }) { diff --git a/src/compiler/codegen.rs b/src/compiler/codegen.rs index 18698b2a..f4087286 100644 --- a/src/compiler/codegen.rs +++ b/src/compiler/codegen.rs @@ -12,9 +12,9 @@ use crate::compiler::clvm::{run, truthy}; use crate::compiler::compiler::is_at_capture; use crate::compiler::comptypes::{ fold_m, join_vecs_to_string, list_to_cons, Binding, BindingPattern, BodyForm, CallSpec, - Callable, CompileErr, CompileForm, CompiledCode, CompilerOpts, CompilerOutput, ConstantKind, DefunCall, - DefunData, HelperForm, InlineFunction, LetData, LetFormInlineHint, LetFormKind, PrimaryCodegen, - RawCallSpec, SyntheticType, + Callable, CompileErr, CompileForm, CompiledCode, CompilerOpts, CompilerOutput, ConstantKind, + DefunCall, DefunData, HelperForm, InlineFunction, LetData, LetFormInlineHint, LetFormKind, + PrimaryCodegen, RawCallSpec, SyntheticType, }; use crate::compiler::debug::{build_swap_table_mut, relabel}; use crate::compiler::evaluate::{Evaluator, EVAL_STACK_LIMIT}; @@ -339,12 +339,10 @@ pub fn get_callable( } (_, _, _, _, true, _) => Ok(Callable::RunCompiler), (_, _, _, _, _, true) => Ok(Callable::EnvPath), - _ => { - Err(CompileErr( - l.clone(), - format!("no such callable '{}'", decode_string(name)), - )) - } + _ => Err(CompileErr( + l.clone(), + format!("no such callable '{}'", decode_string(name)), + )), } } SExp::Integer(_, v) => Ok(Callable::CallPrim(l.clone(), SExp::Integer(l, v.clone()))), @@ -641,21 +639,16 @@ fn compile_call( ); let mut unused_symbol_table = HashMap::new(); - let mut context_wrapper = CompileContextWrapper::from_context(context, &mut unused_symbol_table); - let code = - updated_opts - .compile_program( - &mut context_wrapper.context, - Rc::new(use_body), - )?; + let mut context_wrapper = + CompileContextWrapper::from_context(context, &mut unused_symbol_table); + let code = updated_opts + .compile_program(&mut context_wrapper.context, Rc::new(use_body))?; match code { - CompilerOutput::Program(code) => { - Ok(CompiledCode( - call.loc.clone(), - Rc::new(primquote(call.loc.clone(), Rc::new(code))), - )) - } + CompilerOutput::Program(code) => Ok(CompiledCode( + call.loc.clone(), + Rc::new(primquote(call.loc.clone(), Rc::new(code))), + )), CompilerOutput::Module(_) => { todo!(); } @@ -685,10 +678,7 @@ pub fn do_mod_codegen( // A mod form yields the compiled code. let without_env = opts.set_start_env(None).set_in_defun(false); let mut throwaway_symbols = HashMap::new(); - let mut context_wrapper = CompileContextWrapper::from_context( - context, - &mut throwaway_symbols, - ); + let mut context_wrapper = CompileContextWrapper::from_context(context, &mut throwaway_symbols); let code = codegen(&mut context_wrapper.context, without_env, program)?; Ok(CompiledCode( program.loc.clone(), @@ -914,28 +904,23 @@ fn codegen_( ); let mut unused_symbol_table = HashMap::new(); - let code = - { - let mut context_wrapper = CompileContextWrapper::from_context( - context, - &mut unused_symbol_table - ); - let code = - updated_opts - .compile_program( - &mut context_wrapper.context, - Rc::new(tocompile), - )?; - match code { - CompilerOutput::Program(p) => p, - CompilerOutput::Module(_) => { - todo!(); - } + let code = { + let mut context_wrapper = + CompileContextWrapper::from_context(context, &mut unused_symbol_table); + let code = updated_opts + .compile_program(&mut context_wrapper.context, Rc::new(tocompile))?; + match code { + CompilerOutput::Program(p) => p, + CompilerOutput::Module(_) => { + todo!(); } - }; + } + }; - let code = context.post_codegen_function_optimize(opts.clone(), Some(h), Rc::new(code))?; - let code = fail_if_present(defun.loc.clone(), &compiler.inlines, &defun.name, code)?; + let code = + context.post_codegen_function_optimize(opts.clone(), Some(h), Rc::new(code))?; + let code = + fail_if_present(defun.loc.clone(), &compiler.inlines, &defun.name, code)?; let code = fail_if_present(defun.loc.clone(), &compiler.defuns, &defun.name, code)?; return Ok(compiler.add_defun( &defun.name, @@ -1423,20 +1408,16 @@ fn start_codegen( let updated_opts = opts.set_code_generator(code_generator.clone()); let mut unused_symbols = HashMap::new(); let runner = context.runner(); - let mut context_wrapper = CompileContextWrapper::from_context( - context, - &mut unused_symbols - ); - let code = - match updated_opts.compile_program( - &mut context_wrapper.context, - Rc::new(expand_program), - )? { - CompilerOutput::Program(code) => code, - CompilerOutput::Module(_) => { - todo!(); - } - }; + let mut context_wrapper = + CompileContextWrapper::from_context(context, &mut unused_symbols); + let code = match updated_opts + .compile_program(&mut context_wrapper.context, Rc::new(expand_program))? + { + CompilerOutput::Program(code) => code, + CompilerOutput::Module(_) => { + todo!(); + } + }; run( context_wrapper.context.allocator(), @@ -1514,23 +1495,20 @@ fn start_codegen( let mut unused_symbols = HashMap::new(); let runner = context.runner(); - let mut context_wrapper = CompileContextWrapper::from_context( - context, - &mut unused_symbols - ); - let code = - match updated_opts.compile_program( - &mut context_wrapper.context, - macro_program, - )? { - CompilerOutput::Program(p) => p, - CompilerOutput::Module(_) => { - todo!(); - } - }; + let mut context_wrapper = + CompileContextWrapper::from_context(context, &mut unused_symbols); + let code = match updated_opts + .compile_program(&mut context_wrapper.context, macro_program)? + { + CompilerOutput::Program(p) => p, + CompilerOutput::Module(_) => { + todo!(); + } + }; - let optimized_code = - context_wrapper.context.macro_optimization(opts.clone(), Rc::new(code.clone()))?; + let optimized_code = context_wrapper + .context + .macro_optimization(opts.clone(), Rc::new(code.clone()))?; code_generator.add_macro(&mac.name, optimized_code) } diff --git a/src/compiler/compiler.rs b/src/compiler/compiler.rs index 35936edb..4d20f172 100644 --- a/src/compiler/compiler.rs +++ b/src/compiler/compiler.rs @@ -11,13 +11,19 @@ use crate::classic::clvm::__type_compatibility__::{bi_one, bi_zero, Stream}; use crate::classic::clvm::sexp::sexp_as_bin; use crate::classic::clvm_tools::stages::stage_0::TRunProgram; -use crate::compiler::clvm::{convert_to_clvm_rs, convert_from_clvm_rs, sha256tree}; +use crate::compiler::clvm::{convert_from_clvm_rs, convert_to_clvm_rs, sha256tree}; use crate::compiler::codegen::{codegen, hoist_body_let_binding, process_helper_let_bindings}; -use crate::compiler::comptypes::{BodyForm, CompileErr, CompileForm, CompilerOpts, CompilerOutput, CompileModuleComponent, CompileModuleOutput, DefunData, Export, FrontendOutput, HelperForm, IncludeDesc, PrimaryCodegen, SyntheticType}; +use crate::compiler::comptypes::{ + BodyForm, CompileErr, CompileForm, CompileModuleComponent, CompileModuleOutput, CompilerOpts, + CompilerOutput, DefunData, Export, FrontendOutput, HelperForm, IncludeDesc, PrimaryCodegen, + SyntheticType, +}; use crate::compiler::dialect::{AcceptedDialect, KNOWN_DIALECTS}; -use crate::compiler::frontend::{compile_bodyform, compile_helperform, frontend, match_export_form}; +use crate::compiler::frontend::{ + compile_bodyform, compile_helperform, frontend, match_export_form, +}; use crate::compiler::optimize::get_optimizer; -use crate::compiler::preprocessor::{Preprocessor, detect_chialisp_module}; +use crate::compiler::preprocessor::{detect_chialisp_module, Preprocessor}; use crate::compiler::prims; use crate::compiler::resolve::resolve_namespaces; use crate::compiler::sexp::{decode_string, enlist, parse_sexp, SExp}; @@ -188,19 +194,25 @@ struct ModuleOutputEntry { func: Rc, } -fn break_down_module_output(loc: Srcloc, run_result: Rc) -> Result, CompileErr> { - let list_data = - if let Some(lst) = run_result.proper_list() { - lst - } else { - return Err(CompileErr( - loc, - "output from intermediate module program should have been a proper list".to_string(), - )); - }; +fn break_down_module_output( + loc: Srcloc, + run_result: Rc, +) -> Result, CompileErr> { + let list_data = if let Some(lst) = run_result.proper_list() { + lst + } else { + return Err(CompileErr( + loc, + "output from intermediate module program should have been a proper list".to_string(), + )); + }; if list_data.len() % 2 != 0 { - return Err(CompileErr(loc, "output length from intermediate module program should have been divisible by 2".to_string())); + return Err(CompileErr( + loc, + "output length from intermediate module program should have been divisible by 2" + .to_string(), + )); } let mut result = Vec::new(); @@ -209,8 +221,8 @@ fn break_down_module_output(loc: Srcloc, run_result: Rc) -> Result) -> Result Result { let mut dir = PathBuf::from(file_path); - let mut filename = PathBuf::from(file_path).with_extension("").file_name().map(|f| { - f.to_string_lossy().to_string() - }).unwrap_or_else(|| "program".to_string()); + let mut filename = PathBuf::from(file_path) + .with_extension("") + .file_name() + .map(|f| f.to_string_lossy().to_string()) + .unwrap_or_else(|| "program".to_string()); dir.pop(); let func_dot_hex_list = &[func.to_string(), "hex".to_string()]; let func_dot_hex = func_dot_hex_list.join("."); @@ -233,7 +247,7 @@ fn create_hex_output_path(loc: Srcloc, file_path: &str, func: &str) -> Result> = program.helpers.iter().filter(|f| { - f.name() == &fun_name && matches!(f, HelperForm::Defun(_, _)) - }).cloned().map(Some).collect(); + let mut found_helper: Vec> = program + .helpers + .iter() + .filter(|f| f.name() == &fun_name && matches!(f, HelperForm::Defun(_, _))) + .cloned() + .map(Some) + .collect(); if found_helper.is_empty() { found_helper.push(None); @@ -353,42 +370,55 @@ pub fn compile_module( loc.clone(), vec![ Rc::new(BodyForm::Value(SExp::Atom(loc.clone(), b"c".to_vec()))), - Rc::new(BodyForm::Quoted(SExp::QuotedString(loc.clone(), b'"', fun_name.clone()))), + Rc::new(BodyForm::Quoted(SExp::QuotedString( + loc.clone(), + b'"', + fun_name.clone(), + ))), Rc::new(BodyForm::Call( loc.clone(), vec![ Rc::new(BodyForm::Value(SExp::Atom(loc.clone(), b"c".to_vec()))), Rc::new(BodyForm::Value(SExp::Atom(loc.clone(), fun_name.clone()))), - function_list + function_list, ], - None - )) + None, + )), ], - None + None, )); - program.helpers.push(HelperForm::Defun(false, DefunData { - loc: dd.loc.clone(), - kw: None, - nl: dd.nl.clone(), - name: new_name, - args: Rc::new(SExp::Nil(dd.loc.clone())), - orig_args: Rc::new(SExp::Nil(dd.loc.clone())), - body: Rc::new(BodyForm::Call( - dd.loc.clone(), - vec![ - Rc::new(BodyForm::Value(SExp::Atom(dd.loc.clone(), b"__chia__sha256tree".to_vec()))), - Rc::new(BodyForm::Value(SExp::Atom(dd.loc.clone(), fun_name.clone()))), - ], - None - )), - synthetic: Some(SyntheticType::WantNonInline), - ty: None, - })); + program.helpers.push(HelperForm::Defun( + false, + DefunData { + loc: dd.loc.clone(), + kw: None, + nl: dd.nl.clone(), + name: new_name, + args: Rc::new(SExp::Nil(dd.loc.clone())), + orig_args: Rc::new(SExp::Nil(dd.loc.clone())), + body: Rc::new(BodyForm::Call( + dd.loc.clone(), + vec![ + Rc::new(BodyForm::Value(SExp::Atom( + dd.loc.clone(), + b"__chia__sha256tree".to_vec(), + ))), + Rc::new(BodyForm::Value(SExp::Atom( + dd.loc.clone(), + fun_name.clone(), + ))), + ], + None, + )), + synthetic: Some(SyntheticType::WantNonInline), + ty: None, + }, + )); } else { return Err(CompileErr( loc.clone(), - format!("exported function {} not found", decode_string(&fun_name)) + format!("exported function {} not found", decode_string(&fun_name)), )); } } @@ -400,17 +430,15 @@ pub fn compile_module( let result_clvm = convert_to_clvm_rs(context.allocator(), compiled_result)?; let nil = context.allocator().null(); let runner = context.runner(); - let run_result_clvm = runner.run_program( - context.allocator(), - result_clvm, - nil, - None - ).map_err(|_| CompileErr(loc.clone(), "failed to run intermediate module program".to_string()))?; - let run_result = convert_from_clvm_rs( - context.allocator(), - loc.clone(), - run_result_clvm.1, - )?; + let run_result_clvm = runner + .run_program(context.allocator(), result_clvm, nil, None) + .map_err(|_| { + CompileErr( + loc.clone(), + "failed to run intermediate module program".to_string(), + ) + })?; + let run_result = convert_from_clvm_rs(context.allocator(), loc.clone(), run_result_clvm.1)?; // Components to use for the CompileModuleOutput, which downstream can be // collected for namespacing. @@ -423,31 +451,29 @@ pub fn compile_module( Rc::new(SExp::Cons( loc.clone(), Rc::new(SExp::Atom(loc.clone(), m.name.clone())), - Rc::new(SExp::QuotedString(loc.clone(), b'x', m.hash.clone())) + Rc::new(SExp::QuotedString(loc.clone(), b'x', m.hash.clone())), )), - Rc::new(prog_output) + Rc::new(prog_output), ); let mut stream = Stream::new(None); - let converted_func = convert_to_clvm_rs( - context.allocator(), - m.func.clone() - )?; + let converted_func = convert_to_clvm_rs(context.allocator(), m.func.clone())?; stream.write(sexp_as_bin(context.allocator(), converted_func)); - let output_path = create_hex_output_path(loc.clone(), &opts.filename(), &decode_string(&m.name))?; + let output_path = + create_hex_output_path(loc.clone(), &opts.filename(), &decode_string(&m.name))?; opts.write_new_file(&output_path, stream.get_value().hex().as_bytes())?; components.push(CompileModuleComponent { shortname: m.name.clone(), filename: output_path, content: m.func.clone(), - hash: m.hash + hash: m.hash, }); } Ok(CompileModuleOutput { summary: Rc::new(prog_output), - components + components, }) } @@ -459,9 +485,9 @@ pub fn compile_pre_forms( let p0 = frontend(opts.clone(), pre_forms)?; match p0 { - FrontendOutput::CompileForm(p0) => { - Ok(CompilerOutput::Program(compile_from_compileform(context, opts, p0)?)) - } + FrontendOutput::CompileForm(p0) => Ok(CompilerOutput::Program(compile_from_compileform( + context, opts, p0, + )?)), FrontendOutput::Module(cf, exports) => { // cl23 always reflects optimization. let dialect = opts.dialect(); @@ -471,7 +497,9 @@ pub fn compile_pre_forms( opts }; - Ok(CompilerOutput::Module(compile_module(context, opts, cf, &exports)?)) + Ok(CompilerOutput::Module(compile_module( + context, opts, cf, &exports, + )?)) } } } @@ -627,15 +655,15 @@ impl CompilerOpts for DefaultCompilerOpts { )) } - fn write_new_file( - &self, - target: &str, - content: &[u8] - ) -> Result<(), CompileErr> { + fn write_new_file(&self, target: &str, content: &[u8]) -> Result<(), CompileErr> { fs::write(target, content).map_err(|_| { CompileErr( Srcloc::start(&self.filename()), - format!("could not write output file {} for {}", target, self.filename()) + format!( + "could not write output file {} for {}", + target, + self.filename() + ), ) })?; Ok(()) diff --git a/src/compiler/comptypes.rs b/src/compiler/comptypes.rs index a0be9594..74669261 100644 --- a/src/compiler/comptypes.rs +++ b/src/compiler/comptypes.rs @@ -9,13 +9,13 @@ use clvm_rs::allocator::Allocator; use crate::classic::clvm::__type_compatibility__::{Bytes, BytesFromType}; use crate::classic::clvm_tools::stages::stage_0::TRunProgram; -use crate::compiler::BasicCompileContext; use crate::compiler::clvm::{sha256tree, truthy}; use crate::compiler::dialect::AcceptedDialect; use crate::compiler::sexp::{decode_string, enlist, SExp}; use crate::compiler::srcloc::Srcloc; use crate::compiler::typecheck::TheoryToSExp; use crate::compiler::types::ast::{Polytype, TypeVar}; +use crate::compiler::BasicCompileContext; use crate::util::Number; // Note: only used in tests, not normally dependencies. @@ -340,25 +340,32 @@ pub struct ImportLongName { #[derive(Debug, Clone)] pub enum LongNameTranslation { Namespace, - Filename(String) + Filename(String), } impl ImportLongName { pub fn parse(name: &[u8]) -> (bool, Self) { - let (relative, skip_words) = - if name.starts_with(b".") { - (true, 1) - } else { - (false, 0) - }; + let (relative, skip_words) = if name.starts_with(b".") { + (true, 1) + } else { + (false, 0) + }; - let components = name.split(|ch| *ch == b'.').skip(skip_words).map(|x| x.to_vec()).collect(); + let components = name + .split(|ch| *ch == b'.') + .skip(skip_words) + .map(|x| x.to_vec()) + .collect(); (relative, ImportLongName { components }) } pub fn as_u8_vec(&self, filename: LongNameTranslation) -> Vec { let mut result_vec = vec![]; - let sep = if matches!(filename, LongNameTranslation::Filename(_)) { b'/' } else { b'.' }; + let sep = if matches!(filename, LongNameTranslation::Filename(_)) { + b'/' + } else { + b'.' + }; for (i, c) in self.components.iter().enumerate() { if i != 0 { result_vec.push(sep); @@ -404,7 +411,12 @@ impl ImportLongName { } Some(ImportLongName { - components: self.components.iter().take(self.components.len()-1).cloned().collect() + components: self + .components + .iter() + .take(self.components.len() - 1) + .cloned() + .collect(), }) } @@ -414,9 +426,17 @@ impl ImportLongName { } if self.components.len() > 1 { - return (Some(ImportLongName { - components: self.components.iter().take(self.components.len()-1).cloned().collect() - }), self.components[self.components.len()-1].clone()); + return ( + Some(ImportLongName { + components: self + .components + .iter() + .take(self.components.len() - 1) + .cloned() + .collect(), + }), + self.components[self.components.len() - 1].clone(), + ); } (None, self.components[0].clone()) @@ -465,7 +485,7 @@ impl ModuleImportSpec { match self { ModuleImportSpec::Qualified(q) => q.nl.clone(), ModuleImportSpec::Exposing(e, _) => e.clone(), - ModuleImportSpec::Hiding(e, _) => e.clone() + ModuleImportSpec::Hiding(e, _) => e.clone(), } } @@ -473,7 +493,7 @@ impl ModuleImportSpec { loc: Srcloc, kw: Srcloc, forms: &[SExp], - mut skip: usize + mut skip: usize, ) -> Result { if skip >= forms.len() { return Ok(ModuleImportSpec::Hiding(loc, vec![])); @@ -481,46 +501,43 @@ impl ModuleImportSpec { // Figure out whether it's "import qualified" or // "import qualified foo as bar" - let (first_loc, first_atom) = - if let SExp::Atom(first_loc, first) = &forms[skip] { - (first_loc.clone(), first.clone()) - } else { - return Err(CompileErr( - forms[skip].loc(), - "import must be followed by a name or 'qualified'".to_string() - )); - }; + let (first_loc, first_atom) = if let SExp::Atom(first_loc, first) = &forms[skip] { + (first_loc.clone(), first.clone()) + } else { + return Err(CompileErr( + forms[skip].loc(), + "import must be followed by a name or 'qualified'".to_string(), + )); + }; if first_atom == b"qualified" { if forms.len() < 3 { return Err(CompileErr( loc.clone(), - "import qualified must be followed by a name".to_string() + "import qualified must be followed by a name".to_string(), )); } - let (second_loc, second_atom) = - if let SExp::Atom(second_loc, second) = &forms[2] { - (second_loc.clone(), second.clone()) - } else { - return Err(CompileErr( - forms[2].loc(), - "import qualified must be followed by a name".to_string() - )); - }; + let (second_loc, second_atom) = if let SExp::Atom(second_loc, second) = &forms[2] { + (second_loc.clone(), second.clone()) + } else { + return Err(CompileErr( + forms[2].loc(), + "import qualified must be followed by a name".to_string(), + )); + }; let (_, p) = ImportLongName::parse(&second_atom); if forms.len() == 5 { - let qname = - if let SExp::Atom(_, qname) = &forms[4] { - qname.clone() - } else { - return Err(CompileErr( - forms[4].loc(), - "import qualified ... as qname must be a name".to_string() - )); - }; + let qname = if let SExp::Atom(_, qname) = &forms[4] { + qname.clone() + } else { + return Err(CompileErr( + forms[4].loc(), + "import qualified ... as qname must be a name".to_string(), + )); + }; let (relative_qual, import_name) = ImportLongName::parse(&qname); @@ -534,7 +551,7 @@ impl ModuleImportSpec { nl: forms[4].loc(), relative: relative_qual, name: import_name, - }) + }), })); } else if forms.len() == 3 { return Ok(ModuleImportSpec::Qualified(QualifiedModuleInfo { @@ -555,16 +572,16 @@ impl ModuleImportSpec { if let SExp::Atom(kw_loc, kw) = &forms[skip] { let mut words = vec![]; - for atom in forms.iter().skip(skip+1) { + for atom in forms.iter().skip(skip + 1) { if let SExp::Atom(name_loc, name) = atom { words.push(ModuleImportListedName { nl: name_loc.clone(), - name: name.clone() + name: name.clone(), }); } else { return Err(CompileErr( atom.loc(), - "Exposed names must be atoms".to_string() + "Exposed names must be atoms".to_string(), )); } } @@ -586,21 +603,28 @@ impl ModuleImportSpec { ModuleImportSpec::Qualified(as_name) => { let mut result_vec = vec![ Rc::new(SExp::Atom(as_name.kw.clone(), b"qualified".to_vec())), - Rc::new(SExp::Atom(as_name.nl.clone(), as_name.name.as_u8_vec(LongNameTranslation::Namespace))), + Rc::new(SExp::Atom( + as_name.nl.clone(), + as_name.name.as_u8_vec(LongNameTranslation::Namespace), + )), ]; if let Some(target) = as_name.target.as_ref() { result_vec.push(Rc::new(SExp::Atom(target.kw.clone(), b"as".to_vec()))); - result_vec.push(Rc::new(SExp::Atom(target.nl.clone(), target.name.as_u8_vec(LongNameTranslation::Namespace)))); + result_vec.push(Rc::new(SExp::Atom( + target.nl.clone(), + target.name.as_u8_vec(LongNameTranslation::Namespace), + ))); } Rc::new(enlist(as_name.loc.clone(), &result_vec)) } ModuleImportSpec::Exposing(kl, exposed_names) => { - let mut result_vec = vec![ - Rc::new(SExp::Atom(kl.clone(), b"exposing".to_vec())), - ]; - result_vec.extend(exposed_names.iter().map(|e| { - Rc::new(SExp::Atom(e.nl.clone(), e.name.clone())) - }).collect::>>()); + let mut result_vec = vec![Rc::new(SExp::Atom(kl.clone(), b"exposing".to_vec()))]; + result_vec.extend( + exposed_names + .iter() + .map(|e| Rc::new(SExp::Atom(e.nl.clone(), e.name.clone()))) + .collect::>>(), + ); Rc::new(enlist(kl.clone(), &result_vec)) } // All but these names are in the toplevel namespace after the import. @@ -609,12 +633,13 @@ impl ModuleImportSpec { return Rc::new(SExp::Nil(kl.clone())); } - let mut result_vec = vec![ - Rc::new(SExp::Atom(kl.clone(), b"hiding".to_vec())), - ]; - result_vec.extend(hidden_names.iter().map(|e| { - Rc::new(SExp::Atom(e.nl.clone(), e.name.clone())) - }).collect::>>()); + let mut result_vec = vec![Rc::new(SExp::Atom(kl.clone(), b"hiding".to_vec()))]; + result_vec.extend( + hidden_names + .iter() + .map(|e| Rc::new(SExp::Atom(e.nl.clone(), e.name.clone()))) + .collect::>>(), + ); Rc::new(enlist(kl.clone(), &result_vec)) } } @@ -628,7 +653,7 @@ pub struct NamespaceData { pub nl: Srcloc, pub rendered_name: Vec, pub longname: ImportLongName, - pub helpers: Vec + pub helpers: Vec, } #[derive(Clone, Debug, Serialize)] @@ -638,7 +663,7 @@ pub struct NamespaceRefData { pub nl: Srcloc, pub rendered_name: Vec, pub longname: ImportLongName, - pub specification: ModuleImportSpec + pub specification: ModuleImportSpec, } /// HelperForm is a toplevel binding of some kind. @@ -665,20 +690,25 @@ pub enum HelperForm { fn test_helperform_import_qualified_0() { let srcloc = Srcloc::start("*test-import*"); let (_, name) = ImportLongName::parse(b"foo.bar"); - assert_eq!(HelperForm::Defnsref(NamespaceRefData { - loc: srcloc.clone(), - kw: srcloc.clone(), - nl: srcloc.clone(), - rendered_name: name.as_u8_vec(LongNameTranslation::Namespace), - longname: name.clone(), - specification: ModuleImportSpec::Qualified(QualifiedModuleInfo { + assert_eq!( + HelperForm::Defnsref(NamespaceRefData { loc: srcloc.clone(), - nl: srcloc.clone(), kw: srcloc.clone(), - name: name, - target: None, + nl: srcloc.clone(), + rendered_name: name.as_u8_vec(LongNameTranslation::Namespace), + longname: name.clone(), + specification: ModuleImportSpec::Qualified(QualifiedModuleInfo { + loc: srcloc.clone(), + nl: srcloc.clone(), + kw: srcloc.clone(), + name: name, + target: None, + }) }) - }).to_sexp().to_string(), "(import qualified foo.bar)"); + .to_sexp() + .to_string(), + "(import qualified foo.bar)" + ); } #[test] @@ -687,25 +717,30 @@ fn test_helperform_import_qualified_1() { let (_, name) = ImportLongName::parse(b"foo.bar"); let (relative, target) = ImportLongName::parse(b"FB"); - assert_eq!(HelperForm::Defnsref(NamespaceRefData { - loc: srcloc.clone(), - kw: srcloc.clone(), - nl: srcloc.clone(), - rendered_name: name.as_u8_vec(LongNameTranslation::Namespace), - longname: name.clone(), - specification: ModuleImportSpec::Qualified(QualifiedModuleInfo { + assert_eq!( + HelperForm::Defnsref(NamespaceRefData { loc: srcloc.clone(), - nl: srcloc.clone(), kw: srcloc.clone(), - name: name, - target: Some(QualifiedModuleInfoTarget { - kw: srcloc.clone(), + nl: srcloc.clone(), + rendered_name: name.as_u8_vec(LongNameTranslation::Namespace), + longname: name.clone(), + specification: ModuleImportSpec::Qualified(QualifiedModuleInfo { + loc: srcloc.clone(), nl: srcloc.clone(), - name: target, - relative + kw: srcloc.clone(), + name: name, + target: Some(QualifiedModuleInfoTarget { + kw: srcloc.clone(), + nl: srcloc.clone(), + name: target, + relative + }) }) }) - }).to_sexp().to_string(), "(import qualified foo.bar as FB)"); + .to_sexp() + .to_string(), + "(import qualified foo.bar as FB)" + ); } /// To what purpose is the file included. @@ -880,11 +915,7 @@ pub trait CompilerOpts { ) -> Result<(String, Vec), CompileErr>; /// Fully write a file to the filesystem. - fn write_new_file( - &self, - target_path: &str, - content: &[u8] - ) -> Result<(), CompileErr>; + fn write_new_file(&self, target_path: &str, content: &[u8]) -> Result<(), CompileErr>; /// Given a parsed SExp, compile it as an independent program based on the /// settings given here. The result is bare generated code. @@ -1142,21 +1173,17 @@ impl HelperForm { } HelperForm::Defnsref(defr) => { let tail = match &defr.specification { - ModuleImportSpec::Qualified(_q) => { - defr.specification.to_sexp() - } - _ => { - Rc::new(SExp::Cons( - defr.loc.clone(), - Rc::new(SExp::Atom(defr.nl.clone(), defr.rendered_name.clone())), - defr.specification.to_sexp() - )) - } + ModuleImportSpec::Qualified(_q) => defr.specification.to_sexp(), + _ => Rc::new(SExp::Cons( + defr.loc.clone(), + Rc::new(SExp::Atom(defr.nl.clone(), defr.rendered_name.clone())), + defr.specification.to_sexp(), + )), }; Rc::new(SExp::Cons( defr.loc.clone(), Rc::new(SExp::Atom(defr.loc.clone(), b"import".to_vec())), - tail + tail, )) } HelperForm::Defconstant(defc) => match defc.kind { @@ -1447,13 +1474,13 @@ pub struct CompileModuleComponent { #[derive(Debug, Clone, Serialize)] pub struct CompileModuleOutput { pub summary: Rc, - pub components: Vec + pub components: Vec, } #[derive(Debug, Clone, Serialize)] pub enum CompilerOutput { Program(SExp), - Module(CompileModuleOutput) + Module(CompileModuleOutput), } impl CompilerOutput { @@ -1484,7 +1511,7 @@ pub enum Export { #[derive(Debug, Clone, Serialize)] pub enum FrontendOutput { CompileForm(CompileForm), - Module(CompileForm, Vec) + Module(CompileForm, Vec), } impl FrontendOutput { diff --git a/src/compiler/evaluate.rs b/src/compiler/evaluate.rs index 2ae548e6..0329ee7d 100644 --- a/src/compiler/evaluate.rs +++ b/src/compiler/evaluate.rs @@ -12,8 +12,8 @@ use crate::compiler::clvm::run; use crate::compiler::codegen::{codegen, hoist_assign_form}; use crate::compiler::compiler::is_at_capture; use crate::compiler::comptypes::{ - Binding, BindingPattern, BodyForm, CallSpec, CompileErr, CompileForm, CompilerOpts, CompilerOutput, DefunData, - HelperForm, LambdaData, LetData, LetFormInlineHint, LetFormKind, + Binding, BindingPattern, BodyForm, CallSpec, CompileErr, CompileForm, CompilerOpts, + CompilerOutput, DefunData, HelperForm, LambdaData, LetData, LetFormInlineHint, LetFormKind, }; use crate::compiler::frontend::frontend; use crate::compiler::optimize::get_optimizer; @@ -783,7 +783,14 @@ impl<'info> Evaluator { )); let program = frontend(self.opts.clone(), &[frontend_macro_input])?; - self.shrink_bodyform_visited(allocator, visited, prog_args, env, program.compileform().exp.clone(), false) + self.shrink_bodyform_visited( + allocator, + visited, + prog_args, + env, + program.compileform().exp.clone(), + false, + ) } else { promote_program_to_bodyform( macro_expansion.to_sexp(), @@ -1668,13 +1675,10 @@ impl<'info> Evaluator { self.runner.clone(), &mut symbols, optimizer, - &mut includes + &mut includes, ); let com_result = - match updated_opts.compile_program( - &mut context_wrapper.context, - use_body, - )? { + match updated_opts.compile_program(&mut context_wrapper.context, use_body)? { CompilerOutput::Program(p) => p, CompilerOutput::Module(_) => { todo!(); diff --git a/src/compiler/frontend.rs b/src/compiler/frontend.rs index 658a49d4..723e795d 100644 --- a/src/compiler/frontend.rs +++ b/src/compiler/frontend.rs @@ -9,12 +9,15 @@ use num_bigint::ToBigInt; use crate::classic::clvm::__type_compatibility__::{bi_one, bi_zero}; use crate::compiler::comptypes::{ list_to_cons, ArgsAndTail, Binding, BindingPattern, BodyForm, ChiaType, CompileErr, - CompileForm, CompilerOpts, ConstantKind, DefconstData, DefmacData, DeftypeData, DefunData, Export, FrontendOutput, - HelperForm, ImportLongName, IncludeDesc, LetData, LetFormInlineHint, LetFormKind, LongNameTranslation, ModAccum, ModuleImportSpec, NamespaceData, NamespaceRefData, StructDef, - StructMember, SyntheticType, TypeAnnoKind, + CompileForm, CompilerOpts, ConstantKind, DefconstData, DefmacData, DeftypeData, DefunData, + Export, FrontendOutput, HelperForm, ImportLongName, IncludeDesc, LetData, LetFormInlineHint, + LetFormKind, LongNameTranslation, ModAccum, ModuleImportSpec, NamespaceData, NamespaceRefData, + StructDef, StructMember, SyntheticType, TypeAnnoKind, }; use crate::compiler::lambda::handle_lambda; -use crate::compiler::preprocessor::{detect_chialisp_module, parse_toplevel_mod, preprocess, Preprocessor, ToplevelModParseResult}; +use crate::compiler::preprocessor::{ + detect_chialisp_module, parse_toplevel_mod, preprocess, Preprocessor, ToplevelModParseResult, +}; use crate::compiler::rename::{rename_assign_bindings, rename_children_compileform}; use crate::compiler::sexp::{decode_string, enlist, SExp}; use crate::compiler::srcloc::{HasLoc, Srcloc}; @@ -947,10 +950,7 @@ pub fn augment_fun_type_with_args( } } -fn create_constructor_code( - sdef: &StructDef, - proto: Rc -) -> BodyForm { +fn create_constructor_code(sdef: &StructDef, proto: Rc) -> BodyForm { match proto.atomize() { SExp::Atom(l, n) => BodyForm::Value(SExp::Atom(l, n)), SExp::Cons(l, a, b) => BodyForm::Call( @@ -1149,7 +1149,7 @@ fn parse_chia_type(v: Vec) -> Result { pub fn match_export_form( opts: Rc, - form: Rc + form: Rc, ) -> Result, CompileErr> { if let Some(lst) = form.proper_list() { // Empty form isn't export @@ -1172,7 +1172,7 @@ pub fn match_export_form( let expr = compile_bodyform(opts.clone(), Rc::new(lst[2].clone()))?; return Ok(Some(Export::MainProgram( Rc::new(lst[1].clone()), - Rc::new(expr) + Rc::new(expr), ))); } @@ -1196,7 +1196,7 @@ impl HelperFormResult { pub fn new(helpers: &[HelperForm], ty: Option) -> Self { HelperFormResult { chia_type: ty, - new_helpers: helpers.iter().cloned().collect() + new_helpers: helpers.iter().cloned().collect(), } } } @@ -1204,18 +1204,20 @@ impl HelperFormResult { pub fn compile_namespace( opts: Rc, loc: Srcloc, - internal: &[SExp] + internal: &[SExp], ) -> Result { if internal.len() < 2 { return Err(CompileErr(loc, "Namespace must have a name".to_string())); } - let (_, parsed) = - if let SExp::Atom(_, name) = &internal[1] { - ImportLongName::parse(&name) - } else { - return Err(CompileErr(internal[1].loc(), "Namespace name must be an atom".to_string())); - }; + let (_, parsed) = if let SExp::Atom(_, name) = &internal[1] { + ImportLongName::parse(&name) + } else { + return Err(CompileErr( + internal[1].loc(), + "Namespace name must be an atom".to_string(), + )); + }; let mut helpers = Vec::new(); for sexp in internal.iter().skip(2) { @@ -1224,7 +1226,10 @@ pub fn compile_namespace( helpers.push(h.clone()); } } else { - return Err(CompileErr(sexp.loc(), "Namespaces must contain only definitions".to_string())); + return Err(CompileErr( + sexp.loc(), + "Namespaces must contain only definitions".to_string(), + )); } } @@ -1238,12 +1243,12 @@ pub fn compile_namespace( })) } -pub fn compile_nsref( - loc: Srcloc, - internal: &[SExp] -) -> Result { +pub fn compile_nsref(loc: Srcloc, internal: &[SExp]) -> Result { if internal.len() < 2 { - return Err(CompileErr(loc.clone(), "import must import a module".to_string())); + return Err(CompileErr( + loc.clone(), + "import must import a module".to_string(), + )); } let import_spec = ModuleImportSpec::parse(loc.clone(), internal[0].loc(), internal, 1)?; @@ -1254,16 +1259,18 @@ pub fn compile_nsref( nl: q.nl.clone(), rendered_name: q.name.as_u8_vec(LongNameTranslation::Namespace), longname: q.name.clone(), - specification: import_spec.clone() + specification: import_spec.clone(), })); } - let (_, parsed) = - if let SExp::Atom(_nl, name) = &internal[1] { - ImportLongName::parse(&name) - } else { - return Err(CompileErr(internal[1].loc(), "Import name must be an atom".to_string())); - }; + let (_, parsed) = if let SExp::Atom(_nl, name) = &internal[1] { + ImportLongName::parse(&name) + } else { + return Err(CompileErr( + internal[1].loc(), + "Import name must be an atom".to_string(), + )); + }; Ok(HelperForm::Defnsref(NamespaceRefData { loc, @@ -1271,7 +1278,7 @@ pub fn compile_nsref( nl: import_spec.name_loc(), rendered_name: parsed.as_u8_vec(LongNameTranslation::Namespace), longname: parsed, - specification: import_spec + specification: import_spec, })) } @@ -1412,7 +1419,7 @@ pub fn compile_helperform( } else { Err(CompileErr( matched.body.loc(), - format!("unknown keyword in helper {body}") + format!("unknown keyword in helper {body}"), )) } } else { @@ -1530,9 +1537,7 @@ fn frontend_start( tm.parsed_type, ) } - ToplevelModParseResult::Simple(t) => { - frontend_step_finish(opts.clone(), includes, &t) - } + ToplevelModParseResult::Simple(t) => frontend_step_finish(opts.clone(), includes, &t), } } @@ -1592,13 +1597,13 @@ pub fn frontend( let mut found_main = false; let mut preprocessor = Preprocessor::new(opts.clone()); - let output_forms = preprocessor.run_modules( - &mut includes, - pre_forms, - )?; + let output_forms = preprocessor.run_modules(&mut includes, pre_forms)?; if output_forms.forms.is_empty() { - return Err(CompileErr(Srcloc::start(&opts.filename()), "Module style chialisp programs require at least one export".to_string())); + return Err(CompileErr( + Srcloc::start(&opts.filename()), + "Module style chialisp programs require at least one export".to_string(), + )); } for form in output_forms.forms.iter() { @@ -1621,7 +1626,9 @@ pub fn frontend( ty: None, }; - let loc = output_forms.forms[0].loc().ext(&output_forms.forms[output_forms.forms.len()-1].loc()); + let loc = output_forms.forms[0] + .loc() + .ext(&output_forms.forms[output_forms.forms.len() - 1].loc()); return Ok(FrontendOutput::Module(program, exports)); } diff --git a/src/compiler/inline.rs b/src/compiler/inline.rs index ccb0f45d..d1460055 100644 --- a/src/compiler/inline.rs +++ b/src/compiler/inline.rs @@ -541,11 +541,7 @@ pub fn replace_in_inline( let mut symbols = HashMap::new(); let runner = context.runner(); let optimizer = context.optimizer.duplicate(); - let mut context_wrapper = - CompileContextWrapper::from_context( - context, - &mut symbols - ); + let mut context_wrapper = CompileContextWrapper::from_context(context, &mut symbols); generate_expr_code(&mut context_wrapper.context, opts, compiler, x) }) } diff --git a/src/compiler/mod.rs b/src/compiler/mod.rs index e94d2d3d..8164049c 100644 --- a/src/compiler/mod.rs +++ b/src/compiler/mod.rs @@ -44,7 +44,8 @@ use std::rc::Rc; use crate::classic::clvm_tools::stages::stage_0::TRunProgram; use crate::compiler::comptypes::{ - BodyForm, CompileErr, CompileForm, CompilerOpts, DefunData, HelperForm, IncludeDesc, PrimaryCodegen, + BodyForm, CompileErr, CompileForm, CompilerOpts, DefunData, HelperForm, IncludeDesc, + PrimaryCodegen, }; use crate::compiler::optimize::Optimization; use crate::compiler::sexp::SExp; diff --git a/src/compiler/optimize/above22.rs b/src/compiler/optimize/above22.rs index 9e7f3e99..b354ba7a 100644 --- a/src/compiler/optimize/above22.rs +++ b/src/compiler/optimize/above22.rs @@ -71,14 +71,13 @@ impl Optimization for Strategy23 { ) -> Result { let mut symbols = HashMap::new(); let mut includes = Vec::new(); - let mut wrapper = - CompileContextWrapper::new( - allocator, - runner, - &mut symbols, - self.duplicate(), - &mut includes, - ); + let mut wrapper = CompileContextWrapper::new( + allocator, + runner, + &mut symbols, + self.duplicate(), + &mut includes, + ); deinline_opt(&mut wrapper.context, opts.clone(), cf) } diff --git a/src/compiler/optimize/mod.rs b/src/compiler/optimize/mod.rs index d11bbcb8..37007db6 100644 --- a/src/compiler/optimize/mod.rs +++ b/src/compiler/optimize/mod.rs @@ -330,14 +330,13 @@ fn constant_fun_result( let mut symbols = HashMap::new(); let mut includes = Vec::new(); - let mut wrapper = - CompileContextWrapper::new( - allocator, - runner.clone(), - &mut symbols, - optimizer, - &mut includes, - ); + let mut wrapper = CompileContextWrapper::new( + allocator, + runner.clone(), + &mut symbols, + optimizer, + &mut includes, + ); if let Ok(code) = codegen(&mut wrapper.context, opts.clone(), &to_compile) { code } else { diff --git a/src/compiler/optimize/strategy.rs b/src/compiler/optimize/strategy.rs index 492b2523..d041db92 100644 --- a/src/compiler/optimize/strategy.rs +++ b/src/compiler/optimize/strategy.rs @@ -53,14 +53,13 @@ impl Optimization for ExistingStrategy { if opts.frontend_opt() && opts.dialect().stepping.map(|s| s > 22).unwrap_or(false) { let mut symbols = HashMap::new(); let mut includes = Vec::new(); - let mut wrapper = - CompileContextWrapper::new( - allocator, - runner, - &mut symbols, - self.duplicate(), - &mut includes - ); + let mut wrapper = CompileContextWrapper::new( + allocator, + runner, + &mut symbols, + self.duplicate(), + &mut includes, + ); deinline_opt(&mut wrapper.context, opts.clone(), cf) } else { Ok(cf) diff --git a/src/compiler/preprocessor/mod.rs b/src/compiler/preprocessor/mod.rs index 6f148236..16340dcd 100644 --- a/src/compiler/preprocessor/mod.rs +++ b/src/compiler/preprocessor/mod.rs @@ -15,10 +15,14 @@ use crate::compiler::clvm; use crate::compiler::clvm::{convert_from_clvm_rs, sha256tree, truthy}; use crate::compiler::compiler::{compile_from_compileform, compile_module, compile_pre_forms}; use crate::compiler::comptypes::{ - BodyForm, CompileErr, CompileForm, CompilerOpts, CompilerOutput, ConstantKind, DefconstData, HelperForm, ImportLongName, IncludeDesc, IncludeProcessType, LongNameTranslation, ModuleImportSpec, NamespaceData, NamespaceRefData, QualifiedModuleInfo, TypeAnnoKind, + BodyForm, CompileErr, CompileForm, CompilerOpts, CompilerOutput, ConstantKind, DefconstData, + HelperForm, ImportLongName, IncludeDesc, IncludeProcessType, LongNameTranslation, + ModuleImportSpec, NamespaceData, NamespaceRefData, QualifiedModuleInfo, TypeAnnoKind, +}; +use crate::compiler::dialect::{detect_modern, AcceptedDialect, KNOWN_DIALECTS}; +use crate::compiler::frontend::{ + augment_fun_type_with_args, compile_helperform, compile_nsref, frontend, }; -use crate::compiler::dialect::{AcceptedDialect, detect_modern, KNOWN_DIALECTS}; -use crate::compiler::frontend::{augment_fun_type_with_args, compile_helperform, compile_nsref, frontend}; use crate::compiler::optimize::get_optimizer; use crate::compiler::preprocessor::macros::PreprocessorExtension; use crate::compiler::rename::rename_args_helperform; @@ -28,8 +32,8 @@ use crate::compiler::sexp::{ decode_string, enlist, parse_sexp, Atom, First, NodeSel, SExp, SelectNode, ThisNode, }; use crate::compiler::srcloc::Srcloc; -use crate::compiler::types::ast::Polytype; use crate::compiler::typecheck::parse_type_sexp; +use crate::compiler::types::ast::Polytype; use crate::compiler::CompileContextWrapper; use crate::util::ErrInto; @@ -56,7 +60,7 @@ struct ImportNameMap { #[derive(Debug)] pub enum StoredMacro { Waiting(HelperForm), - Compiled(Rc) + Compiled(Rc), } pub struct Preprocessor { @@ -187,7 +191,7 @@ fn import_name_to_module_name( return Err(CompileErr( loc, - "Relative module name requested from a module entry file".to_string() + "Relative module name requested from a module entry file".to_string(), )); } @@ -202,7 +206,10 @@ fn make_namespace_container( ) -> Result, CompileErr> { let mut result_vec = vec![ Rc::new(SExp::Atom(loc.clone(), b"namespace".to_vec())), - Rc::new(SExp::Atom(nl.clone(), target.as_u8_vec(LongNameTranslation::Namespace))) + Rc::new(SExp::Atom( + nl.clone(), + target.as_u8_vec(LongNameTranslation::Namespace), + )), ]; result_vec.extend(helpers); Ok(Rc::new(enlist(loc.clone(), &result_vec))) @@ -221,14 +228,16 @@ fn make_namespace_ref( nl: nl.clone(), rendered_name: target.as_u8_vec(LongNameTranslation::Namespace), longname: target.clone(), - specification: spec.clone() + specification: spec.clone(), }) } -pub fn detect_chialisp_module( - pre_forms: &[Rc], -) -> Option { - let mut dialect = KNOWN_DIALECTS.get("*standard-cl-23*").unwrap().accepted.clone(); +pub fn detect_chialisp_module(pre_forms: &[Rc]) -> Option { + let mut dialect = KNOWN_DIALECTS + .get("*standard-cl-23*") + .unwrap() + .accepted + .clone(); if pre_forms.is_empty() { return None; @@ -236,16 +245,12 @@ pub fn detect_chialisp_module( if pre_forms.len() > 1 { for p in pre_forms.iter() { - if let Ok(NodeSel::Cons( - kl, - NodeSel::Cons( - (nl, name), - _ - ) - )) = NodeSel::Cons( + if let Ok(NodeSel::Cons(kl, NodeSel::Cons((nl, name), _))) = NodeSel::Cons( Atom::Here("include"), - NodeSel::Cons(Atom::Here(()), Atom::Here("")) - ).select_nodes(p.clone()) { + NodeSel::Cons(Atom::Here(()), Atom::Here("")), + ) + .select_nodes(p.clone()) + { if let Some(use_dialect) = KNOWN_DIALECTS.get(&decode_string(&name)) { return Some(use_dialect.accepted.clone()); } @@ -284,7 +289,7 @@ pub enum ToplevelModParseResult { pub fn parse_toplevel_mod( opts: Rc, - pre_forms: &[Rc] + pre_forms: &[Rc], ) -> Result { if pre_forms.is_empty() { return Err(CompileErr( @@ -379,26 +384,25 @@ impl Preprocessor { pub fn current_module_name(&self) -> Option { if self.namespace_stack.is_empty() { None - } else if let Some(name) = &self.namespace_stack[self.namespace_stack.len()-1].name { + } else if let Some(name) = &self.namespace_stack[self.namespace_stack.len() - 1].name { Some(name.clone()) } else { None } } - fn make_namespace_helper( - &self, - loc: &Srcloc, - name: &ImportLongName, - ) -> HelperForm { - let helpers = - if self.opts.stdenv() { - vec![ - make_namespace_ref(&loc, &loc, &loc, &ImportLongName::parse(b"std.prelude").1, &ModuleImportSpec::Hiding(loc.clone(), vec![])) - ] - } else { - vec![] - }; + fn make_namespace_helper(&self, loc: &Srcloc, name: &ImportLongName) -> HelperForm { + let helpers = if self.opts.stdenv() { + vec![make_namespace_ref( + &loc, + &loc, + &loc, + &ImportLongName::parse(b"std.prelude").1, + &ModuleImportSpec::Hiding(loc.clone(), vec![]), + )] + } else { + vec![] + }; HelperForm::Defnamespace(NamespaceData { loc: loc.clone(), @@ -416,7 +420,7 @@ impl Preprocessor { pub fn import_name_to_module_name( &self, loc: Srcloc, - name: &[u8] + name: &[u8], ) -> Result { let reference_name = self.current_module_name(); import_name_to_module_name(loc, reference_name.as_ref(), name) @@ -466,7 +470,7 @@ impl Preprocessor { includes: &mut Vec, _import_name: &ImportLongName, filename: &str, - content: &[u8] + content: &[u8], ) -> Result>, CompileErr> { let srcloc = Srcloc::start(filename); let mut allocator = Allocator::new(); @@ -479,10 +483,17 @@ impl Preprocessor { (true, dialect, allocator.null()) } else { let classic_parse = assemble(&mut allocator, &program_text).map_err(|_| { - CompileErr(srcloc.clone(), format!("Could not parse {filename} to determine dialect")) + CompileErr( + srcloc.clone(), + format!("Could not parse {filename} to determine dialect"), + ) })?; - (false, detect_modern(&mut allocator, classic_parse), classic_parse) + ( + false, + detect_modern(&mut allocator, classic_parse), + classic_parse, + ) }; let make_constant = |name: &[u8], s: SExp| { @@ -495,7 +506,8 @@ impl Preprocessor { tabled: true, ty: None, body: Rc::new(BodyForm::Quoted(s)), - }).to_sexp() + }) + .to_sexp() }; if !have_module { @@ -512,16 +524,16 @@ impl Preprocessor { &filename, true, ) - .map_err(|e| CompileErr(srcloc.clone(), format!("Subcompile failed: {}", e.1)))?; - let converted = convert_from_clvm_rs( - &mut allocator, - srcloc.clone(), - newly_compiled - )?; + .map_err(|e| CompileErr(srcloc.clone(), format!("Subcompile failed: {}", e.1)))?; + let converted = + convert_from_clvm_rs(&mut allocator, srcloc.clone(), newly_compiled)?; let converted_borrowed: &SExp = converted.borrow(); return Ok(vec![ make_constant(b"program", converted_borrowed.clone()), - make_constant(b"program_hash", SExp::QuotedString(srcloc.clone(), b'x', sha256tree(converted))) + make_constant( + b"program_hash", + SExp::QuotedString(srcloc.clone(), b'x', sha256tree(converted)), + ), ]); } } @@ -535,11 +547,7 @@ impl Preprocessor { includes, ); - match compile_pre_forms( - &mut context_wrapper.context, - self.opts.clone(), - &pre_forms - )? { + match compile_pre_forms(&mut context_wrapper.context, self.opts.clone(), &pre_forms)? { CompilerOutput::Module(module_output) => { let mut output = Vec::new(); for c in module_output.components.iter() { @@ -547,14 +555,24 @@ impl Preprocessor { output.push(make_constant(&c.shortname, borrowed_content.clone())); let mut hash_name = c.shortname.clone(); hash_name.extend(b"_hash".to_vec()); - output.push(make_constant(&hash_name, SExp::QuotedString(srcloc.clone(), b'x', c.hash.clone()))); + output.push(make_constant( + &hash_name, + SExp::QuotedString(srcloc.clone(), b'x', c.hash.clone()), + )); } return Ok(output); } CompilerOutput::Program(compile_output) => { return Ok(vec![ make_constant(b"program", compile_output.clone()), - make_constant(b"program_hash", SExp::QuotedString(srcloc.clone(), b'x', sha256tree(Rc::new(compile_output)))) + make_constant( + b"program_hash", + SExp::QuotedString( + srcloc.clone(), + b'x', + sha256tree(Rc::new(compile_output)), + ), + ), ]); } } @@ -564,14 +582,17 @@ impl Preprocessor { &mut self, loc: Srcloc, includes: &mut Vec, - import_name: &ImportLongName + import_name: &ImportLongName, ) -> Result>, CompileErr> { - let filename_clsp = decode_string(&import_name.as_u8_vec(LongNameTranslation::Filename(".clsp".to_string()))); - let filename_clinc = decode_string(&import_name.as_u8_vec(LongNameTranslation::Filename(".clinc".to_string()))); + let filename_clsp = decode_string( + &import_name.as_u8_vec(LongNameTranslation::Filename(".clsp".to_string())), + ); + let filename_clinc = decode_string( + &import_name.as_u8_vec(LongNameTranslation::Filename(".clinc".to_string())), + ); - if let Ok((full_name, content)) = self - .opts - .read_new_file(self.opts.filename(), filename_clsp) + if let Ok((full_name, content)) = + self.opts.read_new_file(self.opts.filename(), filename_clsp) { return self.import_program(includes, import_name, &full_name, &content); } @@ -586,7 +607,16 @@ impl Preprocessor { let mut out_forms = vec![]; if self.opts.stdenv() { - out_forms.push(make_namespace_ref(&loc, &loc, &loc, &ImportLongName::parse(b"std.prelude").1, &ModuleImportSpec::Hiding(loc.clone(), vec![])).to_sexp()); + out_forms.push( + make_namespace_ref( + &loc, + &loc, + &loc, + &ImportLongName::parse(b"std.prelude").1, + &ModuleImportSpec::Hiding(loc.clone(), vec![]), + ) + .to_sexp(), + ); } self.namespace_stack.push(ImportNameMap { @@ -611,7 +641,7 @@ impl Preprocessor { nl: Srcloc, includes: &mut Vec, spec: &ModuleImportSpec, - import_name: &[u8] + import_name: &[u8], ) -> Result>, CompileErr> { // The name of a module needs more processing. let full_import_name = self.import_name_to_module_name(loc.clone(), import_name)?; @@ -631,7 +661,7 @@ impl Preprocessor { let imported_content = self.import_new_module(loc.clone(), includes, &full_import_name)?; let helper_forms: Vec> = vec![ make_namespace_container(&loc, &nl, &full_import_name, imported_content)?, - ns_helper.to_sexp() + ns_helper.to_sexp(), ]; self.imported_modules.insert(full_import_name.clone()); @@ -663,44 +693,44 @@ impl Preprocessor { .opts .read_new_file(self.opts.filename(), fname.to_string())?; - let content = - if let IncludeProcessType::Bin = &kind { - Rc::new(SExp::Atom(loc.clone(), content)) - } else if let IncludeProcessType::Hex = &kind { - hex_to_modern_sexp( - &mut allocator, - &HashMap::new(), - loc.clone(), - &decode_string(&content), - ) - .map_err(run_to_compile_err)? - } else if let IncludeProcessType::Compiled = &kind { - let decoded_content = decode_string(&content); - let mut symtab = HashMap::new(); - let mut includes = Vec::new(); - let newly_compiled = compile_clvm_text_maybe_opt( - &mut allocator, - self.subcompile_opts.optimize(), - self.subcompile_opts.clone(), - &mut symtab, - &mut includes, - &decoded_content, - &full_name, - true, - ) - .map_err(|e| CompileErr(loc.clone(), format!("Subcompile failed: {}", e.1)))?; - - convert_from_clvm_rs(&mut allocator, loc.clone(), newly_compiled) - .map_err(run_to_compile_err)? - } else { // IncludeProcessType::SExpression - let parsed = parse_sexp(Srcloc::start(&full_name), content.iter().copied()) - .map_err(|e| CompileErr(e.0, e.1))?; - if parsed.len() != 1 { - return Err(CompileErr(loc, format!("More than one form in {fname}"))); - } + let content = if let IncludeProcessType::Bin = &kind { + Rc::new(SExp::Atom(loc.clone(), content)) + } else if let IncludeProcessType::Hex = &kind { + hex_to_modern_sexp( + &mut allocator, + &HashMap::new(), + loc.clone(), + &decode_string(&content), + ) + .map_err(run_to_compile_err)? + } else if let IncludeProcessType::Compiled = &kind { + let decoded_content = decode_string(&content); + let mut symtab = HashMap::new(); + let mut includes = Vec::new(); + let newly_compiled = compile_clvm_text_maybe_opt( + &mut allocator, + self.subcompile_opts.optimize(), + self.subcompile_opts.clone(), + &mut symtab, + &mut includes, + &decoded_content, + &full_name, + true, + ) + .map_err(|e| CompileErr(loc.clone(), format!("Subcompile failed: {}", e.1)))?; + + convert_from_clvm_rs(&mut allocator, loc.clone(), newly_compiled) + .map_err(run_to_compile_err)? + } else { + // IncludeProcessType::SExpression + let parsed = parse_sexp(Srcloc::start(&full_name), content.iter().copied()) + .map_err(|e| CompileErr(e.0, e.1))?; + if parsed.len() != 1 { + return Err(CompileErr(loc, format!("More than one form in {fname}"))); + } - parsed[0].clone() - }; + parsed[0].clone() + }; Ok(vec![compose_defconst(loc, constant_name, content)]) } @@ -713,12 +743,15 @@ impl Preprocessor { desc: IncludeDesc, ) -> Result<(), CompileErr> { // Process an import - let name_string = - if let Some(IncludeProcessType::Module(_)) = kind { - decode_string(&self.import_name_to_module_name(desc.nl.clone(), &desc.name)?.as_u8_vec(LongNameTranslation::Filename(".clinc".to_string()))) - } else { - decode_string(&desc.name) - }; + let name_string = if let Some(IncludeProcessType::Module(_)) = kind { + decode_string( + &self + .import_name_to_module_name(desc.nl.clone(), &desc.name)? + .as_u8_vec(LongNameTranslation::Filename(".clinc".to_string())), + ) + } else { + decode_string(&desc.name) + }; if KNOWN_DIALECTS.contains_key(&name_string) { return Ok(()); @@ -755,7 +788,9 @@ impl Preprocessor { return None; } - self.namespace_stack[self.namespace_stack.len()-1].name.clone() + self.namespace_stack[self.namespace_stack.len() - 1] + .name + .clone() } fn add_helper(&mut self, h: HelperForm) { @@ -777,60 +812,51 @@ impl Preprocessor { fn add_macro(&mut self, h: &HelperForm) { let current_module_name = self.current_module_name(); let (_, helper_name) = ImportLongName::parse(h.name()); - let full_name = - if let Some(module_name) = ¤t_module_name { - module_name.with_child(h.name()) - } else { - helper_name - }; - self.stored_macros.insert(full_name, StoredMacro::Waiting(h.clone())); + let full_name = if let Some(module_name) = ¤t_module_name { + module_name.with_child(h.name()) + } else { + helper_name + }; + self.stored_macros + .insert(full_name, StoredMacro::Waiting(h.clone())); self.add_helper(h.clone()); } - fn find_macro( - &mut self, - loc: Srcloc, - name: &[u8], - ) -> Result>, CompileErr> { + fn find_macro(&mut self, loc: Srcloc, name: &[u8]) -> Result>, CompileErr> { let mut allocator = Allocator::new(); let current_module_name = self.current_module_name(); let (_, parsed_name) = ImportLongName::parse(name); - let (parent_name, clean_last_name_component) = - parsed_name.parent_and_name(); + let (parent_name, clean_last_name_component) = parsed_name.parent_and_name(); let last_name_component = make_defmac_name(&clean_last_name_component); - let updated_name = - if let Some(parent) = &parent_name { - parent.with_child(&last_name_component) - } else { - let (_, parsed_name) = ImportLongName::parse(&last_name_component); - parsed_name - }; + let updated_name = if let Some(parent) = &parent_name { + parent.with_child(&last_name_component) + } else { + let (_, parsed_name) = ImportLongName::parse(&last_name_component); + parsed_name + }; let current_module_name_ref = current_module_name.as_ref().map(|n| n); - let found_name = - if let Some((tname, _helper)) = find_helper_target( - self.opts.clone(), - &self.prototype_program, - current_module_name_ref, - &clean_last_name_component, - &updated_name - ) { - if let Some(mac) = self.stored_macros.get_mut(&tname) { - match mac { - StoredMacro::Compiled(use_macro) => { - return Ok(Some(use_macro.clone())); - } - StoredMacro::Waiting(_h) => { - tname - } + let found_name = if let Some((tname, _helper)) = find_helper_target( + self.opts.clone(), + &self.prototype_program, + current_module_name_ref, + &clean_last_name_component, + &updated_name, + ) { + if let Some(mac) = self.stored_macros.get_mut(&tname) { + match mac { + StoredMacro::Compiled(use_macro) => { + return Ok(Some(use_macro.clone())); } - } else { - return Ok(None); + StoredMacro::Waiting(_h) => tname, } } else { return Ok(None); - }; + } + } else { + return Ok(None); + }; // as inline defuns because they're closest to that semantically. let optimizer = get_optimizer(&loc, self.opts.clone())?; @@ -859,7 +885,7 @@ impl Preprocessor { kw: loc.clone(), name: parent.clone(), target: None, - }) + }), })); } @@ -870,23 +896,26 @@ impl Preprocessor { helpers: main_helpers, exp: Rc::new(BodyForm::Call( loc.clone(), - vec![ - Rc::new(BodyForm::Value(SExp::Atom(loc.clone(), found_name.as_u8_vec(LongNameTranslation::Namespace)))) - ], - Some(Rc::new(BodyForm::Value(SExp::Atom(loc.clone(), b"__chia__arg".to_vec())))) + vec![Rc::new(BodyForm::Value(SExp::Atom( + loc.clone(), + found_name.as_u8_vec(LongNameTranslation::Namespace), + )))], + Some(Rc::new(BodyForm::Value(SExp::Atom( + loc.clone(), + b"__chia__arg".to_vec(), + )))), )), ty: None, }; let new_program = resolve_namespaces(self.opts.clone(), &starting_program)?; - let compiled_program = compile_from_compileform( - &mut wrapper.context, - self.opts.clone(), - new_program, - )?; - self.stored_macros - .insert(found_name.clone(), StoredMacro::Compiled(Rc::new(compiled_program.clone()))); + let compiled_program = + compile_from_compileform(&mut wrapper.context, self.opts.clone(), new_program)?; + self.stored_macros.insert( + found_name.clone(), + StoredMacro::Compiled(Rc::new(compiled_program.clone())), + ); return Ok(Some(Rc::new(compiled_program))); } @@ -931,8 +960,8 @@ impl Preprocessor { Some(ppext), None, ) - .map(nilize) - .map_err(CompileErr::from)?; + .map(nilize) + .map_err(CompileErr::from)?; if let Some(final_result) = self.expand_macros(res.clone(), true)? { return Ok(Some(final_result)); @@ -1002,25 +1031,28 @@ impl Preprocessor { Ok(None) } - fn parse_import(&mut self, loc: Srcloc, form: &[SExp]) -> Result, CompileErr> { + fn parse_import( + &mut self, + loc: Srcloc, + form: &[SExp], + ) -> Result, CompileErr> { if form.is_empty() { return Ok(None); } - let import = - if let SExp::Atom(_, name) = &form[0] { - if name != b"import" { - return Ok(None); - } + let import = if let SExp::Atom(_, name) = &form[0] { + if name != b"import" { + return Ok(None); + } - if let HelperForm::Defnsref(import) = compile_nsref(loc.clone(), form)? { - import - } else { - return Err(CompileErr(loc, "asked to parse import".to_string())); - } + if let HelperForm::Defnsref(import) = compile_nsref(loc.clone(), form)? { + import } else { - return Ok(None); - }; + return Err(CompileErr(loc, "asked to parse import".to_string())); + } + } else { + return Ok(None); + }; let mod_kind = IncludeProcessType::Module(import.specification.clone()); let fname = import.longname.as_u8_vec(LongNameTranslation::Namespace); @@ -1033,7 +1065,7 @@ impl Preprocessor { kind: Some(mod_kind.clone()), }, mod_kind, - fname.clone() + fname.clone(), ))) } @@ -1151,7 +1183,7 @@ impl Preprocessor { name: fname.clone(), }, IncludeProcessType::Compiled, - name.clone() + name.clone(), ))); } @@ -1201,11 +1233,11 @@ impl Preprocessor { if let Some(IncludeType::Basic(i)) = &included { self.recurse_dependencies(includes, None, i.clone())?; self.process_include(includes, i) - } else if let Some(IncludeType::Processed(f, IncludeProcessType::Module(spec), name)) = &included { + } else if let Some(IncludeType::Processed(f, IncludeProcessType::Module(spec), name)) = + &included + { if self.namespace_stack.is_empty() { - self.namespace_stack.push(ImportNameMap { - name: None, - }); + self.namespace_stack.push(ImportNameMap { name: None }); } self.import_module(body.loc(), f.kw.clone(), f.nl.clone(), includes, spec, name) } else if let Some(IncludeType::Processed(f, kind, name)) = &included { @@ -1257,10 +1289,7 @@ impl Preprocessor { )); } let m = self.run(includes, cmod)?; - Ok(PreprocessResult { - modules: true, - .. m - }) + Ok(PreprocessResult { modules: true, ..m }) } } diff --git a/src/compiler/rename.rs b/src/compiler/rename.rs index b37a925c..8366fe46 100644 --- a/src/compiler/rename.rs +++ b/src/compiler/rename.rs @@ -428,7 +428,7 @@ pub fn rename_args_helperform(h: &HelperForm) -> Result let renamed = map_m(rename_args_helperform, &ns.helpers)?; Ok(HelperForm::Defnamespace(NamespaceData { helpers: renamed, - .. ns.clone() + ..ns.clone() })) } HelperForm::Defnsref(_) => Ok(h.clone()), diff --git a/src/compiler/repl.rs b/src/compiler/repl.rs index 9aac54b8..11be2a21 100644 --- a/src/compiler/repl.rs +++ b/src/compiler/repl.rs @@ -133,7 +133,11 @@ impl Repl { )), ); let start_program_fe = frontend(opts.clone(), &[starter_empty_program]).unwrap(); - let evaluator = Evaluator::new(opts.clone(), runner.clone(), start_program_fe.compileform().helpers.clone()); + let evaluator = Evaluator::new( + opts.clone(), + runner.clone(), + start_program_fe.compileform().helpers.clone(), + ); Repl { depth: 0, diff --git a/src/compiler/resolve.rs b/src/compiler/resolve.rs index f8f5a898..bc6f13cd 100644 --- a/src/compiler/resolve.rs +++ b/src/compiler/resolve.rs @@ -5,8 +5,12 @@ use std::rc::Rc; use crate::compiler::codegen::toposort_assign_bindings; use crate::compiler::compiler::is_at_capture; -use crate::compiler::comptypes::{Binding, BindingPattern, BodyForm, CompileErr, CompileForm, CompilerOpts, DefconstData, DefmacData, DefunData, DeftypeData, HelperForm, ImportLongName, LambdaData, LetData, LetFormKind, LongNameTranslation, ModuleImportSpec, NamespaceData, map_m}; -use crate::compiler::frontend::{HelperFormResult, generate_type_helpers}; +use crate::compiler::comptypes::{ + map_m, Binding, BindingPattern, BodyForm, CompileErr, CompileForm, CompilerOpts, DefconstData, + DefmacData, DeftypeData, DefunData, HelperForm, ImportLongName, LambdaData, LetData, + LetFormKind, LongNameTranslation, ModuleImportSpec, NamespaceData, +}; +use crate::compiler::frontend::{generate_type_helpers, HelperFormResult}; use crate::compiler::sexp::{decode_string, SExp}; fn capture_scope(in_scope: &mut HashSet>, args: Rc) { @@ -23,25 +27,25 @@ fn capture_scope(in_scope: &mut HashSet>, args: Rc) { SExp::Atom(_, a) => { in_scope.insert(a.clone()); } - _ => { } + _ => {} } } pub struct FindNamespaceLookingAtHelpers<'a> { hlist: &'a [HelperForm], namespace: Option<&'a ImportLongName>, - offset: usize + offset: usize, } pub struct TourNamespaces<'a> { helpers: &'a [HelperForm], - look_stack: Vec> + look_stack: Vec>, } pub struct FoundHelper<'a> { pub helpers: &'a [HelperForm], pub namespace: Option<&'a ImportLongName>, - pub helper: &'a HelperForm + pub helper: &'a HelperForm, } impl<'a> Iterator for TourNamespaces<'a> { @@ -53,7 +57,7 @@ impl<'a> Iterator for TourNamespaces<'a> { return None; } - let ls_at = self.look_stack.len()-1; + let ls_at = self.look_stack.len() - 1; let ls_len = self.look_stack[ls_at].hlist.len(); if self.look_stack[ls_at].offset >= ls_len { @@ -77,41 +81,38 @@ impl<'a> Iterator for TourNamespaces<'a> { return Some(FoundHelper { helpers: self.helpers, namespace: self.look_stack[ls_at].namespace.clone(), - helper: current + helper: current, }); } } } -fn namespace_helper( - name: &ImportLongName, - value: &HelperForm -) -> HelperFormResult { +fn namespace_helper(name: &ImportLongName, value: &HelperForm) -> HelperFormResult { match value { - HelperForm::Defun(inline,dd) => { - HelperFormResult::new(&[ - HelperForm::Defun(*inline, DefunData { - name: name.as_u8_vec(LongNameTranslation::Namespace), - .. dd.clone() - }) - ], None) - } - HelperForm::Defconstant(dc) => { - HelperFormResult::new(&[ - HelperForm::Defconstant(DefconstData { + HelperForm::Defun(inline, dd) => HelperFormResult::new( + &[HelperForm::Defun( + *inline, + DefunData { name: name.as_u8_vec(LongNameTranslation::Namespace), - .. dc.clone() - }) - ], None) - } - HelperForm::Defmacro(dm) => { - HelperFormResult::new(&[ - HelperForm::Defmacro(DefmacData { - name: name.as_u8_vec(LongNameTranslation::Namespace), - .. dm.clone() - }) - ], None) - } + ..dd.clone() + }, + )], + None, + ), + HelperForm::Defconstant(dc) => HelperFormResult::new( + &[HelperForm::Defconstant(DefconstData { + name: name.as_u8_vec(LongNameTranslation::Namespace), + ..dc.clone() + })], + None, + ), + HelperForm::Defmacro(dm) => HelperFormResult::new( + &[HelperForm::Defmacro(DefmacData { + name: name.as_u8_vec(LongNameTranslation::Namespace), + ..dm.clone() + })], + None, + ), HelperForm::Deftype(ty) => { let new_helpers = generate_type_helpers(&ty.parsed); let mut result_helpers = Vec::new(); @@ -127,20 +128,18 @@ fn namespace_helper( } HelperFormResult::new(&result_helpers, None) } - _ => HelperFormResult::new(&[value.clone()], None) + _ => HelperFormResult::new(&[value.clone()], None), } } -pub fn tour_helpers<'a>( - helpers: &'a [HelperForm], -) -> TourNamespaces<'a> { +pub fn tour_helpers<'a>(helpers: &'a [HelperForm]) -> TourNamespaces<'a> { TourNamespaces { helpers, look_stack: vec![FindNamespaceLookingAtHelpers { hlist: &helpers, namespace: None, offset: 0, - }] + }], } } @@ -149,7 +148,7 @@ pub fn find_helper_target<'a>( helpers: &'a [HelperForm], parent_ns: Option<&ImportLongName>, orig_name: &[u8], - name: &ImportLongName + name: &ImportLongName, ) -> Option<(ImportLongName, HelperForm)> { // XXX speed this up, remove iteration. // Decompose into parent and child. @@ -157,9 +156,10 @@ pub fn find_helper_target<'a>( // Get a list namespace refs from the namespace identified by parent_ns. let tour_helpers: Vec = tour_helpers(&helpers).collect(); - let home_ns: Vec<&FoundHelper> = tour_helpers.iter().filter(|found| { - found.namespace == parent_ns - }).collect(); + let home_ns: Vec<&FoundHelper> = tour_helpers + .iter() + .filter(|found| found.namespace == parent_ns) + .collect(); // check the matching namespace to the one specified to see if we can find the // target. @@ -180,13 +180,12 @@ pub fn find_helper_target<'a>( } } if h.helper.name() == &child { - let combined = - if let Some(p) = parent_ns { - p.with_child(&child) - } else { - let (_, p) = ImportLongName::parse(&child); - p - }; + let combined = if let Some(p) = parent_ns { + p.with_child(&child) + } else { + let (_, p) = ImportLongName::parse(&child); + p + }; return Some((combined, h.helper.clone())); } } @@ -226,7 +225,7 @@ pub fn find_helper_target<'a>( helpers, Some(&ns_spec.longname), orig_name, - &target_name + &target_name, ) { return Some(helper.clone()); } @@ -282,7 +281,10 @@ pub fn find_helper_target<'a>( fn display_namespace(parent_ns: Option<&ImportLongName>) -> String { if let Some(p) = parent_ns { - format!("namespace {}", decode_string(&p.as_u8_vec(LongNameTranslation::Namespace))) + format!( + "namespace {}", + decode_string(&p.as_u8_vec(LongNameTranslation::Namespace)) + ) } else { "the root module".to_string() } @@ -297,18 +299,16 @@ fn add_binding_names(bindings: &mut HashSet>, pattern: &BindingPattern) BindingPattern::Name(n) => { bindings.insert(n.clone()); } - BindingPattern::Complex(c) => { - match c.borrow() { - SExp::Cons(_, a, b) => { - add_binding_names(bindings, &BindingPattern::Complex(a.clone())); - add_binding_names(bindings, &BindingPattern::Complex(b.clone())); - } - SExp::Atom(_, a) => { - bindings.insert(a.clone()); - } - _ => { } + BindingPattern::Complex(c) => match c.borrow() { + SExp::Cons(_, a, b) => { + add_binding_names(bindings, &BindingPattern::Complex(a.clone())); + add_binding_names(bindings, &BindingPattern::Complex(b.clone())); } - } + SExp::Atom(_, a) => { + bindings.insert(a.clone()); + } + _ => {} + }, } } @@ -318,23 +318,22 @@ fn resolve_namespaces_in_expr( program: &CompileForm, parent_ns: Option<&ImportLongName>, in_scope: &HashSet>, - expr: Rc + expr: Rc, ) -> Result, CompileErr> { match expr.borrow() { BodyForm::Call(loc, args, tail) => { - let new_tail = - if let Some(t) = tail.as_ref() { - Some(resolve_namespaces_in_expr( - resolved_helpers, - opts.clone(), - program, - parent_ns, - in_scope, - t.clone() - )?) - } else { - None - }; + let new_tail = if let Some(t) = tail.as_ref() { + Some(resolve_namespaces_in_expr( + resolved_helpers, + opts.clone(), + program, + parent_ns, + in_scope, + t.clone(), + )?) + } else { + None + }; Ok(Rc::new(BodyForm::Call( loc.clone(), @@ -346,12 +345,12 @@ fn resolve_namespaces_in_expr( program, parent_ns, in_scope, - e.clone() + e.clone(), ) }, - &args + &args, )?, - new_tail + new_tail, ))) } BodyForm::Value(SExp::Atom(nl, name)) => { @@ -379,23 +378,36 @@ fn resolve_namespaces_in_expr( } } - let (target_full_name, target_helper) = - if let Some((target_full_name, target_helper)) = find_helper_target( + let (target_full_name, target_helper) = if let Some((target_full_name, target_helper)) = + find_helper_target( opts.clone(), &program.helpers, parent_ns, &name, - &parsed_name + &parsed_name, ) { - (target_full_name, target_helper) - } else if is_compiler_builtin(&name) { - return Ok(expr.clone()); - } else { - return Err(CompileErr(expr.loc(), format!("could not find helper {} in {}", decode_string(&name), display_namespace(parent_ns.clone())))); - }; - - resolved_helpers.insert(target_full_name.clone(), HelperFormResult::new(&[target_helper.clone()], None)); - Ok(Rc::new(BodyForm::Value(SExp::Atom(nl.clone(), target_full_name.as_u8_vec(LongNameTranslation::Namespace))))) + (target_full_name, target_helper) + } else if is_compiler_builtin(&name) { + return Ok(expr.clone()); + } else { + return Err(CompileErr( + expr.loc(), + format!( + "could not find helper {} in {}", + decode_string(&name), + display_namespace(parent_ns.clone()) + ), + )); + }; + + resolved_helpers.insert( + target_full_name.clone(), + HelperFormResult::new(&[target_helper.clone()], None), + ); + Ok(Rc::new(BodyForm::Value(SExp::Atom( + nl.clone(), + target_full_name.as_u8_vec(LongNameTranslation::Namespace), + )))) } BodyForm::Value(_) => Ok(expr.clone()), BodyForm::Quoted(_) => Ok(expr.clone()), @@ -411,25 +423,28 @@ fn resolve_namespaces_in_expr( program, parent_ns, &new_scope, - b.body.clone() + b.body.clone(), )?, - .. b_borrowed.clone() + ..b_borrowed.clone() }; new_bindings.push(Rc::new(new_binding)); add_binding_names(&mut new_scope, &b.pattern); } - Ok(Rc::new(BodyForm::Let(LetFormKind::Sequential, Box::new(LetData { - bindings: new_bindings, - body: resolve_namespaces_in_expr( - resolved_helpers, - opts.clone(), - program, - parent_ns, - &new_scope, - ld.body.clone() - )?, - .. *ld.clone() - })))) + Ok(Rc::new(BodyForm::Let( + LetFormKind::Sequential, + Box::new(LetData { + bindings: new_bindings, + body: resolve_namespaces_in_expr( + resolved_helpers, + opts.clone(), + program, + parent_ns, + &new_scope, + ld.body.clone(), + )?, + ..*ld.clone() + }), + ))) } BodyForm::Let(LetFormKind::Parallel, ld) => { let mut new_scope = in_scope.clone(); @@ -443,25 +458,28 @@ fn resolve_namespaces_in_expr( program, parent_ns, in_scope, - b.body.clone() + b.body.clone(), )?, - .. b_borrowed.clone() + ..b_borrowed.clone() }; new_bindings.push(Rc::new(new_binding)); add_binding_names(&mut new_scope, &b.pattern); } - Ok(Rc::new(BodyForm::Let(LetFormKind::Sequential, Box::new(LetData { - bindings: new_bindings, - body: resolve_namespaces_in_expr( - resolved_helpers, - opts.clone(), - program, - parent_ns, - &new_scope, - ld.body.clone() - )?, - .. *ld.clone() - })))) + Ok(Rc::new(BodyForm::Let( + LetFormKind::Sequential, + Box::new(LetData { + bindings: new_bindings, + body: resolve_namespaces_in_expr( + resolved_helpers, + opts.clone(), + program, + parent_ns, + &new_scope, + ld.body.clone(), + )?, + ..*ld.clone() + }), + ))) } BodyForm::Let(LetFormKind::Assign, ld) => { let mut new_scope = in_scope.clone(); @@ -476,25 +494,28 @@ fn resolve_namespaces_in_expr( program, parent_ns, &new_scope, - b_borrowed.body.clone() + b_borrowed.body.clone(), )?, - .. b_borrowed.clone() + ..b_borrowed.clone() }; new_bindings.push(Rc::new(new_binding)); add_binding_names(&mut new_scope, &b_borrowed.pattern); } - Ok(Rc::new(BodyForm::Let(LetFormKind::Assign, Box::new(LetData { - bindings: new_bindings, - body: resolve_namespaces_in_expr( - resolved_helpers, - opts.clone(), - program, - parent_ns, - &new_scope, - ld.body.clone() - )?, - .. *ld.clone() - })))) + Ok(Rc::new(BodyForm::Let( + LetFormKind::Assign, + Box::new(LetData { + bindings: new_bindings, + body: resolve_namespaces_in_expr( + resolved_helpers, + opts.clone(), + program, + parent_ns, + &new_scope, + ld.body.clone(), + )?, + ..*ld.clone() + }), + ))) } BodyForm::Mod(_, _) => Ok(expr.clone()), BodyForm::Lambda(ld) => { @@ -504,7 +525,7 @@ fn resolve_namespaces_in_expr( program, parent_ns, in_scope, - ld.captures.clone() + ld.captures.clone(), )?; let mut scope_inside_lambda = in_scope.clone(); capture_scope(&mut scope_inside_lambda, ld.capture_args.clone()); @@ -515,12 +536,12 @@ fn resolve_namespaces_in_expr( program, parent_ns, &scope_inside_lambda, - ld.body.clone() + ld.body.clone(), )?; Ok(Rc::new(BodyForm::Lambda(Box::new(LambdaData { captures: new_captures, body: new_body, - .. *ld.clone() + ..*ld.clone() })))) } } @@ -535,12 +556,11 @@ fn resolve_namespaces_in_helper( ) -> Result { match helper { HelperForm::Defnamespace(ns) => { - let combined_ns = - if let Some(p) = parent_ns { - p.combine(&ns.longname) - } else { - ns.longname.clone() - }; + let combined_ns = if let Some(p) = parent_ns { + p.combine(&ns.longname) + } else { + ns.longname.clone() + }; let mut result_helpers = Vec::new(); @@ -550,33 +570,37 @@ fn resolve_namespaces_in_helper( opts.clone(), program, Some(&combined_ns), - h + h, )?; result_helpers.extend(newly_created.new_helpers); } - Ok(HelperFormResult::new(&[ - HelperForm::Defnamespace(NamespaceData { + Ok(HelperFormResult::new( + &[HelperForm::Defnamespace(NamespaceData { helpers: result_helpers, - .. ns.clone() - }) - ], None)) + ..ns.clone() + })], + None, + )) } HelperForm::Defnsref(_) => Ok(HelperFormResult::new(&[helper.clone()], None)), HelperForm::Defun(inline, dd) => { let mut in_scope = HashSet::new(); capture_scope(&mut in_scope, dd.args.clone()); - let new_defun = HelperForm::Defun(*inline, DefunData { - body: resolve_namespaces_in_expr( - resolved_helpers, - opts.clone(), - program, - parent_ns.clone(), - &in_scope, - dd.body.clone() - )?, - .. dd.clone() - }); + let new_defun = HelperForm::Defun( + *inline, + DefunData { + body: resolve_namespaces_in_expr( + resolved_helpers, + opts.clone(), + program, + parent_ns.clone(), + &in_scope, + dd.body.clone(), + )?, + ..dd.clone() + }, + ); Ok(HelperFormResult::new(&[new_defun], None)) } HelperForm::Defconstant(dc) => { @@ -588,9 +612,9 @@ fn resolve_namespaces_in_helper( program, parent_ns.clone(), &in_scope, - dc.body.clone() + dc.body.clone(), )?, - .. dc.clone() + ..dc.clone() }); Ok(HelperFormResult::new(&[new_defconst], None)) } @@ -603,21 +627,24 @@ fn resolve_namespaces_in_helper( opts.clone(), program, parent_ns.clone(), - h + h, )?; result_helpers.extend(results.new_helpers); } Ok(HelperFormResult::new(&result_helpers, None)) } HelperForm::Defmacro(_) => { - return Err(CompileErr(helper.loc(), "Classic macros are deprecated in module style chialisp".to_string())); + return Err(CompileErr( + helper.loc(), + "Classic macros are deprecated in module style chialisp".to_string(), + )); } } } pub fn resolve_namespaces( opts: Rc, - program: &CompileForm + program: &CompileForm, ) -> Result { let mut resolved_helpers: BTreeMap = BTreeMap::new(); let mut new_resolved_helpers: BTreeMap = BTreeMap::new(); @@ -632,14 +659,15 @@ pub fn resolve_namespaces( program, None, &program_scope, - program.exp.clone() + program.exp.clone(), )?; // Since we're resolving names now ahead of compilation, take this opportunity // to do it definitely by visiting every reachable helper from the main // expression. while !new_resolved_helpers.is_empty() { - let mut round_resolved_helpers: BTreeMap = BTreeMap::new(); + let mut round_resolved_helpers: BTreeMap = + BTreeMap::new(); for (name, helpers) in new_resolved_helpers.iter() { if resolved_helpers.contains_key(name) { continue; @@ -672,7 +700,7 @@ pub fn resolve_namespaces( opts.clone(), program, parent.as_ref(), - h + h, )?; result_helpers.extend(results.new_helpers.clone()); @@ -694,6 +722,6 @@ pub fn resolve_namespaces( Ok(CompileForm { helpers: all_helpers, exp: new_expr.clone(), - .. program.clone() + ..program.clone() }) } diff --git a/src/compiler/typechia.rs b/src/compiler/typechia.rs index e42c0048..0f74cbeb 100644 --- a/src/compiler/typechia.rs +++ b/src/compiler/typechia.rs @@ -584,7 +584,12 @@ fn handle_macro( match dequote(loc.clone(), exp_result) { Ok(dequoted) => { let last_reparse = frontend(opts.clone(), &[dequoted])?; - let final_res = chialisp_to_expr(opts, program, form_args, last_reparse.compileform().exp.clone())?; + let final_res = chialisp_to_expr( + opts, + program, + form_args, + last_reparse.compileform().exp.clone(), + )?; Ok(final_res) } Err(_) => { diff --git a/src/tests/classic/stage_2.rs b/src/tests/classic/stage_2.rs index 36ba8dfd..a292a820 100644 --- a/src/tests/classic/stage_2.rs +++ b/src/tests/classic/stage_2.rs @@ -17,11 +17,11 @@ use crate::classic::clvm_tools::stages::stage_2::helpers::{brun, evaluate, quote use crate::classic::clvm_tools::stages::stage_2::operators::run_program_for_search_paths; use crate::classic::clvm_tools::stages::stage_2::reader::{process_embed_file, read_file}; -use crate::compiler::BasicCompileContext; use crate::compiler::comptypes::{CompileErr, CompilerOpts, CompilerOutput, PrimaryCodegen}; use crate::compiler::dialect::AcceptedDialect; use crate::compiler::sexp::{decode_string, SExp}; use crate::compiler::srcloc::Srcloc; +use crate::compiler::BasicCompileContext; fn test_expand_macro( allocator: &mut Allocator, @@ -398,11 +398,7 @@ impl CompilerOpts for TestCompilerOptsPresentsOwnFiles { format!("could not read {filename}"), )) } - fn write_new_file( - &self, - _target: &str, - _content: &[u8] - ) -> Result<(), CompileErr> { + fn write_new_file(&self, _target: &str, _content: &[u8]) -> Result<(), CompileErr> { panic!("should not be writing from tests depending on this opts"); } fn compile_program( diff --git a/src/tests/compiler/compiler.rs b/src/tests/compiler/compiler.rs index 4732e479..5e1101ab 100644 --- a/src/tests/compiler/compiler.rs +++ b/src/tests/compiler/compiler.rs @@ -21,7 +21,15 @@ fn compile_string(content: &String) -> Result { let runner = Rc::new(DefaultProgramRunner::new()); let opts = Rc::new(DefaultCompilerOpts::new(&"*test*".to_string())); - compile_file(&mut allocator, runner, opts, &content, &mut HashMap::new(), &mut Vec::new()).map(|x| x.to_sexp().to_string()) + compile_file( + &mut allocator, + runner, + opts, + &content, + &mut HashMap::new(), + &mut Vec::new(), + ) + .map(|x| x.to_sexp().to_string()) } fn run_string_maybe_opt( @@ -265,8 +273,13 @@ fn run_test_4_opt() { } fn run_test_5_maybe_opt(opt: bool) { - let result = - run_string_maybe_opt(&"(mod (a) (list 1 2))".to_string(), &"()".to_string(), opt, false).unwrap(); + let result = run_string_maybe_opt( + &"(mod (a) (list 1 2))".to_string(), + &"()".to_string(), + opt, + false, + ) + .unwrap(); assert_eq!(result.to_string(), "(1 2)".to_string()); } diff --git a/src/tests/compiler/evaluate.rs b/src/tests/compiler/evaluate.rs index ec5fd121..946d87b5 100644 --- a/src/tests/compiler/evaluate.rs +++ b/src/tests/compiler/evaluate.rs @@ -108,7 +108,15 @@ fn compile_with_fe_opt(s: String) -> Result { let mut opts: Rc = Rc::new(DefaultCompilerOpts::new(&"*program*".to_string())); opts = opts.set_frontend_opt(true); - compile_file(&mut allocator, runner, opts, &s, &mut HashMap::new(), &mut Vec::new()).map(|r| r.to_sexp().to_string()) + compile_file( + &mut allocator, + runner, + opts, + &s, + &mut HashMap::new(), + &mut Vec::new(), + ) + .map(|r| r.to_sexp().to_string()) } #[test] diff --git a/src/tests/compiler/modules.rs b/src/tests/compiler/modules.rs index 4cad8a0d..97b85cc3 100644 --- a/src/tests/compiler/modules.rs +++ b/src/tests/compiler/modules.rs @@ -1,4 +1,4 @@ -use std::cell::{RefCell, Ref, RefMut}; +use std::cell::{Ref, RefCell, RefMut}; use std::collections::HashMap; use std::fs; use std::rc::Rc; @@ -10,32 +10,32 @@ use crate::classic::clvm::serialize::{sexp_from_stream, SimpleCreateCLVMObject}; use crate::classic::clvm_tools::binutils::{assemble, disassemble}; use crate::classic::clvm_tools::stages::stage_0::{DefaultProgramRunner, TRunProgram}; -use crate::compiler::BasicCompileContext; use crate::compiler::clvm::convert_to_clvm_rs; use crate::compiler::compiler::{compile_file, DefaultCompilerOpts}; use crate::compiler::comptypes::{CompileErr, CompilerOpts, CompilerOutput, PrimaryCodegen}; -use crate::compiler::dialect::{AcceptedDialect, detect_modern}; -use crate::compiler::sexp::{decode_string, enlist, SExp, parse_sexp}; +use crate::compiler::dialect::{detect_modern, AcceptedDialect}; +use crate::compiler::sexp::{decode_string, enlist, parse_sexp, SExp}; use crate::compiler::srcloc::Srcloc; +use crate::compiler::BasicCompileContext; #[derive(Clone)] struct TestModuleCompilerOpts { opts: Rc, - written_files: Rc>>> + written_files: Rc>>>, } impl TestModuleCompilerOpts { pub fn new(opts: Rc) -> Self { TestModuleCompilerOpts { opts: opts, - written_files: Rc::new(RefCell::new(HashMap::new())) + written_files: Rc::new(RefCell::new(HashMap::new())), } } fn new_opts(&self, opts: Rc) -> Rc { Rc::new(TestModuleCompilerOpts { opts, - written_files: self.written_files.clone() + written_files: self.written_files.clone(), }) } @@ -123,11 +123,7 @@ impl CompilerOpts for TestModuleCompilerOpts { ) -> Result<(String, Vec), CompileErr> { self.opts.read_new_file(inc_from, filename) } - fn write_new_file( - &self, - target: &str, - content: &[u8] - ) -> Result<(), CompileErr> { + fn write_new_file(&self, target: &str, content: &[u8]) -> Result<(), CompileErr> { let mut wf: RefMut<'_, HashMap>> = self.written_files.borrow_mut(); wf.insert(target.to_string(), content.to_vec()); Ok(()) @@ -144,13 +140,13 @@ impl CompilerOpts for TestModuleCompilerOpts { struct HexArgumentOutcome<'a> { hexfile: &'a str, argument: &'a str, - outcome: Option<&'a str> + outcome: Option<&'a str>, } fn test_compile_and_run_program_with_modules( filename: &str, content: &str, - runs: &[HexArgumentOutcome] + runs: &[HexArgumentOutcome], ) { let loc = Srcloc::start(filename); let parsed: Vec> = parse_sexp(loc.clone(), content.bytes()).expect("should parse"); @@ -158,9 +154,9 @@ fn test_compile_and_run_program_with_modules( let mut allocator = Allocator::new(); let nodeptr = convert_to_clvm_rs(&mut allocator, listed.clone()).expect("should convert"); let dialect = detect_modern(&mut allocator, nodeptr); - let orig_opts: Rc = Rc::new(DefaultCompilerOpts::new(filename)).set_dialect(dialect).set_search_paths(&[ - "resources/tests/module".to_string() - ]); + let orig_opts: Rc = Rc::new(DefaultCompilerOpts::new(filename)) + .set_dialect(dialect) + .set_search_paths(&["resources/tests/module".to_string()]); let source_opts = TestModuleCompilerOpts::new(orig_opts); let opts: Rc = Rc::new(source_opts.clone()); let mut symbol_table = HashMap::new(); @@ -173,20 +169,29 @@ fn test_compile_and_run_program_with_modules( &content, &mut symbol_table, &mut includes, - ).expect("should compile"); + ) + .expect("should compile"); for run in runs.iter() { - let hex_data = source_opts.get_written_file(run.hexfile).expect("should have written hex data beside the source file"); - let mut hex_stream = Stream::new(Some(Bytes::new_validated(Some(UnvalidatedBytesFromType::Hex(decode_string(&hex_data)))).expect("should be valid hex"))); - let compiled_node = sexp_from_stream(&mut allocator, &mut hex_stream, Box::new(SimpleCreateCLVMObject {})).expect("hex data should decode as sexp").1; + let hex_data = source_opts + .get_written_file(run.hexfile) + .expect("should have written hex data beside the source file"); + let mut hex_stream = Stream::new(Some( + Bytes::new_validated(Some(UnvalidatedBytesFromType::Hex(decode_string( + &hex_data, + )))) + .expect("should be valid hex"), + )); + let compiled_node = sexp_from_stream( + &mut allocator, + &mut hex_stream, + Box::new(SimpleCreateCLVMObject {}), + ) + .expect("hex data should decode as sexp") + .1; let assembled_env = assemble(&mut allocator, run.argument).expect("should assemble"); - let run_result = runner.run_program( - &mut allocator, - compiled_node, - assembled_env, - None - ); + let run_result = runner.run_program(&mut allocator, compiled_node, assembled_env, None); if let Some(res) = &run.outcome { let have_outcome = run_result.expect("expected success").1; assert_eq!(&disassemble(&mut allocator, have_outcome, None), res); @@ -209,14 +214,14 @@ fn test_simple_module_compliation() { HexArgumentOutcome { hexfile: hex_filename, argument: "(3)", - outcome: Some("3") + outcome: Some("3"), }, HexArgumentOutcome { hexfile: hex_filename, argument: "(13)", - outcome: None - } - ] + outcome: None, + }, + ], ); } @@ -233,14 +238,14 @@ fn test_simple_module_compliation_assign_rewrite() { HexArgumentOutcome { hexfile: hex_filename, argument: "(3)", - outcome: Some("3") + outcome: Some("3"), }, HexArgumentOutcome { hexfile: hex_filename, argument: "(13)", - outcome: None - } - ] + outcome: None, + }, + ], ); } @@ -257,14 +262,14 @@ fn test_simple_module_compliation_lambda_rewrite() { HexArgumentOutcome { hexfile: hex_filename, argument: "(3 13)", - outcome: Some("16") + outcome: Some("16"), }, HexArgumentOutcome { hexfile: hex_filename, argument: "(13 3)", - outcome: None - } - ] + outcome: None, + }, + ], ); } @@ -281,14 +286,14 @@ fn test_simple_module_compliation_lambda_rewrite_with_body() { HexArgumentOutcome { hexfile: hex_filename, argument: "(3 13)", - outcome: Some("(+ 39)") + outcome: Some("(+ 39)"), }, HexArgumentOutcome { hexfile: hex_filename, argument: "(13 3)", - outcome: None - } - ] + outcome: None, + }, + ], ); } @@ -358,13 +363,11 @@ fn test_simple_module_compliation_simple_type_1() { test_compile_and_run_program_with_modules( filename, &content, - &[ - HexArgumentOutcome { - hexfile: hex_filename, - argument: "(13 17)", - outcome: Some("13") - } - ] + &[HexArgumentOutcome { + hexfile: hex_filename, + argument: "(13 17)", + outcome: Some("13"), + }], ); } @@ -377,12 +380,10 @@ fn test_simple_module_compliation_simple_type_2() { test_compile_and_run_program_with_modules( filename, &content, - &[ - HexArgumentOutcome { - hexfile: hex_filename, - argument: "(13 17)", - outcome: Some("13") - } - ] + &[HexArgumentOutcome { + hexfile: hex_filename, + argument: "(13 17)", + outcome: Some("13"), + }], ); } diff --git a/src/tests/compiler/optimizer/bodyform.rs b/src/tests/compiler/optimizer/bodyform.rs index 3841ad53..efdab1a5 100644 --- a/src/tests/compiler/optimizer/bodyform.rs +++ b/src/tests/compiler/optimizer/bodyform.rs @@ -72,7 +72,10 @@ fn test_bodyform_simple_traversal_0() { ), ]; for (traversal1, want) in tests.iter() { - let retrieved1 = retrieve_bodyform(&traversal1, compiled.compileform().exp.borrow(), &|b| b.clone()); + let retrieved1 = + retrieve_bodyform(&traversal1, compiled.compileform().exp.borrow(), &|b| { + b.clone() + }); if let Some(r) = want { let re = Regex::new(r).unwrap(); assert!(re.is_match(&retrieved1.unwrap().to_sexp().to_string())); @@ -186,7 +189,10 @@ fn make_test_case_for_visitor(program: &str) -> CompileForm { let srcloc = Srcloc::start(progfile); let parsed = parse_sexp(srcloc.clone(), program.bytes()).expect("should parse"); let opts: Rc = Rc::new(DefaultCompilerOpts::new(progfile)); - frontend(opts.clone(), &parsed).expect("should fe").compileform().clone() + frontend(opts.clone(), &parsed) + .expect("should fe") + .compileform() + .clone() } #[test] diff --git a/src/tests/compiler/optimizer/output.rs b/src/tests/compiler/optimizer/output.rs index dfb1788b..ff1038e8 100644 --- a/src/tests/compiler/optimizer/output.rs +++ b/src/tests/compiler/optimizer/output.rs @@ -95,7 +95,13 @@ fn run_string_get_program_and_output_dialect( &mut Vec::new(), ) .and_then(|program| { - run_with_cost(&mut allocator, runner, Rc::new(program.to_sexp()), sexp_args).map_err(|e| match e { + run_with_cost( + &mut allocator, + runner, + Rc::new(program.to_sexp()), + sexp_args, + ) + .map_err(|e| match e { RunFailure::RunErr(l, s) => CompileErr(l, s), RunFailure::RunExn(l, s) => CompileErr(l, s.to_string()), }) diff --git a/src/tests/compiler/preprocessor.rs b/src/tests/compiler/preprocessor.rs index 1da47f08..2764b25c 100644 --- a/src/tests/compiler/preprocessor.rs +++ b/src/tests/compiler/preprocessor.rs @@ -2,7 +2,7 @@ use crate::compiler::compiler::DefaultCompilerOpts; use crate::compiler::comptypes::CompilerOpts; use crate::compiler::dialect::AcceptedDialect; use crate::compiler::preprocessor::preprocess; -use crate::compiler::sexp::{SExp, parse_sexp}; +use crate::compiler::sexp::{parse_sexp, SExp}; use crate::compiler::srcloc::Srcloc; use std::rc::Rc; @@ -528,10 +528,17 @@ fn test_preprocess_basic_list() { strict: true, }); let mut includes = Vec::new(); - let parsed_lst: Vec> = parsed_forms[0].proper_list().expect("was a list").into_iter().map(Rc::new).collect(); - let pp = preprocess(opts.clone(), &mut includes, &parsed_lst) - .expect("should preprocess"); - assert_eq!(pp.forms[pp.forms.len() - 1].to_string(), "(4 1 (4 2 (4 3 ())))"); + let parsed_lst: Vec> = parsed_forms[0] + .proper_list() + .expect("was a list") + .into_iter() + .map(Rc::new) + .collect(); + let pp = preprocess(opts.clone(), &mut includes, &parsed_lst).expect("should preprocess"); + assert_eq!( + pp.forms[pp.forms.len() - 1].to_string(), + "(4 1 (4 2 (4 3 ())))" + ); } #[test] @@ -567,7 +574,12 @@ fn test_preprocessor_tours_includes_properly() { strict: true, }); let parsed = parse_sexp(Srcloc::start(pname), prog.bytes()).expect("should parse"); - let parsed_lst: Vec> = parsed[0].proper_list().expect("was a list").into_iter().map(Rc::new).collect(); + let parsed_lst: Vec> = parsed[0] + .proper_list() + .expect("was a list") + .into_iter() + .map(Rc::new) + .collect(); let mut includes = Vec::new(); let res = preprocess(opts, &mut includes, &parsed_lst).expect("should preprocess"); let expected_lines = &[ diff --git a/src/tests/compiler/types/chialisp.rs b/src/tests/compiler/types/chialisp.rs index 501b26fc..abc145c1 100644 --- a/src/tests/compiler/types/chialisp.rs +++ b/src/tests/compiler/types/chialisp.rs @@ -133,8 +133,10 @@ pub fn test_chialisp_program_typecheck(s: &str, flatten: bool) -> Result