nanoflash 0.1.1

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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! Generate the constants and the linker scripts of a firmware from its layout file, in `build.rs`.
//!
//! The layout is a file:
//!
//! ```no_run
//! nanoflash::build::generate("layout.toml").unwrap();
//! ```
//!
//! Or it is the layout of the board that `[package.metadata.nanoflash]` of the `Cargo.toml` names
//! (see [`crate::cargo`]). With `memory`, nanoflash also writes the whole `memory.x` that
//! `cortex-m-rt` includes, so the firmware does not keep one:
//!
//! ```no_run
//! nanoflash::build::Build::package()
//!     .memory("RAM", 0x2000_0000, 256 * 1024)
//!     .generate()
//!     .unwrap();
//! ```

use crate::cargo::{PackageError, layout_of, read_board, workspace_root};
use crate::layout::{Layout, LayoutErrors, ParseError};
use crate::manifest::Manifest;
use crate::table::TableError;
use crate::table::linker::{MemoryRegion, memory_regions, memory_script, rust_constants};
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use std::path::{Path, PathBuf};

/// The file of Rust constants, written to the output directory.
const CONSTANTS_FILE: &str = "nanoflash_layout.rs";
/// The file of linker regions, written to the output directory.
const LINKER_FILE: &str = "nanoflash_memory.x";
/// The whole linker script that `cortex-m-rt` includes, written when `memory` was called. The
/// linker looks for it by this name.
const MEMORY_FILE: &str = "memory.x";
/// The linker script of the guard, written when `memory` was called.
const GUARD_FILE: &str = "nanoflash_memory_guard.x";
/// The symbol that the `memory.x` of nanoflash defines. The guard asserts that it is 1.
const MEMORY_MARKER: &str = "__nanoflash_memory_x";

/// The files written by [`Build::generate`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Generated {
    /// The Rust constants, to `include!` from the firmware.
    pub constants: PathBuf,
    /// The linker script that declares the memory regions of the layout, for a `memory.x` that
    /// includes it.
    pub linker_script: PathBuf,
    /// The whole `memory.x`, written when [`Build::memory`] was called: the regions of the layout
    /// and the regions given.
    pub memory_script: Option<PathBuf>,
    /// The guard, written with the whole `memory.x`: a linker script that fails the link when
    /// another `memory.x` was linked instead.
    pub memory_guard: Option<PathBuf>,
    /// The files that the output comes from: the layout and, for a package, its `Cargo.toml` and
    /// its board manifest. [`Build::generate`] prints `cargo:rerun-if-changed` for each of them.
    pub inputs: Vec<PathBuf>,
}

/// Why the files could not be generated.
///
/// `Debug` prints the same text as `Display`, so a build script that unwraps the error, or returns
/// it from `main`, shows the message of `nanoflash layout check`.
pub enum BuildError {
    /// A file could not be read or written.
    Io {
        /// The file or directory.
        path: PathBuf,
        /// The cause.
        error: std::io::Error,
    },
    /// The layout file is not valid.
    Parse(ParseError),
    /// The layout has errors.
    Layout(LayoutErrors),
    /// A writer cannot express the layout.
    Table(TableError),
    /// Cargo did not set `OUT_DIR`, so this was not called from a build script.
    MissingOutputDirectory,
    /// Cargo did not set `CARGO_MANIFEST_DIR`, so the package is not known.
    MissingPackageDirectory,
    /// The `Cargo.toml` of the package could not be read.
    Package(PackageError),
    /// The `Cargo.toml` of the package names no board.
    NoBoard {
        /// The `Cargo.toml`.
        cargo_toml: PathBuf,
    },
    /// The board manifest of the package cannot give a layout.
    Manifest {
        /// The board manifest.
        path: PathBuf,
        /// What is wrong.
        message: String,
    },
    /// A `memory.x` in the package directory or in the workspace root would be linked instead of
    /// the one nanoflash writes.
    MemoryScriptShadowed {
        /// The `memory.x` in the package directory or in the workspace root.
        path: PathBuf,
    },
}

