Rust
The Rust port of the HIL evaluator provides a zero-cost-abstraction, memory-safe HIL LISP runtime suitable for both host-side evaluation and direct on-MCU execution via no_std. The crate is published as hil-rs on crates.io (Matsakis & Klock, 2014).
Installation
[dependencies]
hil-rs = "0.12"
tokio = { version = "1", features = ["full"] }
nom = "7"
serialport = "4"
rumqttc = "0.23"
Compilation Pipeline
The pipeline is structured around Rust's ownership model: parsed AST nodes are moved (not copied) through the evaluator, eliminating data races at compile time. The Tokio async runtime multiplexes serial reads, MQTT publishes, and timer-driven sensor polls across a single thread pool (Rust Foundation, 2024).
Enum-Based Abstract Syntax Tree
Rust enums model the HIL LISP AST with exhaustive pattern matching enforced by the compiler. Unlike a class hierarchy, the compiler guarantees every variant is handled.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
Int(i64),
Float(f64),
Bool(bool),
Str(String),
Symbol(String),
List(Vec<Expr>),
Nil,
}
#[derive(Debug, Clone)]
pub enum Decl {
Defun {
name: String,
params: Vec<String>,
body: Box<Expr>,
},
DefVar {
name: String,
init: Box<Expr>,
},
DefMacro {
name: String,
params: Vec<String>,
expansion: Box<Expr>,
},
}
#[derive(Debug, Clone)]
pub struct Program {
pub decls: Vec<Decl>,
pub main: Expr,
}
The #[derive(PartialEq)] on Expr allows comparing AST nodes in tests and property-based testing frameworks without manual impl blocks. Every match on Expr that misses a variant produces a compiler error, which is critical when the evaluator controls live hardware pins (Matsakis & Klock, 2014).
Nom Parser
The parser is built with nom, a parser-combinator library that composes zero-copy parsers from reusable primitives. Nom parsers return IResult<&str, Expr>, threading input through the combinator chain without allocating intermediate strings.
use nom::{
branch::alt,
bytes::complete::{tag, take_while1},
character::complete::{char, multispace0, digit1},
combinator::{map, opt, recognize},
multi::many0,
number::complete::double,
sequence::{delimited, preceded},
IResult,
};
fn is_symbol_char(c: char) -> bool {
!c.is_whitespace() && c != '(' && c != ')' && c != '"'
}
fn parse_symbol(input: &str) -> IResult<&str, Expr> {
map(
take_while1(is_symbol_char),
|s: &str| match s {
"true" => Expr::Bool(true),
"false" => Expr::Bool(false),
"nil" => Expr::Nil,
_ => Expr::Symbol(s.to_string()),
},
)(input)
}
fn parse_int(input: &str) -> IResult<&str, Expr> {
map(recognize(preceded(opt(char('-')), digit1)), |s: &str| {
Expr::Int(s.parse::<i64>().unwrap())
})(input)
}
fn parse_float(input: &str) -> IResult<&str, Expr> {
map(double, Expr::Float)(input)
}
fn parse_string(input: &str) -> IResult<&str, Expr> {
map(
delimited(char('"'), nom::bytes::complete::take_until("\""), char('"')),
|s: &str| Expr::Str(s.to_string()),
)(input)
}
fn parse_list(input: &str) -> IResult<&str, Expr> {
map(
delimited(
char('('),
delimited(multispace0, many0(parse_expr), multispace0),
char(')'),
),
Expr::List,
)(input)
}
fn parse_expr(input: &str) -> IResult<&str, Expr> {
alt((parse_float, parse_int, parse_string, parse_symbol, parse_list))(input)
}
pub fn parse_program(input: &str) -> Result<Program, String> {
match nom::multi::many0(preceded(multispace0, parse_expr))(input) {
Ok((_, exprs)) => {
let decls = Vec::new();
let main = Expr::List(exprs);
Ok(Program { decls, main })
}
Err(e) => Err(format!("Parse error: {:?}", e)),
}
}
Async Evaluator
The evaluator runs on the Tokio runtime. It uses async fn for hardware I/O and evaluates expressions in an Environment struct backed by Arc<RwLock<HashMap>> for concurrent access from multiple tasks (Rust Foundation, 2024).
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use tokio::sync::mpsc;
#[derive(Debug, Clone)]
pub enum EvalError {
UnboundVar(String),
TypeError(String),
ArityError { expected: usize, actual: usize },
}
pub type Env = Arc<RwLock<HashMap<String, Expr>>>;
pub async fn eval(expr: &Expr, env: &Env) -> Result<Expr, EvalError> {
match expr {
Expr::Int(n) => Ok(Expr::Int(*n)),
Expr::Float(f) => Ok(Expr::Float(*f)),
Expr::Bool(b) => Ok(Expr::Bool(*b)),
Expr::Str(s) => Ok(Expr::Str(s.clone())),
Expr::Nil => Ok(Expr::Nil),
Expr::Symbol(name) => {
let map = env.read().map_err(|_| EvalError::TypeError("lock poisoned".into()))?;
map.get(name)
.cloned()
.ok_or_else(|| EvalError::UnboundVar(name.clone()))
}
Expr::List(vec) if vec.is_empty() => Ok(Expr::Nil),
Expr::List(vec) => {
let head = &vec[0];
let args = &vec[1..];
match head {
Expr::Symbol(s) if s == "define" => {
if let [Expr::Symbol(name), val] = args {
let v = eval(val, env).await?;
env.write()
.map_err(|_| EvalError::TypeError("lock poisoned".into()))?
.insert(name.clone(), v.clone());
Ok(v)
} else {
Err(EvalError::ArityError { expected: 2, actual: args.len() })
}
}
Expr::Symbol(s) if s == "log" => {
if let [msg] = args {
let v = eval(msg, env).await?;
println!("[HIL] {:?}", v);
Ok(Expr::Nil)
} else {
Err(EvalError::ArityError { expected: 1, actual: args.len() })
}
}
Expr::Symbol(s) if s == "pin-mode" => {
if let [Expr::Int(pin), Expr::Int(mode)] = args {
println!("[PIN-MODE] pin={} mode={}", pin, mode);
Ok(Expr::Nil)
} else {
Err(EvalError::TypeError("pin-mode expects (int int)".into()))
}
}
Expr::Symbol(s) if s == "digital-write" => {
if let [Expr::Int(pin), Expr::Int(val)] = args {
println!("[DW] pin={} val={}", pin, val);
Ok(Expr::Nil)
} else {
Err(EvalError::TypeError("digital-write expects (int int)".into()))
}
}
Expr::Symbol(s) if s == "+" => {
let a = eval(&args[0], env).await?;
let b = eval(&args[1], env).await?;
match (&a, &b) {
(Expr::Int(x), Expr::Int(y)) => Ok(Expr::Int(x + y)),
(Expr::Float(x), Expr::Float(y)) => Ok(Expr::Float(x + y)),
_ => Err(EvalError::TypeError("+ requires numeric operands".into())),
}
}
Expr::Symbol(s) if s == "-" => {
let a = eval(&args[0], env).await?;
let b = eval(&args[1], env).await?;
match (&a, &b) {
(Expr::Int(x), Expr::Int(y)) => Ok(Expr::Int(x - y)),
(Expr::Float(x), Expr::Float(y)) => Ok(Expr::Float(x - y)),
_ => Err(EvalError::TypeError("- requires numeric operands".into())),
}
}
Expr::Symbol(s) if s == "if" => {
if let [cond, then_e, else_e] = args {
let c = eval(cond, env).await?;
match c {
Expr::Bool(true) => eval(then_e, env).await,
Expr::Bool(false) => eval(else_e, env).await,
_ => Err(EvalError::TypeError("if requires boolean condition".into())),
}
} else {
Err(EvalError::ArityError { expected: 3, actual: args.len() })
}
}
_ => {
let func = eval(head, env).await?;
let mut vals = Vec::new();
for a in args {
vals.push(eval(a, env).await?);
}
apply(&func, &vals).await
}
}
}
}
}
async fn apply(func: &Expr, args: &[Expr]) -> Result<Expr, EvalError> {
match (func, args) {
(Expr::Symbol(s), _) if s == "string-append" => {
let mut result = String::new();
for a in args {
match a {
Expr::Str(s) => result.push_str(s),
other => result.push_str(&format!("{:?}", other)),
}
}
Ok(Expr::Str(result))
}
_ => Err(EvalError::TypeError(format!("cannot apply {:?}", func))),
}
}
Serial Client
The serial client uses the serialport crate, which provides cross-platform serial port access. On no_std targets, HAL trait implementations replace this crate directly.
use serialport::SerialPort;
use std::io::{Read, Write};
use std::time::Duration;
pub struct HILSerial {
port: Box<dyn SerialPort>,
}
impl HILSerial {
pub fn open(path: &str, baud: u32) -> Result<Self, Box<dyn std::error::Error>> {
let port = serialport::new(path, baud)
.timeout(Duration::from_millis(100))
.open()?;
Ok(Self { port })
}
pub fn send_command(&mut self, cmd: &str) -> Result<(), Box<dyn std::error::Error>> {
let payload = format!("{}\n", cmd);
self.port.write_all(payload.as_bytes())?;
self.port.flush()?;
Ok(())
}
pub fn read_response(&mut self) -> Result<String, Box<dyn std::error::Error>> {
let mut buf = vec![0u8; 256];
let n = self.port.read(&mut buf)?;
Ok(String::from_utf8_lossy(&buf[..n]).to_string())
}
}
MQTT Client
MQTT connectivity uses rumqttc, which provides an async client built on Tokio. The client runs as a background task and streams incoming messages through an mpsc channel.
use rumqttc::{MqttClient, MqttOptions, QoS};
use std::time::Duration;
pub async fn connect_mqtt(
client_id: &str,
host: &str,
port: u16,
) -> Result<(MqttClient, rumqttc::EventLoop), Box<dyn std::error::Error>> {
let mut opts = MqttOptions::new(client_id, host, port);
opts.set_keep_alive(Duration::from_secs(30));
let (client, eventloop) = MqttClient::new(opts, 100);
Ok((client, eventloop))
}
pub async fn publish_telemetry(
client: &MqttClient,
topic: &str,
payload: &str,
) -> Result<(), Box<dyn std::error::Error>> {
client.publish(topic, QoS::AtLeastOnce, false, payload.as_bytes())?;
Ok(())
}
pub async fn subscribe_commands(
client: &MqttClient,
topic: &str,
) -> Result<(), Box<dyn std::error::Error>> {
client.subscribe(topic, QoS::AtLeastOnce)?;
Ok(())
}
Embedded Rust (no_std)
For direct MCU execution without an operating system, hil-rs supports no_std builds via Cargo feature flags. The evaluator compiles against the target microcontroller's HAL traits, and serial I/O is handled through the embedded-hal Serial trait rather than the OS serialport crate (labrust, 2023).
#![no_std]
#![no_main]
use cortex_m_rt::entry;
use embedded_hal::serial::{Read, Write};
use hil_rs::ast::Expr;
use hil_rs::eval::eval_no_std;
#[entry]
fn main() -> ! {
let peripherals = stm32f4::stm32f411::Peripherals::take().unwrap();
let mut serial = USART1::new(peripherals.USART1, 115_200);
let source = b"(log \"Hello from MCU\")";
match hil_rs::parser::parse(source) {
Ok(expr) => {
let env = hil_rs::env::Env::new();
let _ = eval_no_std(&expr, &env, &mut serial);
}
Err(_) => {
let _ = serial.write_all(b"PARSE ERROR\n");
}
}
loop {
cortex_m::asm::wfi();
}
}
The no_std path excludes heap-allocating combinators and uses stack-allocated fixed-size buffers. The Expr::List variant is replaced with a bounded ArrayVec in this mode, and recursive evaluator depth is capped by a compile-time constant to prevent stack overflow on MCUs with limited SRAM (labrust, 2023).
Complete Example
The following example parses a HIL program, evaluates it on the Tokio runtime, and publishes results over MQTT. It exercises every component of the Rust port.
use hil_rs::ast::{Decl, Expr, Program};
use hil_rs::eval::{eval, Env};
use hil_rs::mqtt::{connect_mqtt, publish_telemetry, subscribe_commands};
use hil_rs::parser::parse_program;
use hil_rs::serial::HILSerial;
use std::sync::{Arc, RwLock};
use tokio;
const HIL_SOURCE: &str = r#"
(define sensor-pin 2)
(define threshold 512)
(define loop-count 10)
(do
(log "HIL Rust runtime starting")
(pin-mode sensor-pin 0)
(digital-write 13 1))
"#;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Parse
let program = parse_program(HIL_SOURCE)?;
println!("Parsed: {:?}", program);
// Evaluate
let env: Env = Arc::new(RwLock::new(std::collections::HashMap::new()));
let result = eval(&program.main, &env).await?;
println!("Result: {:?}", result);
// Serial
let mut serial = HILSerial::open("/dev/ttyUSB0", 115200)?;
serial.send_command("PING")?;
let resp = serial.read_response()?;
println!("Serial: {}", resp);
// MQTT
let (client, mut eventloop) = connect_mqtt("hil-rust", "localhost", 1883).await?;
subscribe_commands(&client, "hil/commands/#").await?;
publish_telemetry(&client, "hil/status", "running").await?;
tokio::spawn(async move {
loop {
if let Ok(event) = eventloop.poll().await {
println!("MQTT event: {:?}", event);
}
}
});
// Continuous evaluation loop
let eval_env = env.clone();
let eval_client = client.clone();
tokio::spawn(async move {
let mut interval = tokio::time::interval(tokio::time::Duration::from_secs(1));
loop {
interval.tick().await;
if let Ok(reading) = eval(&Expr::List(vec![
Expr::Symbol("analog-read".into()),
Expr::Int(2),
]), &eval_env).await
{
let _ = publish_telemetry(
&eval_client,
"hil/sensors/2",
&format!("{:?}", reading),
).await;
}
}
});
tokio::signal::ctrl_c().await?;
Ok(())
}
References
labrust. (2023). Labrust: Rust for laboratory automation. https://github.com/labrust/labrust
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
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/