js2zig-core 0.18.0

Core JS-to-Zig transpiler library
Documentation
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
// zigir/lower/expr/optional.rs
// Optional chaining (?.) expression lowering.

use oxc_ast::ast::*;

use crate::types::ZigType;
use crate::zigir::ident::IrIdent;
use crate::zigir::kinds::{CallKind, FieldKind, IndexKind};

use super::Lowerer;

impl Lowerer {
    /// Lower an optional chain expression (`obj?.prop`, `obj?.method()`, `obj?.[key]`).
    pub(super) fn lower_optional_chain(
        &mut self,
        ce: &ChainExpression,
    ) -> crate::zigir::types::IrExpr {
        use crate::zigir::types::IrExpr;

        match &ce.expression {
            ChainElement::StaticMemberExpression(sme) => self.lower_optional_sme_chain(sme),
            ChainElement::ComputedMemberExpression(cme) => self.lower_optional_cme_chain(cme),
            ChainElement::CallExpression(call_ce) => self.lower_optional_call_chain(call_ce),
            _ => IrExpr::CompileError {
                span: crate::zigir::source_span::SourceSpan::default(),
                msg: "unsupported optional chain element".to_string(),
            },
        }
    }

    pub(super) fn lower_optional_sme_chain(
        &mut self,
        sme: &StaticMemberExpression,
    ) -> crate::zigir::types::IrExpr {
        use crate::zigir::types::IrExpr;

        let inner = self.lower_optional_chain_object(&sme.object);
        let field_name = sme.property.name.as_str();

        // When the object type is JsAny, use obj.get("prop") which returns
        // .undefined_value for null/undefined — exactly matching ?. semantics.
        // This avoids generating (if (obj) |oc| oc.prop else null) which
        // doesn't compile because JsAny is a union, not an optional.
        if self.expr_type_is_jsany(&sme.object) {
            return IrExpr::Call(crate::zigir::types::IrCallExpr {
                callee: Box::new(IrExpr::FieldAccess {
                    object: Box::new(inner),
                    field: "get".to_string(),
                    field_kind: FieldKind::StructField,
                }),
                args: vec![IrExpr::StringLiteral(field_name.to_string())],
                call_kind: CallKind::Method {
                    object_type: crate::zigir::kinds::MethodObjectKind::JsAny,
                },
            });
        }

        let capture_var = self.name_mangler.next_name("_oc");
        let needs_null_check = self.expr_might_be_null(&sme.object);
        let access_target = if needs_null_check {
            IrExpr::Ident(IrIdent::new(&capture_var))
        } else {
            inner.clone()
        };
        let body = IrExpr::FieldAccess {
            object: Box::new(access_target),
            field: field_name.to_string(),
            field_kind: FieldKind::StructField,
        };

        if !needs_null_check {
            return body;
        }

        IrExpr::OptionalChain {
            object: Box::new(inner),
            capture_var,
            body: Box::new(body),
            needs_null_check: true,
        }
    }

    pub(super) fn lower_optional_cme_chain(
        &mut self,
        cme: &ComputedMemberExpression,
    ) -> crate::zigir::types::IrExpr {
        use crate::zigir::types::IrExpr;

        let inner = self.lower_optional_chain_object(&cme.object);
        let index = self.lower_expr(&cme.expression);

        // When the object type is JsAny, use isNullish() + Conditional instead
        // of OptionalChain. OptionalChain emits (if (obj) |oc| ... else null)
        // which requires a Zig optional type — JsAny is a union, not an optional.
        if self.expr_type_is_jsany(&cme.object) {
            use crate::zigir::kinds::MethodObjectKind;
            use crate::zigir::types::{IrCallExpr, IrStmt, IrVarDecl};

            let temp_name = self.name_mangler.next_name("_oc");
            let block_label = format!("_oc_blk_{}", self.name_mangler.peek_count("_oc"));

            let temp_ident = |n: &str| IrExpr::Ident(IrIdent::new(n));

            return IrExpr::BlockExpr {
                label: block_label,
                body: vec![IrStmt::VarDecl(IrVarDecl::new_const(
                    &temp_name,
                    Some(ZigType::JsAny),
                    Some(inner),
                ))],
                result: Box::new(IrExpr::Conditional {
                    cond: Box::new(IrExpr::Call(IrCallExpr {
                        callee: Box::new(IrExpr::FieldAccess {
                            object: Box::new(temp_ident(&temp_name)),
                            field: "isNullish".to_string(),
                            field_kind: FieldKind::StructField,
                        }),
                        args: vec![],
                        call_kind: CallKind::Method {
                            object_type: MethodObjectKind::JsAny,
                        },
                    })),
                    then: Box::new(IrExpr::Undefined),
                    else_: Box::new(IrExpr::IndexAccess {
                        object: Box::new(temp_ident(&temp_name)),
                        index: Box::new(index),
                        index_kind: IndexKind::SliceIndex,
                    }),
                }),
            };
        }

        let capture_var = self.name_mangler.next_name("_oc");
        let needs_null_check = self.expr_might_be_null(&cme.object);
        let access_target = if needs_null_check {
            IrExpr::Ident(IrIdent::new(&capture_var))
        } else {
            inner.clone()
        };
        let body = IrExpr::IndexAccess {
            object: Box::new(access_target),
            index: Box::new(index),
            index_kind: IndexKind::SliceIndex,
        };

        if !needs_null_check {
            return body;
        }

        IrExpr::OptionalChain {
            object: Box::new(inner),
            capture_var,
            body: Box::new(body),
            needs_null_check: true,
        }
    }

