nucleus-compiler 0.0.1

Nucleus pinmux compiler: stm32.toml parsing, hardware constraint solving, and HAL codegen
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! HAL code generation.
//!
//! Turns a validated [`Config`] into two C files:
//!
//! - `nucleus_config.h` — a typed config struct per peripheral plus `extern`
//!   HAL handle declarations and the `Nucleus_Init()` prototype.
//! - `nucleus_init.c` — the resolved config struct instances, the handle
//!   definitions, and a single `Nucleus_Init()` that enables GPIO clocks,
//!   configures the alternate-function muxing (using AF numbers resolved from
//!   [`nucleus_db`]), and calls the stock ST HAL `HAL_*_Init` functions.
//!
//! **Architectural rule (README):** the generated code never reimplements the
//! HAL. It only calls `Init` functions with resolved parameters, so a HAL
//! point-release that changes internals does not break Nucleus output. The
//! tested HAL family is STM32F4 (`stm32f4xx_hal.h`).
//!
//! Codegen assumes the config already passed [`crate::solver::solve`]; it skips
//! unmodelled peripheral kinds and pins it cannot resolve rather than failing.

use std::fmt::Write;
use std::str::FromStr;

use nucleus_db::{Database, Pin};

use crate::config::{Config, Peripheral};
use crate::model;

/// The generated C sources for a project.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Generated {
    pub config_h: String,
    pub init_c: String,
}

