use crate::config::Runtime;
pub const REPL_PROMPT: &str = ">>> ";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PythonRuntime {
MicroPython,
CircuitPython,
}
impl PythonRuntime {
pub fn interrupt_sequence(self) -> &'static [u8] {
match self {
PythonRuntime::MicroPython => &[],
PythonRuntime::CircuitPython => &[0x03],
}
}
pub fn entry_name(self) -> &'static str {
match self {
PythonRuntime::MicroPython => "main.py",
PythonRuntime::CircuitPython => "code.py",
}
}
pub fn entry_candidates(self) -> &'static [&'static str] {
match self {
PythonRuntime::MicroPython => &["main.py"],
PythonRuntime::CircuitPython => &["code.py", "main.py"],
}
}
pub fn raw_paste_begin(self) -> &'static [u8] {
&[0x01]
}
pub fn raw_paste_end(self) -> &'static [u8] {
&[0x04]
}
}
pub fn entry_name(runtime: PythonRuntime) -> &'static str {
runtime.entry_name()
}
pub fn entry_candidates(runtime: PythonRuntime) -> &'static [&'static str] {
runtime.entry_candidates()
}
pub fn interrupt_sequence(runtime: PythonRuntime) -> &'static [u8] {
runtime.interrupt_sequence()
}
pub fn raw_paste_begin(runtime: PythonRuntime) -> &'static [u8] {
runtime.raw_paste_begin()
}
pub fn raw_paste_end(runtime: PythonRuntime) -> &'static [u8] {
runtime.raw_paste_end()
}
pub fn detect(runtime: Runtime, hint: &str) -> PythonRuntime {
detect_bytes(runtime, hint.as_bytes())
}
pub fn detect_bytes(runtime: Runtime, hint: &[u8]) -> PythonRuntime {
if runtime == Runtime::CircuitPython || mentions_circuitpython(hint) {
PythonRuntime::CircuitPython
} else {
PythonRuntime::MicroPython
}
}
const CIRCUITPYTHON: &[u8] = b"circuitpython";
fn mentions_circuitpython(hint: &[u8]) -> bool {
hint.windows(CIRCUITPYTHON.len())
.any(|window| window.eq_ignore_ascii_case(CIRCUITPYTHON))
}
pub fn stage_program(entry: &str, scripts: &[(&str, &[u8])]) -> String {
if scripts.is_empty() {
return String::new();
}
let mut out = String::new();
out.push_str(concat!(
"def _litz_mkdir(path):\n",
" import os\n",
" cur = ''\n",
" for part in path.split('/')[:-1]:\n",
" cur = part if not cur else cur + '/' + part\n",
" try:\n",
" os.mkdir(cur)\n",
" except OSError:\n",
" pass\n",
"def _litz_stage(name, data):\n",
" _litz_mkdir(name)\n",
" f = open(name, 'wb')\n",
" f.write(data)\n",
" f.close()\n",
));
for (name, bytes) in scripts {
out.push_str("_litz_stage(");
out.push_str(&py_string(name));
out.push_str(", (");
out.push_str(&py_bytes(bytes));
out.push_str("))\n");
}
out.push_str("exec(open(");
out.push_str(&py_string(entry));
out.push_str(").read())\n");
out
}
fn py_string(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('\'');
for ch in text.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'\'' => out.push_str("\\'"),
_ if ch.is_ascii_graphic() || ch == ' ' => out.push(ch),
_ => out.push('?'),
}
}
out.push('\'');
out
}
fn py_bytes(data: &[u8]) -> String {
if data.is_empty() {
return "b''".into();
}
let mut out = String::with_capacity(data.len() * 4);
for (index, chunk) in data.chunks(64).enumerate() {
if index > 0 {
out.push('\n');
}
out.push_str("b'");
for &byte in chunk {
match byte {
b'\\' => out.push_str("\\\\"),
b'\'' => out.push_str("\\'"),
b'\n' => out.push_str("\\n"),
b'\r' => out.push_str("\\r"),
b'\t' => out.push_str("\\t"),
0x20..=0x7e => out.push(byte as char),
_ => out.push_str(&format!("\\x{byte:02x}")),
}
}
out.push('\'');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detection_prefers_circuitpython_and_defaults_to_micropython() {
assert_eq!(
detect(Runtime::CircuitPython, "ESP32_GENERIC_C3.bin"),
PythonRuntime::CircuitPython
);
assert_eq!(
detect(Runtime::Micropython, "firmware.bin"),
PythonRuntime::MicroPython
);
assert_eq!(
detect(Runtime::Native, "micropython.bin"),
PythonRuntime::MicroPython
);
assert_eq!(
detect(Runtime::Native, "adafruit-circuitpython-esp32s3.bin"),
PythonRuntime::CircuitPython
);
assert_eq!(
detect_bytes(
Runtime::Micropython,
b"Adafruit CircuitPython 10.3.2 on 2026-01-01; ESP32-S3\r\n"
),
PythonRuntime::CircuitPython
);
}
#[test]
fn circuitpython_runs_code_py_with_main_py_as_the_fallback() {
assert_eq!(PythonRuntime::MicroPython.entry_name(), "main.py");
assert_eq!(PythonRuntime::CircuitPython.entry_name(), "code.py");
assert_eq!(entry_name(PythonRuntime::CircuitPython), "code.py");
assert_eq!(PythonRuntime::MicroPython.entry_candidates(), ["main.py"]);
assert_eq!(
PythonRuntime::CircuitPython.entry_candidates(),
["code.py", "main.py"]
);
}
#[test]
fn only_circuitpython_needs_an_interrupt_before_the_paste() {
assert!(PythonRuntime::MicroPython.interrupt_sequence().is_empty());
assert_eq!(PythonRuntime::CircuitPython.interrupt_sequence(), &[0x03u8]);
assert!(interrupt_sequence(PythonRuntime::MicroPython).is_empty());
assert_eq!(interrupt_sequence(PythonRuntime::CircuitPython), &[0x03u8]);
for runtime in [PythonRuntime::MicroPython, PythonRuntime::CircuitPython] {
assert_eq!(runtime.raw_paste_begin(), &[0x01u8]);
assert_eq!(runtime.raw_paste_end(), &[0x04u8]);
}
}
#[test]
fn a_multi_file_paste_writes_every_module_then_runs_the_entry() {
let program = stage_program(
"code.py",
&[
("code.py", b"import util\nprint(util.N)\n"),
("lib/util.py", b"N = 42\n"),
],
);
assert!(program.contains("_litz_stage('code.py', (b'import util\\nprint(util.N)\\n'))"));
assert!(program.contains("_litz_stage('lib/util.py', (b'N = 42\\n'))"));
assert!(program.ends_with("exec(open('code.py').read())\n"));
assert!(program.contains("os.mkdir(cur)"), "directories are created");
assert!(!program.contains("boot.py"));
}
#[test]
fn an_empty_paste_has_nothing_to_run() {
assert!(stage_program("code.py", &[]).is_empty());
}
#[test]
fn bytes_are_escaped_into_a_python_literal() {
assert_eq!(py_bytes(b"a\nb'c\\d\x01"), "b'a\\nb\\'c\\\\d\\x01'");
assert_eq!(py_bytes(b""), "b''");
let long = [b'a'; 65];
let literal = py_bytes(&long);
assert_eq!(literal.matches("b'").count(), 2);
}
#[test]
fn a_staged_name_is_escaped_into_the_bootstrap() {
assert_eq!(py_string("lib/util.py"), "'lib/util.py'");
assert_eq!(py_string("o'file.py"), "'o\\'file.py'");
}
}