1use crate::config::Runtime;
17
18pub const REPL_PROMPT: &str = ">>> ";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum PythonRuntime {
26 MicroPython,
27 CircuitPython,
28}
29
30impl PythonRuntime {
31 pub fn interrupt_sequence(self) -> &'static [u8] {
36 match self {
37 PythonRuntime::MicroPython => &[],
38 PythonRuntime::CircuitPython => &[0x03],
39 }
40 }
41
42 pub fn entry_name(self) -> &'static str {
44 match self {
45 PythonRuntime::MicroPython => "main.py",
46 PythonRuntime::CircuitPython => "code.py",
47 }
48 }
49
50 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 pub fn raw_paste_begin(self) -> &'static [u8] {
64 &[0x01]
65 }
66
67 pub fn raw_paste_end(self) -> &'static [u8] {
71 &[0x04]
72 }
73}
74
75pub fn entry_name(runtime: PythonRuntime) -> &'static str {
78 runtime.entry_name()
79}
80
81pub fn entry_candidates(runtime: PythonRuntime) -> &'static [&'static str] {
83 runtime.entry_candidates()
84}
85
86pub fn interrupt_sequence(runtime: PythonRuntime) -> &'static [u8] {
88 runtime.interrupt_sequence()
89}
90
91pub fn raw_paste_begin(runtime: PythonRuntime) -> &'static [u8] {
93 runtime.raw_paste_begin()
94}
95
96pub fn raw_paste_end(runtime: PythonRuntime) -> &'static [u8] {
98 runtime.raw_paste_end()
99}
100
101pub fn detect(runtime: Runtime, hint: &str) -> PythonRuntime {
109 detect_bytes(runtime, hint.as_bytes())
110}
111
112pub 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
125fn mentions_circuitpython(hint: &[u8]) -> bool {
128 hint.windows(CIRCUITPYTHON.len())
129 .any(|window| window.eq_ignore_ascii_case(CIRCUITPYTHON))
130}
131
132pub 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
177fn 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
195fn 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 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 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 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 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 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 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}