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

[Merged by Bors] - bevy_reflect: Add #[reflect(default)] attribute for FromReflect #4140

Closed
wants to merge 5 commits into from

Conversation

MrGVSV
Copy link
Member

@MrGVSV MrGVSV commented Mar 7, 2022

Objective

Currently, FromReflect makes a couple assumptions:

  • Ignored fields must implement Default
  • Active fields must implement FromReflect
  • The reflected must be fully populated for active fields (can't use an empty DynamicStruct)

However, one or both of these requirements might be unachievable, such as for external types. In these cases, it might be nice to tell FromReflect to use a custom default.

Solution

Added the #[reflect(default)] derive helper attribute. This attribute can be applied to any field (ignored or not) and will allow a default value to be specified in place of the regular from_reflect() call.

It takes two forms: #[reflect(default)] and #[reflect(default = "some_func")]. The former specifies that Default::default() should be used while the latter specifies that some_func() should be used. This is pretty much how serde does it.

Example

#[derive(Reflect, FromReflect)]
struct MyStruct {
  // Use `Default::default()`
  #[reflect(default)]
  foo: String,

  // Use `get_bar_default()`
  #[reflect(default = "get_bar_default")]
  #[reflect(ignore)]
  bar: usize,
}

fn get_bar_default() -> usize {
  123
}

Active Fields

As an added benefit, this also allows active fields to be completely missing from their dynamic object. This is because the attribute tells FromReflect how to handle missing active fields (it still tries to use from_reflect first so the FromReflect trait is still required).

let dyn_struct = DynamicStruct::default();

// We can do this without actually including the active fields since they have `#[reflect(default)]`
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);

Container Defaults

Also, with the addition of #3733, people will likely start adding #[reflect(Default)] to their types now. Just like with the fields, we can use this to mark the entire container as "defaultable". This grants us the ability to completely remove the field markers altogether if our type implements Default (and we're okay with fields using that instead of their own Default impls):

#[derive(Reflect, FromReflect)]
#[reflect(Default)]
struct MyStruct {
  foo: String,
  #[reflect(ignore)]
  bar: usize,
}

impl Default for MyStruct {
  fn default() -> Self {
    Self {
      foo: String::from("Hello"),
      bar: 123,
    }
  }
}

// Again, we can now construct this from nothing pretty much
let dyn_struct = DynamicStruct::default();
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);

Now if any field is missing when using FromReflect, we simply fallback onto the container's Default implementation.

This behavior can be completely overridden on a per-field basis, of course, by simply defining those same field attributes like before.

Related


Changelog

  • Added #[reflect(default)] field attribute for FromReflect
    • Allows missing fields to be given a default value when using FromReflect
    • #[reflect(default)] - Use the field's Default implementation
    • #[reflect(default = "some_fn")] - Use a custom function to get the default value
  • Allow #[reflect(Default)] to have a secondary usage as a container attribute
    • Allows missing fields to be given a default value based on the container's Default impl when using FromReflect

@github-actions github-actions bot added the S-Needs-Triage This issue needs to be labelled label Mar 7, 2022
@james7132 james7132 added A-Reflection Runtime information about types C-Feature A new feature, making something new possible and removed S-Needs-Triage This issue needs to be labelled labels Mar 7, 2022
@MrGVSV MrGVSV changed the title Add #[reflect(default)] attribute for FromReflect bevy_reflect: Add #[reflect(default)] attribute for FromReflect Mar 28, 2022
@MrGVSV
Copy link
Member Author

MrGVSV commented May 8, 2022

With #3733 merged, I'm wondering: would also be good to make it so we use the struct's Default impl for unmarked ignored fields (if #[reflect(Default)] is defined)?

So for example, value would default to 123 instead of its usual 0 here:

#[reflect(Default)]
struct Foo {
  value: i32
}

impl Default for Foo {
  fn default() -> Self {
    Self {
      value: 123
    }
  }
}

let foo: Foo = FromReflect::from_reflect(dyn_foo_struct);
assert_eq!(123, foo.value);

This could be convenient for when defining custom Default impls. However, it could also be counter-intuitive and possibly footgunny since it would only be applicable for when #[reflect(Default)] is used.

Alternatively, we could define a container attribute for the struct itself, like serde does. This might result in more macro clutter, though...