    pub(super) fn lower_optional_call_chain(
        &mut self,
        call_ce: &CallExpression,
    ) -> crate::zigir::types::IrExpr {
        use crate::zigir::types::IrExpr;

        let (receiver_name, method_name) = self.extract_optional_call_info(call_ce);
        let needs_null_check = receiver_name
            .as_ref()
            .map(|name| {
                self.get_var_type(name.as_str()).is_none_or(|ty| {
                    !matches!(
                        ty,
                        ZigType::Struct(_)
                            | ZigType::I64
                            | ZigType::F64
                            | ZigType::Bool
                            | ZigType::Str
                            | ZigType::ArrayList(_)
                            | ZigType::NamedStruct(_)
                    )
                })
            })
            .unwrap_or(true);

        let object = match &call_ce.callee {
            Expression::StaticMemberExpression(sme) => {
                self.lower_optional_chain_object(&sme.object)
            }
            Expression::ComputedMemberExpression(cme) => {
                self.lower_optional_chain_object(&cme.object)
            }
            _ => self.lower_expr(call_ce.callee.get_inner_expression()),
        };

        // When the receiver is JsAny, use isNullish() + Conditional instead of
        // OptionalChain. OptionalChain emits (if (obj) |oc| ... else null) which
        // requires a Zig optional type — JsAny is a union, not an optional, so
        // the unwrap syntax does not compile. Instead we bind the receiver to a
        // temp, check .isNullish(), and return undefined_value or the method call.
        let receiver_expr: Option<&Expression> = match &call_ce.callee {
            Expression::StaticMemberExpression(sme) => Some(&sme.object),
            Expression::ComputedMemberExpression(cme) => Some(&cme.object),
            _ => None,
        };
        if needs_null_check
            && let Some(method) = method_name.as_ref()
            && receiver_expr.is_some_and(|e| self.expr_type_is_jsany(e))
        {
            use crate::zigir::kinds::MethodObjectKind;
            use crate::zigir::types::{IrCallExpr, IrStmt, IrVarDecl};

            let temp_name = self.name_mangler.next_name("_oc");
            let block_label = format!("_oc_blk_{}", self.name_mangler.peek_count("_oc"));
            let args = self.lower_args(&call_ce.arguments);

            let temp_ident = |n: &str| IrExpr::Ident(IrIdent::new(n));

            return IrExpr::BlockExpr {
                label: block_label,
                body: vec![IrStmt::VarDecl(IrVarDecl::new_const(
                    &temp_name,
                    Some(ZigType::JsAny),
                    Some(object),
                ))],
                result: Box::new(IrExpr::Conditional {
                    cond: Box::new(IrExpr::Call(IrCallExpr {
                        callee: Box::new(IrExpr::FieldAccess {
                            object: Box::new(temp_ident(&temp_name)),
                            field: "isNullish".to_string(),
                            field_kind: FieldKind::StructField,
                        }),
                        args: vec![],
                        call_kind: CallKind::Method {
                            object_type: MethodObjectKind::JsAny,
                        },
                    })),
                    then: Box::new(IrExpr::Undefined),
                    else_: Box::new(IrExpr::Call(IrCallExpr {
                        callee: Box::new(IrExpr::FieldAccess {
                            object: Box::new(temp_ident(&temp_name)),
                            field: method.clone(),
                            field_kind: FieldKind::StructField,
                        }),
                        args,
                        call_kind: CallKind::Method {
                            object_type: MethodObjectKind::JsAny,
                        },
                    })),
                }),
            };
        }

        let capture_var = self.name_mangler.next_name("_oc");
        let access_target = if needs_null_check {
            IrExpr::Ident(IrIdent::new(&capture_var))
        } else {
            object.clone()
        };

        let args = self.lower_args(&call_ce.arguments);

        let body = if let Some(name) = method_name {
            IrExpr::Call(crate::zigir::types::IrCallExpr {
                callee: Box::new(IrExpr::FieldAccess {
                    object: Box::new(access_target),
                    field: name,
                    field_kind: FieldKind::StructField,
                }),
                args,
                call_kind: CallKind::Method {
                    object_type: crate::zigir::kinds::MethodObjectKind::Unknown,
                },
            })
        } else {
            self.lower_call(call_ce)
        };

        if !needs_null_check {
            return body;
        }

        IrExpr::OptionalChain {
            object: Box::new(object),
            capture_var,
            body: Box::new(body),
            needs_null_check: true,
        }
    }