impl fmt::Display for BuildError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BuildError::Io { path, error } => {
                write!(formatter, "cannot access {}: {error}", path.display())
            }
            BuildError::Parse(error) => write!(formatter, "cannot read the layout: {error}"),
            BuildError::Layout(error) => write!(formatter, "{error}"),
            BuildError::Table(error) => write!(formatter, "{error}"),
            BuildError::MissingOutputDirectory => formatter.write_str(
                "the OUT_DIR environment variable is not set, call this from a build script",
            ),
            BuildError::MissingPackageDirectory => formatter.write_str(
                "the CARGO_MANIFEST_DIR environment variable is not set, call this from a build script",
            ),
            BuildError::Package(error) => write!(formatter, "{error}"),
            BuildError::NoBoard { cargo_toml } => write!(
                formatter,
                "{} names no board: add [package.metadata.nanoflash] board = \"boards/board.toml\", or call Build::layout with the layout file",
                cargo_toml.display()
            ),
            BuildError::Manifest { path, message } => write!(
                formatter,
                "cannot use the board manifest {}: {message}",
                path.display()
            ),
            BuildError::MemoryScriptShadowed { path } => write!(
                formatter,
                "{} would be linked instead of the memory.x nanoflash writes, since the linker looks first in its working directory, which is the workspace root of the package, or its package directory without a workspace: remove it, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory",
                path.display()
            ),
        }
    }
}

impl fmt::Debug for BuildError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, formatter)
    }
}

impl std::error::Error for BuildError {}

/// Where the layout comes from.
#[derive(Debug, Clone)]
enum Source {
    /// A layout file.
    Layout(PathBuf),
    /// The board that the metadata of the package names.
    Package,
}

/// What to generate. Start with [`Build::layout`] or [`Build::package`].
#[derive(Debug, Clone)]
pub struct Build {
    source: Source,
    memory: Vec<MemoryRegion>,
}

impl Build {
    /// Use a layout file. A relative path is relative to the package directory.
    pub fn layout(path: impl AsRef<Path>) -> Build {
        Build {
            source: Source::Layout(path.as_ref().to_path_buf()),
            memory: Vec::new(),
        }
    }

    /// Use the layout of the board that `[package.metadata.nanoflash]` names in the `Cargo.toml`
    /// of the package (the one in `CARGO_MANIFEST_DIR`).
    ///
    /// The board manifest must give one layout: either all its boards use the same layout, or the
    /// metadata names the board with `board-identifier`.
    pub fn package() -> Build {
        Build {
            source: Source::Package,
            memory: Vec::new(),
        }
    }

    /// Add a memory region that is not a partition, such as the RAM of the device, and write the
    /// whole `memory.x` that `cortex-m-rt` includes: the regions of the layout, then the regions
    /// given.
    ///
    /// `memory.x` goes to `OUT_DIR`, which is on the linker search path. The linker looks in its
    /// working directory first. Cargo runs it from the workspace root, or from the package
    /// directory when the package is in no workspace. A `memory.x` in either directory is refused
    /// ([`BuildError::MemoryScriptShadowed`]).
    ///
    /// The check of the package directory and of the workspace root runs when the build script
    /// runs. Cargo reruns the script when a file that it names changes, and the script cannot name
    /// a file that does not exist, so a `memory.x` added later is not noticed by the script. A
    /// second check does not depend on the script: when another `memory.x` was linked, the link
    /// fails and the linker names the symbol `__nanoflash_memory_x` and the script
    /// `nanoflash_memory_guard.x` that checks it.
    ///
    /// A build that does not call `memory` removes the `memory.x` that an earlier build left in
    /// `OUT_DIR`, so it cannot be linked by mistake.
    ///
    /// Call `memory` only when the linker script of the runtime includes `memory.x`, as the
    /// `link.x` of `cortex-m-rt` does. The guard goes to every binary of the package
    /// (`cargo:rustc-link-arg-bins`): a binary that does not link the generated `memory.x`, such
    /// as a binary for the host in the same package, fails to link with
    /// `symbol not found: __nanoflash_memory_x`. Put such a binary in another package.
    pub fn memory(mut self, name: &str, origin: u64, length: u64) -> Build {
        self.memory.push(MemoryRegion {
            name: name.into(),
            origin,
            length,
        });
        self
    }

