Part 1: Rust Compiler Internals
Compilation Pipeline
Source Code (.rs)
↓
Lexer → Tokens
↓
Parser → AST (Abstract Syntax Tree)
↓
HIR (High-level IR)
↓
Type Checking & Borrow Checking
↓
MIR (Mid-level IR)
↓
Optimization
↓
LLVM IR
↓
Machine Code
Abstract Syntax Tree (AST)
use syn::{parse_str, File};
fn main() {
let code = r#"
fn add(a: i32, b: i32) -> i32 {
a + b
}
"#;
let ast: File = parse_str(code).unwrap();
// Inspect the AST
println!("{:#?}", ast);
}
// Output shows the structure:
// File {
// items: [
// Item::Fn {
// sig: Signature {
// ident: "add",
// inputs: [a: i32, b: i32],
// output: i32,
// },
// block: ...
// }
// ]
// }
MIR (Mid-level Intermediate Representation)
// To see MIR output:
// rustc +nightly -Z unpretty=mir myfile.rs
fn factorial(n: u32) -> u32 {
if n == 0 {
1
} else {
n * factorial(n - 1)
}
}
// MIR representation (simplified):
// fn factorial(_1: u32) -> u32 {
// let mut _0: u32;
// let mut _2: bool;
// let mut _3: u32;
// let mut _4: u32;
//
// bb0: {
// _2 = Eq(_1, const 0_u32);
// switchInt(_2) -> [false: bb2, otherwise: bb1];
// }
//
// bb1: {
// _0 = const 1_u32;
// return;
// }
//
// bb2: {
// _4 = Sub(_1, const 1_u32);
// _3 = factorial(_4);
// _0 = Mul(_1, _3);
// return;
// }
// }
Custom Compiler Plugins
// In a separate crate with proc-macro = true
#![feature(rustc_private)]
extern crate rustc_driver;
extern crate rustc_interface;
extern crate rustc_lint;
extern crate rustc_session;
use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_session::declare_lint;
declare_lint! {
pub FORBIDDEN_FUNCTION,
Warn,
"warns when using forbidden functions"
}
struct ForbiddenFunctionLint;
impl LateLintPass<'_> for ForbiddenFunctionLint {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &rustc_hir::Expr) {
// Check for forbidden function calls
// Emit warnings if found
}
}
Part 2: Embedded Rust (no_std)
Understanding no_std
#![no_std] attribute tells the compiler
not to link the standard library. This is essential for embedded systems and OS kernels where
there's no operating system to provide standard library functionality.
#![no_std]
#![no_main]
use core::panic::PanicInfo;
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
#[no_mangle]
pub extern "C" fn _start() -> ! {
// Entry point for bare metal
loop {}
}
Embedded Development for ARM Cortex-M
[package]
name = "stm32-blinky"
version = "0.1.0"
edition = "2021"
[dependencies]
cortex-m = "0.7"
cortex-m-rt = "0.7"
panic-halt = "0.2"
stm32f4xx-hal = { version = "0.16", features = ["stm32f411"] }
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
#![no_std]
#![no_main]
use panic_halt as _;
use cortex_m_rt::entry;
use stm32f4xx_hal::{pac, prelude::*};
#[entry]
fn main() -> ! {
// Get device peripherals
let dp = pac::Peripherals::take().unwrap();
// Configure clock
let rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.sysclk(84.MHz()).freeze();
// Get GPIO port C
let gpioc = dp.GPIOC.split();
// Configure PC13 as output (LED on BluePill)
let mut led = gpioc.pc13.into_push_pull_output();
// Blink LED
loop {
led.set_high();
cortex_m::asm::delay(8_000_000);
led.set_low();
cortex_m::asm::delay(8_000_000);
}
}
Memory Layout and Linker Scripts
/* STM32F411CEU6 */
MEMORY
{
FLASH : ORIGIN = 0x08000000, LENGTH = 512K
RAM : ORIGIN = 0x20000000, LENGTH = 128K
}
/* Stack grows down from end of RAM */
_stack_start = ORIGIN(RAM) + LENGTH(RAM);
SECTIONS
{
.vector_table ORIGIN(FLASH) : {
LONG(_stack_start);
KEEP(*(.vector_table.reset_vector));
} > FLASH
.text : {
*(.text .text.*);
} > FLASH
.rodata : {
*(.rodata .rodata.*);
} > FLASH
.data : {
*(.data .data.*);
} > RAM AT > FLASH
.bss : {
*(.bss .bss.*);
} > RAM
}
Interrupt Handling
#![no_std]
#![no_main]
use cortex_m_rt::{entry, exception};
use panic_halt as _;
#[entry]
fn main() -> ! {
// Setup code
loop {
// Main loop
}
}
#[exception]
fn HardFault(ef: &cortex_m_rt::ExceptionFrame) -> ! {
// Handle hard fault
panic!("HardFault: {:#?}", ef);
}
#[exception]
fn DefaultHandler(irqn: i16) {
// Handle other interrupts
panic!("Unhandled interrupt: {}", irqn);
}
RISC-V Embedded
#![no_std]
#![no_main]
use riscv_rt::entry;
use panic_halt as _;
// UART base address for SiFive FE310
const UART0_BASE: usize = 0x1001_3000;
fn uart_putc(c: u8) {
unsafe {
let txdata = (UART0_BASE + 0x00) as *mut u32;
while (*txdata & 0x8000_0000) != 0 {}
*txdata = c as u32;
}
}
fn uart_puts(s: &str) {
for byte in s.bytes() {
uart_putc(byte);
}
}
#[entry]
fn main() -> ! {
uart_puts("Hello from RISC-V!\r\n");
loop {
uart_puts("Tick\r\n");
// Delay
for _ in 0..1_000_000 {
unsafe { riscv::asm::nop(); }
}
}
}
Advanced Embedded Patterns
DMA (Direct Memory Access)
use stm32f4xx_hal::{dma, pac};
fn setup_dma_transfer() {
let dp = pac::Peripherals::take().unwrap();
// Source buffer
let src_buffer: [u32; 256] = [0; 256];
// Destination buffer
let mut dst_buffer: [u32; 256] = [0; 256];
// Configure DMA stream
let dma2 = dp.DMA2;
let stream = dma::StreamsTuple::new(dma2).0;
// Setup transfer
let transfer = dma::Transfer::init(
stream,
unsafe { &src_buffer },
unsafe { &mut dst_buffer },
dma::config::DmaConfig::default()
.memory_increment(true)
.peripheral_increment(true),
);
// Start transfer
transfer.start(|_| {});
// Wait for completion
while !transfer.get_transfer_complete_flag() {}
}
Power Management
use cortex_m::asm;
use stm32f4xx_hal::pac;
fn enter_sleep_mode() {
let dp = pac::Peripherals::take().unwrap();
let mut scb = cortex_m::peripheral::SCB::ptr();
unsafe {
// Configure sleep mode
(*scb).set_sleepdeep();
// Wait for interrupt
asm::wfi();
}
}
fn enter_stop_mode() {
let dp = pac::Peripherals::take().unwrap();
// Disable systick
cortex_m::peripheral::SYST::ptr();
// Enter STOP mode
dp.PWR.cr.modify(|_, w| w.lpds().set_bit());
dp.PWR.cr.modify(|_, w| w.pdds().clear_bit());
unsafe {
asm::wfi();
}
}
Real-Time Operating Systems (RTOS)
#![no_std]
#![no_main]
use panic_halt as _;
use rtic::app;
use stm32f4xx_hal::{pac, prelude::*};
#[app(device = stm32f4xx_hal::pac, peripherals = true)]
mod app {
use super::*;
#[shared]
struct Shared {
counter: u32,
}
#[local]
struct Local {
led: pac::GPIOC,
}
#[init]
fn init(ctx: init::Context) -> (Shared, Local, init::Monotonics) {
let gpioc = ctx.device.GPIOC;
(
Shared { counter: 0 },
Local { led: gpioc },
init::Monotonics(),
)
}
#[task(shared = [counter])]
fn task1(mut ctx: task1::Context) {
ctx.shared.counter.lock(|c| *c += 1);
}
#[task(shared = [counter], local = [led])]
fn task2(mut ctx: task2::Context) {
ctx.shared.counter.lock(|c| {
if *c % 2 == 0 {
// Toggle LED
}
});
}
}
Best Practices
🔑 Embedded Rust Best Practices
- Minimize Binary Size: Use
opt-level = "z"and LTO - Avoid Allocations: Use stack-allocated data structures
- Handle Panics: Implement appropriate panic handlers
- Test on Hardware: Simulators don't catch everything
- Use Type Safety: Leverage Rust's type system for hardware safety
- Document Memory Maps: Keep clear documentation of hardware layout
Summary
✅ You've learned:
- Rust compiler internals: AST, HIR, MIR
- How to work without the standard library (no_std)
- Embedded development for ARM Cortex-M and RISC-V
- Memory layout and linker scripts
- Interrupt handling and DMA
- Power management and RTOS integration
Understanding compiler internals helps you write better Rust code, while embedded programming skills open up the world of IoT, robotics, and systems programming. These skills are fundamental for becoming a true Rust master.