Skip to main content

js2zig_core/zigir/emit/expr/
template_new.rs

1// zigir/emit/expr/template_new.rs
2// Template literal and new expression emission.
3
4use crate::zigir::emit::Emitter;
5use crate::zigir::emit::helpers::EmitterHelpers;
6use crate::zigir::kinds::{DateConstructorKind, NewConstructor, TypedArrayKind};
7
8impl Emitter {
9    pub(super) fn emit_template_literal(
10        &mut self,
11        parts: &[String],
12        exprs: &[crate::zigir::types::IrExpr],
13        format_specs: &[String],
14    ) {
15        use crate::zigir::emit::helpers::escape_zig_format_string;
16        // Zig template literal → std.fmt.allocPrint
17        if exprs.is_empty() {
18            // No expressions: just a string literal
19            self.write(&format!("\"{}\"", escape_zig_format_string(&parts[0])));
20        } else {
21            // Build the format string: parts[0] + {spec0} + parts[1] + {spec1} + ...
22            let mut fmt = String::new();
23            for (i, part) in parts.iter().enumerate() {
24                if i > 0 && i - 1 < format_specs.len() {
25                    fmt.push_str(&format_specs[i - 1]);
26                }
27                fmt.push_str(&escape_zig_format_string(part));
28            }
29            // Emit args as a separate pass to get their string representations
30            self.emit_alloc_print(&fmt, exprs);
31        }
32    }
33
34    pub(super) fn emit_new_expr(&mut self, new_expr: &crate::zigir::types::IrNewExpr) {
35        use crate::zigir::emit::helpers;
36        match &new_expr.constructor {
37            NewConstructor::Map => {
38                self.write("js_collections.JsMap.init(js_allocator.allocator())");
39            }
40            NewConstructor::Set => {
41                self.write("js_collections.JsSet.init(js_allocator.allocator())");
42            }
43            NewConstructor::Date(kind) => match kind {
44                DateConstructorKind::Now => {
45                    self.write("js_date.JsDate.init()");
46                }
47                DateConstructorKind::FromMillis => {
48                    self.write("js_date.JsDate.fromMillis(");
49                    self.emit_first_arg_or_default(&new_expr.args, "");
50                    self.write(")");
51                }
52                DateConstructorKind::FromString => {
53                    // new Date("2024-01-01") → js_date.JsDate.fromMillis(js_date.parse("2024-01-01"))
54                    self.write("js_date.JsDate.fromMillis(js_date.parse(");
55                    self.emit_first_arg_or_default(&new_expr.args, "");
56                    self.write("))");
57                }
58                DateConstructorKind::FromComponents => {
59                    // new Date(y, m, d, h, min, s, ms)
60                    // Defaults: d=1, h=0, min=0, s=0, ms=0
61                    self.write("js_date.JsDate.fromComponents(");
62                    // y and m are always required; provide defaults for all 7 slots
63                    let defaults = ["0", "0", "1", "0", "0", "0", "0"];
64                    self.emit_args_with_defaults(&new_expr.args, 7, &defaults);
65                    self.write(")");
66                }
67            },
68            NewConstructor::RegExp => {
69                // new RegExp(pat, flags?) → js_regexp.JsRegExp.init(alloc, pat, flags_or_empty) catch @panic(...)
70                self.write("js_regexp.JsRegExp.init(js_allocator.allocator(), ");
71                self.emit_first_arg_or_default(&new_expr.args, "\"\"");
72                self.write(", ");
73                if new_expr.args.len() >= 2 {
74                    self.emit_expr(&new_expr.args[1]);
75                } else {
76                    self.write("\"\"");
77                }
78                self.write(") catch @panic(\"OOM: RegExp init\")");
79            }
80            NewConstructor::TypedArray(kind) => {
81                let (module, init_fn) = super::typed_array_init(kind);
82                let is_float = matches!(
83                    kind,
84                    TypedArrayKind::Float32Array | TypedArrayKind::Float64Array
85                );
86                let elem_type = if is_float { "f64" } else { "i64" };
87                let zero_val = if is_float { "0.0" } else { "0" };
88
89                self.write(&format!("{}.{}(", module, init_fn));
90                match new_expr.args.first() {
91                    // Array literal: emit elements directly as &[_]T{ ... }
92                    Some(crate::zigir::types::IrExpr::ArrayLiteral(arr)) => {
93                        self.write(&format!("&[_]{}{{ ", elem_type));
94                        for (i, elem) in arr.elements.iter().enumerate() {
95                            if i > 0 {
96                                self.write(", ");
97                            }
98                            // Skip spread elements in this context
99                            if !arr.spread_indices.contains(&i) {
100                                self.emit_expr(elem);
101                            }
102                        }
103                        self.write(" }");
104                    }
105                    // Integer literal: a positive, comptime-known length in
106                    // a reasonable range means we can emit `[_]T{ zero } ** n`
107                    // to get a zero-filled typed array.
108                    Some(crate::zigir::types::IrExpr::IntLiteral(n)) if *n > 0 && *n <= 1024 => {
109                        // Comptime-known length: use array repeat syntax
110                        self.write(&format!("&[_]{}{{ {} }} ** {}", elem_type, zero_val, n));
111                    }
112                    // Zero-length or unrealistic length: emit an empty array
113                    // (the runtime call is responsible for sizing).
114                    Some(crate::zigir::types::IrExpr::IntLiteral(_)) => {
115                        self.write(&format!("&[_]{}{{}}", elem_type));
116                    }
117                    // No args: empty array
118                    None => {
119                        self.write(&format!("&[_]{}{{}}", elem_type));
120                    }
121                    // Other expressions: not supported in this position
122                    Some(_) => {
123                        self.write(&helpers::compile_error(
124                            "new TypedArray(expr) only supports array literal or integer length",
125                        ));
126                    }
127                }
128                self.write(")");
129            }
130            NewConstructor::Class(class_name) => {
131                self.write(&format!("{}.init(", class_name));
132                for (i, arg) in new_expr.args.iter().enumerate() {
133                    if i > 0 {
134                        self.write(", ");
135                    }
136                    self.emit_one_arg(arg);
137                }
138                self.write(")");
139            }
140            NewConstructor::Error(msg) => {
141                self.write(&format!(
142                    "JsAny.fromError(\"{}\")",
143                    helpers::escape_zig_string(msg)
144                ));
145            }
146            NewConstructor::Unsupported(name) => {
147                self.write(&helpers::compile_error(&format!(
148                    "new {}() is not supported",
149                    name
150                )));
151            }
152        }
153    }
154}