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