    /// Generate the files in `OUT_DIR` and tell Cargo to rebuild when an input changes and where
    /// to find the linker scripts.
    ///
    /// When [`Build::memory`] was called, this also prints `cargo:rustc-link-arg-bins` with a
    /// linker script that fails the link unless the `memory.x` of nanoflash was linked. The
    /// `memory.x` defines the symbol `__nanoflash_memory_x` as 1, and the script asserts that.
    ///
    /// Needs `OUT_DIR`, and `CARGO_MANIFEST_DIR` for [`Build::package`]. A relative layout path is
    /// relative to `CARGO_MANIFEST_DIR`, or to the working directory when it is not set.
    pub fn generate(self) -> Result<Generated, BuildError> {
        let output_directory =
            std::env::var_os("OUT_DIR").ok_or(BuildError::MissingOutputDirectory)?;
        let output_directory = PathBuf::from(output_directory);
        let package_directory = match (std::env::var_os("CARGO_MANIFEST_DIR"), &self.source) {
            (Some(directory), _) => PathBuf::from(directory),
            (None, Source::Layout(_)) => PathBuf::new(),
            (None, Source::Package) => return Err(BuildError::MissingPackageDirectory),
        };
        let generated = self.generate_into(&package_directory, &output_directory)?;
        for input in &generated.inputs {
            std::println!("cargo:rerun-if-changed={}", input.display());
        }
        std::println!("cargo:rustc-link-search={}", output_directory.display());
        if let Some(guard) = &generated.memory_guard {
            // Only the binaries, as for the `-Tlink.x` of the firmware: a test of the host does
            // not link `memory.x`. Every binary of the package gets the guard, so a package that
            // calls `memory` cannot also have a binary for the host (see `Build::memory`).
            std::println!("cargo:rustc-link-arg-bins=-T{}", guard.display());
        }
        Ok(generated)
    }

    /// Generate the files in `output_directory`, without the environment and without printing.
    ///
    /// A relative layout path is relative to `package_directory`, the directory of the
    /// `Cargo.toml` that [`Build::package`] reads.
    pub fn generate_into(
        self,
        package_directory: &Path,
        output_directory: &Path,
    ) -> Result<Generated, BuildError> {
        let (layout_path, mut inputs) = match &self.source {
            Source::Layout(path) => (package_directory.join(path), Vec::new()),
            Source::Package => board_layout(package_directory)?,
        };
        let text = std::fs::read_to_string(&layout_path).map_err(|error| BuildError::Io {
            path: layout_path.clone(),
            error,
        })?;
        inputs.push(layout_path);
        let resolved = Layout::from_toml(&text)
            .map_err(BuildError::Parse)?
            .resolve()
            .map_err(BuildError::Layout)?;
        let constants: String = rust_constants(&resolved).map_err(BuildError::Table)?;
        let regions: String = memory_regions(&resolved).map_err(BuildError::Table)?;
        let memory = if self.memory.is_empty() {
            None
        } else {
            // The linker looks in its working directory first. Cargo runs it from the workspace
            // root for a member of a workspace, and from the package directory otherwise. A
            // `memory.x` in the package directory of a member is refused too: it is a leftover
            // of a standalone package that no longer links, and a build tool that does not run
            // from the workspace root would link it.
            let mut directories = alloc::vec![package_directory.to_path_buf()];
            if let Some(root) = workspace_root(&package_directory.join("Cargo.toml"))
                && root != package_directory
            {
                directories.push(root);
            }
            for directory in directories {
                let shadow = directory.join(MEMORY_FILE);
                if shadow.exists() {
                    return Err(BuildError::MemoryScriptShadowed { path: shadow });
                }
            }
            let mut script = memory_script(&resolved, &self.memory).map_err(BuildError::Table)?;
            // The guard of the link checks for this symbol.
            script.push_str(&alloc::format!("{MEMORY_MARKER} = 1;\n"));
            Some(script)
        };

        let generated = Generated {
            constants: output_directory.join(CONSTANTS_FILE),
            linker_script: output_directory.join(LINKER_FILE),
            memory_script: memory.as_ref().map(|_| output_directory.join(MEMORY_FILE)),
            memory_guard: memory.as_ref().map(|_| output_directory.join(GUARD_FILE)),
            inputs,
        };
        let mut files = alloc::vec![
            (&generated.constants, constants),
            (&generated.linker_script, regions),
        ];
        let guard = guard_script();
        if let (Some(path), Some(contents)) = (&generated.memory_script, memory) {
            files.push((path, contents));
        }
        if let Some(path) = &generated.memory_guard {
            files.push((path, guard));
        }
        for (path, contents) in files {
            std::fs::write(path, contents).map_err(|error| BuildError::Io {
                path: path.clone(),
                error,
            })?;
        }
        if generated.memory_script.is_none() {
            // `OUT_DIR` persists between builds. A `memory.x` of an earlier build, made when
            // `memory` was called, would stay on the linker search path.
            for name in [MEMORY_FILE, GUARD_FILE] {
                let stale = output_directory.join(name);
                match std::fs::remove_file(&stale) {
                    Ok(()) => {}
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                    Err(error) => return Err(BuildError::Io { path: stale, error }),
                }
            }
        }
        Ok(generated)
    }
}

