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: `str[@as(usize, @intCast(key))]` (promoted to i64)
65    StringChar,
66    /// Unsupported dynamic access → generates @compileError
67    CompileError(String),
68}
69
70/// What kind of function call this is.
71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
72pub enum CallKind {
73    /// Direct function call: `fn(args)`
74    Direct,
75    /// Method call on a known object type: `obj.method(args)`
76    Method { object_type: MethodObjectKind },
77    /// Closure call: `closure_instance(.call)(args)`
78    Closure,
79}
80
81/// Known object types for method call dispatch.
82#[derive(Debug, Clone, PartialEq, Eq, Hash)]
83pub enum MethodObjectKind {
84    ArrayList,
85    String,
86    Map,
87    Set,
88    Date,
89    /// User-defined class method: carries the class name.
90    Class(String),
91    JsAny,
92    Unknown,
93}
94
95/// What kind of constructor `new X(...)` targets.
96#[derive(Debug, Clone, PartialEq, Eq, Hash)]
97pub enum NewConstructor {
98    Map,
99    Set,
100    Date(DateConstructorKind),
101    RegExp,
102    TypedArray(TypedArrayKind),
103    /// User-defined class constructor.
104    Class(String),
105    /// Error constructor: `new Error(msg)`.
106    Error(String),
107    /// Unsupported constructor → generates @compileError.
108    Unsupported(String),
109}
110
111/// How `new Date(...)` was called.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub enum DateConstructorKind {
114    /// `new Date()` → current time
115    Now,
116    /// `new Date(millis)` → from milliseconds
117    FromMillis,
118    /// `new Date(string)` → from string
119    FromString,
120    /// `new Date(y,m,d,h,min,s,ms)` → from components
121    FromComponents,
122}
123
124/// TypedArray element types.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
126pub enum TypedArrayKind {
127    Int8Array,
128    Uint8Array,
129    Uint8ClampedArray,
130    Int16Array,
131    Uint16Array,
132    Int32Array,
133    Uint32Array,
134    Float32Array,
135    Float64Array,
136    BigInt64Array,
137    BigUint64Array,
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn test_field_kind_variants() {
146        let kinds = [
147            FieldKind::StructField,
148            FieldKind::ArrayListLen,
149            FieldKind::StringLen,
150            FieldKind::MapSetSize,
151            FieldKind::MathConstant("pi".to_string()),
152            FieldKind::NumberConstant("floatMax".to_string()),
153            FieldKind::SymbolWellKnown("iterator".to_string()),
154            FieldKind::TypedArrayProp {
155                prop: "buffer".to_string(),
156                type_suffix: None,
157            },
158        ];
159        assert_eq!(kinds.len(), 8);
160    }
161
162    #[test]
163    fn test_call_kind() {
164        let direct = CallKind::Direct;
165        let method = CallKind::Method {
166            object_type: MethodObjectKind::ArrayList,
167        };
168        let closure = CallKind::Closure;
169        assert_ne!(direct, method);
170        assert_ne!(method, closure);
171    }
172
173    #[test]
174    fn test_new_constructor() {
175        let date_now = NewConstructor::Date(DateConstructorKind::Now);
176        let class = NewConstructor::Class("Foo".to_string());
177        assert!(matches!(
178            date_now,
179            NewConstructor::Date(DateConstructorKind::Now)
180        ));
181        assert!(matches!(class, NewConstructor::Class(_)));
182    }
183
184    #[test]
185    fn test_typed_array_kinds() {
186        let all = [
187            TypedArrayKind::Int8Array,
188            TypedArrayKind::Uint8Array,
189            TypedArrayKind::Uint8ClampedArray,
190            TypedArrayKind::Int16Array,
191            TypedArrayKind::Uint16Array,
192            TypedArrayKind::Int32Array,
193            TypedArrayKind::Uint32Array,
194            TypedArrayKind::Float32Array,
195            TypedArrayKind::Float64Array,
196            TypedArrayKind::BigInt64Array,
197            TypedArrayKind::BigUint64Array,
198        ];
199        assert_eq!(all.len(), 11);
200    }
201}