/// One peripheral lowered to everything codegen needs.
struct Lowered {
    /// HAL instance name, e.g. `USART2`.
    instance: String,
    /// Handle variable, e.g. `huart2`.
    handle: String,
    /// HAL handle type, e.g. `UART_HandleTypeDef`.
    handle_type: &'static str,
    /// Per-instance config struct type, e.g. `Nucleus_USART2_Config`.
    config_type: String,
    kind: Kind,
    /// Resolved pin uses: `(pin, af, signal)`.
    pins: Vec<(Pin, u8, &'static str)>,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Kind {
    Usart,
    Spi,
    I2c,
    Tim,
}

/// Generate `nucleus_config.h` and `nucleus_init.c` for `config`.
pub fn generate(config: &Config, db: &Database) -> Generated {
    let lowered: Vec<Lowered> = config
        .peripherals
        .iter()
        .filter_map(|(instance, table)| lower(instance, table, db))
        .collect();

    Generated {
        config_h: config_header(&lowered),
        init_c: init_source(config, &lowered),
    }
}

fn kind_of(instance: &str) -> Option<Kind> {
    let prefix = instance.trim_end_matches(|c: char| c.is_ascii_digit());
    match prefix {
        "usart" | "uart" => Some(Kind::Usart),
        "spi" => Some(Kind::Spi),
        "i2c" | "fmpi2c" => Some(Kind::I2c),
        "tim" => Some(Kind::Tim),
        _ => None,
    }
}

fn lower(instance: &str, table: &Peripheral, db: &Database) -> Option<Lowered> {
    let kind = kind_of(instance)?;
    let roles = model::roles_for(instance)?;
    let name = model::peripheral_name(instance);
    // The instance index is the *trailing* digit run, so `i2c1` -> "1" (not
    // "21" from the embedded "2" in "i2c").
    let digits: String = {
        let rev: String = instance
            .chars()
            .rev()
            .take_while(char::is_ascii_digit)
            .collect();
        rev.chars().rev().collect()
    };

    let (handle_prefix, handle_type) = match kind {
        Kind::Usart => ("huart", "UART_HandleTypeDef"),
        Kind::Spi => ("hspi", "SPI_HandleTypeDef"),
        Kind::I2c => ("hi2c", "I2C_HandleTypeDef"),
        Kind::Tim => ("htim", "TIM_HandleTypeDef"),
    };

    let mut pins = Vec::new();
    for role in roles {
        if let Some(value) = table.pin_str(role.key) {
            if let Ok(pin) = Pin::from_str(value) {
                if let Some(af) = db.find_af(pin, &name, role.signal) {
                    pins.push((pin, af, role.signal));
                }
            }
        }
    }

    Some(Lowered {
        config_type: format!("Nucleus_{name}_Config"),
        handle: format!("{handle_prefix}{digits}"),
        handle_type,
        instance: name,
        kind,
        pins,
    })
}

fn config_header(lowered: &[Lowered]) -> String {
    let mut s = String::new();
    s.push_str(GENERATED_BANNER);
    s.push_str(
        "#ifndef NUCLEUS_CONFIG_H\n\
         #define NUCLEUS_CONFIG_H\n\n\
         #include \"stm32f4xx_hal.h\"\n\n\
         #ifdef __cplusplus\n\
         extern \"C\" {\n\
         #endif\n\n",
    );

    for p in lowered {
        let _ = writeln!(s, "/* {} — resolved configuration */", p.instance);
        let _ = writeln!(s, "typedef struct {{");
        for field in p.kind.config_fields() {
            let _ = writeln!(s, "    uint32_t {field};");
        }
        let _ = writeln!(s, "}} {};", p.config_type);
        let _ = writeln!(s, "extern {} {};\n", p.handle_type, p.handle);
    }

    s.push_str(
        "/* Initializes every peripheral declared in stm32.toml. Call once after\n\
         \x20  HAL_Init() and the system clock configuration. */\n\
         void Nucleus_Init(void);\n\n\
         #ifdef __cplusplus\n\
         }\n\
         #endif\n\n\
         #endif /* NUCLEUS_CONFIG_H */\n",
    );
    s
}

fn init_source(config: &Config, lowered: &[Lowered]) -> String {
    let mut s = String::new();
    s.push_str(GENERATED_BANNER);
    s.push_str("#include \"nucleus_config.h\"\n\n");

    // Handle definitions.
    for p in lowered {
        let _ = writeln!(s, "{} {};", p.handle_type, p.handle);
    }
    s.push('\n');

    // Resolved config struct instances (the "typed config" the HAL init reads).
    for p in lowered {
        emit_config_instance(&mut s, config, p);
    }

    s.push_str("void Nucleus_Init(void)\n{\n");
    s.push_str("    GPIO_InitTypeDef GPIO_InitStruct = {0};\n\n");

    emit_gpio_clock_enables(&mut s, lowered);

    for p in lowered {
        let _ = writeln!(s, "    /* ---- {} ---- */", p.instance);
        emit_gpio_config(&mut s, p);
        emit_peripheral_init(&mut s, p);
        s.push('\n');
    }

    s.push_str("}\n");
    s
}

fn emit_config_instance(s: &mut String, config: &Config, p: &Lowered) {
    let var = format!("{}_config", p.instance.to_ascii_lowercase());
    let table = &config.peripherals[&p.instance.to_ascii_lowercase()];
    let _ = writeln!(s, "static const {} {} = {{", p.config_type, var);
    match p.kind {
        Kind::Usart => {
            let baud = table
                .0
                .get("baud")
                .and_then(toml::Value::as_integer)
                .unwrap_or(115_200);
            let _ = writeln!(s, "    .BaudRate = {baud}u,");
        }
        Kind::Spi => {
            let mode = table
                .0
                .get("mode")
                .and_then(toml::Value::as_integer)
                .unwrap_or(0);
            let (cpol, cpha) = spi_mode(mode);
            let _ = writeln!(s, "    .CLKPolarity = {cpol},");
            let _ = writeln!(s, "    .CLKPhase = {cpha},");
        }
        Kind::I2c => {
            let speed = table
                .0
                .get("speed")
                .and_then(toml::Value::as_str)
                .unwrap_or("standard");
            let hz = if speed.eq_ignore_ascii_case("fast") {
                400_000
            } else {
                100_000
            };
            let _ = writeln!(s, "    .ClockSpeed = {hz}u,");
        }
        Kind::Tim => {
            let (psc, arr) = tim_timing(config, table);
            let _ = writeln!(s, "    .Prescaler = {psc}u,");
            let _ = writeln!(s, "    .Period = {arr}u,");
        }
    }
    let _ = writeln!(s, "}};\n");
}

fn emit_gpio_clock_enables(s: &mut String, lowered: &[Lowered]) {
    let mut ports: Vec<char> = lowered
        .iter()
        .flat_map(|p| p.pins.iter().map(|(pin, _, _)| pin.port.letter()))
        .collect();
    ports.sort_unstable();
    ports.dedup();
    if ports.is_empty() {
        return;
    }
    s.push_str("    /* GPIO port clocks */\n");
    for port in ports {
        let _ = writeln!(s, "    __HAL_RCC_GPIO{port}_CLK_ENABLE();");
    }
    s.push('\n');
}

fn emit_gpio_config(s: &mut String, p: &Lowered) {
    for (pin, af, _signal) in &p.pins {
        let port = pin.port.letter();
        let pull = if p.kind == Kind::I2c {
            "GPIO_PULLUP"
        } else {
            "GPIO_NOPULL"
        };
        let mode = if p.kind == Kind::I2c {
            "GPIO_MODE_AF_OD"
        } else {
            "GPIO_MODE_AF_PP"
        };
        let _ = writeln!(s, "    GPIO_InitStruct.Pin = GPIO_PIN_{};", pin.number);
        let _ = writeln!(s, "    GPIO_InitStruct.Mode = {mode};");
        let _ = writeln!(s, "    GPIO_InitStruct.Pull = {pull};");
        let _ = writeln!(s, "    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;");
        let _ = writeln!(
            s,
            "    GPIO_InitStruct.Alternate = GPIO_AF{af}_{};",
            p.instance
        );
        let _ = writeln!(s, "    HAL_GPIO_Init(GPIO{port}, &GPIO_InitStruct);");
    }
}

fn emit_peripheral_init(s: &mut String, p: &Lowered) {
    let h = &p.handle;
    let cfg = format!("{}_config", p.instance.to_ascii_lowercase());
    let _ = writeln!(s, "    __HAL_RCC_{}_CLK_ENABLE();", p.instance);
    let _ = writeln!(s, "    {h}.Instance = {};", p.instance);
    match p.kind {
        Kind::Usart => {
            let _ = writeln!(s, "    {h}.Init.BaudRate = {cfg}.BaudRate;");
            for (field, val) in [
                ("WordLength", "UART_WORDLENGTH_8B"),
                ("StopBits", "UART_STOPBITS_1"),
                ("Parity", "UART_PARITY_NONE"),
                ("Mode", "UART_MODE_TX_RX"),
                ("HwFlowCtl", "UART_HWCONTROL_NONE"),
                ("OverSampling", "UART_OVERSAMPLING_16"),
            ] {
                let _ = writeln!(s, "    {h}.Init.{field} = {val};");
            }
            let _ = writeln!(s, "    HAL_UART_Init(&{h});");
        }
        Kind::Spi => {
            let _ = writeln!(s, "    {h}.Init.CLKPolarity = {cfg}.CLKPolarity;");
            let _ = writeln!(s, "    {h}.Init.CLKPhase = {cfg}.CLKPhase;");
            for (field, val) in [
                ("Mode", "SPI_MODE_MASTER"),
                ("Direction", "SPI_DIRECTION_2LINES"),
                ("DataSize", "SPI_DATASIZE_8BIT"),
                ("NSS", "SPI_NSS_SOFT"),
                ("BaudRatePrescaler", "SPI_BAUDRATEPRESCALER_16"),
                ("FirstBit", "SPI_FIRSTBIT_MSB"),
                ("TIMode", "SPI_TIMODE_DISABLE"),
                ("CRCCalculation", "SPI_CRCCALCULATION_DISABLE"),
            ] {
                let _ = writeln!(s, "    {h}.Init.{field} = {val};");
            }
            let _ = writeln!(s, "    HAL_SPI_Init(&{h});");
        }
        Kind::I2c => {
            let _ = writeln!(s, "    {h}.Init.ClockSpeed = {cfg}.ClockSpeed;");
            for (field, val) in [
                ("DutyCycle", "I2C_DUTYCYCLE_2"),
                ("OwnAddress1", "0"),
                ("AddressingMode", "I2C_ADDRESSINGMODE_7BIT"),
                ("DualAddressMode", "I2C_DUALADDRESS_DISABLE"),
                ("OwnAddress2", "0"),
                ("GeneralCallMode", "I2C_GENERALCALL_DISABLE"),
                ("NoStretchMode", "I2C_NOSTRETCH_DISABLE"),
            ] {
                let _ = writeln!(s, "    {h}.Init.{field} = {val};");
            }
            let _ = writeln!(s, "    HAL_I2C_Init(&{h});");
        }
        Kind::Tim => {
            let _ = writeln!(s, "    {h}.Init.Prescaler = {cfg}.Prescaler;");
            let _ = writeln!(s, "    {h}.Init.Period = {cfg}.Period;");
            for (field, val) in [
                ("CounterMode", "TIM_COUNTERMODE_UP"),
                ("ClockDivision", "TIM_CLOCKDIVISION_DIV1"),
                ("AutoReloadPreload", "TIM_AUTORELOAD_PRELOAD_ENABLE"),
            ] {
                let _ = writeln!(s, "    {h}.Init.{field} = {val};");
            }
            let _ = writeln!(s, "    HAL_TIM_PWM_Init(&{h});");
        }
    }
}

impl Kind {
    fn config_fields(self) -> &'static [&'static str] {
        match self {
            Kind::Usart => &["BaudRate"],
            Kind::Spi => &["CLKPolarity", "CLKPhase"],
            Kind::I2c => &["ClockSpeed"],
            Kind::Tim => &["Prescaler", "Period"],
        }
    }
}

