Skip to main content

code_transpiler/
julia_ir.rs

1use crate::ir::{Expr, Function, Param, Program, Stmt, StructDef, StructField, Type};
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct JuliaParseError(pub String);
5impl std::fmt::Display for JuliaParseError {
6    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7        f.write_str(&self.0)
8    }
9}
10impl std::error::Error for JuliaParseError {}
11
12fn split_top_level(s: &str, needle: char) -> Vec<String> {
13    let mut out = Vec::new();
14    let mut depth = 0i32;
15    let mut quote = false;
16    let mut esc = false;
17    let mut start = 0usize;
18    for (i, c) in s.char_indices() {
19        if quote {
20            if esc {
21                esc = false;
22                continue;
23            }
24            if c == '\\' {
25                esc = true;
26                continue;
27            }
28            if c == '"' {
29                quote = false
30            }
31            continue;
32        }
33        match c {
34            '"' => quote = true,
35            '(' | '[' | '{' => depth += 1,
36            ')' | ']' | '}' => depth -= 1,
37            _ if c == needle && depth == 0 => {
38                out.push(s[start..i].trim().to_string());
39                start = i + c.len_utf8();
40            }
41            _ => {}
42        }
43    }
44    out.push(s[start..].trim().to_string());
45    out
46}
47fn strip_outer(mut s: &str) -> &str {
48    loop {
49        let x = s.trim();
50        if x.starts_with('(') && x.ends_with(')') {
51            let mut d = 0i32;
52            let mut ok = true;
53            for (i, c) in x.char_indices() {
54                match c {
55                    '(' => d += 1,
56                    ')' => {
57                        d -= 1;
58                        if d == 0 && i + 1 < x.len() {
59                            ok = false;
60                            break;
61                        }
62                    }
63                    _ => {}
64                }
65            }
66            if ok {
67                s = &x[1..x.len() - 1];
68                continue;
69            }
70        }
71        return x;
72    }
73}
74fn find_binary(s: &str, ops: &[&str]) -> Option<(usize, &'static str)> {
75    let mut depth = 0i32;
76    let mut quote = false;
77    let b = s.as_bytes();
78    let mut i = s.len();
79    while i > 0 {
80        i -= 1;
81        let c = b[i] as char;
82        if quote {
83            if c == '"' && (i == 0 || b[i - 1] != b'\\') {
84                quote = false
85            }
86            continue;
87        }
88        match c {
89            '"' => quote = true,
90            ')' | ']' | '}' => depth += 1,
91            '(' | '[' | '{' => depth -= 1,
92            _ => {}
93        }
94        if depth != 0 {
95            continue;
96        }
97        for op in ops {
98            if i + op.len() <= s.len() && &s[i..i + op.len()] == *op {
99                if (*op == "-" || *op == "+") && i == 0 {
100                    continue;
101                }
102                let v = match *op {
103                    "||" => "||",
104                    "&&" => "&&",
105                    "==" => "==",
106                    "!=" => "!=",
107                    "<=" => "<=",
108                    ">=" => ">=",
109                    "<" => "<",
110                    ">" => ">",
111                    "+" => "+",
112                    "-" => "-",
113                    "*" => "*",
114                    "/" => "/",
115                    "%" => "%",
116                    _ => continue,
117                };
118                return Some((i, v));
119            }
120        }
121    }
122    None
123}
124
125fn julia_type(s: &str) -> Type {
126    let s = s.trim();
127    if let Some(inner) = s.strip_prefix("Vector{").and_then(|x| x.strip_suffix('}')) {
128        return Type::Slice(Box::new(julia_type(inner)));
129    }
130    if let Some(inner) = s.strip_prefix("Dict{").and_then(|x| x.strip_suffix('}')) {
131        let p = split_top_level(inner, ',');
132        if p.len() == 2 {
133            return Type::Map(Box::new(julia_type(&p[0])), Box::new(julia_type(&p[1])));
134        }
135    }
136    if let Some(inner) = s.strip_prefix("Tuple{").and_then(|x| x.strip_suffix('}')) {
137        return Type::Tuple(
138            split_top_level(inner, ',')
139                .iter()
140                .map(|x| julia_type(x))
141                .collect(),
142        );
143    }
144    match s {
145        "Nothing" => Type::Unit,
146        "Bool" => Type::Bool,
147        "String" => Type::String,
148        "Int" => Type::Int,
149        "Int8" => Type::Int8,
150        "Int16" => Type::Int16,
151        "Int32" => Type::Int32,
152        "Int64" => Type::Int64,
153        "UInt" => Type::UInt,
154        "UInt8" => Type::UInt8,
155        "UInt16" => Type::UInt16,
156        "UInt32" => Type::UInt32,
157        "UInt64" => Type::UInt64,
158        "Float32" => Type::Float32,
159        "Float64" => Type::Float64,
160        "Any" | "" => Type::Named("Any".into()),
161        other => Type::Named(other.into()),
162    }
163}
164
165pub fn parse_julia_expr(input: &str) -> Result<Expr, JuliaParseError> {
166    let x = strip_outer(input.trim().trim_end_matches(';'));
167    if x.is_empty() {
168        return Err(JuliaParseError("empty Julia expression".into()));
169    }
170    let tuple = split_top_level(x, ',');
171    if tuple.len() > 1 {
172        return tuple
173            .iter()
174            .map(|p| parse_julia_expr(p))
175            .collect::<Result<Vec<_>, _>>()
176            .map(Expr::Tuple);
177    }
178    match x {
179        "true" => return Ok(Expr::Bool(true)),
180        "false" => return Ok(Expr::Bool(false)),
181        "nothing" | "missing" => return Ok(Expr::Nil),
182        _ => {}
183    }
184    if x.starts_with('"') && x.ends_with('"') && x.len() >= 2 {
185        return Ok(Expr::String(
186            x[1..x.len() - 1].replace("\\\"", "\"").replace("\\n", "\n"),
187        ));
188    }
189    if x.parse::<i128>().is_ok() {
190        return Ok(Expr::Int(x.into()));
191    }
192    if x.parse::<f64>().is_ok() && (x.contains('.') || x.contains('e') || x.contains('E')) {
193        return Ok(Expr::Float(x.into()));
194    }
195    for ops in [
196        &["||"][..],
197        &["&&"][..],
198        &["==", "!=", "<=", ">=", "<", ">"][..],
199        &["+", "-"][..],
200        &["*", "/", "%"][..],
201    ] {
202        if let Some((i, op)) = find_binary(x, ops) {
203            return Ok(Expr::Binary {
204                left: Box::new(parse_julia_expr(&x[..i])?),
205                op: op.into(),
206                right: Box::new(parse_julia_expr(&x[i + op.len()..])?),
207            });
208        }
209    }
210    if let Some(rest) = x.strip_prefix('!') {
211        return Ok(Expr::Unary {
212            op: "!".into(),
213            value: Box::new(parse_julia_expr(rest)?),
214        });
215    }
216    if x.starts_with('[') && x.ends_with(']') {
217        let inside = &x[1..x.len() - 1];
218        let items = if inside.trim().is_empty() {
219            Vec::new()
220        } else {
221            split_top_level(inside, ',')
222                .iter()
223                .map(|p| parse_julia_expr(p))
224                .collect::<Result<Vec<_>, _>>()?
225        };
226        return Ok(Expr::Array {
227            items,
228            element_type: None,
229        });
230    }
231    if let Some(inner) = x.strip_prefix("Dict(").and_then(|y| y.strip_suffix(')')) {
232        let mut entries = Vec::new();
233        if !inner.trim().is_empty() {
234            for p in split_top_level(inner, ',') {
235                let mut depth = 0i32;
236                let mut at = None;
237                let bytes = p.as_bytes();
238                let mut i = 0;
239                while i + 1 < bytes.len() {
240                    let c = bytes[i] as char;
241                    match c {
242                        '(' | '[' | '{' => depth += 1,
243                        ')' | ']' | '}' => depth -= 1,
244                        _ => {}
245                    }
246                    if depth == 0 && bytes[i] == b'=' && bytes[i + 1] == b'>' {
247                        at = Some(i);
248                        break;
249                    }
250                    i += 1;
251                }
252                let at =
253                    at.ok_or_else(|| JuliaParseError(format!("unsupported Dict entry: {p}")))?;
254                entries.push((parse_julia_expr(&p[..at])?, parse_julia_expr(&p[at + 2..])?));
255            }
256        }
257        return Ok(Expr::Map {
258            key_type: Box::new(Type::Named("Any".into())),
259            value_type: Box::new(Type::Named("Any".into())),
260            entries,
261        });
262    }
263    if x.ends_with(']') {
264        if let Some(open) = x.find('[') {
265            let base = x[..open].trim();
266            if !base.is_empty() {
267                let idx = &x[open + 1..x.len() - 1];
268                let one_based = parse_julia_expr(idx)?;
269                let zero_based = Expr::Binary {
270                    left: Box::new(one_based),
271                    op: "-".into(),
272                    right: Box::new(Expr::Int("1".into())),
273                };
274                return Ok(Expr::Index {
275                    value: Box::new(parse_julia_expr(base)?),
276                    index: Box::new(zero_based),
277                });
278            }
279        }
280    }
281    if x.ends_with(')') {
282        if let Some(open) = x.find('(') {
283            let name = x[..open].trim();
284            if name
285                .chars()
286                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '!')
287            {
288                let raw = &x[open + 1..x.len() - 1];
289                let args = if raw.trim().is_empty() {
290                    Vec::new()
291                } else {
292                    split_top_level(raw, ',')
293                        .iter()
294                        .map(|p| parse_julia_expr(p))
295                        .collect::<Result<Vec<_>, _>>()?
296                };
297                let function = match name {
298                    "length" => "len",
299                    "push!" => "append",
300                    other => other,
301                }
302                .to_string();
303                return Ok(Expr::Call { function, args });
304            }
305        }
306    }
307    if x.chars()
308        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
309    {
310        return Ok(Expr::Ident(x.into()));
311    }
312    Err(JuliaParseError(format!(
313        "unsupported Julia expression: {x}"
314    )))
315}
316
317fn parse_signature(line: &str) -> Result<(String, Vec<Param>, Option<Type>), JuliaParseError> {
318    let rest = line
319        .trim()
320        .strip_prefix("function ")
321        .ok_or_else(|| JuliaParseError("not a function".into()))?;
322    let open = rest
323        .find('(')
324        .ok_or_else(|| JuliaParseError(format!("invalid Julia function signature: {line}")))?;
325    let mut depth = 0i32;
326    let mut close = None;
327    for (i, c) in rest[open..].char_indices() {
328        match c {
329            '(' => depth += 1,
330            ')' => {
331                depth -= 1;
332                if depth == 0 {
333                    close = Some(open + i);
334                    break;
335                }
336            }
337            _ => {}
338        }
339    }
340    let close = close
341        .ok_or_else(|| JuliaParseError(format!("unclosed Julia function signature: {line}")))?;
342    let name = rest[..open].trim().to_string();
343    let raw = &rest[open + 1..close];
344    let tail = rest[close + 1..].trim();
345    let mut params = Vec::new();
346    if !raw.trim().is_empty() {
347        for p in split_top_level(raw, ',') {
348            let mut parts = p.splitn(2, "::");
349            let n = parts.next().unwrap().trim();
350            let t = parts.next().unwrap_or("Any").trim();
351            params.push(Param {
352                name: n.into(),
353                ty: julia_type(t),
354            });
355        }
356    }
357    let ret = tail
358        .strip_prefix("::")
359        .map(julia_type)
360        .filter(|t| !matches!(t, Type::Unit));
361    Ok((name, params, ret))
362}
363
364fn top_assign(line: &str) -> Option<(String, String, String)> {
365    for op in ["+=", "-=", "*=", "/=", "="] {
366        let mut depth = 0i32;
367        let b = line.as_bytes();
368        let ob = op.as_bytes();
369        let mut i = 0;
370        while i + ob.len() <= b.len() {
371            let c = b[i] as char;
372            match c {
373                '(' | '[' | '{' => depth += 1,
374                ')' | ']' | '}' => depth -= 1,
375                _ => {}
376            }
377            if depth == 0 && &b[i..i + ob.len()] == ob {
378                if op == "="
379                    && ((i > 0 && matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))
380                        || (i + 1 < b.len() && b[i + 1] == b'='))
381                {
382                    i += 1;
383                    continue;
384                }
385                return Some((
386                    line[..i].trim().into(),
387                    op.into(),
388                    line[i + op.len()..].trim().into(),
389                ));
390            }
391            i += 1;
392        }
393    }
394    None
395}
396
397fn parse_block(
398    lines: &[String],
399    pos: &mut usize,
400    stop_on_else: bool,
401) -> Result<(Vec<Stmt>, Option<String>), JuliaParseError> {
402    let mut out = Vec::new();
403    while *pos < lines.len() {
404        let line = lines[*pos].trim();
405        if line.is_empty() || line.starts_with('#') {
406            *pos += 1;
407            continue;
408        }
409        if line == "end" {
410            *pos += 1;
411            return Ok((out, Some("end".into())));
412        }
413        if stop_on_else && (line == "else" || line.starts_with("elseif ")) {
414            *pos += 1;
415            return Ok((out, Some(line.into())));
416        }
417        if let Some(cond) = line.strip_prefix("if ") {
418            *pos += 1;
419            let cond = parse_julia_expr(cond)?;
420            let (then_body, stop) = parse_block(lines, pos, true)?;
421            let else_body = match stop.as_deref() {
422                Some("else") => {
423                    let (b, _) = parse_block(lines, pos, false)?;
424                    b
425                }
426                Some(s) if s.starts_with("elseif ") => {
427                    let nested_cond = parse_julia_expr(s.trim_start_matches("elseif "))?;
428                    let (tb, st) = parse_block(lines, pos, true)?;
429                    let eb = match st.as_deref() {
430                        Some("else") => parse_block(lines, pos, false)?.0,
431                        _ => Vec::new(),
432                    };
433                    vec![Stmt::If {
434                        cond: nested_cond,
435                        then_body: tb,
436                        else_body: eb,
437                    }]
438                }
439                _ => Vec::new(),
440            };
441            out.push(Stmt::If {
442                cond,
443                then_body,
444                else_body,
445            });
446            continue;
447        }
448        if let Some(cond) = line.strip_prefix("while ") {
449            *pos += 1;
450            let (body, _) = parse_block(lines, pos, false)?;
451            out.push(Stmt::While {
452                cond: parse_julia_expr(cond)?,
453                body,
454            });
455            continue;
456        }
457        if let Some(rest) = line.strip_prefix("for ") {
458            if let Some((name, iter)) = rest.split_once(" in ") {
459                if iter.contains(':') {
460                    return Err(JuliaParseError(
461                        "Julia range for-loops are not yet normalized safely".into(),
462                    ));
463                }
464                *pos += 1;
465                let (body, _) = parse_block(lines, pos, false)?;
466                out.push(Stmt::ForEach {
467                    value: name.trim().into(),
468                    iter: parse_julia_expr(iter)?,
469                    body,
470                });
471                continue;
472            }
473        }
474        if let Some(rest) = line.strip_prefix("return") {
475            *pos += 1;
476            let v = rest.trim();
477            out.push(Stmt::Return(if v.is_empty() {
478                None
479            } else {
480                Some(parse_julia_expr(v)?)
481            }));
482            continue;
483        }
484        if line == "break" {
485            out.push(Stmt::Break);
486            *pos += 1;
487            continue;
488        }
489        if line == "continue" {
490            out.push(Stmt::Continue);
491            *pos += 1;
492            continue;
493        }
494        if (line.starts_with("println(") || line.starts_with("print(")) && line.ends_with(')') {
495            let newline = line.starts_with("println(");
496            let open = line.find('(').unwrap();
497            let raw = &line[open + 1..line.len() - 1];
498            let args = if raw.trim().is_empty() {
499                Vec::new()
500            } else {
501                split_top_level(raw, ',')
502                    .iter()
503                    .map(|p| parse_julia_expr(p))
504                    .collect::<Result<Vec<_>, _>>()?
505            };
506            out.push(Stmt::Print { newline, args });
507            *pos += 1;
508            continue;
509        }
510        if line.starts_with("push!(") && line.ends_with(')') {
511            let raw = &line[6..line.len() - 1];
512            let p = split_top_level(raw, ',');
513            if p.len() == 2 {
514                out.push(Stmt::Assign {
515                    target: p[0].clone(),
516                    op: "=".into(),
517                    value: Expr::Call {
518                        function: "append".into(),
519                        args: vec![parse_julia_expr(&p[0])?, parse_julia_expr(&p[1])?],
520                    },
521                });
522                *pos += 1;
523                continue;
524            }
525        }
526        if let Some((lhs, op, rhs)) = top_assign(line) {
527            if lhs.contains(',') {
528                out.push(if op == "=" {
529                    Stmt::MultiLet {
530                        names: split_top_level(&lhs, ','),
531                        value: parse_julia_expr(&rhs)?,
532                        mutable: true,
533                    }
534                } else {
535                    return Err(JuliaParseError(
536                        "compound tuple assignment unsupported".into(),
537                    ));
538                });
539                *pos += 1;
540                continue;
541            }
542            if lhs.ends_with(']') {
543                if let Some(open) = lhs.find('[') {
544                    let base = &lhs[..open];
545                    let idx = &lhs[open + 1..lhs.len() - 1];
546                    let zero = Expr::Binary {
547                        left: Box::new(parse_julia_expr(idx)?),
548                        op: "-".into(),
549                        right: Box::new(Expr::Int("1".into())),
550                    };
551                    out.push(Stmt::IndexAssign {
552                        collection: parse_julia_expr(base)?,
553                        index: zero,
554                        op,
555                        value: parse_julia_expr(&rhs)?,
556                        map_value_type: None,
557                    });
558                    *pos += 1;
559                    continue;
560                }
561            }
562            let existing = out
563                .iter()
564                .any(|s| matches!(s,Stmt::Let{name,..} if name==&lhs));
565            if op == "=" && !existing {
566                out.push(Stmt::Let {
567                    name: lhs,
568                    ty: None,
569                    value: parse_julia_expr(&rhs)?,
570                    mutable: true,
571                })
572            } else {
573                out.push(Stmt::Assign {
574                    target: lhs,
575                    op,
576                    value: parse_julia_expr(&rhs)?,
577                })
578            };
579            *pos += 1;
580            continue;
581        }
582        out.push(Stmt::Expr(parse_julia_expr(line)?));
583        *pos += 1;
584    }
585    Ok((out, None))
586}
587
588pub fn parse_julia(code: &str) -> Result<Program, JuliaParseError> {
589    let lines = code
590        .replace("\r\n", "\n")
591        .lines()
592        .map(|x| x.trim().to_string())
593        .collect::<Vec<_>>();
594    let mut structs = Vec::new();
595    let mut functions = Vec::new();
596    let mut i = 0usize;
597    while i < lines.len() {
598        let line = lines[i].trim();
599        if line.is_empty() || line.starts_with('#') || line == "main()" {
600            i += 1;
601            continue;
602        }
603        if let Some(name) = line
604            .strip_prefix("mutable struct ")
605            .or_else(|| line.strip_prefix("struct "))
606        {
607            i += 1;
608            let mut fields = Vec::new();
609            while i < lines.len() && lines[i].trim() != "end" {
610                let f = lines[i].trim();
611                if !f.is_empty() {
612                    let mut p = f.splitn(2, "::");
613                    let n = p.next().unwrap().trim();
614                    let t = p.next().ok_or_else(|| {
615                        JuliaParseError(format!("untyped Julia struct field unsupported: {f}"))
616                    })?;
617                    fields.push(StructField {
618                        name: n.into(),
619                        ty: julia_type(t),
620                    });
621                }
622                i += 1;
623            }
624            if i >= lines.len() {
625                return Err(JuliaParseError(format!("unterminated struct {name}")));
626            }
627            i += 1;
628            structs.push(StructDef {
629                name: name.trim().into(),
630                fields,
631            });
632            continue;
633        }
634        if line.starts_with("function ") {
635            let (name, params, return_type) = parse_signature(line)?;
636            i += 1;
637            let (body, _) = parse_block(&lines, &mut i, false)?;
638            functions.push(Function {
639                name,
640                params,
641                return_type,
642                body,
643            });
644            continue;
645        }
646        // Generated keyword constructor helpers are safe to ignore for the neutral IR.
647        if line.contains("(; ") && line.contains(" = ") {
648            i += 1;
649            continue;
650        }
651        return Err(JuliaParseError(format!(
652            "unsupported Julia top-level syntax: {line}"
653        )));
654    }
655    Ok(Program { structs, functions })
656}