forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.rs
More file actions
644 lines (576 loc) · 23.1 KB
/
Copy pathcompiler.rs
File metadata and controls
644 lines (576 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! AST -> Bytecode compiler.
use crate::ast::*;
use crate::bytecode::*;
use crate::types::{Capability, EffectRow, Type};
use std::collections::HashMap;
// ---------------------------------------------------------------------------
// Compiler state
// ---------------------------------------------------------------------------
#[derive(Debug)]
struct LocalVar {
name: String,
reg: u8,
}
#[derive(Debug)]
pub struct Compiler {
module: Module,
locals: Vec<LocalVar>,
next_reg: u8,
loop_breaks: Vec<Vec<u32>>, // stack of break-jump PCs per loop
current_actor: Option<String>,
}
impl Compiler {
pub fn new(module_name: String) -> Self {
Compiler {
module: Module::new(module_name),
locals: Vec::new(),
next_reg: 1, // r0 reserved for temporaries / return value
loop_breaks: Vec::new(),
current_actor: None,
}
}
pub fn finish(self) -> Module {
self.module
}
pub fn module(&self) -> &Module {
&self.module
}
// -- Variable management --
fn alloc_reg(&mut self) -> u8 {
let r = self.next_reg;
self.next_reg += 1;
assert!(self.next_reg <= 255, "register overflow");
r
}
fn free_reg(&mut self, _r: u8) {
// Simple bump allocator - in production, use a register pool
}
fn find_local(&self, name: &str) -> Option<u8> {
self.locals.iter().rev().find(|l| l.name == name).map(|l| l.reg)
}
fn push_local(&mut self, name: String, reg: u8) {
self.locals.push(LocalVar { name, reg });
}
fn pop_local(&mut self) -> Option<LocalVar> {
self.locals.pop()
}
// -- Entry point --
pub fn compile_module(&mut self, module: &ast::Module) {
for decl in &module.decls {
self.compile_decl(decl);
}
self.module.emit(OpCode::Halt, 0, 0, 0);
}
fn compile_decl(&mut self, decl: &Decl) {
match decl {
Decl::Fun { name, params, body, .. } => {
let saved_locals = self.locals.clone();
let saved_reg = self.next_reg;
self.locals.clear();
self.next_reg = 1;
// Parameters start at r1
for (pname, _) in params {
let reg = self.alloc_reg();
self.push_local(pname.clone(), reg);
}
let entry = self.module.instructions.len() as u32;
let ret_reg = self.compile_expr(body);
self.module.emit(OpCode::Ret, ret_reg, 0, 0);
self.module.behavior_table.push(BehaviorTableEntry {
name: name.clone(),
param_count: params.len() as u8,
entry_point: entry,
effect_annotation: None,
});
self.locals = saved_locals;
self.next_reg = saved_reg;
}
Decl::Actor { def, .. } => {
self.current_actor = Some(def.name.clone());
for behavior in &def.behaviors {
self.compile_behavior(&def.name, behavior);
}
self.current_actor = None;
}
Decl::Agent { def, .. } => {
self.current_actor = Some(def.name.clone());
for behavior in &def.behaviors {
self.compile_behavior(&def.name, behavior);
}
self.current_actor = None;
}
_ => {}
}
}
fn compile_behavior(&mut self, actor_name: &str, behavior: &Behavior) {
let saved_locals = self.locals.clone();
let saved_reg = self.next_reg;
self.locals.clear();
self.next_reg = 1;
for (pname, _) in &behavior.params {
let reg = self.alloc_reg();
self.push_local(pname.clone(), reg);
}
let entry = self.module.instructions.len() as u32;
let ret_reg = self.compile_expr(&behavior.body);
self.module.emit(OpCode::Ret, ret_reg, 0, 0);
self.module.behavior_table.push(BehaviorTableEntry {
name: format!("{}.{}", actor_name, behavior.name),
param_count: behavior.params.len() as u8,
entry_point: entry,
effect_annotation: None,
});
self.locals = saved_locals;
self.next_reg = saved_reg;
}
// -- Expression compiler --
fn compile_expr(&mut self, expr: &Expr) -> u8 {
match expr {
Expr::Literal(lit, _) => self.compile_literal(lit),
Expr::Var(name, _) => {
if let Some(reg) = self.find_local(name) {
let dst = self.alloc_reg();
self.module.emit(OpCode::Move, dst, reg, 0);
dst
} else {
// Global - load from constants
let dst = self.alloc_reg();
let name_idx = self.module.add_string(name.clone());
self.module.emit(OpCode::LoadConst, dst,
((name_idx >> 8) & 0xFF) as u8,
(name_idx & 0xFF) as u8);
dst
}
}
Expr::Let { name, value, body, .. } => {
let val_reg = self.compile_expr(value);
self.push_local(name.clone(), val_reg);
let result = self.compile_expr(body);
self.pop_local();
result
}
Expr::LetRec { name, params, value, body, .. } => {
// Allocate register for the recursive function
let fun_reg = self.alloc_reg();
self.push_local(name.clone(), fun_reg);
// Compile the function body with parameters
let saved_locals = self.locals.clone();
let saved_reg = self.next_reg;
self.locals.clear();
self.next_reg = 1;
for (pname, _) in params {
let reg = self.alloc_reg();
self.push_local(pname.clone(), reg);
}
let entry = self.module.instructions.len() as u32;
let ret_reg = self.compile_expr(value);
self.module.emit(OpCode::Ret, ret_reg, 0, 0);
self.module.behavior_table.push(BehaviorTableEntry {
name: name.clone(),
param_count: params.len() as u8,
entry_point: entry,
effect_annotation: None,
});
self.locals = saved_locals;
self.next_reg = saved_reg;
// Now compile the body
let result = self.compile_expr(body);
self.pop_local();
result
}
Expr::If { cond, then_branch, else_branch, .. } => {
let cond_reg = self.compile_expr(cond);
let jump_else = self.module.instructions.len() as u32;
self.module.emit(OpCode::JumpIfNot, cond_reg, 0, 0); // patched later
let then_reg = self.compile_expr(then_branch);
let jump_end = self.module.instructions.len() as u32;
self.module.emit(OpCode::Jump, 0, 0, 0); // patched later
let else_pc = self.module.instructions.len() as u32;
let else_reg = else_branch.as_ref()
.map(|e| self.compile_expr(e))
.unwrap_or_else(|| {
let r = self.alloc_reg();
self.module.emit(OpCode::LoadNull, r, 0, 0);
r
});
let end_pc = self.module.instructions.len() as u32;
// Patch jumps
let else_offset = (else_pc as i32 - jump_else as i32 - 1) as i16;
self.module.patch_jump(jump_else, else_offset);
let end_offset = (end_pc as i32 - jump_end as i32 - 1) as i16;
self.module.patch_jump(jump_end, end_offset);
// Move result to a single register
let result_reg = self.alloc_reg();
self.module.emit(OpCode::Move, result_reg, then_reg, 0);
result_reg
}
Expr::Lambda { params, body, .. } => {
let saved_locals = self.locals.clone();
let saved_reg = self.next_reg;
self.locals.clear();
self.next_reg = 1;
for (pname, _) in params {
let reg = self.alloc_reg();
self.push_local(pname.clone(), reg);
}
let entry = self.module.instructions.len() as u32;
let ret_reg = self.compile_expr(body);
self.module.emit(OpCode::Ret, ret_reg, 0, 0);
let lambda_name = format!("__lambda_{}", entry);
self.module.behavior_table.push(BehaviorTableEntry {
name: lambda_name,
param_count: params.len() as u8,
entry_point: entry,
effect_annotation: None,
});
self.locals = saved_locals;
self.next_reg = saved_reg;
let dst = self.alloc_reg();
dst
}
Expr::App { func, args, .. } => {
let func_reg = self.compile_expr(func);
let mut arg_regs = Vec::new();
for arg in args {
arg_regs.push(self.compile_expr(arg));
}
let dst = self.alloc_reg();
if !arg_regs.is_empty() {
// Move args to consecutive registers starting at func_reg+1
for (i, &arg_reg) in arg_regs.iter().enumerate() {
let target = func_reg + 1 + i as u8;
if arg_reg != target {
self.module.emit(OpCode::Move, target, arg_reg, 0);
}
}
}
self.module.emit(OpCode::Call, dst, func_reg,
(func_reg + args.len() as u8));
dst
}
Expr::Block { exprs, .. } => {
let mut last_reg = 0;
for (i, e) in exprs.iter().enumerate() {
let is_last = i == exprs.len() - 1;
if is_last {
last_reg = self.compile_expr(e);
} else {
self.compile_expr(e);
}
}
last_reg
}
Expr::Binary { op, left, right, .. } => {
let l = self.compile_expr(left);
let r = self.compile_expr(right);
let dst = self.alloc_reg();
let opcode = match op {
BinOp::Add => OpCode::Add,
BinOp::Sub => OpCode::Sub,
BinOp::Mul => OpCode::Mul,
BinOp::Div => OpCode::Div,
BinOp::Mod => OpCode::Mod,
BinOp::Eq => OpCode::Eq,
BinOp::Ne => OpCode::Ne,
BinOp::Lt => OpCode::Lt,
BinOp::Le => OpCode::Le,
BinOp::Gt => OpCode::Gt,
BinOp::Ge => OpCode::Ge,
BinOp::And => OpCode::And,
BinOp::Or => OpCode::Or,
BinOp::Cons => OpCode::Cons,
_ => OpCode::Add,
};
self.module.emit(opcode, dst, l, r);
dst
}
Expr::Tuple(elems, _) => {
let mut regs = Vec::new();
for e in elems {
regs.push(self.compile_expr(e));
}
let dst = self.alloc_reg();
if !regs.is_empty() {
for (i, ®) in regs.iter().enumerate() {
self.module.emit(OpCode::Move, dst + 1 + i as u8, reg, 0);
}
self.module.emit(OpCode::NewTuple, dst, dst + 1,
(dst + regs.len() as u8));
} else {
self.module.emit(OpCode::LoadNull, dst, 0, 0);
}
dst
}
Expr::Record(fields, _) => {
let dst = self.alloc_reg();
let mut field_regs = Vec::new();
for (name, expr) in fields {
let reg = self.compile_expr(expr);
field_regs.push((name.clone(), reg));
}
for (_name, reg) in field_regs {
// Store field name in string table
self.module.emit(OpCode::Move, dst + 1, reg, 0);
}
self.module.emit(OpCode::NewRecord, dst, field_regs.len() as u8, 0);
dst
}
Expr::FieldAccess { expr, field, .. } => {
let obj = self.compile_expr(expr);
let dst = self.alloc_reg();
let field_idx = self.module.add_string(field.clone());
self.module.emit(OpCode::FieldGet, dst, obj,
((field_idx >> 8) & 0xFF) as u8);
dst
}
Expr::Array(elems, _) => {
let dst = self.alloc_reg();
for (i, e) in elems.iter().enumerate() {
let reg = self.compile_expr(e);
self.module.emit(OpCode::Move, dst + 1 + i as u8, reg, 0);
}
self.module.emit(OpCode::NewArray, dst, dst + 1,
(dst + elems.len() as u8));
dst
}
Expr::Unary { op, expr, .. } => {
let operand = self.compile_expr(expr);
let dst = self.alloc_reg();
let opcode = match op {
UnOp::Neg => OpCode::Neg,
UnOp::Not => OpCode::Not,
};
self.module.emit(opcode, dst, operand, 0);
dst
}
Expr::Match { scrutinee, arms, .. } => {
let scrut_reg = self.compile_expr(scrutinee);
let mut end_jumps = Vec::new();
let dst = self.alloc_reg();
for (pattern, arm_body) in arms {
// Simple pattern: just Var for now
if let Pattern::Var(name) = pattern {
self.push_local(name.clone(), scrut_reg);
let arm_reg = self.compile_expr(arm_body);
self.module.emit(OpCode::Move, dst, arm_reg, 0);
self.pop_local();
break; // Only handle first arm for now
}
}
dst
}
Expr::Spawn { actor_type, init, .. } => {
let type_reg = self.compile_expr(actor_type);
let dst = self.alloc_reg();
// Compile init args
for (i, (_name, expr)) in init.iter().enumerate() {
let reg = self.compile_expr(expr);
self.module.emit(OpCode::Move, dst + 2 + i as u8, reg, 0);
}
self.module.emit(OpCode::Spawn, dst, type_reg,
(dst + 2 + init.len() as u8));
dst
}
Expr::Send { actor, behavior, args, .. } => {
let actor_reg = self.compile_expr(actor);
let beh_idx = self.module.add_string(behavior.clone());
let mut arg_regs = Vec::new();
for arg in args {
arg_regs.push(self.compile_expr(arg));
}
for (i, ®) in arg_regs.iter().enumerate() {
self.module.emit(OpCode::Move, actor_reg + 2 + i as u8, reg, 0);
}
self.module.emit(OpCode::Send, 0, actor_reg,
((beh_idx >> 8) & 0xFF) as u8);
0
}
Expr::Ask { actor, behavior, args, .. } => {
let actor_reg = self.compile_expr(actor);
let dst = self.alloc_reg();
let beh_idx = self.module.add_string(behavior.clone());
let mut arg_regs = Vec::new();
for arg in args {
arg_regs.push(self.compile_expr(arg));
}
for (i, ®) in arg_regs.iter().enumerate() {
self.module.emit(OpCode::Move, dst + 1 + i as u8, reg, 0);
}
self.module.emit(OpCode::Ask, dst, actor_reg,
((beh_idx >> 8) & 0xFF) as u8);
dst
}
Expr::SelfRef(_) => {
let dst = self.alloc_reg();
self.module.emit(OpCode::SelfAddr, dst, 0, 0);
dst
}
Expr::Perform { effect, op, args, .. } => {
let dst = self.alloc_reg();
let eff_idx = self.module.add_string(effect.clone());
let op_idx = self.module.add_string(op.clone());
for (i, arg) in args.iter().enumerate() {
let reg = self.compile_expr(arg);
self.module.emit(OpCode::Move, dst + 1 + i as u8, reg, 0);
}
self.module.emit(OpCode::Perform, dst,
((eff_idx >> 8) & 0xFF) as u8,
((op_idx >> 8) & 0xFF) as u8);
dst
}
Expr::Handle { body, handlers, .. } => {
// Compile handlers setup
let _handler_pcs: Vec<u32> = handlers.iter().map(|h| {
let op_idx = self.module.add_string(h.op.clone());
self.module.instructions.len() as u32
}).collect();
let body_reg = self.compile_expr(body);
// Pop handlers
for _ in handlers {
self.module.emit(OpCode::PopHandler, 0, 0, 0);
}
body_reg
}
Expr::Pipe { left, right, .. } => {
let l = self.compile_expr(left);
let r = self.compile_expr(right);
let dst = self.alloc_reg();
self.module.emit(OpCode::Call, dst, r, l);
dst
}
Expr::Try { body, catch_arms: _, .. } => {
self.compile_expr(body)
}
Expr::Await { expr, .. } => {
self.compile_expr(expr)
}
Expr::Migrate { actor, node, .. } => {
let actor_reg = self.compile_expr(actor);
let node_reg = self.compile_expr(node);
let dst = self.alloc_reg();
self.module.emit(OpCode::Migrate, dst, actor_reg, node_reg);
dst
}
Expr::CapAnnotate { expr, .. } => {
self.compile_expr(expr)
}
Expr::TypeAnnotate { expr, .. } => {
self.compile_expr(expr)
}
Expr::Assign { target, value, .. } => {
let val_reg = self.compile_expr(value);
if let Expr::Var(name, _) = target.as_ref() {
if let Some(reg) = self.find_local(name) {
self.module.emit(OpCode::Move, reg, val_reg, 0);
reg
} else {
val_reg
}
} else {
val_reg
}
}
Expr::ActorDef(_, _) | Expr::AgentDef(_, _) => {
let dst = self.alloc_reg();
self.module.emit(OpCode::LoadNull, dst, 0, 0);
dst
}
Expr::Receive { .. } => {
let dst = self.alloc_reg();
self.module.emit(OpCode::LoadNull, dst, 0, 0);
dst
}
Expr::Index { .. } => {
let dst = self.alloc_reg();
self.module.emit(OpCode::LoadNull, dst, 0, 0);
dst
}
}
}
fn compile_literal(&mut self, lit: &Literal) -> u8 {
let dst = self.alloc_reg();
match lit {
Literal::Int(n) => {
let idx = self.module.add_constant(Constant::Int(*n));
self.module.emit(OpCode::LoadConst, dst,
((idx >> 8) & 0xFF) as u8,
(idx & 0xFF) as u8);
}
Literal::Float(n) => {
let idx = self.module.add_constant(Constant::Float(*n));
self.module.emit(OpCode::LoadConst, dst,
((idx >> 8) & 0xFF) as u8,
(idx & 0xFF) as u8);
}
Literal::String(s) => {
let idx = self.module.add_constant(Constant::String(s.clone()));
self.module.emit(OpCode::LoadConst, dst,
((idx >> 8) & 0xFF) as u8,
(idx & 0xFF) as u8);
}
Literal::Bool(b) => {
let idx = self.module.add_constant(Constant::Bool(*b));
self.module.emit(OpCode::LoadConst, dst,
((idx >> 8) & 0xFF) as u8,
(idx & 0xFF) as u8);
}
Literal::Unit => {
self.module.emit(OpCode::LoadNull, dst, 0, 0);
}
}
dst
}
}
// ---------------------------------------------------------------------------
// Convenience function
// ---------------------------------------------------------------------------
pub fn compile(module: &ast::Module) -> Module {
let mut compiler = Compiler::new(module.name.clone());
compiler.compile_module(module);
compiler.finish()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::*;
use crate::types::Span;
fn s() -> Span { Span { start: 0, end: 0, line: 1, col: 1 } }
#[test]
fn test_compile_literal() {
let m = ast::Module {
name: "test".to_string(),
decls: vec![],
span: s(),
};
let mut c = Compiler::new("test".to_string());
c.compile_module(&m);
let module = c.finish();
assert!(!module.instructions.is_empty());
}
#[test]
fn test_compile_function() {
let m = ast::Module {
name: "test".to_string(),
decls: vec![
Decl::Fun {
name: "add".to_string(),
type_params: vec![],
params: vec![("x".to_string(), None), ("y".to_string(), None)],
ret_type: None,
effect: None,
body: Expr::Binary {
op: BinOp::Add,
left: Box::new(Expr::Var("x".to_string(), s())),
right: Box::new(Expr::Var("y".to_string(), s())),
span: s(),
},
span: s(),
}
],
span: s(),
};
let module = compile(&m);
assert!(!module.behavior_table.is_empty());
assert_eq!(module.behavior_table[0].name, "add");
}
}