Skip to main content

Haskell

The Haskell port of the HIL evaluator leverages algebraic data types, a monadic evaluation pipeline, and parser combinators to implement a strongly-typed, pure-functional HIL LISP interpreter. The package is published as hil-haskell on Hackage and can be installed via Cabal or Stack (Peyton Jones, 2003).

Installation​

# Via Cabal
cabal install hil-haskell

# Via Stack
stack install hil-haskell

Compilation Pipeline​

The pipeline is structured as a pure functional transformation: source text is parsed into an algebraic AST, validated against the type environment, evaluated in a reader-monad context that carries hardware state, and finally reported through serial or MQTT channels. Each stage is a total function, guaranteeing that no runtime exceptions escape into the hardware control path (Lipovača, 2011).

Abstract Syntax Tree​

The HIL LISP AST is modeled as a closed sum type. Every construct the language supports appears exactly once in the Expr type, making the evaluator exhaustive by construction.

module HIL.AST where

data Expr
= EInt Int
| EFloat Double
| EBool Bool
| EString String
| ESymbol String
| EList [Expr]
| ENil
deriving (Eq, Show)

data Decl
= Defun String [String] Expr
| DefVar String Expr
| DefMacro String [String] Expr
deriving (Eq, Show)

data Program = Program [Decl] Expr
deriving (Eq, Show)

Because Haskell's pattern matching is total, the evaluator must handle every constructor of Expr. The compiler enforces this at build time, which means an unhandled node type becomes a compile error rather than a runtime fault on live hardware (Thompson, 2019).

Parser Combinator​

The parser is built on Parsec. It reads HIL LISP s-expressions and produces the Expr AST directly.

module HIL.Parser where

import Text.ParserCombinators.Parsec
import HIL.AST

spaces1 :: Parser ()
spaces1 = skipMany1 space

symbol :: Parser String
symbol = many1 (noneOf " \t\n\r()\"'") <* spaces

parseAtom :: Parser Expr
parseAtom = do
s <- symbol
return $ case s of
"true" -> EBool True
"false" -> EBool False
_ -> ESymbol s

parseNumber :: Parser Expr
parseNumber = do
digits <- many1 digit
option (EInt (read digits)) $ do
char '.'
frac <- many1 digit
return $ EFloat (read (digits ++ "." ++ frac))

parseString :: Parser Expr
parseString = EString <$> (char '"' *> many (noneOf "\"") <* char '"')

parseExpr :: Parser Expr
parseExpr = choice
[ try parseNumber
, parseString
, parseAtom
, parseList
, ENil <$ string "nil"
]

parseList :: Parser Expr
parseList = char '(' *> spaces *> elts <* char ')' <* spaces
where
elts = EList <$> many parseExpr

parseHIL :: String -> Either ParseError Expr
parseHIL = parse (spaces *> parseExpr <* eof) "<input>"

Monadic Evaluator​

The evaluator runs in a ReaderT Env (ExceptT EvalError IO) stack. The Reader carries the immutable environment, Except short-circuits on errors without exceptions, and IO is reserved for side effects such as serial writes (Thompson, 2019).

module HIL.Eval where

import Control.Monad.Reader
import Control.Monad.Except
import qualified Data.Map.Strict as Map
import HIL.AST

type Env = Map.Map String Expr

data EvalError
= UnboundVar String
| TypeError String
| ArityError String Int Int
deriving (Show)

type EvalM a = ReaderT Env (ExceptT EvalError IO) a

eval :: Expr -> EvalM Expr
eval (EInt n) = return (EInt n)
eval (EBool b) = return (EBool b)
eval (EString s) = return (EString s)
eval (ESymbol name) = do
env <- ask
case Map.lookup name env of
Nothing -> throwError (UnboundVar name)
Just val -> return val
eval (EList [ESymbol "do", rest]) = eval rest
eval (EList [ESymbol "if", cond, thenE, elseE]) = do
c <- eval cond
case c of
EBool True -> eval thenE
EBool False -> eval elseE
_ -> throwError (TypeError "if requires boolean")
eval (EList [ESymbol "define", ESymbol name, val]) = do
v <- eval val
local (Map.insert name v) (return v)
eval (EList (ESymbol fname : args)) = do
func <- eval (ESymbol fname)
vals <- mapM eval args
apply func vals
eval (EList []) = return ENil
eval other = throwError (TypeError ("cannot eval: " ++ show other))

apply :: Expr -> [Expr] -> EvalM Expr
apply (ESymbol "+") [EInt a, EInt b] = return (EInt (a + b))
apply (ESymbol "-") [EInt a, EInt b] = return (EInt (a - b))
apply (ESymbol "*") [EInt a, EInt b] = return (EInt (a * b))
apply (ESymbol "log") [msg] = do
liftIO $ putStrLn ("[HIL] " ++ show msg)
return ENil
apply (ESymbol "pin-mode") [EInt pin, EInt mode] = do
liftIO $ putStrLn ("[PIN-MODE] pin=" ++ show pin ++ " mode=" ++ show mode)
return ENil
apply (ESymbol "digital-write") [EInt pin, EInt val] = do
liftIO $ putStrLn ("[DW] pin=" ++ show pin ++ " val=" ++ show val)
return ENil
apply f args = throwError (ArityError (show f) 0 (length args))

