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::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 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 #[allow(dead_code)]
113 pub 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 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 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 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 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 fn emit_bit_not(&mut self, dst: u8, src: u8) {
148 self.emit(Instruction::abc(Opcode::BitNot, dst, src, 0));
149 }
150
151 pub 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 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 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 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 fn emit_bytes_len(&mut self, dst: u8, src: u8) {
170 self.emit(Instruction::abc(Opcode::BytesLen, dst, src, 0));
171 }
172
173 pub 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 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 fn emit_record_len(&mut self, dst: u8, src: u8) {
182 self.emit(Instruction::abc(Opcode::RecordLen, dst, src, 0));
183 }
184
185 pub 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 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 fn emit_map_len(&mut self, dst: u8, map: u8) {
194 self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
195 }
196
197 pub 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 fn emit_table_open(&mut self, dst: u8, name: u8) {
214 self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
215 }
216
217 pub 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 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 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 fn emit_neg(&mut self, dst: u8, src: u8) {
241 self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
242 }
243
244 pub 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 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 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 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 fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
277 self.emit_delegate_with_native(dst, src_cap, rights, None);
278 }
279
280 pub fn emit_delegate_with_native(
284 &mut self,
285 dst: u8,
286 src_cap: u8,
287 rights: crate::bytecode::CapRights,
288 native_cap: Option<u8>,
289 ) {
290 let native_reg = match native_cap {
291 Some(reg) => reg,
292 None => 255,
293 };
294 self.emit(Instruction::new(
295 Opcode::Delegate,
296 dst,
297 src_cap,
298 native_reg,
299 rights.bits() as i32,
300 ));
301 }
302
303 pub fn emit_yield(&mut self) {
304 self.emit(Instruction::nullary(Opcode::Yield));
305 }
306
307 pub fn emit_sleep(&mut self, millis_reg: u8) {
308 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
309 }
310
311 pub fn emit_exit(&mut self, reg: u8) {
312 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
313 }
314
315 pub fn emit_self_pid(&mut self, dst: u8) {
318 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
319 }
320
321 pub fn emit_fresh_request_id(&mut self, dst: u8) {
323 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
324 }
325
326 pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
328 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
329 }
330
331 pub fn emit_receive(&mut self, dst: u8) {
332 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
333 }
334
335 pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
336 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
337 }
338
339 pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
341 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
342 }
343
344 pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
346 self.emit(Instruction::a_imm(
347 Opcode::ReceiveMatchImm,
348 dst,
349 i32::from(tag),
350 ));
351 }
352
353 pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
355 self.emit(Instruction::abc(
356 Opcode::ReceiveMatchCorr,
357 dst,
358 tag_reg,
359 id_reg,
360 ));
361 }
362
363 pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
365 self.emit(Instruction::new(
366 Opcode::ReceiveMatchCorrImm,
367 dst,
368 id_reg,
369 0,
370 i32::from(tag),
371 ));
372 }
373
374 pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
376 self.emit(Instruction::abc(
377 Opcode::ReceiveMatchTimeout,
378 dst,
379 tag_reg,
380 millis_reg,
381 ));
382 }
383
384 pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
386 self.emit(Instruction::new(
387 Opcode::ReceiveMatchImmTimeout,
388 dst,
389 millis_reg,
390 0,
391 i32::from(tag),
392 ));
393 }
394
395 pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
397 self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
398 }
399
400 pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
402 self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
403 }
404
405 pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
406 self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
407 }
408
409 pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
410 self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
411 }
412
413 pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
414 self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
415 }
416
417 pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
419 self.emit(Instruction::abc(
420 Opcode::ReceiveMatchEq,
421 dst,
422 tag_reg,
423 payload_reg,
424 ));
425 }
426
427 pub fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
429 self.emit(Instruction::abc(
430 Opcode::ReceiveMatchValue,
431 dst,
432 tag_reg,
433 payload_reg,
434 ));
435 }
436
437 pub fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
439 self.emit(Instruction::abc(
440 Opcode::SendRemote,
441 node_reg,
442 name_reg,
443 msg_reg,
444 ));
445 }
446
447 pub fn emit_start_supervisor(&mut self, strategy: u8) {
449 self.emit(Instruction::only_imm(
450 Opcode::StartSupervisor,
451 i32::from(strategy),
452 ));
453 }
454
455 pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
457 self.emit(Instruction::new(
458 Opcode::StartChild,
459 dst,
460 policy,
461 0,
462 match i32::try_from(function) {
463 Ok(n) => n,
464 Err(_) => i32::MAX,
465 },
466 ));
467 }
468
469 pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
471 self.emit(Instruction::a_imm(
472 Opcode::ReceiveMatchKind,
473 dst,
474 i32::from(kind),
475 ));
476 }
477
478 pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
486 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
487 }
488
489 pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
491 self.emit(Instruction::new(
492 Opcode::AskTimeout,
493 dest,
494 target_cap_reg,
495 msg_reg,
496 i32::from(millis_reg),
497 ));
498 }
499
500 pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
501 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
502 }
503
504 pub fn emit_demonitor(&mut self, monitor_reg: u8) {
505 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
506 }
507
508 pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
509 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
510 }
511
512 pub fn emit_unlink(&mut self, link_reg: u8) {
513 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
514 }
515
516 pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
517 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
518 }
519
520 pub fn emit_set_restart_policy(&mut self, policy: u8) {
522 self.emit(Instruction::only_imm(
523 Opcode::SetRestartPolicy,
524 i32::from(policy),
525 ));
526 }
527
528 pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
532 self.emit(Instruction::new(
533 Opcode::HostAwait,
534 dst,
535 args_reg,
536 0,
537 op as i32,
538 ));
539 }
540
541 pub fn emit_register_name(&mut self, name_reg: u8) {
542 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
543 }
544
545 pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
546 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
547 }
548
549 pub fn emit_trap(&mut self, code: i32) {
550 self.emit(Instruction::only_imm(Opcode::Trap, code));
551 }
552
553 pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
554 self.emit(Instruction::new(
555 Opcode::Call,
556 dst,
557 argc,
558 0,
559 function as i32,
560 ));
561 }
562
563 pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
570 self.emit(Instruction::new(
571 Opcode::CallNative,
572 dst,
573 argc,
574 0,
575 native_index as i32,
576 ));
577 }
578
579 pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
593 self.emit(Instruction::new(
594 Opcode::CallNativeFrom,
595 dst,
596 src,
597 0,
598 native_index as i32,
599 ));
600 }
601
602 pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
608 self.emit_call_native(base, native_index, argc);
609 }
610
611 pub fn emit_return(&mut self, reg: u8) {
612 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
613 }
614
615 pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
621 let name = name.into();
622 let entry = self.code.len() as u32;
623 let idx = self.functions.len() as u32;
624 self.functions.push(FunctionDef {
625 name: name.clone(),
626 entry,
627 arity,
628 num_registers,
629 });
630 self.fn_starts.insert(name, idx);
631 idx
632 }
633
634 pub fn function_index(&self, name: &str) -> Option<u32> {
635 self.fn_starts.get(name).copied()
636 }
637
638 pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
643 if let Some(def) = self.functions.get_mut(function_index as usize) {
644 def.num_registers = num_registers;
645 }
646 }
647
648 pub fn finish(mut self) -> Chunk {
655 for (idx, label) in self.pending_jumps.drain(..) {
656 let imm = self.label_targets.get(&label).and_then(|target| {
657 let offset = i64::from(*target) - (idx as i64 + 1);
659 i32::try_from(offset).ok()
660 });
661 match imm {
662 Some(imm) => self.code[idx].imm = imm,
663 None => {
664 self.code[idx].op = Opcode::Trap;
665 self.code[idx].imm = 0;
666 }
667 }
668 }
669 Chunk {
670 name: self.name,
671 constants: self.constants,
672 code: self.code,
673 functions: self.functions,
674 }
675 }
676}
677#[cfg(test)]
678mod tests {
679 use super::*;
680
681 #[test]
682 fn unbound_label_becomes_a_trap() {
683 let mut b = ChunkBuilder::new("t");
684 b.begin_function("main", 0, 1);
685 let missing = b.new_label();
686 b.emit_jump(missing);
687 b.emit_return(0);
688 let chunk = b.finish();
689 assert_eq!(chunk.code[0].op, Opcode::Trap);
690 }
691
692 #[test]
693 fn emit_native1_from_never_clobbers_source_register() {
694 let mut b = ChunkBuilder::new("clobber-test");
695 b.begin_function("main", 0, 8);
696 b.emit_native1_from(1, 0, 10);
697 b.emit_native1_from(2, 0, 11);
698 b.emit_native1_from(3, 0, 12);
699 let chunk = b.finish();
700
701 assert_eq!(chunk.code.len(), 3);
702 for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
703 let instr = chunk.code[idx];
704 assert_eq!(instr.op, Opcode::CallNativeFrom);
705 assert_eq!(instr.b, 0, "source register stays r0");
706 assert_eq!(instr.a, dest);
707 assert_ne!(instr.a, instr.b);
708 assert_eq!(instr.imm, expected_native);
709 }
710 }
711
712 #[test]
713 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
714 let mut b = ChunkBuilder::new("native-n-test");
715 b.begin_function("main", 0, 8);
716 b.emit_load_imm(1, 7);
717 b.emit_load_imm(2, 1);
718 b.emit_native_n(1, 99, 2);
719 let chunk = b.finish();
720
721 assert_eq!(chunk.code.len(), 3);
722 assert_eq!(chunk.code[2].op, Opcode::CallNative);
723 assert_eq!(chunk.code[2].a, 1);
724 assert_eq!(chunk.code[2].b, 2);
725 assert_eq!(chunk.code[2].imm, 99);
726 }
727}