Search code examples
haskellcode-generationcompiler-construction

Creating unique labels in Haskell


I'm writing a compiler for a simple imperative language in Haskell, outputting Java bytecode. I've gotten to the point where I'm emitting an abstract representation of bytecodes.

While writing code for compiling if-statements I ran in to some trouble. To implement if-statements I need labels to jump to. Therefore I need to generate a name for that label, and that name needs to be unique.

My first thought was to thread some state through compileStatement, i.e

compileStatement :: Statement -> UniqueIDState -> [AbstractInstruction]

Of course, compilerStatement is recursive, so using this method would require me to pass the state of the unique ID generator back upp from the recursive calls:

compileStatement :: Statement -> UniqueIDState -> (UniqueIdState, [AbstractInstruction])

This seems a bit clumsy, especially if I realize I need to carry around more state in the future; is there a more elegant way?


Solution

  • You need a "unique supply". The usual way to do this in Haskell is by threading a counter through the State monad, which automates the plumbing problem you describe.