/// The linker script that fails the link when the `memory.x` of nanoflash was not linked.
///
/// Cargo reruns a build script only when a file that it names changed. A `memory.x` that appears
/// later in the package directory or in the workspace root does not rerun it, so the build-time
/// check misses it. The linker checks this script on every link.
///
/// The assertion reads the marker. It does not test `DEFINED(marker)`: rust-lld evaluates
/// `DEFINED` in the order of the scripts on the command line, so it reports a marker that a later
/// script defines as not defined, and the build script of a firmware prints `-Tlink.x` after
/// `generate`. A read of the marker is the same in every order. When another `memory.x` was
/// linked, the marker does not exist, and both rust-lld and GNU ld report the symbol and the line
/// of this script instead of the message of the assertion.
fn guard_script() -> String {
    alloc::format!(
        "/* Generated by nanoflash. Do not edit.\n\
        \x20  The memory.x that nanoflash writes defines the symbol {MEMORY_MARKER}. If the linker\n\
        \x20  reports that this symbol is not found, it linked another memory.x: the one in the\n\
        \x20  package directory or in the workspace root. Remove it. */\n\
        ASSERT({MEMORY_MARKER} == 1, \"the memory.x that nanoflash writes was not linked, since another memory.x was found first: remove the memory.x in the package directory or in the workspace root, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory\");\n"
    )
}

/// The layout file of the board of the package in `package_directory`, and the files read to find
/// it: the `Cargo.toml`, which names the board, and the board manifest.
fn board_layout(package_directory: &Path) -> Result<(PathBuf, Vec<PathBuf>), BuildError> {
    let cargo_toml = package_directory.join("Cargo.toml");
    let board = read_board(&cargo_toml)
        .map_err(BuildError::Package)?
        .ok_or_else(|| BuildError::NoBoard {
            cargo_toml: cargo_toml.clone(),
        })?;
    let manifest_error = |message: String| BuildError::Manifest {
        path: board.board.clone(),
        message,
    };
    let text = std::fs::read_to_string(&board.board).map_err(|error| BuildError::Io {
        path: board.board.clone(),
        error,
    })?;
    // The format comes from the content, as for the `nanoflash` command, not from the extension.
    let manifest =
        Manifest::parse(&text).map_err(|error| manifest_error(alloc::format!("{error}")))?;
    let layout = layout_of(&manifest, board.board_identifier.as_deref()).map_err(manifest_error)?;
    let directory = board.board.parent().unwrap_or_else(|| Path::new(""));
    Ok((
        directory.join(layout),
        alloc::vec![cargo_toml, board.board.clone()],
    ))
}

/// Generate the files in `OUT_DIR` and tell Cargo to rebuild when the layout changes and where
/// to find the linker script. The same as `Build::layout(layout_path).generate()`.
pub fn generate(layout_path: impl AsRef<Path>) -> Result<Generated, BuildError> {
    Build::layout(layout_path).generate()
}

