Skip to content

Support #[implicit] and #[use_type] in #[cgp_impl] #195

@soareschen

Description

@soareschen

Similar to #194, we should add support for #[implicit] arguments, so that users can implement a CGP trait more easily without needing to define additional getter traits.

#[implicit] Arguments

For example, given:

#[cgp_component(AreaCalculator)]
pub trait CanCalculateArea {
    fn area(&self) -> f64;
}

One should be able to implement a RectangleArea provider without needing an additional HasRectangleFields getter trait:

#[cgp_impl(RectangleArea)]
impl AreaCalculator {
    fn area(
        &self,
        #[implicit] width: f64,
        #[implicit] height: f64,
    ) -> f64 {
        width * height
    }
}

Behind the scene, the desugaring is equivalent to:

#[cgp_impl(RectangleArea)]
impl AreaCalculator 
where
    Self: HasField<Symbol!("width"), Value = f64>
        + HasField<Symbol!("height"), Value = f64>,
{
    fn area(
        &self,
    ) -> f64 {
        let width = self.get_field(PhantomData::<Symbol!("width")>).clone();
        let height = self.get_field(PhantomData::<Symbol!("height")>).clone();

        width * height
    }
}

#[use_type] Modifier

Given:

#[cgp_component(AreaCalculator)]
pub trait CanCalculateArea: HasScalarType {
    fn area(&self) -> Self::Scalar;
}

we should enable the use of abstract type in #[cgp_impl] through the #[use_type] attribute:

#[cgp_impl(RectangleArea)]
#[use_type(HasScalarType::Scalar)]
impl AreaCalculator {
    fn area(
        &self,
        #[implicit] width: Scalar,
        #[implicit] height: Scalar,
    ) -> Scalar {
        width * height
    }
}

Behind the scene, the desugaring is equivalent to:

#[cgp_impl(RectangleArea)]
impl AreaCalculator 
where
    Self: HasScalarType
        + HasField<Symbol!("width"), Value = Self::Scalar>
        + HasField<Symbol!("height"), Value = Self::Scalar>,
{
    fn area(
        &self,
    ) -> Self::Scalar {
        let width = self.get_field(PhantomData::<Symbol!("width")>).clone();
        let height = self.get_field(PhantomData::<Symbol!("height")>).clone();

        width * height
    }
}

This would significantly improve the usability of abstract types, as the user would no longer need to keep adding the Self:: prefix or bind it to a local generic type.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions