polycomp 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1157 @@
1
+ use crate::ast::*;
2
+ use crate::diagnostics::{PolyError, Span};
3
+ use crate::ir::*;
4
+ use crate::resolver::ImportBindings;
5
+ use rustc_hash::FxHashMap;
6
+
7
+ struct LoopTargets {
8
+ break_bb: BasicBlockId,
9
+ continue_bb: BasicBlockId,
10
+ }
11
+
12
+ struct Lowerer<'a> {
13
+ module_id: usize,
14
+ _fn_id: FnId,
15
+ bindings: &'a ImportBindings,
16
+ local_fn_names: &'a FxHashMap<String, usize>,
17
+ call_sites: &'a mut Vec<CallSite>,
18
+ next_reg: usize,
19
+ register_types: Vec<IrType>,
20
+ blocks: Vec<BasicBlock>,
21
+ current_block: usize,
22
+ scopes: Vec<FxHashMap<String, Register>>,
23
+ loop_stack: Vec<LoopTargets>,
24
+ defer_stack: Vec<Expr>,
25
+ }
26
+
27
+ impl<'a> Lowerer<'a> {
28
+ fn new(
29
+ module_id: usize,
30
+ fn_id: FnId,
31
+ bindings: &'a ImportBindings,
32
+ local_fn_names: &'a FxHashMap<String, usize>,
33
+ call_sites: &'a mut Vec<CallSite>,
34
+ ) -> Self {
35
+ Self {
36
+ module_id,
37
+ _fn_id: fn_id,
38
+ bindings,
39
+ local_fn_names,
40
+ call_sites,
41
+ next_reg: 0,
42
+ register_types: Vec::new(),
43
+ blocks: vec![BasicBlock {
44
+ id: BasicBlockId(0),
45
+ instructions: Vec::new(),
46
+ }],
47
+ current_block: 0,
48
+ scopes: vec![FxHashMap::default()],
49
+ loop_stack: Vec::new(),
50
+ defer_stack: Vec::new(),
51
+ }
52
+ }
53
+
54
+ fn alloc_reg(&mut self, ty: IrType) -> Register {
55
+ let r = Register(self.next_reg);
56
+ self.next_reg += 1;
57
+ self.register_types.push(ty);
58
+ r
59
+ }
60
+
61
+ fn new_block(&mut self) -> BasicBlockId {
62
+ let id = BasicBlockId(self.blocks.len());
63
+ self.blocks.push(BasicBlock {
64
+ id,
65
+ instructions: Vec::new(),
66
+ });
67
+ id
68
+ }
69
+
70
+ fn switch_to(&mut self, id: BasicBlockId) {
71
+ self.current_block = id.0;
72
+ }
73
+
74
+ fn current_terminated(&self) -> bool {
75
+ self.blocks[self.current_block]
76
+ .instructions
77
+ .last()
78
+ .is_some_and(|i| {
79
+ matches!(
80
+ i,
81
+ IrInstruction::Return(_)
82
+ | IrInstruction::Jump(_)
83
+ | IrInstruction::BranchIf(_, _, _)
84
+ | IrInstruction::Throw(_)
85
+ )
86
+ })
87
+ }
88
+
89
+ fn emit(&mut self, instr: IrInstruction) {
90
+ if !self.current_terminated() {
91
+ self.blocks[self.current_block].instructions.push(instr);
92
+ }
93
+ }
94
+
95
+ fn push_scope(&mut self) {
96
+ self.scopes.push(FxHashMap::default());
97
+ }
98
+
99
+ fn pop_scope(&mut self) {
100
+ if self.scopes.len() > 1 {
101
+ self.scopes.pop();
102
+ }
103
+ }
104
+
105
+ fn lookup_var(&self, name: &str) -> Option<Register> {
106
+ for scope in self.scopes.iter().rev() {
107
+ if let Some(&r) = scope.get(name) {
108
+ return Some(r);
109
+ }
110
+ }
111
+ None
112
+ }
113
+
114
+ fn bind_var(&mut self, name: String, reg: Register, fn_scoped: bool) {
115
+ if fn_scoped {
116
+ self.scopes[0].insert(name, reg);
117
+ } else {
118
+ self.scopes.last_mut().unwrap().insert(name, reg);
119
+ }
120
+ }
121
+
122
+ fn alloc_call_site(&mut self, target: LazyTarget, span: Span) -> CallSiteId {
123
+ let id = CallSiteId(self.call_sites.len() as u32);
124
+ self.call_sites.push(CallSite {
125
+ id,
126
+ target,
127
+ span,
128
+ resolved_fn: None,
129
+ });
130
+ id
131
+ }
132
+
133
+ fn emit_defers(&mut self) -> Result<(), PolyError> {
134
+ let defers = self.defer_stack.clone();
135
+ for expr in defers.into_iter().rev() {
136
+ let _ = self.lower_expr(&expr)?;
137
+ }
138
+ Ok(())
139
+ }
140
+
141
+ fn lower_stmts(&mut self, stmts: &[Stmt]) -> Result<(), PolyError> {
142
+ for stmt in stmts {
143
+ self.lower_stmt(stmt)?;
144
+ if self.current_terminated() {
145
+ break;
146
+ }
147
+ }
148
+ Ok(())
149
+ }
150
+
151
+ fn lower_stmt(&mut self, stmt: &Stmt) -> Result<(), PolyError> {
152
+ match stmt {
153
+ Stmt::VarDecl {
154
+ name,
155
+ ty,
156
+ init,
157
+ is_function_scoped,
158
+ ..
159
+ } => {
160
+ let ir_ty = hint_to_ir_type(*ty);
161
+ let existing = if *is_function_scoped {
162
+ self.lookup_var(name)
163
+ } else {
164
+ self.scopes.last().unwrap().get(name).copied()
165
+ };
166
+ let dst = existing.unwrap_or_else(|| {
167
+ let r = self.alloc_reg(ir_ty);
168
+ self.bind_var(name.clone(), r, *is_function_scoped);
169
+ r
170
+ });
171
+
172
+ if let Some(expr) = init {
173
+ let val_reg = self.lower_expr(expr)?;
174
+ if ir_ty != IrType::Dynamic && ir_ty != IrType::Void {
175
+ self.emit(IrInstruction::Cast(dst, ir_ty, val_reg));
176
+ } else {
177
+ self.emit(IrInstruction::Move(dst, val_reg));
178
+ }
179
+ } else {
180
+ self.emit(IrInstruction::LoadConst(dst, Constant::Nil));
181
+ }
182
+ }
183
+
184
+ Stmt::MultiVarDecl {
185
+ names,
186
+ init,
187
+ is_function_scoped,
188
+ ..
189
+ } => {
190
+ let init_reg = self.lower_expr(init)?;
191
+ for (idx, name) in names.iter().enumerate() {
192
+ let dst = self.alloc_reg(IrType::Dynamic);
193
+ self.bind_var(name.clone(), dst, *is_function_scoped);
194
+ let idx_reg = self.alloc_reg(IrType::I64);
195
+ self.emit(IrInstruction::LoadConst(idx_reg, Constant::Int(idx as i64)));
196
+ self.emit(IrInstruction::GetIndex(dst, init_reg, idx_reg));
197
+ }
198
+ }
199
+
200
+ Stmt::Assign {
201
+ target,
202
+ op,
203
+ value,
204
+ span,
205
+ } => {
206
+ let rhs = self.lower_expr(value)?;
207
+ match target {
208
+ AssignTarget::Var(name) => {
209
+ let var_reg = self.lookup_var(name).ok_or_else(|| {
210
+ PolyError::spanned(
211
+ "E0301",
212
+ format!("assignment to undeclared variable '{name}'"),
213
+ *span,
214
+ )
215
+ })?;
216
+ if let Some(bin_op) = op {
217
+ self.emit(IrInstruction::BinOp(
218
+ map_binop(*bin_op),
219
+ var_reg,
220
+ var_reg,
221
+ rhs,
222
+ ));
223
+ } else {
224
+ self.emit(IrInstruction::Move(var_reg, rhs));
225
+ }
226
+ }
227
+ AssignTarget::Field(obj_expr, field) => {
228
+ let obj_reg = self.lower_expr(obj_expr)?;
229
+ if let Some(bin_op) = op {
230
+ let tmp = self.alloc_reg(IrType::Dynamic);
231
+ self.emit(IrInstruction::GetField(tmp, obj_reg, field.clone()));
232
+ let res = self.alloc_reg(IrType::Dynamic);
233
+ self.emit(IrInstruction::BinOp(map_binop(*bin_op), res, tmp, rhs));
234
+ self.emit(IrInstruction::SetField(obj_reg, field.clone(), res));
235
+ } else {
236
+ self.emit(IrInstruction::SetField(obj_reg, field.clone(), rhs));
237
+ }
238
+ }
239
+ AssignTarget::Index(obj_expr, idx_expr) => {
240
+ let obj_reg = self.lower_expr(obj_expr)?;
241
+ let idx_reg = self.lower_expr(idx_expr)?;
242
+ if let Some(bin_op) = op {
243
+ let tmp = self.alloc_reg(IrType::Dynamic);
244
+ self.emit(IrInstruction::GetIndex(tmp, obj_reg, idx_reg));
245
+ let res = self.alloc_reg(IrType::Dynamic);
246
+ self.emit(IrInstruction::BinOp(map_binop(*bin_op), res, tmp, rhs));
247
+ self.emit(IrInstruction::SetIndex(obj_reg, idx_reg, res));
248
+ } else {
249
+ self.emit(IrInstruction::SetIndex(obj_reg, idx_reg, rhs));
250
+ }
251
+ }
252
+ AssignTarget::Tuple(names) => {
253
+ for (idx, name) in names.iter().enumerate() {
254
+ if let Some(var_reg) = self.lookup_var(name) {
255
+ let idx_reg = self.alloc_reg(IrType::I64);
256
+ self.emit(IrInstruction::LoadConst(
257
+ idx_reg,
258
+ Constant::Int(idx as i64),
259
+ ));
260
+ self.emit(IrInstruction::GetIndex(var_reg, rhs, idx_reg));
261
+ }
262
+ }
263
+ }
264
+ }
265
+ }
266
+
267
+ Stmt::If {
268
+ init,
269
+ cond,
270
+ then_body,
271
+ else_body,
272
+ ..
273
+ } => {
274
+ self.push_scope();
275
+ if let Some(init_stmt) = init {
276
+ self.lower_stmt(init_stmt)?;
277
+ }
278
+ let cond_reg = self.lower_expr(cond)?;
279
+ let then_bb = self.new_block();
280
+ let else_bb = self.new_block();
281
+ let merge_bb = self.new_block();
282
+
283
+ self.emit(IrInstruction::BranchIf(cond_reg, then_bb, else_bb));
284
+
285
+ self.switch_to(then_bb);
286
+ self.push_scope();
287
+ self.lower_stmts(then_body)?;
288
+ self.pop_scope();
289
+ self.emit(IrInstruction::Jump(merge_bb));
290
+
291
+ self.switch_to(else_bb);
292
+ self.push_scope();
293
+ self.lower_stmts(else_body)?;
294
+ self.pop_scope();
295
+ self.emit(IrInstruction::Jump(merge_bb));
296
+
297
+ self.pop_scope();
298
+ self.switch_to(merge_bb);
299
+ }
300
+
301
+ Stmt::While { cond, body, .. } => {
302
+ let header_bb = self.new_block();
303
+ let body_bb = self.new_block();
304
+ let exit_bb = self.new_block();
305
+
306
+ self.emit(IrInstruction::Jump(header_bb));
307
+ self.switch_to(header_bb);
308
+ let cond_reg = self.lower_expr(cond)?;
309
+ self.emit(IrInstruction::BranchIf(cond_reg, body_bb, exit_bb));
310
+
311
+ self.loop_stack.push(LoopTargets {
312
+ break_bb: exit_bb,
313
+ continue_bb: header_bb,
314
+ });
315
+ self.switch_to(body_bb);
316
+ self.push_scope();
317
+ self.lower_stmts(body)?;
318
+ self.pop_scope();
319
+ self.emit(IrInstruction::Jump(header_bb));
320
+ self.loop_stack.pop();
321
+
322
+ self.switch_to(exit_bb);
323
+ }
324
+
325
+ Stmt::ForRange {
326
+ var,
327
+ start,
328
+ end,
329
+ inclusive,
330
+ step,
331
+ body,
332
+ ..
333
+ } => {
334
+ let start_reg = self.lower_expr(start)?;
335
+ let end_reg = self.lower_expr(end)?;
336
+ let step_reg = if let Some(st) = step {
337
+ self.lower_expr(st)?
338
+ } else {
339
+ let s = self.alloc_reg(IrType::I64);
340
+ self.emit(IrInstruction::LoadConst(s, Constant::Int(1)));
341
+ s
342
+ };
343
+
344
+ self.push_scope();
345
+ let idx_reg = self.alloc_reg(IrType::I64);
346
+ self.emit(IrInstruction::Move(idx_reg, start_reg));
347
+ self.bind_var(var.clone(), idx_reg, false);
348
+
349
+ let header_bb = self.new_block();
350
+ let body_bb = self.new_block();
351
+ let step_bb = self.new_block();
352
+ let exit_bb = self.new_block();
353
+
354
+ self.emit(IrInstruction::Jump(header_bb));
355
+ self.switch_to(header_bb);
356
+ let cmp_reg = self.alloc_reg(IrType::Bool);
357
+ let cmp_op = if *inclusive { IrBinOp::Le } else { IrBinOp::Lt };
358
+ self.emit(IrInstruction::BinOp(cmp_op, cmp_reg, idx_reg, end_reg));
359
+ self.emit(IrInstruction::BranchIf(cmp_reg, body_bb, exit_bb));
360
+
361
+ self.loop_stack.push(LoopTargets {
362
+ break_bb: exit_bb,
363
+ continue_bb: step_bb,
364
+ });
365
+ self.switch_to(body_bb);
366
+ self.lower_stmts(body)?;
367
+ self.emit(IrInstruction::Jump(step_bb));
368
+ self.loop_stack.pop();
369
+
370
+ self.switch_to(step_bb);
371
+ self.emit(IrInstruction::BinOp(
372
+ IrBinOp::Add,
373
+ idx_reg,
374
+ idx_reg,
375
+ step_reg,
376
+ ));
377
+ self.emit(IrInstruction::Jump(header_bb));
378
+
379
+ self.pop_scope();
380
+ self.switch_to(exit_bb);
381
+ }
382
+
383
+ Stmt::ForIn {
384
+ index_var,
385
+ var,
386
+ iter,
387
+ body,
388
+ ..
389
+ } => {
390
+ let arr_reg = self.lower_expr(iter)?;
391
+ let len_reg = self.alloc_reg(IrType::I64);
392
+ self.emit(IrInstruction::CallBuiltin(
393
+ len_reg,
394
+ BuiltinId::Len,
395
+ vec![arr_reg],
396
+ ));
397
+ let idx_reg = self.alloc_reg(IrType::I64);
398
+ self.emit(IrInstruction::LoadConst(idx_reg, Constant::Int(0)));
399
+ let one_reg = self.alloc_reg(IrType::I64);
400
+ self.emit(IrInstruction::LoadConst(one_reg, Constant::Int(1)));
401
+
402
+ self.push_scope();
403
+ if let Some(iv) = index_var {
404
+ self.bind_var(iv.clone(), idx_reg, false);
405
+ }
406
+ let elem_reg = self.alloc_reg(IrType::Dynamic);
407
+ self.bind_var(var.clone(), elem_reg, false);
408
+
409
+ let header_bb = self.new_block();
410
+ let body_bb = self.new_block();
411
+ let step_bb = self.new_block();
412
+ let exit_bb = self.new_block();
413
+
414
+ self.emit(IrInstruction::Jump(header_bb));
415
+ self.switch_to(header_bb);
416
+ let cmp_reg = self.alloc_reg(IrType::Bool);
417
+ self.emit(IrInstruction::BinOp(
418
+ IrBinOp::Lt,
419
+ cmp_reg,
420
+ idx_reg,
421
+ len_reg,
422
+ ));
423
+ self.emit(IrInstruction::BranchIf(cmp_reg, body_bb, exit_bb));
424
+
425
+ self.switch_to(body_bb);
426
+ self.emit(IrInstruction::GetIndex(elem_reg, arr_reg, idx_reg));
427
+ self.loop_stack.push(LoopTargets {
428
+ break_bb: exit_bb,
429
+ continue_bb: step_bb,
430
+ });
431
+ self.lower_stmts(body)?;
432
+ self.emit(IrInstruction::Jump(step_bb));
433
+ self.loop_stack.pop();
434
+
435
+ self.switch_to(step_bb);
436
+ self.emit(IrInstruction::BinOp(
437
+ IrBinOp::Add,
438
+ idx_reg,
439
+ idx_reg,
440
+ one_reg,
441
+ ));
442
+ self.emit(IrInstruction::Jump(header_bb));
443
+
444
+ self.pop_scope();
445
+ self.switch_to(exit_bb);
446
+ }
447
+
448
+ Stmt::Switch {
449
+ expr,
450
+ cases,
451
+ default,
452
+ ..
453
+ } => {
454
+ let target_val = if let Some(e) = expr {
455
+ Some(self.lower_expr(e)?)
456
+ } else {
457
+ None
458
+ };
459
+ let exit_bb = self.new_block();
460
+ self.loop_stack.push(LoopTargets {
461
+ break_bb: exit_bb,
462
+ continue_bb: exit_bb,
463
+ });
464
+
465
+ let mut next_case_bb = self.new_block();
466
+ for (vals, body) in cases {
467
+ self.switch_to(next_case_bb);
468
+ next_case_bb = self.new_block();
469
+ let case_body_bb = self.new_block();
470
+
471
+ if let Some(tv) = target_val {
472
+ for val_expr in vals {
473
+ let vr = self.lower_expr(val_expr)?;
474
+ let cmp_r = self.alloc_reg(IrType::Bool);
475
+ self.emit(IrInstruction::BinOp(IrBinOp::Eq, cmp_r, tv, vr));
476
+ let try_next_val = self.new_block();
477
+ self.emit(IrInstruction::BranchIf(cmp_r, case_body_bb, try_next_val));
478
+ self.switch_to(try_next_val);
479
+ }
480
+ self.emit(IrInstruction::Jump(next_case_bb));
481
+ } else {
482
+ // Go switch without expr (boolean conditions)
483
+ for val_expr in vals {
484
+ let cond_r = self.lower_expr(val_expr)?;
485
+ let try_next_val = self.new_block();
486
+ self.emit(IrInstruction::BranchIf(cond_r, case_body_bb, try_next_val));
487
+ self.switch_to(try_next_val);
488
+ }
489
+ self.emit(IrInstruction::Jump(next_case_bb));
490
+ }
491
+
492
+ self.switch_to(case_body_bb);
493
+ self.push_scope();
494
+ self.lower_stmts(body)?;
495
+ self.pop_scope();
496
+ self.emit(IrInstruction::Jump(exit_bb));
497
+ }
498
+
499
+ self.switch_to(next_case_bb);
500
+ self.push_scope();
501
+ self.lower_stmts(default)?;
502
+ self.pop_scope();
503
+ self.emit(IrInstruction::Jump(exit_bb));
504
+
505
+ self.loop_stack.pop();
506
+ self.switch_to(exit_bb);
507
+ }
508
+
509
+ Stmt::TryCatch {
510
+ try_body,
511
+ catch_var,
512
+ catch_body,
513
+ finally_body,
514
+ ..
515
+ } => {
516
+ let catch_bb = self.new_block();
517
+ let finally_bb = self.new_block();
518
+ let err_reg = self.alloc_reg(IrType::Dynamic);
519
+
520
+ self.emit(IrInstruction::TryBegin(catch_bb, err_reg));
521
+ self.push_scope();
522
+ self.lower_stmts(try_body)?;
523
+ self.pop_scope();
524
+ self.emit(IrInstruction::TryEnd);
525
+ self.emit(IrInstruction::Jump(finally_bb));
526
+
527
+ self.switch_to(catch_bb);
528
+ self.push_scope();
529
+ if let Some(cv) = catch_var {
530
+ self.bind_var(cv.clone(), err_reg, false);
531
+ }
532
+ self.lower_stmts(catch_body)?;
533
+ self.pop_scope();
534
+ self.emit(IrInstruction::Jump(finally_bb));
535
+
536
+ self.switch_to(finally_bb);
537
+ self.push_scope();
538
+ self.lower_stmts(finally_body)?;
539
+ self.pop_scope();
540
+ }
541
+
542
+ Stmt::Throw(expr, _) => {
543
+ let r = self.lower_expr(expr)?;
544
+ self.emit(IrInstruction::Throw(r));
545
+ }
546
+
547
+ Stmt::Defer(expr, _) => {
548
+ self.defer_stack.push(expr.clone());
549
+ }
550
+
551
+ Stmt::Return(expr, _) => {
552
+ let reg = match expr {
553
+ Some(e) => Some(self.lower_expr(e)?),
554
+ None => None,
555
+ };
556
+ self.emit_defers()?;
557
+ self.emit(IrInstruction::Return(reg));
558
+ }
559
+
560
+ Stmt::Break(span) => {
561
+ let target = self
562
+ .loop_stack
563
+ .last()
564
+ .map(|l| l.break_bb)
565
+ .ok_or_else(|| PolyError::spanned("E0302", "'break' outside loop", *span))?;
566
+ self.emit(IrInstruction::Jump(target));
567
+ }
568
+
569
+ Stmt::Continue(span) => {
570
+ let target = self
571
+ .loop_stack
572
+ .last()
573
+ .map(|l| l.continue_bb)
574
+ .ok_or_else(|| PolyError::spanned("E0303", "'continue' outside loop", *span))?;
575
+ self.emit(IrInstruction::Jump(target));
576
+ }
577
+
578
+ Stmt::ExprStmt(expr, _) => {
579
+ let _ = self.lower_expr(expr)?;
580
+ }
581
+
582
+ Stmt::Block(stmts, _) => {
583
+ self.push_scope();
584
+ self.lower_stmts(stmts)?;
585
+ self.pop_scope();
586
+ }
587
+ }
588
+ Ok(())
589
+ }
590
+
591
+ fn lower_expr(&mut self, expr: &Expr) -> Result<Register, PolyError> {
592
+ match expr {
593
+ Expr::Nil(_) => {
594
+ let r = self.alloc_reg(IrType::Dynamic);
595
+ self.emit(IrInstruction::LoadConst(r, Constant::Nil));
596
+ Ok(r)
597
+ }
598
+ Expr::Bool(b, _) => {
599
+ let r = self.alloc_reg(IrType::Bool);
600
+ self.emit(IrInstruction::LoadConst(r, Constant::Bool(*b)));
601
+ Ok(r)
602
+ }
603
+ Expr::Int(i, _) => {
604
+ let r = self.alloc_reg(IrType::I64);
605
+ self.emit(IrInstruction::LoadConst(r, Constant::Int(*i)));
606
+ Ok(r)
607
+ }
608
+ Expr::Float(f, _) => {
609
+ let r = self.alloc_reg(IrType::F64);
610
+ self.emit(IrInstruction::LoadConst(r, Constant::Float(*f)));
611
+ Ok(r)
612
+ }
613
+ Expr::Str(s, _) => {
614
+ let r = self.alloc_reg(IrType::Str);
615
+ self.emit(IrInstruction::LoadConst(r, Constant::String(s.clone())));
616
+ Ok(r)
617
+ }
618
+ Expr::Regex { pattern, flags, .. } => {
619
+ let r = self.alloc_reg(IrType::Dynamic);
620
+ self.emit(IrInstruction::LoadConst(
621
+ r,
622
+ Constant::Regex {
623
+ pattern: pattern.clone(),
624
+ flags: flags.clone(),
625
+ },
626
+ ));
627
+ Ok(r)
628
+ }
629
+ Expr::TemplateStr { parts, .. } => {
630
+ if parts.is_empty() {
631
+ let r = self.alloc_reg(IrType::Str);
632
+ self.emit(IrInstruction::LoadConst(r, Constant::String(String::new())));
633
+ return Ok(r);
634
+ }
635
+ let mut current_reg: Option<Register> = None;
636
+ for p in parts {
637
+ let part_reg = match p {
638
+ TemplatePart::Literal(s) => {
639
+ let r = self.alloc_reg(IrType::Str);
640
+ self.emit(IrInstruction::LoadConst(r, Constant::String(s.clone())));
641
+ r
642
+ }
643
+ TemplatePart::Expr { expr, format_spec } => {
644
+ let raw_r = self.lower_expr(expr)?;
645
+ if let Some(spec) = format_spec {
646
+ let spec_r = self.alloc_reg(IrType::Str);
647
+ self.emit(IrInstruction::LoadConst(
648
+ spec_r,
649
+ Constant::String(format!("%{spec}")),
650
+ ));
651
+ let res_r = self.alloc_reg(IrType::Str);
652
+ self.emit(IrInstruction::CallBuiltin(
653
+ res_r,
654
+ BuiltinId::Sprintf,
655
+ vec![spec_r, raw_r],
656
+ ));
657
+ res_r
658
+ } else {
659
+ let res_r = self.alloc_reg(IrType::Str);
660
+ self.emit(IrInstruction::CallBuiltin(
661
+ res_r,
662
+ BuiltinId::Str,
663
+ vec![raw_r],
664
+ ));
665
+ res_r
666
+ }
667
+ }
668
+ };
669
+ if let Some(acc) = current_reg {
670
+ let next_acc = self.alloc_reg(IrType::Str);
671
+ self.emit(IrInstruction::BinOp(
672
+ IrBinOp::Add,
673
+ next_acc,
674
+ acc,
675
+ part_reg,
676
+ ));
677
+ current_reg = Some(next_acc);
678
+ } else {
679
+ current_reg = Some(part_reg);
680
+ }
681
+ }
682
+ Ok(current_reg.unwrap_or_else(|| {
683
+ let r = self.alloc_reg(IrType::Str);
684
+ self.emit(IrInstruction::LoadConst(r, Constant::String(String::new())));
685
+ r
686
+ }))
687
+ }
688
+ Expr::Var(name, span) => {
689
+ if let Some(r) = self.lookup_var(name) {
690
+ return Ok(r);
691
+ }
692
+ if self.local_fn_names.contains_key(name)
693
+ || self.bindings.named.contains_key(name)
694
+ || !self.bindings.wildcards.is_empty()
695
+ {
696
+ let site = self.alloc_call_site(
697
+ LazyTarget::Direct {
698
+ from_module: self.module_id,
699
+ symbol: name.clone(),
700
+ },
701
+ *span,
702
+ );
703
+ let r = self.alloc_reg(IrType::Dynamic);
704
+ self.emit(IrInstruction::ResolveFn(r, site));
705
+ return Ok(r);
706
+ }
707
+ Err(PolyError::spanned(
708
+ "E0304",
709
+ format!("use of undeclared variable '{name}'"),
710
+ *span,
711
+ ))
712
+ }
713
+ Expr::Array(items, _) | Expr::Tuple(items, _) => {
714
+ let mut regs = Vec::with_capacity(items.len());
715
+ for item in items {
716
+ regs.push(self.lower_expr(item)?);
717
+ }
718
+ let r = self.alloc_reg(IrType::Dynamic);
719
+ self.emit(IrInstruction::CreateArray(r, regs));
720
+ Ok(r)
721
+ }
722
+ Expr::ObjectLit(cls, fields, _) => {
723
+ let obj = self.alloc_reg(IrType::Dynamic);
724
+ let cname = cls.clone().unwrap_or_else(|| "Object".to_string());
725
+ self.emit(IrInstruction::CreateObject(obj, cname));
726
+ for (k, v) in fields {
727
+ let vr = self.lower_expr(v)?;
728
+ self.emit(IrInstruction::SetField(obj, k.clone(), vr));
729
+ }
730
+ Ok(obj)
731
+ }
732
+ Expr::Cast { ty, expr, .. } => {
733
+ let src = self.lower_expr(expr)?;
734
+ let ir_ty = hint_to_ir_type(*ty);
735
+ let dst = self.alloc_reg(ir_ty);
736
+ self.emit(IrInstruction::Cast(dst, ir_ty, src));
737
+ Ok(dst)
738
+ }
739
+ Expr::Unary(op, inner, _) => {
740
+ let src = self.lower_expr(inner)?;
741
+ let dst = self.alloc_reg(IrType::Dynamic);
742
+ let irop = match op {
743
+ UnaryOp::Neg => IrUnaryOp::Neg,
744
+ UnaryOp::Not => IrUnaryOp::Not,
745
+ UnaryOp::BitNot => IrUnaryOp::BitNot,
746
+ };
747
+ self.emit(IrInstruction::UnaryOp(irop, dst, src));
748
+ Ok(dst)
749
+ }
750
+ Expr::Binary(op, l, r, _) => {
751
+ if matches!(op, BinOp::And | BinOp::Or) {
752
+ let l_reg = self.lower_expr(l)?;
753
+ let res = self.alloc_reg(IrType::Bool);
754
+ let rhs_bb = self.new_block();
755
+ let short_bb = self.new_block();
756
+ let merge_bb = self.new_block();
757
+
758
+ if *op == BinOp::And {
759
+ self.emit(IrInstruction::BranchIf(l_reg, rhs_bb, short_bb));
760
+ } else {
761
+ self.emit(IrInstruction::BranchIf(l_reg, short_bb, rhs_bb));
762
+ }
763
+
764
+ self.switch_to(short_bb);
765
+ self.emit(IrInstruction::LoadConst(
766
+ res,
767
+ Constant::Bool(*op == BinOp::Or),
768
+ ));
769
+ self.emit(IrInstruction::Jump(merge_bb));
770
+
771
+ self.switch_to(rhs_bb);
772
+ let r_reg = self.lower_expr(r)?;
773
+ self.emit(IrInstruction::Cast(res, IrType::Bool, r_reg));
774
+ self.emit(IrInstruction::Jump(merge_bb));
775
+
776
+ self.switch_to(merge_bb);
777
+ return Ok(res);
778
+ }
779
+
780
+ if *op == BinOp::NullCoal {
781
+ let l_reg = self.lower_expr(l)?;
782
+ let res = self.alloc_reg(IrType::Dynamic);
783
+ let nil_reg = self.alloc_reg(IrType::Dynamic);
784
+ self.emit(IrInstruction::LoadConst(nil_reg, Constant::Nil));
785
+ let is_nil = self.alloc_reg(IrType::Bool);
786
+ self.emit(IrInstruction::BinOp(IrBinOp::Eq, is_nil, l_reg, nil_reg));
787
+
788
+ let rhs_bb = self.new_block();
789
+ let short_bb = self.new_block();
790
+ let merge_bb = self.new_block();
791
+
792
+ self.emit(IrInstruction::BranchIf(is_nil, rhs_bb, short_bb));
793
+
794
+ self.switch_to(short_bb);
795
+ self.emit(IrInstruction::Move(res, l_reg));
796
+ self.emit(IrInstruction::Jump(merge_bb));
797
+
798
+ self.switch_to(rhs_bb);
799
+ let r_reg = self.lower_expr(r)?;
800
+ self.emit(IrInstruction::Move(res, r_reg));
801
+ self.emit(IrInstruction::Jump(merge_bb));
802
+
803
+ self.switch_to(merge_bb);
804
+ return Ok(res);
805
+ }
806
+
807
+ let lr = self.lower_expr(l)?;
808
+ let rr = self.lower_expr(r)?;
809
+ let dst = self.alloc_reg(IrType::Dynamic);
810
+ self.emit(IrInstruction::BinOp(map_binop(*op), dst, lr, rr));
811
+ Ok(dst)
812
+ }
813
+ Expr::Update {
814
+ name,
815
+ inc,
816
+ prefix,
817
+ span,
818
+ } => {
819
+ let var_reg = self.lookup_var(name).ok_or_else(|| {
820
+ PolyError::spanned("E0304", format!("undeclared variable '{name}'"), *span)
821
+ })?;
822
+ let one = self.alloc_reg(IrType::I64);
823
+ self.emit(IrInstruction::LoadConst(one, Constant::Int(1)));
824
+ let op = if *inc { IrBinOp::Add } else { IrBinOp::Sub };
825
+ if *prefix {
826
+ self.emit(IrInstruction::BinOp(op, var_reg, var_reg, one));
827
+ Ok(var_reg)
828
+ } else {
829
+ let old = self.alloc_reg(self.register_types[var_reg.0]);
830
+ self.emit(IrInstruction::Move(old, var_reg));
831
+ self.emit(IrInstruction::BinOp(op, var_reg, var_reg, one));
832
+ Ok(old)
833
+ }
834
+ }
835
+ Expr::Call { callee, args, span } => {
836
+ let mut arg_regs = Vec::with_capacity(args.len());
837
+ for a in args {
838
+ arg_regs.push(self.lower_expr(a)?);
839
+ }
840
+ let dst = self.alloc_reg(IrType::Dynamic);
841
+
842
+ match &**callee {
843
+ Expr::Var(name, _) => {
844
+ if let Some(var_reg) = self.lookup_var(name) {
845
+ self.emit(IrInstruction::CallIndirect(dst, var_reg, arg_regs));
846
+ return Ok(dst);
847
+ }
848
+ if let Some(builtin) = BuiltinId::from_name(name) {
849
+ self.emit(IrInstruction::CallBuiltin(dst, builtin, arg_regs));
850
+ return Ok(dst);
851
+ }
852
+ if self.local_fn_names.contains_key(name) {
853
+ let site = self.alloc_call_site(
854
+ LazyTarget::SelfModule {
855
+ module_id: self.module_id,
856
+ symbol: name.clone(),
857
+ },
858
+ *span,
859
+ );
860
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
861
+ return Ok(dst);
862
+ }
863
+ let site = self.alloc_call_site(
864
+ LazyTarget::Direct {
865
+ from_module: self.module_id,
866
+ symbol: name.clone(),
867
+ },
868
+ *span,
869
+ );
870
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
871
+ Ok(dst)
872
+ }
873
+ Expr::Member {
874
+ object,
875
+ field,
876
+ optional,
877
+ ..
878
+ } => {
879
+ if let Expr::Var(ns, _) = &**object {
880
+ if (ns == "console" || ns == "Console")
881
+ && (field == "log" || field == "WriteLine" || field == "Write")
882
+ {
883
+ let b = if field == "Write" {
884
+ BuiltinId::Print
885
+ } else {
886
+ BuiltinId::Println
887
+ };
888
+ self.emit(IrInstruction::CallBuiltin(dst, b, arg_regs));
889
+ return Ok(dst);
890
+ }
891
+ if (ns == "Math" || ns == "math")
892
+ && let Some(b) = BuiltinId::from_name(field)
893
+ {
894
+ self.emit(IrInstruction::CallBuiltin(dst, b, arg_regs));
895
+ return Ok(dst);
896
+ }
897
+ if (ns == "fmt" || ns == "std") && (field == "Println" || field == "Print" || field == "Printf" || field == "Sprintf") {
898
+ let b = match field.as_str() {
899
+ "Println" => BuiltinId::Println,
900
+ "Print" => BuiltinId::Print,
901
+ "Printf" => BuiltinId::Printf,
902
+ _ => BuiltinId::Sprintf,
903
+ };
904
+ self.emit(IrInstruction::CallBuiltin(dst, b, arg_regs));
905
+ return Ok(dst);
906
+ }
907
+ if ns == "strings" || ns == "re" || ns == "regexp" || ns == "Regex" {
908
+ let b_opt = match field.as_str() {
909
+ "Contains" | "contains" => Some(BuiltinId::StrContains),
910
+ "Split" | "split" => Some(BuiltinId::StrSplit),
911
+ "TrimSpace" | "Trim" | "trim" => Some(BuiltinId::StrTrim),
912
+ "ToUpper" | "toUpperCase" | "upper" => Some(BuiltinId::StrUpper),
913
+ "ToLower" | "toLowerCase" | "lower" => Some(BuiltinId::StrLower),
914
+ "ReplaceAll" | "Replace" | "replace" => Some(BuiltinId::StrReplace),
915
+ "MatchString" | "match" | "IsMatch" | "test" => Some(BuiltinId::RegexTest),
916
+ "FindAllString" | "findAll" => Some(BuiltinId::RegexFindAll),
917
+ _ => None,
918
+ };
919
+ if let Some(b) = b_opt {
920
+ self.emit(IrInstruction::CallBuiltin(dst, b, arg_regs));
921
+ return Ok(dst);
922
+ }
923
+ }
924
+ if self.bindings.namespaces.contains_key(ns) && self.lookup_var(ns).is_none() {
925
+ let site = self.alloc_call_site(
926
+ LazyTarget::Direct {
927
+ from_module: self.module_id,
928
+ symbol: format!("{ns}::{field}"),
929
+ },
930
+ *span,
931
+ );
932
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
933
+ return Ok(dst);
934
+ }
935
+ }
936
+
937
+ let obj_reg = self.lower_expr(object)?;
938
+ if *optional {
939
+ let nil_r = self.alloc_reg(IrType::Dynamic);
940
+ self.emit(IrInstruction::LoadConst(nil_r, Constant::Nil));
941
+ let is_nil = self.alloc_reg(IrType::Bool);
942
+ self.emit(IrInstruction::BinOp(IrBinOp::Eq, is_nil, obj_reg, nil_r));
943
+ let call_bb = self.new_block();
944
+ let skip_bb = self.new_block();
945
+ let merge_bb = self.new_block();
946
+ self.emit(IrInstruction::BranchIf(is_nil, skip_bb, call_bb));
947
+
948
+ self.switch_to(skip_bb);
949
+ self.emit(IrInstruction::Move(dst, nil_r));
950
+ self.emit(IrInstruction::Jump(merge_bb));
951
+
952
+ self.switch_to(call_bb);
953
+ self.emit(IrInstruction::CallMethod(
954
+ dst,
955
+ obj_reg,
956
+ field.clone(),
957
+ arg_regs,
958
+ ));
959
+ self.emit(IrInstruction::Jump(merge_bb));
960
+
961
+ self.switch_to(merge_bb);
962
+ return Ok(dst);
963
+ }
964
+
965
+ self.emit(IrInstruction::CallMethod(
966
+ dst,
967
+ obj_reg,
968
+ field.clone(),
969
+ arg_regs,
970
+ ));
971
+ Ok(dst)
972
+ }
973
+ other => {
974
+ let fn_reg = self.lower_expr(other)?;
975
+ self.emit(IrInstruction::CallIndirect(dst, fn_reg, arg_regs));
976
+ Ok(dst)
977
+ }
978
+ }
979
+ }
980
+ Expr::Member {
981
+ object,
982
+ field,
983
+ optional,
984
+ ..
985
+ } => {
986
+ let obj_reg = self.lower_expr(object)?;
987
+ let dst = self.alloc_reg(IrType::Dynamic);
988
+
989
+ if *optional {
990
+ let nil_r = self.alloc_reg(IrType::Dynamic);
991
+ self.emit(IrInstruction::LoadConst(nil_r, Constant::Nil));
992
+ let is_nil = self.alloc_reg(IrType::Bool);
993
+ self.emit(IrInstruction::BinOp(IrBinOp::Eq, is_nil, obj_reg, nil_r));
994
+ let get_bb = self.new_block();
995
+ let skip_bb = self.new_block();
996
+ let merge_bb = self.new_block();
997
+ self.emit(IrInstruction::BranchIf(is_nil, skip_bb, get_bb));
998
+
999
+ self.switch_to(skip_bb);
1000
+ self.emit(IrInstruction::Move(dst, nil_r));
1001
+ self.emit(IrInstruction::Jump(merge_bb));
1002
+
1003
+ self.switch_to(get_bb);
1004
+ self.emit(IrInstruction::GetField(dst, obj_reg, field.clone()));
1005
+ self.emit(IrInstruction::Jump(merge_bb));
1006
+
1007
+ self.switch_to(merge_bb);
1008
+ return Ok(dst);
1009
+ }
1010
+
1011
+ if field == "length" || field == "Count" {
1012
+ self.emit(IrInstruction::CallBuiltin(
1013
+ dst,
1014
+ BuiltinId::Len,
1015
+ vec![obj_reg],
1016
+ ));
1017
+ } else {
1018
+ self.emit(IrInstruction::GetField(dst, obj_reg, field.clone()));
1019
+ }
1020
+ Ok(dst)
1021
+ }
1022
+ Expr::Index { object, index, .. } => {
1023
+ let obj_reg = self.lower_expr(object)?;
1024
+ let idx_reg = self.lower_expr(index)?;
1025
+ let dst = self.alloc_reg(IrType::Dynamic);
1026
+ self.emit(IrInstruction::GetIndex(dst, obj_reg, idx_reg));
1027
+ Ok(dst)
1028
+ }
1029
+ Expr::Ternary {
1030
+ cond,
1031
+ then_expr,
1032
+ else_expr,
1033
+ ..
1034
+ } => {
1035
+ let cond_reg = self.lower_expr(cond)?;
1036
+ let res = self.alloc_reg(IrType::Dynamic);
1037
+ let then_bb = self.new_block();
1038
+ let else_bb = self.new_block();
1039
+ let merge_bb = self.new_block();
1040
+ self.emit(IrInstruction::BranchIf(cond_reg, then_bb, else_bb));
1041
+
1042
+ self.switch_to(then_bb);
1043
+ let tv = self.lower_expr(then_expr)?;
1044
+ self.emit(IrInstruction::Move(res, tv));
1045
+ self.emit(IrInstruction::Jump(merge_bb));
1046
+
1047
+ self.switch_to(else_bb);
1048
+ let ev = self.lower_expr(else_expr)?;
1049
+ self.emit(IrInstruction::Move(res, ev));
1050
+ self.emit(IrInstruction::Jump(merge_bb));
1051
+
1052
+ self.switch_to(merge_bb);
1053
+ Ok(res)
1054
+ }
1055
+ }
1056
+ }
1057
+ }
1058
+
1059
+ fn hint_to_ir_type(hint: TypeHint) -> IrType {
1060
+ match hint {
1061
+ TypeHint::Unknown | TypeHint::Array | TypeHint::Object | TypeHint::Regex => IrType::Dynamic,
1062
+ TypeHint::Void => IrType::Void,
1063
+ TypeHint::Bool => IrType::Bool,
1064
+ TypeHint::Int => IrType::I64,
1065
+ TypeHint::Float => IrType::F64,
1066
+ TypeHint::Str => IrType::Str,
1067
+ }
1068
+ }
1069
+
1070
+ fn map_binop(op: BinOp) -> IrBinOp {
1071
+ match op {
1072
+ BinOp::Add => IrBinOp::Add,
1073
+ BinOp::Sub => IrBinOp::Sub,
1074
+ BinOp::Mul => IrBinOp::Mul,
1075
+ BinOp::Div => IrBinOp::Div,
1076
+ BinOp::FloorDiv => IrBinOp::FloorDiv,
1077
+ BinOp::Mod => IrBinOp::Mod,
1078
+ BinOp::Pow => IrBinOp::Pow,
1079
+ BinOp::Eq => IrBinOp::Eq,
1080
+ BinOp::Ne => IrBinOp::Ne,
1081
+ BinOp::Lt => IrBinOp::Lt,
1082
+ BinOp::Le => IrBinOp::Le,
1083
+ BinOp::Gt => IrBinOp::Gt,
1084
+ BinOp::Ge => IrBinOp::Ge,
1085
+ BinOp::And => IrBinOp::And,
1086
+ BinOp::Or => IrBinOp::Or,
1087
+ BinOp::NullCoal => IrBinOp::Or,
1088
+ BinOp::BitAnd => IrBinOp::BitAnd,
1089
+ BinOp::BitOr => IrBinOp::BitOr,
1090
+ BinOp::BitXor => IrBinOp::BitXor,
1091
+ BinOp::Shl => IrBinOp::Shl,
1092
+ BinOp::Shr => IrBinOp::Shr,
1093
+ }
1094
+ }
1095
+
1096
+ pub fn lower_function(
1097
+ fn_id: FnId,
1098
+ module_id: usize,
1099
+ qualified_name: String,
1100
+ decl: &FunctionDecl,
1101
+ bindings: &ImportBindings,
1102
+ local_fn_names: &FxHashMap<String, usize>,
1103
+ call_sites: &mut Vec<CallSite>,
1104
+ ) -> Result<IrFunction, PolyError> {
1105
+ let mut lowerer = Lowerer::new(module_id, fn_id, bindings, local_fn_names, call_sites);
1106
+ let mut params = Vec::with_capacity(decl.params.len());
1107
+ for p in &decl.params {
1108
+ let ir_ty = hint_to_ir_type(p.ty);
1109
+ let reg = lowerer.alloc_reg(ir_ty);
1110
+ lowerer.bind_var(p.name.clone(), reg, true);
1111
+ params.push((reg, ir_ty));
1112
+ }
1113
+
1114
+ lowerer.lower_stmts(&decl.body)?;
1115
+ if !lowerer.current_terminated() {
1116
+ lowerer.emit_defers()?;
1117
+ lowerer.emit(IrInstruction::Return(None));
1118
+ }
1119
+
1120
+ Ok(IrFunction {
1121
+ id: fn_id,
1122
+ module_id,
1123
+ qualified_name,
1124
+ params,
1125
+ return_type: hint_to_ir_type(decl.return_type),
1126
+ register_types: lowerer.register_types,
1127
+ blocks: lowerer.blocks,
1128
+ })
1129
+ }
1130
+
1131
+ pub fn lower_top_level(
1132
+ fn_id: FnId,
1133
+ module_id: usize,
1134
+ qualified_name: String,
1135
+ stmts: &[Stmt],
1136
+ bindings: &ImportBindings,
1137
+ local_fn_names: &FxHashMap<String, usize>,
1138
+ call_sites: &mut Vec<CallSite>,
1139
+ ) -> Result<IrFunction, PolyError> {
1140
+ let fake_decl = FunctionDecl {
1141
+ name: "__top_level".to_string(),
1142
+ params: Vec::new(),
1143
+ return_type: TypeHint::Unknown,
1144
+ body: stmts.to_vec(),
1145
+ is_exported: false,
1146
+ span: Span::dummy(),
1147
+ };
1148
+ lower_function(
1149
+ fn_id,
1150
+ module_id,
1151
+ qualified_name,
1152
+ &fake_decl,
1153
+ bindings,
1154
+ local_fn_names,
1155
+ call_sites,
1156
+ )
1157
+ }