Copy link
Contributor

@PROMETHIA-27 PROMETHIA-27 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests for correct behavior would probably also be a good idea.

I like the changes overall, but mixing all of the cleanup changes with the actual feature additions does make it harder to review.

crates/bevy_reflect/bevy_reflect_derive/src/attributes.rs Outdated Show resolved Hide resolved
@MrGVSV
Copy link
Member Author

MrGVSV commented May 9, 2022

Tests for correct behavior would probably also be a good idea.

Lol was just adding some since I noticed that too.

I like the changes overall, but mixing all of the cleanup changes with the actual feature additions does make it harder to review.

Would it be better if I split it up then? I like the changes because they make the end product a lot nicer to read/maintain. But if it's too difficult to review, then I can try to turn the cleanup changes into a followup PR.

@MrGVSV
Copy link
Member Author

MrGVSV commented May 9, 2022

Also @PROMETHIA-27, any thoughts on #4140 (comment)?

I left a review note on your PR (#4540) saying that this PR would help with ctor stuff. However, looking at it now I realize I never actually implemented that portion of it (although it would still work if you defined #[reflect(default)] on all fields).

@PROMETHIA-27
Copy link
Contributor

I think it makes sense that if you reflect Default on a type, then creating an instance of that type from e.g. an empty dynamic struct should have all default values. So yeah, I think it's a good idea. I'm somewhat hesitant but I think it makes more sense than each value defaulting to its own default value. But also, it might cause a niche backwards incompatibility issue if that's done- I'm not sure if it's worth worrying about (or worth intentionally causing anyway) but good to keep in mind I think.
E.g. if I have the type

#[derive(Reflect)]
#[reflect(Default)]
struct Foo {
    x: i32
}

where x defaults to 12, this would suddenly change behavior from a 0'd x to 12 without changing the code. But reflect(Default) was also just added and hasn't been released in a version yet, so chances are no one is going to run into this.

@MrGVSV
Copy link
Member Author

MrGVSV commented May 9, 2022

where x defaults to 12, this would suddenly change behavior from a 0'd x to 12 without changing the code.

Yeah that was one of the concerns. Although, I think it makes sense that using #[reflect(Default)] would act much like serde's container #[serde(default)]. And thinking on it more, using an alternative mechanism (like our own container #[reflect(default)]) could result in weird/unexpected behavior.

So I think if a user lets the reflection system know it implements Default, then we should use it.

But reflect(Default) was also just added and hasn't been released in a version yet, so chances are no one is going to run into this.

Yeah this might be a good reason to add it before 0.8 is released (ideally).

@MrGVSV
Copy link
Member Author

MrGVSV commented May 10, 2022

Going to put this in draft form until #4712 is merged. We could just revert to the first commit of this PR and rebase from there, but I think it would just be easier to wait and see if the cleanup PR gets accepted/merged first so I can use some of the niceties added there.

If it's rejected or gets blocked for a long time, I'll go ahead and do the revert and rebase.

@MrGVSV MrGVSV force-pushed the reflect-default-attribute branch from 3c16ac3 to 7fcce32 Compare May 17, 2022 06:34
@MrGVSV
Copy link
Member Author

MrGVSV commented May 17, 2022

Rebased and reopened!

@MrGVSV MrGVSV marked this pull request as ready for review May 17, 2022 06:43
@MrGVSV MrGVSV requested a review from PROMETHIA-27 May 17, 2022 06:43
@MrGVSV
Copy link
Member Author

MrGVSV commented May 17, 2022

Although, I think it makes sense that using #[reflect(Default)] would act much like serde's container #[serde(default)]

Added this behavior!

Copy link
Member

@alice-i-cecile alice-i-cecile left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some small nits to clean up, then this LGTM. We'll need a second reviewer (@PROMETHIA-27?) before I can merge this though; it's not trivial and more eyes will help.

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Copy link
Contributor

@PROMETHIA-27 PROMETHIA-27 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@alice-i-cecile
Copy link
Member

bors r+

bors bot pushed a commit that referenced this pull request May 30, 2022
…4140)

# Objective

Currently, `FromReflect` makes a couple assumptions:

