dixscript 1.0.0

Config, code, and encryption in one file — a data interchange format with compile-time functions, AES-256/ChaCha20 built-in, and cross-platform FFI
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
419
420
421
422
423
424
425
426
427
428
429
// src/Builtins/Resolver/static_object_registry.rs
//! Central registry for all static objects in DixScript
//! Provides thread-safe access to Math, DateTime, Array, Dix, etc.

use crate::Builtins::Core::{DixValue, IBuiltinMethod, DixType};
use crate::Builtins::Static::{
    IStaticObject, ArrayObject, DateTimeObject, DixObject,
    EnumObject, GuidObject, IpAddressObject, MathObject, RandomObject,
};
use std::collections::HashMap;
use std::sync::{OnceLock, RwLock};

/// Global static object registry
static REGISTRY: OnceLock<StaticObjectRegistry> = OnceLock::new();

/// Registry for all static objects
pub struct StaticObjectRegistry {
    objects: RwLock<HashMap<String, Box<dyn IStaticObject>>>,
}

impl StaticObjectRegistry {
    /// Create and initialize the registry
    fn new() -> Self {
        let mut registry = StaticObjectRegistry {
            objects: RwLock::new(HashMap::new()),
        };
        registry.initialize_objects();
        registry
    }

    /// Initialize all built-in static objects
    fn initialize_objects(&mut self) {
        let mut objects = self.objects.write().unwrap();

        // Register core static objects
        objects.insert("Dix".to_string(), Box::new(DixObject::new()));
        objects.insert("Math".to_string(), Box::new(MathObject::new()));
        objects.insert("DateTime".to_string(), Box::new(DateTimeObject::new()));
        objects.insert("Array".to_string(), Box::new(ArrayObject::new()));
        objects.insert("Random".to_string(), Box::new(RandomObject::new()));
        objects.insert("Enum".to_string(), Box::new(EnumObject::new()));
        objects.insert("Guid".to_string(), Box::new(GuidObject::new()));
        objects.insert("IpAddress".to_string(), Box::new(IpAddressObject::new()));
    }

    /// Get the global registry instance
    fn get() -> &'static StaticObjectRegistry {
        REGISTRY.get_or_init(StaticObjectRegistry::new)
    }
}

// ==================== PUBLIC API ====================

/// Initialize the static object registry
pub fn initialize_static_registry() {
    // Force initialization
    let _ = StaticObjectRegistry::get();
}

/// Check if a static object exists
pub fn has_static_object(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();
    objects.contains_key(name)
}

