fiberplane / fp-bindgen

Bindings generator for full-stack WASM plugins
https://fiberplane.dev
Apache License 2.0
479 stars 18 forks source link

Array with length of constant expression cannot derive `Serializable` #144

Open MikuroXina opened 2 years ago

MikuroXina commented 2 years ago

Hello, I'm using this crate for creating a plugin system for my editor application.

I have added matrix structs with deriving Serializable as:

#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Serializable)]
pub struct Mat2x2 {
    pub components: [f64; 2 * 2],
}

#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Serializable)]
pub struct Mat2x3 {
    pub components: [f64; 3 * 2],
}

// :
// :

#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Serializable)]
pub struct Mat4x4 {
    pub components: [f64; 4 * 4],
}
// Actually, all combinations of rows and columns are made by `paste!` and my macro. So I don't want to inline them manually if possible.

But it doesn't work against the intention and shows this error (formatted):

Only value types are supported. Incompatible type in struct field: Field {
    attrs: [],
    vis: Public(VisPublic { pub_token: Pub }),
    ident: Some(Ident { ident: "components", span: #94 bytes(6040..6050) }),
    colon_token: Some(Colon),
    ty: Array(TypeArray {
        bracket_token: Bracket,
        elem: Path(TypePath {
            qself: None,
            path: Path {
                leading_colon: None,
                segments: [PathSegment {
                    ident: Ident {
                        ident: "f64",
                        span: #94 bytes(6053..6056)
                    },
                    arguments: None
                }]
            }
        }),
        semi_token: Semi,
        len: Binary(ExprBinary {
            attrs: [],
            left: Lit(ExprLit {
                attrs: [],
                lit: Int(LitInt { token: 2 })
            }),
            op: Mul(Star),
            right: Lit(ExprLit {
                attrs: [],
                lit: Int(LitInt { token: 2 })
            })
        })
    })
}

It seems that Serializable cannot be derived by the fixed array with length of using const variable too. According to the behaviour of parsing, it is like not to accept except an integer literal.

const TWO: usize = 2;

#[repr(C)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Serializable)]
pub struct Vec2 {
    pub components: [f64; TWO], // errors
}

Then, I implemented Serializable trait manually for matrix structs as below and it works well.

// :
impl fp_bindgen::prelude::Serializable for Mat3x3 {
    fn ident() -> fp_bindgen::prelude::TypeIdent {
        fp_bindgen::prelude::TypeIdent::from(stringify!(Mat3x3))
    }
    fn ty() -> fp_bindgen::prelude::Type {
        fp_bindgen::prelude::Type::from_item(
            &format!(
                concat!("#[repr(C)] pub struct ",
                    stringify!(Mat3x3),
                    " {{ pub components : [f64 ; {}], }}"),
                $cols * $rows,
            ),
        )
    }
    fn collect_types(types: &mut fp_bindgen::prelude::TypeMap) {
        if let std::collections::btree_map::Entry::Vacant(entry)
            = types.entry(Self::ident())
        {
            entry.insert(Self::ty());
            <[f64; 3 * 3]>::collect_types(types);
        }
    }
}
// :

Is this a bug or an unsupported feature?

arendjr commented 2 years ago

I believe currently it only works if you use an integer literal for your dimension (see for example: https://github.com/fiberplane/fp-bindgen/blob/main/examples/example-protocol/src/main.rs#L64). But we don't evaluate other types of expressions.

I'll leave this open as a feature request, but I'm not sure how difficult this would be to implement, to be honest.