1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
// zigir/lower/expr/member.rs
// Static/computed member expressions + type inference.
use oxc_ast::ast::*;
use crate::types::ZigType;
use crate::zigir::ident::IrIdent;
use crate::zigir::kinds::{ComputedKeyKind, FieldKind, IndexKind};
use super::Lowerer;
impl Lowerer {
/// Shorthand to construct `IrExpr::FieldAccess { object, field, field_kind }`
/// with the standard object-lowering and field-name conversion.
fn make_field_access(
&mut self,
mem: &StaticMemberExpression,
field_kind: FieldKind,
) -> crate::zigir::types::IrExpr {
use crate::zigir::types::IrExpr;
IrExpr::FieldAccess {
object: Box::new(self.lower_expr(&mem.object)),
field: mem.property.name.as_str().to_string(),
field_kind,
}
}
/// Lower a static member expression (`obj.field`).
///
/// Determines the FieldKind based on:
/// - Math constants → `MathConstant`
/// - Number constants → `NumberConstant`
/// - Symbol well-known → `SymbolWellKnown`
/// - TypedArray properties → `TypedArrayProp`
/// - Map/Set `.size` → `MapSetSize`
/// - ArrayList `.length` → `ArrayListLen`
/// - Other `.length` → `StringLen`
/// - Default → `StructField`
pub(super) fn lower_static_member(
&mut self,
mem: &StaticMemberExpression,
) -> crate::zigir::types::IrExpr {
use crate::zigir::types::IrExpr;
let field_name = mem.property.name.as_str();
// R8-C7: Inside a constructor body, reads of `this.<field>` must also
// be rewritten to the pre-declared local `var <field>`. The ctor's
// `init` function has no `self` parameter (it returns a fresh struct
// by value), so the default lowering — `IrExpr::This` + FieldAccess —
// would emit `self.field`, which Zig rejects as an undeclared
// identifier. The `this_rewrite_fields` flag is set inside
// `lower_class_method` for constructors exactly so that BOTH reads
// and writes of `this.field` get rewritten consistently.
//
// This branch must come before every other `this`-based special case
// (static block, default StructField) because those assume a `self`
// receiver exists, which is false inside `init`.
if let Some(ref fields) = self.this_rewrite_fields
&& matches!(&mem.object, Expression::ThisExpression(_))
&& fields.contains(&field_name.to_string())
{
return IrExpr::Ident(IrIdent::new(field_name));
}
// ── Math constants: Math.PI, Math.E, etc. ──
if let Expression::Identifier(id) = &mem.object {
if id.name.as_str() == "Math" {
return self
.make_field_access(mem, FieldKind::MathConstant(field_name.to_string()));
}
// ── Number constants: Number.MAX_VALUE, Number.NaN, etc. ──
if id.name.as_str() == "Number" {
return self
.make_field_access(mem, FieldKind::NumberConstant(field_name.to_string()));
}
// ── Symbol well-known: Symbol.iterator, etc. ──
if id.name.as_str() == "Symbol" {
return self
.make_field_access(mem, FieldKind::SymbolWellKnown(field_name.to_string()));
}
// ── TypedArray properties ──
if let Some(zig_type) = self.type_info.var_types.get(id.name.as_str()) {
if let ZigType::NamedStruct(name) = zig_type {
// ── TypedArray properties (buffer, byteLength, byteOffset) ──
if Self::is_typedarray_type(name)
&& matches!(field_name, "buffer" | "byteLength" | "byteOffset")
{
let type_suffix = Self::typedarray_type_suffix(name).map(|s| s.to_string());
return self.make_field_access(
mem,
FieldKind::TypedArrayProp {
prop: field_name.to_string(),
type_suffix,
},
);
}
// ── Map/Set .size ──
if matches!(name.as_str(), "Map" | "Set") && field_name == "size" {
return self.make_field_access(mem, FieldKind::MapSetSize);
}
}
// ── ArrayList .length → .items.len ──
if matches!(zig_type, ZigType::ArrayList(_)) && field_name == "length" {
return self.make_field_access(mem, FieldKind::ArrayListLen);
}
}
}
// ── .length — type-aware dispatch ──
if field_name == "length" {
// Special case: __arguments is a []const JsAny slice
if let Expression::Identifier(id) = &mem.object
&& (id.name.as_str() == "__arguments" || id.name.as_str() == "arguments")
{
return self.make_field_access(mem, FieldKind::ArgumentsLen);
}
// Check type info for the object to determine the right FieldKind
if let Expression::Identifier(id) = &mem.object
&& let Some(zig_type) = self.type_info.var_types.get(id.name.as_str())
{
if matches!(zig_type, ZigType::Str) {
return self.make_field_access(mem, FieldKind::StringLen);
}
if matches!(zig_type, ZigType::ArrayList(_)) {
return self.make_field_access(mem, FieldKind::ArrayListLen);
}
// NamedStruct (TypedArray, Map, Set, etc.) or other types → slice .len
return self.make_field_access(mem, FieldKind::SliceLen);
}
// No var_types entry: try infer_expr_type for non-Identifier objects
if !matches!(&mem.object, Expression::Identifier(_)) {
if let Some(inferred) = self.infer_expr_type(&mem.object) {
if matches!(inferred, ZigType::Str) {
return self.make_field_access(mem, FieldKind::StringLen);
}
return self.make_field_access(mem, FieldKind::SliceLen);
}
// No type info at all — default to SliceLen
return self.make_field_access(mem, FieldKind::SliceLen);
}
// Identifier with no type info: default to StringLen
return self.make_field_access(mem, FieldKind::StringLen);
}
// ── RegExp properties: .source, .flags, .global, .ignoreCase ──
if let Expression::Identifier(id) = &mem.object {
let var_name = id.name.as_str();
if let Some(ctx) = &self.fn_ctx
&& ctx.regexp_vars.contains(var_name)
&& matches!(
field_name,
"source" | "flags" | "global" | "ignoreCase" | "lastIndex"
)
{
return self.make_field_access(
mem,
FieldKind::RegExpProp {
prop: field_name.to_string(),
},
);
}
}
// ── Static class field: ClassName.field → StaticField kind ──
if let Expression::Identifier(id) = &mem.object {
let obj_name = id.name.as_str();
if let Some(static_fields) = self.class_static_fields.get(obj_name)
&& static_fields.contains(field_name)
{
return self.make_field_access(
mem,
FieldKind::StaticField {
class_name: obj_name.to_string(),
},
);
}
}
// ── Static block: this.field → StaticField kind (same as ClassName.field) ──
// Note: this uses a different object (class_name instead of lowered this), so
// we can't use make_field_access here.
if matches!(&mem.object, Expression::ThisExpression(_))
&& self.in_static_block
&& let Some(ref class_name) = self.current_class
&& let Some(static_fields) = self.class_static_fields.get(class_name)
&& static_fields.contains(field_name)
{
return IrExpr::FieldAccess {
object: Box::new(IrExpr::Ident(IrIdent::new(class_name))),
field: field_name.to_string(),
field_kind: FieldKind::StaticField {
class_name: class_name.clone(),
},
};
}
// ── Default: struct field access ──
self.make_field_access(mem, FieldKind::StructField)
}
/// Lower a computed member expression (`obj[key]`).
///
/// Three sub-cases:
/// - NumericLiteral key → IndexAccess (ArrayListItem or SliceIndex)
/// - StringLiteral key → ComputedField (StructField, MapGet, JsAnyGetByKey)
/// - Dynamic expression key → ComputedField (varies by object type)
pub(super) fn lower_computed_member(
&mut self,
mem: &ComputedMemberExpression,
) -> crate::zigir::types::IrExpr {
use crate::zigir::types::IrExpr;
let object = Box::new(self.lower_expr(&mem.object));
// Determine the ZigType of the object (for routing)
let obj_type = self.infer_expr_type(&mem.object);
// Special case: arguments/__arguments → slice indexing
let is_arguments = matches!(&mem.object, Expression::Identifier(id)
if id.name.as_str() == "arguments" || id.name.as_str() == "__arguments");
// ── Case 1: NumericLiteral key → IndexAccess or StringCharAt ──
if let Expression::NumericLiteral(nl) = &mem.expression {
if is_arguments {
return IrExpr::IndexAccess {
object,
index: Box::new(IrExpr::IntLiteral(nl.value as i64)),
index_kind: IndexKind::SliceIndex,
};
}
let is_arraylist = obj_type
.as_ref()
.map(|t| matches!(t, ZigType::ArrayList(_)))
.unwrap_or(false);
let is_string = obj_type
.as_ref()
.map(|t| matches!(t, ZigType::Str))
.unwrap_or(false);
// str[0] → StringCharAt (JS charAt semantics, returns Str)
if is_string {
return IrExpr::ComputedField {
object,
key: Box::new(IrExpr::IntLiteral(nl.value as i64)),
key_kind: ComputedKeyKind::StringCharAt,
};
}
return IrExpr::IndexAccess {
object,
index: Box::new(IrExpr::IntLiteral(nl.value as i64)),
index_kind: if is_arraylist {
IndexKind::ArrayListItem
} else {
IndexKind::SliceIndex
},
};
}
// ── Case 2: StringLiteral key → ComputedField ──
if let Expression::StringLiteral(sl) = &mem.expression {
let key_kind = match &obj_type {
Some(ZigType::Struct(_)) => ComputedKeyKind::StructField,
Some(ZigType::NamedStruct(name)) if name == "Map" => ComputedKeyKind::MapGet,
Some(ZigType::NamedStruct(_)) => ComputedKeyKind::StructField,
Some(ZigType::Anytype) | Some(ZigType::JsAny) => ComputedKeyKind::JsAnyGetByKey,
_ => ComputedKeyKind::JsAnyGetByKey,
};
return IrExpr::ComputedField {
object,
key: Box::new(IrExpr::StringLiteral(sl.value.to_string())),
key_kind,
};
}
// ── Case 3: Dynamic expression key → ComputedField ──
let key = Box::new(self.lower_expr(&mem.expression));
// Special case: arguments/__arguments → IndexAccess with SliceIndex
if is_arguments {
return IrExpr::IndexAccess {
object,
index: key,
index_kind: IndexKind::SliceIndex,
};
}
let key_kind = match &obj_type {
Some(ZigType::Anytype) | Some(ZigType::JsAny) => ComputedKeyKind::JsAnyGetByKey,
Some(ZigType::NamedStruct(name)) if name == "Map" => ComputedKeyKind::MapGet,
Some(ZigType::ArrayList(_)) => ComputedKeyKind::ArrayListItem,
Some(ZigType::Str) => ComputedKeyKind::StringCharAt,
Some(ZigType::Struct(_)) | Some(ZigType::NamedStruct(_)) => {
ComputedKeyKind::StructField
}
None => ComputedKeyKind::JsAnyGetByKey,
_ => ComputedKeyKind::CompileError(format!(
"computed access on unsupported type: {:?}",
obj_type
)),
};
IrExpr::ComputedField {
object,
key,
key_kind,
}
}
/// Look up the ZigType of an identifier by name.
/// Checks special globals, then var_types (exact, qualified, suffix-based).
pub(crate) fn infer_ident_type(&self, name: &str) -> Option<ZigType> {
// Special globals
match name {
"Infinity" | "NaN" => return Some(ZigType::F64),
"undefined" => return Some(ZigType::JsAny),
// arguments is lowered to __arguments: []const JsAny
// Use ArrayList(JsAny) as the closest ZigType approximation for inference.
"arguments" => return Some(ZigType::ArrayList(Box::new(ZigType::JsAny))),
_ => {}
}
// Exact match
if let Some(ty) = self.type_info.var_types.get(name) {
return Some(ty.clone());
}
// Qualified match (fn_name::var_name)
if let Some(ctx) = self.fn_ctx.as_ref() {
let qualified = format!("{}::{}", ctx.name, name);
if let Some(ty) = self.type_info.var_types.get(&qualified) {
return Some(ty.clone());
}
}
// Suffix match (any_key::var_name)
let suffix = format!("::{}", name);
for (k, v) in &self.type_info.var_types {
if k.ends_with(&suffix) {
return Some(v.clone());
}
}
None
}
/// Infer the ZigType of an expression based on type_info and expression structure.
/// Enhanced version that covers literal types, member access, calls, and more.
pub(crate) fn infer_expr_type(&self, expr: &Expression) -> Option<ZigType> {
match expr {
Expression::Identifier(id) => self.infer_ident_type(id.name.as_str()),
Expression::NumericLiteral(nl) => {
// Shared logic (P2-2): value-based detection via
// crate::types::numeric_literal_type.
Some(crate::types::numeric_literal_type(nl.value))
}
Expression::StringLiteral(_) => Some(ZigType::Str),
Expression::TemplateLiteral(_) => Some(ZigType::Str),
Expression::BooleanLiteral(_) => Some(ZigType::Bool),
Expression::BigIntLiteral(_) => Some(ZigType::BigInt),
Expression::NullLiteral(_) => Some(ZigType::JsAny),
Expression::UnaryExpression(ue) => match ue.operator {
UnaryOperator::LogicalNot => Some(ZigType::Bool),
UnaryOperator::Void => Some(ZigType::JsAny),
UnaryOperator::Typeof => Some(ZigType::Str),
UnaryOperator::UnaryNegation => {
// -0.0 must stay F64 to preserve IEEE 754 signed zero:
// Zig's @as(i64, @intFromFloat(-0.0)) produces 0, losing
// the sign. Match on the underlying NumericLiteral value
// (covers both `0.0` and `-0.0` since they compare equal).
if let Expression::NumericLiteral(nl) = &ue.argument
&& nl.value == 0.0
{
return Some(ZigType::F64);
}
self.infer_expr_type(&ue.argument)
}
UnaryOperator::UnaryPlus => match self.infer_expr_type(&ue.argument) {
// ToNumber conversion: bool → i64, str → f64, numbers pass through.
Some(ZigType::Bool) => Some(ZigType::I64),
Some(ZigType::Str) => Some(ZigType::F64),
other => other,
},
UnaryOperator::BitwiseNot => {
// JS: ~x converts to Int32 then bit-negates; we store as
// I64. A BigInt operand stays BigInt.
match self.infer_expr_type(&ue.argument) {
Some(ZigType::BigInt) => Some(ZigType::BigInt),
_ => Some(ZigType::I64),
}
}
_ => None,
},
Expression::BinaryExpression(be) => {
let left_ty = self.infer_expr_type(&be.left);
let right_ty = self.infer_expr_type(&be.right);
Self::infer_binary_result_type(&be.operator, left_ty, right_ty)
}
Expression::ConditionalExpression(ce) => {
let then_ty = self.infer_expr_type(&ce.consequent);
let else_ty = self.infer_expr_type(&ce.alternate);
match (then_ty, else_ty) {
// Both branches agree → that type
(Some(a), Some(b)) if a == b => Some(a),
// Numeric promotion only: I64 ↔ F64 → F64. Mirrors
// infer_binary_result_type's I64+F64 rule. Other mixed
// combinations (e.g. Str ? F64) must NOT promote:
// the Str branch cannot be coerced to F64, so returning
// F64 here would cause downstream emit to wrap the
// string-branch value in @floatFromInt, which is invalid
// Zig. Fall through to None (JsAny fallback).
(Some(ZigType::F64), Some(ZigType::I64))
| (Some(ZigType::I64), Some(ZigType::F64)) => Some(ZigType::F64),
_ => None,
}
}
Expression::ParenthesizedExpression(pe) => self.infer_expr_type(&pe.expression),
Expression::StaticMemberExpression(mem) => {
// Known constants
if let Expression::Identifier(id) = &mem.object {
match id.name.as_str() {
"Math" => {
return match mem.property.name.as_str() {
"PI" | "E" | "LN2" | "LN10" | "LOG2E" | "LOG10E" | "SQRT1_2"
| "SQRT2" => Some(ZigType::F64),
_ => None,
};
}
"Number" => {
return match mem.property.name.as_str() {
"MAX_SAFE_INTEGER" | "MIN_SAFE_INTEGER" | "MAX_VALUE"
| "MIN_VALUE" => Some(ZigType::F64),
"POSITIVE_INFINITY" | "NEGATIVE_INFINITY" | "NaN" => {
Some(ZigType::F64)
}
"EPSILON" => Some(ZigType::F64),
_ => None,
};
}
_ => {}
}
}
// Try struct field inference
let obj_ty = self.infer_expr_type(&mem.object);
match obj_ty {
Some(ZigType::NamedStruct(name)) => {
if let Some(fields) = self.type_info.class_field_types.get(&name)
&& let Some(ty) = fields.get(mem.property.name.as_str())
{
return Some(ty.clone());
}
None
}
_ => None,
}
}
Expression::CallExpression(ce) => {
// Try to infer from known method calls
if let Expression::StaticMemberExpression(mem) = &ce.callee {
// Number.* methods: let the builtin detection path
// (detect_builtin_call + builtin_return_type) handle
// them correctly. Previously "Number" returned I64 for
// ALL methods including isInteger/isNaN/isFinite (P0-8 fix).
// Method return type from object type
let obj_ty = self.infer_expr_type(&mem.object);
if let Some(ZigType::NamedStruct(name)) = &obj_ty {
match name.as_str() {
"Map" => match mem.property.name.as_str() {
"get" => return Some(ZigType::JsAny),
"has" | "delete" => return Some(ZigType::Bool),
_ => {}
},
"Set" => match mem.property.name.as_str() {
"has" | "delete" => return Some(ZigType::Bool),
_ => {}
},
_ => {}
}
}
// String method returns
if obj_ty == Some(ZigType::Str) {
match mem.property.name.as_str() {
"charAt" | "substring" | "slice" | "toLowerCase" | "toUpperCase"
| "trim" | "repeat" | "replace" | "replaceAll" | "padStart"
| "padEnd" => return Some(ZigType::Str),
// charCodeAt/codePointAt can return NaN → F64 (P1-9 fix)
"charCodeAt" | "codePointAt" => return Some(ZigType::F64),
"indexOf" | "lastIndexOf" => return Some(ZigType::I64),
"includes" | "startsWith" | "endsWith" => return Some(ZigType::Bool),
_ => {}
}
}
}
// Try function return type lookup
if let Expression::Identifier(id) = &ce.callee
&& let Some(ty) = self.type_info.fn_return_types.get(id.name.as_str())
{
return Some(ty.clone());
}
// Try built-in constructor / function calls
if let Some(builtin) = crate::native_builtins::detect_builtin_call(ce) {
// Object(x) → passthrough: inherits argument type
if builtin == crate::native_builtins::BuiltinCall::ObjectConstructor
&& ce.arguments.len() == 1
&& let Some(arg) = ce.arguments.first()
&& let Some(e) = arg.as_expression()
&& let Some(arg_ty) = self.infer_expr_type(e)
{
return Some(arg_ty);
}
if let Some(ret_ty) = crate::native_builtins::builtin_return_type(&builtin) {
return Some(ret_ty);
}
}
None
}
// Object literal → infer as Struct with field types
Expression::ObjectExpression(oe) => {
let mut fields = Vec::new();
for prop in &oe.properties {
if let ObjectPropertyKind::ObjectProperty(op) = prop {
let field_name = match &op.key {
PropertyKey::StaticIdentifier(id) => id.name.as_str().to_string(),
PropertyKey::StringLiteral(s) => s.value.to_string(),
_ => continue,
};
let field_ty = self.infer_expr_type(&op.value).unwrap_or(ZigType::JsAny);
fields.push((field_name, field_ty));
}
}
Some(ZigType::Struct(fields))
}
// Array literal → ArrayList of element type.
// Walk ALL elements and unify their types.
//
// IMPORTANT: this must agree with `emit_array_literal`'s element
// type decision. The emitter uses a conservative `all_same` check
// — any mismatch (e.g. IntLiteral + FloatLiteral) forces the
// whole array to JsAny. So we mirror that here: any mismatch
// degrades to JsAny. Previously this branch used `find_map` which
// returned the FIRST element's type — so for `[1, 2.5]` the
// lowerer inferred `ArrayList(I64)` while emit produced
// `ArrayList(JsAny)`, an inconsistency that risked downstream
// type-annotation mismatches.
//
// Spread elements (`...arr`) are skipped: their source element
// type would require cross-expression inference. emit_array_literal
// already forces JsAny whenever a spread is present, so falling
// through to `unwrap_or(JsAny)` here matches emit's behavior.
Expression::ArrayExpression(ae) => {
let mut elem_ty: Option<ZigType> = None;
for el in &ae.elements {
let Some(e) = el.as_expression() else {
continue;
};
let Some(t) = self.infer_expr_type(e) else {
continue;
};
elem_ty = Some(match elem_ty {
None => t,
Some(a) if a == t => a,
// Any mismatch degrades to JsAny — matches emit
// (all_same=false → JsAny). No numeric promotion
// here, to stay strictly aligned with the emitter.
Some(_) => ZigType::JsAny,
});
if elem_ty == Some(ZigType::JsAny) {
break;
}
}
Some(ZigType::ArrayList(Box::new(
elem_ty.unwrap_or(ZigType::JsAny),
)))
}
// Computed member access: obj[key]
Expression::ComputedMemberExpression(cme) => {
// arguments[i] → JsAny (since __arguments is []const JsAny)
if let Expression::Identifier(id) = &cme.object
&& (id.name.as_str() == "arguments" || id.name.as_str() == "__arguments")
{
return Some(ZigType::JsAny);
}
// General: ArrayList(T)[i] → T
if let Some(ZigType::ArrayList(elem)) = self.infer_expr_type(&cme.object) {
return Some(*elem);
}
None
}
_ => None,
}
}
/// Infer the result type of a binary operation from operand types.
///
/// Delegates to `TypeInferrer::infer_binary_type` for the core type-mapping
/// logic when both operand types are known (P2-2: eliminates ~70 lines of
/// duplicated operator→type match arms). Falls back to conservative defaults
/// when one or both types are unknown.
pub(super) fn infer_binary_result_type(
op: &BinaryOperator,
left_ty: Option<ZigType>,
right_ty: Option<ZigType>,
) -> Option<ZigType> {
// Comparison operators (including `in` and `instanceof`) always
// produce bool, even when operand types are unknown.
if matches!(
op,
BinaryOperator::Equality
| BinaryOperator::Inequality
| BinaryOperator::StrictEquality
| BinaryOperator::StrictInequality
| BinaryOperator::LessThan
| BinaryOperator::GreaterThan
| BinaryOperator::LessEqualThan
| BinaryOperator::GreaterEqualThan
| BinaryOperator::In
| BinaryOperator::Instanceof
) {
return Some(ZigType::Bool);
}
// When both operand types are known, delegate to the shared core logic.
// `infer_binary_type` must not take `&self` (it's a pure function of
// operator + types), so we call it as an associated function.
if let (Some(l), Some(r)) = (&left_ty, &right_ty) {
let result = crate::infer::TypeInferrer::infer_binary_type(*op, l.clone(), r.clone());
// JsAny is the catch-all "unknown" return from infer_binary_type
// (for operators not explicitly handled); convert to None for the
// Option-based API used by the lowerer.
return (result != ZigType::JsAny).then_some(result);
}
// Partial knowledge: produce conservative defaults for operators with
// predictable results regardless of the missing operand type.
let both_bigint = left_ty == Some(ZigType::BigInt) && right_ty == Some(ZigType::BigInt);
match op {
// Remainder/Division/Exponential: BigInt if both BigInt, else F64.
BinaryOperator::Remainder | BinaryOperator::Division | BinaryOperator::Exponential => {
if both_bigint {
Some(ZigType::BigInt)
} else {
Some(ZigType::F64)
}
}
// Bitwise/Shift: BigInt if both BigInt, else I64.
BinaryOperator::BitwiseAnd
| BinaryOperator::BitwiseOR
| BinaryOperator::BitwiseXOR
| BinaryOperator::ShiftLeft
| BinaryOperator::ShiftRight
| BinaryOperator::ShiftRightZeroFill => {
if both_bigint {
Some(ZigType::BigInt)
} else {
Some(ZigType::I64)
}
}
_ => None,
}
}
/// Infer the type of a simple assignment target (left-hand side of `++`/`--` etc.).
/// Handles the same cases as `infer_assign_target_type` but for `SimpleAssignmentTarget`.
pub(in crate::zigir::lower) fn infer_simple_assign_target_type(
&self,
target: &SimpleAssignmentTarget,
) -> Option<ZigType> {
use oxc_ast::ast::SimpleAssignmentTarget;
match target {
SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => {
self.infer_ident_type(id.name.as_str())
}
SimpleAssignmentTarget::StaticMemberExpression(mem) => {
self.infer_static_member_type(mem)
}
_ => None,
}
}
/// Infer the type of an assignment target (left-hand side of `=` / `+=` etc.).
/// Only handles the common cases: identifier and static member expression.
pub(in crate::zigir::lower) fn infer_assign_target_type(
&self,
target: &AssignmentTarget,
) -> Option<ZigType> {
use oxc_ast::ast::AssignmentTarget;
match target {
AssignmentTarget::AssignmentTargetIdentifier(id) => {
self.infer_ident_type(id.name.as_str())
}
AssignmentTarget::StaticMemberExpression(mem) => self.infer_static_member_type(mem),
_ => None,
}
}
/// Shared logic for inferring the type of a static member expression
/// used as an assignment target (`obj.field = ...` or `obj.field++`).
/// Checks static class field type, then falls back to object type.
fn infer_static_member_type(&self, mem: &StaticMemberExpression) -> Option<ZigType> {
if let Expression::Identifier(id) = &mem.object {
let obj_name = id.name.as_str();
let field_name = mem.property.name.as_str();
if let Some(static_fields) = self.class_static_fields.get(obj_name)
&& static_fields.contains(field_name)
{
let var_key = format!("__{}_{}", obj_name, field_name);
if let Some(ty) = self.type_info.var_types.get(&var_key) {
return Some(ty.clone());
}
}
}
self.infer_expr_type(&mem.object)
}
/// Determine FieldKind for a member assignment target (`obj.field = ...`).
///
/// Checks whether `object_expr.field_name` refers to a static class field,
/// and returns `FieldKind::StaticField` if so. Otherwise returns `FieldKind::StructField`.
pub(super) fn infer_member_field_kind(
&self,
object_expr: &Expression,
field_name: &str,
) -> FieldKind {
if let Expression::Identifier(id) = object_expr {
let obj_name = id.name.as_str();
if let Some(static_fields) = self.class_static_fields.get(obj_name)
&& static_fields.contains(field_name)
{
return FieldKind::StaticField {
class_name: obj_name.to_string(),
};
}
}
// In static blocks, `this.field` is equivalent to `ClassName.field`
if matches!(object_expr, Expression::ThisExpression(_))
&& self.in_static_block
&& let Some(ref class_name) = self.current_class
&& let Some(static_fields) = self.class_static_fields.get(class_name)
&& static_fields.contains(field_name)
{
return FieldKind::StaticField {
class_name: class_name.clone(),
};
}
FieldKind::StructField
}
}