Serial Communication​

Serial I/O uses the HSerial library, which wraps POSIX termios on Linux and exposes a SerialPort handle. The communication follows the HIL wire protocol: ASCII frames delimited by newlines with a trailing CRC-8 checksum.

module HIL.Serial where

import System.Hardware.Serialport
import Data.ByteString.Char8 qualified as B
import Data.Char (ord)

openHILPort :: FilePath -> Int -> IO SerialPort
openHILPort path baud = openSerial path defaultSerialSettings
{ commSpeed = toEnum baud
, dataBits = Eight
, stopBits = One
, parity = NoParity
}

sendCommand :: SerialPort -> String -> IO ()
sendCommand port cmd = do
let payload = cmd ++ [chr (crc8 cmd)]
send port (B.pack payload)
return ()

receiveResponse :: SerialPort -> IO String
receiveResponse port = do
bytes <- recv port 256
return (B.unpack bytes)

crc8 :: String -> Int
crc8 s = foldl (\acc c -> (acc `xor` ord c) `mod` 256) 0 s
where xor a b = a `Data.Bits.xor` b

MQTT Integration​

MQTT connectivity uses mqtt-hs, providing a pure-functional interface to publish telemetry and subscribe to command topics.

module HIL.MQTT where

import Network.MQTT.Client
import qualified Data.ByteString.Char8 as B

connectBroker :: String -> Int -> IO MQTTClient
connectBroker host port = do
let connOpts = (mqttConfig { _hostname = host
, _port = fromIntegral port
, _connID = "hil-haskell"
})
newMQTTClient connOpts

publishTelemetry :: MQTTClient -> String -> String -> IO ()
publishTelemetry client topic payload =
publish client topic (B.pack payload) QoS1

subscribeCommands :: MQTTClient -> (String -> IO ()) -> IO ()
subscribeCommands client handler = do
subscribe client [("#", QoS1)]
forever $ do
msg <- waitForMessage client
handler (B.unpack (messagePayload msg))

STM Concurrency​

For concurrent hardware access—reading from multiple sensors while publishing telemetry—the evaluator uses Software Transactional Memory. STM composes concurrent actions with the same referential-transparency guarantees as pure code (Peyton Jones, 2003).

module HIL.Concurrent where

import Control.Concurrent.STM
import Control.Concurrent.Async (mapConcurrently)

data SensorReading = SensorReading
{ sensorId :: String
, value :: Double
} deriving (Show)

readSensors :: [String] -> TVar [SensorReading] -> IO ()
readSensors sensors tvar = do
readings <- mapConcurrently readOne sensors
atomically $ writeTVar tvar readings
where
readOne sid = do
v <- simulateADC sid -- placeholder for real ADC read
return $ SensorReading sid v

simulateADC :: String -> IO Double
simulateADC _ = return 3.14 -- stub

publishLoop :: MQTTClient -> TVar [SensorReading] -> IO ()
publishLoop client tvar = forever $ do
readings <- atomically $ readTVar tvar
mapM_ (\r -> publishTelemetry client ("hil/sensors/" ++ sensorId r)
(show (value r))) readings
threadDelay 1000000

Complete Example​

The following program reads a digital sensor, computes a rolling average, and publishes the result over MQTT. It demonstrates the full pipeline from source parsing through concurrent evaluation.

module Main where

import HIL.AST
import HIL.Parser
import HIL.Eval
import HIL.Serial
import HIL.MQTT
import HIL.Concurrent
import Control.Concurrent.STM
import qualified Data.Map.Strict as Map

hilSource :: String
hilSource = unlines
[ "(define sensor-pin 2)"
, "(define threshold 512)"
, "(define loop-count 10)"
, "(do"
, " (log \"HIL Haskell runtime starting\")"
, " (pin-mode sensor-pin 0)"
, " (for i 0 loop-count"
, " (do"
, " (define raw (analog-read sensor-pin))"
, " (log (string-append \"Reading: \" (to-string raw)))"
, " (if (> raw threshold)"
, " (digital-write 13 1)"
, " (digital-write 13 13 0)))))"
]

main :: IO ()
main = do
case parseHIL hilSource of
Left err -> print err
Right ast -> do
putStrLn $ "Parsed AST: " ++ show ast
result <- runExceptT (runReaderT (eval ast) Map.empty)
case result of
Left err -> putStrLn $ "Error: " ++ show err
Right val -> putStrLn $ "Result: " ++ show val

References​

Lipovača, M. (2011). Real world Haskell. O'Reilly Media.

Matsakis, N. D., & Klock, F. S. (2014). The Rust language. ACM SIGAda Ada Letters, 34(3), 103–104. https://doi.org/10.1145/2669742.2669745

Peyton Jones, S. (Ed.). (2003). Haskell 98 language and libraries: The revised report. Cambridge University Press.

Rashwan, S. (2026). HIL: A LISP-based hardware-in-the-loop operating system. https://github.com/SRashwan/hilp

Rust Foundation. (2024). The Rust programming language (2nd ed.). https://doc.rust-lang.org/book/

Thompson, S. (2019). Haskell: The craft of functional programming (3rd ed.). Pearson.

labrust. (2023). Labrust: Rust for laboratory automation. https://github.com/labrust/labrust