2024-01-10

How do you idiomatically implement a nontrivial typestate pattern in Rust? [closed]

I'm trying to build the FSM of a simple CPU, which consists of about 40 states, with loops, and many conditionals across many variables of the overall CPU state. This FSM operates like a simple Turing Machine; reading memory cells (think vector of u16), computing some results, and storing them back into memory.

My question is: how is this implemented idiomatically in Rust?

The way I've considered it, you would do something like this:

  1. Have a base enum representing the states.
  2. Have another enum for each state which represents transitions (but maybe all in the same enum?).
  3. Somehow you'd have to access the CPU state (value of all the different registers etc) to know how to emit the next state transition, but to be efficient about it, you'd need to be able to pass different subsets of the CPU state, yet somehow only mutate a single copy that represents the CPU state after the computation.
  4. You could probably build a vector of "state diffs" which you could apply all at once when you reach certain states, which would also be good for implementing a simple debugger.

I'm new to rust, so modelling these sort of complex compositional type problems still doesn't come very naturally.

If you want to see how things work so far, I have a repo here: https://github.com/ijustlovemath/lrc3



No comments:

Post a Comment