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