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(crate) fn new(name: impl Into<String>) -> Self {
31 ChunkBuilder {
32 name: name.into(),
33 constants: Vec::with_capacity(32),
34 code: Vec::with_capacity(128),
35 functions: Vec::with_capacity(8),
36 next_label: 0,
37 label_targets: HashMap::with_capacity(16),
38 pending_jumps: Vec::with_capacity(16),
39 fn_starts: HashMap::with_capacity(8),
40 }
41 }
42
43 pub(crate) 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(crate) fn new_label(&mut self) -> Label {
54 let l = Label(self.next_label);
55 self.next_label += 1;
56 l
57 }
58
59 pub(crate) 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(crate) fn emit_halt(&mut self) {
70 self.emit(Instruction::nullary(Opcode::Halt));
71 }
72
73 pub(crate) 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(crate) fn emit_load_imm(&mut self, dst: u8, imm: i32) {
78 self.emit(Instruction::a_imm(Opcode::LoadImm, dst, imm));
79 }
80
81 pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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 #[allow(dead_code)]
113 pub(crate) fn emit_ne_imm(&mut self, dst: u8, src: u8, imm: i32) {
114 self.emit(Instruction::new(Opcode::NeImm, dst, src, 0, imm));
115 }
116
117 pub(crate) fn emit_le_imm(&mut self, dst: u8, src: u8, imm: i32) {
119 self.emit(Instruction::new(Opcode::LeImm, dst, src, 0, imm));
120 }
121
122 #[allow(dead_code)]
124 pub(crate) fn emit_gt_imm(&mut self, dst: u8, src: u8, imm: i32) {
125 self.emit(Instruction::new(Opcode::GtImm, dst, src, 0, imm));
126 }
127
128 #[allow(dead_code)]
130 pub(crate) fn emit_ge_imm(&mut self, dst: u8, src: u8, imm: i32) {
131 self.emit(Instruction::new(Opcode::GeImm, dst, src, 0, imm));
132 }
133
134 pub(crate) fn emit_bit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
135 debug_assert!(matches!(
136 op,
137 Opcode::BitAnd
138 | Opcode::BitOr
139 | Opcode::BitXor
140 | Opcode::Shl
141 | Opcode::Shr
142 | Opcode::Ushr
143 ));
144 self.emit(Instruction::abc(op, dst, lhs, rhs));
145 }
146
147 pub(crate) fn emit_bit_not(&mut self, dst: u8, src: u8) {
148 self.emit(Instruction::abc(Opcode::BitNot, dst, src, 0));
149 }
150
151 pub(crate) fn emit_list_pack(&mut self, dst: u8, base: u8, count: i32) {
152 self.emit(Instruction::new(Opcode::ListPack, dst, base, 0, count));
153 }
154
155 pub(crate) fn emit_list_get(&mut self, dst: u8, src: u8, index: i32) {
156 self.emit(Instruction::new(Opcode::ListGet, dst, src, 0, index));
157 }
158
159 pub(crate) fn emit_list_len(&mut self, dst: u8, src: u8) {
160 self.emit(Instruction::abc(Opcode::ListLen, dst, src, 0));
161 }
162
163 #[allow(dead_code)]
164 pub(crate) fn emit_str_len(&mut self, dst: u8, src: u8) {
165 self.emit(Instruction::abc(Opcode::StrLen, dst, src, 0));
166 }
167
168 #[allow(dead_code)]
169 pub(crate) fn emit_bytes_len(&mut self, dst: u8, src: u8) {
170 self.emit(Instruction::abc(Opcode::BytesLen, dst, src, 0));
171 }
172
173 pub(crate) fn emit_record_pack(&mut self, dst: u8, base: u8, count: i32) {
174 self.emit(Instruction::new(Opcode::RecordPack, dst, base, 0, count));
175 }
176
177 pub(crate) fn emit_record_get(&mut self, dst: u8, src: u8, index: i32) {
178 self.emit(Instruction::new(Opcode::RecordGet, dst, src, 0, index));
179 }
180
181 pub(crate) fn emit_record_len(&mut self, dst: u8, src: u8) {
182 self.emit(Instruction::abc(Opcode::RecordLen, dst, src, 0));
183 }
184
185 pub(crate) fn emit_map_pack(&mut self, dst: u8, base: u8, pairs: i32) {
186 self.emit(Instruction::new(Opcode::MapPack, dst, base, 0, pairs));
187 }
188
189 pub(crate) fn emit_map_get(&mut self, dst: u8, map: u8, key: u8) {
190 self.emit(Instruction::abc(Opcode::MapGet, dst, map, key));
191 }
192
193 pub(crate) fn emit_map_len(&mut self, dst: u8, map: u8) {
194 self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
195 }
196
197 pub(crate) fn emit_receive_match_cmp(
198 &mut self,
199 dst: u8,
200 tag: u8,
201 bound: u8,
202 cmp: super::opcode::IntCmp,
203 ) {
204 self.emit(Instruction::new(
205 Opcode::ReceiveMatchCmp,
206 dst,
207 tag,
208 bound,
209 cmp.as_imm(),
210 ));
211 }
212
213 pub(crate) fn emit_table_open(&mut self, dst: u8, name: u8) {
214 self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
215 }
216
217 pub(crate) fn emit_table_get(&mut self, dst: u8, cap: u8, key: u8) {
218 self.emit(Instruction::abc(Opcode::TableGet, dst, cap, key));
219 }
220
221 pub(crate) fn emit_table_put(&mut self, cap: u8, key: u8, value: u8) {
222 self.emit(Instruction::abc(Opcode::TablePut, cap, key, value));
223 }
224
225 pub(crate) fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
226 debug_assert!(matches!(
227 op,
228 Opcode::Add
229 | Opcode::Sub
230 | Opcode::Mul
231 | Opcode::Div
232 | Opcode::Mod
233 | Opcode::Eq
234 | Opcode::Lt
235 | Opcode::Le
236 ));
237 self.emit(Instruction::abc(op, dst, lhs, rhs));
238 }
239
240 pub(crate) fn emit_neg(&mut self, dst: u8, src: u8) {
241 self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
242 }
243
244 pub(crate) fn emit_jump(&mut self, target: Label) {
245 let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
246 self.pending_jumps.push((idx, target));
247 }
248
249 pub(crate) fn emit_branch(&mut self, cond: u8, target: Label) {
250 let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
251 self.pending_jumps.push((idx, target));
252 }
253
254 pub(crate) fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
255 self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
256 }
257
258 pub(crate) fn emit_spawn_with_rights(
261 &mut self,
262 dst: u8,
263 function: u32,
264 argc: u8,
265 rights: crate::bytecode::CapRights,
266 ) {
267 self.emit(Instruction::new(
268 Opcode::Spawn,
269 dst,
270 argc,
271 rights.bits_u8(),
272 function as i32,
273 ));
274 }
275
276 pub(crate) fn emit_delegate(
277 &mut self,
278 dst: u8,
279 src_cap: u8,
280 rights: crate::bytecode::CapRights,
281 ) {
282 self.emit_delegate_with_native(dst, src_cap, rights, None);
283 }
284
285 pub(crate) fn emit_delegate_with_native(
289 &mut self,
290 dst: u8,
291 src_cap: u8,
292 rights: crate::bytecode::CapRights,
293 native_cap: Option<u8>,
294 ) {
295 let native_reg = match native_cap {
296 Some(reg) => reg,
297 None => 255,
298 };
299 self.emit(Instruction::new(
300 Opcode::Delegate,
301 dst,
302 src_cap,
303 native_reg,
304 rights.bits() as i32,
305 ));
306 }
307
308 pub(crate) fn emit_yield(&mut self) {
309 self.emit(Instruction::nullary(Opcode::Yield));
310 }
311
312 pub(crate) fn emit_sleep(&mut self, millis_reg: u8) {
313 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
314 }
315
316 pub(crate) fn emit_exit(&mut self, reg: u8) {
317 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
318 }
319
320 pub(crate) fn emit_self_pid(&mut self, dst: u8) {
323 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
324 }
325
326 pub(crate) fn emit_fresh_request_id(&mut self, dst: u8) {
328 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
329 }
330
331 pub(crate) fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
333 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
334 }
335
336 pub(crate) fn emit_receive(&mut self, dst: u8) {
337 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
338 }
339
340 pub(crate) fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
341 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
342 }
343
344 pub(crate) fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
346 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
347 }
348
349 pub(crate) fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
351 self.emit(Instruction::a_imm(
352 Opcode::ReceiveMatchImm,
353 dst,
354 i32::from(tag),
355 ));
356 }
357
358 pub(crate) fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
360 self.emit(Instruction::abc(
361 Opcode::ReceiveMatchCorr,
362 dst,
363 tag_reg,
364 id_reg,
365 ));
366 }
367
368 pub(crate) fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
370 self.emit(Instruction::new(
371 Opcode::ReceiveMatchCorrImm,
372 dst,
373 id_reg,
374 0,
375 i32::from(tag),
376 ));
377 }
378
379 pub(crate) fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
381 self.emit(Instruction::abc(
382 Opcode::ReceiveMatchTimeout,
383 dst,
384 tag_reg,
385 millis_reg,
386 ));
387 }
388
389 pub(crate) fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
391 self.emit(Instruction::new(
392 Opcode::ReceiveMatchImmTimeout,
393 dst,
394 millis_reg,
395 0,
396 i32::from(tag),
397 ));
398 }
399
400 pub(crate) fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
402 self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
403 }
404
405 pub(crate) fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
407 self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
408 }
409
410 pub(crate) fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
411 self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
412 }
413
414 pub(crate) fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
415 self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
416 }
417
418 pub(crate) fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
419 self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
420 }
421
422 pub(crate) fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
424 self.emit(Instruction::abc(
425 Opcode::ReceiveMatchEq,
426 dst,
427 tag_reg,
428 payload_reg,
429 ));
430 }
431
432 pub(crate) fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
434 self.emit(Instruction::abc(
435 Opcode::ReceiveMatchValue,
436 dst,
437 tag_reg,
438 payload_reg,
439 ));
440 }
441
442 pub(crate) fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
444 self.emit(Instruction::abc(
445 Opcode::SendRemote,
446 node_reg,
447 name_reg,
448 msg_reg,
449 ));
450 }
451
452 pub(crate) fn emit_start_supervisor(&mut self, strategy: u8) {
454 self.emit(Instruction::only_imm(
455 Opcode::StartSupervisor,
456 i32::from(strategy),
457 ));
458 }
459
460 pub(crate) fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
462 self.emit(Instruction::new(
463 Opcode::StartChild,
464 dst,
465 policy,
466 0,
467 match i32::try_from(function) {
468 Ok(n) => n,
469 Err(_) => i32::MAX,
470 },
471 ));
472 }
473
474 pub(crate) fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
476 self.emit(Instruction::a_imm(
477 Opcode::ReceiveMatchKind,
478 dst,
479 i32::from(kind),
480 ));
481 }
482
483 pub(crate) fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
491 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
492 }
493
494 pub(crate) fn emit_ask_timeout(
496 &mut self,
497 dest: u8,
498 target_cap_reg: u8,
499 msg_reg: u8,
500 millis_reg: u8,
501 ) {
502 self.emit(Instruction::new(
503 Opcode::AskTimeout,
504 dest,
505 target_cap_reg,
506 msg_reg,
507 i32::from(millis_reg),
508 ));
509 }
510
511 pub(crate) fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
512 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
513 }
514
515 pub(crate) fn emit_demonitor(&mut self, monitor_reg: u8) {
516 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
517 }
518
519 pub(crate) fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
520 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
521 }
522
523 pub(crate) fn emit_unlink(&mut self, link_reg: u8) {
524 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
525 }
526
527 pub(crate) fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
528 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
529 }
530
531 pub(crate) fn emit_set_restart_policy(&mut self, policy: u8) {
533 self.emit(Instruction::only_imm(
534 Opcode::SetRestartPolicy,
535 i32::from(policy),
536 ));
537 }
538
539 pub(crate) fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
543 self.emit(Instruction::new(
544 Opcode::HostAwait,
545 dst,
546 args_reg,
547 0,
548 op as i32,
549 ));
550 }
551
552 pub(crate) fn emit_register_name(&mut self, name_reg: u8) {
553 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
554 }
555
556 pub(crate) fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
557 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
558 }
559
560 pub(crate) fn emit_trap(&mut self, code: i32) {
561 self.emit(Instruction::only_imm(Opcode::Trap, code));
562 }
563
564 pub(crate) fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
565 self.emit(Instruction::new(
566 Opcode::Call,
567 dst,
568 argc,
569 0,
570 function as i32,
571 ));
572 }
573
574 pub(crate) fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
581 self.emit(Instruction::new(
582 Opcode::CallNative,
583 dst,
584 argc,
585 0,
586 native_index as i32,
587 ));
588 }
589
590 pub(crate) fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
604 self.emit(Instruction::new(
605 Opcode::CallNativeFrom,
606 dst,
607 src,
608 0,
609 native_index as i32,
610 ));
611 }
612
613 pub(crate) fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
619 self.emit_call_native(base, native_index, argc);
620 }
621
622 pub(crate) fn emit_return(&mut self, reg: u8) {
623 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
624 }
625
626 pub(crate) fn begin_function(
632 &mut self,
633 name: impl Into<String>,
634 arity: u8,
635 num_registers: u8,
636 ) -> u32 {
637 let name = name.into();
638 let entry = self.code.len() as u32;
639 let idx = self.functions.len() as u32;
640 self.functions.push(FunctionDef {
641 name: name.clone(),
642 entry,
643 arity,
644 num_registers,
645 });
646 self.fn_starts.insert(name, idx);
647 idx
648 }
649
650 pub(crate) fn function_index(&self, name: &str) -> Option<u32> {
651 self.fn_starts.get(name).copied()
652 }
653
654 pub(crate) fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
659 if let Some(def) = self.functions.get_mut(function_index as usize) {
660 def.num_registers = num_registers;
661 }
662 }
663
664 pub(crate) fn finish(mut self) -> Chunk {
671 for (idx, label) in self.pending_jumps.drain(..) {
672 let imm = self.label_targets.get(&label).and_then(|target| {
673 let offset = i64::from(*target) - (idx as i64 + 1);
675 i32::try_from(offset).ok()
676 });
677 match imm {
678 Some(imm) => self.code[idx].imm = imm,
679 None => {
680 self.code[idx].op = Opcode::Trap;
681 self.code[idx].imm = 0;
682 }
683 }
684 }
685 Chunk {
686 name: self.name,
687 constants: self.constants,
688 code: self.code,
689 functions: self.functions,
690 }
691 }
692}
693#[cfg(test)]
694mod tests {
695 use super::*;
696
697 #[test]
698 fn unbound_label_becomes_a_trap() {
699 let mut b = ChunkBuilder::new("t");
700 b.begin_function("main", 0, 1);
701 let missing = b.new_label();
702 b.emit_jump(missing);
703 b.emit_return(0);
704 let chunk = b.finish();
705 assert_eq!(chunk.code[0].op, Opcode::Trap);
706 }
707
708 #[test]
709 fn emit_native1_from_never_clobbers_source_register() {
710 let mut b = ChunkBuilder::new("clobber-test");
711 b.begin_function("main", 0, 8);
712 b.emit_native1_from(1, 0, 10);
713 b.emit_native1_from(2, 0, 11);
714 b.emit_native1_from(3, 0, 12);
715 let chunk = b.finish();
716
717 assert_eq!(chunk.code.len(), 3);
718 for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
719 let instr = chunk.code[idx];
720 assert_eq!(instr.op, Opcode::CallNativeFrom);
721 assert_eq!(instr.b, 0, "source register stays r0");
722 assert_eq!(instr.a, dest);
723 assert_ne!(instr.a, instr.b);
724 assert_eq!(instr.imm, expected_native);
725 }
726 }
727
728 #[test]
729 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
730 let mut b = ChunkBuilder::new("native-n-test");
731 b.begin_function("main", 0, 8);
732 b.emit_load_imm(1, 7);
733 b.emit_load_imm(2, 1);
734 b.emit_native_n(1, 99, 2);
735 let chunk = b.finish();
736
737 assert_eq!(chunk.code.len(), 3);
738 assert_eq!(chunk.code[2].op, Opcode::CallNative);
739 assert_eq!(chunk.code[2].a, 1);
740 assert_eq!(chunk.code[2].b, 2);
741 assert_eq!(chunk.code[2].imm, 99);
742 }
743}