1use std::collections::HashMap;
2
3use super::chunk::{Chunk, FunctionDef};
4use super::instruction::Instruction;
5use super::opcode::Opcode;
6use super::value::Value;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct Label(u32);
12
13pub(crate) struct ChunkBuilder {
18 name: String,
19 constants: Vec<Value>,
20 code: Vec<Instruction>,
21 functions: Vec<FunctionDef>,
22 next_label: u32,
23 label_targets: HashMap<Label, u32>,
24 pending_jumps: Vec<(usize, Label)>,
26 fn_starts: HashMap<String, u32>,
27}
28
29impl ChunkBuilder {
30 pub fn new(name: impl Into<String>) -> Self {
31 ChunkBuilder {
32 name: name.into(),
33 constants: Vec::new(),
34 code: Vec::new(),
35 functions: Vec::new(),
36 next_label: 0,
37 label_targets: HashMap::new(),
38 pending_jumps: Vec::new(),
39 fn_starts: HashMap::new(),
40 }
41 }
42
43 pub fn const_(&mut self, v: Value) -> u32 {
44 if let Some(pos) = self.constants.iter().position(|c| c == &v) {
47 return pos as u32;
48 }
49 self.constants.push(v);
50 (self.constants.len() - 1) as u32
51 }
52
53 pub fn new_label(&mut self) -> Label {
54 let l = Label(self.next_label);
55 self.next_label += 1;
56 l
57 }
58
59 pub fn bind_label(&mut self, label: Label) {
61 self.label_targets.insert(label, self.code.len() as u32);
62 }
63
64 fn emit(&mut self, instr: Instruction) -> usize {
65 self.code.push(instr);
66 self.code.len() - 1
67 }
68
69 pub fn emit_halt(&mut self) {
70 self.emit(Instruction::nullary(Opcode::Halt));
71 }
72
73 pub fn emit_load_const(&mut self, dst: u8, konst: u32) {
74 self.emit(Instruction::new(Opcode::LoadConst, dst, 0, 0, konst as i32));
75 }
76
77 pub fn emit_load_imm(&mut self, dst: u8, imm: i32) {
78 self.emit(Instruction::a_imm(Opcode::LoadImm, dst, imm));
79 }
80
81 pub fn emit_move(&mut self, dst: u8, src: u8) {
82 self.emit(Instruction::abc(Opcode::Move, dst, src, 0));
83 }
84
85 pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
86 debug_assert!(matches!(
87 op,
88 Opcode::Add
89 | Opcode::Sub
90 | Opcode::Mul
91 | Opcode::Div
92 | Opcode::Mod
93 | Opcode::Eq
94 | Opcode::Lt
95 | Opcode::Le
96 ));
97 self.emit(Instruction::abc(op, dst, lhs, rhs));
98 }
99
100 pub fn emit_neg(&mut self, dst: u8, src: u8) {
101 self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
102 }
103
104 pub fn emit_jump(&mut self, target: Label) {
105 let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
106 self.pending_jumps.push((idx, target));
107 }
108
109 pub fn emit_branch(&mut self, cond: u8, target: Label) {
110 let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
111 self.pending_jumps.push((idx, target));
112 }
113
114 pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
115 self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
116 }
117
118 pub fn emit_spawn_with_rights(
121 &mut self,
122 dst: u8,
123 function: u32,
124 argc: u8,
125 rights: crate::bytecode::CapRights,
126 ) {
127 self.emit(Instruction::new(
128 Opcode::Spawn,
129 dst,
130 argc,
131 rights.bits_u8(),
132 function as i32,
133 ));
134 }
135
136 pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
137 self.emit(Instruction::new(
138 Opcode::Delegate,
139 dst,
140 src_cap,
141 255,
142 rights.bits() as i32,
143 ));
144 }
145
146 pub fn emit_yield(&mut self) {
147 self.emit(Instruction::nullary(Opcode::Yield));
148 }
149
150 pub fn emit_sleep(&mut self, millis_reg: u8) {
151 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
152 }
153
154 pub fn emit_exit(&mut self, reg: u8) {
155 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
156 }
157
158 pub fn emit_self_pid(&mut self, dst: u8) {
161 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
162 }
163
164 pub fn emit_fresh_request_id(&mut self, dst: u8) {
166 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
167 }
168
169 pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
171 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
172 }
173
174 pub fn emit_receive(&mut self, dst: u8) {
175 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
176 }
177
178 pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
179 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
180 }
181
182 pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
184 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
185 }
186
187 pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
189 self.emit(Instruction::a_imm(
190 Opcode::ReceiveMatchImm,
191 dst,
192 i32::from(tag),
193 ));
194 }
195
196 pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
198 self.emit(Instruction::abc(
199 Opcode::ReceiveMatchCorr,
200 dst,
201 tag_reg,
202 id_reg,
203 ));
204 }
205
206 pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
208 self.emit(Instruction::new(
209 Opcode::ReceiveMatchCorrImm,
210 dst,
211 id_reg,
212 0,
213 i32::from(tag),
214 ));
215 }
216
217 pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
219 self.emit(Instruction::a_imm(
220 Opcode::ReceiveMatchKind,
221 dst,
222 i32::from(kind),
223 ));
224 }
225
226 pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
234 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
235 }
236
237 pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
239 self.emit(Instruction::new(
240 Opcode::AskTimeout,
241 dest,
242 target_cap_reg,
243 msg_reg,
244 i32::from(millis_reg),
245 ));
246 }
247
248 pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
249 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
250 }
251
252 pub fn emit_demonitor(&mut self, monitor_reg: u8) {
253 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
254 }
255
256 pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
257 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
258 }
259
260 pub fn emit_unlink(&mut self, link_reg: u8) {
261 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
262 }
263
264 pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
265 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
266 }
267
268 pub fn emit_set_restart_policy(&mut self, policy: u8) {
270 self.emit(Instruction::only_imm(
271 Opcode::SetRestartPolicy,
272 i32::from(policy),
273 ));
274 }
275
276 pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
280 self.emit(Instruction::new(
281 Opcode::HostAwait,
282 dst,
283 args_reg,
284 0,
285 op as i32,
286 ));
287 }
288
289 pub fn emit_register_name(&mut self, name_reg: u8) {
290 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
291 }
292
293 pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
294 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
295 }
296
297 pub fn emit_trap(&mut self, code: i32) {
298 self.emit(Instruction::only_imm(Opcode::Trap, code));
299 }
300
301 pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
302 self.emit(Instruction::new(
303 Opcode::Call,
304 dst,
305 argc,
306 0,
307 function as i32,
308 ));
309 }
310
311 pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
318 self.emit(Instruction::new(
319 Opcode::CallNative,
320 dst,
321 argc,
322 0,
323 native_index as i32,
324 ));
325 }
326
327 pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
349 self.emit_move(dst, src);
350 self.emit_call_native(dst, native_index, 1);
351 }
352
353 pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
359 self.emit_call_native(base, native_index, argc);
360 }
361
362 pub fn emit_return(&mut self, reg: u8) {
363 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
364 }
365
366 pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
372 let name = name.into();
373 let entry = self.code.len() as u32;
374 let idx = self.functions.len() as u32;
375 self.functions.push(FunctionDef {
376 name: name.clone(),
377 entry,
378 arity,
379 num_registers,
380 });
381 self.fn_starts.insert(name, idx);
382 idx
383 }
384
385 pub fn function_index(&self, name: &str) -> Option<u32> {
386 self.fn_starts.get(name).copied()
387 }
388
389 pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
394 if let Some(def) = self.functions.get_mut(function_index as usize) {
395 def.num_registers = num_registers;
396 }
397 }
398
399 pub fn finish(mut self) -> Chunk {
407 for (idx, label) in self.pending_jumps.drain(..) {
408 match self.label_targets.get(&label) {
409 Some(target) => {
410 let offset = *target as i64 - (idx as i64 + 1);
412 self.code[idx].imm = offset as i32;
413 }
414 None => {
415 self.code[idx].imm = 0;
417 }
418 }
419 }
420 Chunk {
421 name: self.name,
422 constants: self.constants,
423 code: self.code,
424 functions: self.functions,
425 }
426 }
427}
428#[cfg(test)]
429mod tests {
430 use super::*;
431
432 #[test]
433 fn emit_native1_from_never_clobbers_source_register() {
434 let mut b = ChunkBuilder::new("clobber-test");
435 b.begin_function("main", 0, 8);
436 b.emit_native1_from(1, 0, 10);
437 b.emit_native1_from(2, 0, 11);
438 b.emit_native1_from(3, 0, 12);
439 let chunk = b.finish();
440
441 assert_eq!(chunk.code.len(), 6);
442 for (move_idx, call_idx, expected_native) in
443 [(0usize, 1usize, 10i32), (2, 3, 11), (4, 5, 12)]
444 {
445 assert_eq!(chunk.code[move_idx].op, Opcode::Move);
446 assert_eq!(chunk.code[move_idx].b, 0);
447 assert_eq!(chunk.code[call_idx].op, Opcode::CallNative);
448 assert_ne!(chunk.code[call_idx].a, 0);
449 assert_eq!(chunk.code[call_idx].imm, expected_native);
450 }
451 }
452
453 #[test]
454 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
455 let mut b = ChunkBuilder::new("native-n-test");
456 b.begin_function("main", 0, 8);
457 b.emit_load_imm(1, 7);
458 b.emit_load_imm(2, 1);
459 b.emit_native_n(1, 99, 2);
460 let chunk = b.finish();
461
462 assert_eq!(chunk.code.len(), 3);
463 assert_eq!(chunk.code[2].op, Opcode::CallNative);
464 assert_eq!(chunk.code[2].a, 1);
465 assert_eq!(chunk.code[2].b, 2);
466 assert_eq!(chunk.code[2].imm, 99);
467 }
468
469 #[test]
470 fn macro_forms_produce_identical_bytecode_to_the_methods() {
471 let mut via_method = ChunkBuilder::new("via-method");
472 via_method.begin_function("main", 0, 8);
473 via_method.emit_native1_from(1, 0, 10);
474 via_method.emit_native_n(1, 99, 2);
475
476 let mut via_macro = ChunkBuilder::new("via-macro");
477 via_macro.begin_function("main", 0, 8);
478 crate::emit_native1_from!(via_macro, 1, 0, 10);
479 crate::emit_native_n!(via_macro, 1, 99, 2);
480
481 assert_eq!(via_method.finish().code, via_macro.finish().code);
482 }
483}