    pub(super) fn lower_optional_chain_object(
        &mut self,
        expr: &Expression,
    ) -> crate::zigir::types::IrExpr {
        match expr {
            Expression::StaticMemberExpression(sme) if sme.optional => {
                self.lower_optional_sme_chain(sme)
            }
            Expression::ComputedMemberExpression(cme) if cme.optional => {
                self.lower_optional_cme_chain(cme)
            }
            Expression::ChainExpression(ce) => self.lower_optional_chain(ce),
            _ => self.lower_expr(expr),
        }
    }

    /// Extract receiver expression and method name from an optional call expression.
    /// For `obj?.greet("World")`, returns (Some(obj_ident_or_expr), Some("greet"), ...).
    /// Returns owned data since we need to release the borrow before calling lower_expr.
    pub(super) fn extract_optional_call_info(
        &self,
        ce: &CallExpression,
    ) -> (Option<String>, Option<String>) {
        match &ce.callee {
            Expression::StaticMemberExpression(sme) => {
                // Extract receiver identifier name if it's a simple identifier
                let receiver_name = match &sme.object {
                    Expression::Identifier(id) => Some(id.name.to_string()),
                    _ => None,
                };
                (receiver_name, Some(sme.property.name.to_string()))
            }
            Expression::ComputedMemberExpression(cme) => {
                let receiver_name = match &cme.object {
                    Expression::Identifier(id) => Some(id.name.to_string()),
                    _ => None,
                };
                (receiver_name, None)
            }
            _ => (None, None),
        }
    }

    /// Check if an expression might be null at runtime.
    /// Returns false for known non-null types (structs, i64, f64, bool, str, ArrayList, etc.)
    pub(super) fn expr_might_be_null(&self, expr: &Expression) -> bool {
        match expr {
            Expression::NumericLiteral(_)
            | Expression::StringLiteral(_)
            | Expression::BooleanLiteral(_)
            | Expression::ArrayExpression(_)
            | Expression::ObjectExpression(_) => false,

            Expression::NullLiteral(_) => true,

            Expression::Identifier(id) => {
                let ty = self.get_var_type(id.name.as_str());
                match ty {
                    Some(
                        ZigType::Struct(_)
                        | ZigType::I64
                        | ZigType::F64
                        | ZigType::Bool
                        | ZigType::Str
                        | ZigType::ArrayList(_)
                        | ZigType::NamedStruct(_),
                    ) => false,
                    // Unknown type: conservatively assume it might be null
                    // so that optional chaining null checks are not skipped.
                    None => true,
                    _ => true, // JsAny, Anytype, Void → might be null
                }
            }

            // ChainExpression result is always nullable (the else branch is null)
            Expression::ChainExpression(_) => true,

            // Call expressions might return null
            Expression::CallExpression(_) => true,

            // Member access: check recursively
            Expression::StaticMemberExpression(sme) => self.expr_might_be_null(&sme.object),
            Expression::ComputedMemberExpression(cme) => self.expr_might_be_null(&cme.object),

            // Conservative: assume everything else might be null
            _ => true,
        }
    }

    /// Check if an expression's inferred type is JsAny.
    /// Used to decide whether optional chaining should use obj.get() instead
    /// of (if (obj) |oc| oc.prop else null), since JsAny is a union not an optional.
    pub(super) fn expr_type_is_jsany(&self, expr: &Expression) -> bool {
        match expr {
            Expression::NullLiteral(_) => true,
            Expression::Identifier(id) => {
                matches!(self.get_var_type(id.name.as_str()), Some(ZigType::JsAny))
            }
            Expression::CallExpression(_) => {
                // Many runtime calls return JsAny; be conservative
                true
            }
            Expression::ParenthesizedExpression(pe) => {
                // Unwrap parentheses and check the inner expression
                self.expr_type_is_jsany(&pe.expression)
            }
            _ => {
                // Fallback: use type inference to check if the expression is JsAny.
                // This covers assignment, conditional, logical, member access, and
                // other expression types whose inferred type could be JsAny.
                self.infer_expr_type(expr) == Some(ZigType::JsAny)
            }
        }
    }

    /// Get the type of a variable, checking fn_local_types (per-function) first,
    /// then falling back to global var_types. This fixes the scoping issue where
    /// var_names from different functions collide in the flat var_types map.
    fn get_var_type(&self, name: &str) -> Option<ZigType> {
        // Per-function local types take priority
        if let Some(ty) = self
            .fn_ctx
            .as_ref()
            .and_then(|ctx| ctx.fn_local_types.get(name))
        {
            return Some(ty.clone());
        }
        // Fall back to global var_types
        self.type_info.var_types.get(name).cloned()
    }
}