nanoflash 0.1.2

Lay out the flash of ESP32 and Arduino boards and write firmware to them through their bootloaders, natively or in the browser over Web Serial.
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! Linker memory regions and Rust constants, for the `build.rs` of a firmware.

use super::TableError;
use crate::layout::{ResolvedLayout, ResolvedPartition, Role};
use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt::Write;

const REGIONS_WRITER: &str = "linker";
const CONSTANTS_WRITER: &str = "constants";
const DEFAULT_REGION: &str = "FLASH";

/// Words that cannot be an identifier as they are, in any edition.
const KEYWORDS: &[&str] = &[
    "abstract", "as", "async", "await", "become", "box", "break", "const", "continue", "do", "dyn",
    "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if", "impl", "in", "let",
    "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref", "return",
    "static", "struct", "trait", "true", "try", "type", "typeof", "unsafe", "unsized", "use",
    "virtual", "where", "while", "yield",
];

/// Words that cannot be written as raw identifiers.
const NOT_RAW: &[&str] = &["self", "super", "crate"];

/// The `MEMORY` block of a linker script, with one region for every partition.
///
/// The region of a partition is its `linker.region` attribute, else `FLASH` for the firmware,
/// else its name in upper case with every other character replaced by `_`.
///
/// A partition that grows with the flash of the device keeps a region of its size on the minimum
/// flash (the layout must be resolved for it), which is the least it has on any device, and a
/// comment says so. A partition that moves with the flash gets no region, only a comment: no
/// `ORIGIN` is right on every device, and a firmware that uses it fails to link.
pub fn memory_regions(layout: &ResolvedLayout) -> Result<String, TableError> {
    memory_script(layout, &[])
}

/// A memory region that is not a partition of the layout, such as the RAM of the device.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemoryRegion {
    /// The name of the region in the linker script, such as `RAM`.
    pub name: String,
    /// The address of the first byte.
    pub origin: u64,
    /// The size in bytes.
    pub length: u64,
}

/// The `MEMORY` block of [`memory_regions`], with the regions of `extra` after the regions of the
/// layout, written in the same way.
///
/// This is the whole text of a `memory.x` for `cortex-m-rt`, which needs the regions `FLASH` and
/// `RAM`. A region of `extra` is an error when its name is not valid (as for the `linker.region`
/// attribute of a partition), when it has the name of a region of the layout (a partition that
/// moves with the flash has no region, but its name is still taken), or when an earlier region of
/// `extra` has the same name.
pub fn memory_script(
    layout: &ResolvedLayout,
    extra: &[MemoryRegion],
) -> Result<String, TableError> {
    at_minimum(layout, REGIONS_WRITER)?;
    let firmware_without_region: Vec<&ResolvedPartition> = layout
        .partitions
        .iter()
        .filter(|partition| {
            partition.definition.role == Role::Firmware && explicit_region(partition).is_none()
        })
        .collect();
    if let [first, second, ..] = firmware_without_region.as_slice() {
        return Err(TableError::SeveralFirmware {
            writer: REGIONS_WRITER,
            first: first.definition.name.clone(),
            second: second.definition.name.clone(),
        });
    }

    let mut taken: Vec<(String, String)> = Vec::new();
    let mut text = String::from(
        "/* Generated by nanoflash from the board layout. Do not edit. */\nMEMORY\n{\n",
    );
    for partition in &layout.partitions {
        let name = partition.definition.name.as_str();
        let region = match explicit_region(partition) {
            Some(region) => {
                if !valid_region_name(region) {
                    return Err(unknown_value(
                        REGIONS_WRITER,
                        name,
                        "region",
                        String::from(region),
                    ));
                }
                String::from(region)
            }
            None if partition.definition.role == Role::Firmware => String::from(DEFAULT_REGION),
            None => region_from_name(name),
        };
        if let Some(error) = collision(REGIONS_WRITER, &taken, name, &region) {
            return Err(error);
        }
        taken.push((region.clone(), name.into()));
        if partition.moves_with_flash {
            let what = if partition.grows_with_flash {
                "grows and moves"
            } else {
                "moves"
            };
            let _ = writeln!(
                text,
                "  /* {region} {what} with the flash of the device: no region. */"
            );
            continue;
        }
        if partition.grows_with_flash {
            let _ = writeln!(
                text,
                "  /* {region} grows with the flash of the device: LENGTH is its size on the minimum flash. */"
            );
        }
        let out_of_range = || TableError::OutOfRange {
            partition: name.into(),
            writer: REGIONS_WRITER,
        };
        let origin = partition.address(&layout.flash).ok_or_else(out_of_range)?;
        // Writing to a `String` cannot fail.
        let _ = writeln!(
            text,
            "  {region} : ORIGIN = {origin:#010X}, LENGTH = {:#010X}",
            partition.size
        );
    }
    for (index, region) in extra.iter().enumerate() {
        if !valid_region_name(&region.name) {
            return Err(TableError::InvalidRegionName {
                name: region.name.clone(),
            });
        }
        if taken.iter().any(|(name, _)| *name == region.name) {
            return Err(TableError::DuplicateRegion {
                name: region.name.clone(),
            });
        }
        if extra
            .iter()
            .take(index)
            .any(|earlier| earlier.name == region.name)
        {
            return Err(TableError::RepeatedRegion {
                name: region.name.clone(),
            });
        }
        let _ = writeln!(
            text,
            "  {} : ORIGIN = {:#010X}, LENGTH = {:#010X}",
            region.name, region.origin, region.length
        );
    }
    text.push_str("}\n");
    Ok(text)
}

/// Rust constants for the flash and for every partition, as the source of a module.
///
/// The constants are `u32` when every value written fits, else `u64`. Each partition is a module
/// named after it, with `OFFSET`, `SIZE` and `ADDRESS`, except in a layout that detects the
/// flash size. There the layout must be resolved for its minimum flash and:
///
/// - `FLASH_MINIMUM_SIZE` replaces `FLASH_SIZE`;
/// - a partition that grows with the flash has `MINIMUM_SIZE`, its size on the minimum flash
///   (the least it has on any device, at least the minimum its layout declares), instead of
///   `SIZE`;
/// - a partition that moves with the flash has no `OFFSET` and no `ADDRESS`, so a firmware that
///   uses them fails to compile instead of writing at the wrong place.
pub fn rust_constants(layout: &ResolvedLayout) -> Result<String, TableError> {
    at_minimum(layout, CONSTANTS_WRITER)?;
    let mut values = Vec::new();
    values.push(layout.flash.size);
    values.push(layout.flash.base_address);
    let mut addresses = Vec::new();
    for partition in &layout.partitions {
        let address = partition
            .address(&layout.flash)
            .ok_or_else(|| TableError::OutOfRange {
                partition: partition.definition.name.clone(),
                writer: CONSTANTS_WRITER,
            })?;
        if !partition.moves_with_flash {
            values.push(partition.offset);
            values.push(address);
        }
        values.push(partition.size);
        addresses.push(address);
    }
    let wide = values.iter().any(|value| u32::try_from(*value).is_err());
    let (kind, digits) = if wide { ("u64", 16) } else { ("u32", 8) };

    let flash_size = if layout.minimum_flash_size.is_some() {
        "FLASH_MINIMUM_SIZE"
    } else {
        "FLASH_SIZE"
    };
    let mut taken: Vec<(String, String)> = Vec::new();
    let mut text = String::from("// Generated by nanoflash from the board layout. Do not edit.\n");
    let _ = writeln!(
        text,
        "pub const {flash_size}: {kind} = {};",
        literal(layout.flash.size, digits)
    );
    let _ = writeln!(
        text,
        "pub const FLASH_BASE_ADDRESS: {kind} = {};",
        literal(layout.flash.base_address, digits)
    );
    for (partition, address) in layout.partitions.iter().zip(addresses) {
        let name = partition.definition.name.as_str();
        let module = module_name(name);
        if let Some(error) = collision(CONSTANTS_WRITER, &taken, name, &module) {
            return Err(error);
        }
        let _ = writeln!(text, "pub mod {module} {{");
        match (partition.grows_with_flash, partition.moves_with_flash) {
            (true, true) => text.push_str(
                "    // Grows and moves with the flash of the device: MINIMUM_SIZE is its size on the minimum flash, and its offset is only known once the flash is.\n",
            ),
            (true, false) => text.push_str(
                "    // Grows with the flash of the device: MINIMUM_SIZE is its size on the minimum flash.\n",
            ),
            (false, true) => text.push_str(
                "    // Moves with the flash of the device: its offset is only known once the flash is.\n",
            ),
            (false, false) => {}
        }
        if !partition.moves_with_flash {
            let _ = writeln!(
                text,
                "    pub const OFFSET: {kind} = {};",
                literal(partition.offset, digits)
            );
        }
        let size_name = if partition.grows_with_flash {
            "MINIMUM_SIZE"
        } else {
            "SIZE"
        };
        let _ = writeln!(
            text,
            "    pub const {size_name}: {kind} = {};",
            literal(partition.size, digits)
        );
        if !partition.moves_with_flash {
            let _ = writeln!(
                text,
                "    pub const ADDRESS: {kind} = {};",
                literal(address, digits)
            );
        }
        text.push_str("}\n");
        taken.push((module, name.into()));
    }
    Ok(text)
}

