polycomp 0.0.0-stage → 0.2.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,826 @@
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
+ }
25
+
26
+ impl<'a> Lowerer<'a> {
27
+ fn new(
28
+ module_id: usize,
29
+ fn_id: FnId,
30
+ bindings: &'a ImportBindings,
31
+ local_fn_names: &'a FxHashMap<String, usize>,
32
+ call_sites: &'a mut Vec<CallSite>,
33
+ ) -> Self {
34
+ Self {
35
+ module_id,
36
+ fn_id,
37
+ bindings,
38
+ local_fn_names,
39
+ call_sites,
40
+ next_reg: 0,
41
+ register_types: Vec::new(),
42
+ blocks: vec![BasicBlock {
43
+ id: BasicBlockId(0),
44
+ instructions: Vec::new(),
45
+ }],
46
+ current_block: 0,
47
+ scopes: vec![FxHashMap::default()],
48
+ loop_stack: Vec::new(),
49
+ }
50
+ }
51
+
52
+ fn alloc_reg(&mut self, ty: IrType) -> Register {
53
+ let r = Register(self.next_reg);
54
+ self.next_reg += 1;
55
+ self.register_types.push(ty);
56
+ r
57
+ }
58
+
59
+ fn new_block(&mut self) -> BasicBlockId {
60
+ let id = BasicBlockId(self.blocks.len());
61
+ self.blocks.push(BasicBlock {
62
+ id,
63
+ instructions: Vec::new(),
64
+ });
65
+ id
66
+ }
67
+
68
+ fn switch_to(&mut self, id: BasicBlockId) {
69
+ self.current_block = id.0;
70
+ }
71
+
72
+ fn current_terminated(&self) -> bool {
73
+ self.blocks[self.current_block]
74
+ .instructions
75
+ .last()
76
+ .is_some_and(|i| {
77
+ matches!(
78
+ i,
79
+ IrInstruction::Return(_)
80
+ | IrInstruction::Jump(_)
81
+ | IrInstruction::BranchIf(_, _, _)
82
+ )
83
+ })
84
+ }
85
+
86
+ fn emit(&mut self, instr: IrInstruction) {
87
+ if !self.current_terminated() {
88
+ self.blocks[self.current_block].instructions.push(instr);
89
+ }
90
+ }
91
+
92
+ fn push_scope(&mut self) {
93
+ self.scopes.push(FxHashMap::default());
94
+ }
95
+
96
+ fn pop_scope(&mut self) {
97
+ if self.scopes.len() > 1 {
98
+ self.scopes.pop();
99
+ }
100
+ }
101
+
102
+ fn lookup_var(&self, name: &str) -> Option<Register> {
103
+ for scope in self.scopes.iter().rev() {
104
+ if let Some(&r) = scope.get(name) {
105
+ return Some(r);
106
+ }
107
+ }
108
+ None
109
+ }
110
+
111
+ fn bind_var(&mut self, name: String, reg: Register, fn_scoped: bool) {
112
+ if fn_scoped {
113
+ self.scopes[0].insert(name, reg);
114
+ } else {
115
+ self.scopes.last_mut().unwrap().insert(name, reg);
116
+ }
117
+ }
118
+
119
+ fn alloc_call_site(&mut self, target: LazyTarget, span: Span) -> CallSiteId {
120
+ let id = CallSiteId(self.call_sites.len() as u32);
121
+ self.call_sites.push(CallSite {
122
+ id,
123
+ target,
124
+ span,
125
+ resolved_fn: None,
126
+ });
127
+ id
128
+ }
129
+
130
+ fn lower_stmts(&mut self, stmts: &[Stmt]) -> Result<(), PolyError> {
131
+ for stmt in stmts {
132
+ self.lower_stmt(stmt)?;
133
+ if self.current_terminated() {
134
+ break;
135
+ }
136
+ }
137
+ Ok(())
138
+ }
139
+
140
+ fn lower_stmt(&mut self, stmt: &Stmt) -> Result<(), PolyError> {
141
+ match stmt {
142
+ Stmt::VarDecl {
143
+ name,
144
+ ty,
145
+ init,
146
+ is_function_scoped,
147
+ ..
148
+ } => {
149
+ let ir_ty = hint_to_ir_type(*ty);
150
+ let existing = if *is_function_scoped {
151
+ self.lookup_var(name)
152
+ } else {
153
+ self.scopes.last().unwrap().get(name).copied()
154
+ };
155
+ let dst = existing.unwrap_or_else(|| {
156
+ let r = self.alloc_reg(ir_ty);
157
+ self.bind_var(name.clone(), r, *is_function_scoped);
158
+ r
159
+ });
160
+
161
+ if let Some(expr) = init {
162
+ let val_reg = self.lower_expr(expr)?;
163
+ if ir_ty != IrType::Dynamic && ir_ty != IrType::Void {
164
+ self.emit(IrInstruction::Cast(dst, ir_ty, val_reg));
165
+ } else {
166
+ self.emit(IrInstruction::Move(dst, val_reg));
167
+ }
168
+ } else {
169
+ self.emit(IrInstruction::LoadConst(dst, Constant::Nil));
170
+ }
171
+ }
172
+
173
+ Stmt::Assign {
174
+ target, op, value, span
175
+ } => {
176
+ let rhs = self.lower_expr(value)?;
177
+ match target {
178
+ AssignTarget::Var(name) => {
179
+ let var_reg = self.lookup_var(name).ok_or_else(|| {
180
+ PolyError::spanned(
181
+ "E0301",
182
+ format!("assignment to undeclared variable '{name}'"),
183
+ *span,
184
+ )
185
+ })?;
186
+ if let Some(bin_op) = op {
187
+ self.emit(IrInstruction::BinOp(
188
+ map_binop(*bin_op),
189
+ var_reg,
190
+ var_reg,
191
+ rhs,
192
+ ));
193
+ } else {
194
+ self.emit(IrInstruction::Move(var_reg, rhs));
195
+ }
196
+ }
197
+ AssignTarget::Field(obj_expr, field) => {
198
+ let obj_reg = self.lower_expr(obj_expr)?;
199
+ if let Some(bin_op) = op {
200
+ let tmp = self.alloc_reg(IrType::Dynamic);
201
+ self.emit(IrInstruction::GetField(tmp, obj_reg, field.clone()));
202
+ let res = self.alloc_reg(IrType::Dynamic);
203
+ self.emit(IrInstruction::BinOp(map_binop(*bin_op), res, tmp, rhs));
204
+ self.emit(IrInstruction::SetField(obj_reg, field.clone(), res));
205
+ } else {
206
+ self.emit(IrInstruction::SetField(obj_reg, field.clone(), rhs));
207
+ }
208
+ }
209
+ AssignTarget::Index(obj_expr, idx_expr) => {
210
+ let obj_reg = self.lower_expr(obj_expr)?;
211
+ let idx_reg = self.lower_expr(idx_expr)?;
212
+ if let Some(bin_op) = op {
213
+ let tmp = self.alloc_reg(IrType::Dynamic);
214
+ self.emit(IrInstruction::GetIndex(tmp, obj_reg, idx_reg));
215
+ let res = self.alloc_reg(IrType::Dynamic);
216
+ self.emit(IrInstruction::BinOp(map_binop(*bin_op), res, tmp, rhs));
217
+ self.emit(IrInstruction::SetIndex(obj_reg, idx_reg, res));
218
+ } else {
219
+ self.emit(IrInstruction::SetIndex(obj_reg, idx_reg, rhs));
220
+ }
221
+ }
222
+ }
223
+ }
224
+
225
+ Stmt::If {
226
+ cond,
227
+ then_body,
228
+ else_body,
229
+ ..
230
+ } => {
231
+ let cond_reg = self.lower_expr(cond)?;
232
+ let then_bb = self.new_block();
233
+ let else_bb = self.new_block();
234
+ let merge_bb = self.new_block();
235
+
236
+ self.emit(IrInstruction::BranchIf(cond_reg, then_bb, else_bb));
237
+
238
+ self.switch_to(then_bb);
239
+ self.push_scope();
240
+ self.lower_stmts(then_body)?;
241
+ self.pop_scope();
242
+ self.emit(IrInstruction::Jump(merge_bb));
243
+
244
+ self.switch_to(else_bb);
245
+ self.push_scope();
246
+ self.lower_stmts(else_body)?;
247
+ self.pop_scope();
248
+ self.emit(IrInstruction::Jump(merge_bb));
249
+
250
+ self.switch_to(merge_bb);
251
+ }
252
+
253
+ Stmt::While { cond, body, .. } => {
254
+ let header_bb = self.new_block();
255
+ let body_bb = self.new_block();
256
+ let exit_bb = self.new_block();
257
+
258
+ self.emit(IrInstruction::Jump(header_bb));
259
+ self.switch_to(header_bb);
260
+ let cond_reg = self.lower_expr(cond)?;
261
+ self.emit(IrInstruction::BranchIf(cond_reg, body_bb, exit_bb));
262
+
263
+ self.loop_stack.push(LoopTargets {
264
+ break_bb: exit_bb,
265
+ continue_bb: header_bb,
266
+ });
267
+ self.switch_to(body_bb);
268
+ self.push_scope();
269
+ self.lower_stmts(body)?;
270
+ self.pop_scope();
271
+ self.emit(IrInstruction::Jump(header_bb));
272
+ self.loop_stack.pop();
273
+
274
+ self.switch_to(exit_bb);
275
+ }
276
+
277
+ Stmt::ForRange {
278
+ var,
279
+ start,
280
+ end,
281
+ inclusive,
282
+ step,
283
+ body,
284
+ ..
285
+ } => {
286
+ let start_reg = self.lower_expr(start)?;
287
+ let end_reg = self.lower_expr(end)?;
288
+ let step_reg = if let Some(st) = step {
289
+ self.lower_expr(st)?
290
+ } else {
291
+ let s = self.alloc_reg(IrType::I64);
292
+ self.emit(IrInstruction::LoadConst(s, Constant::Int(1)));
293
+ s
294
+ };
295
+
296
+ self.push_scope();
297
+ let idx_reg = self.alloc_reg(IrType::I64);
298
+ self.emit(IrInstruction::Move(idx_reg, start_reg));
299
+ self.bind_var(var.clone(), idx_reg, false);
300
+
301
+ let header_bb = self.new_block();
302
+ let body_bb = self.new_block();
303
+ let step_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 cmp_reg = self.alloc_reg(IrType::Bool);
309
+ let cmp_op = if *inclusive { IrBinOp::Le } else { IrBinOp::Lt };
310
+ self.emit(IrInstruction::BinOp(cmp_op, cmp_reg, idx_reg, end_reg));
311
+ self.emit(IrInstruction::BranchIf(cmp_reg, body_bb, exit_bb));
312
+
313
+ self.loop_stack.push(LoopTargets {
314
+ break_bb: exit_bb,
315
+ continue_bb: step_bb,
316
+ });
317
+ self.switch_to(body_bb);
318
+ self.lower_stmts(body)?;
319
+ self.emit(IrInstruction::Jump(step_bb));
320
+ self.loop_stack.pop();
321
+
322
+ self.switch_to(step_bb);
323
+ self.emit(IrInstruction::BinOp(
324
+ IrBinOp::Add,
325
+ idx_reg,
326
+ idx_reg,
327
+ step_reg,
328
+ ));
329
+ self.emit(IrInstruction::Jump(header_bb));
330
+
331
+ self.pop_scope();
332
+ self.switch_to(exit_bb);
333
+ }
334
+
335
+ Stmt::ForIn {
336
+ var, iter, body, ..
337
+ } => {
338
+ let arr_reg = self.lower_expr(iter)?;
339
+ let len_reg = self.alloc_reg(IrType::I64);
340
+ self.emit(IrInstruction::CallBuiltin(
341
+ len_reg,
342
+ BuiltinId::Len,
343
+ vec![arr_reg],
344
+ ));
345
+ let idx_reg = self.alloc_reg(IrType::I64);
346
+ self.emit(IrInstruction::LoadConst(idx_reg, Constant::Int(0)));
347
+ let one_reg = self.alloc_reg(IrType::I64);
348
+ self.emit(IrInstruction::LoadConst(one_reg, Constant::Int(1)));
349
+
350
+ self.push_scope();
351
+ let elem_reg = self.alloc_reg(IrType::Dynamic);
352
+ self.bind_var(var.clone(), elem_reg, false);
353
+
354
+ let header_bb = self.new_block();
355
+ let body_bb = self.new_block();
356
+ let step_bb = self.new_block();
357
+ let exit_bb = self.new_block();
358
+
359
+ self.emit(IrInstruction::Jump(header_bb));
360
+ self.switch_to(header_bb);
361
+ let cmp_reg = self.alloc_reg(IrType::Bool);
362
+ self.emit(IrInstruction::BinOp(
363
+ IrBinOp::Lt,
364
+ cmp_reg,
365
+ idx_reg,
366
+ len_reg,
367
+ ));
368
+ self.emit(IrInstruction::BranchIf(cmp_reg, body_bb, exit_bb));
369
+
370
+ self.switch_to(body_bb);
371
+ self.emit(IrInstruction::GetIndex(elem_reg, arr_reg, idx_reg));
372
+ self.loop_stack.push(LoopTargets {
373
+ break_bb: exit_bb,
374
+ continue_bb: step_bb,
375
+ });
376
+ self.lower_stmts(body)?;
377
+ self.emit(IrInstruction::Jump(step_bb));
378
+ self.loop_stack.pop();
379
+
380
+ self.switch_to(step_bb);
381
+ self.emit(IrInstruction::BinOp(
382
+ IrBinOp::Add,
383
+ idx_reg,
384
+ idx_reg,
385
+ one_reg,
386
+ ));
387
+ self.emit(IrInstruction::Jump(header_bb));
388
+
389
+ self.pop_scope();
390
+ self.switch_to(exit_bb);
391
+ }
392
+
393
+ Stmt::Return(expr, _) => {
394
+ let reg = match expr {
395
+ Some(e) => Some(self.lower_expr(e)?),
396
+ None => None,
397
+ };
398
+ self.emit(IrInstruction::Return(reg));
399
+ }
400
+
401
+ Stmt::Break(span) => {
402
+ let target = self
403
+ .loop_stack
404
+ .last()
405
+ .map(|l| l.break_bb)
406
+ .ok_or_else(|| PolyError::spanned("E0302", "'break' outside loop", *span))?;
407
+ self.emit(IrInstruction::Jump(target));
408
+ }
409
+
410
+ Stmt::Continue(span) => {
411
+ let target = self
412
+ .loop_stack
413
+ .last()
414
+ .map(|l| l.continue_bb)
415
+ .ok_or_else(|| PolyError::spanned("E0303", "'continue' outside loop", *span))?;
416
+ self.emit(IrInstruction::Jump(target));
417
+ }
418
+
419
+ Stmt::ExprStmt(expr, _) => {
420
+ let _ = self.lower_expr(expr)?;
421
+ }
422
+
423
+ Stmt::Block(stmts, _) => {
424
+ self.push_scope();
425
+ self.lower_stmts(stmts)?;
426
+ self.pop_scope();
427
+ }
428
+ }
429
+ Ok(())
430
+ }
431
+
432
+ fn lower_expr(&mut self, expr: &Expr) -> Result<Register, PolyError> {
433
+ match expr {
434
+ Expr::Nil(_) => {
435
+ let r = self.alloc_reg(IrType::Dynamic);
436
+ self.emit(IrInstruction::LoadConst(r, Constant::Nil));
437
+ Ok(r)
438
+ }
439
+ Expr::Bool(b, _) => {
440
+ let r = self.alloc_reg(IrType::Bool);
441
+ self.emit(IrInstruction::LoadConst(r, Constant::Bool(*b)));
442
+ Ok(r)
443
+ }
444
+ Expr::Int(i, _) => {
445
+ let r = self.alloc_reg(IrType::I64);
446
+ self.emit(IrInstruction::LoadConst(r, Constant::Int(*i)));
447
+ Ok(r)
448
+ }
449
+ Expr::Float(f, _) => {
450
+ let r = self.alloc_reg(IrType::F64);
451
+ self.emit(IrInstruction::LoadConst(r, Constant::Float(*f)));
452
+ Ok(r)
453
+ }
454
+ Expr::Str(s, _) => {
455
+ let r = self.alloc_reg(IrType::Str);
456
+ self.emit(IrInstruction::LoadConst(r, Constant::String(s.clone())));
457
+ Ok(r)
458
+ }
459
+ Expr::Var(name, span) => {
460
+ if let Some(r) = self.lookup_var(name) {
461
+ return Ok(r);
462
+ }
463
+ if self.local_fn_names.contains_key(name)
464
+ || self.bindings.named.contains_key(name)
465
+ || !self.bindings.wildcards.is_empty()
466
+ {
467
+ let site = self.alloc_call_site(
468
+ LazyTarget::Direct {
469
+ from_module: self.module_id,
470
+ symbol: name.clone(),
471
+ },
472
+ *span,
473
+ );
474
+ let r = self.alloc_reg(IrType::Dynamic);
475
+ self.emit(IrInstruction::ResolveFn(r, site));
476
+ return Ok(r);
477
+ }
478
+ Err(PolyError::spanned(
479
+ "E0304",
480
+ format!("use of undeclared variable '{name}'"),
481
+ *span,
482
+ ))
483
+ }
484
+ Expr::Array(items, _) => {
485
+ let mut regs = Vec::with_capacity(items.len());
486
+ for item in items {
487
+ regs.push(self.lower_expr(item)?);
488
+ }
489
+ let r = self.alloc_reg(IrType::Dynamic);
490
+ self.emit(IrInstruction::CreateArray(r, regs));
491
+ Ok(r)
492
+ }
493
+ Expr::ObjectLit(cls, fields, _) => {
494
+ let obj = self.alloc_reg(IrType::Dynamic);
495
+ let cname = cls.clone().unwrap_or_else(|| "Object".to_string());
496
+ self.emit(IrInstruction::CreateObject(obj, cname));
497
+ for (k, v) in fields {
498
+ let vr = self.lower_expr(v)?;
499
+ self.emit(IrInstruction::SetField(obj, k.clone(), vr));
500
+ }
501
+ Ok(obj)
502
+ }
503
+ Expr::Unary(op, inner, _) => {
504
+ let src = self.lower_expr(inner)?;
505
+ let dst = self.alloc_reg(IrType::Dynamic);
506
+ let irop = match op {
507
+ UnaryOp::Neg => IrUnaryOp::Neg,
508
+ UnaryOp::Not => IrUnaryOp::Not,
509
+ UnaryOp::BitNot => IrUnaryOp::BitNot,
510
+ };
511
+ self.emit(IrInstruction::UnaryOp(irop, dst, src));
512
+ Ok(dst)
513
+ }
514
+ Expr::Binary(op, l, r, _) => {
515
+ // Short-circuit `&&` / `||` / `and` / `or`
516
+ if matches!(op, BinOp::And | BinOp::Or) {
517
+ let l_reg = self.lower_expr(l)?;
518
+ let res = self.alloc_reg(IrType::Bool);
519
+ let rhs_bb = self.new_block();
520
+ let short_bb = self.new_block();
521
+ let merge_bb = self.new_block();
522
+
523
+ if *op == BinOp::And {
524
+ self.emit(IrInstruction::BranchIf(l_reg, rhs_bb, short_bb));
525
+ } else {
526
+ self.emit(IrInstruction::BranchIf(l_reg, short_bb, rhs_bb));
527
+ }
528
+
529
+ self.switch_to(short_bb);
530
+ self.emit(IrInstruction::LoadConst(
531
+ res,
532
+ Constant::Bool(*op == BinOp::Or),
533
+ ));
534
+ self.emit(IrInstruction::Jump(merge_bb));
535
+
536
+ self.switch_to(rhs_bb);
537
+ let r_reg = self.lower_expr(r)?;
538
+ self.emit(IrInstruction::Cast(res, IrType::Bool, r_reg));
539
+ self.emit(IrInstruction::Jump(merge_bb));
540
+
541
+ self.switch_to(merge_bb);
542
+ return Ok(res);
543
+ }
544
+
545
+ let lr = self.lower_expr(l)?;
546
+ let rr = self.lower_expr(r)?;
547
+ let dst = self.alloc_reg(IrType::Dynamic);
548
+ self.emit(IrInstruction::BinOp(map_binop(*op), dst, lr, rr));
549
+ Ok(dst)
550
+ }
551
+ Expr::Update {
552
+ name,
553
+ inc,
554
+ prefix,
555
+ span,
556
+ } => {
557
+ let var_reg = self.lookup_var(name).ok_or_else(|| {
558
+ PolyError::spanned("E0304", format!("undeclared variable '{name}'"), *span)
559
+ })?;
560
+ let one = self.alloc_reg(IrType::I64);
561
+ self.emit(IrInstruction::LoadConst(one, Constant::Int(1)));
562
+ let op = if *inc { IrBinOp::Add } else { IrBinOp::Sub };
563
+ if *prefix {
564
+ self.emit(IrInstruction::BinOp(op, var_reg, var_reg, one));
565
+ Ok(var_reg)
566
+ } else {
567
+ let old = self.alloc_reg(self.register_types[var_reg.0]);
568
+ self.emit(IrInstruction::Move(old, var_reg));
569
+ self.emit(IrInstruction::BinOp(op, var_reg, var_reg, one));
570
+ Ok(old)
571
+ }
572
+ }
573
+ Expr::Call { callee, args, span } => {
574
+ let mut arg_regs = Vec::with_capacity(args.len());
575
+ for a in args {
576
+ arg_regs.push(self.lower_expr(a)?);
577
+ }
578
+ let dst = self.alloc_reg(IrType::Dynamic);
579
+
580
+ match &**callee {
581
+ Expr::Var(name, _) => {
582
+ if let Some(var_reg) = self.lookup_var(name) {
583
+ self.emit(IrInstruction::CallIndirect(dst, var_reg, arg_regs));
584
+ return Ok(dst);
585
+ }
586
+ if let Some(builtin) = BuiltinId::from_name(name) {
587
+ self.emit(IrInstruction::CallBuiltin(dst, builtin, arg_regs));
588
+ return Ok(dst);
589
+ }
590
+ if let Some(&idx) = self.local_fn_names.get(name) {
591
+ // If calling self directly, emit fast CallFn!
592
+ let _ = idx;
593
+ let site = self.alloc_call_site(
594
+ LazyTarget::SelfModule {
595
+ module_id: self.module_id,
596
+ symbol: name.clone(),
597
+ },
598
+ *span,
599
+ );
600
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
601
+ return Ok(dst);
602
+ }
603
+ let site = self.alloc_call_site(
604
+ LazyTarget::Direct {
605
+ from_module: self.module_id,
606
+ symbol: name.clone(),
607
+ },
608
+ *span,
609
+ );
610
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
611
+ Ok(dst)
612
+ }
613
+ Expr::Member { object, field, .. } => {
614
+ if let Expr::Var(ns, _) = &**object {
615
+ if ns == "console" && field == "log" {
616
+ self.emit(IrInstruction::CallBuiltin(
617
+ dst,
618
+ BuiltinId::Println,
619
+ arg_regs,
620
+ ));
621
+ return Ok(dst);
622
+ }
623
+ if ns == "Math"
624
+ && let Some(b) = BuiltinId::from_name(field)
625
+ {
626
+ self.emit(IrInstruction::CallBuiltin(dst, b, arg_regs));
627
+ return Ok(dst);
628
+ }
629
+ if self.bindings.namespaces.contains_key(ns) && self.lookup_var(ns).is_none()
630
+ {
631
+ let site = self.alloc_call_site(
632
+ LazyTarget::Direct {
633
+ from_module: self.module_id,
634
+ symbol: format!("{ns}::{field}"),
635
+ },
636
+ *span,
637
+ );
638
+ self.emit(IrInstruction::CallLazy(dst, site, arg_regs));
639
+ return Ok(dst);
640
+ }
641
+ }
642
+ let obj_reg = self.lower_expr(object)?;
643
+ if field == "push" || field == "append" {
644
+ let mut b_args = vec![obj_reg];
645
+ b_args.extend(arg_regs);
646
+ self.emit(IrInstruction::CallBuiltin(dst, BuiltinId::Push, b_args));
647
+ return Ok(dst);
648
+ }
649
+ if field == "pop" && arg_regs.is_empty() {
650
+ self.emit(IrInstruction::CallBuiltin(
651
+ dst,
652
+ BuiltinId::Pop,
653
+ vec![obj_reg],
654
+ ));
655
+ return Ok(dst);
656
+ }
657
+ if field == "len" && arg_regs.is_empty() {
658
+ self.emit(IrInstruction::CallBuiltin(
659
+ dst,
660
+ BuiltinId::Len,
661
+ vec![obj_reg],
662
+ ));
663
+ return Ok(dst);
664
+ }
665
+ let fn_reg = self.alloc_reg(IrType::Dynamic);
666
+ self.emit(IrInstruction::GetField(fn_reg, obj_reg, field.clone()));
667
+ let mut m_args = vec![obj_reg];
668
+ m_args.extend(arg_regs);
669
+ self.emit(IrInstruction::CallIndirect(dst, fn_reg, m_args));
670
+ Ok(dst)
671
+ }
672
+ other => {
673
+ let fn_reg = self.lower_expr(other)?;
674
+ self.emit(IrInstruction::CallIndirect(dst, fn_reg, arg_regs));
675
+ Ok(dst)
676
+ }
677
+ }
678
+ }
679
+ Expr::Member { object, field, .. } => {
680
+ let obj_reg = self.lower_expr(object)?;
681
+ let dst = self.alloc_reg(IrType::Dynamic);
682
+ if field == "length" {
683
+ self.emit(IrInstruction::CallBuiltin(
684
+ dst,
685
+ BuiltinId::Len,
686
+ vec![obj_reg],
687
+ ));
688
+ } else {
689
+ self.emit(IrInstruction::GetField(dst, obj_reg, field.clone()));
690
+ }
691
+ Ok(dst)
692
+ }
693
+ Expr::Index { object, index, .. } => {
694
+ let obj_reg = self.lower_expr(object)?;
695
+ let idx_reg = self.lower_expr(index)?;
696
+ let dst = self.alloc_reg(IrType::Dynamic);
697
+ self.emit(IrInstruction::GetIndex(dst, obj_reg, idx_reg));
698
+ Ok(dst)
699
+ }
700
+ Expr::Ternary {
701
+ cond,
702
+ then_expr,
703
+ else_expr,
704
+ ..
705
+ } => {
706
+ let cond_reg = self.lower_expr(cond)?;
707
+ let res = self.alloc_reg(IrType::Dynamic);
708
+ let then_bb = self.new_block();
709
+ let else_bb = self.new_block();
710
+ let merge_bb = self.new_block();
711
+ self.emit(IrInstruction::BranchIf(cond_reg, then_bb, else_bb));
712
+
713
+ self.switch_to(then_bb);
714
+ let tv = self.lower_expr(then_expr)?;
715
+ self.emit(IrInstruction::Move(res, tv));
716
+ self.emit(IrInstruction::Jump(merge_bb));
717
+
718
+ self.switch_to(else_bb);
719
+ let ev = self.lower_expr(else_expr)?;
720
+ self.emit(IrInstruction::Move(res, ev));
721
+ self.emit(IrInstruction::Jump(merge_bb));
722
+
723
+ self.switch_to(merge_bb);
724
+ Ok(res)
725
+ }
726
+ }
727
+ }
728
+ }
729
+
730
+ fn hint_to_ir_type(hint: TypeHint) -> IrType {
731
+ match hint {
732
+ TypeHint::Unknown => IrType::Dynamic,
733
+ TypeHint::Void => IrType::Void,
734
+ TypeHint::Bool => IrType::Bool,
735
+ TypeHint::Int => IrType::I64,
736
+ TypeHint::Float => IrType::F64,
737
+ TypeHint::Str => IrType::Str,
738
+ }
739
+ }
740
+
741
+ fn map_binop(op: BinOp) -> IrBinOp {
742
+ match op {
743
+ BinOp::Add => IrBinOp::Add,
744
+ BinOp::Sub => IrBinOp::Sub,
745
+ BinOp::Mul => IrBinOp::Mul,
746
+ BinOp::Div => IrBinOp::Div,
747
+ BinOp::FloorDiv => IrBinOp::FloorDiv,
748
+ BinOp::Mod => IrBinOp::Mod,
749
+ BinOp::Eq => IrBinOp::Eq,
750
+ BinOp::Ne => IrBinOp::Ne,
751
+ BinOp::Lt => IrBinOp::Lt,
752
+ BinOp::Le => IrBinOp::Le,
753
+ BinOp::Gt => IrBinOp::Gt,
754
+ BinOp::Ge => IrBinOp::Ge,
755
+ BinOp::And => IrBinOp::And,
756
+ BinOp::Or => IrBinOp::Or,
757
+ BinOp::BitAnd => IrBinOp::BitAnd,
758
+ BinOp::BitOr => IrBinOp::BitOr,
759
+ BinOp::BitXor => IrBinOp::BitXor,
760
+ BinOp::Shl => IrBinOp::Shl,
761
+ BinOp::Shr => IrBinOp::Shr,
762
+ }
763
+ }
764
+
765
+ pub fn lower_function(
766
+ fn_id: FnId,
767
+ module_id: usize,
768
+ qualified_name: String,
769
+ decl: &FunctionDecl,
770
+ bindings: &ImportBindings,
771
+ local_fn_names: &FxHashMap<String, usize>,
772
+ call_sites: &mut Vec<CallSite>,
773
+ ) -> Result<IrFunction, PolyError> {
774
+ let mut lowerer = Lowerer::new(module_id, fn_id, bindings, local_fn_names, call_sites);
775
+ let mut params = Vec::with_capacity(decl.params.len());
776
+ for p in &decl.params {
777
+ let ir_ty = hint_to_ir_type(p.ty);
778
+ let reg = lowerer.alloc_reg(ir_ty);
779
+ lowerer.bind_var(p.name.clone(), reg, true);
780
+ params.push((reg, ir_ty));
781
+ }
782
+
783
+ lowerer.lower_stmts(&decl.body)?;
784
+ if !lowerer.current_terminated() {
785
+ lowerer.emit(IrInstruction::Return(None));
786
+ }
787
+
788
+ let _ = lowerer.fn_id;
789
+ Ok(IrFunction {
790
+ id: fn_id,
791
+ module_id,
792
+ qualified_name,
793
+ params,
794
+ return_type: hint_to_ir_type(decl.return_type),
795
+ register_types: lowerer.register_types,
796
+ blocks: lowerer.blocks,
797
+ })
798
+ }
799
+
800
+ pub fn lower_top_level(
801
+ fn_id: FnId,
802
+ module_id: usize,
803
+ qualified_name: String,
804
+ stmts: &[Stmt],
805
+ bindings: &ImportBindings,
806
+ local_fn_names: &FxHashMap<String, usize>,
807
+ call_sites: &mut Vec<CallSite>,
808
+ ) -> Result<IrFunction, PolyError> {
809
+ let fake_decl = FunctionDecl {
810
+ name: "__top_level".to_string(),
811
+ params: Vec::new(),
812
+ return_type: TypeHint::Unknown,
813
+ body: stmts.to_vec(),
814
+ is_exported: false,
815
+ span: Span::dummy(),
816
+ };
817
+ lower_function(
818
+ fn_id,
819
+ module_id,
820
+ qualified_name,
821
+ &fake_decl,
822
+ bindings,
823
+ local_fn_names,
824
+ call_sites,
825
+ )
826
+ }