/// SPI mode (0–3) → `(CLKPolarity, CLKPhase)` HAL macros.
fn spi_mode(mode: i64) -> (&'static str, &'static str) {
    match mode {
        1 => ("SPI_POLARITY_LOW", "SPI_PHASE_2EDGE"),
        2 => ("SPI_POLARITY_HIGH", "SPI_PHASE_1EDGE"),
        3 => ("SPI_POLARITY_HIGH", "SPI_PHASE_2EDGE"),
        _ => ("SPI_POLARITY_LOW", "SPI_PHASE_1EDGE"),
    }
}

/// Resolve a PWM timer's `(Prescaler, Period)` from the requested frequency and
/// duty resolution. Uses the device `clock_hz` as the timer clock estimate
/// (an approximation — full clock-tree solving is explicitly out of scope).
fn tim_timing(config: &Config, table: &Peripheral) -> (u32, u32) {
    let bits = table
        .0
        .get("duty_resolution_bits")
        .and_then(toml::Value::as_integer)
        .unwrap_or(16)
        .clamp(1, 31) as u32;
    let arr: u32 = (1u32 << bits) - 1;

    let freq = table
        .0
        .get("frequency_hz")
        .and_then(toml::Value::as_integer)
        .unwrap_or(1000)
        .max(1) as u64;
    let timer_clk = config.device.clock_hz.unwrap_or(180_000_000).max(1);

    // freq = timer_clk / ((PSC + 1) * (ARR + 1))  =>  PSC = timer_clk/(freq*(ARR+1)) - 1
    let divisor = freq * (arr as u64 + 1);
    let psc = (timer_clk / divisor).saturating_sub(1);
    (psc.min(u32::MAX as u64) as u32, arr)
}

