1use std::collections::HashSet;
5
6use oxc_ast::ast::*;
7
8use crate::types::ZigType;
9use crate::zigir::ident::IrIdent;
10use crate::zigir::source_span::SourceSpan;
11use crate::zigir::types::{IrBlock, IrDecl, IrForInKind, IrForOfKind};
12
13use super::Lowerer;
14
15impl Lowerer {
20 pub(super) fn lower_stmt(&mut self, stmt: &Statement) -> crate::zigir::types::IrStmt {
27 match stmt {
28 Statement::VariableDeclaration(vd) => {
30 if vd.declarations.len() == 1 {
32 let decl = &vd.declarations[0];
33 match &decl.id {
34 BindingPattern::ObjectPattern(_) | BindingPattern::ArrayPattern(_) => {
35 self.lower_destructure_decl(decl)
36 }
37 _ => {
38 let ir_decl = self.lower_var_decl(decl, vd.kind.is_const());
39 match ir_decl {
40 IrDecl::Var(v) => crate::zigir::types::IrStmt::VarDecl(v),
41 IrDecl::CompileError { span, msg } => {
42 crate::zigir::types::IrStmt::CompileError { span, msg }
43 }
44 _ => crate::zigir::types::IrStmt::Comment(
45 "// unexpected decl type in statement context".to_string(),
46 ),
47 }
48 }
49 }
50 } else {
51 let stmts: Vec<crate::zigir::types::IrStmt> = vd
52 .declarations
53 .iter()
54 .flat_map(|decl| match &decl.id {
55 BindingPattern::ObjectPattern(_) | BindingPattern::ArrayPattern(_) => {
56 vec![self.lower_destructure_decl(decl)]
57 }
58 _ => {
59 let ir_decl = self.lower_var_decl(decl, vd.kind.is_const());
60 match ir_decl {
61 IrDecl::Var(v) => vec![crate::zigir::types::IrStmt::VarDecl(v)],
62 IrDecl::CompileError { span, msg } => {
63 vec![crate::zigir::types::IrStmt::CompileError {
64 span,
65 msg,
66 }]
67 }
68 _ => vec![],
69 }
70 }
71 })
72 .collect();
73 if stmts.len() == 1 {
74 stmts.into_iter().next().expect("stmts.len()==1 guarantees one element")
75 } else {
76 crate::zigir::types::IrStmt::Block(IrBlock::new_transparent(stmts))
79 }
80 }
81 }
82
83 Statement::IfStatement(is) => self.lower_if(is),
85
86 Statement::WhileStatement(ws) => {
87 let label = self.current_loop_label();
88 crate::zigir::types::IrStmt::While {
89 cond: self.lower_expr(&ws.test),
90 body: self.lower_stmt_as_block(&ws.body, None),
91 label,
92 }
93 }
94
95 Statement::DoWhileStatement(dws) => {
96 let label = self.current_loop_label();
97 crate::zigir::types::IrStmt::DoWhile {
98 body: self.lower_stmt_as_block(&dws.body, None),
99 cond: self.lower_expr(&dws.test),
100 label,
101 }
102 }
103
104 Statement::ForStatement(fs) => self.lower_for(fs),
105 Statement::ForOfStatement(fos) => self.lower_for_of(fos),
106 Statement::ForInStatement(fis) => self.lower_for_in(fis),
107
108 Statement::SwitchStatement(ss) => self.lower_switch(ss),
109
110 Statement::TryStatement(ts) => self.lower_try(ts),
112 Statement::ThrowStatement(ts) => crate::zigir::types::IrStmt::Throw {
113 value: self.lower_expr(&ts.argument),
114 error_name: None,
115 },
116
117 Statement::ReturnStatement(rs) => {
119 if let Some(fn_ctx) = self.fn_ctx.as_mut() {
120 fn_ctx.seen_return = true;
121 }
122 let value = rs.argument.as_ref().map(|expr| {
123 let mut val = self.lower_expr(expr);
124 if let Some(ref fn_ctx) = self.fn_ctx
128 && fn_ctx.return_type == Some(ZigType::I64)
129 {
130 val = self.coerce_i64_result_type(val);
131 }
132 if let Some(ref fn_ctx) = self.fn_ctx
136 && fn_ctx.return_type == Some(ZigType::F64)
137 {
138 val = self.coerce_f64_result_type(val);
139 }
140 if let Some(ref fn_ctx) = self.fn_ctx
144 && fn_ctx.return_type == Some(ZigType::JsAny)
145 {
146 val = self.coerce_jsany_result_type(val);
147 }
148 val
149 });
150 crate::zigir::types::IrStmt::Return { value }
151 }
152 Statement::BreakStatement(bs) => crate::zigir::types::IrStmt::Break {
153 label: bs.label.as_ref().map(|l| l.name.to_string()),
154 },
155 Statement::ContinueStatement(cs) => crate::zigir::types::IrStmt::Continue {
156 label: cs.label.as_ref().map(|l| l.name.to_string()),
157 },
158
159 Statement::BlockStatement(bs) => {
161 self.name_mangler.push_shadow_scope();
162 let stmts: Vec<crate::zigir::types::IrStmt> =
163 bs.body.iter().map(|s| self.lower_stmt(s)).collect();
164 self.name_mangler.pop_shadow_scope();
165 crate::zigir::types::IrStmt::Block(IrBlock::new(stmts))
166 }
167 Statement::LabeledStatement(ls) => self.lower_labeled(ls),
168
169 Statement::ExpressionStatement(es) => {
171 if let Some(fields) = self.this_rewrite_fields.clone()
184 && let Some(rewritten) =
185 self.try_rewrite_this_field_assignment(&es.expression, &fields)
186 {
187 return rewritten;
188 }
189 if let Some(throw_value) = self.make_const_reassign_throw(&es.expression) {
194 crate::zigir::types::IrStmt::Throw {
195 value: throw_value,
196 error_name: Some("ConstReassignment".to_string()),
197 }
198 } else {
199 let prev_in_expr_stmt = self.in_expr_stmt;
205 self.in_expr_stmt = true;
206 let expr = self.lower_expr(&es.expression);
207 self.in_expr_stmt = prev_in_expr_stmt;
208 crate::zigir::types::IrStmt::Expr(expr)
209 }
210 }
211
212 Statement::FunctionDeclaration(fd) => {
214 self.lower_nested_fn_decl(fd)
215 }
216
217 Statement::WithStatement(ws) => {
219 let span = self.span_to_source_span(ws.span);
220 self.add_error(span, "with statement is not supported");
221 crate::zigir::types::IrStmt::CompileError {
222 span: SourceSpan::default(),
223 msg: "with statement is not supported".to_string(),
224 }
225 }
226
227 Statement::EmptyStatement(_) => crate::zigir::types::IrStmt::Comment("".to_string()),
229 Statement::DebuggerStatement(ds) => {
230 crate::zigir::types::IrStmt::CompileError {
231 span: self.span_to_source_span(ds.span),
232 msg: "debugger statement is not supported (debugging is not available in compiled Zig)".to_string(),
233 }
234 }
235
236 Statement::ClassDeclaration(cd) => {
238 let name = cd
239 .id
240 .as_ref()
241 .map(|id| id.name.as_str())
242 .unwrap_or("<anonymous>");
243 crate::zigir::types::IrStmt::CompileError {
244 span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
245 msg: format!("nested class declaration '{}' is not supported", name),
246 }
247 }
248 Statement::ExportDefaultDeclaration(_) => crate::zigir::types::IrStmt::CompileError {
249 span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
250 msg: "export default is not supported".to_string(),
251 },
252 Statement::ImportDeclaration(_) => crate::zigir::types::IrStmt::CompileError {
253 span: self.span_to_source_span(oxc_span::GetSpan::span(stmt)),
254 msg: "import declaration is not supported".to_string(),
255 },
256
257 _ => {
259 let span = oxc_span::GetSpan::span(stmt);
260 crate::zigir::types::IrStmt::CompileError {
261 span: self.span_to_source_span(span),
262 msg: "Unsupported statement type".to_string(),
263 }
264 }
265 }
266 }
267
268 pub(super) fn lower_stmt_as_block(
273 &mut self,
274 stmt: &Statement,
275 label: Option<String>,
276 ) -> IrBlock {
277 let stmts = match stmt {
278 Statement::BlockStatement(bs) => {
279 self.name_mangler.push_shadow_scope();
280 let stmts: Vec<crate::zigir::types::IrStmt> =
281 bs.body.iter().map(|s| self.lower_stmt(s)).collect();
282 self.name_mangler.pop_shadow_scope();
283 stmts
284 }
285 _ => vec![self.lower_stmt(stmt)],
286 };
287 IrBlock {
288 stmts,
289 label,
290 transparent: false,
291 }
292 }
293
294 pub(super) fn lower_if(&mut self, is: &IfStatement) -> crate::zigir::types::IrStmt {
296 let cond = self.lower_expr(&is.test);
297 let then = self.lower_stmt_as_block(&is.consequent, None);
298 let else_ = is
299 .alternate
300 .as_ref()
301 .map(|alt| self.lower_stmt_as_block(alt, None));
302 crate::zigir::types::IrStmt::If { cond, then, else_ }
303 }
304
305 pub(super) fn lower_for(&mut self, fs: &ForStatement) -> crate::zigir::types::IrStmt {
310 let label = self.current_loop_label();
311
312 let init = fs.init.as_ref().map(|init| match init {
313 ForStatementInit::VariableDeclaration(vd) => {
314 let is_const = vd.kind.is_const();
316 let stmts: Vec<crate::zigir::types::IrStmt> = vd
317 .declarations
318 .iter()
319 .filter_map(|d| {
320 let decl = self.lower_var_decl(d, is_const);
321 match decl {
322 IrDecl::Var(v) => Some(crate::zigir::types::IrStmt::VarDecl(v)),
323 _ => None,
324 }
325 })
326 .collect();
327 if stmts.len() == 1 {
328 Box::new(
329 stmts
330 .into_iter()
331 .next()
332 .expect("stmts.len()==1 guarantees one element"),
333 )
334 } else {
335 Box::new(crate::zigir::types::IrStmt::Block(
339 IrBlock::new_transparent(stmts),
340 ))
341 }
342 }
343 _ => {
344 if let Some(expr) = init.as_expression() {
348 let ctor_fields = self.this_rewrite_fields.clone();
349 if let Some(fields) = &ctor_fields
350 && let Some(rewritten) =
351 self.try_rewrite_this_field_assignment(expr, fields)
352 {
353 Box::new(rewritten)
354 } else {
355 Box::new(crate::zigir::types::IrStmt::Expr(self.lower_expr(expr)))
356 }
357 } else {
358 Box::new(crate::zigir::types::IrStmt::Comment(
359 "// skipped init".to_string(),
360 ))
361 }
362 }
363 });
364
365 let cond = fs.test.as_ref().map(|expr| self.lower_expr(expr));
366 let update = fs.update.as_ref().map(|expr| {
367 let ctor_fields = self.this_rewrite_fields.clone();
370 if let Some(fields) = &ctor_fields
371 && let Some(rewritten) = self.try_rewrite_this_field_assignment(expr, fields)
372 {
373 Box::new(rewritten)
374 } else {
375 Box::new(crate::zigir::types::IrStmt::Expr(self.lower_expr(expr)))
376 }
377 });
378 let body = self.lower_stmt_as_block(&fs.body, None);
379
380 crate::zigir::types::IrStmt::For {
381 init,
382 cond,
383 update,
384 body,
385 label,
386 }
387 }
388
389 pub(super) fn lower_for_of(&mut self, fos: &ForOfStatement) -> crate::zigir::types::IrStmt {
395 let label = self.current_loop_label();
396
397 if fos.r#await {
399 let span = self.span_to_source_span(fos.span);
400 self.add_error(
401 span,
402 "for await...of is not supported. Use synchronous for...of instead.",
403 );
404 return crate::zigir::types::IrStmt::CompileError {
405 span: SourceSpan::default(),
406 msg: "for await...of is not supported".to_string(),
407 };
408 }
409
410 let (var, destructure_vars) = self.extract_for_of_vars(&fos.left);
412
413 let (kind, iterable_is_arraylist) = self.detect_for_of_kind(&fos.right);
415
416 if matches!(kind, IrForOfKind::AsyncUnsupported) {
417 return crate::zigir::types::IrStmt::CompileError {
418 span: SourceSpan::default(),
419 msg: "for await...of is not supported".to_string(),
420 };
421 }
422
423 let loop_var_keys: Vec<String> = if matches!(kind, IrForOfKind::MapSetIter { .. }) {
426 if destructure_vars.is_empty() {
427 vec![var.js_name.clone()]
428 } else {
429 destructure_vars
430 .iter()
431 .map(|dv| dv.js_name.clone())
432 .collect()
433 }
434 } else if let IrForOfKind::Str { .. } = &kind {
435 vec![var.js_name.clone()]
436 } else {
437 Vec::new()
438 };
439 let saved_types: Vec<(String, Option<ZigType>)> = loop_var_keys
440 .iter()
441 .map(|k| (k.clone(), self.type_info.var_types.get(k).cloned()))
442 .collect();
443
444 if matches!(kind, IrForOfKind::MapSetIter { .. }) {
448 if destructure_vars.is_empty() {
449 self.type_info
450 .var_types
451 .insert(var.js_name.clone(), ZigType::JsAny);
452 } else {
453 for dv in &destructure_vars {
454 self.type_info
455 .var_types
456 .insert(dv.js_name.clone(), ZigType::JsAny);
457 }
458 }
459 }
460
461 if let IrForOfKind::Str { .. } = &kind {
464 self.type_info
465 .var_types
466 .insert(var.js_name.clone(), ZigType::I64);
467 }
468
469 let iterable = self.lower_expr(&fos.right);
470 let body = self.lower_stmt_as_block(&fos.body, None);
471
472 for (key, old_type) in &saved_types {
474 if let Some(t) = old_type {
475 self.type_info.var_types.insert(key.clone(), t.clone());
476 } else {
477 self.type_info.var_types.remove(key);
478 }
479 }
480
481 let kind = if let IrForOfKind::Str { .. } = &kind {
484 let var_used = match &fos.body {
485 Statement::BlockStatement(b) => b
486 .body
487 .iter()
488 .any(|s| Self::ast_stmt_uses_ident(&var.js_name, s)),
489 other => Self::ast_stmt_uses_ident(&var.js_name, other),
490 };
491 IrForOfKind::Str { var_used }
492 } else {
493 kind
494 };
495
496 crate::zigir::types::IrStmt::ForOf {
497 var,
498 destructure_vars,
499 iterable,
500 iterable_is_arraylist,
501 body,
502 kind,
503 is_async: fos.r#await,
504 label,
505 }
506 }
507
508 pub(super) fn lower_for_in(&mut self, fis: &ForInStatement) -> crate::zigir::types::IrStmt {
514 let label = self.current_loop_label();
515
516 let var = self.extract_for_in_var(&fis.left);
518
519 let kind = self.detect_for_in_kind(&fis.right);
521
522 if matches!(kind, IrForInKind::Unsupported) {
523 let obj_name = match &fis.right {
524 Expression::Identifier(id) => id.name.to_string(),
525 _ => "<expression>".to_string(),
526 };
527 let span = self.span_to_source_span(fis.span);
528 self.add_error(
529 span,
530 format!("for-in: '{}' is not a dynamic object", obj_name),
531 );
532 }
533
534 match &kind {
547 IrForInKind::MapIter => {
548 self.type_info
549 .var_types
550 .insert(var.js_name.clone(), ZigType::JsAny);
551 }
552 IrForInKind::HashMapIter => {
553 self.type_info
554 .var_types
555 .insert(var.js_name.clone(), ZigType::Str);
556 }
557 _ => {}
558 }
559
560 let iterable = if matches!(kind, IrForInKind::StructUnroll { .. }) {
561 let mut idents = HashSet::new();
563 Self::collect_ast_expr_idents(&fis.right, &mut idents);
564 if let Some(ctx) = self.fn_ctx.as_mut() {
565 ctx.compile_time_referenced_idents.extend(idents);
566 }
567 crate::zigir::types::IrExpr::Null
568 } else {
569 self.lower_expr(&fis.right)
570 };
571 let body = self.lower_stmt_as_block(&fis.body, None);
572
573 crate::zigir::types::IrStmt::ForIn {
574 var,
575 iterable,
576 body,
577 kind,
578 label,
579 }
580 }
581
582 pub(super) fn extract_for_of_vars(&self, left: &ForStatementLeft) -> (IrIdent, Vec<IrIdent>) {
586 match left {
587 ForStatementLeft::VariableDeclaration(vd) => {
588 if let Some(decl) = vd.declarations.first() {
589 if let BindingPattern::ArrayPattern(ap) = &decl.id {
591 let names: Vec<IrIdent> = ap
592 .elements
593 .iter()
594 .filter_map(|elem| {
595 elem.as_ref().and_then(|pat| {
596 crate::infer::binding_name(pat).map(IrIdent::new)
597 })
598 })
599 .collect();
600 let primary = names
601 .first()
602 .cloned()
603 .unwrap_or_else(|| IrIdent::new("item"));
604 return (primary, names);
605 }
606 if let Some(name) = crate::infer::binding_name(&decl.id) {
608 return (IrIdent::new(name), vec![]);
609 }
610 }
611 (IrIdent::new("item"), vec![])
612 }
613 _ => (IrIdent::new("item"), vec![]),
614 }
615 }
616
617 pub(super) fn extract_for_in_var(&self, left: &ForStatementLeft) -> IrIdent {
619 match left {
620 ForStatementLeft::VariableDeclaration(vd) => vd
621 .declarations
622 .first()
623 .and_then(|decl| crate::infer::binding_name(&decl.id))
624 .map(IrIdent::new)
625 .unwrap_or_else(|| IrIdent::new("key")),
626 ForStatementLeft::AssignmentTargetIdentifier(id) => IrIdent::new(id.name.as_str()),
627 _ => IrIdent::new("key"),
628 }
629 }
630
631 pub(super) fn detect_for_of_kind(&self, right: &Expression) -> (IrForOfKind, bool) {
633 match right {
634 Expression::Identifier(id) => {
635 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
636 if let ZigType::NamedStruct(name) = zig_type {
638 if name == "Map" {
639 return (IrForOfKind::MapSetIter { is_map: true }, false);
640 }
641 if name == "Set" {
642 return (IrForOfKind::MapSetIter { is_map: false }, false);
643 }
644 }
645 if matches!(zig_type, ZigType::ArrayList(_)) {
647 return (IrForOfKind::Array, true);
648 }
649 if matches!(zig_type, ZigType::Str) {
651 return (IrForOfKind::Str { var_used: true }, false);
655 }
656 }
657 (IrForOfKind::Array, false)
659 }
660 Expression::StringLiteral(_) => (IrForOfKind::Str { var_used: true }, false),
661 _ => (IrForOfKind::Array, false),
662 }
663 }
664
665 pub(super) fn detect_for_in_kind(&self, right: &Expression) -> IrForInKind {
667 match right {
668 Expression::Identifier(id) => {
669 if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
670 if let ZigType::NamedStruct(name) = zig_type
672 && name == "Map"
673 {
674 return IrForInKind::MapIter;
675 }
676 if matches!(zig_type, ZigType::Anytype) {
678 return IrForInKind::HashMapIter;
679 }
680 if let ZigType::Struct(fields) = zig_type
682 && !fields.is_empty()
683 {
684 return IrForInKind::StructUnroll {
685 fields: fields.iter().map(|(n, _)| n.clone()).collect(),
686 };
687 }
688 if let ZigType::NamedStruct(name) = zig_type
690 && let Some(typedef) = self.jsdoc_data.typedefs.get(name)
691 && !typedef.fields.is_empty()
692 {
693 let fields: Vec<String> =
694 typedef.fields.iter().map(|f| f.name.clone()).collect();
695 return IrForInKind::StructUnroll { fields };
696 }
697 }
698 IrForInKind::Unsupported
699 }
700 _ => IrForInKind::Unsupported,
701 }
702 }
703
704 pub(super) fn lower_switch(&mut self, ss: &SwitchStatement) -> crate::zigir::types::IrStmt {
706 let expr = self.lower_expr(&ss.discriminant);
707
708 let n = ss.cases.len();
713 let mut body_ranges: Vec<(usize, usize)> = Vec::with_capacity(n);
714 for i in 0..n {
715 let mut end = i + 1;
716 while end <= n {
717 let has_break = ss.cases[end - 1]
720 .consequent
721 .iter()
722 .any(|s| matches!(s, Statement::BreakStatement(bs) if bs.label.is_none()));
723 if has_break {
724 break;
725 }
726 if end < n {
727 end += 1;
728 } else {
729 break;
730 }
731 }
732 body_ranges.push((i, end));
733 }
734
735 let mut cases: Vec<crate::zigir::types::IrSwitchCase> = Vec::with_capacity(n);
737 for (i, case) in ss.cases.iter().enumerate() {
738 let test = case.test.as_ref().map(|e| self.lower_expr(e));
739 let (start, end) = body_ranges[i];
740 let mut body: Vec<crate::zigir::types::IrStmt> = Vec::new();
741 for j in start..end {
742 for s in &ss.cases[j].consequent {
743 if matches!(s, Statement::BreakStatement(bs) if bs.label.is_none()) {
746 break;
747 }
748 body.push(self.lower_stmt(s));
749 }
750 }
751 cases.push(crate::zigir::types::IrSwitchCase { test, body });
752 }
753
754 crate::zigir::types::IrStmt::Switch { expr, cases }
755 }
756
757 pub(super) fn lower_try(&mut self, ts: &TryStatement) -> crate::zigir::types::IrStmt {
759 let catchable_before = self
769 .fn_ctx
770 .as_ref()
771 .is_some_and(|ctx| ctx.has_catchable_error);
772
773 let try_block = {
774 let stmts = ts.block.body.iter().map(|s| self.lower_stmt(s)).collect();
775 IrBlock::new(stmts)
776 };
777
778 let catchable_after = self
779 .fn_ctx
780 .as_ref()
781 .is_some_and(|ctx| ctx.has_catchable_error);
782 let has_catchable_error_in_try = catchable_after && !catchable_before;
783
784 if let Some(ctx) = self.fn_ctx.as_mut() {
796 ctx.has_catchable_error = catchable_before;
797 }
798
799 let has_nested_try = ts
801 .block
802 .body
803 .iter()
804 .any(|s| matches!(s, Statement::TryStatement(_)));
805
806 fn ir_stmt_has_throw(s: &crate::zigir::types::IrStmt) -> bool {
808 match s {
809 crate::zigir::types::IrStmt::Throw { .. } => true,
810 crate::zigir::types::IrStmt::If { then, else_, .. } => {
812 ir_block_has_throw(then) || else_.as_ref().is_some_and(ir_block_has_throw)
813 }
814 crate::zigir::types::IrStmt::While { body, .. }
815 | crate::zigir::types::IrStmt::DoWhile { body, .. }
816 | crate::zigir::types::IrStmt::For { body, .. }
817 | crate::zigir::types::IrStmt::ForOf { body, .. }
818 | crate::zigir::types::IrStmt::ForIn { body, .. } => ir_block_has_throw(body),
819 crate::zigir::types::IrStmt::Switch { cases, .. } => {
820 cases.iter().any(|c| c.body.iter().any(ir_stmt_has_throw))
821 }
822 crate::zigir::types::IrStmt::Block(b) => ir_block_has_throw(b),
823 crate::zigir::types::IrStmt::Try {
828 try_block,
829 catch_block,
830 finally,
831 ..
832 } => {
833 ir_block_has_throw(try_block)
834 || ir_block_has_throw(catch_block)
835 || finally.as_ref().is_some_and(ir_block_has_throw)
836 }
837 _ => false,
838 }
839 }
840 fn ir_block_has_throw(block: &IrBlock) -> bool {
841 block.stmts.iter().any(ir_stmt_has_throw)
842 }
843 let has_throw = ir_block_has_throw(&try_block) || has_catchable_error_in_try;
844
845 fn ir_finally_has_escaping_break_or_continue(
851 stmts: &[crate::zigir::types::IrStmt],
852 ) -> bool {
853 fn check(s: &crate::zigir::types::IrStmt) -> bool {
854 use crate::zigir::types::IrStmt;
855 match s {
856 IrStmt::Break { .. } | IrStmt::Continue { .. } => true,
857 IrStmt::If { then, else_, .. } => {
858 check_block(&then.stmts)
859 || else_.as_ref().is_some_and(|e| check_block(&e.stmts))
860 }
861 IrStmt::Block(b) => check_block(&b.stmts),
862 IrStmt::Switch { cases, .. } => cases.iter().any(|c| c.body.iter().any(check)),
863 IrStmt::Try {
864 try_block,
865 catch_block,
866 finally,
867 ..
868 } => {
869 check_block(&try_block.stmts)
870 || check_block(&catch_block.stmts)
871 || finally.as_ref().is_some_and(|f| check_block(&f.stmts))
872 }
873 IrStmt::While { .. }
875 | IrStmt::DoWhile { .. }
876 | IrStmt::For { .. }
877 | IrStmt::ForOf { .. }
878 | IrStmt::ForIn { .. } => false,
879 _ => false,
880 }
881 }
882 fn check_block(stmts: &[crate::zigir::types::IrStmt]) -> bool {
883 stmts.iter().any(check)
884 }
885 check_block(stmts)
886 }
887
888 let (catch_var, catch_var_referenced, catch_block) = if let Some(handler) = &ts.handler {
889 let var = handler
890 .param
891 .as_ref()
892 .and_then(|p| crate::infer::binding_name(&p.pattern))
893 .map(|name| self.make_ident(name));
894 if let Some(ref v) = var {
897 self.type_info
898 .var_types
899 .insert(v.zig_name.clone(), ZigType::JsError);
900 }
901 let stmts = handler
902 .body
903 .body
904 .iter()
905 .map(|s| self.lower_stmt(s))
906 .collect();
907 let catch_var_referenced = if let Some(ref cv) = var {
909 let js_name = &cv.js_name;
910 handler
911 .body
912 .body
913 .iter()
914 .any(|s| Self::stmt_references_name(s, js_name))
915 } else {
916 false
917 };
918 (var, catch_var_referenced, IrBlock::new(stmts))
919 } else {
920 (None, false, IrBlock::new(vec![]))
921 };
922
923 let finally = ts.finalizer.as_ref().map(|f| {
924 let stmts = f.body.iter().map(|s| self.lower_stmt(s)).collect();
925 IrBlock::new(stmts)
926 });
927
928 if let Some(ref fin) = finally
935 && ir_finally_has_escaping_break_or_continue(&fin.stmts)
936 {
937 let span = self.span_to_source_span(ts.span);
938 let msg = "break/continue in finally block is not supported";
939 self.add_error(span.clone(), msg);
940 return crate::zigir::types::IrStmt::CompileError {
941 span,
942 msg: msg.to_string(),
943 };
944 }
945
946 crate::zigir::types::IrStmt::Try {
947 try_block,
948 catch_var,
949 catch_var_referenced,
950 catch_block,
951 finally,
952 has_throw,
953 has_nested_try,
954 }
955 }
956
957 pub(super) fn stmt_references_name(stmt: &Statement, name: &str) -> bool {
960 match stmt {
961 Statement::ExpressionStatement(es) => Self::expr_references_name(&es.expression, name),
962 Statement::ReturnStatement(rs) => rs
963 .argument
964 .as_ref()
965 .is_some_and(|a| Self::expr_references_name(a, name)),
966 Statement::VariableDeclaration(vd) => vd.declarations.iter().any(|d| {
967 d.init
968 .as_ref()
969 .is_some_and(|init| Self::expr_references_name(init, name))
970 }),
971 Statement::BlockStatement(bs) => {
972 bs.body.iter().any(|s| Self::stmt_references_name(s, name))
973 }
974 Statement::ThrowStatement(ts) => Self::expr_references_name(&ts.argument, name),
975 Statement::IfStatement(ifs) => {
976 Self::stmt_references_name(&ifs.consequent, name)
977 || ifs
978 .alternate
979 .as_ref()
980 .is_some_and(|a| Self::stmt_references_name(a, name))
981 }
982 Statement::WhileStatement(ws) => {
983 Self::expr_references_name(&ws.test, name)
984 || Self::stmt_references_name(&ws.body, name)
985 }
986 Statement::DoWhileStatement(dws) => {
987 Self::stmt_references_name(&dws.body, name)
988 || Self::expr_references_name(&dws.test, name)
989 }
990 Statement::ForStatement(fs) => {
991 Self::stmt_references_name(&fs.body, name)
992 || fs
993 .test
994 .as_ref()
995 .is_some_and(|e| Self::expr_references_name(e, name))
996 || fs
997 .update
998 .as_ref()
999 .is_some_and(|e| Self::expr_references_name(e, name))
1000 }
1001 Statement::ForOfStatement(fos) => {
1002 Self::expr_references_name(&fos.right, name)
1003 || Self::stmt_references_name(&fos.body, name)
1004 }
1005 Statement::ForInStatement(fis) => {
1006 Self::expr_references_name(&fis.right, name)
1007 || Self::stmt_references_name(&fis.body, name)
1008 }
1009 Statement::LabeledStatement(ls) => Self::stmt_references_name(&ls.body, name),
1010 Statement::SwitchStatement(ss) => ss.cases.iter().any(|c| {
1011 c.consequent
1012 .iter()
1013 .any(|s| Self::stmt_references_name(s, name))
1014 }),
1015 Statement::TryStatement(ts) => {
1016 ts.block
1017 .body
1018 .iter()
1019 .any(|s| Self::stmt_references_name(s, name))
1020 || ts.handler.as_ref().is_some_and(|h| {
1021 h.body
1022 .body
1023 .iter()
1024 .any(|s| Self::stmt_references_name(s, name))
1025 })
1026 || ts
1027 .finalizer
1028 .as_ref()
1029 .is_some_and(|f| f.body.iter().any(|s| Self::stmt_references_name(s, name)))
1030 }
1031 _ => false,
1032 }
1033 }
1034
1035 pub(super) fn expr_references_name(expr: &Expression, name: &str) -> bool {
1036 match expr {
1037 Expression::Identifier(id) => id.name.as_str() == name,
1038 Expression::BinaryExpression(be) => {
1039 Self::expr_references_name(&be.left, name)
1040 || Self::expr_references_name(&be.right, name)
1041 }
1042 Expression::LogicalExpression(le) => {
1043 Self::expr_references_name(&le.left, name)
1044 || Self::expr_references_name(&le.right, name)
1045 }
1046 Expression::UnaryExpression(ue) => Self::expr_references_name(&ue.argument, name),
1047 Expression::UpdateExpression(ue) => {
1048 Self::simple_assign_target_references_name(&ue.argument, name)
1049 }
1050 Expression::AssignmentExpression(ae) => {
1051 Self::assign_target_references_name(&ae.left, name)
1052 || Self::expr_references_name(&ae.right, name)
1053 }
1054 Expression::ConditionalExpression(ce) => {
1055 Self::expr_references_name(&ce.test, name)
1056 || Self::expr_references_name(&ce.consequent, name)
1057 || Self::expr_references_name(&ce.alternate, name)
1058 }
1059 Expression::CallExpression(ce) => {
1060 Self::expr_references_name(&ce.callee, name)
1061 || ce
1062 .arguments
1063 .iter()
1064 .any(|a| Self::arg_references_name(a, name))
1065 }
1066 Expression::NewExpression(ne) => {
1067 Self::expr_references_name(&ne.callee, name)
1068 || ne
1069 .arguments
1070 .iter()
1071 .any(|a| Self::arg_references_name(a, name))
1072 }
1073 Expression::StaticMemberExpression(sme) => {
1074 Self::expr_references_name(&sme.object, name)
1075 }
1076 Expression::ComputedMemberExpression(cme) => {
1077 Self::expr_references_name(&cme.object, name)
1078 || Self::expr_references_name(&cme.expression, name)
1079 }
1080 Expression::ArrayExpression(ae) => ae.elements.iter().any(|e| match e {
1081 ArrayExpressionElement::SpreadElement(se) => {
1082 Self::expr_references_name(&se.argument, name)
1083 }
1084 other => other
1085 .as_expression()
1086 .is_some_and(|e| Self::expr_references_name(e, name)),
1087 }),
1088 Expression::ObjectExpression(oe) => oe.properties.iter().any(|p| match p {
1089 ObjectPropertyKind::ObjectProperty(op) => {
1090 Self::expr_references_name(&op.value, name)
1091 }
1092 ObjectPropertyKind::SpreadProperty(sp) => {
1093 Self::expr_references_name(&sp.argument, name)
1094 }
1095 }),
1096 Expression::SequenceExpression(se) => se
1097 .expressions
1098 .iter()
1099 .any(|e| Self::expr_references_name(e, name)),
1100 Expression::TemplateLiteral(tl) => tl
1101 .expressions
1102 .iter()
1103 .any(|e| Self::expr_references_name(e, name)),
1104 Expression::ChainExpression(ce) => {
1105 Self::chain_element_references_name(&ce.expression, name)
1106 }
1107 Expression::AwaitExpression(ae) => Self::expr_references_name(&ae.argument, name),
1108 Expression::TaggedTemplateExpression(tte) => {
1109 Self::expr_references_name(&tte.tag, name)
1110 || tte
1111 .quasi
1112 .expressions
1113 .iter()
1114 .any(|e| Self::expr_references_name(e, name))
1115 }
1116 _ => false,
1117 }
1118 }
1119
1120 fn assign_target_references_name(target: &AssignmentTarget, name: &str) -> bool {
1122 match target {
1123 AssignmentTarget::AssignmentTargetIdentifier(id) => id.name.as_str() == name,
1124 AssignmentTarget::ArrayAssignmentTarget(_)
1127 | AssignmentTarget::ObjectAssignmentTarget(_) => {
1128 true
1133 }
1134 _ => false,
1135 }
1136 }
1137
1138 fn simple_assign_target_references_name(target: &SimpleAssignmentTarget, name: &str) -> bool {
1140 match target {
1141 SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => id.name.as_str() == name,
1142 _ => false,
1143 }
1144 }
1145
1146 fn chain_element_references_name(elem: &ChainElement, name: &str) -> bool {
1148 match elem {
1149 ChainElement::StaticMemberExpression(sme) => {
1150 Self::expr_references_name(&sme.object, name)
1151 }
1152 ChainElement::ComputedMemberExpression(cme) => {
1153 Self::expr_references_name(&cme.object, name)
1154 || Self::expr_references_name(&cme.expression, name)
1155 }
1156 ChainElement::CallExpression(ce) => {
1157 Self::expr_references_name(&ce.callee, name)
1158 || ce
1159 .arguments
1160 .iter()
1161 .any(|a| Self::arg_references_name(a, name))
1162 }
1163 _ => false,
1164 }
1165 }
1166
1167 fn arg_references_name(arg: &Argument, name: &str) -> bool {
1169 match arg {
1170 Argument::SpreadElement(se) => Self::expr_references_name(&se.argument, name),
1171 other => {
1173 if let Some(expr) = other.as_expression() {
1174 Self::expr_references_name(expr, name)
1175 } else {
1176 false
1177 }
1178 }
1179 }
1180 }
1181
1182 pub(super) fn lower_labeled(&mut self, ls: &LabeledStatement) -> crate::zigir::types::IrStmt {
1188 let label_str = ls.label.name.to_string();
1189
1190 match &ls.body {
1191 Statement::WhileStatement(_)
1193 | Statement::DoWhileStatement(_)
1194 | Statement::ForStatement(_)
1195 | Statement::ForOfStatement(_)
1196 | Statement::ForInStatement(_) => {
1197 self.pending_label = Some(label_str);
1199 self.lower_stmt(&ls.body)
1200 }
1201 _ => {
1203 let ir_stmt = self.lower_stmt(&ls.body);
1204 let has_break = Self::stmt_has_break_to_label(&ls.body, &label_str);
1206 if has_break {
1207 crate::zigir::types::IrStmt::Block(IrBlock::with_label(
1209 if let crate::zigir::types::IrStmt::Block(b) = ir_stmt {
1210 b.stmts
1211 } else {
1212 vec![ir_stmt]
1213 },
1214 label_str,
1215 ))
1216 } else {
1217 ir_stmt
1218 }
1219 }
1220 }
1221 }
1222
1223 pub(super) fn stmt_has_break_to_label(stmt: &Statement, label_name: &str) -> bool {
1225 match stmt {
1226 Statement::BreakStatement(bs) => bs
1227 .label
1228 .as_ref()
1229 .is_some_and(|l| l.name.as_str() == label_name),
1230 Statement::BlockStatement(bs) => bs
1231 .body
1232 .iter()
1233 .any(|s| Self::stmt_has_break_to_label(s, label_name)),
1234 Statement::IfStatement(is) => {
1235 Self::stmt_has_break_to_label(&is.consequent, label_name)
1236 || is
1237 .alternate
1238 .as_ref()
1239 .is_some_and(|a| Self::stmt_has_break_to_label(a, label_name))
1240 }
1241 Statement::LabeledStatement(ls) => Self::stmt_has_break_to_label(&ls.body, label_name),
1242 Statement::TryStatement(ts) => {
1243 ts.block
1244 .body
1245 .iter()
1246 .any(|s| Self::stmt_has_break_to_label(s, label_name))
1247 || ts.handler.as_ref().is_some_and(|h| {
1248 h.body
1249 .body
1250 .iter()
1251 .any(|s| Self::stmt_has_break_to_label(s, label_name))
1252 })
1253 || ts.finalizer.as_ref().is_some_and(|f| {
1254 f.body
1255 .iter()
1256 .any(|s| Self::stmt_has_break_to_label(s, label_name))
1257 })
1258 }
1259 Statement::SwitchStatement(ss) => ss.cases.iter().any(|c| {
1260 c.consequent
1261 .iter()
1262 .any(|s| Self::stmt_has_break_to_label(s, label_name))
1263 }),
1264 Statement::ForStatement(fs) => Self::stmt_has_break_to_label(&fs.body, label_name),
1265 Statement::ForOfStatement(fos) => Self::stmt_has_break_to_label(&fos.body, label_name),
1266 Statement::ForInStatement(fis) => Self::stmt_has_break_to_label(&fis.body, label_name),
1267 Statement::WhileStatement(ws) => Self::stmt_has_break_to_label(&ws.body, label_name),
1268 Statement::DoWhileStatement(dws) => {
1269 Self::stmt_has_break_to_label(&dws.body, label_name)
1270 }
1271 _ => false,
1272 }
1273 }
1274
1275 fn make_const_reassign_throw(
1281 &mut self,
1282 expr: &Expression,
1283 ) -> Option<crate::zigir::types::IrExpr> {
1284 if let Expression::AssignmentExpression(ae) = expr {
1285 if let AssignmentTarget::AssignmentTargetIdentifier(id) = &ae.left {
1287 let is_const_reassign = self
1289 .fn_ctx
1290 .as_ref()
1291 .is_some_and(|ctx| ctx.js_const_reassigned.contains(id.name.as_str()));
1292 if is_const_reassign {
1293 return Some(self.lower_expr(&ae.right));
1298 }
1299 }
1300 }
1301 None
1302 }
1303
1304 pub(super) fn current_loop_label(&mut self) -> Option<String> {
1306 self.pending_label.take()
1307 }
1308
1309 pub(super) fn lower_block(&mut self, stmts: &[Statement]) -> IrBlock {
1311 let ir_stmts: Vec<crate::zigir::types::IrStmt> =
1312 stmts.iter().map(|s| self.lower_stmt(s)).collect();
1313 IrBlock::new(ir_stmts)
1314 }
1315
1316 fn coerce_i64_result_type(
1330 &self,
1331 expr: crate::zigir::types::IrExpr,
1332 ) -> crate::zigir::types::IrExpr {
1333 use crate::zigir::types::IrExpr;
1334 match expr {
1335 IrExpr::RemExpr {
1337 left,
1338 right,
1339 left_type,
1340 right_type,
1341 result_type: None,
1342 } => IrExpr::RemExpr {
1343 left,
1344 right,
1345 left_type,
1346 right_type,
1347 result_type: Some(ZigType::I64),
1348 },
1349 IrExpr::DivExpr {
1350 left,
1351 right,
1352 left_type,
1353 right_type,
1354 result_type: None,
1355 } => IrExpr::DivExpr {
1356 left,
1357 right,
1358 left_type,
1359 right_type,
1360 result_type: Some(ZigType::I64),
1361 },
1362 IrExpr::PowExpr {
1363 base,
1364 exp,
1365 base_type,
1366 exp_type,
1367 result_type: None,
1368 } => IrExpr::PowExpr {
1369 base,
1370 exp,
1371 base_type,
1372 exp_type,
1373 result_type: Some(ZigType::I64),
1374 },
1375 IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::JsAny => {
1378 Self::wrap_jsany_to_i64(IrExpr::BuiltinCall(bc))
1379 }
1380 IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::F64 => IrExpr::DivExpr {
1385 left: Box::new(IrExpr::BuiltinCall(bc)),
1386 right: Box::new(IrExpr::IntLiteral(1)),
1387 left_type: ZigType::F64,
1388 right_type: ZigType::I64,
1389 result_type: Some(ZigType::I64),
1390 },
1391 IrExpr::HostCall(hc) if hc.return_type == ZigType::F64 => IrExpr::DivExpr {
1393 left: Box::new(IrExpr::HostCall(hc)),
1394 right: Box::new(IrExpr::IntLiteral(1)),
1395 left_type: ZigType::F64,
1396 right_type: ZigType::I64,
1397 result_type: Some(ZigType::I64),
1398 },
1399 IrExpr::HostCall(hc) if hc.return_type == ZigType::JsAny => {
1402 Self::wrap_jsany_to_i64(IrExpr::HostCall(hc))
1403 }
1404 IrExpr::Call(call) => {
1407 let returns_jsany = match &*call.callee {
1408 IrExpr::Ident(ident) | IrExpr::TypedIdent { ident, .. } => {
1409 self.type_info.fn_return_types.get(&ident.js_name) == Some(&ZigType::JsAny)
1410 }
1411 _ => false,
1412 };
1413 if returns_jsany {
1414 Self::wrap_jsany_to_i64(IrExpr::Call(call))
1415 } else {
1416 IrExpr::Call(call)
1417 }
1418 }
1419 IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1421 cond,
1422 then: Box::new(self.coerce_i64_result_type(*then)),
1423 else_: Box::new(self.coerce_i64_result_type(*else_)),
1424 },
1425 IrExpr::Sequence(mut exprs) => {
1427 if let Some(last) = exprs.pop() {
1428 exprs.push(self.coerce_i64_result_type(last));
1429 }
1430 IrExpr::Sequence(exprs)
1431 }
1432 IrExpr::Binary {
1434 ref left_type,
1435 ref right_type,
1436 ..
1437 } => {
1438 let is_f64 = left_type.as_ref() == Some(&ZigType::F64)
1439 || right_type.as_ref() == Some(&ZigType::F64);
1440 if is_f64 {
1441 Self::wrap_f64_to_i64(expr)
1442 } else {
1443 expr
1444 }
1445 }
1446 IrExpr::Unary {
1448 ref operand_type, ..
1449 } => {
1450 if operand_type.as_ref() == Some(&ZigType::F64) {
1451 Self::wrap_f64_to_i64(expr)
1452 } else {
1453 expr
1454 }
1455 }
1456 IrExpr::Logical {
1458 ref left_type,
1459 ref right_type,
1460 ..
1461 } => {
1462 let same_type =
1463 left_type.is_some() && right_type.is_some() && left_type == right_type;
1464 if same_type && left_type.as_ref() == Some(&ZigType::F64) {
1465 Self::wrap_f64_to_i64(expr)
1466 } else {
1467 expr
1468 }
1469 }
1470 IrExpr::TypedIdent {
1473 ident,
1474 ty: ZigType::F64,
1475 } => Self::wrap_f64_to_i64(IrExpr::TypedIdent {
1476 ident,
1477 ty: ZigType::F64,
1478 }),
1479 IrExpr::TypedIdent {
1481 ident,
1482 ty: ZigType::JsAny,
1483 } => Self::wrap_jsany_to_i64(IrExpr::TypedIdent {
1484 ident,
1485 ty: ZigType::JsAny,
1486 }),
1487 IrExpr::OptionalChain {
1490 object,
1491 capture_var,
1492 body,
1493 needs_null_check,
1494 } => IrExpr::OptionalChain {
1495 object,
1496 capture_var,
1497 body: Box::new(self.coerce_i64_result_type(*body)),
1498 needs_null_check,
1499 },
1500 other => other,
1501 }
1502 }
1503
1504 fn coerce_f64_result_type(
1510 &self,
1511 expr: crate::zigir::types::IrExpr,
1512 ) -> crate::zigir::types::IrExpr {
1513 use crate::zigir::kinds::{CallKind, MethodObjectKind};
1514 use crate::zigir::types::IrExpr;
1515
1516 const I64_DATE_METHODS: &[&str] = &[
1518 "getTime",
1519 "getFullYear",
1520 "getMonth",
1521 "getDate",
1522 "getDay",
1523 "getHours",
1524 "getMinutes",
1525 "getSeconds",
1526 "getMilliseconds",
1527 "getTimezoneOffset",
1528 "valueOf",
1529 "getUTCFullYear",
1530 "getUTCMonth",
1531 "getUTCDate",
1532 "getUTCDay",
1533 "getUTCHours",
1534 "getUTCMinutes",
1535 "getUTCSeconds",
1536 "getUTCMilliseconds",
1537 "setFullYear",
1538 "setMonth",
1539 "setDate",
1540 "setHours",
1541 "setMinutes",
1542 "setSeconds",
1543 "setMilliseconds",
1544 "setUTCFullYear",
1545 "setUTCMonth",
1546 "setUTCDate",
1547 "setUTCHours",
1548 "setUTCMinutes",
1549 "setUTCSeconds",
1550 "setUTCMilliseconds",
1551 "setTime",
1552 ];
1553
1554 match expr {
1555 IrExpr::FloatLiteral(_) => expr,
1557 IrExpr::DivExpr { .. } | IrExpr::RemExpr { .. } | IrExpr::PowExpr { .. } => expr,
1558 IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::F64 => IrExpr::BuiltinCall(bc),
1559 IrExpr::HostCall(hc) if hc.return_type == ZigType::F64 => IrExpr::HostCall(hc),
1560
1561 IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::I64 => {
1563 Self::wrap_i64_to_f64(IrExpr::BuiltinCall(bc))
1564 }
1565 IrExpr::HostCall(hc) if hc.return_type == ZigType::I64 => {
1567 Self::wrap_i64_to_f64(IrExpr::HostCall(hc))
1568 }
1569
1570 IrExpr::Call(call) => {
1572 let is_date_method = matches!(
1573 call.call_kind,
1574 CallKind::Method {
1575 object_type: MethodObjectKind::Date
1576 }
1577 );
1578 let method_name = match &*call.callee {
1579 IrExpr::FieldAccess { field, .. } => Some(field.as_str()),
1580 _ => None,
1581 };
1582 let needs_wrap = is_date_method
1583 && method_name.is_some_and(|name| I64_DATE_METHODS.contains(&name));
1584
1585 if needs_wrap {
1586 Self::wrap_i64_to_f64(IrExpr::Call(call))
1587 } else {
1588 IrExpr::Call(call)
1589 }
1590 }
1591
1592 IrExpr::Ident(ident) => {
1594 let needs_wrap =
1595 self.type_info.var_types.get(&ident.js_name) == Some(&ZigType::I64);
1596 if needs_wrap {
1597 Self::wrap_i64_to_f64(IrExpr::Ident(ident))
1598 } else {
1599 IrExpr::Ident(ident)
1600 }
1601 }
1602
1603 IrExpr::TypedIdent { ident, ty } => {
1605 if ty == ZigType::I64 {
1606 Self::wrap_i64_to_f64(IrExpr::TypedIdent { ident, ty })
1607 } else {
1608 IrExpr::TypedIdent { ident, ty }
1609 }
1610 }
1611
1612 IrExpr::IntLiteral(_) => Self::wrap_i64_to_f64(expr),
1614
1615 IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1617 cond,
1618 then: Box::new(self.coerce_f64_result_type(*then)),
1619 else_: Box::new(self.coerce_f64_result_type(*else_)),
1620 },
1621
1622 IrExpr::Sequence(mut exprs) => {
1624 if let Some(last) = exprs.pop() {
1625 exprs.push(self.coerce_f64_result_type(last));
1626 }
1627 IrExpr::Sequence(exprs)
1628 }
1629
1630 IrExpr::Binary {
1633 ref left_type,
1634 ref right_type,
1635 ..
1636 } => {
1637 let is_f64 = left_type.as_ref() == Some(&ZigType::F64)
1638 || right_type.as_ref() == Some(&ZigType::F64);
1639 let is_known_i64 = left_type.as_ref() == Some(&ZigType::I64)
1640 || right_type.as_ref() == Some(&ZigType::I64);
1641 if is_f64 || !is_known_i64 {
1642 expr
1643 } else {
1644 Self::wrap_i64_to_f64(expr)
1645 }
1646 }
1647 IrExpr::Unary {
1649 ref operand_type, ..
1650 } => {
1651 if operand_type.as_ref() == Some(&ZigType::I64) {
1652 Self::wrap_i64_to_f64(expr)
1653 } else {
1654 expr
1655 }
1656 }
1657 IrExpr::Logical {
1659 ref left_type,
1660 ref right_type,
1661 ..
1662 } => {
1663 let same_type =
1664 left_type.is_some() && right_type.is_some() && left_type == right_type;
1665 if same_type && left_type.as_ref() == Some(&ZigType::I64) {
1666 Self::wrap_i64_to_f64(expr)
1667 } else {
1668 expr
1669 }
1670 }
1671
1672 IrExpr::OptionalChain {
1674 object,
1675 capture_var,
1676 body,
1677 needs_null_check,
1678 } => IrExpr::OptionalChain {
1679 object,
1680 capture_var,
1681 body: Box::new(self.coerce_f64_result_type(*body)),
1682 needs_null_check,
1683 },
1684
1685 other => other,
1687 }
1688 }
1689
1690 fn wrap_i64_to_f64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1693 crate::zigir::types::IrExpr::DivExpr {
1694 left: Box::new(expr),
1695 right: Box::new(crate::zigir::types::IrExpr::IntLiteral(1)),
1696 left_type: ZigType::I64,
1697 right_type: ZigType::I64,
1698 result_type: None,
1699 }
1700 }
1701
1702 fn wrap_f64_to_i64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1706 crate::zigir::types::IrExpr::DivExpr {
1707 left: Box::new(expr),
1708 right: Box::new(crate::zigir::types::IrExpr::IntLiteral(1)),
1709 left_type: ZigType::F64,
1710 right_type: ZigType::I64,
1711 result_type: Some(ZigType::I64),
1712 }
1713 }
1714
1715 fn wrap_jsany_to_i64(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1719 use crate::zigir::kinds::CallKind;
1720 use crate::zigir::types::{IrCallExpr, IrExpr};
1721 IrExpr::Call(IrCallExpr {
1722 callee: Box::new(IrExpr::FieldAccess {
1723 object: Box::new(expr),
1724 field: "asI64".to_string(),
1725 field_kind: crate::zigir::kinds::FieldKind::StructField,
1726 }),
1727 args: vec![],
1728 call_kind: CallKind::Direct,
1729 })
1730 }
1731
1732 fn wrap_in_jsany_from(expr: crate::zigir::types::IrExpr) -> crate::zigir::types::IrExpr {
1736 use crate::zigir::kinds::{CallKind, FieldKind};
1737 use crate::zigir::types::{IrCallExpr, IrExpr};
1738 IrExpr::Call(IrCallExpr {
1739 callee: Box::new(IrExpr::FieldAccess {
1740 object: Box::new(IrExpr::Ident(crate::zigir::ident::IrIdent::new("JsAny"))),
1741 field: "from".to_string(),
1742 field_kind: FieldKind::StructField,
1743 }),
1744 args: vec![expr],
1745 call_kind: CallKind::Direct,
1746 })
1747 }
1748
1749 fn coerce_jsany_result_type(
1753 &self,
1754 expr: crate::zigir::types::IrExpr,
1755 ) -> crate::zigir::types::IrExpr {
1756 use crate::zigir::types::IrExpr;
1757
1758 match expr {
1759 IrExpr::Call(call) => {
1761 let returns_jsany = match &*call.callee {
1762 IrExpr::Ident(ident) | IrExpr::TypedIdent { ident, .. } => {
1763 self.type_info.fn_return_types.get(&ident.js_name) == Some(&ZigType::JsAny)
1764 }
1765 _ => false,
1766 };
1767 if returns_jsany {
1768 IrExpr::Call(call)
1769 } else {
1770 Self::wrap_in_jsany_from(IrExpr::Call(call))
1772 }
1773 }
1774 IrExpr::BuiltinCall(bc) if bc.return_type == ZigType::JsAny => IrExpr::BuiltinCall(bc),
1775 IrExpr::HostCall(hc) if hc.return_type == ZigType::JsAny => IrExpr::HostCall(hc),
1776
1777 IrExpr::Ident(ident) => {
1779 let is_jsany =
1780 self.type_info.var_types.get(&ident.js_name) == Some(&ZigType::JsAny);
1781 if is_jsany {
1782 IrExpr::Ident(ident)
1783 } else {
1784 Self::wrap_in_jsany_from(IrExpr::Ident(ident))
1785 }
1786 }
1787
1788 IrExpr::TypedIdent { ident, ty } => {
1790 if ty == ZigType::JsAny {
1791 IrExpr::TypedIdent { ident, ty }
1792 } else {
1793 Self::wrap_in_jsany_from(IrExpr::TypedIdent { ident, ty })
1794 }
1795 }
1796
1797 IrExpr::IntLiteral(_)
1799 | IrExpr::FloatLiteral(_)
1800 | IrExpr::BoolLiteral(_)
1801 | IrExpr::StringLiteral(_) => Self::wrap_in_jsany_from(expr),
1802 IrExpr::BuiltinCall(bc)
1803 if matches!(
1804 bc.return_type,
1805 ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Str
1806 ) =>
1807 {
1808 Self::wrap_in_jsany_from(IrExpr::BuiltinCall(bc))
1809 }
1810 IrExpr::HostCall(hc)
1811 if matches!(
1812 hc.return_type,
1813 ZigType::I64 | ZigType::F64 | ZigType::Bool | ZigType::Str
1814 ) =>
1815 {
1816 Self::wrap_in_jsany_from(IrExpr::HostCall(hc))
1817 }
1818 IrExpr::BuiltinCall(_) | IrExpr::HostCall(_) => Self::wrap_in_jsany_from(expr),
1821 IrExpr::Binary { .. } | IrExpr::Unary { .. } => Self::wrap_in_jsany_from(expr),
1822 IrExpr::FieldAccess { .. } => Self::wrap_in_jsany_from(expr),
1823 IrExpr::IndexAccess { .. } => Self::wrap_in_jsany_from(expr),
1824 IrExpr::RemExpr { .. } | IrExpr::DivExpr { .. } | IrExpr::PowExpr { .. } => {
1826 Self::wrap_in_jsany_from(expr)
1827 }
1828 IrExpr::Logical { .. } => Self::wrap_in_jsany_from(expr),
1830 IrExpr::Update { .. } | IrExpr::Assign { .. } => Self::wrap_in_jsany_from(expr),
1832 IrExpr::ArrayLiteral(_) | IrExpr::ObjectLiteral(_) => Self::wrap_in_jsany_from(expr),
1834 IrExpr::TemplateLiteral { .. } | IrExpr::AllocPrint { .. } => {
1835 Self::wrap_in_jsany_from(expr)
1836 }
1837 IrExpr::BigIntLiteral(_) => Self::wrap_in_jsany_from(expr),
1838 IrExpr::New(ref ne) if ne.result_type == ZigType::JsAny => expr,
1843 IrExpr::New(_) => Self::wrap_in_jsany_from(expr),
1844 IrExpr::BlockExpr { .. } => Self::wrap_in_jsany_from(expr),
1845 IrExpr::Null | IrExpr::Undefined => expr,
1847
1848 IrExpr::OptionalChain { .. } => Self::wrap_in_jsany_from(expr),
1852
1853 IrExpr::Await(_) => Self::wrap_in_jsany_from(expr),
1856
1857 IrExpr::ArrayCallbackInline(_) | IrExpr::ArrayMethodInline(_) => {
1860 Self::wrap_in_jsany_from(expr)
1861 }
1862
1863 IrExpr::ComputedField { .. } => Self::wrap_in_jsany_from(expr),
1865
1866 IrExpr::Paren(inner) => self.coerce_jsany_result_type(*inner),
1868
1869 IrExpr::Typeof(_) => Self::wrap_in_jsany_from(expr),
1871
1872 IrExpr::Void(_) => expr,
1874
1875 IrExpr::Spread(_) => Self::wrap_in_jsany_from(expr),
1877
1878 IrExpr::FnExpr(_) => Self::wrap_in_jsany_from(expr),
1880
1881 IrExpr::This => Self::wrap_in_jsany_from(expr),
1883
1884 IrExpr::ArrowFn(_) | IrExpr::Closure(_) => Self::wrap_in_jsany_from(expr),
1886
1887 IrExpr::CompileError { .. } => expr,
1889
1890 IrExpr::Conditional { cond, then, else_ } => IrExpr::Conditional {
1892 cond,
1893 then: Box::new(self.coerce_jsany_result_type(*then)),
1894 else_: Box::new(self.coerce_jsany_result_type(*else_)),
1895 },
1896
1897 IrExpr::Sequence(mut exprs) => {
1899 if let Some(last) = exprs.pop() {
1900 exprs.push(self.coerce_jsany_result_type(last));
1901 }
1902 IrExpr::Sequence(exprs)
1903 }
1904 }
1905 }
1906}