/// Refuse a layout resolved for a flash larger than its minimum.
fn at_minimum(layout: &ResolvedLayout, writer: &'static str) -> Result<(), TableError> {
    match layout.minimum_flash_size {
        Some(minimum_flash_size) if minimum_flash_size != layout.flash.size => {
            Err(TableError::NotAtMinimum {
                writer,
                flash_size: layout.flash.size,
                minimum_flash_size,
            })
        }
        _ => Ok(()),
    }
}

fn explicit_region(partition: &ResolvedPartition) -> Option<&str> {
    partition
        .definition
        .linker
        .as_ref()
        .and_then(|attributes| attributes.region.as_deref())
}

/// Whether a linker script can hold `name` as the name of a region: ASCII letters, digits and `_`,
/// and not starting with a digit.
fn valid_region_name(name: &str) -> bool {
    !name.is_empty()
        && !name.starts_with(|character: char| character.is_ascii_digit())
        && name
            .chars()
            .all(|character| character.is_ascii_alphanumeric() || character == '_')
}

/// The error for `identifier` when an earlier partition already turned into it.
fn collision(
    writer: &'static str,
    taken: &[(String, String)],
    name: &str,
    identifier: &str,
) -> Option<TableError> {
    taken
        .iter()
        .find(|(taken_identifier, _)| taken_identifier == identifier)
        .map(|(_, first)| TableError::NameCollision {
            writer,
            first: first.clone(),
            second: name.into(),
            identifier: identifier.into(),
        })
}

fn unknown_value(
    writer: &'static str,
    partition: &str,
    attribute: &'static str,
    value: String,
) -> TableError {
    TableError::UnknownValue {
        writer,
        partition: partition.into(),
        attribute,
        value,
    }
}

fn region_from_name(name: &str) -> String {
    let mut region: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || character == '_' {
                character.to_ascii_uppercase()
            } else {
                '_'
            }
        })
        .collect();
    if region.is_empty() || region.starts_with(|character: char| character.is_ascii_digit()) {
        region.insert(0, '_');
    }
    region
}

fn module_name(name: &str) -> String {
    let lower: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' {
                character
            } else if character.is_ascii_uppercase() {
                character.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    if lower.is_empty() || lower == "_" || lower.starts_with(|c: char| c.is_ascii_digit()) {
        format!("partition_{lower}")
    } else if NOT_RAW.contains(&lower.as_str()) {
        format!("{lower}_partition")
    } else if KEYWORDS.contains(&lower.as_str()) {
        format!("r#{lower}")
    } else {
        lower
    }
}

/// A hexadecimal literal with the digits grouped by four, such as `0x0010_0000`.
fn literal(value: u64, digits: usize) -> String {
    let plain = format!("{value:0digits$X}");
    let mut text = String::from("0x");
    let length = plain.len();
    for (index, digit) in plain.chars().enumerate() {
        if index > 0 && (length - index) % 4 == 0 {
            text.push('_');
        }
        text.push(digit);
    }
    text
}

#[cfg(all(test, feature = "toml"))]
mod tests {
    use super::*;
    use crate::layout::Layout;
    use alloc::string::ToString;
    use std::path::Path;

    fn resolved(text: &str) -> ResolvedLayout {
        Layout::from_toml(text).unwrap().resolve().unwrap()
    }

    fn fixture(name: &str) -> ResolvedLayout {
        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/layouts")
            .join(name);
        resolved(&std::fs::read_to_string(path).unwrap())
    }

