oxilean_codegen/ruby_backend/
rubyexpr_traits.rs1use crate::lcnf::*;
12
13use super::functions::{fmt_ruby_class, fmt_ruby_method, fmt_ruby_module_stmt, fmt_ruby_stmt};
14use super::types::{RubyExpr, RubyLit};
15use std::fmt;
16
17impl fmt::Display for RubyExpr {
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 match self {
20 RubyExpr::Lit(lit) => write!(f, "{}", lit),
21 RubyExpr::Var(name) => write!(f, "{}", name),
22 RubyExpr::BinOp(op, lhs, rhs) => write!(f, "({} {} {})", lhs, op, rhs),
23 RubyExpr::UnaryOp(op, operand) => write!(f, "{}({})", op, operand),
24 RubyExpr::Call(name, args) => {
25 write!(f, "{}(", name)?;
26 for (i, a) in args.iter().enumerate() {
27 if i > 0 {
28 write!(f, ", ")?;
29 }
30 write!(f, "{}", a)?;
31 }
32 write!(f, ")")
33 }
34 RubyExpr::MethodCall(recv, method, args) => {
35 write!(f, "{}.{}(", recv, method)?;
36 for (i, a) in args.iter().enumerate() {
37 if i > 0 {
38 write!(f, ", ")?;
39 }
40 write!(f, "{}", a)?;
41 }
42 write!(f, ")")
43 }
44 RubyExpr::Block(params, stmts) => {
45 write!(f, "{{ ")?;
46 if !params.is_empty() {
47 write!(f, "|{}| ", params.join(", "))?;
48 }
49 for stmt in stmts {
50 write!(f, "{} ", stmt)?;
51 }
52 write!(f, "}}")
53 }
54 RubyExpr::Lambda(params, stmts) => {
55 write!(f, "->(")?;
56 for (i, p) in params.iter().enumerate() {
57 if i > 0 {
58 write!(f, ", ")?;
59 }
60 write!(f, "{}", p)?;
61 }
62 write!(f, ") {{ ")?;
63 for stmt in stmts {
64 write!(f, "{} ", stmt)?;
65 }
66 write!(f, "}}")
67 }
68 RubyExpr::If(cond, then_e, else_e) => {
69 write!(f, "({} ? {} : {})", cond, then_e, else_e)
70 }
71 RubyExpr::Case(scrutinee, branches, default) => {
72 writeln!(f, "case {}", scrutinee)?;
73 for (pat, body) in branches {
74 write!(f, "when {}\n {}\n", pat, body)?;
75 }
76 if let Some(def) = default {
77 write!(f, "else\n {}\n", def)?;
78 }
79 write!(f, "end")
80 }
81 RubyExpr::Array(elems) => {
82 write!(f, "[")?;
83 for (i, e) in elems.iter().enumerate() {
84 if i > 0 {
85 write!(f, ", ")?;
86 }
87 write!(f, "{}", e)?;
88 }
89 write!(f, "]")
90 }
91 RubyExpr::Hash(pairs) => {
92 write!(f, "{{")?;
93 for (i, (k, v)) in pairs.iter().enumerate() {
94 if i > 0 {
95 write!(f, ", ")?;
96 }
97 match k {
98 RubyExpr::Lit(RubyLit::Symbol(name)) => {
99 write!(f, "{}: {}", name, v)?;
100 }
101 _ => {
102 write!(f, "{} => {}", k, v)?;
103 }
104 }
105 }
106 write!(f, "}}")
107 }
108 RubyExpr::Assign(name, rhs) => write!(f, "{} = {}", name, rhs),
109 RubyExpr::Return(expr) => write!(f, "return {}", expr),
110 }
111 }
112}