1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use super::*;
impl Codegen {
/// Emit a top-level function as a wrapper + body pair, mangled by its file id.
pub(super) fn function(
&self,
span: Span,
emit: &mut Emit,
out: &mut String,
) -> Result<(), Diagnostic> {
let info = self.fn_info(emit, span);
self.emit_callable(
&func_wrapper(emit.file_id, &info.name),
&func_body(emit.file_id, &info.name),
&[],
&info.params,
&info.body,
&info.cell_names,
emit,
out,
)
}
/// Emit an object method as an `mf_`/`mb_` pair. A method is an ordinary
/// callable whose first parameter is the implicit `self` receiver.
pub(super) fn method(
&self,
class: &Class,
span: Span,
emit: &mut Emit,
out: &mut String,
) -> Result<(), Diagnostic> {
let info = self.fn_info(emit, span);
// `params` already carries `self` first (added during analysis).
self.emit_callable(
&format!("{METHOD_PREFIX}{}_{}", class.id, info.name),
&format!("{METHOD_BODY_PREFIX}{}_{}", class.id, info.name),
&[],
&info.params,
&info.body,
&info.cell_names,
emit,
out,
)
}
/// Emit a nested function as a `c_`/`cb_` pair, taking its captured cells as
/// leading parameters.
pub(super) fn closure(
&self,
info: &FnInfo,
emit: &mut Emit,
out: &mut String,
) -> Result<(), Diagnostic> {
let id = info.fn_id.expect("compiler bug: closure without an id");
self.emit_callable(
&format!("{CLOSURE_PREFIX}{id}"),
&format!("{CLOSURE_BODY_PREFIX}{id}"),
&info.captures,
&info.params,
&info.body,
&info.cell_names,
emit,
out,
)
}
/// Emit a wrapper + body pair. The wrapper counts the call against the
/// recursion limit and undoes it on every exit path — even a `?` inside the
/// body — because `exit_call` runs after the body returns. Captured cells lead
/// the parameter list; any local a nested closure captures becomes a `Cell`.
#[allow(clippy::too_many_arguments)]
pub(super) fn emit_callable(
&self,
wrapper_name: &str,
body_name: &str,
captures: &[String],
params: &[String],
body: &[Stmt],
cell_names: &HashSet<String>,
emit: &mut Emit,
out: &mut String,
) -> Result<(), Diagnostic> {
let wrapper_params = signature(captures, params, false);
out.push_str(&format!(
"\nfn {wrapper_name}({wrapper_params}) -> DogeResult<Value> {{\n"
));
out.push_str(" enter_call(&mut env.depth)?;\n");
let call_args = {
let mut v: Vec<String> = captures
.iter()
.chain(params.iter())
.map(|p| format!("{NAME_PREFIX}{p}"))
.collect();
v.push("env".to_string());
v.join(", ")
};
out.push_str(&format!(" let result = {body_name}({call_args});\n"));
out.push_str(" exit_call(&mut env.depth);\n");
out.push_str(" result\n");
out.push_str("}\n");
let body_params = signature(captures, params, true);
out.push_str(&format!(
"\nfn {body_name}({body_params}) -> DogeResult<Value> {{\n"
));
let mut locals: HashMap<String, Local> = HashMap::new();
// Captured cells arrive already shared, as `Cell` parameters.
for name in captures {
locals.insert(name.clone(), Local::Cell);
}
// A value parameter a nested closure captures is rebound to a fresh cell.
for param in params {
if cell_names.contains(param) {
out.push_str(&format!(
" let {NAME_PREFIX}{param} = Rc::new(RefCell::new({NAME_PREFIX}{param}));\n"
));
locals.insert(param.clone(), Local::Cell);
} else {
locals.insert(param.clone(), Local::Plain);
}
}
// Body-hoisted names (including nested-function names) get a fresh binding:
// a `Cell` when captured or a function name, otherwise a plain `Value`.
for name in hoisted_names(body) {
if params.iter().any(|p| p == &name) {
continue;
}
if cell_names.contains(&name) {
out.push_str(&format!(
" let {NAME_PREFIX}{name}: Cell = Rc::new(RefCell::new(Value::None));\n"
));
locals.insert(name, Local::Cell);
} else {
out.push_str(&format!(
" let mut {NAME_PREFIX}{name}: Value = Value::None;\n"
));
locals.insert(name, Local::Plain);
}
}
emit.locals = locals;
emit.local_funcs = child_funcdefs(body)
.into_iter()
.map(|(name, params, _, _)| (name.to_string(), params.clone()))
.collect();
emit.try_stack.clear();
emit.loop_stack.clear();
for stmt in body {
self.stmt(stmt, 1, emit, out)?;
}
// Falling off the end returns none.
out.push_str(" Ok(Value::None)\n");
out.push_str("}\n");
Ok(())
}
/// Emit a constructor `n_<id>`: build a fresh instance tagged with this class,
/// run the effective `init` (this class's, or the nearest ancestor's), and
/// return the object. The callsite wraps the `n_` call in the fail suffix, so
/// the `?` on `init` here is correct.
pub(super) fn constructor(&self, classes: &[Class], class: &Class, out: &mut String) {
let init = effective_init(classes, class);
let init_binding = init
.map(|(_, params)| params.binding_names())
.unwrap_or_default();
let ctor_params = signature(&[], &init_binding, false);
out.push_str(&format!(
"\nfn {CTOR_PREFIX}{}({ctor_params}) -> DogeResult<Value> {{\n",
class.id
));
out.push_str(&format!(
" let obj = Value::object({}u32, \"{}\");\n",
class.id,
escape_str(&class.name)
));
// `init` runs against the defining class's wrapper — an inherited `init`
// dispatches to the ancestor's `mf_`, with the new object as the receiver.
if let Some((def, _)) = init {
let mut args: Vec<String> = vec!["obj.clone()".to_string()];
args.extend(init_binding.iter().map(|p| format!("{NAME_PREFIX}{p}")));
args.push("env".to_string());
out.push_str(&format!(
" {METHOD_PREFIX}{}_init({})?;\n",
def.id,
args.join(", ")
));
}
out.push_str(" Ok(obj)\n");
out.push_str("}\n");
}
}