    #[test]
    fn nrf52840_memory_regions() {
        let text = memory_regions(&fixture("nrf52840-arduino.toml")).unwrap();
        assert_eq!(
            text,
            "/* Generated by nanoflash from the board layout. Do not edit. */\n\
MEMORY\n{\n\
\x20 BOOTLOADER : ORIGIN = 0x00000000, LENGTH = 0x00010000\n\
\x20 FLASH : ORIGIN = 0x00010000, LENGTH = 0x000E0000\n\
\x20 STORAGE : ORIGIN = 0x000F0000, LENGTH = 0x00010000\n\
}\n"
        );
    }

    #[test]
    fn nrf52840_constants() {
        let text = rust_constants(&fixture("nrf52840-arduino.toml")).unwrap();
        assert_eq!(
            text,
            "// Generated by nanoflash from the board layout. Do not edit.\n\
pub const FLASH_SIZE: u32 = 0x0010_0000;\n\
pub const FLASH_BASE_ADDRESS: u32 = 0x0000_0000;\n\
pub mod bootloader {\n\
\x20   pub const OFFSET: u32 = 0x0000_0000;\n\
\x20   pub const SIZE: u32 = 0x0001_0000;\n\
\x20   pub const ADDRESS: u32 = 0x0000_0000;\n\
}\n\
pub mod application {\n\
\x20   pub const OFFSET: u32 = 0x0001_0000;\n\
\x20   pub const SIZE: u32 = 0x000E_0000;\n\
\x20   pub const ADDRESS: u32 = 0x0001_0000;\n\
}\n\
pub mod storage {\n\
\x20   pub const OFFSET: u32 = 0x000F_0000;\n\
\x20   pub const SIZE: u32 = 0x0001_0000;\n\
\x20   pub const ADDRESS: u32 = 0x000F_0000;\n\
}\n"
        );
    }

    #[test]
    fn growing_constants() {
        assert_eq!(
            rust_constants(&fixture("growing.toml")).unwrap(),
            "// Generated by nanoflash from the board layout. Do not edit.\n\
pub const FLASH_MINIMUM_SIZE: u32 = 0x0008_0000;\n\
pub const FLASH_BASE_ADDRESS: u32 = 0x0000_0000;\n\
pub mod bootloader {\n    pub const OFFSET: u32 = 0x0000_0000;\n    pub const SIZE: u32 = 0x0001_0000;\n    pub const ADDRESS: u32 = 0x0000_0000;\n}\n\
pub mod application {\n    pub const OFFSET: u32 = 0x0001_0000;\n    pub const SIZE: u32 = 0x0004_0000;\n    pub const ADDRESS: u32 = 0x0001_0000;\n}\n\
pub mod storage {\n    // Grows with the flash of the device: MINIMUM_SIZE is its size on the minimum flash.\n    pub const OFFSET: u32 = 0x0005_0000;\n    pub const MINIMUM_SIZE: u32 = 0x0002_F000;\n    pub const ADDRESS: u32 = 0x0005_0000;\n}\n\
pub mod log {\n    // Moves with the flash of the device: its offset is only known once the flash is.\n    pub const SIZE: u32 = 0x0000_1000;\n}\n"
        );
    }

    #[test]
    fn growing_memory_regions() {
        assert_eq!(
            memory_regions(&fixture("growing.toml")).unwrap(),
            "/* Generated by nanoflash from the board layout. Do not edit. */\nMEMORY\n{\n\
\x20 BOOTLOADER : ORIGIN = 0x00000000, LENGTH = 0x00010000\n\
\x20 FLASH : ORIGIN = 0x00010000, LENGTH = 0x00040000\n\
\x20 /* STORAGE grows with the flash of the device: LENGTH is its size on the minimum flash. */\n\
\x20 STORAGE : ORIGIN = 0x00050000, LENGTH = 0x0002F000\n\
\x20 /* LOG moves with the flash of the device: no region. */\n}\n"
        );
    }

    #[test]
    fn memory_script_adds_regions() {
        let layout = fixture("nrf52840-arduino.toml");
        let regions = [MemoryRegion {
            name: "RAM".into(),
            origin: 0x2000_0000,
            length: 0x40000,
        }];
        let text = memory_script(&layout, &regions).unwrap();
        let mut expected = memory_regions(&layout).unwrap();
        expected.truncate(expected.len() - "}\n".len());
        expected.push_str("\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}\n");
        assert_eq!(text, expected);
        assert_eq!(
            memory_script(&layout, &[]).unwrap(),
            memory_regions(&layout).unwrap()
        );
    }