* Ignored fields must implement `Default`
* Active fields must implement `FromReflect`
* The reflected must be fully populated for active fields (can't use an empty `DynamicStruct`)

However, one or both of these requirements might be unachievable, such as for external types. In these cases, it might be nice to tell `FromReflect` to use a custom default.

## Solution

Added the `#[reflect(default)]` derive helper attribute. This attribute can be applied to any field (ignored or not) and will allow a default value to be specified in place of the regular `from_reflect()` call. 

It takes two forms: `#[reflect(default)]` and `#[reflect(default = "some_func")]`. The former specifies that `Default::default()` should be used while the latter specifies that `some_func()` should be used. This is pretty much [how serde does it](https://serde.rs/field-attrs.html#default).

### Example

```rust
#[derive(Reflect, FromReflect)]
struct MyStruct {
  // Use `Default::default()`
  #[reflect(default)]
  foo: String,

  // Use `get_bar_default()`
  #[reflect(default = "get_bar_default")]
  #[reflect(ignore)]
  bar: usize,
}

fn get_bar_default() -> usize {
  123
}
```

### Active Fields

As an added benefit, this also allows active fields to be completely missing from their dynamic object. This is because the attribute tells `FromReflect` how to handle missing active fields (it still tries to use `from_reflect` first so the `FromReflect` trait is still required).

```rust
let dyn_struct = DynamicStruct::default();

// We can do this without actually including the active fields since they have `#[reflect(default)]`
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

### Container Defaults

Also, with the addition of #3733, people will likely start adding `#[reflect(Default)]` to their types now. Just like with the fields, we can use this to mark the entire container as "defaultable". This grants us the ability to completely remove the field markers altogether if our type implements `Default` (and we're okay with fields using that instead of their own `Default` impls):

```rust
#[derive(Reflect, FromReflect)]
#[reflect(Default)]
struct MyStruct {
  foo: String,
  #[reflect(ignore)]
  bar: usize,
}

impl Default for MyStruct {
  fn default() -> Self {
    Self {
      foo: String::from("Hello"),
      bar: 123,
    }
  }
}

// Again, we can now construct this from nothing pretty much
let dyn_struct = DynamicStruct::default();
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

Now if _any_ field is missing when using `FromReflect`, we simply fallback onto the container's `Default` implementation.

This behavior can be completely overridden on a per-field basis, of course, by simply defining those same field attributes like before.

### Related

* #3733
* #1395
* #2377

---

## Changelog

* Added `#[reflect(default)]` field attribute for `FromReflect`
  * Allows missing fields to be given a default value when using `FromReflect`
  * `#[reflect(default)]` - Use the field's `Default` implementation
  * `#[reflect(default = "some_fn")]` - Use a custom function to get the default value
* Allow `#[reflect(Default)]` to have a secondary usage as a container attribute
  * Allows missing fields to be given a default value based on the container's `Default` impl when using `FromReflect`


Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
@bors
Copy link
Contributor

bors bot commented May 30, 2022

Build failed (retrying...):

bors bot pushed a commit that referenced this pull request May 30, 2022
…4140)

# Objective

Currently, `FromReflect` makes a couple assumptions:

* Ignored fields must implement `Default`
* Active fields must implement `FromReflect`
* The reflected must be fully populated for active fields (can't use an empty `DynamicStruct`)

However, one or both of these requirements might be unachievable, such as for external types. In these cases, it might be nice to tell `FromReflect` to use a custom default.

## Solution

Added the `#[reflect(default)]` derive helper attribute. This attribute can be applied to any field (ignored or not) and will allow a default value to be specified in place of the regular `from_reflect()` call. 

It takes two forms: `#[reflect(default)]` and `#[reflect(default = "some_func")]`. The former specifies that `Default::default()` should be used while the latter specifies that `some_func()` should be used. This is pretty much [how serde does it](https://serde.rs/field-attrs.html#default).

### Example

```rust
#[derive(Reflect, FromReflect)]
struct MyStruct {
  // Use `Default::default()`
  #[reflect(default)]
  foo: String,

  // Use `get_bar_default()`
  #[reflect(default = "get_bar_default")]
  #[reflect(ignore)]
  bar: usize,
}

fn get_bar_default() -> usize {
  123
}
```

### Active Fields

As an added benefit, this also allows active fields to be completely missing from their dynamic object. This is because the attribute tells `FromReflect` how to handle missing active fields (it still tries to use `from_reflect` first so the `FromReflect` trait is still required).

```rust
let dyn_struct = DynamicStruct::default();

// We can do this without actually including the active fields since they have `#[reflect(default)]`
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

### Container Defaults

Also, with the addition of #3733, people will likely start adding `#[reflect(Default)]` to their types now. Just like with the fields, we can use this to mark the entire container as "defaultable". This grants us the ability to completely remove the field markers altogether if our type implements `Default` (and we're okay with fields using that instead of their own `Default` impls):

```rust
#[derive(Reflect, FromReflect)]
#[reflect(Default)]
struct MyStruct {
  foo: String,
  #[reflect(ignore)]
  bar: usize,
}

impl Default for MyStruct {
  fn default() -> Self {
    Self {
      foo: String::from("Hello"),
      bar: 123,
    }
  }
}

// Again, we can now construct this from nothing pretty much
let dyn_struct = DynamicStruct::default();
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

Now if _any_ field is missing when using `FromReflect`, we simply fallback onto the container's `Default` implementation.

This behavior can be completely overridden on a per-field basis, of course, by simply defining those same field attributes like before.

### Related

* #3733
* #1395
* #2377

---

## Changelog

* Added `#[reflect(default)]` field attribute for `FromReflect`
  * Allows missing fields to be given a default value when using `FromReflect`
  * `#[reflect(default)]` - Use the field's `Default` implementation
  * `#[reflect(default = "some_fn")]` - Use a custom function to get the default value
* Allow `#[reflect(Default)]` to have a secondary usage as a container attribute
  * Allows missing fields to be given a default value based on the container's `Default` impl when using `FromReflect`


Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
@bors bors bot changed the title bevy_reflect: Add #[reflect(default)] attribute for FromReflect [Merged by Bors] - bevy_reflect: Add #[reflect(default)] attribute for FromReflect May 30, 2022
@bors bors bot closed this May 30, 2022
@MrGVSV MrGVSV deleted the reflect-default-attribute branch May 30, 2022 19:25
james7132 pushed a commit to james7132/bevy that referenced this pull request Jun 7, 2022
…evyengine#4140)

# Objective

Currently, `FromReflect` makes a couple assumptions:

* Ignored fields must implement `Default`
* Active fields must implement `FromReflect`
* The reflected must be fully populated for active fields (can't use an empty `DynamicStruct`)

However, one or both of these requirements might be unachievable, such as for external types. In these cases, it might be nice to tell `FromReflect` to use a custom default.

## Solution

Added the `#[reflect(default)]` derive helper attribute. This attribute can be applied to any field (ignored or not) and will allow a default value to be specified in place of the regular `from_reflect()` call. 

It takes two forms: `#[reflect(default)]` and `#[reflect(default = "some_func")]`. The former specifies that `Default::default()` should be used while the latter specifies that `some_func()` should be used. This is pretty much [how serde does it](https://serde.rs/field-attrs.html#default).

### Example

```rust
#[derive(Reflect, FromReflect)]
struct MyStruct {
  // Use `Default::default()`
  #[reflect(default)]
  foo: String,

  // Use `get_bar_default()`
  #[reflect(default = "get_bar_default")]
  #[reflect(ignore)]
  bar: usize,
}

fn get_bar_default() -> usize {
  123
}
```

### Active Fields

As an added benefit, this also allows active fields to be completely missing from their dynamic object. This is because the attribute tells `FromReflect` how to handle missing active fields (it still tries to use `from_reflect` first so the `FromReflect` trait is still required).

```rust
let dyn_struct = DynamicStruct::default();

// We can do this without actually including the active fields since they have `#[reflect(default)]`
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

### Container Defaults

Also, with the addition of bevyengine#3733, people will likely start adding `#[reflect(Default)]` to their types now. Just like with the fields, we can use this to mark the entire container as "defaultable". This grants us the ability to completely remove the field markers altogether if our type implements `Default` (and we're okay with fields using that instead of their own `Default` impls):

```rust
#[derive(Reflect, FromReflect)]
#[reflect(Default)]
struct MyStruct {
  foo: String,
  #[reflect(ignore)]
  bar: usize,
}

impl Default for MyStruct {
  fn default() -> Self {
    Self {
      foo: String::from("Hello"),
      bar: 123,
    }
  }
}

// Again, we can now construct this from nothing pretty much
let dyn_struct = DynamicStruct::default();
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

Now if _any_ field is missing when using `FromReflect`, we simply fallback onto the container's `Default` implementation.

This behavior can be completely overridden on a per-field basis, of course, by simply defining those same field attributes like before.

### Related

* bevyengine#3733
* bevyengine#1395
* bevyengine#2377

---

## Changelog

* Added `#[reflect(default)]` field attribute for `FromReflect`
  * Allows missing fields to be given a default value when using `FromReflect`
  * `#[reflect(default)]` - Use the field's `Default` implementation
  * `#[reflect(default = "some_fn")]` - Use a custom function to get the default value
* Allow `#[reflect(Default)]` to have a secondary usage as a container attribute
  * Allows missing fields to be given a default value based on the container's `Default` impl when using `FromReflect`


Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
ItsDoot pushed a commit to ItsDoot/bevy that referenced this pull request Feb 1, 2023
…evyengine#4140)

# Objective

Currently, `FromReflect` makes a couple assumptions:

* Ignored fields must implement `Default`
* Active fields must implement `FromReflect`
* The reflected must be fully populated for active fields (can't use an empty `DynamicStruct`)

However, one or both of these requirements might be unachievable, such as for external types. In these cases, it might be nice to tell `FromReflect` to use a custom default.

## Solution

Added the `#[reflect(default)]` derive helper attribute. This attribute can be applied to any field (ignored or not) and will allow a default value to be specified in place of the regular `from_reflect()` call. 

It takes two forms: `#[reflect(default)]` and `#[reflect(default = "some_func")]`. The former specifies that `Default::default()` should be used while the latter specifies that `some_func()` should be used. This is pretty much [how serde does it](https://serde.rs/field-attrs.html#default).

### Example

```rust
#[derive(Reflect, FromReflect)]
struct MyStruct {
  // Use `Default::default()`
  #[reflect(default)]
  foo: String,

  // Use `get_bar_default()`
  #[reflect(default = "get_bar_default")]
  #[reflect(ignore)]
  bar: usize,
}

fn get_bar_default() -> usize {
  123
}
```

### Active Fields

As an added benefit, this also allows active fields to be completely missing from their dynamic object. This is because the attribute tells `FromReflect` how to handle missing active fields (it still tries to use `from_reflect` first so the `FromReflect` trait is still required).

```rust
let dyn_struct = DynamicStruct::default();

// We can do this without actually including the active fields since they have `#[reflect(default)]`
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

### Container Defaults

Also, with the addition of bevyengine#3733, people will likely start adding `#[reflect(Default)]` to their types now. Just like with the fields, we can use this to mark the entire container as "defaultable". This grants us the ability to completely remove the field markers altogether if our type implements `Default` (and we're okay with fields using that instead of their own `Default` impls):

```rust
#[derive(Reflect, FromReflect)]
#[reflect(Default)]
struct MyStruct {
  foo: String,
  #[reflect(ignore)]
  bar: usize,
}

impl Default for MyStruct {
  fn default() -> Self {
    Self {
      foo: String::from("Hello"),
      bar: 123,
    }
  }
}

// Again, we can now construct this from nothing pretty much
let dyn_struct = DynamicStruct::default();
let my_struct = <MyStruct as FromReflect>::from_reflect(&dyn_struct);
```

Now if _any_ field is missing when using `FromReflect`, we simply fallback onto the container's `Default` implementation.

This behavior can be completely overridden on a per-field basis, of course, by simply defining those same field attributes like before.

### Related

* bevyengine#3733
* bevyengine#1395
* bevyengine#2377

---

## Changelog

* Added `#[reflect(default)]` field attribute for `FromReflect`
  * Allows missing fields to be given a default value when using `FromReflect`
  * `#[reflect(default)]` - Use the field's `Default` implementation
  * `#[reflect(default = "some_fn")]` - Use a custom function to get the default value
* Allow `#[reflect(Default)]` to have a secondary usage as a container attribute
  * Allows missing fields to be given a default value based on the container's `Default` impl when using `FromReflect`


Co-authored-by: Gino Valente <49806985+MrGVSV@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-Reflection Runtime information about types C-Feature A new feature, making something new possible
Projects
Archived in project
Development

Successfully merging this pull request may close these issues.

4 participants