state-shift 0.1.0

Macros for implementing Type-State-Pattern on your structs and methods
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482


# What is State-Shift?

**State-Shift** is a macro library that generates **type-state-pattern boilerplate code for your structs**. So that you can write your structs as usual, but still get the benefits of type-safety!

If you don't appreciate all the boilerplate code required by Type-State-Pattern that makes the DevX worse, but you still like the idea of type-safety provided by it, this library is for you. Type-State-Pattern-Macro lets you write your code as if type-state-pattern was not there, yet grants you the benefits of type-safety. BEST OF BOTH WORLDS!


### What the hell is even Type-State-Pattern?

Here is a great blog post that explains it, I heard that the author is a good person: https://cryptical.xyz/rust/type-state-pattern

TL;DR -> instead of relying on runtime checks, Type-State-Pattern uses type-safety to enforce specific methods are only callable at specific states at compile time.

For example, you cannot call `fight()` method on a `Player` struct when it is in `Dead` state. You normally accomplish this by introducing boolean flags and runtime checks. With Type-State-Pattern, you achieve this without any runtime checks, purely by the type-safety provided by Rust primitives.

This is good, due to:
- better DevX (users of the library won't be even able to call this invalid methods)
- less runtime bugs
- less runtime checks -> more performant code
- zero-cost abstractions for this type checks (no additional performance cost of doing this)

<br/>

# Example Usage of This Library

### 1. State-Focused Methods

Let’s say you have a `Player` struct with methods like:

- `die()`
- `resurrect()`

As a reasonable person, you probably don’t want someone to call `die()` on a player who’s already `Dead`.

> [!TIP]
> People cannot die twice!

With this library, you can ensure that your methods respect the logical state transitions, preventing awkward situations like trying to "double-die."

This library lets you have above mentioned type-safe methods, without:
- duplicating your structs (one for `Dead` state and one for `Alive` state)
- writing runtime checks
- hurting the performance of your code
- making your code horrible to look at due to infamous Type-State-Pattern

In short, the users of this library won't be able to call:

> [!CAUTION]
> ```rust
> let player = PlayerBuilder::new().die().die(); // ❌ Invalid!
> ```
> The good thing is, after calling the first `die()` method, the second `die()` **won't be even suggested** by your IDE via autocomplete.
>
> And even if you insist to type it anyway, it will be a compile-time error!


### 2. Field/Method Order & Dependencies

Imagine you have a `PlayerBuilder` struct designed to construct a `Player`. Some fields need to be set before others because of logical dependencies. For instance, the `race` field must be specified before the `level` field, as the race affects how we calculate the player's starting level.

> [!CAUTION]
>  So, we don't want the below code:
>```rust
>let player = PlayerBuilder::new().level(10) // ❌ Invalid!
>```

> [!TIP]
>  We want the below code:
>```rust
>let player = PlayerBuilder::new().race(Race::Human).level(10) // ✅
>```

The gist of it is, some fields of the `PlayerBuilder` are depending on other fields. So we want to force the users of this library to set these fields in order by making invalid orders completely unrepresentable at compile time. Even rust-analyzer won't suggest the invalid methods as auto-completion! How wonderful is that!

<details>
    <summary><b>Show me the code!</b></summary>

```rust
#[derive(Debug)]
struct Player {
    race: Race,
    level: u8,
    skill_slots: u8,
}

#[derive(Debug, PartialEq)]
enum Race {
    #[allow(unused)]
    Orc,
    Human,
}

#[type_state(state_slots = 1, default_state = Initial)]
struct PlayerBuilder {
    race: Option<Race>,
    level: Option<u8>,
    skill_slots: Option<u8>,
}

// put the constructors in a separate impl block
impl PlayerBuilder {
    fn new() -> Self {
        PlayerBuilder {
            race: None,
            level: None,
            skill_slots: None,
            _state: (PhantomData),
        }
    }
}

#[states(Initial, RaceSet, LevelSet, SkillSlotsSet)]
impl PlayerBuilder {
    #[require(Initial)] // can be called only at `Initial` state.
    #[switch_to(RaceSet)] // Transitions to `RaceSet` state
    fn set_race(self, race: Race) -> PlayerBuilder {
        PlayerBuilder {
            race: Some(race),
            level: self.level,
            skill_slots: self.skill_slots,
            _state: (PhantomData),
        }
    }

    #[require(RaceSet)]
    #[switch_to(LevelSet)]
    fn set_level(self, level_modifier: u8) -> PlayerBuilder {
        let level = match self.race {
            Some(Race::Orc) => level_modifier + 2, // Orc's have +2 level advantage
            Some(Race::Human) => level_modifier,   // humans are weak
            None => unreachable!("type safety ensures that `race` is initialized"),
        };

        PlayerBuilder {
            race: self.race,
            level: Some(level),
            skill_slots: self.skill_slots,
            _state: (PhantomData),
        }
    }

    #[require(LevelSet)]
    #[switch_to(SkillSlotsSet)]
    fn set_skill_slots(self, skill_slot_modifier: u8) -> PlayerBuilder {
        let skill_slots = match self.race {
            Some(Race::Orc) => skill_slot_modifier,
            Some(Race::Human) => skill_slot_modifier + 1, // Human's have +1 skill slot advantage
            None => unreachable!("type safety ensures that `race` should be initialized"),
        };

        PlayerBuilder {
            race: self.race,
            level: self.level,
            skill_slots: Some(skill_slots),
            _state: (PhantomData),
        }
    }

    #[require(A)] /// doesn't require any state, so this is available at any state
    fn say_hi(self) -> Self {
        println!("Hi!");

        self
    }

    #[require(SkillSlotsSet)]
    fn build(self) -> Player {
        Player {
            race: self.race.expect("type safety ensures this is set"),
            level: self.level.expect("type safety ensures this is set"),
            skill_slots: self.skill_slots.expect("type safety ensures this is set"),
        }
    }
}
```

> If you want to see what this macro expands to, check out `examples` folder. I have both a `complex_expanded.rs` and a `simple_expanded.rs`.

</details>

<br/>
<br/>

# Benefits of using this Library

### 1. You get type-safety for your methods, without any runtime checks

<br/>

### 2. Hiding the ugly and unreadable boilerplate code required for your structs:
<br/>

- without this library, you probably have to write something like this (BAD):
    ```rust
    struct PlayerBuilder<State1 = Initial, State2 = Initial, State3 = Initial>
    where
        State1: TypeStateProtector,
        State2: TypeStateProtector,
        State3: TypeStateProtector,
    {
        race: Option<Race>,
        level: Option<u8>,
        skill_slots: Option<u8>,
        spell_slots: Option<u8>,
        _state: (
            PhantomData<State1>,
            PhantomData<State2>,
            PhantomData<State3>,
        ),
    }
    ```

> [!CAUTION]
> The above code might suck the enjoyment out of writing Rust code.

<br/>
<br/>

- with this library, you can write this (GOOD):
    ```rust
    #[type_state(state_slots = 3, default_state = Initial)]
    struct PlayerBuilder {
        race: Option<Race>,
        level: Option<u8>,
        skill_slots: Option<u8>,
        spell_slots: Option<u8>,
    }
    ```

> [!TIP]
> Mmmhh! Much better, right?

<br/>

### 3. Hiding the  ugly and unreadable boilerplate code required for your impl blocks:

<br/>

- without this library, you probably have to write something like this (BAD):

    ```rust
    impl<B, C> PlayerBuilder<Initial, B, C>
    where
        B: TypeStateProtector,
        C: TypeStateProtector,
    {
        fn set_race(self, race: Race) -> PlayerBuilder<RaceSet, B, C> {
            {
                {
                    PlayerBuilder {
                        race: Some(race),
                        level: self.level,
                        skill_slots: self.skill_slots,
                        spell_slots: self.spell_slots,
                        _state: (PhantomData, PhantomData, PhantomData),
                    }
                }
            }
        }
    }
    ```
> [!CAUTION]
> It's not immediately obvious what's going on here, which state is required, to which state it's transitioning into, etc.

<br/>
<br/>

- with this library, you can write this (GOOD):
    ```rust
    #[require(Initial, B, C)]
    #[switch_to(RaceSet, B, C)]
    fn set_race(self, race: Race) -> PlayerBuilder {
        PlayerBuilder {
            race: Some(race),
            level: self.level,
            skill_slots: self.skill_slots,
            spell_slots: self.spell_slots,
            _state: (PhantomData, PhantomData, PhantomData),
        }
    }
    ```

> [!TIP]
> Immediately signals:
>
> - which state is required.
>
> - to which state it's transitioning into.
>
> No weird generics and intermediate unit structs that hurting your brain.

<br/>
<br/>

### 4. Hiding the ugly and unreadable boilerplate code required for intermediate traits and structs:

<br/>

- without this library, in order to ensure the type-safety, you have to write traits and unit structs (BAD):
    ```rust
    mod sealed {
        pub trait Sealed {}
    }

    pub trait TypeStateProtector: sealed::Sealed {}

    struct Initial;
    struct RaceSet;
    struct LevelSet;
    struct SkillSlotsSet;
    struct SpellSlotsSet;

    impl sealed::Sealed for Initial {}
    impl sealed::Sealed for RaceSet {}
    impl sealed::Sealed for LevelSet {}
    impl sealed::Sealed for SkillSlotsSet {}
    impl sealed::Sealed for SpellSlotsSet {}

    impl TypeStateProtector for Initial {}
    impl TypeStateProtector for RaceSet {}
    impl TypeStateProtector for LevelSet {}
    impl TypeStateProtector for SkillSlotsSet {}
    impl TypeStateProtector for SpellSlotsSet {}
    ```

> [!CAUTION]
> EWWWW

<br/>
<br/>


- with this library, you can write this (GOOD):
    ```rust
    #[states(Initial, RaceSet, LevelSet, SkillSlotsSet, SpellSlotsSet)]
    impl PlayerBuilder {
        // ...methods redacted...
    }
    ```

> [!TIP]
> The necessary states that we want to use, cannot be more clear!

<br/>

### 5. Sealed-traits

this library also uses sealed-traits to ensure even more safety! And again, you don't need to worry about anything. Sealed-traits basically ensure that the user cannot implement these trait themselves. So, your structs are super-safe!

<br/>


### 6. Clear documentation

I tried to document nearly everything. If you are curios on what do the macros do under the hood, even those macros are documented! Just check the inline documentation and I'm sure you will understand what's going on in a blink of an eye!

<br/>

### 7. Suggestions and contributions are welcome!

I'm a quite friendly guy. Don't hesitate to open an issue or a pull request if you have any suggestions or if you want to contribute! Just keep in mind that everyone contributing to here (including myself) are doing it voluntarily. So, always be respectful and appreciate other's time and effort.


# Advanced & Helpful Tips

Remember, this library is just hiding the ugly type-state-pattern boilerplate code under the hood. This means, your code still have to obey some rules.

Most of the issues arise from when we are returning the `Self` type. The compiler doesn't like the `Self` keyword in type-state-pattern, because we are actually not returning the `Self`, but a different type. For example, it could be that our method is accepting `Player<Alive>` but we are returning `Player<Dead>`.

And you know how Rust compiler is. It is very strict about types!


### Rules

1. If your method is switching states (most probably it does), avoid using `Self` in the return position of the method's signature:
   
> [!CAUTION]
>
> ```rust
> fn my_method(self) -> Self { // `-> Self` ❌
>    // redacted body
> }

> [!TIP]
> ```rust
> fn my_method(self) -> PlayerBuilder { // `-> ConcreteName` ✅
>    // redacted body
> }


2. Similarly, also avoid using `Self` in the method's body:

> [!CAUTION]
>
> ```rust
> fn my_method(self) -> PlayerBuilder {
>
>    Self {  // `Self {}` ❌
>       race: Race::human
>       level: self.level
>    }
> }

> [!TIP]
> ```rust
> fn my_method(self) -> PlayerBuilder {
>
>    PlayerBuilder {  // `PlayerBuilder {}` ✅
>       race: Race::human
>       level: self.level
>    }
> }

3. `self` is ok to use, but there is one exception:

> [!CAUTION]
>
> ```rust
> fn my_method(self) -> PlayerBuilder {
>
>    PlayerBuilder {
>       race: Race::human
>       ..self  // `..self` ❌
>    }
> }

> [!NOTE]
> actually having `..self` is not supported by the Rust compiler in this context, YET.
>
> So hoping it will become stable in the future and we won't have to worry about it.

4. In order to have `states`, the macros expand your struct with a hidden `_state` field. So, when you are constructing your struct, you have to provide this field as well. Don't worry about the value, it will be just `(PhantomData)`. Feel free to take a look at the example codes to see how it is used.

> [!TIP]
> ```rust
> fn my_method(self) -> PlayerBuilder {
>
>    PlayerBuilder {
>       race: Race::human
>       level: self.level
>       _state: (PhantomData)  // ✅
>    }
> }

### Tips

1. Tracking multiple states

This feature was both my favorite to implement and the most brain-melting (design-wise and implementation-wise).

**The problem:**

Imagine you have three fields for your struct: `a`, `b`, and `c`. You want `c` to be set only after both `a` and `b` are set. Not just one of them—both.

How do you accomplish this with type-state-pattern? This is a problem because the default design pattern allows you to have a single state to track.

One workaround is to have multiple states for the combinations of `a` and `b`. For example, you can have the following states:
- `a_set_but_b_not_set`
- `b_set_but_a_not_set`
- `a_set_and_b_set`.

This is not a good solution due to 2 reasons:
- it is fucking ugly
- you need to duplicate your methods and give them different names, because you cannot have multiple methods with the same name. If this didn't make sense, take a look at the expanded codes, and you will see why we need to have the same method on different `impl` blocks. The compiler of course doesn't like that. The only workaround to have the same function body on different `impl` blocks, is to have different names for these methods. Same methods, but different names? No more explanation needed on why this is bad.

**The Solution:**

Multiple state slots. By allowing multiple state slots, you can track each state separately, and they won't override each other. You can see this in action in the `tests/complex_example.rs`. It showcases how this is done, and when can it be useful. Now, the macro for our struct should make more sense:

```rust
#[type_state(state_slots = 3, default_state = Initial)]
struct PlayerBuilder {
    race: Option<Race>,
    level: Option<u8>,
    skill_slots: Option<u8>,
    spell_slots: Option<u8>,
}
```

Happy coding!