114 points · by bitshifta · 3y ago · 87 comments
I've been a huge fan of the type-state pattern [1]. I don't see it mentioned often, and never outside of Rust so far. However, it's applicable to most languages, including ones you wouldn't suspect (Python). If you introduce a whole new type (not a big deal in Rust; more of a ceremony in C# et al.) for `DeletedUser`, you can simply leave off the `active` function! Any action (==state transition) on that type will be legal and possible. Methods have unit value return type, no `Result` needed. You cannot handle that incorrectly! The code won't even compile.
I am still in the process of exploring downsides to the pattern. For example, in classic OOP languages, you can create a type hierarchy, with a top-level `User`, and the different kinds inheriting from it (and then ideally be marked `final`/`sealed` or whatever). You can then treat all users the same by interacting with the top-level type. Useful for DB interaction, for example. The same in Rust would go through traits: `impl User for DeletedUser`. But it's not quite as nice, is it?
Still, it's a great pattern that I use as often as I can!
An interface with multiple implementations.
The typesstate pattern felt hostile when libs using it only included examples of use directly in a main function where you didn't have to specify the type; you'd try to use them in a program in a struct field, function signature etc, and wouldn't know what type to put in.
Example of typestates I've seen: `Spi<SPI1, PA5<Alternate<AF11>>, PA6<Alternate<AF69>...>>>>>>>`
When would be easier to use a plain `Spi` struct.
These aren't necessarily critiques of the typestate pattern in general, but those are the 2 points that pushed me away from it.
In the function signature, Rust deliberately doesn't have inference, you must write down the types and decltype would not be acceptable for that purpose.
https://github.com/tim-group/higher-kinded-lifecycle/blob/ma...
This is where you can index the different constructors (enum variants) with an additional type variables and even specialize them when needed. A pretty powerful tool to encode at the type level that similar things are slightly different.
Being able to say 'Rust enums can carry arguments' - for some reason - sounds less intimidating and conveys the core feature.
(but yeah, 'enum with arguments' also describes it very well)
Also, Rust does have actual tagged unions for C interop that you have to define yourself as a `struct` with an int field and a `union` field, just like in C.
Their representation in memory may not use it, but it's still defined.
Combine it with switches and you get compiler guarantees that every state is explicitly handled, and if you are in a particular state you always have the relevant child objects.
I remember being shocked dart lacked this functionality when I tried out flutter.
They aren't as ergonomic or type-safe, and rather surprisingly the match statement is not an expression in Python's grammar, but regardless of its problems the match statement is very powerful, even more so than static equivalents.
[1] https://docs.python.org/3/library/stdtypes.html#types-union
[2] https://mypy.readthedocs.io/en/stable/type_narrowing.html
[3] https://docs.python.org/3/library/typing.html#typing.assert_...
I had to try:
pub enum Foo {
Foo { a: i32 },
}
impl Foo {
pub fn new() -> Self {
Foo::Foo { a: 42 }
}
pub fn get_a(Foo::Foo{a}: &Self) -> &i32 {
a
}
}
At opt level above zero (-C opt-level=1) the tag is elided: example::Foo::new:
mov eax, 42
ret
example::Foo::get_a:
mov rax, rdi
ret
https://godbolt.org/z/qKzMqvhb7The next step is to encode your transition logic in the From impls between the enum structs and you've got yourself a first-rate state machine.
Pascal and Delphi have always had variant records as part of the language. Are these not "mainstream" enough, especially Delphi?
One thing Rust could really use are anonymous unions (A | B |C instead of E::A(A), E::B(B), E::C(C)). They are to enums what tuple types are to structs.
Another thing that a new language designer might consider is a mechanism to control the layout. For example say I have a pair of nested enums
enum A {
A0(B),
...
A15(B),
}
enum B {
B0,
...
B15,
}
The outer enum A can be represented as `u8` where the upper nibble is the tag for `A` and the lower nibble is the value of `B`.This is kind of a niche thing, but you see it in binary protocols from time to time and losing the ergonomics of enum/match because the enum can't represent your data without widening it is a shame.
Another problem that shows up is this
enum E {
A = 0
B = 1,
Rest(u8),
}
This can't be represented in 1 byte because `Rest` could be 0 or 1. There's no way to tell the compiler that the value of E::Rest is disjoint from any other values in the enum definition - the only way is to add `Rest1, Rest2, ...` variants for all possible values of the underlying data.This problem crops up when you use the `zerocopy` crate.
And finally something that is super difficult to reason about (and has many implications) is storing the tag out-of-band of the enum data. I believe Zig can do this, but I'm not sure much how it works.
These are super minor gripes about using enums in Rust, but I feel like not enough discussion goes towards some of their limitations and tradeoffs, particularly for high performance applications.
Ceylon had union types, which is the only place i've seen these: https://github.com/eclipse-archived/ceylon-lang.org/blob/mas...
Another thing Rust enums are missing is having each variant be a type. If you have an enum Shape with variants Circle, Rectangle, and Polygon, there is no way to write a function which only takes a Circle. So you end up defining a struct for each case, then making your enum a trivial wrapper round the three structs. You end up with Shape::Circle and Circle, which are different things, and writing code like c.0.radius to get at the fields. It's rather inelegant. So either variants should be types in their own right, or an enum should be defined as a composition of existing types.
https://github.com/rust-lang/lang-team/issues/122
Kind of a shame, but wrapper types work well enough that I understand. It does look like if there was someone with enough resources to make it happen that they'd be receptive to it.
But this is just a generic sum type?
data Sum a b = L a | R b
infixr 5 type Sum as ⊕
type E₂ a b z = a ⊕ b ⊕ z
type E₃ a b c z = a ⊕ b ⊕ c ⊕ z
-- and so on…
Here, `Eₙ` represents a sum type with at least `n` members indexed by their position, and `z` represents any type so that it's possible to keep extending the number of positions via further nesting. When you're done you set it to a type with no members: type E₃AndNoMore a b c = a ⊕ b ⊕ c ⊕ Void
I don't know Rust so I can't claim if it allows it, but I'm almost certain it does.No, it's actually less generic. It's not determined by position but by type. For example `A | B | A` is the same type as `A | B`.
This is useful as a shorthand when you don't want/need a new type to represent your problem, similar to tuples.
> This is useful as a shorthand when you don't want/need a new type to represent your problem, similar to tuples.
Yes this is handled perfectly by the generic sum type, you don't need untagged unions for this. Rust used to have Either in its standard library, but they removed it and kept Result only. Semantically they're the same (a ⊕ b) but Result's name implies it has something to do with some "results". Anyways nothing stops you from creating one yourself, or even using Result if you're fine with the weird-sounding name.
Storing the tag 'out of band' is something you can only do as part of some larger object, in which case you can similarly have getters and setters that take or return enums and do the appropriate conversion.
It gets verbose fast when you are talking about all combinations of variants of an enum.
Very powerful tool. I wish Go had (real) enums.
https://github.com/containerd/runwasi/blob/ba5ab5ada5a401762...
{Active -> Inactive,
Inactive -> Active,
Active -> Suspended,
Suspended -> Active,
...}
And then having only _one_ function that mutates and checks for the valid transitions? In the author's implementation you need to read a lot of code to derive the state machine from the method's implementations instead of it being immediately obvious from looking at a data structure. I understand there's a benefit of the implementation being checked by the compiler in this way, but at the same time it seem to spread logic across many methods. Is there an alternative middle-ground?The worst is when someone refactors it into a "modern" approach and then proceeds to break the general flow of the state machine again and again.
While in Rust, the implementation is done for a Trait, and the user can choose static or dynamic dispatch (Trait vs dyn Trait).
I feel the same dissonance between static and dynamic state machines in Rust (type states vs enum). Sometimes I want to enforce it at compile time, while sometimes, at runtime. And the implementation is forced to choose for the user.
I am sure one could write some (proc) macro, and there might be some crates to do that already. But it doesn't feel as elegant as the static/dynamic Trait in my mind.
What does this look like under the hood (in memory)? Does the compiler automatically generate a struct/union? Does the value take up the same width regardless of state?
> Does the value take up the same width regardless of state?
Yes. As the other commenter mentioned, it's the size of the largest variant (same as a union in C) + a tag (almost the same as an enum in C). In some rare cases, the compiler even manages to optimize out the tag.