/// Generate `nanoflash_layout.rs` and `nanoflash_memory.x` in a directory.
pub fn generate_into(layout_path: &Path, output_directory: &Path) -> Result<Generated, BuildError> {
    Build::layout(layout_path).generate_into(Path::new(""), output_directory)
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use std::fs;

    fn scratch(name: &str) -> PathBuf {
        let directory = Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../target/test-scratch"
        ))
        .join(std::format!("nanoflash-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&directory);
        fs::create_dir_all(&directory).unwrap();
        directory
    }

    fn fixture(name: &str) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/layouts")
            .join(name)
    }

    #[test]
    fn generate_into_writes_both_files() {
        let directory = scratch("both");
        let generated = generate_into(&fixture("nrf52840-arduino.toml"), &directory).unwrap();
        let resolved =
            Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
                .unwrap()
                .resolve()
                .unwrap();
        assert_eq!(
            fs::read_to_string(&generated.constants).unwrap(),
            rust_constants(&resolved).unwrap()
        );
        assert_eq!(
            fs::read_to_string(&generated.linker_script).unwrap(),
            memory_regions(&resolved).unwrap()
        );
        fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn generate_into_writes_minimum_sizes() {
        let directory = scratch("minimum");
        let generated = generate_into(&fixture("growing.toml"), &directory).unwrap();
        let constants = fs::read_to_string(&generated.constants).unwrap();
        assert!(constants.contains("MINIMUM_SIZE"), "{constants}");
        assert!(constants.contains("FLASH_MINIMUM_SIZE"), "{constants}");
        assert!(!constants.contains("FLASH_SIZE: "), "{constants}");
        fs::remove_dir_all(&directory).unwrap();
    }

    #[test]
    fn generate_reports_layout_errors() {
        let directory = scratch("overlap");
        let layout = directory.join("layout.toml");
        fs::write(
            &layout,
            "[flash]\nsize = \"1 MiB\"\nbase-address = 0x0\n\n\
             [[partition]]\nname = \"a\"\nrole = \"firmware\"\noffset = 0x0\nsize = 0x20000\n\n\
             [[partition]]\nname = \"b\"\nrole = \"storage\"\noffset = 0x10000\nsize = 0x10000\n",
        )
        .unwrap();
        let error = generate_into(&layout, &directory).unwrap_err();
        assert!(matches!(error, BuildError::Layout(_)));
        assert!(error.to_string().contains("overlap"), "{error}");
        let debug = std::format!("{error:?}");
        assert!(debug.contains("overlap") && debug.contains("0x"), "{debug}");
        assert_eq!(debug, error.to_string());
        fs::remove_dir_all(&directory).unwrap();
    }

    /// A package directory with a `Cargo.toml` that names `boards/b.toml`, whose boards are given,
    /// and the layouts `layouts/a.toml` (the nrf52840 fixture) and `layouts/b.toml` (`growing`).
    fn package(name: &str, metadata: &str, boards: &[(&str, &str)]) -> PathBuf {
        let directory = scratch(name);
        fs::create_dir_all(directory.join("boards")).unwrap();
        fs::create_dir_all(directory.join("layouts")).unwrap();
        fs::write(
            directory.join("Cargo.toml"),
            std::format!("[package]\nname = \"firmware\"\n\n{metadata}"),
        )
        .unwrap();
        let mut manifest = String::new();
        for (identifier, layout) in boards {
            manifest.push_str(&std::format!(
                "[[board]]\nidentifier = \"{identifier}\"\nprotocol = \"espressif\"\nchip = \"esp32\"\nlayout = \"../layouts/{layout}\"\n"
            ));
        }
        fs::write(directory.join("boards/b.toml"), manifest).unwrap();
        for (target, source) in [
            ("a.toml", "nrf52840-arduino.toml"),
            ("b.toml", "growing.toml"),
        ] {
            fs::copy(fixture(source), directory.join("layouts").join(target)).unwrap();
        }
        directory
    }

    const BOARD: &str = "[package.metadata.nanoflash]\nboard = \"boards/b.toml\"\n";

    fn nrf52840_regions() -> String {
        memory_regions(
            &Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
                .unwrap()
                .resolve()
                .unwrap(),
        )
        .unwrap()
    }

    #[test]
    fn package_layout_is_used() {
        let directory = package("package", BOARD, &[("b", "a.toml")]);
        let output = scratch("package-output");
        let generated = Build::package().generate_into(&directory, &output).unwrap();
        let resolved =
            Layout::from_toml(&fs::read_to_string(fixture("nrf52840-arduino.toml")).unwrap())
                .unwrap()
                .resolve()
                .unwrap();
        assert_eq!(
            fs::read_to_string(&generated.constants).unwrap(),
            rust_constants(&resolved).unwrap()
        );
        assert_eq!(generated.memory_script, None);
        assert_eq!(
            generated.inputs,
            [
                directory.join("Cargo.toml"),
                directory.join("boards/b.toml"),
                directory.join("boards/../layouts/a.toml")
            ]
        );
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn layout_inputs_are_the_layout() {
        let output = scratch("layout-inputs");
        let generated = Build::layout(fixture("nrf52840-arduino.toml"))
            .generate_into(Path::new("unused"), &output)
            .unwrap();
        assert_eq!(generated.inputs, [fixture("nrf52840-arduino.toml")]);
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn memory_writes_memory_x() {
        let output = scratch("memory");
        let generated = Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap();
        let path = output.join("memory.x");
        assert_eq!(generated.memory_script, Some(path.clone()));
        let mut expected = nrf52840_regions();
        expected.truncate(expected.len() - 2);
        expected.push_str("\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}\n");
        expected.push_str(&std::format!("{MEMORY_MARKER} = 1;\n"));
        assert_eq!(fs::read_to_string(path).unwrap(), expected);
        assert_eq!(
            fs::read_to_string(&generated.linker_script).unwrap(),
            nrf52840_regions()
        );
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn memory_writes_a_guard_that_needs_the_marker() {
        let output = scratch("guard");
        let generated = Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap();
        let path = output.join("nanoflash_memory_guard.x");
        assert_eq!(generated.memory_guard, Some(path.clone()));
        let guard = fs::read_to_string(path).unwrap();
        assert!(
            guard.contains(&std::format!("ASSERT({MEMORY_MARKER} == 1, \"")),
            "{guard}"
        );
        // The linker reports a missing symbol with the file and the line, not the message of the
        // assertion. The comment explains the symbol to the reader of the file.
        assert!(guard.contains("not found"), "{guard}");
        for name in ["memory.x", "package directory", "workspace root"] {
            assert!(guard.contains(name), "{name}: {guard}");
        }
        // The message is a string of the linker script: it has no quote of its own.
        assert_eq!(guard.matches('"').count(), 2, "{guard}");
        // The guard does not use `DEFINED`: rust-lld evaluates it in the order of the scripts on
        // the command line, so it fails when the guard comes before `link.x`.
        assert!(!guard.contains("DEFINED"), "{guard}");
        let memory = fs::read_to_string(output.join("memory.x")).unwrap();
        assert!(
            memory.contains(&std::format!("{MEMORY_MARKER} = 1;")),
            "{memory}"
        );
        // The marker is not in the regions that a `memory.x` of the firmware includes.
        let regions = fs::read_to_string(&generated.linker_script).unwrap();
        assert!(!regions.contains(MEMORY_MARKER), "{regions}");
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn no_guard_without_memory_and_a_stale_guard_is_removed() {
        let output = scratch("guard-stale");
        Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap();
        assert!(output.join("nanoflash_memory_guard.x").exists());
        let generated = Build::layout(fixture("nrf52840-arduino.toml"))
            .generate_into(Path::new(""), &output)
            .unwrap();
        assert_eq!(generated.memory_guard, None);
        assert!(!output.join("nanoflash_memory_guard.x").exists());
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn memory_naming_a_region_of_the_layout_is_refused() {
        let output = scratch("memory-duplicate");
        let error = Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("FLASH", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap_err();
        assert!(matches!(
            error,
            BuildError::Table(TableError::DuplicateRegion { .. })
        ));
        assert!(error.to_string().contains("FLASH"), "{error}");
        assert!(!output.join("memory.x").exists());
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn memory_x_in_the_package_is_refused() {
        let directory = package("shadow", BOARD, &[("b", "a.toml")]);
        let shadow = directory.join("memory.x");
        fs::write(&shadow, "INCLUDE nanoflash_memory.x\n").unwrap();
        let output = scratch("shadow-output");
        let error = Build::package()
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(&directory, &output)
            .unwrap_err();
        assert!(matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == shadow));
        assert_eq!(
            error.to_string(),
            std::format!(
                "{} would be linked instead of the memory.x nanoflash writes, since the linker looks first in its working directory, which is the workspace root of the package, or its package directory without a workspace: remove it, or keep it with INCLUDE nanoflash_memory.x and do not call Build::memory",
                shadow.display()
            )
        );
        assert!(!output.join("memory.x").exists());
        let generated = Build::package().generate_into(&directory, &output).unwrap();
        assert_eq!(generated.memory_script, None);
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    /// A workspace root in a scratch directory, with the package `firmware` as its member.
    fn workspace(name: &str) -> (PathBuf, PathBuf) {
        let root = scratch(name);
        fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"firmware\"]\n",
        )
        .unwrap();
        let member = root.join("firmware");
        fs::create_dir_all(member.join("boards")).unwrap();
        fs::create_dir_all(member.join("layouts")).unwrap();
        fs::write(
            member.join("Cargo.toml"),
            std::format!("[package]\nname = \"firmware\"\n\n{BOARD}"),
        )
        .unwrap();
        fs::write(
            member.join("boards/b.toml"),
            "[[board]]\nidentifier = \"b\"\nprotocol = \"espressif\"\nchip = \"esp32\"\nlayout = \"../layouts/a.toml\"\n",
        )
        .unwrap();
        fs::copy(
            fixture("nrf52840-arduino.toml"),
            member.join("layouts/a.toml"),
        )
        .unwrap();
        (root, member)
    }

    #[test]
    fn memory_x_in_the_workspace_root_is_refused() {
        let (root, member) = workspace("workspace-shadow");
        let shadow = root.join("memory.x");
        fs::write(&shadow, "MEMORY { FLASH : ORIGIN = 0, LENGTH = 1 }\n").unwrap();
        let output = scratch("workspace-shadow-output");
        let error = Build::package()
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(&member, &output)
            .unwrap_err();
        assert!(matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == shadow));
        assert!(!output.join("memory.x").exists());
        // Without `memory`, nothing is written to the output that could be shadowed.
        Build::package().generate_into(&member, &output).unwrap();
        // The package directory of the member is refused too.
        fs::remove_file(&shadow).unwrap();
        let member_shadow = member.join("memory.x");
        fs::write(&member_shadow, "INCLUDE nanoflash_memory.x\n").unwrap();
        let error = Build::package()
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(&member, &output)
            .unwrap_err();
        assert!(
            matches!(&error, BuildError::MemoryScriptShadowed { path } if *path == member_shadow)
        );
        fs::remove_file(&member_shadow).unwrap();
        Build::package()
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(&member, &output)
            .unwrap();
        assert!(output.join("memory.x").exists());
        fs::remove_dir_all(&root).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn a_stale_memory_x_is_removed_when_memory_is_not_called() {
        let output = scratch("stale");
        Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap();
        assert!(output.join("memory.x").exists());
        let generated = Build::layout(fixture("nrf52840-arduino.toml"))
            .generate_into(Path::new(""), &output)
            .unwrap();
        assert_eq!(generated.memory_script, None);
        assert!(!output.join("memory.x").exists());
        // Without a file to remove, nothing fails.
        Build::layout(fixture("nrf52840-arduino.toml"))
            .generate_into(Path::new(""), &output)
            .unwrap();
        // An error before the first write leaves the file as it was.
        Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap();
        let error = Build::layout(fixture("nrf52840-arduino.toml"))
            .memory("FLASH", 0x2000_0000, 0x40000)
            .generate_into(Path::new(""), &output)
            .unwrap_err();
        assert!(matches!(error, BuildError::Table(_)), "{error}");
        assert!(output.join("memory.x").exists());
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn the_format_of_the_board_manifest_is_read_from_its_content() {
        // The nanoflash command decides in the same way: JSON when the text starts with `{`.
        let json = "{\"board\": [{\"identifier\": \"b\", \"protocol\": \"espressif\", \"chip\": \"esp32\", \"layout\": \"../layouts/a.toml\"}]}";
        for name in ["b.JSON", "b.json", "b.manifest"] {
            let directory = package(
                "manifest-format",
                &std::format!("[package.metadata.nanoflash]\nboard = \"boards/{name}\"\n"),
                &[("b", "a.toml")],
            );
            fs::write(directory.join("boards").join(name), json).unwrap();
            let output = scratch("manifest-format-output");
            let generated = Build::package().generate_into(&directory, &output);
            assert!(generated.is_ok(), "{name}: {generated:?}");
            fs::remove_dir_all(&directory).unwrap();
            fs::remove_dir_all(&output).unwrap();
        }
    }

    #[test]
    fn package_without_a_board() {
        let directory = package("no-board", "", &[("b", "a.toml")]);
        let output = scratch("no-board-output");
        let error = Build::package()
            .generate_into(&directory, &output)
            .unwrap_err();
        let cargo_toml = directory.join("Cargo.toml");
        assert!(matches!(&error, BuildError::NoBoard { cargo_toml: path } if *path == cargo_toml));
        assert_eq!(
            error.to_string(),
            std::format!(
                "{} names no board: add [package.metadata.nanoflash] board = \"boards/board.toml\", or call Build::layout with the layout file",
                cargo_toml.display()
            )
        );
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn package_with_bad_metadata_or_a_missing_manifest() {
        let directory = package(
            "bad-metadata",
            "[package.metadata.nanoflash]\nport = \"x\"\n",
            &[("b", "a.toml")],
        );
        let output = scratch("bad-metadata-output");
        let error = Build::package()
            .generate_into(&directory, &output)
            .unwrap_err();
        assert!(matches!(error, BuildError::Package(_)), "{error}");
        assert!(error.to_string().contains("unknown key"), "{error}");
        fs::remove_file(directory.join("boards/b.toml")).unwrap();
        fs::write(
            directory.join("Cargo.toml"),
            std::format!("[package]\nname = \"firmware\"\n\n{BOARD}"),
        )
        .unwrap();
        let error = Build::package()
            .generate_into(&directory, &output)
            .unwrap_err();
        assert!(matches!(error, BuildError::Io { .. }), "{error}");
        fs::write(directory.join("boards/b.toml"), "not toml = [").unwrap();
        let error = Build::package()
            .generate_into(&directory, &output)
            .unwrap_err();
        assert!(matches!(error, BuildError::Manifest { .. }), "{error}");
        assert!(
            error.to_string().starts_with(&std::format!(
                "cannot use the board manifest {}: ",
                directory.join("boards/b.toml").display()
            )),
            "{error}"
        );
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn several_layouts_need_an_identifier() {
        let directory = package("several", BOARD, &[("one", "a.toml"), ("two", "b.toml")]);
        let output = scratch("several-output");
        let error = Build::package()
            .generate_into(&directory, &output)
            .unwrap_err();
        assert!(matches!(&error, BuildError::Manifest { .. }), "{error}");
        let message = error.to_string();
        assert!(
            message.contains("\"one\"") && message.contains("\"two\""),
            "{message}"
        );
        assert!(message.contains("board-identifier"), "{message}");

        fs::write(
            directory.join("Cargo.toml"),
            "[package]\nname = \"firmware\"\n\n[package.metadata.nanoflash]\nboard = \"boards/b.toml\"\nboard-identifier = \"two\"\n",
        )
        .unwrap();
        let generated = Build::package().generate_into(&directory, &output).unwrap();
        assert!(
            fs::read_to_string(&generated.constants)
                .unwrap()
                .contains("FLASH_MINIMUM_SIZE")
        );
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }

    #[test]
    fn growing_layouts_keep_their_rules() {
        let directory = package("growing", BOARD, &[("b", "b.toml")]);
        let output = scratch("growing-output");
        let generated = Build::package()
            .memory("RAM", 0x2000_0000, 0x40000)
            .generate_into(&directory, &output)
            .unwrap();
        let text = fs::read_to_string(generated.memory_script.unwrap()).unwrap();
        assert!(
            text.contains(
                "\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"
            ),
            "{text}"
        );
        assert!(
            text.contains("/* LOG moves with the flash of the device: no region. */"),
            "{text}"
        );
        assert!(!text.contains("LOG :"), "{text}");
        assert!(
            text.ends_with(&std::format!(
                "\x20 RAM : ORIGIN = 0x20000000, LENGTH = 0x00040000\n}}\n{MEMORY_MARKER} = 1;\n"
            )),
            "{text}"
        );
        fs::remove_dir_all(&directory).unwrap();
        fs::remove_dir_all(&output).unwrap();
    }
}