Skip to main content

litz_engine/
python.rs

1//! The Python runtimes a firmware can speak, and the staging text pasted into
2//! their REPLs.
3//!
4//! A board configured with a Python runtime boots a stock interpreter instead
5//! of the project's own application. The runner never imports or executes the
6//! guest's Python itself: it waits for the REPL prompt, sends the raw-REPL
7//! control bytes and pastes a program, so everything here is pure bytes and
8//! strings. Keeping it separate from the run loop is what makes the
9//! handshake testable without booting a chip.
10//!
11//! MicroPython and CircuitPython share the friendly-REPL prompt and the raw
12//! paste framing. They differ in the file the interpreter runs on boot —
13//! CircuitPython looks for `code.py`, MicroPython for `main.py` — and in
14//! whether a program may already be running when the paste arrives.
15
16use crate::config::Runtime;
17
18/// The friendly-REPL prompt both runtimes print. It is the only sign the
19/// interpreter is ready; matching a banner would tie the runner to one build's
20/// wording.
21pub const REPL_PROMPT: &str = ">>> ";
22
23/// Which interpreter a board's console speaks.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum PythonRuntime {
26    MicroPython,
27    CircuitPython,
28}
29
30impl PythonRuntime {
31    /// The bytes that interrupt a running program, if the runtime can be
32    /// running one. CircuitPython starts `code.py` itself, so its REPL is busy
33    /// until Ctrl-C is sent; a stock MicroPython boot lands at the prompt with
34    /// nothing to interrupt.
35    pub fn interrupt_sequence(self) -> &'static [u8] {
36        match self {
37            PythonRuntime::MicroPython => &[],
38            PythonRuntime::CircuitPython => &[0x03],
39        }
40    }
41
42    /// The entry file the runtime executes on boot.
43    pub fn entry_name(self) -> &'static str {
44        match self {
45            PythonRuntime::MicroPython => "main.py",
46            PythonRuntime::CircuitPython => "code.py",
47        }
48    }
49
50    /// The entry names the runtime accepts, in preference order.
51    ///
52    /// CircuitPython falls back to `main.py` when a project stages that name
53    /// instead, so a project choosing the MicroPython convention still runs.
54    pub fn entry_candidates(self) -> &'static [&'static str] {
55        match self {
56            PythonRuntime::MicroPython => &["main.py"],
57            PythonRuntime::CircuitPython => &["code.py", "main.py"],
58        }
59    }
60
61    /// Ctrl-A enters MicroPython's raw REPL, where the interpreter does not
62    /// echo or line-edit, so the pasted bytes arrive exactly as written.
63    pub fn raw_paste_begin(self) -> &'static [u8] {
64        &[0x01]
65    }
66
67    /// Ctrl-D compiles and runs the raw paste. Both runtimes use the same
68    /// framing; the parameter keeps the staging sequence one shape at the call
69    /// site even though the bytes do not differ.
70    pub fn raw_paste_end(self) -> &'static [u8] {
71        &[0x04]
72    }
73}
74
75/// `PythonRuntime::entry_name` as a free function, so a call site that already
76/// holds the runtime can read `entry_name(runtime)`.
77pub fn entry_name(runtime: PythonRuntime) -> &'static str {
78    runtime.entry_name()
79}
80
81/// `PythonRuntime::entry_candidates` as a free function.
82pub fn entry_candidates(runtime: PythonRuntime) -> &'static [&'static str] {
83    runtime.entry_candidates()
84}
85
86/// `PythonRuntime::interrupt_sequence` as a free function.
87pub fn interrupt_sequence(runtime: PythonRuntime) -> &'static [u8] {
88    runtime.interrupt_sequence()
89}
90
91/// `PythonRuntime::raw_paste_begin` as a free function.
92pub fn raw_paste_begin(runtime: PythonRuntime) -> &'static [u8] {
93    runtime.raw_paste_begin()
94}
95
96/// `PythonRuntime::raw_paste_end` as a free function.
97pub fn raw_paste_end(runtime: PythonRuntime) -> &'static [u8] {
98    runtime.raw_paste_end()
99}
100
101/// Which interpreter a board's console speaks, from the configured runtime and
102/// a firmware hint: its file name or a captured banner.
103///
104/// An explicit `runtime = "circuitpython"` wins. Otherwise a hint that names
105/// CircuitPython wins over the MicroPython default, because the image is what
106/// will actually boot; a MicroPython build or an image that says nothing about
107/// CircuitPython stays MicroPython.
108pub fn detect(runtime: Runtime, hint: &str) -> PythonRuntime {
109    detect_bytes(runtime, hint.as_bytes())
110}
111
112/// `detect` for a firmware image or a console banner the caller already holds
113/// as bytes. The scan is case-insensitive and does not require the hint to be
114/// UTF-8.
115pub fn detect_bytes(runtime: Runtime, hint: &[u8]) -> PythonRuntime {
116    if runtime == Runtime::CircuitPython || mentions_circuitpython(hint) {
117        PythonRuntime::CircuitPython
118    } else {
119        PythonRuntime::MicroPython
120    }
121}
122
123const CIRCUITPYTHON: &[u8] = b"circuitpython";
124
125/// Whether a file name or banner names CircuitPython. Case-insensitive because
126/// a path may be lowercased while the banner is `Adafruit CircuitPython`.
127fn mentions_circuitpython(hint: &[u8]) -> bool {
128    hint.windows(CIRCUITPYTHON.len())
129        .any(|window| window.eq_ignore_ascii_case(CIRCUITPYTHON))
130}
131
132/// The Python a multi-file project pastes. It writes every staged file through
133/// `open(..., 'wb')`, creating the directories the path needs, then runs the
134/// entry file in the REPL's own globals so `__name__` stays `__main__`.
135///
136/// The shape is shared with the MicroPython path in `runner.rs`; the difference
137/// is only which name is passed as `entry`. Neither runtime needs a `boot.py`:
138/// CircuitPython runs the entry itself, and wiring files through `boot.py`
139/// would execute them before the paste had a chance to finish.
140///
141/// An empty `scripts` list returns an empty string because there is nothing to
142/// stage; the caller pastes a single file directly, as `runner.rs` does.
143pub fn stage_program(entry: &str, scripts: &[(&str, &[u8])]) -> String {
144    if scripts.is_empty() {
145        return String::new();
146    }
147    let mut out = String::new();
148    out.push_str(concat!(
149        "def _litz_mkdir(path):\n",
150        "    import os\n",
151        "    cur = ''\n",
152        "    for part in path.split('/')[:-1]:\n",
153        "        cur = part if not cur else cur + '/' + part\n",
154        "        try:\n",
155        "            os.mkdir(cur)\n",
156        "        except OSError:\n",
157        "            pass\n",
158        "def _litz_stage(name, data):\n",
159        "    _litz_mkdir(name)\n",
160        "    f = open(name, 'wb')\n",
161        "    f.write(data)\n",
162        "    f.close()\n",
163    ));
164    for (name, bytes) in scripts {
165        out.push_str("_litz_stage(");
166        out.push_str(&py_string(name));
167        out.push_str(", (");
168        out.push_str(&py_bytes(bytes));
169        out.push_str("))\n");
170    }
171    out.push_str("exec(open(");
172    out.push_str(&py_string(entry));
173    out.push_str(").read())\n");
174    out
175}
176
177/// A Python string literal for ASCII paths. The stage validator rejects
178/// anything that is not a plain relative path, so unusual characters become
179/// `?` rather than an escape a build's parser might not share.
180fn py_string(text: &str) -> String {
181    let mut out = String::with_capacity(text.len() + 2);
182    out.push('\'');
183    for ch in text.chars() {
184        match ch {
185            '\\' => out.push_str("\\\\"),
186            '\'' => out.push_str("\\'"),
187            _ if ch.is_ascii_graphic() || ch == ' ' => out.push(ch),
188            _ => out.push('?'),
189        }
190    }
191    out.push('\'');
192    out
193}
194
195/// A Python bytes literal, split into adjacent literals so one long file does
196/// not produce one endless line. Python concatenates adjacent literals, so the
197/// newline between chunks is whitespace, not a change in value.
198fn py_bytes(data: &[u8]) -> String {
199    if data.is_empty() {
200        return "b''".into();
201    }
202    let mut out = String::with_capacity(data.len() * 4);
203    for (index, chunk) in data.chunks(64).enumerate() {
204        if index > 0 {
205            out.push('\n');
206        }
207        out.push_str("b'");
208        for &byte in chunk {
209            match byte {
210                b'\\' => out.push_str("\\\\"),
211                b'\'' => out.push_str("\\'"),
212                b'\n' => out.push_str("\\n"),
213                b'\r' => out.push_str("\\r"),
214                b'\t' => out.push_str("\\t"),
215                0x20..=0x7e => out.push(byte as char),
216                _ => out.push_str(&format!("\\x{byte:02x}")),
217            }
218        }
219        out.push('\'');
220    }
221    out
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn detection_prefers_circuitpython_and_defaults_to_micropython() {
230        // An explicit runtime always wins.
231        assert_eq!(
232            detect(Runtime::CircuitPython, "ESP32_GENERIC_C3.bin"),
233            PythonRuntime::CircuitPython
234        );
235        assert_eq!(
236            detect(Runtime::Micropython, "firmware.bin"),
237            PythonRuntime::MicroPython
238        );
239        assert_eq!(
240            detect(Runtime::Native, "micropython.bin"),
241            PythonRuntime::MicroPython
242        );
243
244        // A firmware name or banner that says CircuitPython identifies the
245        // image even when the project left the runtime at its default.
246        assert_eq!(
247            detect(Runtime::Native, "adafruit-circuitpython-esp32s3.bin"),
248            PythonRuntime::CircuitPython
249        );
250        assert_eq!(
251            detect_bytes(
252                Runtime::Micropython,
253                b"Adafruit CircuitPython 10.3.2 on 2026-01-01; ESP32-S3\r\n"
254            ),
255            PythonRuntime::CircuitPython
256        );
257    }
258
259    #[test]
260    fn circuitpython_runs_code_py_with_main_py_as_the_fallback() {
261        assert_eq!(PythonRuntime::MicroPython.entry_name(), "main.py");
262        assert_eq!(PythonRuntime::CircuitPython.entry_name(), "code.py");
263        // The free functions are the form a caller with a plain runtime uses.
264        assert_eq!(entry_name(PythonRuntime::CircuitPython), "code.py");
265        assert_eq!(PythonRuntime::MicroPython.entry_candidates(), ["main.py"]);
266        assert_eq!(
267            PythonRuntime::CircuitPython.entry_candidates(),
268            ["code.py", "main.py"]
269        );
270    }
271
272    #[test]
273    fn only_circuitpython_needs_an_interrupt_before_the_paste() {
274        assert!(PythonRuntime::MicroPython.interrupt_sequence().is_empty());
275        assert_eq!(PythonRuntime::CircuitPython.interrupt_sequence(), &[0x03u8]);
276        assert!(interrupt_sequence(PythonRuntime::MicroPython).is_empty());
277        assert_eq!(interrupt_sequence(PythonRuntime::CircuitPython), &[0x03u8]);
278        // Raw-REPL framing is shared; the call site still names the runtime so
279        // one staging sequence covers both.
280        for runtime in [PythonRuntime::MicroPython, PythonRuntime::CircuitPython] {
281            assert_eq!(runtime.raw_paste_begin(), &[0x01u8]);
282            assert_eq!(runtime.raw_paste_end(), &[0x04u8]);
283        }
284    }
285
286    #[test]
287    fn a_multi_file_paste_writes_every_module_then_runs_the_entry() {
288        let program = stage_program(
289            "code.py",
290            &[
291                ("code.py", b"import util\nprint(util.N)\n"),
292                ("lib/util.py", b"N = 42\n"),
293            ],
294        );
295        assert!(program.contains("_litz_stage('code.py', (b'import util\\nprint(util.N)\\n'))"));
296        assert!(program.contains("_litz_stage('lib/util.py', (b'N = 42\\n'))"));
297        assert!(program.ends_with("exec(open('code.py').read())\n"));
298        assert!(program.contains("os.mkdir(cur)"), "directories are created");
299        // CircuitPython must not need a boot.py hook to see the files.
300        assert!(!program.contains("boot.py"));
301    }
302
303    #[test]
304    fn an_empty_paste_has_nothing_to_run() {
305        assert!(stage_program("code.py", &[]).is_empty());
306    }
307
308    #[test]
309    fn bytes_are_escaped_into_a_python_literal() {
310        assert_eq!(py_bytes(b"a\nb'c\\d\x01"), "b'a\\nb\\'c\\\\d\\x01'");
311        assert_eq!(py_bytes(b""), "b''");
312        // A file longer than one 64-byte chunk becomes adjacent literals, not
313        // one line Python would refuse to parse at the REPL.
314        let long = [b'a'; 65];
315        let literal = py_bytes(&long);
316        assert_eq!(literal.matches("b'").count(), 2);
317    }
318
319    #[test]
320    fn a_staged_name_is_escaped_into_the_bootstrap() {
321        assert_eq!(py_string("lib/util.py"), "'lib/util.py'");
322        assert_eq!(py_string("o'file.py"), "'o\\'file.py'");
323    }
324}