const GENERATED_BANNER: &str = "\
/* Generated by Nucleus — do not edit by hand.\n\
\x20* Regenerate with `nucleus build`. Source of truth: stm32.toml. */\n\n";

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config;

    fn gen(text: &str) -> Generated {
        let cfg = config::parse(text).unwrap();
        generate(&cfg, &Database::f446re())
    }

    const EXAMPLE: &str = r#"
[device]
family = "STM32F446RE"
clock_hz = 180_000_000

[peripherals.usart2]
tx = "PA2"
rx = "PA3"
baud = 115200

[peripherals.spi1]
mosi = "PA7"
miso = "PA6"
sck = "PA5"
nss = "PA4"
mode = 0

[peripherals.i2c1]
sda = "PB9"
scl = "PB8"
speed = "fast"

[peripherals.tim2]
channel1 = "PA0"
frequency_hz = 1000
duty_resolution_bits = 16
"#;

    #[test]
    fn header_declares_handles_and_prototype() {
        let g = gen(EXAMPLE);
        assert!(g.config_h.contains("extern UART_HandleTypeDef huart2;"));
        assert!(g.config_h.contains("typedef struct {"));
        assert!(g.config_h.contains("void Nucleus_Init(void);"));
        assert!(g.config_h.contains("#ifndef NUCLEUS_CONFIG_H"));
    }

    #[test]
    fn init_calls_stock_hal_init_functions() {
        let g = gen(EXAMPLE);
        for call in [
            "HAL_UART_Init(&huart2);",
            "HAL_SPI_Init(&hspi1);",
            "HAL_I2C_Init(&hi2c1);",
            "HAL_TIM_PWM_Init(&htim2);",
        ] {
            assert!(g.init_c.contains(call), "missing {call}\n{}", g.init_c);
        }
        // Exactly one init entry point.
        assert_eq!(g.init_c.matches("void Nucleus_Init(void)").count(), 1);
    }

    #[test]
    fn gpio_uses_af_numbers_from_database() {
        let g = gen(EXAMPLE);
        // PA2 = USART2_TX is AF7; PA7 = SPI1_MOSI is AF5; PB9 = I2C1_SDA is AF4.
        assert!(g.init_c.contains("GPIO_InitStruct.Pin = GPIO_PIN_2;"));
        assert!(g.init_c.contains("GPIO_AF7_USART2;"));
        assert!(g.init_c.contains("GPIO_AF5_SPI1;"));
        assert!(g.init_c.contains("GPIO_AF4_I2C1;"));
    }

    #[test]
    fn enables_each_gpio_port_clock_once() {
        let g = gen(EXAMPLE);
        assert_eq!(g.init_c.matches("__HAL_RCC_GPIOA_CLK_ENABLE();").count(), 1);
        assert_eq!(g.init_c.matches("__HAL_RCC_GPIOB_CLK_ENABLE();").count(), 1);
    }

    #[test]
    fn i2c_pins_are_open_drain_with_pullups() {
        let g = gen(EXAMPLE);
        assert!(g.init_c.contains("GPIO_MODE_AF_OD"));
        assert!(g.init_c.contains("GPIO_PULLUP"));
    }

    #[test]
    fn resolved_params_land_in_config_structs() {
        let g = gen(EXAMPLE);
        assert!(g.init_c.contains(".BaudRate = 115200u,"));
        assert!(g.init_c.contains(".ClockSpeed = 400000u,")); // fast
        assert!(g.init_c.contains(".CLKPolarity = SPI_POLARITY_LOW,")); // mode 0
    }

    #[test]
    fn output_is_deterministic() {
        assert_eq!(gen(EXAMPLE), gen(EXAMPLE));
    }

    #[test]
    fn empty_config_still_emits_valid_init() {
        let g = gen("[device]\nfamily = \"STM32F446RE\"\n");
        assert!(g.init_c.contains("void Nucleus_Init(void)"));
        assert!(g.config_h.contains("void Nucleus_Init(void);"));
    }
}