    #[test]
    fn memory_script_refuses_a_duplicate() {
        let layout = fixture("nrf52840-arduino.toml");
        let regions = [MemoryRegion {
            name: "FLASH".into(),
            origin: 0x2000_0000,
            length: 0x40000,
        }];
        let error = memory_script(&layout, &regions).unwrap_err();
        assert_eq!(
            error,
            TableError::DuplicateRegion {
                name: "FLASH".into()
            }
        );
        assert_eq!(
            error.to_string(),
            "the region FLASH is both a partition of the layout and a memory region given to the build: rename one"
        );
    }

    #[test]
    fn memory_script_refuses_a_region_name_the_linker_cannot_read() {
        let layout = fixture("nrf52840-arduino.toml");
        for name in ["", "2RAM", "RA M", "RAM:", "RAM\n}", "R\u{c4}M"] {
            let regions = [MemoryRegion {
                name: name.into(),
                origin: 0x2000_0000,
                length: 0x40000,
            }];
            let error = memory_script(&layout, &regions).unwrap_err();
            assert_eq!(
                error,
                TableError::InvalidRegionName { name: name.into() },
                "{name:?}"
            );
        }
        let error = memory_script(
            &layout,
            &[MemoryRegion {
                name: "RA M".into(),
                origin: 0,
                length: 1,
            }],
        )
        .unwrap_err();
        assert_eq!(
            error.to_string(),
            "the memory region \"RA M\" given to the build has a name that the linker cannot read: use ASCII letters, digits and _, and do not start with a digit"
        );
    }

    #[test]
    fn memory_script_refuses_a_region_given_twice() {
        let layout = fixture("nrf52840-arduino.toml");
        let region = |origin| MemoryRegion {
            name: "RAM".into(),
            origin,
            length: 0x1000,
        };
        let error =
            memory_script(&layout, &[region(0x2000_0000), region(0x3000_0000)]).unwrap_err();
        assert_eq!(error, TableError::RepeatedRegion { name: "RAM".into() });
        assert_eq!(
            error.to_string(),
            "the memory region RAM is given to the build more than once: give each region once"
        );
    }

    const GROW_AND_MOVE: &str = "[flash]\nsize = \"detect\"\nminimum = \"1 MiB\"\nbase-address = 0x0\n\n\
[[partition]]\nname = \"bootloader\"\nrole = \"bootloader\"\noffset = 0x0\nsize = \"64 KiB\"\n\n\
[[partition]]\nname = \"data\"\nrole = \"custom\"\nsize = { minimum = \"64 KiB\", grow = 1 }\n\n\
[[partition]]\nname = \"storage\"\nrole = \"storage\"\nsize = { minimum = \"64 KiB\", grow = 1 }\n";

    #[test]
    fn a_partition_that_grows_and_moves_gets_neither_offset_nor_region() {
        let layout = resolved(GROW_AND_MOVE);
        let constants = rust_constants(&layout).unwrap();
        assert!(
            constants.contains(
                "pub mod storage {\n    // Grows and moves with the flash of the device: MINIMUM_SIZE is its size on the minimum flash, and its offset is only known once the flash is.\n    pub const MINIMUM_SIZE: u32 = 0x"
            ),
            "{constants}"
        );
        assert!(!constants.contains("pub mod storage {\n    pub const OFFSET"));
        let regions = memory_regions(&layout).unwrap();
        assert!(
            regions.contains(
                "  /* STORAGE grows and moves with the flash of the device: no region. */\n"
            ),
            "{regions}"
        );
        assert!(!regions.contains("STORAGE :"), "{regions}");
    }

    #[test]
    fn writers_refuse_a_layout_resolved_above_its_minimum() {
        let text = std::fs::read_to_string(
            Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/layouts/growing.toml"),
        )
        .unwrap();
        let layout = Layout::from_toml(&text)
            .unwrap()
            .resolve_for(Some(0x100000))
            .unwrap();
        let expected = TableError::NotAtMinimum {
            writer: "constants",
            flash_size: 0x100000,
            minimum_flash_size: 0x80000,
        };
        assert_eq!(rust_constants(&layout).unwrap_err(), expected);
        let error = memory_regions(&layout).unwrap_err();
        assert!(matches!(
            error,
            TableError::NotAtMinimum {
                writer: "linker",
                ..
            }
        ));
        let message = error.to_string();
        assert!(
            message.contains("0x80000") && message.contains("0x100000"),
            "{message}"
        );
    }

