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 if dst == src {
83 return;
84 }
85 self.emit(Instruction::abc(Opcode::Move, dst, src, 0));
86 }
87
88 pub fn emit_add_imm(&mut self, dst: u8, src: u8, imm: i32) {
90 self.emit(Instruction::new(Opcode::AddImm, dst, src, 0, imm));
91 }
92
93 pub fn emit_sub_imm(&mut self, dst: u8, src: u8, imm: i32) {
94 self.emit(Instruction::new(Opcode::SubImm, dst, src, 0, imm));
95 }
96
97 pub fn emit_lt_imm(&mut self, dst: u8, src: u8, imm: i32) {
98 self.emit(Instruction::new(Opcode::LtImm, dst, src, 0, imm));
99 }
100
101 pub fn emit_mul_imm(&mut self, dst: u8, src: u8, imm: i32) {
103 self.emit(Instruction::new(Opcode::MulImm, dst, src, 0, imm));
104 }
105
106 pub fn emit_eq_imm(&mut self, dst: u8, src: u8, imm: i32) {
108 self.emit(Instruction::new(Opcode::EqImm, dst, src, 0, imm));
109 }
110
111 pub fn emit_le_imm(&mut self, dst: u8, src: u8, imm: i32) {
113 self.emit(Instruction::new(Opcode::LeImm, dst, src, 0, imm));
114 }
115
116 pub fn emit_bit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
117 debug_assert!(matches!(
118 op,
119 Opcode::BitAnd | Opcode::BitOr | Opcode::BitXor | Opcode::Shl | Opcode::Shr
120 ));
121 self.emit(Instruction::abc(op, dst, lhs, rhs));
122 }
123
124 pub fn emit_bit_not(&mut self, dst: u8, src: u8) {
125 self.emit(Instruction::abc(Opcode::BitNot, dst, src, 0));
126 }
127
128 pub fn emit_list_pack(&mut self, dst: u8, base: u8, count: i32) {
129 self.emit(Instruction::new(Opcode::ListPack, dst, base, 0, count));
130 }
131
132 pub fn emit_list_get(&mut self, dst: u8, src: u8, index: i32) {
133 self.emit(Instruction::new(Opcode::ListGet, dst, src, 0, index));
134 }
135
136 pub fn emit_list_len(&mut self, dst: u8, src: u8) {
137 self.emit(Instruction::abc(Opcode::ListLen, dst, src, 0));
138 }
139
140 pub fn emit_map_pack(&mut self, dst: u8, base: u8, pairs: i32) {
141 self.emit(Instruction::new(Opcode::MapPack, dst, base, 0, pairs));
142 }
143
144 pub fn emit_map_get(&mut self, dst: u8, map: u8, key: u8) {
145 self.emit(Instruction::abc(Opcode::MapGet, dst, map, key));
146 }
147
148 pub fn emit_map_len(&mut self, dst: u8, map: u8) {
149 self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
150 }
151
152 pub fn emit_receive_match_cmp(
153 &mut self,
154 dst: u8,
155 tag: u8,
156 bound: u8,
157 cmp: super::opcode::IntCmp,
158 ) {
159 self.emit(Instruction::new(
160 Opcode::ReceiveMatchCmp,
161 dst,
162 tag,
163 bound,
164 cmp.as_imm(),
165 ));
166 }
167
168 pub fn emit_table_open(&mut self, dst: u8, name: u8) {
169 self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
170 }
171
172 pub fn emit_table_get(&mut self, dst: u8, cap: u8, key: u8) {
173 self.emit(Instruction::abc(Opcode::TableGet, dst, cap, key));
174 }
175
176 pub fn emit_table_put(&mut self, cap: u8, key: u8, value: u8) {
177 self.emit(Instruction::abc(Opcode::TablePut, cap, key, value));
178 }
179
180 pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
181 debug_assert!(matches!(
182 op,
183 Opcode::Add
184 | Opcode::Sub
185 | Opcode::Mul
186 | Opcode::Div
187 | Opcode::Mod
188 | Opcode::Eq
189 | Opcode::Lt
190 | Opcode::Le
191 ));
192 self.emit(Instruction::abc(op, dst, lhs, rhs));
193 }
194
195 pub fn emit_neg(&mut self, dst: u8, src: u8) {
196 self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
197 }
198
199 pub fn emit_jump(&mut self, target: Label) {
200 let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
201 self.pending_jumps.push((idx, target));
202 }
203
204 pub fn emit_branch(&mut self, cond: u8, target: Label) {
205 let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
206 self.pending_jumps.push((idx, target));
207 }
208
209 pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
210 self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
211 }
212
213 pub fn emit_spawn_with_rights(
216 &mut self,
217 dst: u8,
218 function: u32,
219 argc: u8,
220 rights: crate::bytecode::CapRights,
221 ) {
222 self.emit(Instruction::new(
223 Opcode::Spawn,
224 dst,
225 argc,
226 rights.bits_u8(),
227 function as i32,
228 ));
229 }
230
231 pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
232 self.emit_delegate_with_native(dst, src_cap, rights, None);
233 }
234
235 pub fn emit_delegate_with_native(
239 &mut self,
240 dst: u8,
241 src_cap: u8,
242 rights: crate::bytecode::CapRights,
243 native_cap: Option<u8>,
244 ) {
245 let native_reg = match native_cap {
246 Some(reg) => reg,
247 None => 255,
248 };
249 self.emit(Instruction::new(
250 Opcode::Delegate,
251 dst,
252 src_cap,
253 native_reg,
254 rights.bits() as i32,
255 ));
256 }
257
258 pub fn emit_yield(&mut self) {
259 self.emit(Instruction::nullary(Opcode::Yield));
260 }
261
262 pub fn emit_sleep(&mut self, millis_reg: u8) {
263 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
264 }
265
266 pub fn emit_exit(&mut self, reg: u8) {
267 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
268 }
269
270 pub fn emit_self_pid(&mut self, dst: u8) {
273 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
274 }
275
276 pub fn emit_fresh_request_id(&mut self, dst: u8) {
278 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
279 }
280
281 pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
283 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
284 }
285
286 pub fn emit_receive(&mut self, dst: u8) {
287 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
288 }
289
290 pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
291 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
292 }
293
294 pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
296 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
297 }
298
299 pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
301 self.emit(Instruction::a_imm(
302 Opcode::ReceiveMatchImm,
303 dst,
304 i32::from(tag),
305 ));
306 }
307
308 pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
310 self.emit(Instruction::abc(
311 Opcode::ReceiveMatchCorr,
312 dst,
313 tag_reg,
314 id_reg,
315 ));
316 }
317
318 pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
320 self.emit(Instruction::new(
321 Opcode::ReceiveMatchCorrImm,
322 dst,
323 id_reg,
324 0,
325 i32::from(tag),
326 ));
327 }
328
329 pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
331 self.emit(Instruction::abc(
332 Opcode::ReceiveMatchTimeout,
333 dst,
334 tag_reg,
335 millis_reg,
336 ));
337 }
338
339 pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
341 self.emit(Instruction::new(
342 Opcode::ReceiveMatchImmTimeout,
343 dst,
344 millis_reg,
345 0,
346 i32::from(tag),
347 ));
348 }
349
350 pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
352 self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
353 }
354
355 pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
357 self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
358 }
359
360 pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
361 self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
362 }
363
364 pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
365 self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
366 }
367
368 pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
369 self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
370 }
371
372 pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
374 self.emit(Instruction::abc(
375 Opcode::ReceiveMatchEq,
376 dst,
377 tag_reg,
378 payload_reg,
379 ));
380 }
381
382 pub fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
384 self.emit(Instruction::abc(
385 Opcode::ReceiveMatchValue,
386 dst,
387 tag_reg,
388 payload_reg,
389 ));
390 }
391
392 pub fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
394 self.emit(Instruction::abc(
395 Opcode::SendRemote,
396 node_reg,
397 name_reg,
398 msg_reg,
399 ));
400 }
401
402 pub fn emit_start_supervisor(&mut self, strategy: u8) {
404 self.emit(Instruction::only_imm(
405 Opcode::StartSupervisor,
406 i32::from(strategy),
407 ));
408 }
409
410 pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
412 self.emit(Instruction::new(
413 Opcode::StartChild,
414 dst,
415 policy,
416 0,
417 match i32::try_from(function) {
418 Ok(n) => n,
419 Err(_) => i32::MAX,
420 },
421 ));
422 }
423
424 pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
426 self.emit(Instruction::a_imm(
427 Opcode::ReceiveMatchKind,
428 dst,
429 i32::from(kind),
430 ));
431 }
432
433 pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
441 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
442 }
443
444 pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
446 self.emit(Instruction::new(
447 Opcode::AskTimeout,
448 dest,
449 target_cap_reg,
450 msg_reg,
451 i32::from(millis_reg),
452 ));
453 }
454
455 pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
456 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
457 }
458
459 pub fn emit_demonitor(&mut self, monitor_reg: u8) {
460 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
461 }
462
463 pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
464 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
465 }
466
467 pub fn emit_unlink(&mut self, link_reg: u8) {
468 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
469 }
470
471 pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
472 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
473 }
474
475 pub fn emit_set_restart_policy(&mut self, policy: u8) {
477 self.emit(Instruction::only_imm(
478 Opcode::SetRestartPolicy,
479 i32::from(policy),
480 ));
481 }
482
483 pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
487 self.emit(Instruction::new(
488 Opcode::HostAwait,
489 dst,
490 args_reg,
491 0,
492 op as i32,
493 ));
494 }
495
496 pub fn emit_register_name(&mut self, name_reg: u8) {
497 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
498 }
499
500 pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
501 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
502 }
503
504 pub fn emit_trap(&mut self, code: i32) {
505 self.emit(Instruction::only_imm(Opcode::Trap, code));
506 }
507
508 pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
509 self.emit(Instruction::new(
510 Opcode::Call,
511 dst,
512 argc,
513 0,
514 function as i32,
515 ));
516 }
517
518 pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
525 self.emit(Instruction::new(
526 Opcode::CallNative,
527 dst,
528 argc,
529 0,
530 native_index as i32,
531 ));
532 }
533
534 pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
548 self.emit(Instruction::new(
549 Opcode::CallNativeFrom,
550 dst,
551 src,
552 0,
553 native_index as i32,
554 ));
555 }
556
557 pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
563 self.emit_call_native(base, native_index, argc);
564 }
565
566 pub fn emit_return(&mut self, reg: u8) {
567 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
568 }
569
570 pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
576 let name = name.into();
577 let entry = self.code.len() as u32;
578 let idx = self.functions.len() as u32;
579 self.functions.push(FunctionDef {
580 name: name.clone(),
581 entry,
582 arity,
583 num_registers,
584 });
585 self.fn_starts.insert(name, idx);
586 idx
587 }
588
589 pub fn function_index(&self, name: &str) -> Option<u32> {
590 self.fn_starts.get(name).copied()
591 }
592
593 pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
598 if let Some(def) = self.functions.get_mut(function_index as usize) {
599 def.num_registers = num_registers;
600 }
601 }
602
603 pub fn finish(mut self) -> Chunk {
610 for (idx, label) in self.pending_jumps.drain(..) {
611 let imm = self.label_targets.get(&label).and_then(|target| {
612 let offset = i64::from(*target) - (idx as i64 + 1);
614 i32::try_from(offset).ok()
615 });
616 match imm {
617 Some(imm) => self.code[idx].imm = imm,
618 None => {
619 self.code[idx].op = Opcode::Trap;
620 self.code[idx].imm = 0;
621 }
622 }
623 }
624 Chunk {
625 name: self.name,
626 constants: self.constants,
627 code: self.code,
628 functions: self.functions,
629 }
630 }
631}
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 #[test]
637 fn unbound_label_becomes_a_trap() {
638 let mut b = ChunkBuilder::new("t");
639 b.begin_function("main", 0, 1);
640 let missing = b.new_label();
641 b.emit_jump(missing);
642 b.emit_return(0);
643 let chunk = b.finish();
644 assert_eq!(chunk.code[0].op, Opcode::Trap);
645 }
646
647 #[test]
648 fn emit_native1_from_never_clobbers_source_register() {
649 let mut b = ChunkBuilder::new("clobber-test");
650 b.begin_function("main", 0, 8);
651 b.emit_native1_from(1, 0, 10);
652 b.emit_native1_from(2, 0, 11);
653 b.emit_native1_from(3, 0, 12);
654 let chunk = b.finish();
655
656 assert_eq!(chunk.code.len(), 3);
657 for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
658 let instr = chunk.code[idx];
659 assert_eq!(instr.op, Opcode::CallNativeFrom);
660 assert_eq!(instr.b, 0, "source register stays r0");
661 assert_eq!(instr.a, dest);
662 assert_ne!(instr.a, instr.b);
663 assert_eq!(instr.imm, expected_native);
664 }
665 }
666
667 #[test]
668 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
669 let mut b = ChunkBuilder::new("native-n-test");
670 b.begin_function("main", 0, 8);
671 b.emit_load_imm(1, 7);
672 b.emit_load_imm(2, 1);
673 b.emit_native_n(1, 99, 2);
674 let chunk = b.finish();
675
676 assert_eq!(chunk.code.len(), 3);
677 assert_eq!(chunk.code[2].op, Opcode::CallNative);
678 assert_eq!(chunk.code[2].a, 1);
679 assert_eq!(chunk.code[2].b, 2);
680 assert_eq!(chunk.code[2].imm, 99);
681 }
682}