From 73cda2d4f9d81e5803657a839afb5b843de98906 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sun, 2 Aug 2020 15:39:08 +0800 Subject: [PATCH] rustfmt. --- Cargo.toml | 5 +- codegen/Cargo.toml | 4 +- codegen/src/function.rs | 246 +++++++++++++++--------- codegen/src/lib.rs | 31 +-- codegen/src/module.rs | 108 ++++++----- codegen/src/rhai_module.rs | 79 +++++--- codegen/tests/test_functions.rs | 66 ++++--- codegen/tests/test_modules.rs | 60 ++++-- codegen/ui_tests/first_shared_ref.rs | 7 +- codegen/ui_tests/non_clonable.rs | 7 +- codegen/ui_tests/non_clonable_second.rs | 7 +- codegen/ui_tests/return_mut_ref.rs | 7 +- codegen/ui_tests/return_pointer.rs | 12 +- codegen/ui_tests/return_shared_ref.rs | 9 +- codegen/ui_tests/second_shared_ref.rs | 7 +- 15 files changed, 409 insertions(+), 246 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9a282a45..297a5a88 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ categories = [ "no-std", "embedded", "wasm", "parser-implementations" ] [dependencies] num-traits = { version = "0.2.11", default-features = false } smallvec = { version = "1.4.1", default-features = false } +rhai_codegen = { version = "0.1", path = "codegen" } [features] #default = ["unchecked", "sync", "no_optimize", "no_float", "only_i32", "no_index", "no_object", "no_function", "no_module"] @@ -80,10 +81,6 @@ version = "0.2.1" default_features = false optional = true -[dependencies.rhai_codegen] -version = "0.1" -path = "codegen" - [target.'cfg(target_arch = "wasm32")'.dependencies] instant= { version = "0.1.4", features = ["wasm-bindgen"] } # WASM implementation of std::time::Instant diff --git a/codegen/Cargo.toml b/codegen/Cargo.toml index 53aa7d31..89a6f66f 100644 --- a/codegen/Cargo.toml +++ b/codegen/Cargo.toml @@ -2,7 +2,7 @@ name = "rhai_codegen" version = "0.1.0" edition = "2018" -authors = ["Stephen Chung", "jhwgh1968"] +authors = ["jhwgh1968", "Stephen Chung"] description = "Proceducral macro support package for Rhai, a scripting language for Rust" homepage = "https://github.com/jonathandturner/rhai" repository = "https://github.com/jonathandturner/rhai" @@ -12,7 +12,7 @@ license = "MIT OR Apache-2.0" proc-macro = true [dev-dependencies] -rhai = { version = "*", path = ".." } +rhai = { path = ".." } trybuild = "1" [dependencies] diff --git a/codegen/src/function.rs b/codegen/src/function.rs index 46015a7c..eab15386 100644 --- a/codegen/src/function.rs +++ b/codegen/src/function.rs @@ -19,29 +19,36 @@ impl Parse for ExportedFn { // Determine if the function is public. let is_public = match fn_all.vis { syn::Visibility::Public(_) => true, - _ => false + _ => false, }; // Determine whether function generates a special calling convention for a mutable // reciever. let mut_receiver = { if let Some(first_arg) = fn_all.sig.inputs.first() { match first_arg { - syn::FnArg::Receiver(syn::Receiver { reference: Some(_), ..}) => true, - syn::FnArg::Typed(syn::PatType { ref ty, .. }) => { - match ty.as_ref() { - &syn::Type::Reference(syn::TypeReference { - mutability: Some(_), .. }) => true, - &syn::Type::Reference(syn::TypeReference { mutability: None, - ref elem, .. }) => { - match elem.as_ref() { - &syn::Type::Path(ref p) if p.path == str_type_path => false, - _ => return Err(syn::Error::new(ty.span(), - "references from Rhai in this position \ - must be mutable")), - } - }, - _ => false, - } + syn::FnArg::Receiver(syn::Receiver { + reference: Some(_), .. + }) => true, + syn::FnArg::Typed(syn::PatType { ref ty, .. }) => match ty.as_ref() { + &syn::Type::Reference(syn::TypeReference { + mutability: Some(_), + .. + }) => true, + &syn::Type::Reference(syn::TypeReference { + mutability: None, + ref elem, + .. + }) => match elem.as_ref() { + &syn::Type::Path(ref p) if p.path == str_type_path => false, + _ => { + return Err(syn::Error::new( + ty.span(), + "references from Rhai in this position \ + must be mutable", + )) + } + }, + _ => false, }, _ => false, } @@ -57,31 +64,46 @@ impl Parse for ExportedFn { _ => panic!("internal error: receiver argument outside of first position!?"), }; let is_ok = match ty.as_ref() { - &syn::Type::Reference(syn::TypeReference { mutability: Some(_), .. }) => false, - &syn::Type::Reference(syn::TypeReference { mutability: None, - ref elem, .. }) => { - match elem.as_ref() { - &syn::Type::Path(ref p) if p.path == str_type_path => true, - _ => false, - } + &syn::Type::Reference(syn::TypeReference { + mutability: Some(_), + .. + }) => false, + &syn::Type::Reference(syn::TypeReference { + mutability: None, + ref elem, + .. + }) => match elem.as_ref() { + &syn::Type::Path(ref p) if p.path == str_type_path => true, + _ => false, }, &syn::Type::Verbatim(_) => false, _ => true, }; if !is_ok { - return Err(syn::Error::new(ty.span(), "this type in this position passes from \ - Rhai by value")); + return Err(syn::Error::new( + ty.span(), + "this type in this position passes from \ + Rhai by value", + )); } } // No returning references or pointers. if let syn::ReturnType::Type(_, ref rtype) = fn_all.sig.output { match rtype.as_ref() { - &syn::Type::Ptr(_) => return Err(syn::Error::new(fn_all.sig.output.span(), - "cannot return a pointer to Rhai")), - &syn::Type::Reference(_) => return Err(syn::Error::new(fn_all.sig.output.span(), - "cannot return a reference to Rhai")), - _ => {}, + &syn::Type::Ptr(_) => { + return Err(syn::Error::new( + fn_all.sig.output.span(), + "cannot return a pointer to Rhai", + )) + } + &syn::Type::Reference(_) => { + return Err(syn::Error::new( + fn_all.sig.output.span(), + "cannot return a reference to Rhai", + )) + } + _ => {} } } Ok(ExportedFn { @@ -110,7 +132,7 @@ impl ExportedFn { &self.signature.ident } - pub(crate) fn arg_list(&self) -> impl Iterator { + pub(crate) fn arg_list(&self) -> impl Iterator { self.signature.inputs.iter() } @@ -127,8 +149,10 @@ impl ExportedFn { } pub fn generate(self) -> proc_macro2::TokenStream { - let name: syn::Ident = syn::Ident::new(&format!("rhai_fn__{}", self.name().to_string()), - self.name().span()); + let name: syn::Ident = syn::Ident::new( + &format!("rhai_fn__{}", self.name().to_string()), + self.name().span(), + ); let impl_block = self.generate_impl("Token"); quote! { #[allow(unused)] @@ -156,23 +180,30 @@ impl ExportedFn { let first_arg = self.arg_list().next().unwrap(); let var = syn::Ident::new("arg0", proc_macro2::Span::call_site()); match first_arg { - syn::FnArg::Typed(pattern) => { + syn::FnArg::Typed(pattern) => { let arg_type: &syn::Type = { match pattern.ty.as_ref() { - &syn::Type::Reference( - syn::TypeReference { ref elem, .. }) => elem.as_ref(), + &syn::Type::Reference(syn::TypeReference { ref elem, .. }) => { + elem.as_ref() + } ref p => p, } }; let downcast_span = quote_spanned!( arg_type.span()=> args[0usize].downcast_mut::<#arg_type>().unwrap()); - unpack_stmts.push(syn::parse2::(quote! { - let #var: &mut _ = #downcast_span; - }).unwrap()); - input_type_exprs.push(syn::parse2::(quote_spanned!( - arg_type.span()=> std::any::TypeId::of::<#arg_type>() - )).unwrap()); - }, + unpack_stmts.push( + syn::parse2::(quote! { + let #var: &mut _ = #downcast_span; + }) + .unwrap(), + ); + input_type_exprs.push( + syn::parse2::(quote_spanned!( + arg_type.span()=> std::any::TypeId::of::<#arg_type>() + )) + .unwrap(), + ); + } syn::FnArg::Receiver(_) => todo!("true self parameters not implemented yet"), } unpack_exprs.push(syn::parse2::(quote! { #var }).unwrap()); @@ -189,42 +220,52 @@ impl ExportedFn { let var = syn::Ident::new(&format!("arg{}", i), proc_macro2::Span::call_site()); let is_str_ref; match arg { - syn::FnArg::Typed(pattern) => { + syn::FnArg::Typed(pattern) => { let arg_type: &syn::Type = pattern.ty.as_ref(); let downcast_span = match pattern.ty.as_ref() { - &syn::Type::Reference(syn::TypeReference { mutability: None, - ref elem, .. }) => { - match elem.as_ref() { - &syn::Type::Path(ref p) if p.path == str_type_path => { - is_str_ref = true; - quote_spanned!(arg_type.span()=> + &syn::Type::Reference(syn::TypeReference { + mutability: None, + ref elem, + .. + }) => match elem.as_ref() { + &syn::Type::Path(ref p) if p.path == str_type_path => { + is_str_ref = true; + quote_spanned!(arg_type.span()=> args[#i] .downcast_clone::() .unwrap()) - }, - _ => panic!("internal error: why wasn't this found earlier!?"), } + _ => panic!("internal error: why wasn't this found earlier!?"), }, _ => { is_str_ref = false; quote_spanned!(arg_type.span()=> args[#i].downcast_clone::<#arg_type>().unwrap()) - }, + } }; - unpack_stmts.push(syn::parse2::(quote! { - let #var = #downcast_span; - }).unwrap()); + unpack_stmts.push( + syn::parse2::(quote! { + let #var = #downcast_span; + }) + .unwrap(), + ); if !is_str_ref { - input_type_exprs.push(syn::parse2::(quote_spanned!( - arg_type.span()=> std::any::TypeId::of::<#arg_type>() - )).unwrap()); + input_type_exprs.push( + syn::parse2::(quote_spanned!( + arg_type.span()=> std::any::TypeId::of::<#arg_type>() + )) + .unwrap(), + ); } else { - input_type_exprs.push(syn::parse2::(quote_spanned!( - arg_type.span()=> std::any::TypeId::of::() - )).unwrap()); + input_type_exprs.push( + syn::parse2::(quote_spanned!( + arg_type.span()=> std::any::TypeId::of::() + )) + .unwrap(), + ); } - }, + } syn::FnArg::Receiver(_) => panic!("internal error: how did this happen!?"), } if !is_str_ref { @@ -302,8 +343,10 @@ mod function_tests { assert!(item_fn.is_public()); assert!(item_fn.return_type().is_none()); - assert_eq!(item_fn.arg_list().next().unwrap(), - &syn::parse2::(quote! { x: usize }).unwrap()); + assert_eq!( + item_fn.arg_list().next().unwrap(), + &syn::parse2::(quote! { x: usize }).unwrap() + ); } #[test] @@ -319,10 +362,14 @@ mod function_tests { assert!(item_fn.is_public()); assert!(item_fn.return_type().is_none()); - assert_eq!(item_fn.arg_list().next().unwrap(), - &syn::parse2::(quote! { x: usize }).unwrap()); - assert_eq!(item_fn.arg_list().skip(1).next().unwrap(), - &syn::parse2::(quote! { y: f32 }).unwrap()); + assert_eq!( + item_fn.arg_list().next().unwrap(), + &syn::parse2::(quote! { x: usize }).unwrap() + ); + assert_eq!( + item_fn.arg_list().skip(1).next().unwrap(), + &syn::parse2::(quote! { y: f32 }).unwrap() + ); } #[test] @@ -336,11 +383,12 @@ mod function_tests { assert!(!item_fn.mutable_receiver()); assert!(item_fn.is_public()); assert_eq!(item_fn.arg_list().count(), 0); - assert_eq!(item_fn.return_type().unwrap(), - &syn::Type::Path(syn::TypePath { - qself: None, - path: syn::parse2::(quote! { usize }).unwrap() - }) + assert_eq!( + item_fn.return_type().unwrap(), + &syn::Type::Path(syn::TypePath { + qself: None, + path: syn::parse2::(quote! { usize }).unwrap() + }) ); } @@ -351,8 +399,7 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), - "cannot return a reference to Rhai"); + assert_eq!(format!("{}", err), "cannot return a reference to Rhai"); } #[test] @@ -362,8 +409,7 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), - "cannot return a pointer to Rhai"); + assert_eq!(format!("{}", err), "cannot return a pointer to Rhai"); } #[test] @@ -373,8 +419,10 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), - "references from Rhai in this position must be mutable"); + assert_eq!( + format!("{}", err), + "references from Rhai in this position must be mutable" + ); } #[test] @@ -384,8 +432,10 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), - "this type in this position passes from Rhai by value"); + assert_eq!( + format!("{}", err), + "this type in this position passes from Rhai by value" + ); } #[test] @@ -395,8 +445,10 @@ mod function_tests { }; let err = syn::parse2::(input_tokens).unwrap_err(); - assert_eq!(format!("{}", err), - "this type in this position passes from Rhai by value"); + assert_eq!( + format!("{}", err), + "this type in this position passes from Rhai by value" + ); } #[test] @@ -412,8 +464,10 @@ mod function_tests { assert!(item_fn.is_public()); assert!(item_fn.return_type().is_none()); - assert_eq!(item_fn.arg_list().next().unwrap(), - &syn::parse2::(quote! { message: &str }).unwrap()); + assert_eq!( + item_fn.arg_list().next().unwrap(), + &syn::parse2::(quote! { message: &str }).unwrap() + ); } #[test] @@ -429,10 +483,14 @@ mod function_tests { assert!(item_fn.is_public()); assert!(item_fn.return_type().is_none()); - assert_eq!(item_fn.arg_list().next().unwrap(), - &syn::parse2::(quote! { level: usize }).unwrap()); - assert_eq!(item_fn.arg_list().skip(1).next().unwrap(), - &syn::parse2::(quote! { message: &str }).unwrap()); + assert_eq!( + item_fn.arg_list().next().unwrap(), + &syn::parse2::(quote! { level: usize }).unwrap() + ); + assert_eq!( + item_fn.arg_list().skip(1).next().unwrap(), + &syn::parse2::(quote! { message: &str }).unwrap() + ); } #[test] @@ -490,7 +548,9 @@ mod generate_tests { let expected = expected.to_string(); if &actual != &expected { let mut counter = 0; - let iter = actual.chars().zip(expected.chars()) + let iter = actual + .chars() + .zip(expected.chars()) .inspect(|_| counter += 1) .skip_while(|(a, e)| *a == *e); let (actual_diff, expected_diff) = { @@ -508,7 +568,7 @@ mod generate_tests { } #[test] - fn minimal_fn () { + fn minimal_fn() { let input_tokens: TokenStream = quote! { pub fn do_nothing() { } }; diff --git a/codegen/src/lib.rs b/codegen/src/lib.rs index f22b9da9..fb214c5d 100644 --- a/codegen/src/lib.rs +++ b/codegen/src/lib.rs @@ -75,8 +75,10 @@ mod module; mod rhai_module; #[proc_macro_attribute] -pub fn export_fn(_args: proc_macro::TokenStream, - input: proc_macro::TokenStream) -> proc_macro::TokenStream { +pub fn export_fn( + _args: proc_macro::TokenStream, + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { let mut output = proc_macro2::TokenStream::from(input.clone()); let function_def = parse_macro_input!(input as function::ExportedFn); output.extend(function_def.generate()); @@ -84,8 +86,10 @@ pub fn export_fn(_args: proc_macro::TokenStream, } #[proc_macro_attribute] -pub fn export_module(_args: proc_macro::TokenStream, - input: proc_macro::TokenStream) -> proc_macro::TokenStream { +pub fn export_module( + _args: proc_macro::TokenStream, + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { let module_def = parse_macro_input!(input as module::Module); let tokens = module_def.generate(); proc_macro::TokenStream::from(tokens) @@ -108,8 +112,8 @@ pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenS let items: Vec = args.into_iter().collect(); if items.len() != 3 { return proc_macro::TokenStream::from( - syn::Error::new(arg_span, "this macro requires three arguments") - .to_compile_error()); + syn::Error::new(arg_span, "this macro requires three arguments").to_compile_error(), + ); } let rhai_module = &items[0]; let export_name = match &items[1] { @@ -122,15 +126,20 @@ pub fn register_exported_fn(args: proc_macro::TokenStream) -> proc_macro::TokenS } else { return proc_macro::TokenStream::from( syn::Error::new(items[2].span(), "third argument must be a function name") - .to_compile_error()); + .to_compile_error(), + ); }; let gen_mod_path: syn::punctuated::Punctuated = { let mut g = rust_modpath.clone().segments; g.pop(); - let ident = syn::Ident::new(&format!("rhai_fn__{}", - rust_modpath.segments.last().unwrap().ident), - items[2].span()); - g.push_value(syn::PathSegment { ident, arguments: syn::PathArguments::None }); + let ident = syn::Ident::new( + &format!("rhai_fn__{}", rust_modpath.segments.last().unwrap().ident), + items[2].span(), + ); + g.push_value(syn::PathSegment { + ident, + arguments: syn::PathArguments::None, + }); g }; let tokens = quote! { diff --git a/codegen/src/module.rs b/codegen/src/module.rs index e22b6ec8..e2c236e4 100644 --- a/codegen/src/module.rs +++ b/codegen/src/module.rs @@ -17,36 +17,39 @@ impl Parse for Module { let fns: Vec<_>; let consts: Vec<_>; if let Some((_, ref content)) = mod_all.content { - fns = content.iter() - .filter_map(|item| { - match item { - syn::Item::Fn(f) => { - if let syn::Visibility::Public(_) = f.vis { - Some(f) - } else { - None - } - }, - _ => None, + fns = content + .iter() + .filter_map(|item| match item { + syn::Item::Fn(f) => { + if let syn::Visibility::Public(_) = f.vis { + Some(f) + } else { + None + } } + _ => None, }) .try_fold(Vec::new(), |mut vec, itemfn| { syn::parse2::(itemfn.to_token_stream()) .map(|f| vec.push(f)) .map(|_| vec) })?; - consts = content.iter() - .filter_map(|item| { - match item { - syn::Item::Const(syn::ItemConst {vis, ref expr, ident, ..}) => { - if let syn::Visibility::Public(_) = vis { - Some((ident.to_string(), expr.as_ref().clone())) - } else { - None - } - }, - _ => None, + consts = content + .iter() + .filter_map(|item| match item { + syn::Item::Const(syn::ItemConst { + vis, + ref expr, + ident, + .. + }) => { + if let syn::Visibility::Public(_) = vis { + Some((ident.to_string(), expr.as_ref().clone())) + } else { + None + } } + _ => None, }) .collect(); } else { @@ -87,7 +90,6 @@ mod module_tests { #[test] fn empty_module() { - let input_tokens: TokenStream = quote! { pub mod empty { } }; @@ -99,7 +101,6 @@ mod module_tests { #[test] fn one_factory_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn get_mystic_number() -> INT { @@ -113,13 +114,14 @@ mod module_tests { assert_eq!(item_mod.fns.len(), 1); assert_eq!(item_mod.fns[0].name().to_string(), "get_mystic_number"); assert_eq!(item_mod.fns[0].arg_count(), 0); - assert_eq!(item_mod.fns[0].return_type().unwrap(), - &syn::parse2::(quote! { INT }).unwrap()); + assert_eq!( + item_mod.fns[0].return_type().unwrap(), + &syn::parse2::(quote! { INT }).unwrap() + ); } #[test] fn one_single_arg_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn add_one_to(x: INT) -> INT { @@ -133,15 +135,18 @@ mod module_tests { assert_eq!(item_mod.fns.len(), 1); assert_eq!(item_mod.fns[0].name().to_string(), "add_one_to"); assert_eq!(item_mod.fns[0].arg_count(), 1); - assert_eq!(item_mod.fns[0].arg_list().next().unwrap(), - &syn::parse2::(quote! { x: INT }).unwrap()); - assert_eq!(item_mod.fns[0].return_type().unwrap(), - &syn::parse2::(quote! { INT }).unwrap()); + assert_eq!( + item_mod.fns[0].arg_list().next().unwrap(), + &syn::parse2::(quote! { x: INT }).unwrap() + ); + assert_eq!( + item_mod.fns[0].return_type().unwrap(), + &syn::parse2::(quote! { INT }).unwrap() + ); } #[test] fn one_double_arg_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn add_together(x: INT, y: INT) -> INT { @@ -156,18 +161,23 @@ mod module_tests { assert_eq!(item_mod.fns.len(), 1); assert_eq!(item_mod.fns[0].name().to_string(), "add_together"); assert_eq!(item_mod.fns[0].arg_count(), 2); - assert_eq!(args.next().unwrap(), - &syn::parse2::(quote! { x: INT }).unwrap()); - assert_eq!(args.next().unwrap(), - &syn::parse2::(quote! { y: INT }).unwrap()); + assert_eq!( + args.next().unwrap(), + &syn::parse2::(quote! { x: INT }).unwrap() + ); + assert_eq!( + args.next().unwrap(), + &syn::parse2::(quote! { y: INT }).unwrap() + ); assert!(args.next().is_none()); - assert_eq!(item_mod.fns[0].return_type().unwrap(), - &syn::parse2::(quote! { INT }).unwrap()); + assert_eq!( + item_mod.fns[0].return_type().unwrap(), + &syn::parse2::(quote! { INT }).unwrap() + ); } #[test] fn one_constant_module() { - let input_tokens: TokenStream = quote! { pub mod one_constant { pub const MYSTIC_NUMBER: INT = 42; @@ -178,12 +188,14 @@ mod module_tests { assert!(item_mod.fns.is_empty()); assert_eq!(item_mod.consts.len(), 1); assert_eq!(&item_mod.consts[0].0, "MYSTIC_NUMBER"); - assert_eq!(item_mod.consts[0].1, syn::parse2::(quote! { 42 }).unwrap()); + assert_eq!( + item_mod.consts[0].1, + syn::parse2::(quote! { 42 }).unwrap() + ); } #[test] fn one_private_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { fn get_mystic_number() -> INT { @@ -199,7 +211,6 @@ mod module_tests { #[test] fn one_private_constant_module() { - let input_tokens: TokenStream = quote! { pub mod one_constant { const MYSTIC_NUMBER: INT = 42; @@ -224,7 +235,9 @@ mod generate_tests { let expected = expected.to_string(); if &actual != &expected { let mut counter = 0; - let iter = actual.chars().zip(expected.chars()) + let iter = actual + .chars() + .zip(expected.chars()) .inspect(|_| counter += 1) .skip_while(|(a, e)| *a == *e); let (actual_diff, expected_diff) = { @@ -265,7 +278,6 @@ mod generate_tests { #[test] fn one_factory_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn get_mystic_number() -> INT { @@ -320,7 +332,6 @@ mod generate_tests { #[test] fn one_single_arg_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn add_one_to(x: INT) -> INT { @@ -376,7 +387,6 @@ mod generate_tests { #[test] fn one_double_arg_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { pub fn add_together(x: INT, y: INT) -> INT { @@ -435,7 +445,6 @@ mod generate_tests { #[test] fn one_constant_module() { - let input_tokens: TokenStream = quote! { pub mod one_constant { pub const MYSTIC_NUMBER: INT = 42; @@ -462,7 +471,6 @@ mod generate_tests { #[test] fn one_constant_module_imports_preserved() { - let input_tokens: TokenStream = quote! { pub mod one_constant { pub use rhai::INT; @@ -491,7 +499,6 @@ mod generate_tests { #[test] fn one_private_fn_module() { - let input_tokens: TokenStream = quote! { pub mod one_fn { fn get_mystic_number() -> INT { @@ -521,7 +528,6 @@ mod generate_tests { #[test] fn one_private_constant_module() { - let input_tokens: TokenStream = quote! { pub mod one_constant { const MYSTIC_NUMBER: INT = 42; @@ -547,7 +553,6 @@ mod generate_tests { #[test] fn one_str_arg_fn_module() { - let input_tokens: TokenStream = quote! { pub mod str_fn { pub fn print_out_to(x: &str) { @@ -604,7 +609,6 @@ mod generate_tests { #[test] fn one_mut_ref_fn_module() { - let input_tokens: TokenStream = quote! { pub mod ref_fn { pub fn increment(x: &mut FLOAT) { diff --git a/codegen/src/rhai_module.rs b/codegen/src/rhai_module.rs index ba04b50c..f817e213 100644 --- a/codegen/src/rhai_module.rs +++ b/codegen/src/rhai_module.rs @@ -6,7 +6,7 @@ pub(crate) type ExportedConst = (String, syn::Expr); pub(crate) fn generate_body( fns: &Vec, - consts: &Vec + consts: &Vec, ) -> proc_macro2::TokenStream { let mut set_fn_stmts: Vec = Vec::new(); let mut set_const_stmts: Vec = Vec::new(); @@ -14,51 +14,67 @@ pub(crate) fn generate_body( for (const_name, const_expr) in consts { let const_literal = syn::LitStr::new(&const_name, proc_macro2::Span::call_site()); - set_const_stmts.push(syn::parse2::(quote! { - m.set_var(#const_literal, #const_expr); - }).unwrap()); + set_const_stmts.push( + syn::parse2::(quote! { + m.set_var(#const_literal, #const_expr); + }) + .unwrap(), + ); } // NB: these are token streams, because reparsing messes up "> >" vs ">>" let mut gen_fn_tokens: Vec = Vec::new(); for function in fns { - let fn_token_name = syn::Ident::new(&format!("{}__Token", function.name().to_string()), - function.name().span()); - let fn_literal = syn::LitStr::new(&function.name().to_string(), - proc_macro2::Span::call_site()); - let fn_input_types: Vec = function.arg_list() + let fn_token_name = syn::Ident::new( + &format!("{}__Token", function.name().to_string()), + function.name().span(), + ); + let fn_literal = + syn::LitStr::new(&function.name().to_string(), proc_macro2::Span::call_site()); + let fn_input_types: Vec = function + .arg_list() .map(|fnarg| match fnarg { syn::FnArg::Receiver(_) => panic!("internal error: receiver fn outside impl!?"), syn::FnArg::Typed(syn::PatType { ref ty, .. }) => { let arg_type = match ty.as_ref() { - &syn::Type::Reference(syn::TypeReference { mutability: None, - ref elem, .. }) => { - match elem.as_ref() { - &syn::Type::Path(ref p) if p.path == str_type_path => - syn::parse2::(quote! { - rhai::ImmutableString }).unwrap(), - _ => panic!("internal error: non-string shared reference!?"), + &syn::Type::Reference(syn::TypeReference { + mutability: None, + ref elem, + .. + }) => match elem.as_ref() { + &syn::Type::Path(ref p) if p.path == str_type_path => { + syn::parse2::(quote! { + rhai::ImmutableString }) + .unwrap() } + _ => panic!("internal error: non-string shared reference!?"), }, - &syn::Type::Reference(syn::TypeReference { mutability: Some(_), - ref elem, .. }) => { - match elem.as_ref() { - &syn::Type::Path(ref p) => syn::parse2::(quote! { - #p }).unwrap(), - _ => panic!("internal error: non-string shared reference!?"), - } + &syn::Type::Reference(syn::TypeReference { + mutability: Some(_), + ref elem, + .. + }) => match elem.as_ref() { + &syn::Type::Path(ref p) => syn::parse2::(quote! { + #p }) + .unwrap(), + _ => panic!("internal error: non-string shared reference!?"), }, t => t.clone(), }; syn::parse2::(quote! { - core::any::TypeId::of::<#arg_type>()}).unwrap() - }, - }).collect(); + core::any::TypeId::of::<#arg_type>()}) + .unwrap() + } + }) + .collect(); - set_fn_stmts.push(syn::parse2::(quote! { - m.set_fn(#fn_literal, FnAccess::Public, &[#(#fn_input_types),*], - rhai::plugin::CallableFunction::from_plugin(#fn_token_name())); - }).unwrap()); + set_fn_stmts.push( + syn::parse2::(quote! { + m.set_fn(#fn_literal, FnAccess::Public, &[#(#fn_input_types),*], + rhai::plugin::CallableFunction::from_plugin(#fn_token_name())); + }) + .unwrap(), + ); gen_fn_tokens.push(quote! { #[allow(non_camel_case_types)] @@ -79,7 +95,8 @@ pub(crate) fn generate_body( m } } - }).unwrap(); + }) + .unwrap(); let (_, generate_call_content) = generate_fncall.content.take().unwrap(); diff --git a/codegen/tests/test_functions.rs b/codegen/tests/test_functions.rs index a0ebb6c0..bc779b74 100644 --- a/codegen/tests/test_functions.rs +++ b/codegen/tests/test_functions.rs @@ -1,36 +1,44 @@ -use rhai::{EvalAltResult, FLOAT, INT, Module, RegisterFn}; -use rhai::plugin::*; use rhai::module_resolvers::*; +use rhai::plugin::*; +use rhai::{EvalAltResult, Module, RegisterFn, FLOAT, INT}; pub mod raw_fn { - use rhai::FLOAT; use rhai::export_fn; + use rhai::FLOAT; #[export_fn] pub fn distance_function(x1: FLOAT, y1: FLOAT, x2: FLOAT, y2: FLOAT) -> FLOAT { - ((y2 - y1).abs().powf(2.0) + (x2 -x1).abs().powf(2.0)).sqrt() + ((y2 - y1).abs().powf(2.0) + (x2 - x1).abs().powf(2.0)).sqrt() } } #[test] fn raw_fn_test() -> Result<(), Box> { let mut engine = Engine::new(); - engine.register_fn("get_mystic_number", || { 42 as FLOAT }); + engine.register_fn("get_mystic_number", || 42 as FLOAT); let mut m = Module::new(); - rhai::register_exported_fn!(m, "euclidean_distance".to_string(), raw_fn::distance_function); + rhai::register_exported_fn!( + m, + "euclidean_distance".to_string(), + raw_fn::distance_function + ); let mut r = StaticModuleResolver::new(); r.insert("Math::Advanced".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Math::Advanced" as math; - let x = math::euclidean_distance(0.0, 1.0, 0.0, get_mystic_number()); x"#)?, 41.0); + assert_eq!( + engine.eval::( + r#"import "Math::Advanced" as math; + let x = math::euclidean_distance(0.0, 1.0, 0.0, get_mystic_number()); x"# + )?, + 41.0 + ); Ok(()) } mod raw_fn_mut { - use rhai::FLOAT; use rhai::export_fn; + use rhai::FLOAT; #[export_fn] pub fn add_in_place(f1: &mut FLOAT, f2: FLOAT) { @@ -41,18 +49,22 @@ mod raw_fn_mut { #[test] fn raw_fn_mut_test() -> Result<(), Box> { let mut engine = Engine::new(); - engine.register_fn("get_mystic_number", || { 42 as FLOAT }); + engine.register_fn("get_mystic_number", || 42 as FLOAT); let mut m = Module::new(); rhai::register_exported_fn!(m, "add_in_place", raw_fn_mut::add_in_place); let mut r = StaticModuleResolver::new(); r.insert("Math::Advanced".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Math::Advanced" as math; + assert_eq!( + engine.eval::( + r#"import "Math::Advanced" as math; let x = get_mystic_number(); math::add_in_place(x, 1.0); - x"#)?, 43.0); + x"# + )?, + 43.0 + ); Ok(()) } @@ -69,29 +81,33 @@ mod raw_fn_str { #[test] fn raw_fn_str_test() -> Result<(), Box> { let mut engine = Engine::new(); - engine.register_fn("get_mystic_number", || { 42 as FLOAT }); + engine.register_fn("get_mystic_number", || 42 as FLOAT); let mut m = Module::new(); rhai::register_exported_fn!(m, "write_out_str", raw_fn_str::write_out_str); let mut r = StaticModuleResolver::new(); r.insert("Host::IO".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Host::IO" as io; + assert_eq!( + engine.eval::( + r#"import "Host::IO" as io; let x = io::write_out_str("hello world!"); - x"#)?, true); + x"# + )?, + true + ); Ok(()) } mod mut_opaque_ref { - use rhai::INT; use rhai::export_fn; + use rhai::INT; #[derive(Clone)] pub struct StatusMessage { os_code: Option, message: String, - is_ok: bool + is_ok: bool, } #[export_fn] @@ -130,12 +146,16 @@ fn mut_opaque_ref_test() -> Result<(), Box> { r.insert("Host::Msg".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Host::Msg" as msg; + assert_eq!( + engine.eval::( + r#"import "Host::Msg" as msg; let message1 = msg::new_message(true, "it worked"); let ok1 = msg::write_out_message(message1); let message2 = msg::new_os_message(true, 0); let ok2 = msg::write_out_message(message2); - ok1 && ok2"#)?, true); + ok1 && ok2"# + )?, + true + ); Ok(()) } diff --git a/codegen/tests/test_modules.rs b/codegen/tests/test_modules.rs index ebc661a9..0794991b 100644 --- a/codegen/tests/test_modules.rs +++ b/codegen/tests/test_modules.rs @@ -1,12 +1,12 @@ -use rhai::{EvalAltResult, FLOAT, INT, RegisterFn}; -use rhai::plugin::*; use rhai::module_resolvers::*; +use rhai::plugin::*; +use rhai::{EvalAltResult, RegisterFn, FLOAT, INT}; pub mod empty_module { use rhai::export_module; #[export_module] - pub mod EmptyModule { } + pub mod EmptyModule {} } #[test] @@ -17,8 +17,10 @@ fn empty_module_test() -> Result<(), Box> { r.insert("Module::Empty".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Module::Empty" as m; 42"#)?, 42); + assert_eq!( + engine.eval::(r#"import "Module::Empty" as m; 42"#)?, + 42 + ); Ok(()) } @@ -42,10 +44,14 @@ fn one_fn_module_test() -> Result<(), Box> { r.insert("Math::Advanced".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Math::Advanced" as math; + assert_eq!( + engine.eval::( + r#"import "Math::Advanced" as math; let m = math::get_mystic_number(); - m"#)?, 42.0); + m"# + )?, + 42.0 + ); Ok(()) } @@ -59,7 +65,7 @@ pub mod one_fn_and_const_module { pub const MYSTIC_NUMBER: FLOAT = 42.0 as FLOAT; pub fn euclidean_distance(x1: FLOAT, y1: FLOAT, x2: FLOAT, y2: FLOAT) -> FLOAT { - ((y2 - y1).abs().powf(2.0) + (x2 -x1).abs().powf(2.0)).sqrt() + ((y2 - y1).abs().powf(2.0) + (x2 - x1).abs().powf(2.0)).sqrt() } } } @@ -72,11 +78,15 @@ fn one_fn_and_const_module_test() -> Result<(), Box> { r.insert("Math::Advanced".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Math::Advanced" as math; + assert_eq!( + engine.eval::( + r#"import "Math::Advanced" as math; let m = math::MYSTIC_NUMBER; let x = math::euclidean_distance(0.0, 1.0, 0.0, m); - x"#)?, 41.0); + x"# + )?, + 41.0 + ); Ok(()) } @@ -100,27 +110,31 @@ fn raw_fn_str_module_test() -> Result<(), Box> { r.insert("Host::IO".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Host::IO" as io; + assert_eq!( + engine.eval::( + r#"import "Host::IO" as io; let x = io::write_out_str("hello world!"); - x"#)?, true); + x"# + )?, + true + ); Ok(()) } pub mod mut_opaque_ref_module { - use rhai::INT; use rhai::export_module; + use rhai::INT; #[derive(Clone)] pub struct StatusMessage { os_code: Option, message: String, - is_ok: bool + is_ok: bool, } #[export_module] pub mod host_msg { - use super::{INT, StatusMessage}; + use super::{StatusMessage, INT}; pub fn new_message(is_ok: bool, message: &str) -> StatusMessage { StatusMessage { @@ -153,13 +167,17 @@ fn mut_opaque_ref_test() -> Result<(), Box> { r.insert("Host::Msg".to_string(), m); engine.set_module_resolver(Some(r)); - assert_eq!(engine.eval::( - r#"import "Host::Msg" as msg; + assert_eq!( + engine.eval::( + r#"import "Host::Msg" as msg; let success = "it worked"; let message1 = msg::new_message(true, success); let ok1 = msg::write_out_message(message1); let message2 = msg::new_os_message(true, 0); let ok2 = msg::write_out_message(message2); - ok1 && ok2"#)?, true); + ok1 && ok2"# + )?, + true + ); Ok(()) } diff --git a/codegen/ui_tests/first_shared_ref.rs b/codegen/ui_tests/first_shared_ref.rs index c8d6c9f4..d8c88abf 100644 --- a/codegen/ui_tests/first_shared_ref.rs +++ b/codegen/ui_tests/first_shared_ref.rs @@ -13,7 +13,12 @@ pub fn test_fn(input: &NonClonable) -> bool { } fn main() { - let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = NonClonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; if test_fn(n) { println!("yes"); } else { diff --git a/codegen/ui_tests/non_clonable.rs b/codegen/ui_tests/non_clonable.rs index c5c6d5a2..8283d3f8 100644 --- a/codegen/ui_tests/non_clonable.rs +++ b/codegen/ui_tests/non_clonable.rs @@ -13,7 +13,12 @@ pub fn test_fn(input: NonClonable) -> bool { } fn main() { - let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = NonClonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; if test_fn(n) { println!("yes"); } else { diff --git a/codegen/ui_tests/non_clonable_second.rs b/codegen/ui_tests/non_clonable_second.rs index d31e3436..dd2642ba 100644 --- a/codegen/ui_tests/non_clonable_second.rs +++ b/codegen/ui_tests/non_clonable_second.rs @@ -13,7 +13,12 @@ pub fn test_fn(a: u32, b: NonClonable) -> bool { } fn main() { - let n = NonClonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = NonClonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; if test_fn(10, n) { println!("yes"); } else { diff --git a/codegen/ui_tests/return_mut_ref.rs b/codegen/ui_tests/return_mut_ref.rs index 5568beee..aeeadbe5 100644 --- a/codegen/ui_tests/return_mut_ref.rs +++ b/codegen/ui_tests/return_mut_ref.rs @@ -14,7 +14,12 @@ pub fn test_fn(input: &mut Clonable) -> &mut bool { } fn main() { - let n = Clonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = Clonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; if test_fn(n) { println!("yes"); } else { diff --git a/codegen/ui_tests/return_pointer.rs b/codegen/ui_tests/return_pointer.rs index fa20d73c..4a7f8182 100644 --- a/codegen/ui_tests/return_pointer.rs +++ b/codegen/ui_tests/return_pointer.rs @@ -14,6 +14,14 @@ pub fn test_fn(input: Clonable) -> *const str { } fn main() { - let n = Clonable { a: 0.0, b: 10, c: 'a', d: true }; - println!("{}", unsafe { let ptr = test_fn(n); *ptr }); + let n = Clonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; + println!("{}", unsafe { + let ptr = test_fn(n); + *ptr + }); } diff --git a/codegen/ui_tests/return_shared_ref.rs b/codegen/ui_tests/return_shared_ref.rs index 384c3882..2091eada 100644 --- a/codegen/ui_tests/return_shared_ref.rs +++ b/codegen/ui_tests/return_shared_ref.rs @@ -9,11 +9,16 @@ struct Clonable { } #[export_fn] -pub fn test_fn(input: Clonable) -> & 'static str { +pub fn test_fn(input: Clonable) -> &'static str { "yes" } fn main() { - let n = Clonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = Clonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; println!("{}", test_fn(n)); } diff --git a/codegen/ui_tests/second_shared_ref.rs b/codegen/ui_tests/second_shared_ref.rs index cf09608d..06058814 100644 --- a/codegen/ui_tests/second_shared_ref.rs +++ b/codegen/ui_tests/second_shared_ref.rs @@ -14,7 +14,12 @@ pub fn test_fn(input: Clonable, factor: &bool) -> bool { } fn main() { - let n = Clonable { a: 0.0, b: 10, c: 'a', d: true }; + let n = Clonable { + a: 0.0, + b: 10, + c: 'a', + d: true, + }; if test_fn(n, &true) { println!("yes"); } else {