Some thoughts on simple state machines using x86_64 / assembly

State machines can be clunky to define in some languages. The definition of clunky here is mostly about boilerplate. I wanted to see how it was in assembly. I think assembly is well suited for it with the usage of macros. I think it demonstrates an interesting property of macros: they allow you essentially create DSLs with little effort.

Exhibit A:

.intel_syntax noprefix

/* My macros for making function calling easier on the mind. */
.include "std.macro"

/* Macros for making state machines. */
.include "sm.macro"

GREEN   = 2
YELLOW  = 1
RED     = 0

MachineDefinition TrafficLights
  State GREEN,  YELLOW
  State YELLOW, RED
  State RED,    GREEN
  MachineDefinitionEnd

MachineIgnition TrafficLights GREEN
  Tick 3
  Halt

/* Translates to: */

sm_TrafficLights: push esp
  cmp state, GREEN;  cmove state, YELLOW; je sm_end_TrafficLights
  cmp state, YELLOW; cmove state, RED;    je sm_end_TrafficLights;
  cmp state, RED;    cmove state, GREEN;  je sm_end_TrafficLights;
  mov state, INVALID
sm_end_TrafficLights:
  pop esp; ret

/* I just use λ to abstract calling conventions, not to define a function. */

.global main
xcode = rdi
main:
  mov state, GREEN
  λ   sm_TrafficLights, state
  λ   sm_TrafficLights, state
  λ   sm_TrafficLights, state
  cmp state, INVALID; cmove xcode, 1; cmovne xcode, 0
  λ   exit, xcode


Pretty interesting to think about. What other patterns and paradigms can easily be translated to assembly and some light macros?

In some examples people like to (ab)use type systems to encode the transition constraints, but what's the point? In the above, it's either a transition, or it doesn't exist. Maybe there's no need for a type system here? :)

Comments

  1. this is awesome. I'm convinced. Let's go back to structured programming but with meaningful macros.
    Have you checked out any true low-level forth systems in which words can get assembled into object code?

    I was also thinking that we could drive event loops with hw interrupts and the handler is the ISR... like mouse and stuff...

    time for brutalist minimalism errr the brutmnml mvmnt

    ReplyDelete

Post a Comment