code_transpiler/
python_frontend.rs1use crate::julia_ir::{parse_julia, JuliaParseError};
2use crate::Program;
3
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct PythonParseError(pub String);
6impl std::fmt::Display for PythonParseError {
7 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8 f.write_str(&self.0)
9 }
10}
11impl std::error::Error for PythonParseError {}
12
13fn py_type_to_julia(t: &str) -> Result<String, PythonParseError> {
14 let t = t.trim();
15 if let Some(inner) = t.strip_prefix("list[").and_then(|x| x.strip_suffix(']')) {
16 return Ok(format!("Vector{{{}}}", py_type_to_julia(inner)?));
17 }
18 if let Some(inner) = t.strip_prefix("List[").and_then(|x| x.strip_suffix(']')) {
19 return Ok(format!("Vector{{{}}}", py_type_to_julia(inner)?));
20 }
21 Ok(match t {
22 "int" => "Int",
23 "float" => "Float64",
24 "bool" => "Bool",
25 "str" => "String",
26 "None" => "Nothing",
27 "" => "Any",
28 other => {
29 return Err(PythonParseError(format!(
30 "unsupported Python type annotation: {other}"
31 )))
32 }
33 }
34 .into())
35}
36fn split_top_level(s: &str, needle: char) -> Vec<String> {
37 let mut out = Vec::new();
38 let mut d = 0i32;
39 let mut q = false;
40 let mut esc = false;
41 let mut start = 0;
42 for (i, c) in s.char_indices() {
43 if q {
44 if esc {
45 esc = false;
46 continue;
47 }
48 if c == '\\' {
49 esc = true;
50 continue;
51 }
52 if c == '"' || c == '\'' {
53 q = false
54 }
55 continue;
56 }
57 match c {
58 '"' | '\'' => q = true,
59 '(' | '[' | '{' => d += 1,
60 ')' | ']' | '}' => d -= 1,
61 _ if c == needle && d == 0 => {
62 out.push(s[start..i].trim().into());
63 start = i + c.len_utf8()
64 }
65 _ => {}
66 }
67 }
68 out.push(s[start..].trim().into());
69 out
70}
71fn typed_params(raw: &str) -> Result<String, PythonParseError> {
72 if raw.trim().is_empty() {
73 return Ok(String::new());
74 }
75 split_top_level(raw, ',')
76 .into_iter()
77 .map(|p| {
78 let (n, t) = p.split_once(':').ok_or_else(|| {
79 PythonParseError(format!(
80 "Python parameters require type annotations in native frontend: {p}"
81 ))
82 })?;
83 Ok(format!("{}::{}", n.trim(), py_type_to_julia(t)?))
84 })
85 .collect::<Result<Vec<_>, _>>()
86 .map(|v| v.join(", "))
87}
88fn normalize_expr(mut x: String, zero_based_arrays: &[String]) -> String {
89 x = x
90 .replace("True", "true")
91 .replace("False", "false")
92 .replace("None", "nothing");
93 x = x.replace(" and ", " && ").replace(" or ", " || ");
94 if let Some(rest) = x.strip_prefix("not ") {
95 x = format!("!({rest})")
96 }
97 x = x.replace("len(", "length(");
98 for name in zero_based_arrays {
99 let needle = format!("{name}[");
100 let mut from = 0usize;
101 while let Some(rel) = x[from..].find(&needle) {
102 let start = from + rel + needle.len();
103 let mut depth = 1i32;
104 let mut end = None;
105 for (i, c) in x[start..].char_indices() {
106 match c {
107 '[' => depth += 1,
108 ']' => {
109 depth -= 1;
110 if depth == 0 {
111 end = Some(start + i);
112 break;
113 }
114 }
115 _ => {}
116 }
117 }
118 let Some(end) = end else { break };
119 let idx = x[start..end].to_string();
120 let repl = format!("{name}[({idx}) + 1]");
121 let whole_start = start - needle.len();
122 x.replace_range(whole_start..=end, &repl);
123 from = whole_start + repl.len();
124 }
125 }
126 x
127}
128
129#[derive(Clone, Copy, PartialEq, Eq)]
130enum Kind {
131 Function,
132 If,
133 While,
134}
135
136pub fn python_to_julia_pivot(code: &str) -> Result<String, PythonParseError> {
137 let mut out = Vec::<String>::new();
138 let mut blocks = Vec::<(usize, Kind)>::new();
139 let mut arrays = Vec::<String>::new();
140 for raw in code.replace("\r\n", "\n").lines() {
141 if raw.trim().is_empty() || raw.trim_start().starts_with('#') {
142 continue;
143 }
144 let indent = raw.len() - raw.trim_start().len();
145 let mut line = raw.trim().to_string();
146 let continuation = line.starts_with("elif ") || line == "else:";
147 while let Some(&(bi, bk)) = blocks.last() {
148 if indent < bi || (indent == bi && !(continuation && bk == Kind::If)) {
149 blocks.pop();
150 out.push("end".into())
151 } else {
152 break;
153 }
154 }
155 let mut opened = None;
156 if let Some(rest) = line.strip_prefix("def ") {
157 if !line.ends_with(':') {
158 return Err(PythonParseError(format!(
159 "invalid Python function header: {line}"
160 )));
161 }
162 let rest = &rest[..rest.len() - 1];
163 let open = rest.find('(').ok_or_else(|| {
164 PythonParseError(format!("invalid Python function header: {line}"))
165 })?;
166 let close = rest.rfind(')').ok_or_else(|| {
167 PythonParseError(format!("invalid Python function header: {line}"))
168 })?;
169 let name = rest[..open].trim();
170 let params = typed_params(&rest[open + 1..close])?;
171 let tail = rest[close + 1..].trim();
172 let ret = if let Some(t) = tail.strip_prefix("->") {
173 format!("::{}", py_type_to_julia(t)?)
174 } else {
175 String::new()
176 };
177 out.push(format!("function {name}({params}){ret}"));
178 opened = Some(Kind::Function)
179 } else if let Some(c) = line.strip_prefix("if ").and_then(|x| x.strip_suffix(':')) {
180 out.push(format!("if {}", normalize_expr(c.into(), &arrays)));
181 opened = Some(Kind::If)
182 } else if let Some(c) = line.strip_prefix("elif ").and_then(|x| x.strip_suffix(':')) {
183 if blocks.last().map(|x| x.1) != Some(Kind::If) {
184 return Err(PythonParseError("elif without matching if".into()));
185 }
186 out.push(format!("elseif {}", normalize_expr(c.into(), &arrays)))
187 } else if line == "else:" {
188 if blocks.last().map(|x| x.1) != Some(Kind::If) {
189 return Err(PythonParseError("else without matching if".into()));
190 }
191 out.push("else".into())
192 } else if let Some(c) = line
193 .strip_prefix("while ")
194 .and_then(|x| x.strip_suffix(':'))
195 {
196 out.push(format!("while {}", normalize_expr(c.into(), &arrays)));
197 opened = Some(Kind::While)
198 } else if line.starts_with("for ") {
199 return Err(PythonParseError("Python for/range lowering is the next porting chunk; use while in the current native frontend".into()));
200 } else if let Some(rest) = line.strip_prefix("return") {
201 let e = rest.trim();
202 out.push(if e.is_empty() {
203 "return".into()
204 } else {
205 format!("return {}", normalize_expr(e.into(), &arrays))
206 })
207 } else if line == "break" || line == "continue" {
208 out.push(line)
209 } else {
210 if let Some((lhs, rhs)) = line.split_once('=') {
211 if !lhs.contains(['!', '<', '>']) && !rhs.starts_with('=') {
212 let n = lhs.trim();
213 let r = rhs.trim();
214 if n.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
215 && r.starts_with('[')
216 && r.ends_with(']')
217 && !arrays.iter().any(|x| x == n)
218 {
219 arrays.push(n.into())
220 }
221 }
222 }
223 if line.starts_with("print(") {
224 line = line.replacen("print(", "println(", 1)
225 }
226 out.push(normalize_expr(line, &arrays));
227 }
228 if let Some(k) = opened {
229 blocks.push((indent, k))
230 }
231 }
232 while blocks.pop().is_some() {
233 out.push("end".into())
234 }
235 Ok(out.join("\n") + "\n")
236}
237
238pub fn parse_python(code: &str) -> Result<Program, PythonParseError> {
239 let pivot = python_to_julia_pivot(code)?;
240 parse_julia(&pivot).map_err(|e: JuliaParseError| PythonParseError(e.to_string()))
241}