Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code refactor. #751

Merged
merged 10 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
- uses: actions-rs/cargo@v1
with:
command: check
args: "--features decimal,metadata,serde,debugging"

# typical build with various feature combinations
build:
Expand Down
2 changes: 1 addition & 1 deletion codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ metadata = []

[dependencies]
proc-macro2 = "1.0.0"
syn = { version = "1.0.0", features = ["full", "parsing", "printing", "proc-macro", "extra-traits"] }
syn = { version = "2.0.0", features = ["full", "parsing", "printing", "proc-macro", "extra-traits"] }
quote = "1.0.0"

[dev-dependencies]
Expand Down
70 changes: 34 additions & 36 deletions codegen/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ pub enum ExportScope {
}

impl Default for ExportScope {
fn default() -> ExportScope {
ExportScope::PubOnly
fn default() -> Self {
Self::PubOnly
}
}

Expand Down Expand Up @@ -118,17 +118,11 @@ pub fn inner_item_attributes<T: ExportedParams>(
attr_name: &str,
) -> syn::Result<T> {
// Find the #[rhai_fn] attribute which will turn be read for function parameters.
if let Some(index) = attrs
.iter()
.position(|a| a.path.get_ident().map_or(false, |i| *i == attr_name))
{
if let Some(index) = attrs.iter().position(|a| a.path().is_ident(attr_name)) {
let rhai_fn_attr = attrs.remove(index);

// Cannot have more than one #[rhai_fn]
if let Some(duplicate) = attrs
.iter()
.find(|a| a.path.get_ident().map_or(false, |i| *i == attr_name))
{
if let Some(duplicate) = attrs.iter().find(|&a| a.path().is_ident(attr_name)) {
return Err(syn::Error::new(
duplicate.span(),
format!("duplicated attribute '{attr_name}'"),
Expand All @@ -148,33 +142,37 @@ pub fn doc_attributes(attrs: &[syn::Attribute]) -> syn::Result<Vec<String>> {
let mut buf = String::new();

for attr in attrs {
if let Some(i) = attr.path.get_ident() {
if *i == "doc" {
if let syn::Meta::NameValue(syn::MetaNameValue {
lit: syn::Lit::Str(s),
if !attr.path().is_ident("doc") {
continue;
}

if let syn::Meta::NameValue(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(ref s),
..
}) = attr.parse_meta()?
{
let mut line = s.value();

if line.contains('\n') {
// Must be a block comment `/** ... */`
if !buf.is_empty() {
comments.push(buf.clone());
buf.clear();
}
line.insert_str(0, "/**");
line.push_str("*/");
comments.push(line);
} else {
// Single line - assume it is `///`
if !buf.is_empty() {
buf.push('\n');
}
buf.push_str("///");
buf.push_str(&line);
}
}),
..
}) = attr.meta
{
let mut line = s.value();

if line.contains('\n') {
// Must be a block comment `/** ... */`
if !buf.is_empty() {
comments.push(buf.clone());
buf.clear();
}
line.insert_str(0, "/**");
line.push_str("*/");
comments.push(line);
} else {
// Single line - assume it is `///`
if !buf.is_empty() {
buf.push('\n');
}
buf.push_str("///");
buf.push_str(&line);
}
}
}
Expand All @@ -189,7 +187,7 @@ pub fn doc_attributes(attrs: &[syn::Attribute]) -> syn::Result<Vec<String>> {
pub fn collect_cfg_attr(attrs: &[syn::Attribute]) -> Vec<syn::Attribute> {
attrs
.iter()
.filter(|&a| a.path.get_ident().map_or(false, |i| *i == "cfg"))
.filter(|&a| a.path().is_ident("cfg"))
.cloned()
.collect()
}
10 changes: 5 additions & 5 deletions codegen/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ pub enum FnSpecialAccess {
}

impl Default for FnSpecialAccess {
fn default() -> FnSpecialAccess {
FnSpecialAccess::None
fn default() -> Self {
Self::None
}
}

Expand Down Expand Up @@ -309,7 +309,7 @@ impl Parse for ExportedFn {
{
pass_context = true;
}
_ => {}
_ => (),
}
}

Expand Down Expand Up @@ -389,7 +389,7 @@ impl Parse for ExportedFn {
"Rhai functions cannot return references",
))
}
_ => {}
_ => (),
}
}
Ok(ExportedFn {
Expand Down Expand Up @@ -597,7 +597,7 @@ impl ExportedFn {
"index setter cannot return any value",
))
}
_ => {}
_ => (),
}

self.params = params;
Expand Down
15 changes: 8 additions & 7 deletions codegen/src/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,14 @@ pub fn parse_register_macro(
syn::Expr::Lit(lit_str) => quote_spanned!(items[1].span() => #lit_str),
expr => quote! { #expr },
};
let rust_mod_path = if let syn::Expr::Path(ref path) = &items[2] {
path.path.clone()
} else {
return Err(syn::Error::new(
items[2].span(),
"third argument must be a function name",
));
let rust_mod_path = match &items[2] {
syn::Expr::Path(ref path) => path.path.clone(),
_ => {
return Err(syn::Error::new(
items[2].span(),
"third argument must be a function name",
))
}
};
let module = items.remove(0);
Ok((module, export_name, rust_mod_path))
Expand Down
4 changes: 2 additions & 2 deletions codegen/ui_tests/export_mod_cfg.stderr
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
error: expected attribute arguments in parentheses: #[rhai_fn(...)]
--> ui_tests/export_mod_cfg.rs:12:1
--> ui_tests/export_mod_cfg.rs:12:3
|
12 | #[rhai_fn]
| ^^^^^^^^^^
| ^^^^^^^

error[E0433]: failed to resolve: use of undeclared crate or module `test_mod`
--> ui_tests/export_mod_cfg.rs:23:8
Expand Down
9 changes: 4 additions & 5 deletions src/api/build_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,9 @@ impl<'a, T: Variant + Clone> TypeBuilder<'a, T> {
impl<'a, T: Variant + Clone> Drop for TypeBuilder<'a, T> {
#[inline]
fn drop(&mut self) {
if let Some(name) = self.name {
self.engine.register_type_with_name::<T>(name);
} else {
self.engine.register_type::<T>();
}
match self.name {
Some(name) => self.engine.register_type_with_name::<T>(name),
None => self.engine.register_type::<T>(),
};
}
}
30 changes: 18 additions & 12 deletions src/api/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,15 @@ impl Engine {

let mut interner;
let mut guard;
let interned_strings = if let Some(ref interner) = self.interned_strings {
guard = locked_write(interner);
&mut *guard
} else {
interner = StringsInterner::new();
&mut interner
let interned_strings = match self.interned_strings {
Some(ref interner) => {
guard = locked_write(interner);
&mut *guard
}
None => {
interner = StringsInterner::new();
&mut interner
}
};

let state = &mut ParseState::new(scope, interned_strings, tc);
Expand Down Expand Up @@ -308,12 +311,15 @@ impl Engine {

let mut interner;
let mut guard;
let interned_strings = if let Some(ref interner) = self.interned_strings {
guard = locked_write(interner);
&mut *guard
} else {
interner = StringsInterner::new();
&mut interner
let interned_strings = match self.interned_strings {
Some(ref interner) => {
guard = locked_write(interner);
&mut *guard
}
None => {
interner = StringsInterner::new();
&mut interner
}
};

let state = &mut ParseState::new(Some(scope), interned_strings, t);
Expand Down
15 changes: 9 additions & 6 deletions src/api/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,15 @@ impl Engine {
let ast = {
let mut interner;
let mut guard;
let interned_strings = if let Some(ref interner) = self.interned_strings {
guard = locked_write(interner);
&mut *guard
} else {
interner = StringsInterner::new();
&mut interner
let interned_strings = match self.interned_strings {
Some(ref interner) => {
guard = locked_write(interner);
&mut *guard
}
None => {
interner = StringsInterner::new();
&mut interner
}
};

let (stream, tc) = self.lex_raw(&scripts, self.token_mapper.as_deref());
Expand Down
9 changes: 5 additions & 4 deletions src/api/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,11 @@ impl Engine {

if contents.starts_with("#!") {
// Remove shebang
if let Some(n) = contents.find('\n') {
contents.drain(0..n).count();
} else {
contents.clear();
match contents.find('\n') {
Some(n) => {
contents.drain(0..n).count();
}
None => contents.clear(),
}
};

Expand Down
9 changes: 3 additions & 6 deletions src/api/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,12 +227,9 @@ impl Engine {
#[must_use]
pub(crate) fn format_type_name<'a>(&'a self, name: &'a str) -> std::borrow::Cow<'a, str> {
if let Some(x) = name.strip_prefix("&mut ") {
let r = self.format_type_name(x);

return if x == r {
name.into()
} else {
format!("&mut {r}").into()
return match self.format_type_name(x) {
r if r == x => name.into(),
r => format!("&mut {r}").into(),
};
}

Expand Down
25 changes: 13 additions & 12 deletions src/api/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,15 @@ impl Engine {
let ast = {
let mut interner;
let mut guard;
let interned_strings = if let Some(ref interner) = self.interned_strings {
guard = locked_write(interner);
&mut *guard
} else {
interner = StringsInterner::new();
&mut interner
let interned_strings = match self.interned_strings {
Some(ref interner) => {
guard = locked_write(interner);
&mut *guard
}
None => {
interner = StringsInterner::new();
&mut interner
}
};

let state = &mut ParseState::new(None, interned_strings, tokenizer_control);
Expand Down Expand Up @@ -174,12 +177,10 @@ pub fn format_map_as_json(map: &Map) -> String {
write!(result, "{key:?}").unwrap();
result.push(':');

if let Some(val) = value.read_lock::<Map>() {
result.push_str(&format_map_as_json(&val));
} else if value.is_unit() {
result.push_str("null");
} else {
write!(result, "{value:?}").unwrap();
match value.read_lock::<Map>() {
Some(val) => result.push_str(&format_map_as_json(&val)),
None if value.is_unit() => result.push_str("null"),
None => write!(result, "{value:?}").unwrap(),
}
}

Expand Down
9 changes: 5 additions & 4 deletions src/api/optimize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,11 @@ impl Engine {
);

#[cfg(feature = "metadata")]
if let Some(doc) = ast.doc_mut() {
_new_ast.set_doc(std::mem::take(doc));
} else {
_new_ast.clear_doc();
match ast.doc_mut() {
Some(doc) => _new_ast.set_doc(std::mem::take(doc)),
None => {
_new_ast.clear_doc();
}
}

_new_ast
Expand Down
15 changes: 9 additions & 6 deletions src/api/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,15 @@ impl Engine {

let mut interner;
let mut guard;
let interned_strings = if let Some(ref interner) = self.interned_strings {
guard = locked_write(interner);
&mut *guard
} else {
interner = StringsInterner::new();
&mut interner
let interned_strings = match self.interned_strings {
Some(ref interner) => {
guard = locked_write(interner);
&mut *guard
}
None => {
interner = StringsInterner::new();
&mut interner
}
};

let state = &mut ParseState::new(Some(scope), interned_strings, tc);
Expand Down
Loading
Loading