git @ Cat's Eye Technologies Burro / master src / Language / Turmac / IRCompiler.hs
master

Tree @master (Download .tar.gz)

IRCompiler.hs @masterraw · history · blame

-- SPDX-FileCopyrightText: Chris Pressey, the creator of this work, has dedicated it to the public domain.
-- For more information, please refer to <https://unlicense.org/>
-- SPDX-License-Identifier: Unlicense

module Language.Turmac.IRCompiler where

import Data.List (nub)

import Language.Turmac.Model
import Language.Turmac.IR


-- Group rules by state
groupByState :: [TMRule] -> [(StateId, [(Symbol, (StateId, Symbol, Direction))])]
groupByState rules =
    [(state, [(sym, (newSym, newState, dir)) |
             (s, sym, newSym, newState, dir) <- rules, s == state])
    | state <- states]
    where states = nub [s | (s,_,_,_,_) <- rules]

-- Convert a single state's rules to CondSymbol
stateRulesToProg :: [(Symbol, (Symbol, StateId, Direction))] -> Prog
stateRulesToProg rules =
    CondSymbol [(sym, Seq [WriteMoveGoto newSym dir newState])
               | (sym, (newSym, newState, dir)) <- rules]

-- Convert all rules to full program
buildProgram :: [TMRule] -> Prog
buildProgram rules =
    Program (CondState [(state, stateRulesToProg stateRules)
                      | (state, stateRules) <- groupByState rules])