    #[test]
    fn identifiers_are_sanitised() {
        let layout = resolved(
            "[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
             [[partition]]\nname = \"nvs-keys\"\nrole = \"storage\"\noffset = 0x0\nsize = 0x1000\n\n\
             [[partition]]\nname = \"2nd\"\nrole = \"storage\"\noffset = 0x1000\nsize = 0x1000\n\n\
             [[partition]]\nname = \"type\"\nrole = \"storage\"\noffset = 0x2000\nsize = 0x1000\n\n\
             [[partition]]\nname = \"self\"\nrole = \"storage\"\noffset = 0x3000\nsize = 0x1000\n",
        );
        let constants = rust_constants(&layout).unwrap();
        for module in ["nvs_keys", "partition_2nd", "r#type", "self_partition"] {
            assert!(
                constants.contains(&std::format!("pub mod {module} {{")),
                "{module}"
            );
        }
        let regions = memory_regions(&layout).unwrap();
        for region in ["NVS_KEYS", "_2ND", "TYPE", "SELF"] {
            assert!(
                regions.contains(&std::format!("  {region} : ORIGIN")),
                "{region}"
            );
        }
    }

    #[test]
    fn identifier_collisions_name_both_partitions() {
        let layout = resolved(
            "[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
             [[partition]]\nname = \"a-b\"\nrole = \"storage\"\noffset = 0x0\nsize = 0x1000\n\n\
             [[partition]]\nname = \"a_b\"\nrole = \"storage\"\noffset = 0x1000\nsize = 0x1000\n",
        );
        for error in [
            rust_constants(&layout).unwrap_err(),
            memory_regions(&layout).unwrap_err(),
        ] {
            assert!(
                matches!(&error, TableError::NameCollision { first, second, .. } if first == "a-b" && second == "a_b"),
                "{error}"
            );
            let message = error.to_string();
            assert!(
                message.contains("\"a-b\"") && message.contains("\"a_b\""),
                "{message}"
            );
        }
    }

    #[test]
    fn several_firmware_partitions_are_refused() {
        let layout = resolved(
            "[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
             [[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x1000\n\n\
             [[partition]]\nname = \"b\"\nrole = \"firmware\"\noffset = 0x1000\nsize = 0x1000\n",
        );
        assert!(matches!(
            memory_regions(&layout),
            Err(TableError::SeveralFirmware { .. })
        ));
    }

    #[test]
    fn explicit_regions_and_wide_values() {
        let layout = resolved(
            "[flash]\nsize = \"1 MiB\"\nbase-address = 0x1_0000_0000\n\n\
             [[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x1000\nlinker = { region = \"RAM_CODE\" }\n",
        );
        assert!(
            memory_regions(&layout)
                .unwrap()
                .contains("  RAM_CODE : ORIGIN = 0x100000000, LENGTH = 0x00001000")
        );
        let constants = rust_constants(&layout).unwrap();
        assert!(constants.contains("pub const FLASH_BASE_ADDRESS: u64 = 0x0000_0001_0000_0000;"));
    }

    #[test]
    fn constants_compile() {
        for (index, text) in [
            rust_constants(&fixture("esp32-s3-8mb.toml")).unwrap(),
            rust_constants(&fixture("growing.toml")).unwrap(),
            rust_constants(&resolved(GROW_AND_MOVE)).unwrap(),
        ]
        .into_iter()
        .enumerate()
        {
            compiles(index, &text);
        }
    }

    fn compiles(index: usize, text: &str) {
        let directory = std::path::Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../target/test-scratch"
        ))
        .join(std::format!(
            "nanoflash-constants-{}-{index}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&directory);
        std::fs::create_dir_all(&directory).unwrap();
        let source = directory.join("constants.rs");
        std::fs::write(&source, text).unwrap();
        let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
        let output = std::process::Command::new(rustc)
            .args([
                "--crate-type",
                "lib",
                "--edition",
                "2024",
                "--emit",
                "metadata",
                "-o",
            ])
            .arg(directory.join("constants.rmeta"))
            .arg(&source)
            .output()
            .unwrap();
        let success = output.status.success();
        let stderr = std::string::String::from_utf8_lossy(&output.stderr).into_owned();
        std::fs::remove_dir_all(&directory).unwrap();
        assert!(success, "{stderr}");
    }
}