Skip to main content

litz_engine/
board.rs

1//! Checking a board bundle before a project depends on it.
2//!
3//! A board manifest is easy to get subtly wrong — a module built against the
4//! other ABI, a schematic that names a pin the header does not have — and the
5//! failure normally appears only when a diagram tries to boot it. This module
6//! answers the same questions `litz run` would, without a project or a
7//! firmware: does the manifest parse, does the module instantiate under the
8//! ABI it names, and does the onboard schematic describe a `$chip`?
9
10use litz_board::chip::Chip;
11use litz_catalog::Registry;
12use std::path::{Path, PathBuf};
13
14/// What a board bundle contains, once it has been checked.
15#[derive(Clone, Debug)]
16pub struct BoardReport {
17    pub id: String,
18    pub name: String,
19    pub version: String,
20    /// The chip backend, when the board names a builtin one.
21    pub chip: Option<String>,
22    /// The ABI and module, when the board carries a component.
23    pub simulator: Option<(String, String)>,
24    /// What the component says it is, when it could be instantiated here.
25    pub module_name: Option<String>,
26    /// The rate the guest counts `run-result.cycles` at.
27    pub cpu_hz: Option<u64>,
28    pub pins: usize,
29    pub wires: usize,
30}
31
32impl BoardReport {
33    pub fn lines(&self) -> String {
34        let mut text = format!("{} {} ({})\n", self.id, self.version, self.name);
35        match (&self.chip, &self.simulator) {
36            (Some(chip), None) => text.push_str(&format!("  chip {chip}: builtin\n")),
37            (None, Some((abi, module))) => {
38                text.push_str(&format!("  module {module} ({abi})\n"));
39                if let Some(name) = &self.module_name {
40                    text.push_str(&format!("  component reports {name}\n"));
41                }
42                if let Some(hz) = self.cpu_hz {
43                    text.push_str(&format!("  cpu {hz} Hz\n"));
44                }
45            }
46            _ => {}
47        }
48        text.push_str(&format!("  header pins {}\n", self.pins));
49        text.push_str(&format!("  schematic wires {}\n", self.wires));
50        text
51    }
52}
53
54/// Check one board directory or manifest.
55///
56/// The path may be a `board.toml` or the directory that holds it. Everything
57/// named by the manifest is resolved relative to the manifest, the same rule
58/// the catalog and the runner use.
59pub fn check(path: &Path) -> Result<BoardReport, String> {
60    let manifest_path = if path.is_dir() {
61        let candidate = path.join("board.toml");
62        if candidate.is_file() {
63            candidate
64        } else {
65            // A distributed bundle may keep its own file name; accept the one
66            // manifest in the directory, but never a simulator's Cargo.toml.
67            let mut found: Vec<PathBuf> = std::fs::read_dir(path)
68                .map_err(|e| format!("{}: {e}", path.display()))?
69                .filter_map(|entry| entry.ok())
70                .map(|entry| entry.path())
71                .filter(|file| {
72                    file.extension()
73                        .is_some_and(|extension| extension == "toml")
74                        && file.file_name().is_none_or(|name| name != "Cargo.toml")
75                })
76                .collect();
77            found.sort();
78            match found.as_slice() {
79                [one] => one.clone(),
80                _ => {
81                    return Err(format!(
82                        "{}: a board directory holds one manifest, `board.toml`",
83                        path.display()
84                    ));
85                }
86            }
87        }
88    } else {
89        path.to_path_buf()
90    };
91    let text = std::fs::read_to_string(&manifest_path)
92        .map_err(|e| format!("{}: {e}", manifest_path.display()))?;
93    let mut registry = Registry::builtin();
94    let id = registry
95        .insert_text(&text)
96        .map_err(|e| format!("{}: {e}", manifest_path.display()))?;
97    let manifest = registry
98        .get(&id)
99        .ok_or_else(|| format!("{}: the manifest did not load", manifest_path.display()))?
100        .clone();
101    let info = manifest.board.as_ref().ok_or_else(|| {
102        format!(
103            "{}: this is a part manifest, not a board",
104            manifest_path.display()
105        )
106    })?;
107    let dir = manifest_path
108        .parent()
109        .map(Path::to_path_buf)
110        .unwrap_or_else(|| PathBuf::from("."));
111
112    if let Some(chip) = &info.chip
113        && !crate::runner::is_builtin_chip(chip)
114    {
115        return Err(format!(
116            "{}: chip {chip:?} is not built in; name a wasm component under \
117             [board.simulator] instead",
118            manifest_path.display()
119        ));
120    }
121
122    let mut wires = 0;
123    if let Some(schematic) = &info.schematic {
124        let path = dir.join(schematic);
125        let text =
126            std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
127        let circuit = litz_diagram::Circuit::from_json(&text)
128            .map_err(|e| format!("{}: {e}", path.display()))?;
129        if !circuit.parts.iter().any(|part| part.type_key == "$chip") {
130            return Err(format!(
131                "{}: the onboard schematic has no `$chip` part",
132                path.display()
133            ));
134        }
135        wires = circuit.connections.len();
136    }
137
138    let mut module_name = None;
139    let mut cpu_hz = None;
140    if let Some(simulator) = &info.simulator {
141        let module = dir.join(&simulator.module);
142        let bytes = std::fs::read(&module).map_err(|e| format!("{}: {e}", module.display()))?;
143        let chip =
144            litz_mcu_wasm::WasmChip::from_bytes_with_abi(&bytes, &simulator.module, &simulator.abi)
145                .map_err(|e| {
146                    format!(
147                        "{}: does not instantiate as {}: {e}\n  the guest must be built against                          the WIT that `abi` names; `litz catalog new board` copies it as wit-v2/",
148                        module.display(),
149                        simulator.abi
150                    )
151                })?;
152        module_name = Some(chip.name().to_string());
153        cpu_hz = Some(chip.info().cpu_hz);
154    }
155
156    Ok(BoardReport {
157        id: manifest.id,
158        name: manifest.name,
159        version: manifest.version,
160        chip: info.chip.clone(),
161        simulator: info
162            .simulator
163            .as_ref()
164            .map(|simulator| (simulator.abi.clone(), simulator.module.clone())),
165        module_name,
166        cpu_hz,
167        pins: manifest.pins.len(),
168        wires,
169    })
170}