/// Call a method on a static object
pub fn call_static_method(
    object_name: &str,
    method_name: &str,
    args: &[DixValue],
) -> Result<DixValue, String> {
    if object_name.is_empty() {
        return Err("Object name cannot be empty".to_string());
    }

    if method_name.is_empty() {
        return Err("Method name cannot be empty".to_string());
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    let obj = objects
        .get(object_name)
        .ok_or_else(|| format!("Unknown static object: {}", object_name))?;

    obj.call_method(method_name, args)
}

/// Check if a static object has a specific method
pub fn has_static_method(object_name: &str, method_name: &str) -> bool {
    if object_name.is_empty() || method_name.is_empty() {
        return false;
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    objects
        .get(object_name)
        .map(|obj| obj.has_method(method_name))
        .unwrap_or(false)
}

/// Get all registered object names
pub fn get_object_names() -> Vec<String> {
    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();
    objects.keys().cloned().collect()
}

/// Get all method names for a specific object
pub fn get_method_names(object_name: &str) -> Vec<String> {
    if object_name.is_empty() {
        return Vec::new();
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    objects
        .get(object_name)
        .map(|obj| obj.get_method_names())
        .unwrap_or_default()
}

/// Get method information (parameter count, return type, description)
/// This replaces the problematic get_method that returned a trait object reference
pub fn get_method_info(
    object_name: &str,
    method_name: &str,
) -> Option<MethodInfo> {
    if object_name.is_empty() || method_name.is_empty() {
        return None;
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    objects.get(object_name).and_then(|obj| {
        obj.get_method(method_name).map(|m| MethodInfo {
            name: m.name().to_string(),
            parameter_count: m.parameter_count(),
            min_parameter_count: m.min_parameter_count(),
            return_type: m.return_type(),
            description: m.description().to_string(),
        })
    })
}

/// Check if method exists and get basic info for validation
pub fn get_method(object_name: &str, method_name: &str) -> Option<&'static dyn IBuiltinMethod> {
    // NOTE: This function cannot safely return a reference to a trait object
    // because the RwLock guard would be dropped before we return.
    // Instead, use get_method_info() or call methods directly through call_static_method()

    // For now, we check if it exists and return None
    // Callers should use get_method_info instead
    if has_static_method(object_name, method_name) {
        // We can't actually return the method reference due to lifetime issues
        // This is a design limitation we'll work around
        None
    } else {
        None
    }
}

/// Validate a static method call's argument *types* against the method's real
/// `validate_arguments` (which may include a custom type validator), entirely
/// inside the registry's read lock. This sidesteps the lifetime issue that
/// prevents `get_method()` from returning a borrowed `&dyn IBuiltinMethod`
/// directly to callers outside the lock.
pub fn validate_call_with_types(
    object_name: &str,
    method_name: &str,
    args: &[DixValue],
) -> bool {
    if object_name.is_empty() || method_name.is_empty() {
        return false;
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    let obj = match objects.get(object_name) {
        Some(o) => o,
        None => return false,
    };

    match obj.get_method(method_name) {
        Some(method) => method.validate_arguments(args),
        None => false,
    }
}

/// Validate a static method call
pub fn validate_call(
    object_name: &str,
    method_name: &str,
    arg_count: usize,
) -> ValidationResult {
    if object_name.is_empty() {
        return ValidationResult::error("Object name cannot be empty");
    }

    if method_name.is_empty() {
        return ValidationResult::error("Method name cannot be empty");
    }

    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    let obj = match objects.get(object_name) {
        Some(o) => o,
        None => return ValidationResult::error(&format!("Unknown static object: {}", object_name)),
    };

    if !obj.has_method(method_name) {
        return ValidationResult::error(&format!(
            "{} has no method: {}",
            object_name, method_name
        ));
    }

    // Get method info to validate parameter count
    drop(objects); // Release the lock before calling get_method_info

    if let Some(method_info) = get_method_info(object_name, method_name) {
        // Check parameter count (-1 means variadic)
        if method_info.parameter_count != -1 && method_info.parameter_count as usize != arg_count {
            return ValidationResult::error(&format!(
                "{}.{} expects {} arguments, got {}",
                object_name,
                method_name,
                method_info.parameter_count,
                arg_count
            ));
        }
    }

    ValidationResult::success()
}

/// Get full registry information
pub fn get_full_registry() -> HashMap<String, Vec<String>> {
    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    let mut result = HashMap::new();
    for (name, obj) in objects.iter() {
        result.insert(name.clone(), obj.get_method_names());
    }
    result
}

/// Export registry information for documentation
pub fn export_registry_info() -> RegistryInfo {
    let registry = StaticObjectRegistry::get();
    let objects = registry.objects.read().unwrap();

    let mut object_infos = Vec::new();

    for (name, obj) in objects.iter() {
        let mut method_infos = Vec::new();

        for method_name in obj.get_method_names() {
            if let Some(method) = obj.get_method(&method_name) {
                method_infos.push(MethodInfo {
                    name: method.name().to_string(),
                    parameter_count: method.parameter_count(),
                    min_parameter_count: method.min_parameter_count(),
                    return_type: method.return_type(),
                    description: method.description().to_string(),
                });
            }
        }

        object_infos.push(ObjectInfo {
            name: name.clone(),
            methods: method_infos,
        });
    }

    RegistryInfo {
        objects: object_infos,
    }
}

// ==================== VALIDATION RESULT ====================

/// Validation result for static method calls
#[derive(Debug, Clone)]
pub struct ValidationResult {
    is_valid: bool,
    error_message: Option<String>,
}

impl ValidationResult {
    pub fn success() -> Self {
        ValidationResult {
            is_valid: true,
            error_message: None,
        }
    }

    pub fn error(message: &str) -> Self {
        ValidationResult {
            is_valid: false,
            error_message: Some(message.to_string()),
        }
    }

    pub fn is_valid(&self) -> bool {
        self.is_valid
    }

    pub fn error_message(&self) -> Option<&str> {
        self.error_message.as_deref()
    }
}

// ==================== REGISTRY INFORMATION TYPES ====================

/// Complete registry information
#[derive(Debug, Clone)]
pub struct RegistryInfo {
    pub objects: Vec<ObjectInfo>,
}

/// Information about a static object
#[derive(Debug, Clone)]
pub struct ObjectInfo {
    pub name: String,
    pub methods: Vec<MethodInfo>,
}

/// Information about a method
#[derive(Debug, Clone)]
pub struct MethodInfo {
    pub name: String,
    pub parameter_count: i32,
    pub min_parameter_count: i32,
    pub return_type: DixType,
    pub description: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_registry_initialization() {
        initialize_static_registry();
        let names = get_object_names();
        assert!(!names.is_empty());
        assert!(names.contains(&"Math".to_string()));
        assert!(names.contains(&"DateTime".to_string()));
    }

    #[test]
    fn test_has_static_object() {
        initialize_static_registry();
        assert!(has_static_object("Math"));
        assert!(has_static_object("DateTime"));
        assert!(!has_static_object("NonExistent"));
    }

    #[test]
    fn test_has_static_method() {
        initialize_static_registry();
        assert!(has_static_method("Math", "max"));
        assert!(has_static_method("DateTime", "now"));
        assert!(!has_static_method("Math", "nonexistent"));
    }

    #[test]
    fn test_validate_call() {
        initialize_static_registry();
        let result = validate_call("Math", "max", 2);
        assert!(result.is_valid());

        let result = validate_call("Math", "max", 3);
        assert!(!result.is_valid());

        let result = validate_call("NonExistent", "method", 0);
        assert!(!result.is_valid());
    }

    #[test]
    fn test_get_method_info() {
        initialize_static_registry();
        let info = get_method_info("Math", "max");
        assert!(info.is_some());

        if let Some(method_info) = info {
            assert_eq!(method_info.name, "max");
            assert_eq!(method_info.parameter_count, 2);
        }
    }

    #[test]
    fn test_validate_call_with_types() {
        initialize_static_registry();
        // Math.max(a, b) requires all_numeric — two ints should pass
        let ok = validate_call_with_types(
            "Math",
            "max",
            &[DixValue::from_int(1), DixValue::from_int(2)],
        );
        assert!(ok);

        // A string argument should fail Math.max's numeric validator
        let bad = validate_call_with_types(
            "Math",
            "max",
            &[DixValue::from_string("a".to_string()), DixValue::from_int(2)],
        );
        assert!(!bad);

        // Unknown method
        let missing = validate_call_with_types("Math", "nonexistent", &[]);
        assert!(!missing);
    }
            }