Skip to content

Commit

Permalink
bug: unused generic type parameters (#1136)
Browse files Browse the repository at this point in the history
Unused generic type parameters will now be included as PhantomData in both generated structs and enums.
  • Loading branch information
segfault-magnet authored Oct 10, 2023
1 parent 22f10db commit 91ffd8f
Show file tree
Hide file tree
Showing 25 changed files with 1,040 additions and 658 deletions.
42 changes: 42 additions & 0 deletions docs/src/types/custom_types.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,45 @@ Your Rust code would look like this:
```rust,ignore
{{#include ../../../packages/fuels/tests/types_contracts.rs:generic}}
```

### Unused generic type parameters

Sway supports unused generic type parameters when declaring structs/enums:

```Rust
struct SomeStruct<T, K> {
field: u64
}

enum SomeEnum<T, K> {
One: u64
}

```

If you tried the same in Rust you'd get complaints that `T` and `K` must be used or removed. When generating Rust bindings for such types we make use of the [`PhantomData`](https://doc.rust-lang.org/std/marker/struct.PhantomData.html#unused-type-parameters) type. The generated bindings for the above example would look something like this:

```Rust
struct SomeStruct<T, K> {
pub field: u64,
pub _unused_generic_0: PhantomData<T>
pub _unused_generic_1: PhantomData<K>
}

enum SomeEnum<T, K> {
One(u64),
IgnoreMe(PhantomData<T>, PhantomData<K>)
}
```

To lessen the impact to developer experience you may use `SomeStruct::new` to initialize the above structure without bothering with the `PhantomData`s:

```rust,ignore
{{#include ../../../examples/types/src/lib.rs:unused_generics_struct}}
```

If your struct doesn't have any fields we'll also derive `Default`. As for enums all `PhantomData`s are placed inside a new variant called `IgnoreMe` which you'll need to ignore in your matches:

```rust,ignore
{{#include ../../../examples/types/src/lib.rs:unused_generics_enum}}
```
153 changes: 153 additions & 0 deletions examples/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,157 @@ mod tests {
// ANCHOR_END: type_conversion
Ok(())
}

#[tokio::test]
async fn unused_generics() -> Result<()> {
use fuels::prelude::*;
abigen!(Contract(
name = "MyContract",
abi = r#" {
"types": [
{
"typeId": 0,
"type": "()",
"components": [],
"typeParameters": null
},
{
"typeId": 1,
"type": "enum MyEnum",
"components": [
{
"name": "One",
"type": 7,
"typeArguments": null
}
],
"typeParameters": [
3,
2
]
},
{
"typeId": 2,
"type": "generic K",
"components": null,
"typeParameters": null
},
{
"typeId": 3,
"type": "generic T",
"components": null,
"typeParameters": null
},
{
"typeId": 4,
"type": "struct MyStruct",
"components": [
{
"name": "field",
"type": 7,
"typeArguments": null
}
],
"typeParameters": [
3,
2
]
},
{
"typeId": 5,
"type": "u16",
"components": null,
"typeParameters": null
},
{
"typeId": 6,
"type": "u32",
"components": null,
"typeParameters": null
},
{
"typeId": 7,
"type": "u64",
"components": null,
"typeParameters": null
},
{
"typeId": 8,
"type": "u8",
"components": null,
"typeParameters": null
}
],
"functions": [
{
"inputs": [
{
"name": "arg",
"type": 4,
"typeArguments": [
{
"name": "",
"type": 8,
"typeArguments": null
},
{
"name": "",
"type": 5,
"typeArguments": null
}
]
},
{
"name": "arg_2",
"type": 1,
"typeArguments": [
{
"name": "",
"type": 6,
"typeArguments": null
},
{
"name": "",
"type": 7,
"typeArguments": null
}
]
}
],
"name": "test_function",
"output": {
"name": "",
"type": 0,
"typeArguments": null
},
"attributes": null
}
],
"loggedTypes": [],
"messagesTypes": [],
"configurables": []
}"#
));

// ANCHOR: unused_generics_struct
assert_eq!(
<MyStruct<u16, u32>>::new(15),
MyStruct {
field: 15,
_unused_generic_0: std::marker::PhantomData,
_unused_generic_1: std::marker::PhantomData
}
);
// ANCHOR_END: unused_generics_struct

let my_enum = <MyEnum<u32, u64>>::One(15);
// ANCHOR: unused_generics_enum
match my_enum {
MyEnum::One(_value) => {}
MyEnum::IgnoreMe(..) => panic!("Will never receive this variant"),
}
// ANCHOR_END: unused_generics_enum

Ok(())
}
}
4 changes: 4 additions & 0 deletions packages/fuels-code-gen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,9 @@ regex = { workspace = true }
serde_json = { workspace = true }
syn = { workspace = true }

[dev-dependencies]
pretty_assertions = "1.4"


[package.metadata.cargo-machete]
ignored = ["Inflector"]
Original file line number Diff line number Diff line change
Expand Up @@ -162,16 +162,21 @@ pub(crate) fn expand_fn(abi_fun: &FullABIFunction) -> Result<TokenStream> {
};
generator.set_body(body);

Ok(generator.into())
Ok(generator.generate())
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;

use fuel_abi_types::abi::program::{ABIFunction, ProgramABI, TypeApplication, TypeDeclaration};
use fuel_abi_types::abi::{
full_program::FullABIFunction,
program::{ABIFunction, ProgramABI, TypeApplication, TypeDeclaration},
};
use pretty_assertions::assert_eq;
use quote::quote;

use super::*;
use crate::{error::Result, program_bindings::abigen::bindings::contract::expand_fn};

#[test]
fn test_expand_fn_simple_abi() -> Result<()> {
Expand Down Expand Up @@ -395,13 +400,13 @@ mod tests {

let expected = quote! {
#[doc = "Calls the contract's `HelloWorld` function"]
pub fn HelloWorld(&self, bimbam: bool) -> ::fuels::programs::contract::ContractCallHandler<T, ()> {
pub fn HelloWorld(&self, bimbam: ::core::primitive::bool) -> ::fuels::programs::contract::ContractCallHandler<T, ()> {
::fuels::programs::contract::method_hash(
self.contract_id.clone(),
self.account.clone(),
::fuels::core::codec::resolve_fn_selector(
"HelloWorld",
&[<bool as ::fuels::core::traits::Parameterize>::param_type()]
&[<::core::primitive::bool as ::fuels::core::traits::Parameterize>::param_type()]
),
&[::fuels::core::traits::Tokenizable::into_token(bimbam)],
self.log_decoder.clone(),
Expand Down
Loading

0 comments on commit 91ffd8f

Please sign in to comment.