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_delegate_with_native(dst, src_cap, rights, None);
138 }
139
140 pub fn emit_delegate_with_native(
144 &mut self,
145 dst: u8,
146 src_cap: u8,
147 rights: crate::bytecode::CapRights,
148 native_cap: Option<u8>,
149 ) {
150 let native_reg = match native_cap {
151 Some(reg) => reg,
152 None => 255,
153 };
154 self.emit(Instruction::new(
155 Opcode::Delegate,
156 dst,
157 src_cap,
158 native_reg,
159 rights.bits() as i32,
160 ));
161 }
162
163 pub fn emit_yield(&mut self) {
164 self.emit(Instruction::nullary(Opcode::Yield));
165 }
166
167 pub fn emit_sleep(&mut self, millis_reg: u8) {
168 self.emit(Instruction::abc(Opcode::Sleep, millis_reg, 0, 0));
169 }
170
171 pub fn emit_exit(&mut self, reg: u8) {
172 self.emit(Instruction::abc(Opcode::Exit, reg, 0, 0));
173 }
174
175 pub fn emit_self_pid(&mut self, dst: u8) {
178 self.emit(Instruction::abc(Opcode::SelfPid, dst, 0, 0));
179 }
180
181 pub fn emit_fresh_request_id(&mut self, dst: u8) {
183 self.emit(Instruction::abc(Opcode::FreshRequestId, dst, 0, 0));
184 }
185
186 pub fn emit_send(&mut self, target_cap_reg: u8, msg_reg: u8) {
188 self.emit(Instruction::abc(Opcode::Send, target_cap_reg, msg_reg, 0));
189 }
190
191 pub fn emit_receive(&mut self, dst: u8) {
192 self.emit(Instruction::abc(Opcode::Receive, dst, 0, 0));
193 }
194
195 pub fn emit_receive_timeout(&mut self, dst: u8, millis_reg: u8) {
196 self.emit(Instruction::abc(Opcode::ReceiveTimeout, dst, millis_reg, 0));
197 }
198
199 pub fn emit_receive_match(&mut self, dst: u8, tag_reg: u8) {
201 self.emit(Instruction::abc(Opcode::ReceiveMatch, dst, tag_reg, 0));
202 }
203
204 pub fn emit_receive_match_imm(&mut self, dst: u8, tag: u16) {
206 self.emit(Instruction::a_imm(
207 Opcode::ReceiveMatchImm,
208 dst,
209 i32::from(tag),
210 ));
211 }
212
213 pub fn emit_receive_match_corr(&mut self, dst: u8, tag_reg: u8, id_reg: u8) {
215 self.emit(Instruction::abc(
216 Opcode::ReceiveMatchCorr,
217 dst,
218 tag_reg,
219 id_reg,
220 ));
221 }
222
223 pub fn emit_receive_match_corr_imm(&mut self, dst: u8, tag: u16, id_reg: u8) {
225 self.emit(Instruction::new(
226 Opcode::ReceiveMatchCorrImm,
227 dst,
228 id_reg,
229 0,
230 i32::from(tag),
231 ));
232 }
233
234 pub fn emit_receive_match_timeout(&mut self, dst: u8, tag_reg: u8, millis_reg: u8) {
236 self.emit(Instruction::abc(
237 Opcode::ReceiveMatchTimeout,
238 dst,
239 tag_reg,
240 millis_reg,
241 ));
242 }
243
244 pub fn emit_receive_match_imm_timeout(&mut self, dst: u8, tag: u16, millis_reg: u8) {
246 self.emit(Instruction::new(
247 Opcode::ReceiveMatchImmTimeout,
248 dst,
249 millis_reg,
250 0,
251 i32::from(tag),
252 ));
253 }
254
255 pub fn emit_is_alive(&mut self, dst: u8, cap_reg: u8) {
257 self.emit(Instruction::abc(Opcode::IsAlive, dst, cap_reg, 0));
258 }
259
260 pub fn emit_exit_signal(&mut self, cap_reg: u8, reason_reg: u8) {
262 self.emit(Instruction::abc(Opcode::ExitSignal, cap_reg, reason_reg, 0));
263 }
264
265 pub fn emit_dict_put(&mut self, dst: u8, key_reg: u8, value_reg: u8) {
266 self.emit(Instruction::abc(Opcode::DictPut, dst, key_reg, value_reg));
267 }
268
269 pub fn emit_dict_get(&mut self, dst: u8, key_reg: u8) {
270 self.emit(Instruction::abc(Opcode::DictGet, dst, key_reg, 0));
271 }
272
273 pub fn emit_dict_erase(&mut self, dst: u8, key_reg: u8) {
274 self.emit(Instruction::abc(Opcode::DictErase, dst, key_reg, 0));
275 }
276
277 pub fn emit_receive_match_eq(&mut self, dst: u8, tag_reg: u8, payload_reg: u8) {
279 self.emit(Instruction::abc(
280 Opcode::ReceiveMatchEq,
281 dst,
282 tag_reg,
283 payload_reg,
284 ));
285 }
286
287 pub fn emit_start_child(&mut self, dst: u8, function: u32, policy: u8) {
289 self.emit(Instruction::new(
290 Opcode::StartChild,
291 dst,
292 policy,
293 0,
294 match i32::try_from(function) {
295 Ok(n) => n,
296 Err(_) => i32::MAX,
297 },
298 ));
299 }
300
301 pub fn emit_receive_match_kind(&mut self, dst: u8, kind: u8) {
303 self.emit(Instruction::a_imm(
304 Opcode::ReceiveMatchKind,
305 dst,
306 i32::from(kind),
307 ));
308 }
309
310 pub fn emit_ask(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8) {
318 self.emit(Instruction::abc(Opcode::Ask, dest, target_cap_reg, msg_reg));
319 }
320
321 pub fn emit_ask_timeout(&mut self, dest: u8, target_cap_reg: u8, msg_reg: u8, millis_reg: u8) {
323 self.emit(Instruction::new(
324 Opcode::AskTimeout,
325 dest,
326 target_cap_reg,
327 msg_reg,
328 i32::from(millis_reg),
329 ));
330 }
331
332 pub fn emit_monitor(&mut self, dest: u8, target_cap_reg: u8) {
333 self.emit(Instruction::abc(Opcode::Monitor, dest, target_cap_reg, 0));
334 }
335
336 pub fn emit_demonitor(&mut self, monitor_reg: u8) {
337 self.emit(Instruction::abc(Opcode::Demonitor, monitor_reg, 0, 0));
338 }
339
340 pub fn emit_link(&mut self, dest: u8, target_cap_reg: u8) {
341 self.emit(Instruction::abc(Opcode::Link, dest, target_cap_reg, 0));
342 }
343
344 pub fn emit_unlink(&mut self, link_reg: u8) {
345 self.emit(Instruction::abc(Opcode::Unlink, link_reg, 0, 0));
346 }
347
348 pub fn emit_set_trap_exit(&mut self, enabled_reg: u8) {
349 self.emit(Instruction::abc(Opcode::SetTrapExit, enabled_reg, 0, 0));
350 }
351
352 pub fn emit_set_restart_policy(&mut self, policy: u8) {
354 self.emit(Instruction::only_imm(
355 Opcode::SetRestartPolicy,
356 i32::from(policy),
357 ));
358 }
359
360 pub fn emit_host_await(&mut self, dst: u8, args_reg: u8, op: u32) {
364 self.emit(Instruction::new(
365 Opcode::HostAwait,
366 dst,
367 args_reg,
368 0,
369 op as i32,
370 ));
371 }
372
373 pub fn emit_register_name(&mut self, name_reg: u8) {
374 self.emit(Instruction::abc(Opcode::RegisterName, name_reg, 0, 0));
375 }
376
377 pub fn emit_whereis(&mut self, dst: u8, name_reg: u8) {
378 self.emit(Instruction::abc(Opcode::Whereis, dst, name_reg, 0));
379 }
380
381 pub fn emit_trap(&mut self, code: i32) {
382 self.emit(Instruction::only_imm(Opcode::Trap, code));
383 }
384
385 pub fn emit_call(&mut self, dst: u8, function: u32, argc: u8) {
386 self.emit(Instruction::new(
387 Opcode::Call,
388 dst,
389 argc,
390 0,
391 function as i32,
392 ));
393 }
394
395 pub fn emit_call_native(&mut self, dst: u8, native_index: u32, argc: u8) {
402 self.emit(Instruction::new(
403 Opcode::CallNative,
404 dst,
405 argc,
406 0,
407 native_index as i32,
408 ));
409 }
410
411 pub fn emit_native1_from(&mut self, dst: u8, src: u8, native_index: u32) {
433 self.emit_move(dst, src);
434 self.emit_call_native(dst, native_index, 1);
435 }
436
437 pub fn emit_native_n(&mut self, base: u8, native_index: u32, argc: u8) {
443 self.emit_call_native(base, native_index, argc);
444 }
445
446 pub fn emit_return(&mut self, reg: u8) {
447 self.emit(Instruction::abc(Opcode::Return, reg, 0, 0));
448 }
449
450 pub fn begin_function(&mut self, name: impl Into<String>, arity: u8, num_registers: u8) -> u32 {
456 let name = name.into();
457 let entry = self.code.len() as u32;
458 let idx = self.functions.len() as u32;
459 self.functions.push(FunctionDef {
460 name: name.clone(),
461 entry,
462 arity,
463 num_registers,
464 });
465 self.fn_starts.insert(name, idx);
466 idx
467 }
468
469 pub fn function_index(&self, name: &str) -> Option<u32> {
470 self.fn_starts.get(name).copied()
471 }
472
473 pub fn set_num_registers(&mut self, function_index: u32, num_registers: u8) {
478 if let Some(def) = self.functions.get_mut(function_index as usize) {
479 def.num_registers = num_registers;
480 }
481 }
482
483 pub fn finish(mut self) -> Chunk {
490 for (idx, label) in self.pending_jumps.drain(..) {
491 let imm = self.label_targets.get(&label).and_then(|target| {
492 let offset = i64::from(*target) - (idx as i64 + 1);
494 i32::try_from(offset).ok()
495 });
496 match imm {
497 Some(imm) => self.code[idx].imm = imm,
498 None => {
499 self.code[idx].op = Opcode::Trap;
500 self.code[idx].imm = 0;
501 }
502 }
503 }
504 Chunk {
505 name: self.name,
506 constants: self.constants,
507 code: self.code,
508 functions: self.functions,
509 }
510 }
511}
512#[cfg(test)]
513mod tests {
514 use super::*;
515
516 #[test]
517 fn unbound_label_becomes_a_trap() {
518 let mut b = ChunkBuilder::new("t");
519 b.begin_function("main", 0, 1);
520 let missing = b.new_label();
521 b.emit_jump(missing);
522 b.emit_return(0);
523 let chunk = b.finish();
524 assert_eq!(chunk.code[0].op, Opcode::Trap);
525 }
526
527 #[test]
528 fn emit_native1_from_never_clobbers_source_register() {
529 let mut b = ChunkBuilder::new("clobber-test");
530 b.begin_function("main", 0, 8);
531 b.emit_native1_from(1, 0, 10);
532 b.emit_native1_from(2, 0, 11);
533 b.emit_native1_from(3, 0, 12);
534 let chunk = b.finish();
535
536 assert_eq!(chunk.code.len(), 6);
537 for (move_idx, call_idx, expected_native) in
538 [(0usize, 1usize, 10i32), (2, 3, 11), (4, 5, 12)]
539 {
540 assert_eq!(chunk.code[move_idx].op, Opcode::Move);
541 assert_eq!(chunk.code[move_idx].b, 0);
542 assert_eq!(chunk.code[call_idx].op, Opcode::CallNative);
543 assert_ne!(chunk.code[call_idx].a, 0);
544 assert_eq!(chunk.code[call_idx].imm, expected_native);
545 }
546 }
547
548 #[test]
549 fn emit_native_n_is_a_plain_call_native_with_no_extra_instructions() {
550 let mut b = ChunkBuilder::new("native-n-test");
551 b.begin_function("main", 0, 8);
552 b.emit_load_imm(1, 7);
553 b.emit_load_imm(2, 1);
554 b.emit_native_n(1, 99, 2);
555 let chunk = b.finish();
556
557 assert_eq!(chunk.code.len(), 3);
558 assert_eq!(chunk.code[2].op, Opcode::CallNative);
559 assert_eq!(chunk.code[2].a, 1);
560 assert_eq!(chunk.code[2].b, 2);
561 assert_eq!(chunk.code[2].imm, 99);
562 }
563
564 #[test]
565 fn macro_forms_produce_identical_bytecode_to_the_methods() {
566 let mut via_method = ChunkBuilder::new("via-method");
567 via_method.begin_function("main", 0, 8);
568 via_method.emit_native1_from(1, 0, 10);
569 via_method.emit_native_n(1, 99, 2);
570
571 let mut via_macro = ChunkBuilder::new("via-macro");
572 via_macro.begin_function("main", 0, 8);
573 crate::emit_native1_from!(via_macro, 1, 0, 10);
574 crate::emit_native_n!(via_macro, 1, 99, 2);
575
576 assert_eq!(via_method.finish().code, via_macro.finish().code);
577 }
578}