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

Associated "constants" for Rust-types? #683

Open
tgolsson opened this issue Mar 29, 2024 · 1 comment
Open

Associated "constants" for Rust-types? #683

tgolsson opened this issue Mar 29, 2024 · 1 comment
Labels
enhancement New feature or request

Comments

@tgolsson
Copy link
Contributor

A common pattern in Rust is something like this:

pub struct Color(u8, u8, u8, u8);

impl Color {
    pub const RED: Self = Self(255, 0, 0, 255);
}

However, this pattern cannot be represented in any way in Rune as far as I can tell, since Any types can't be ConstValue -- and that's the only pattern for associated values I can find. For ergonomics, it'd be nice if one could still do it, even if (technically) the type isn't POD from rune's perspective. For example, an associated_field_function? Not sure what would be the most efficient from the implementation perspective. Another option would be to have some form of ConstValue::UserDefined(Bytes, ToValueFn), though I'm not sure about how that'd work in actual const-eval.

@udoprog udoprog added the enhancement New feature or request label Mar 29, 2024
@udoprog
Copy link
Collaborator

udoprog commented Mar 29, 2024

I think Any types can be constant values - if they can be represented with ConstValue.

What would be needed for external types are two things:

  • The data being stored. Probably a constant Tuple or constant Object, and;
  • The metadata which identifiers the type, probably its type hash.

These could be represented using six new variants:

  • ConstValue::EmptyStruct.
  • ConstValue::TupleStruct.
  • ConstValue::Struct.
  • ConstValue::EmptyVariant.
  • ConstValue::TupleVariant.
  • ConstValue::StructVariant.

The metadata of structs would need the type hash of the struct they represent, variants would need two pieces of metadata, the type hash of the enum it belongs to and the type hash of the variant.

The metadata can then be used by a Vm to convert a ConstValue into a Value as needed by looking up the relevant RTTI. Trying to coerce a ConstValue from something incompatible would result in an error, similar to how trying to construct a structure in the Vm would be an error if it doesn't have the appropriate fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants