oxilean_codegen/go_backend/
goexpr_traits.rs1use crate::lcnf::*;
12
13use super::functions::format_stmts;
14use super::types::GoExpr;
15use std::fmt;
16
17impl fmt::Display for GoExpr {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 match self {
20 GoExpr::Lit(lit) => write!(f, "{}", lit),
21 GoExpr::Var(name) => write!(f, "{}", name),
22 GoExpr::Call(func, args) => {
23 write!(f, "{}(", func)?;
24 for (i, a) in args.iter().enumerate() {
25 if i > 0 {
26 write!(f, ", ")?;
27 }
28 write!(f, "{}", a)?;
29 }
30 write!(f, ")")
31 }
32 GoExpr::BinOp(op, lhs, rhs) => write!(f, "({} {} {})", lhs, op, rhs),
33 GoExpr::Unary(op, operand) => write!(f, "({}{})", op, operand),
34 GoExpr::Field(obj, field) => write!(f, "{}.{}", obj, field),
35 GoExpr::Index(base, idx) => write!(f, "{}[{}]", base, idx),
36 GoExpr::TypeAssert(expr, ty) => write!(f, "{}.({}", expr, ty),
37 GoExpr::Composite(ty, fields) => {
38 write!(f, "{}{{", ty)?;
39 for (i, (name, val)) in fields.iter().enumerate() {
40 if i > 0 {
41 write!(f, ", ")?;
42 }
43 write!(f, "{}: {}", name, val)?;
44 }
45 write!(f, "}}")
46 }
47 GoExpr::SliceLit(elem_ty, elems) => {
48 write!(f, "[]{}{{", elem_ty)?;
49 for (i, e) in elems.iter().enumerate() {
50 if i > 0 {
51 write!(f, ", ")?;
52 }
53 write!(f, "{}", e)?;
54 }
55 write!(f, "}}")
56 }
57 GoExpr::AddressOf(inner) => write!(f, "&{}", inner),
58 GoExpr::Deref(inner) => write!(f, "*{}", inner),
59 GoExpr::FuncLit(params, rets, body) => {
60 write!(f, "func(")?;
61 for (i, (name, ty)) in params.iter().enumerate() {
62 if i > 0 {
63 write!(f, ", ")?;
64 }
65 write!(f, "{} {}", name, ty)?;
66 }
67 write!(f, ")")?;
68 match rets.len() {
69 0 => {}
70 1 => write!(f, " {}", rets[0])?,
71 _ => {
72 write!(f, " (")?;
73 for (i, r) in rets.iter().enumerate() {
74 if i > 0 {
75 write!(f, ", ")?;
76 }
77 write!(f, "{}", r)?;
78 }
79 write!(f, ")")?;
80 }
81 }
82 write!(f, " {{")?;
83 let body_str = format_stmts(body, 1);
84 if !body_str.is_empty() {
85 write!(f, "\n{}\n}}", body_str)?;
86 } else {
87 write!(f, "}}")?;
88 }
89 Ok(())
90 }
91 GoExpr::Make(ty, args) => {
92 write!(f, "make({}", ty)?;
93 for a in args {
94 write!(f, ", {}", a)?;
95 }
96 write!(f, ")")
97 }
98 GoExpr::New(ty) => write!(f, "new({})", ty),
99 }
100 }
101}