Skip to main content

js2zig_core/zigir/
kinds.rs

1// zigir/kinds.rs
2// Classification enums for member access, calls, and computed keys.
3
4/// How a field access (`obj.field`) should be emitted in Zig.
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6pub enum FieldKind {
7    /// Direct struct field: `obj.field`
8    StructField,
9    /// Namespace/module access: `std.math.pi` (chained field access on import)
10    Namespace,
11    /// ArrayList length: `arr.items.len`
12    ArrayListLen,
13    /// String length: `js_string.utf16Len(str)` (UTF-16 code unit count, JS semantics)
14    StringLen,
15    /// Slice/TypedArray length: `obj.len` (element count)
16    SliceLen,
17    /// arguments.length: `@as(i64, @intCast(obj.len))` — JS .length is i64, Zig .len is usize
18    ArgumentsLen,
19    /// Map/Set size: `map.size()` or `set.size()`  (method call, not field)
20    MapSetSize,
21    /// Math constant: `std.math.pi`, etc.
22    MathConstant(String),
23    /// Number constant: `std.math.floatMax(f64)`, etc.
24    NumberConstant(String),
25    /// Well-known Symbol: `js_symbol.symbolIterator()`, etc.
26    SymbolWellKnown(String),
27    /// TypedArray property: `.buffer`, `.byteLength`, `.byteOffset`
28    /// `type_suffix` carries the element type suffix (e.g., "I32" for Int32Array)
29    /// to emit `js_runtime.js_typedarray.bufferI32(arr)`.
30    TypedArrayProp {
31        prop: String,
32        type_suffix: Option<String>,
33    },
34    /// Private class field: `self.field` (from #field syntax)
35    Private,
36    /// Pointer dereference field: `obj.field.*` (captured mutable closure var)
37    PointerDeref,
38    /// RegExp property: `.source`, `.flags`, `.global`
39    RegExpProp { prop: String },
40    /// Static class field: `ClassName.field` → `__ClassName_field` module-scope var
41    StaticField { class_name: String },
42}
43
44/// How an index access (`obj[idx]`) should be emitted in Zig.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum IndexKind {
47    /// ArrayList item: `arr.items[n]`
48    ArrayListItem,
49    /// Slice index: `arr[n]`
50    SliceIndex,
51}
52
53/// How a computed member access (`obj[key]`) should be emitted.
54#[derive(Debug, Clone, PartialEq, Eq, Hash)]
55pub enum ComputedKeyKind {
56    /// Struct field via @field: `@field(obj, key)`
57    StructField,
58    /// Map get: `obj.get(key)`
59    MapGet,
60    /// JsAny dynamic: `obj.getByKey(key, alloc)`
61    JsAnyGetByKey,
62    /// ArrayList item: `arr.items[@as(usize, @intCast(key))]`
63    ArrayListItem,
64    /// String character (single-character substring): `js_string.charAt(alloc, str, idx) catch ...`
65    /// Returns `[]const u8` (ZigType::Str). Matches JS `str[i]` semantics which
66    /// returns the i-th UTF-16 code unit as a substring (like `String.prototype.charAt`).
67    StringCharAt,
68    /// Unsupported dynamic access → generates @compileError
69    CompileError(String),
70}
71
72/// What kind of function call this is.
73#[derive(Debug, Clone, PartialEq, Eq, Hash)]
74pub enum CallKind {
75    /// Direct function call: `fn(args)`
76    Direct,
77    /// Method call on a known object type: `obj.method(args)`
78    Method { object_type: MethodObjectKind },
79    /// Closure call: `closure_instance(.call)(args)`
80    Closure,
81}
82
83/// Known object types for method call dispatch.
84#[derive(Debug, Clone, PartialEq, Eq, Hash)]
85pub enum MethodObjectKind {
86    ArrayList,
87    String,
88    Map,
89    Set,
90    Date,
91    /// User-defined class method: carries the class name.
92    Class(String),
93    JsAny,
94    Unknown,
95}
96
97/// What kind of constructor `new X(...)` targets.
98#[derive(Debug, Clone, PartialEq, Eq, Hash)]
99pub enum NewConstructor {
100    Map,
101    Set,
102    Date(DateConstructorKind),
103    RegExp,
104    TypedArray(TypedArrayKind),
105    /// User-defined class constructor.
106    Class(String),
107    /// Error constructor: `new Error(msg)`.
108    Error(String),
109    /// Unsupported constructor → generates @compileError.
110    Unsupported(String),
111}
112
113/// How `new Date(...)` was called.
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub enum DateConstructorKind {
116    /// `new Date()` → current time
117    Now,
118    /// `new Date(millis)` → from milliseconds
119    FromMillis,
120    /// `new Date(string)` → from string
121    FromString,
122    /// `new Date(y,m,d,h,min,s,ms)` → from components
123    FromComponents,
124}
125
126/// TypedArray element types.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
128pub enum TypedArrayKind {
129    Int8Array,
130    Uint8Array,
131    Uint8ClampedArray,
132    Int16Array,
133    Uint16Array,
134    Int32Array,
135    Uint32Array,
136    Float32Array,
137    Float64Array,
138    BigInt64Array,
139    BigUint64Array,
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn test_field_kind_variants() {
148        let kinds = [
149            FieldKind::StructField,
150            FieldKind::ArrayListLen,
151            FieldKind::StringLen,
152            FieldKind::MapSetSize,
153            FieldKind::MathConstant("pi".to_string()),
154            FieldKind::NumberConstant("floatMax".to_string()),
155            FieldKind::SymbolWellKnown("iterator".to_string()),
156            FieldKind::TypedArrayProp {
157                prop: "buffer".to_string(),
158                type_suffix: None,
159            },
160        ];
161        assert_eq!(kinds.len(), 8);
162    }
163
164    #[test]
165    fn test_call_kind() {
166        let direct = CallKind::Direct;
167        let method = CallKind::Method {
168            object_type: MethodObjectKind::ArrayList,
169        };
170        let closure = CallKind::Closure;
171        assert_ne!(direct, method);
172        assert_ne!(method, closure);
173    }
174
175    #[test]
176    fn test_new_constructor() {
177        let date_now = NewConstructor::Date(DateConstructorKind::Now);
178        let class = NewConstructor::Class("Foo".to_string());
179        assert!(matches!(
180            date_now,
181            NewConstructor::Date(DateConstructorKind::Now)
182        ));
183        assert!(matches!(class, NewConstructor::Class(_)));
184    }
185
186    #[test]
187    fn test_typed_array_kinds() {
188        let all = [
189            TypedArrayKind::Int8Array,
190            TypedArrayKind::Uint8Array,
191            TypedArrayKind::Uint8ClampedArray,
192            TypedArrayKind::Int16Array,
193            TypedArrayKind::Uint16Array,
194            TypedArrayKind::Int32Array,
195            TypedArrayKind::Uint32Array,
196            TypedArrayKind::Float32Array,
197            TypedArrayKind::Float64Array,
198            TypedArrayKind::BigInt64Array,
199            TypedArrayKind::BigUint64Array,
200        ];
201        assert_eq!(all.len(), 11);
202    }
203}