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_record_pack(&mut self, dst: u8, base: u8, count: i32) {
141 self.emit(Instruction::new(Opcode::RecordPack, dst, base, 0, count));
142 }
143
144 pub fn emit_record_get(&mut self, dst: u8, src: u8, index: i32) {
145 self.emit(Instruction::new(Opcode::RecordGet, dst, src, 0, index));
146 }
147
148 pub fn emit_record_len(&mut self, dst: u8, src: u8) {
149 self.emit(Instruction::abc(Opcode::RecordLen, dst, src, 0));
150 }
151
152 pub fn emit_map_pack(&mut self, dst: u8, base: u8, pairs: i32) {
153 self.emit(Instruction::new(Opcode::MapPack, dst, base, 0, pairs));
154 }
155
156 pub fn emit_map_get(&mut self, dst: u8, map: u8, key: u8) {
157 self.emit(Instruction::abc(Opcode::MapGet, dst, map, key));
158 }
159
160 pub fn emit_map_len(&mut self, dst: u8, map: u8) {
161 self.emit(Instruction::abc(Opcode::MapLen, dst, map, 0));
162 }
163
164 pub fn emit_receive_match_cmp(
165 &mut self,
166 dst: u8,
167 tag: u8,
168 bound: u8,
169 cmp: super::opcode::IntCmp,
170 ) {
171 self.emit(Instruction::new(
172 Opcode::ReceiveMatchCmp,
173 dst,
174 tag,
175 bound,
176 cmp.as_imm(),
177 ));
178 }
179
180 pub fn emit_table_open(&mut self, dst: u8, name: u8) {
181 self.emit(Instruction::abc(Opcode::TableOpen, dst, name, 0));
182 }
183
184 pub fn emit_table_get(&mut self, dst: u8, cap: u8, key: u8) {
185 self.emit(Instruction::abc(Opcode::TableGet, dst, cap, key));
186 }
187
188 pub fn emit_table_put(&mut self, cap: u8, key: u8, value: u8) {
189 self.emit(Instruction::abc(Opcode::TablePut, cap, key, value));
190 }
191
192 pub fn emit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) {
193 debug_assert!(matches!(
194 op,
195 Opcode::Add
196 | Opcode::Sub
197 | Opcode::Mul
198 | Opcode::Div
199 | Opcode::Mod
200 | Opcode::Eq
201 | Opcode::Lt
202 | Opcode::Le
203 ));
204 self.emit(Instruction::abc(op, dst, lhs, rhs));
205 }
206
207 pub fn emit_neg(&mut self, dst: u8, src: u8) {
208 self.emit(Instruction::abc(Opcode::Neg, dst, src, 0));
209 }
210
211 pub fn emit_jump(&mut self, target: Label) {
212 let idx = self.emit(Instruction::only_imm(Opcode::Jump, 0));
213 self.pending_jumps.push((idx, target));
214 }
215
216 pub fn emit_branch(&mut self, cond: u8, target: Label) {
217 let idx = self.emit(Instruction::a_imm(Opcode::Branch, cond, 0));
218 self.pending_jumps.push((idx, target));
219 }
220
221 pub fn emit_spawn(&mut self, dst: u8, function: u32, argc: u8) {
222 self.emit_spawn_with_rights(dst, function, argc, crate::bytecode::CapRights::FLOW);
223 }
224
225 pub fn emit_spawn_with_rights(
228 &mut self,
229 dst: u8,
230 function: u32,
231 argc: u8,
232 rights: crate::bytecode::CapRights,
233 ) {
234 self.emit(Instruction::new(
235 Opcode::Spawn,
236 dst,
237 argc,
238 rights.bits_u8(),
239 function as i32,
240 ));
241 }
242
243 pub fn emit_delegate(&mut self, dst: u8, src_cap: u8, rights: crate::bytecode::CapRights) {
244 self.emit_delegate_with_native(dst, src_cap, rights, None);
245 }
246
247 pub fn emit_delegate_with_native(
251 &mut self,
252 dst: u8,
253 src_cap: u8,
254 rights: crate::bytecode::CapRights,
255 native_cap: Option<u8>,
256 ) {
257 let native_reg = match native_cap {
258 Some(reg) => reg,
259 None => 255,
260 };
261 self.emit(Instruction::new(
262 Opcode::Delegate,
263 dst,
264 src_cap,
265 native_reg,
266 rights.bits() as i32,
267 ));
268 }
269
270 pub fn emit_yield(&mut self) {
271 self.emit(Instruction::nullary(Opcode::Yield));
272 }
273
274 pub fn emit_sleep(&mut self, millis_reg: u8) {
275 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
276 }
277
278 pub fn emit_exit(&mut self, reg: u8) {
279 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
280 }
281
282 pub fn emit_self_pid(&mut self, dst: u8) {
285 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
286 }
287
288 pub fn emit_fresh_request_id(&mut self, dst: u8) {
290 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
291 }
292
293 pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
295 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
296 }
297
298 pub fn emit_receive(&mut self, dst: u8) {
299 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
300 }
301
302 pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
303 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
304 }
305
306 pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
308 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
309 }
310
311 pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
313 self.emit(Instruction::a_imm(
314 Opcode::ReceiveMatchImm,
315 dst,
316 i32::from(tag),
317 ));
318 }
319
320 pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
322 self.emit(Instruction::abc(
323 Opcode::ReceiveMatchCorr,
324 dst,
325 tag_reg,
326 id_reg,
327 ));
328 }
329
330 pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
332 self.emit(Instruction::new(
333 Opcode::ReceiveMatchCorrImm,
334 dst,
335 id_reg,
336 0,
337 i32::from(tag),
338 ));
339 }
340
341 pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
343 self.emit(Instruction::abc(
344 Opcode::ReceiveMatchTimeout,
345 dst,
346 tag_reg,
347 millis_reg,
348 ));
349 }
350
351 pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
353 self.emit(Instruction::new(
354 Opcode::ReceiveMatchImmTimeout,
355 dst,
356 millis_reg,
357 0,
358 i32::from(tag),
359 ));
360 }
361
362 pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
364 self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
365 }
366
367 pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
369 self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
370 }
371
372 pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
373 self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
374 }
375
376 pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
377 self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
378 }
379
380 pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
381 self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
382 }
383
384 pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
386 self.emit(Instruction::abc(
387 Opcode::ReceiveMatchEq,
388 dst,
389 tag_reg,
390 payload_reg,
391 ));
392 }
393
394 pub fn emit_receive_match_value(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
396 self.emit(Instruction::abc(
397 Opcode::ReceiveMatchValue,
398 dst,
399 tag_reg,
400 payload_reg,
401 ));
402 }
403
404 pub fn emit_send_remote(&mut self, node_reg: u8, name_reg: u8, msg_reg: u8) {
406 self.emit(Instruction::abc(
407 Opcode::SendRemote,
408 node_reg,
409 name_reg,
410 msg_reg,
411 ));
412 }
413
414 pub fn emit_start_supervisor(&mut self, strategy: u8) {
416 self.emit(Instruction::only_imm(
417 Opcode::StartSupervisor,
418 i32::from(strategy),
419 ));
420 }
421
422 pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
424 self.emit(Instruction::new(
425 Opcode::StartChild,
426 dst,
427 policy,
428 0,
429 match i32::try_from(function) {
430 Ok(n) => n,
431 Err(_) => i32::MAX,
432 },
433 ));
434 }
435
436 pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
438 self.emit(Instruction::a_imm(
439 Opcode::ReceiveMatchKind,
440 dst,
441 i32::from(kind),
442 ));
443 }
444
445 pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
453 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
454 }
455
456 pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
458 self.emit(Instruction::new(
459 Opcode::AskTimeout,
460 dest,
461 target_cap_reg,
462 msg_reg,
463 i32::from(millis_reg),
464 ));
465 }
466
467 pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
468 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
469 }
470
471 pub fn emit_demonitor(&mut self, monitor_reg: u8) {
472 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
473 }
474
475 pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
476 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
477 }
478
479 pub fn emit_unlink(&mut self, link_reg: u8) {
480 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
481 }
482
483 pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
484 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
485 }
486
487 pub fn emit_set_restart_policy(&mut self, policy: u8) {
489 self.emit(Instruction::only_imm(
490 Opcode::SetRestartPolicy,
491 i32::from(policy),
492 ));
493 }
494
495 pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
499 self.emit(Instruction::new(
500 Opcode::HostAwait,
501 dst,
502 args_reg,
503 0,
504 op as i32,
505 ));
506 }
507
508 pub fn emit_register_name(&mut self, name_reg: u8) {
509 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
510 }
511
512 pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
513 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
514 }
515
516 pub fn emit_trap(&mut self, code: i32) {
517 self.emit(Instruction::only_imm(Opcode::Trap, code));
518 }
519
520 pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
521 self.emit(Instruction::new(
522 Opcode::Call,
523 dst,
524 argc,
525 0,
526 function as i32,
527 ));
528 }
529
530 pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
537 self.emit(Instruction::new(
538 Opcode::CallNative,
539 dst,
540 argc,
541 0,
542 native_index as i32,
543 ));
544 }
545
546 pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
560 self.emit(Instruction::new(
561 Opcode::CallNativeFrom,
562 dst,
563 src,
564 0,
565 native_index as i32,
566 ));
567 }
568
569 pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
575 self.emit_call_native(base, native_index, argc);
576 }
577
578 pub fn emit_return(&mut self, reg: u8) {
579 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
580 }
581
582 pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
588 let name = name.into();
589 let entry = self.code.len() as u32;
590 let idx = self.functions.len() as u32;
591 self.functions.push(FunctionDef {
592 name: name.clone(),
593 entry,
594 arity,
595 num_registers,
596 });
597 self.fn_starts.insert(name, idx);
598 idx
599 }
600
601 pub fn function_index(&self, name: &str) -> Option<u32> {
602 self.fn_starts.get(name).copied()
603 }
604
605 pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
610 if let Some(def) = self.functions.get_mut(function_index as usize) {
611 def.num_registers = num_registers;
612 }
613 }
614
615 pub fn finish(mut self) -> Chunk {
622 for (idx, label) in self.pending_jumps.drain(..) {
623 let imm = self.label_targets.get(&label).and_then(|target| {
624 let offset = i64::from(*target) - (idx as i64 + 1);
626 i32::try_from(offset).ok()
627 });
628 match imm {
629 Some(imm) => self.code[idx].imm = imm,
630 None => {
631 self.code[idx].op = Opcode::Trap;
632 self.code[idx].imm = 0;
633 }
634 }
635 }
636 Chunk {
637 name: self.name,
638 constants: self.constants,
639 code: self.code,
640 functions: self.functions,
641 }
642 }
643}
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 #[test]
649 fn unbound_label_becomes_a_trap() {
650 let mut b = ChunkBuilder::new("t");
651 b.begin_function("main", 0, 1);
652 let missing = b.new_label();
653 b.emit_jump(missing);
654 b.emit_return(0);
655 let chunk = b.finish();
656 assert_eq!(chunk.code[0].op, Opcode::Trap);
657 }
658
659 #[test]
660 fn emit_native1_from_never_clobbers_source_register() {
661 let mut b = ChunkBuilder::new("clobber-test");
662 b.begin_function("main", 0, 8);
663 b.emit_native1_from(1, 0, 10);
664 b.emit_native1_from(2, 0, 11);
665 b.emit_native1_from(3, 0, 12);
666 let chunk = b.finish();
667
668 assert_eq!(chunk.code.len(), 3);
669 for (idx, dest, expected_native) in [(0usize, 1u8, 10i32), (1, 2, 11), (2, 3, 12)] {
670 let instr = chunk.code[idx];
671 assert_eq!(instr.op, Opcode::CallNativeFrom);
672 assert_eq!(instr.b, 0, "source register stays r0");
673 assert_eq!(instr.a, dest);
674 assert_ne!(instr.a, instr.b);
675 assert_eq!(instr.imm, expected_native);
676 }
677 }
678
679 #[test]
680 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
681 let mut b = ChunkBuilder::new("native-n-test");
682 b.begin_function("main", 0, 8);
683 b.emit_load_imm(1, 7);
684 b.emit_load_imm(2, 1);
685 b.emit_native_n(1, 99, 2);
686 let chunk = b.finish();
687
688 assert_eq!(chunk.code.len(), 3);
689 assert_eq!(chunk.code[2].op, Opcode::CallNative);
690 assert_eq!(chunk.code[2].a, 1);
691 assert_eq!(chunk.code[2].b, 2);
692 assert_eq!(chunk.code[2].imm, 99);
693 }
694}