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

Provide macro in method builtins for better object value extraction #81

Open
phorward opened this issue Oct 23, 2022 · 2 comments
Open
Labels
help wanted Extra attention is needed

Comments

@phorward
Copy link
Member

Many methods in Tokay are currently defined exemplary this way:

tokay_method!("dict_len(dict)", {
    let dict = dict.borrow();

    if let Some(dict) = dict.object::<Dict>() {
        Ok(RefValue::from(dict.len()))
    } else {
        Err(Error::from(format!(
            "{} only accepts '{}' as parameter, not '{}'",
            __function,
            "dict",
            dict.name()
        )))
    }
});

The only relevant code implementing the method's functionality is

Ok(RefValue::from(dict.len()))

This could be replaced by a much shorter, nice macro call that could look as something like this:

tokay_method!("dict_len(dict)", {
    with_object!(dict, Dict, {
         Ok(RefValue::from(dict.len()))
    })
});

The following macros are required:

  • with_object - borrows an object for read, throws an error when given RefValue is not the given object
  • with_object_mut - borrows an object for write, throws an error when given RefValue is not the given object
@phorward phorward self-assigned this Oct 23, 2022
@phorward phorward added tokay feature New feature or request and removed feature New feature or request labels Oct 23, 2022
@phorward phorward added the help wanted Extra attention is needed label Nov 11, 2022
@phorward
Copy link
Member Author

After some tests, the initial idea of this issue isn't possible due Rusts macro hygiene feature.

@phorward phorward removed their assignment Nov 11, 2022
@phorward
Copy link
Member Author

phorward commented Jan 22, 2023

Alternatively to a macro, two functions

  • RefValue::with_object<T>(Fn<&T> -> Result<R, Err<Error>>) -> Result<R, Err<Error>>
  • RefValue::with_object_mut<T>(FnMut<&mut T> -> Result<R, Err<Error>>) -> Result<R, Err<Error>>

could be made available.. They borrow the value, cast to the particular object and run a function. In case the object cannot be borrowed or the type doesn't match, an error is generated and thrown.

@phorward phorward removed the tokay label Oct 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant