1use crate::ir::{Expr, Function, Param, Program, Stmt, StructDef, StructField, SwitchCase, Type};
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct GoParseError(pub String);
5impl std::fmt::Display for GoParseError {
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 GoParseError {}
11
12fn go_type(s: &str) -> Type {
13 let s = s.trim();
14 if let Some(inner) = s.strip_prefix("[]") {
15 return Type::Slice(Box::new(go_type(inner)));
16 }
17 if let Some(rest) = s.strip_prefix("map[") {
18 if let Some(close) = rest.find(']') {
19 let key = &rest[..close];
20 let value = &rest[close + 1..];
21 return Type::Map(Box::new(go_type(key)), Box::new(go_type(value)));
22 }
23 }
24 match s {
25 "bool" => Type::Bool,
26 "string" => Type::String,
27 "int" => Type::Int,
28 "int8" => Type::Int8,
29 "int16" => Type::Int16,
30 "int32" | "rune" => Type::Int32,
31 "int64" => Type::Int64,
32 "uint" => Type::UInt,
33 "uint8" | "byte" => Type::UInt8,
34 "uint16" => Type::UInt16,
35 "uint32" => Type::UInt32,
36 "uint64" => Type::UInt64,
37 "float32" => Type::Float32,
38 "float64" => Type::Float64,
39 "" => Type::Unit,
40 other => Type::Named(other.to_string()),
41 }
42}
43
44fn parse_return_type(s: &str) -> Result<Option<Type>, GoParseError> {
45 let s = s.trim();
46 if s.is_empty() {
47 return Ok(None);
48 }
49 if s.starts_with('(') && s.ends_with(')') {
50 let inner = &s[1..s.len() - 1];
51 let mut types = Vec::new();
52 for part in split_top_level(inner, ',') {
53 let words: Vec<_> = part.split_whitespace().collect();
54 match words.as_slice() {
55 [ty] => types.push(go_type(ty)),
56 [_name, ty] => types.push(go_type(ty)),
57 _ => {
58 return Err(GoParseError(format!(
59 "unsupported multiple return syntax: {part}"
60 )))
61 }
62 }
63 }
64 return Ok(Some(Type::Tuple(types)));
65 }
66 Ok(Some(go_type(s)))
67}
68
69fn zero_expr(t: &Type) -> Option<Expr> {
70 match t {
71 Type::Bool => Some(Expr::Bool(false)),
72 Type::String => Some(Expr::String(String::new())),
73 Type::Int
74 | Type::Int8
75 | Type::Int16
76 | Type::Int32
77 | Type::Int64
78 | Type::UInt
79 | Type::UInt8
80 | Type::UInt16
81 | Type::UInt32
82 | Type::UInt64 => Some(Expr::Int("0".into())),
83 Type::Float32 | Type::Float64 => Some(Expr::Float("0.0".into())),
84 _ => None,
85 }
86}
87
88fn split_top_level(s: &str, needle: char) -> Vec<String> {
89 let mut out = Vec::new();
90 let mut depth = 0i32;
91 let mut quote = false;
92 let mut esc = false;
93 let mut start = 0usize;
94 for (i, c) in s.char_indices() {
95 if quote {
96 if esc {
97 esc = false;
98 continue;
99 }
100 if c == '\\' {
101 esc = true;
102 continue;
103 }
104 if c == '"' {
105 quote = false;
106 }
107 continue;
108 }
109 match c {
110 '"' => quote = true,
111 '(' | '[' | '{' => depth += 1,
112 ')' | ']' | '}' => depth -= 1,
113 _ if c == needle && depth == 0 => {
114 out.push(s[start..i].trim().to_string());
115 start = i + c.len_utf8();
116 }
117 _ => {}
118 }
119 }
120 out.push(s[start..].trim().to_string());
121 out
122}
123
124fn find_top_level_char(s: &str, needle: char) -> Option<usize> {
125 let mut depth = 0i32;
126 let mut quote = false;
127 let mut esc = false;
128 for (i, c) in s.char_indices() {
129 if quote {
130 if esc {
131 esc = false;
132 continue;
133 }
134 if c == '\\' {
135 esc = true;
136 continue;
137 }
138 if c == '"' {
139 quote = false;
140 }
141 continue;
142 }
143 match c {
144 '"' => quote = true,
145 '(' | '[' | '{' => depth += 1,
146 ')' | ']' | '}' => depth -= 1,
147 _ if c == needle && depth == 0 => return Some(i),
148 _ => {}
149 }
150 }
151 None
152}
153
154fn matching_paren(s: &str, open: usize) -> Option<usize> {
155 let mut depth = 0usize;
156 let mut quote = false;
157 let mut esc = false;
158 for (offset, c) in s[open..].char_indices() {
159 if quote {
160 if esc {
161 esc = false;
162 continue;
163 }
164 if c == '\\' {
165 esc = true;
166 continue;
167 }
168 if c == '"' {
169 quote = false;
170 }
171 continue;
172 }
173 match c {
174 '"' => quote = true,
175 '(' => depth += 1,
176 ')' => {
177 depth = depth.checked_sub(1)?;
178 if depth == 0 {
179 return Some(open + offset);
180 }
181 }
182 _ => {}
183 }
184 }
185 None
186}
187
188fn find_binary(s: &str, ops: &[&str]) -> Option<(usize, &'static str)> {
189 let mut depth = 0i32;
190 let mut quote = false;
191 let b = s.as_bytes();
192 let mut i = s.len();
193 while i > 0 {
194 i -= 1;
195 let c = b[i] as char;
196 if quote {
197 if c == '"' && (i == 0 || b[i - 1] != b'\\') {
198 quote = false;
199 }
200 continue;
201 }
202 match c {
203 '"' => quote = true,
204 ')' | ']' | '}' => depth += 1,
205 '(' | '[' | '{' => depth -= 1,
206 _ => {}
207 }
208 if depth != 0 {
209 continue;
210 }
211 for op in ops {
212 if i + op.len() <= s.len() && &s[i..i + op.len()] == *op {
213 if (op == &"-" || op == &"+") && i == 0 {
214 continue;
215 }
216 let leaked: &'static str = match *op {
217 "||" => "||",
218 "&&" => "&&",
219 "==" => "==",
220 "!=" => "!=",
221 "<=" => "<=",
222 ">=" => ">=",
223 "<" => "<",
224 ">" => ">",
225 "+" => "+",
226 "-" => "-",
227 "*" => "*",
228 "/" => "/",
229 "%" => "%",
230 _ => continue,
231 };
232 return Some((i, leaked));
233 }
234 }
235 }
236 None
237}
238
239pub fn parse_expr(s: &str) -> Result<Expr, GoParseError> {
240 let x = s.trim().trim_end_matches(';').trim();
241 if x.is_empty() {
242 return Err(GoParseError("empty expression".into()));
243 }
244
245 let tuple_parts = split_top_level(x, ',');
246 if tuple_parts.len() > 1 {
247 return tuple_parts
248 .iter()
249 .map(|part| parse_expr(part))
250 .collect::<Result<Vec<_>, _>>()
251 .map(Expr::Tuple);
252 }
253
254 if x == "true" {
255 return Ok(Expr::Bool(true));
256 }
257 if x == "false" {
258 return Ok(Expr::Bool(false));
259 }
260 if x == "nil" {
261 return Ok(Expr::Nil);
262 }
263 if x.starts_with('"') && x.ends_with('"') && x.len() >= 2 {
264 return Ok(Expr::String(x[1..x.len() - 1].to_string()));
265 }
266 if x.parse::<i128>().is_ok() {
267 return Ok(Expr::Int(x.to_string()));
268 }
269 if x.contains('.') && x.parse::<f64>().is_ok() {
270 return Ok(Expr::Float(x.to_string()));
271 }
272
273 for ops in [
274 &["||"][..],
275 &["&&"][..],
276 &["==", "!=", "<=", ">=", "<", ">"][..],
277 &["+", "-"][..],
278 &["*", "/", "%"][..],
279 ] {
280 if let Some((i, op)) = find_binary(x, ops) {
281 let l = parse_expr(&x[..i])?;
282 let r = parse_expr(&x[i + op.len()..])?;
283 return Ok(Expr::Binary {
284 left: Box::new(l),
285 op: op.to_string(),
286 right: Box::new(r),
287 });
288 }
289 }
290 if let Some(rest) = x.strip_prefix('!') {
291 return Ok(Expr::Unary {
292 op: "!".into(),
293 value: Box::new(parse_expr(rest)?),
294 });
295 }
296 if let Some(rest) = x.strip_prefix('-') {
297 return Ok(Expr::Unary {
298 op: "-".into(),
299 value: Box::new(parse_expr(rest)?),
300 });
301 }
302
303 if x.starts_with("[]") && x.ends_with('}') {
304 if let Some(open) = x.find('{') {
305 let element_text = x[2..open].trim();
306 let element_type = if element_text.is_empty() {
307 None
308 } else {
309 Some(Box::new(go_type(element_text)))
310 };
311 let inside = &x[open + 1..x.len() - 1];
312 let mut items = Vec::new();
313 if !inside.trim().is_empty() {
314 for item in split_top_level(inside, ',') {
315 items.push(parse_expr(&item)?);
316 }
317 }
318 return Ok(Expr::Array {
319 items,
320 element_type,
321 });
322 }
323 }
324
325 if x.starts_with("map[") && x.ends_with('}') {
327 if let Some(open) = x.find('{') {
328 let ty_text = x[..open].trim();
329 if let Type::Map(key_type, value_type) = go_type(ty_text) {
330 let inside = &x[open + 1..x.len() - 1];
331 let mut entries = Vec::new();
332 if !inside.trim().is_empty() {
333 for part in split_top_level(inside, ',') {
334 let colon = find_top_level_char(&part, ':').ok_or_else(|| {
335 GoParseError(format!("map literal entry needs key:value: {part}"))
336 })?;
337 entries
338 .push((parse_expr(&part[..colon])?, parse_expr(&part[colon + 1..])?));
339 }
340 }
341 return Ok(Expr::Map {
342 key_type,
343 value_type,
344 entries,
345 });
346 }
347 }
348 }
349
350 if x.ends_with('}') {
352 if let Some(open) = x.find('{') {
353 let ty = x[..open].trim();
354 if !ty.is_empty()
355 && ty
356 .chars()
357 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
358 {
359 let inside = &x[open + 1..x.len() - 1];
360 let parts = if inside.trim().is_empty() {
361 Vec::new()
362 } else {
363 split_top_level(inside, ',')
364 };
365 let keyed = parts.iter().any(|p| find_top_level_char(p, ':').is_some());
366 if keyed {
367 let mut fields = Vec::new();
368 for part in parts {
369 let colon = find_top_level_char(&part, ':').ok_or_else(|| {
370 GoParseError("cannot mix keyed and positional struct fields".into())
371 })?;
372 let name = part[..colon].trim();
373 if name.is_empty() {
374 return Err(GoParseError("empty struct field name".into()));
375 }
376 fields.push((name.to_string(), parse_expr(&part[colon + 1..])?));
377 }
378 return Ok(Expr::StructLiteral {
379 ty: ty.to_string(),
380 fields,
381 positional: Vec::new(),
382 });
383 }
384 let positional = parts
385 .iter()
386 .map(|part| parse_expr(part))
387 .collect::<Result<Vec<_>, _>>()?;
388 return Ok(Expr::StructLiteral {
389 ty: ty.to_string(),
390 fields: Vec::new(),
391 positional,
392 });
393 }
394 }
395 }
396
397 if x.ends_with(')') {
398 if let Some(open) = x.find('(') {
399 let fun = x[..open].trim();
400 if !fun.is_empty() {
401 let inside = &x[open + 1..x.len() - 1];
402 let mut args = Vec::new();
403 if !inside.trim().is_empty() {
404 for a in split_top_level(inside, ',') {
405 args.push(parse_expr(&a)?);
406 }
407 }
408 return Ok(Expr::Call {
409 function: fun.to_string(),
410 args,
411 });
412 }
413 }
414 }
415 if x.ends_with(']') {
416 if let Some(open) = x.rfind('[') {
417 return Ok(Expr::Index {
418 value: Box::new(parse_expr(&x[..open])?),
419 index: Box::new(parse_expr(&x[open + 1..x.len() - 1])?),
420 });
421 }
422 }
423 if x.chars()
424 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.')
425 {
426 return Ok(Expr::Ident(x.to_string()));
427 }
428 Ok(Expr::Raw(x.to_string()))
429}
430
431fn parse_params(s: &str) -> Result<Vec<Param>, GoParseError> {
432 if s.trim().is_empty() {
433 return Ok(Vec::new());
434 }
435 let chunks = split_top_level(s, ',');
436 let mut out = Vec::new();
437 let mut pending_names: Vec<String> = Vec::new();
438 for item in chunks {
439 let words: Vec<&str> = item.split_whitespace().collect();
440 match words.as_slice() {
441 [name] => pending_names.push((*name).to_string()),
442 [name, ty] => {
443 pending_names.push((*name).to_string());
444 for n in pending_names.drain(..) {
445 out.push(Param {
446 name: n,
447 ty: go_type(ty),
448 });
449 }
450 }
451 _ => {
452 return Err(GoParseError(format!(
453 "unsupported Go parameter syntax: {item}"
454 )))
455 }
456 }
457 }
458 if !pending_names.is_empty() {
459 return Err(GoParseError("parameter group missing type".into()));
460 }
461 Ok(out)
462}
463
464#[derive(Debug)]
465enum Frame {
466 Function(Function),
467 If {
468 cond: Expr,
469 then_body: Vec<Stmt>,
470 else_body: Vec<Stmt>,
471 in_else: bool,
472 },
473 While {
474 cond: Expr,
475 body: Vec<Stmt>,
476 },
477 ForEach {
478 value: String,
479 iter: Expr,
480 body: Vec<Stmt>,
481 },
482 ForClassic {
483 cond: Expr,
484 body: Vec<Stmt>,
485 post: Box<Stmt>,
486 },
487 Switch {
488 value: Option<Expr>,
489 cases: Vec<SwitchCase>,
490 default: Vec<Stmt>,
491 active_case: Option<usize>,
492 in_default: bool,
493 },
494}
495
496fn push_stmt(frames: &mut [Frame], stmt: Stmt) -> Result<(), GoParseError> {
497 let top = frames
498 .last_mut()
499 .ok_or_else(|| GoParseError("statement outside function".into()))?;
500 match top {
501 Frame::Function(f) => f.body.push(stmt),
502 Frame::If {
503 then_body,
504 else_body,
505 in_else,
506 ..
507 } => {
508 if *in_else {
509 else_body.push(stmt)
510 } else {
511 then_body.push(stmt)
512 }
513 }
514 Frame::While { body, .. } => body.push(stmt),
515 Frame::ForEach { body, .. } => body.push(stmt),
516 Frame::ForClassic { body, .. } => body.push(stmt),
517 Frame::Switch {
518 cases,
519 default,
520 active_case,
521 in_default,
522 ..
523 } => {
524 if *in_default {
525 default.push(stmt);
526 } else if let Some(i) = *active_case {
527 cases[i].body.push(stmt);
528 } else {
529 return Err(GoParseError(
530 "switch statement before first case/default".into(),
531 ));
532 }
533 }
534 }
535 Ok(())
536}
537
538fn contains_continue(body: &[Stmt]) -> bool {
539 body.iter().any(|s| match s {
540 Stmt::Continue => true,
541 Stmt::If {
542 then_body,
543 else_body,
544 ..
545 } => contains_continue(then_body) || contains_continue(else_body),
546 Stmt::While { body, .. } | Stmt::ForEach { body, .. } => contains_continue(body),
547 Stmt::Switch { cases, default, .. } => {
548 cases.iter().any(|c| contains_continue(&c.body)) || contains_continue(default)
549 }
550 _ => false,
551 })
552}
553
554fn contains_break(body: &[Stmt]) -> bool {
555 body.iter().any(|s| match s {
556 Stmt::Break => true,
557 Stmt::If {
558 then_body,
559 else_body,
560 ..
561 } => contains_break(then_body) || contains_break(else_body),
562 Stmt::While { body, .. } | Stmt::ForEach { body, .. } => contains_break(body),
563 Stmt::Switch { cases, default, .. } => {
564 cases.iter().any(|c| contains_break(&c.body)) || contains_break(default)
565 }
566 _ => false,
567 })
568}
569
570fn close_frame(frames: &mut Vec<Frame>, program: &mut Program) -> Result<(), GoParseError> {
571 let frame = frames
572 .pop()
573 .ok_or_else(|| GoParseError("unbalanced closing brace".into()))?;
574 match frame {
575 Frame::Function(f) => {
576 if frames.is_empty() {
577 program.functions.push(f);
578 Ok(())
579 } else {
580 Err(GoParseError("nested Go functions are unsupported".into()))
581 }
582 }
583 Frame::If {
584 cond,
585 then_body,
586 else_body,
587 ..
588 } => push_stmt(
589 frames,
590 Stmt::If {
591 cond,
592 then_body,
593 else_body,
594 },
595 ),
596 Frame::While { cond, body } => push_stmt(frames, Stmt::While { cond, body }),
597 Frame::ForEach { value, iter, body } => {
598 push_stmt(frames, Stmt::ForEach { value, iter, body })
599 }
600 Frame::ForClassic {
601 cond,
602 mut body,
603 post,
604 } => {
605 if contains_continue(&body) {
606 return Err(GoParseError("classic Go for-loop with continue is deferred until post-on-continue lowering is native".into()));
607 }
608 body.push(*post);
609 push_stmt(frames, Stmt::While { cond, body })
610 }
611 Frame::Switch {
612 value,
613 cases,
614 default,
615 ..
616 } => {
617 if cases.iter().any(|c| contains_break(&c.body)) || contains_break(&default) {
618 return Err(GoParseError(
619 "break inside switch is deferred until switch-exit lowering is native".into(),
620 ));
621 }
622 push_stmt(
623 frames,
624 Stmt::Switch {
625 value,
626 cases,
627 default,
628 },
629 )
630 }
631 }
632}
633
634fn parse_inline_stmt(s: &str) -> Result<Stmt, GoParseError> {
635 let s = s.trim().trim_end_matches(';').trim();
636 if let Some(pos) = s.find(":=") {
637 let names = split_top_level(&s[..pos], ',');
638 let value = parse_expr(&s[pos + 2..])?;
639 if names.len() > 1 {
640 return Ok(Stmt::MultiLet {
641 names,
642 value,
643 mutable: true,
644 });
645 }
646 return Ok(Stmt::Let {
647 name: names[0].clone(),
648 ty: None,
649 value,
650 mutable: true,
651 });
652 }
653 if let Some(stripped) = s.strip_suffix("++") {
654 return Ok(Stmt::Assign {
655 target: stripped.trim().into(),
656 op: "+=".into(),
657 value: Expr::Int("1".into()),
658 });
659 }
660 if let Some(stripped) = s.strip_suffix("--") {
661 return Ok(Stmt::Assign {
662 target: stripped.trim().into(),
663 op: "-=".into(),
664 value: Expr::Int("1".into()),
665 });
666 }
667 for op in ["+=", "-=", "*=", "/=", "="] {
668 if let Some(pos) = s.find(op) {
669 if op == "="
670 && (s.contains("==") || s.contains("!=") || s.contains("<=") || s.contains(">="))
671 {
672 continue;
673 }
674 let lhs = &s[..pos];
675 let targets = split_top_level(lhs, ',');
676 if targets.len() > 1 {
677 if op != "=" {
678 return Err(GoParseError(
679 "compound tuple assignment is unsupported".into(),
680 ));
681 }
682 return Ok(Stmt::MultiAssign {
683 targets,
684 value: parse_expr(&s[pos + 1..])?,
685 });
686 }
687 if lhs.contains('[') {
688 match parse_expr(lhs.trim())? {
689 Expr::Index {
690 value: collection,
691 index,
692 } => {
693 return Ok(Stmt::IndexAssign {
694 collection: *collection,
695 index: *index,
696 op: op.into(),
697 value: parse_expr(&s[pos + op.len()..])?,
698 map_value_type: None,
699 });
700 }
701 _ => {
702 return Err(GoParseError(
703 "only direct slice/map indexed assignment is native".into(),
704 ));
705 }
706 }
707 }
708 return Ok(Stmt::Assign {
709 target: lhs.trim().into(),
710 op: op.into(),
711 value: parse_expr(&s[pos + op.len()..])?,
712 });
713 }
714 }
715 Ok(Stmt::Expr(parse_expr(s)?))
716}
717
718fn parse_struct_field_line(s: &str) -> Result<Vec<StructField>, GoParseError> {
719 let mut words: Vec<&str> = s.trim_end_matches(';').split_whitespace().collect();
720 if words.len() < 2 {
721 return Err(GoParseError(format!("unsupported struct field: {s}")));
722 }
723 let ty = words.pop().unwrap();
724 let names = words.join(" ");
725 let mut fields = Vec::new();
726 for name in names.split(',').map(str::trim).filter(|x| !x.is_empty()) {
727 fields.push(StructField {
728 name: name.to_string(),
729 ty: go_type(ty),
730 });
731 }
732 Ok(fields)
733}
734
735fn local_expr_type(
736 e: &Expr,
737 env: &std::collections::BTreeMap<String, Type>,
738 functions: &std::collections::BTreeMap<String, Option<Type>>,
739) -> Option<Type> {
740 match e {
741 Expr::Ident(name) => env.get(name).cloned(),
742 Expr::Int(_) => Some(Type::Int),
743 Expr::Float(_) => Some(Type::Float64),
744 Expr::String(_) => Some(Type::String),
745 Expr::Bool(_) => Some(Type::Bool),
746 Expr::Unary { value, .. } => local_expr_type(value, env, functions),
747 Expr::Binary { left, op, .. } => {
748 if matches!(
749 op.as_str(),
750 "==" | "!=" | "<" | "<=" | ">" | ">=" | "&&" | "||"
751 ) {
752 Some(Type::Bool)
753 } else {
754 local_expr_type(left, env, functions)
755 }
756 }
757 Expr::Call { function, .. } => functions.get(function).cloned().flatten(),
758 Expr::Index { value, .. } => match local_expr_type(value, env, functions)? {
759 Type::Slice(inner) => Some(*inner),
760 Type::Map(_, value) => Some(*value),
761 _ => None,
762 },
763 Expr::MapIndex { value_type, .. } => Some((**value_type).clone()),
764 Expr::MapLookupOk { value_type, .. } => {
765 Some(Type::Tuple(vec![(**value_type).clone(), Type::Bool]))
766 }
767 Expr::Array {
768 element_type,
769 items,
770 } => element_type
771 .as_ref()
772 .map(|t| Type::Slice(t.clone()))
773 .or_else(|| {
774 items
775 .first()
776 .and_then(|x| local_expr_type(x, env, functions))
777 .map(|t| Type::Slice(Box::new(t)))
778 }),
779 Expr::Map {
780 key_type,
781 value_type,
782 ..
783 } => Some(Type::Map(key_type.clone(), value_type.clone())),
784 Expr::Tuple(items) => Some(Type::Tuple(
785 items
786 .iter()
787 .map(|x| local_expr_type(x, env, functions))
788 .collect::<Option<Vec<_>>>()?,
789 )),
790 Expr::StructLiteral { ty, .. } => Some(Type::Named(ty.clone())),
791 Expr::Nil | Expr::Raw(_) => None,
792 }
793}
794
795fn annotate_expr(
796 e: &mut Expr,
797 env: &std::collections::BTreeMap<String, Type>,
798 functions: &std::collections::BTreeMap<String, Option<Type>>,
799) {
800 match e {
801 Expr::Unary { value, .. } => annotate_expr(value, env, functions),
802 Expr::Binary { left, right, .. } => {
803 annotate_expr(left, env, functions);
804 annotate_expr(right, env, functions);
805 }
806 Expr::Call { args, .. } => {
807 for arg in args {
808 annotate_expr(arg, env, functions);
809 }
810 }
811 Expr::Index { value, index } => {
812 annotate_expr(value, env, functions);
813 annotate_expr(index, env, functions);
814 if let Some(Type::Map(_, value_type)) = local_expr_type(value, env, functions) {
815 let v = std::mem::replace(value, Box::new(Expr::Nil));
816 let i = std::mem::replace(index, Box::new(Expr::Nil));
817 *e = Expr::MapIndex {
818 value: v,
819 index: i,
820 value_type,
821 };
822 }
823 }
824 Expr::MapIndex { value, index, .. } | Expr::MapLookupOk { value, index, .. } => {
825 annotate_expr(value, env, functions);
826 annotate_expr(index, env, functions);
827 }
828 Expr::Array { items, .. } => {
829 for item in items {
830 annotate_expr(item, env, functions);
831 }
832 }
833 Expr::Map { entries, .. } => {
834 for (key, value) in entries {
835 annotate_expr(key, env, functions);
836 annotate_expr(value, env, functions);
837 }
838 }
839 Expr::Tuple(items) => {
840 for item in items {
841 annotate_expr(item, env, functions);
842 }
843 }
844 Expr::StructLiteral {
845 fields, positional, ..
846 } => {
847 for (_, value) in fields {
848 annotate_expr(value, env, functions);
849 }
850 for value in positional {
851 annotate_expr(value, env, functions);
852 }
853 }
854 Expr::Ident(_)
855 | Expr::Int(_)
856 | Expr::Float(_)
857 | Expr::String(_)
858 | Expr::Bool(_)
859 | Expr::Nil
860 | Expr::Raw(_) => {}
861 }
862}
863
864fn annotate_statements(
865 stmts: &mut [Stmt],
866 env: &mut std::collections::BTreeMap<String, Type>,
867 functions: &std::collections::BTreeMap<String, Option<Type>>,
868) {
869 for stmt in stmts {
870 match stmt {
871 Stmt::Let {
872 name, ty, value, ..
873 } => {
874 annotate_expr(value, env, functions);
875 if let Some(t) = ty
876 .clone()
877 .or_else(|| local_expr_type(value, env, functions))
878 {
879 env.insert(name.clone(), t);
880 }
881 }
882 Stmt::MultiLet { names, value, .. } => {
883 annotate_expr(value, env, functions);
884 if names.len() == 2 {
885 if let Expr::MapIndex {
886 value: map,
887 index,
888 value_type,
889 } = value
890 {
891 let map = std::mem::replace(map, Box::new(Expr::Nil));
892 let index = std::mem::replace(index, Box::new(Expr::Nil));
893 let value_type = value_type.clone();
894 *value = Expr::MapLookupOk {
895 value: map,
896 index,
897 value_type,
898 };
899 }
900 }
901 if let Some(Type::Tuple(types)) = local_expr_type(value, env, functions) {
902 for (name, ty) in names.iter().zip(types) {
903 env.insert(name.clone(), ty);
904 }
905 }
906 }
907 Stmt::Assign { value, .. } | Stmt::MultiAssign { value, .. } | Stmt::Expr(value) => {
908 annotate_expr(value, env, functions)
909 }
910 Stmt::IndexAssign {
911 collection,
912 index,
913 value,
914 map_value_type,
915 ..
916 } => {
917 annotate_expr(collection, env, functions);
918 annotate_expr(index, env, functions);
919 annotate_expr(value, env, functions);
920 if let Some(Type::Map(_, item)) = local_expr_type(collection, env, functions) {
921 *map_value_type = Some((*item).clone());
922 }
923 }
924 Stmt::Print { args, .. } => {
925 for arg in args {
926 annotate_expr(arg, env, functions);
927 }
928 }
929 Stmt::Return(Some(value)) => annotate_expr(value, env, functions),
930 Stmt::Return(None) | Stmt::Break | Stmt::Continue => {}
931 Stmt::If {
932 cond,
933 then_body,
934 else_body,
935 } => {
936 annotate_expr(cond, env, functions);
937 let mut then_env = env.clone();
938 annotate_statements(then_body, &mut then_env, functions);
939 let mut else_env = env.clone();
940 annotate_statements(else_body, &mut else_env, functions);
941 }
942 Stmt::While { cond, body } => {
943 annotate_expr(cond, env, functions);
944 let mut inner = env.clone();
945 annotate_statements(body, &mut inner, functions);
946 }
947 Stmt::ForEach { value, iter, body } => {
948 annotate_expr(iter, env, functions);
949 let iter_type = local_expr_type(iter, env, functions);
950 let mut inner = env.clone();
951 match iter_type {
952 Some(Type::Slice(item)) => {
953 inner.insert(value.clone(), (*item).clone());
954 let original = std::mem::replace(iter, Expr::Nil);
955 *iter = Expr::Call {
956 function: "__go_slice_values".into(),
957 args: vec![original],
958 };
959 }
960 Some(Type::Map(_, item)) => {
961 inner.insert(value.clone(), (*item).clone());
962 let original = std::mem::replace(iter, Expr::Nil);
963 *iter = Expr::Call {
964 function: "__go_map_values".into(),
965 args: vec![original],
966 };
967 }
968 _ => {}
969 }
970 annotate_statements(body, &mut inner, functions);
971 }
972 Stmt::Switch {
973 value,
974 cases,
975 default,
976 } => {
977 if let Some(v) = value {
978 annotate_expr(v, env, functions);
979 }
980 for case in cases {
981 for v in &mut case.values {
982 annotate_expr(v, env, functions);
983 }
984 let mut inner = env.clone();
985 annotate_statements(&mut case.body, &mut inner, functions);
986 }
987 let mut inner = env.clone();
988 annotate_statements(default, &mut inner, functions);
989 }
990 }
991 }
992}
993
994fn annotate_program(program: &mut Program) {
995 let functions = program
996 .functions
997 .iter()
998 .map(|f| (f.name.clone(), f.return_type.clone()))
999 .collect::<std::collections::BTreeMap<_, _>>();
1000 for function in &mut program.functions {
1001 let mut env = function
1002 .params
1003 .iter()
1004 .map(|p| (p.name.clone(), p.ty.clone()))
1005 .collect::<std::collections::BTreeMap<_, _>>();
1006 annotate_statements(&mut function.body, &mut env, &functions);
1007 }
1008}
1009
1010pub fn parse_go(code: &str) -> Result<Program, GoParseError> {
1011 let normalized = code.replace("\r\n", "\n");
1012 let mut program = Program {
1013 structs: Vec::new(),
1014 functions: Vec::new(),
1015 };
1016 let mut frames: Vec<Frame> = Vec::new();
1017 let mut import_block = false;
1018 let mut struct_builder: Option<StructDef> = None;
1019
1020 for (line_no, raw) in normalized.lines().enumerate() {
1021 let mut s = raw.trim();
1022 if s.is_empty() || s.starts_with("//") || s.starts_with("package ") {
1023 continue;
1024 }
1025
1026 if let Some(def) = struct_builder.as_mut() {
1027 if s == "}" {
1028 program.structs.push(struct_builder.take().unwrap());
1029 } else {
1030 def.fields.extend(
1031 parse_struct_field_line(s)
1032 .map_err(|e| GoParseError(format!("line {}: {}", line_no + 1, e.0)))?,
1033 );
1034 }
1035 continue;
1036 }
1037
1038 if import_block {
1039 if s == ")" {
1040 import_block = false;
1041 }
1042 continue;
1043 }
1044 if s.starts_with("import (") {
1045 import_block = true;
1046 continue;
1047 }
1048 if s.starts_with("import ") {
1049 continue;
1050 }
1051
1052 if frames.is_empty() {
1053 if let Some(rest) = s.strip_prefix("type ") {
1054 if let Some(name) = rest.strip_suffix(" struct {") {
1055 struct_builder = Some(StructDef {
1056 name: name.trim().to_string(),
1057 fields: Vec::new(),
1058 });
1059 continue;
1060 }
1061 return Err(GoParseError(format!(
1062 "line {}: only struct type declarations are native so far",
1063 line_no + 1
1064 )));
1065 }
1066 if s.starts_with("const ") || s.starts_with("var ") {
1067 return Err(GoParseError(format!(
1068 "line {}: top-level const/var declarations are not yet native",
1069 line_no + 1
1070 )));
1071 }
1072 }
1073
1074 if s == "}" {
1075 close_frame(&mut frames, &mut program)?;
1076 continue;
1077 }
1078 if s == "} else {" {
1079 match frames.last_mut() {
1080 Some(Frame::If { in_else, .. }) => {
1081 *in_else = true;
1082 continue;
1083 }
1084 _ => {
1085 return Err(GoParseError(format!(
1086 "line {}: else without matching if",
1087 line_no + 1
1088 )))
1089 }
1090 }
1091 }
1092
1093 if let Some(rest) = s.strip_prefix("func ") {
1094 if !frames.is_empty() {
1095 return Err(GoParseError(format!(
1096 "line {}: methods/nested functions are not yet native",
1097 line_no + 1
1098 )));
1099 }
1100 let open = rest
1101 .find('(')
1102 .ok_or_else(|| GoParseError(format!("line {}: malformed function", line_no + 1)))?;
1103 let close = matching_paren(rest, open)
1104 .ok_or_else(|| GoParseError(format!("line {}: malformed function", line_no + 1)))?;
1105 let name = rest[..open].trim().to_string();
1106 let params = parse_params(&rest[open + 1..close])?;
1107 let tail = rest[close + 1..].trim();
1108 if !tail.ends_with('{') {
1109 return Err(GoParseError(format!(
1110 "line {}: function body must open on same line",
1111 line_no + 1
1112 )));
1113 }
1114 let ret = tail[..tail.len() - 1].trim();
1115 let return_type = parse_return_type(ret)?;
1116 frames.push(Frame::Function(Function {
1117 name,
1118 params,
1119 return_type,
1120 body: Vec::new(),
1121 }));
1122 continue;
1123 }
1124
1125 if s.starts_with("if ") && s.ends_with('{') {
1126 let cond = parse_expr(s[3..s.len() - 1].trim())?;
1127 frames.push(Frame::If {
1128 cond,
1129 then_body: Vec::new(),
1130 else_body: Vec::new(),
1131 in_else: false,
1132 });
1133 continue;
1134 }
1135
1136 if (s == "switch {" || s.starts_with("switch ")) && s.ends_with('{') {
1137 let inner = s["switch".len()..s.len() - 1].trim();
1138 let value = if inner.is_empty() {
1139 None
1140 } else {
1141 Some(parse_expr(inner)?)
1142 };
1143 frames.push(Frame::Switch {
1144 value,
1145 cases: Vec::new(),
1146 default: Vec::new(),
1147 active_case: None,
1148 in_default: false,
1149 });
1150 continue;
1151 }
1152 if let Some(case_text) = s.strip_prefix("case ").and_then(|x| x.strip_suffix(':')) {
1153 match frames.last_mut() {
1154 Some(Frame::Switch {
1155 cases,
1156 active_case,
1157 in_default,
1158 ..
1159 }) => {
1160 let values = split_top_level(case_text, ',')
1161 .iter()
1162 .map(|x| parse_expr(x))
1163 .collect::<Result<Vec<_>, _>>()?;
1164 cases.push(SwitchCase {
1165 values,
1166 body: Vec::new(),
1167 });
1168 *active_case = Some(cases.len() - 1);
1169 *in_default = false;
1170 continue;
1171 }
1172 _ => {
1173 return Err(GoParseError(format!(
1174 "line {}: case outside switch",
1175 line_no + 1
1176 )))
1177 }
1178 }
1179 }
1180 if s == "default:" {
1181 match frames.last_mut() {
1182 Some(Frame::Switch {
1183 active_case,
1184 in_default,
1185 ..
1186 }) => {
1187 *active_case = None;
1188 *in_default = true;
1189 continue;
1190 }
1191 _ => {
1192 return Err(GoParseError(format!(
1193 "line {}: default outside switch",
1194 line_no + 1
1195 )))
1196 }
1197 }
1198 }
1199
1200 if s.starts_with("for ") && s.ends_with('{') {
1201 let inner = s[4..s.len() - 1].trim();
1202 if inner.is_empty() {
1203 frames.push(Frame::While {
1204 cond: Expr::Bool(true),
1205 body: Vec::new(),
1206 });
1207 continue;
1208 }
1209 if let Some(pos) = inner.find(":= range ") {
1210 let lhs = inner[..pos].trim();
1211 let iter = parse_expr(inner[pos + 9..].trim())?;
1212 if let Some(value) = lhs.strip_prefix("_,") {
1213 frames.push(Frame::ForEach {
1214 value: value.trim().to_string(),
1215 iter,
1216 body: Vec::new(),
1217 });
1218 continue;
1219 }
1220 return Err(GoParseError(format!("line {}: index-bearing range loops are deferred to preserve Go's zero-based index semantics", line_no + 1)));
1221 }
1222 let clauses = split_top_level(inner, ';');
1223 if clauses.len() == 3 {
1224 if clauses[0].trim().is_empty()
1225 || clauses[1].trim().is_empty()
1226 || clauses[2].trim().is_empty()
1227 {
1228 return Err(GoParseError(format!(
1229 "line {}: partial classic for clauses are not yet native",
1230 line_no + 1
1231 )));
1232 }
1233 let init = parse_inline_stmt(&clauses[0])?;
1234 push_stmt(&mut frames, init)?;
1235 let cond = parse_expr(&clauses[1])?;
1236 let post = parse_inline_stmt(&clauses[2])?;
1237 frames.push(Frame::ForClassic {
1238 cond,
1239 body: Vec::new(),
1240 post: Box::new(post),
1241 });
1242 continue;
1243 }
1244 frames.push(Frame::While {
1245 cond: parse_expr(inner)?,
1246 body: Vec::new(),
1247 });
1248 continue;
1249 }
1250
1251 if s.starts_with("defer ") || s.starts_with("go ") || s == "fallthrough" {
1252 return Err(GoParseError(format!(
1253 "line {}: unsupported Go control syntax: {s}",
1254 line_no + 1
1255 )));
1256 }
1257
1258 s = s.trim_end_matches(';').trim();
1259 if s == "break" {
1260 push_stmt(&mut frames, Stmt::Break)?;
1261 continue;
1262 }
1263 if s == "continue" {
1264 push_stmt(&mut frames, Stmt::Continue)?;
1265 continue;
1266 }
1267 if s == "return" {
1268 push_stmt(&mut frames, Stmt::Return(None))?;
1269 continue;
1270 }
1271 if let Some(v) = s.strip_prefix("return ") {
1272 push_stmt(&mut frames, Stmt::Return(Some(parse_expr(v)?)))?;
1273 continue;
1274 }
1275
1276 for (prefix, newline) in [("fmt.Println(", true), ("fmt.Print(", false)] {
1277 if let Some(inner) = s.strip_prefix(prefix).and_then(|v| v.strip_suffix(')')) {
1278 let mut args = Vec::new();
1279 if !inner.trim().is_empty() {
1280 for a in split_top_level(inner, ',') {
1281 args.push(parse_expr(&a)?);
1282 }
1283 }
1284 push_stmt(&mut frames, Stmt::Print { newline, args })?;
1285 s = "";
1286 break;
1287 }
1288 }
1289 if s.is_empty() {
1290 continue;
1291 }
1292
1293 if let Some(pos) = s.find(":=") {
1294 let names = split_top_level(&s[..pos], ',');
1295 let value = parse_expr(&s[pos + 2..])?;
1296 if names.len() > 1 {
1297 push_stmt(
1298 &mut frames,
1299 Stmt::MultiLet {
1300 names,
1301 value,
1302 mutable: true,
1303 },
1304 )?;
1305 } else {
1306 push_stmt(
1307 &mut frames,
1308 Stmt::Let {
1309 name: names[0].clone(),
1310 ty: None,
1311 value,
1312 mutable: true,
1313 },
1314 )?;
1315 }
1316 continue;
1317 }
1318 if let Some(rest) = s.strip_prefix("var ") {
1319 let mut parts = rest
1320 .splitn(3, char::is_whitespace)
1321 .filter(|x| !x.is_empty());
1322 let name = parts
1323 .next()
1324 .ok_or_else(|| GoParseError("malformed var".into()))?;
1325 let ty_s = parts
1326 .next()
1327 .ok_or_else(|| GoParseError("typed var requires type".into()))?;
1328 let tail = parts.next().unwrap_or("").trim();
1329 let declared = go_type(ty_s);
1330 let value = if let Some(stripped) = tail.strip_prefix('=') {
1331 parse_expr(stripped.trim())?
1332 } else {
1333 zero_expr(&declared).ok_or_else(|| {
1334 GoParseError(format!(
1335 "line {}: zero value not yet native for type {ty_s}",
1336 line_no + 1
1337 ))
1338 })?
1339 };
1340 push_stmt(
1341 &mut frames,
1342 Stmt::Let {
1343 name: name.into(),
1344 ty: Some(declared),
1345 value,
1346 mutable: true,
1347 },
1348 )?;
1349 continue;
1350 }
1351 if let Some(stripped) = s.strip_suffix("++") {
1352 push_stmt(
1353 &mut frames,
1354 Stmt::Assign {
1355 target: stripped.trim().into(),
1356 op: "+=".into(),
1357 value: Expr::Int("1".into()),
1358 },
1359 )?;
1360 continue;
1361 }
1362 if let Some(stripped) = s.strip_suffix("--") {
1363 push_stmt(
1364 &mut frames,
1365 Stmt::Assign {
1366 target: stripped.trim().into(),
1367 op: "-=".into(),
1368 value: Expr::Int("1".into()),
1369 },
1370 )?;
1371 continue;
1372 }
1373
1374 let mut assigned = false;
1375 for op in ["+=", "-=", "*=", "/=", "="] {
1376 if let Some(pos) = s.find(op) {
1377 if op == "="
1378 && (s.contains("==")
1379 || s.contains("!=")
1380 || s.contains("<=")
1381 || s.contains(">="))
1382 {
1383 continue;
1384 }
1385 let targets = split_top_level(&s[..pos], ',');
1386 if targets.len() > 1 {
1387 if op != "=" {
1388 return Err(GoParseError(format!(
1389 "line {}: compound tuple assignment unsupported",
1390 line_no + 1
1391 )));
1392 }
1393 push_stmt(
1394 &mut frames,
1395 Stmt::MultiAssign {
1396 targets,
1397 value: parse_expr(&s[pos + 1..])?,
1398 },
1399 )?;
1400 } else {
1401 if targets[0].contains('[') {
1402 match parse_expr(targets[0].trim())? {
1403 Expr::Index {
1404 value: collection,
1405 index,
1406 } => {
1407 push_stmt(
1408 &mut frames,
1409 Stmt::IndexAssign {
1410 collection: *collection,
1411 index: *index,
1412 op: op.into(),
1413 value: parse_expr(&s[pos + op.len()..])?,
1414 map_value_type: None,
1415 },
1416 )?;
1417 }
1418 _ => {
1419 return Err(GoParseError(format!(
1420 "line {}: only direct slice/map indexed assignment is native",
1421 line_no + 1
1422 )));
1423 }
1424 }
1425 } else {
1426 push_stmt(
1427 &mut frames,
1428 Stmt::Assign {
1429 target: targets[0].clone(),
1430 op: op.into(),
1431 value: parse_expr(&s[pos + op.len()..])?,
1432 },
1433 )?;
1434 }
1435 }
1436 assigned = true;
1437 break;
1438 }
1439 }
1440 if assigned {
1441 continue;
1442 }
1443 push_stmt(&mut frames, Stmt::Expr(parse_expr(s)?))?;
1444 }
1445
1446 if struct_builder.is_some() {
1447 return Err(GoParseError("unclosed struct declaration".into()));
1448 }
1449 if !frames.is_empty() {
1450 return Err(GoParseError("unbalanced Go blocks at end of file".into()));
1451 }
1452 if program.functions.is_empty() {
1453 return Err(GoParseError("no Go functions found".into()));
1454 }
1455 annotate_program(&mut program);
1456 Ok(program)
1457}