danielpclark / rutie

“The Tie Between Ruby and Rust.”
MIT License
940 stars 62 forks source link

A sugestion for a macro called typed_methods! #124

Open abinoam opened 4 years ago

abinoam commented 4 years ago

If I use the methods! macro I keep repeating the unwrapping of the args and treating them with a raise ArgumentError at the VM so it doesn't panic at the Rust side and it gives the opportunity to the Ruby code to treat the error. In my small project I've created a trait to easy this task.

use rutie::{AnyException, Object, VM};

pub trait ArgsTreating<R> {
    fn unwrap_or_rb_raise(self) -> R;
}

impl<A, E> ArgsTreating<A> for Result<A, E>
where
    A: Object,
    E: Into<AnyException> + std::fmt::Debug,
{
    fn unwrap_or_rb_raise(self) -> A {
        match self {
            Ok(object) => object,
            Err(exception) => {
                VM::raise_ex(exception);
                unreachable!();
            }
        }
    }
}

And I use it like this:

    fn pub_dot(other: MatrixRs) -> MatrixRs {
        let other = other.unwrap_or_rb_raise();
...

This gets tedious. Is it possible to create a sister macro called typed_methods! where this tedious work is done automatically?

Se we would have 3 sister macros: unsafe_methods! that doesn't wrap args methods! that wraps args and it gives the task for you to handle typed_methods (or other name) that handle the checking and automatically rb_raise for you so you have a clean code with the guarantee of having args with correct type.

Just an initial idea.

danielpclark commented 3 years ago

I really like this idea and I think the code sample you've provided a beautiful in illustrating how we can improve.

Does the word typed accurately describe what is being done here? The reason this question comes to mind is everything in Rust is already typed, so it doesn't appear to be named for the problem it's solving. It's a form of destructuring or safe unwrapping. Something like pure_methods! might be nice, or even better ruby_methods! given the context is being able to raise the error within the Ruby VM.

My preference leans towards ruby_methods!, but I'm open to persuasion on this one.

abinoam commented 3 years ago

I liked ruby_methods!.

Bear in mind that I'm Brazilian and I'm far from being a good english language reference. So, please double check my naming suggestion (in english).