lambdust 0.1.1

A Scheme dialect with gradual typing and effect systems
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
#![allow(unused_variables)]
//! Type safety and runtime verification system for FFI operations.
//!
//! This module provides comprehensive type checking, runtime validation,
//! and safety guarantees for FFI function calls and data marshalling.

use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, RwLock};

use crate::eval::Value;
use crate::ast::Literal;
use crate::diagnostics::Error;
use crate::ffi::c_types::CType;

/// Type alias for safety results to reduce error size
pub type SafetyResult<T> = std::result::Result<T, Box<SafetyError>>;

/// Errors that can occur during safety validation
#[derive(Debug, Clone)]
pub enum SafetyError {
    /// Type signature mismatch
    SignatureMismatch {
        function: String,
        expected: FunctionSignature,
        actual: Box<FunctionSignature>,
    },
    /// Invalid function pointer
    InvalidFunctionPointer {
        function: String,
        pointer: *const u8,
    },
    /// Runtime type check failed
    RuntimeTypeCheck {
        parameter: usize,
        expected: CType,
        actual_value: String,
    },
    /// Boundary violation
    BoundaryViolation {
        operation: String,
        description: String,
    },
    /// Null pointer dereference
    NullPointerDereference {
        parameter: usize,
        context: String,
    },
    /// Buffer bounds check failed
    BufferBoundsCheck {
        buffer_size: usize,
        access_offset: usize,
        access_size: usize,
    },
    /// Uninitialized memory access
    UninitializedMemory {
        pointer: *const u8,
        size: usize,
    },
    /// Stack overflow protection
    StackOverflow {
        current_depth: usize,
        max_depth: usize,
    },
    /// Resource leak detected
    ResourceLeak {
        resource_type: String,
        resource_id: String,
    },
}

impl fmt::Display for SafetyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SafetyError::SignatureMismatch { function, expected, actual } => {
                write!(f, "Function '{function}' signature mismatch: expected {expected:?}, got {actual:?}")
            }
            SafetyError::InvalidFunctionPointer { function, pointer } => {
                write!(f, "Invalid function pointer for '{function}': {pointer:p}")
            }
            SafetyError::RuntimeTypeCheck { parameter, expected, actual_value } => {
                write!(f, "Runtime type check failed for parameter {parameter}: expected {expected}, got {actual_value}")
            }
            SafetyError::BoundaryViolation { operation, description } => {
                write!(f, "Boundary violation in {operation}: {description}")
            }
            SafetyError::NullPointerDereference { parameter, context } => {
                write!(f, "Null pointer dereference in parameter {parameter} ({context})")
            }
            SafetyError::BufferBoundsCheck { buffer_size, access_offset, access_size } => {
                write!(f, "Buffer bounds check failed: buffer size {buffer_size}, access offset {access_offset}, access size {access_size}")
            }
            SafetyError::UninitializedMemory { pointer, size } => {
                write!(f, "Uninitialized memory access at {pointer:p} (size {size})")
            }
            SafetyError::StackOverflow { current_depth, max_depth } => {
                write!(f, "Stack overflow: current depth {current_depth}, max depth {max_depth}")
            }
            SafetyError::ResourceLeak { resource_type, resource_id } => {
                write!(f, "Resource leak detected: {resource_type} (ID: {resource_id})")
            }
        }
    }
}

impl std::error::Error for SafetyError {}

impl From<SafetyError> for Error {
    fn from(safety_error: SafetyError) -> Self {
        Error::runtime_error(safety_error.to_string(), None)
    }
}

/// Function signature for type checking
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionSignature {
    /// Function name
    pub name: String,
    /// Parameter types
    pub parameters: Vec<CType>,
    /// Return type
    pub return_type: CType,
    /// Whether the function is variadic
    pub variadic: bool,
    /// Whether the function can be called safely
    pub safe: bool,
    /// Additional constraints
    pub constraints: Vec<TypeConstraint>,
}

/// Type constraints for additional validation
#[derive(Debug, Clone, PartialEq)]
pub enum TypeConstraint {
    /// Parameter must not be null
    NonNull(usize),
    /// Parameter must be within bounds
    Bounds {
        parameter: usize,
        min: i64,
        max: i64,
    },
    /// String parameter must be null-terminated
    NullTerminated(usize),
    /// Buffer parameter with size parameter
    BufferWithSize {
        buffer_param: usize,
        size_param: usize,
    },
    /// Pointer parameter must be aligned
    Aligned {
        parameter: usize,
        alignment: usize,
    },
    /// Resource management constraint
    ResourceManagement {
        parameter: usize,
        resource_type: String,
        lifetime: ResourceLifetime,
    },
}

/// Resource lifetime management
#[derive(Debug, Clone, PartialEq)]
pub enum ResourceLifetime {
    /// Resource is owned by caller
    Owned,
    /// Resource is borrowed for function duration
    Borrowed,
    /// Resource is transferred to callee
    Transferred,
    /// Resource has shared ownership
    Shared,
}

/// Type safety validator
#[derive(Debug)]
pub struct TypeSafetyValidator {
    /// Registered function signatures
    signatures: RwLock<HashMap<String, FunctionSignature>>,
    /// Runtime validation rules
    validation_rules: RwLock<HashMap<String, Vec<ValidationRule>>>,
    /// Type checking configuration
    config: RwLock<SafetyConfig>,
    /// Safety statistics
    stats: RwLock<SafetyStats>,
    /// Stack depth tracking
    stack_depth: RwLock<usize>,
}

/// Runtime validation rule
#[derive(Debug, Clone)]
pub struct ValidationRule {
    /// Rule name
    pub name: String,
    /// When to apply this rule
    pub trigger: ValidationTrigger,
    /// Validation function
    pub validator: ValidationFunction,
    /// Whether this rule is enabled
    pub enabled: bool,
}

/// When to trigger validation
#[derive(Debug, Clone)]
pub enum ValidationTrigger {
    /// Before function call
    PreCall,
    /// After function call
    PostCall,
    /// On parameter conversion
    ParameterConversion(usize),
    /// On return value conversion
    ReturnConversion,
    /// Custom trigger condition
    Custom(String),
}

/// Validation function type
#[derive(Debug, Clone)]
pub enum ValidationFunction {
    /// Null pointer check
    NullPointerCheck,
    /// Bounds check
    BoundsCheck { min: i64, max: i64 },
    /// Buffer size check
    BufferSizeCheck,
    /// String validation
    StringValidation,
    /// Alignment check
    AlignmentCheck { alignment: usize },
    /// Custom validation
    Custom { name: String, description: String },
}

/// Safety configuration
#[derive(Debug, Clone)]
pub struct SafetyConfig {
    /// Enable runtime type checking
    pub runtime_type_checking: bool,
    /// Enable null pointer checking
    pub null_pointer_checking: bool,
    /// Enable bounds checking
    pub bounds_checking: bool,
    /// Enable buffer overflow protection
    pub buffer_overflow_protection: bool,
    /// Enable stack overflow protection
    pub stack_overflow_protection: bool,
    /// Maximum call stack depth
    pub max_stack_depth: usize,
    /// Enable resource leak detection
    pub resource_leak_detection: bool,
    /// Enable function pointer validation
    pub function_pointer_validation: bool,
    /// Enable memory alignment checking
    pub memory_alignment_checking: bool,
}

impl Default for SafetyConfig {
    fn default() -> Self {
        Self {
            runtime_type_checking: true,
            null_pointer_checking: true,
            bounds_checking: true,
            buffer_overflow_protection: true,
            stack_overflow_protection: true,
            max_stack_depth: 64,
            resource_leak_detection: true,
            function_pointer_validation: true,
            memory_alignment_checking: true,
        }
    }
}

/// Safety validation statistics
#[derive(Debug, Default, Clone)]
pub struct SafetyStats {
    /// Total function calls validated
    pub total_validations: u64,
    /// Successful validations
    pub successful_validations: u64,
    /// Failed validations
    pub failed_validations: u64,
    /// Null pointer violations prevented
    pub null_pointer_violations: u64,
    /// Bounds violations prevented
    pub bounds_violations: u64,
    /// Buffer overflow attempts prevented
    pub buffer_overflow_prevented: u64,
    /// Stack overflow attempts prevented
    pub stack_overflow_prevented: u64,
    /// Resource leaks detected
    pub resource_leaks_detected: u64,
}

impl Default for TypeSafetyValidator {
    fn default() -> Self {
        Self::new()
    }
}

impl TypeSafetyValidator {
    /// Create a new type safety validator
    pub fn new() -> Self {
        Self {
            signatures: RwLock::new(HashMap::new()),
            validation_rules: RwLock::new(HashMap::new()),
            config: RwLock::new(SafetyConfig::default()),
            stats: RwLock::new(SafetyStats::default()),
            stack_depth: RwLock::new(0),
        }
    }

    /// Configure the safety validator
    pub fn configure(&self, config: SafetyConfig) {
        let mut current_config = self.config.write().unwrap();
        *current_config = config;
    }

    /// Register a function signature
    pub fn register_function_signature(&self, signature: FunctionSignature) -> SafetyResult<()> {
        let mut signatures = self.signatures.write().unwrap();
        signatures.insert(signature.name.clone(), signature);
        Ok(())
    }

    /// Add a validation rule for a function
    pub fn add_validation_rule(&self, function_name: String, rule: ValidationRule) {
        let mut rules = self.validation_rules.write().unwrap();
        rules.entry(function_name).or_default().push(rule);
    }

    /// Validate a function call before execution
    pub fn validate_function_call(
        &self,
        function_name: &str,
        args: &[Value],
        function_ptr: *const u8,
    ) -> SafetyResult<()> {
        let config = self.config.read().unwrap();

        // Update statistics
        {
            let mut stats = self.stats.write().unwrap();
            stats.total_validations += 1;
        }

        // Stack overflow protection
        if config.stack_overflow_protection {
            let mut depth = self.stack_depth.write().unwrap();
            if *depth >= config.max_stack_depth {
                let mut stats = self.stats.write().unwrap();
                stats.stack_overflow_prevented += 1;
                return Err(Box::new(SafetyError::StackOverflow {
                    current_depth: *depth,
                    max_depth: config.max_stack_depth,
                }));
            }
            *depth += 1;
        }

        // Function pointer validation
        if config.function_pointer_validation && function_ptr.is_null() {
            return Err(Box::new(SafetyError::InvalidFunctionPointer {
                function: function_name.to_string(),
                pointer: function_ptr,
            }));
        }

        // Get function signature
        let signature = {
            let signatures = self.signatures.read().unwrap();
            signatures.get(function_name).cloned()
        };

        if let Some(sig) = signature {
            // Runtime type checking
            if config.runtime_type_checking {
                self.validate_parameter_types(&sig, args, function_name)?;
            }

            // Constraint validation
            self.validate_constraints(&sig, args, function_name)?;

            // Custom validation rules
            self.apply_validation_rules(function_name, args, ValidationTrigger::PreCall)?;
        }

        // Update success statistics
        {
            let mut stats = self.stats.write().unwrap();
            stats.successful_validations += 1;
        }

        Ok(())
    }

    /// Validate function call completion
    pub fn validate_function_completion(
        &self,
        function_name: &str,
        return_value: &Value,
    ) -> SafetyResult<()> {
        let config = self.config.read().unwrap();

        // Decrement stack depth
        if config.stack_overflow_protection {
            let mut depth = self.stack_depth.write().unwrap();
            if *depth > 0 {
                *depth -= 1;
            }
        }

        // Validate return value type
        if let Some(signature) = self.get_function_signature(function_name) {
            if config.runtime_type_checking {
                self.validate_return_type(&signature, return_value, function_name)?;
            }

            // Apply post-call validation rules
            self.apply_validation_rules(function_name, &[], ValidationTrigger::PostCall)?;
        }

        Ok(())
    }

    /// Validate parameter types
    fn validate_parameter_types(
        &self,
        signature: &FunctionSignature,
        args: &[Value],
        function_name: &str,
    ) -> SafetyResult<()> {
        // Check parameter count
        if !signature.variadic && args.len() != signature.parameters.len() {
            return Err(Box::new(SafetyError::SignatureMismatch {
                function: function_name.to_string(),
                expected: signature.clone(),
                actual: Box::new(FunctionSignature {
                    name: function_name.to_string(),
                    parameters: args.iter().map(|_| CType::Void).collect(), // Simplified
                    return_type: CType::Void,
                    variadic: false,
                    safe: false,
                    constraints: vec![],
                }),
            }));
        }

        // Validate each parameter
        for (i, (arg, expected_type)) in args.iter().zip(signature.parameters.iter()).enumerate() {
            if !self.is_value_compatible_with_type(arg, expected_type) {
                return Err(Box::new(SafetyError::RuntimeTypeCheck {
                    parameter: i,
                    expected: expected_type.clone(),
                    actual_value: format!("{arg:?}"),
                }));
            }
        }

        Ok(())
    }

    /// Validate return type
    fn validate_return_type(
        &self,
        signature: &FunctionSignature,
        return_value: &Value,
        _function_name: &str,
    ) -> SafetyResult<()> {
        if !self.is_value_compatible_with_type(return_value, &signature.return_type) {
            return Err(Box::new(SafetyError::RuntimeTypeCheck {
                parameter: 0, // Return value
                expected: signature.return_type.clone(),
                actual_value: format!("{return_value:?}"),
            }));
        }

        Ok(())
    }

    /// Check if a value is compatible with a C type
    fn is_value_compatible_with_type(&self, value: &Value, c_type: &CType) -> bool {
        match (value, c_type) {
            (Value::Literal(literal), t) if literal.is_number() && t.is_numeric() => true,
            (Value::Literal(literal), CType::Float | CType::Double) if literal.is_number() => true,
            (Value::Literal(Literal::Boolean(_)), CType::Bool) => true,
            (Value::Literal(Literal::String(_)), CType::CString) => true,
            (Value::Literal(Literal::Character(_)), CType::Char) => true,
            (Value::Nil, t) if t.is_pointer() => true,
            _ => false,
        }
    }

    /// Validate type constraints
    fn validate_constraints(
        &self,
        signature: &FunctionSignature,
        args: &[Value],
        function_name: &str,
    ) -> SafetyResult<()> {
        let config = self.config.read().unwrap();

        for constraint in &signature.constraints {
            match constraint {
                TypeConstraint::NonNull(param_idx) => {
                    if config.null_pointer_checking && *param_idx < args.len()
                        && matches!(args[*param_idx], Value::Nil) {
                            let mut stats = self.stats.write().unwrap();
                            stats.null_pointer_violations += 1;
                            return Err(Box::new(SafetyError::NullPointerDereference {
                                parameter: *param_idx,
                                context: function_name.to_string(),
                            }));
                        }
                }
                TypeConstraint::Bounds { parameter, min, max } => {
                    if config.bounds_checking && *parameter < args.len() {
                        if let Value::Literal(literal) = &args[*parameter] {
                            if let Some(val) = literal.to_f64() {
                                if val < (*min as f64) || val > (*max as f64) {
                                    let mut stats = self.stats.write().unwrap();
                                    stats.bounds_violations += 1;
                                    return Err(Box::new(SafetyError::BoundaryViolation {
                                        operation: format!("parameter {parameter} bounds check"),
                                        description: format!("value {val} not in range [{min}..{max}]"),
                                    }));
                                }
                            }
                        }
                    }
                }
                TypeConstraint::BufferWithSize { buffer_param, size_param } => {
                    if config.buffer_overflow_protection && 
                       *buffer_param < args.len() && *size_param < args.len() {
                        // This would require more complex validation in practice
                        // For now, just check that both parameters are present
                        if matches!(args[*buffer_param], Value::Nil) {
                            let mut stats = self.stats.write().unwrap();
                            stats.buffer_overflow_prevented += 1;
                            return Err(Box::new(SafetyError::NullPointerDereference {
                                parameter: *buffer_param,
                                context: "buffer parameter".to_string(),
                            }));
                        }
                    }
                }
                _ => {
                    // Other constraints would be implemented here
                }
            }
        }

        Ok(())
    }

    /// Apply validation rules
    fn apply_validation_rules(
        &self,
        function_name: &str,
        args: &[Value],
        trigger: ValidationTrigger,
    ) -> SafetyResult<()> {
        let rules = self.validation_rules.read().unwrap();
        if let Some(function_rules) = rules.get(function_name) {
            for rule in function_rules {
                if rule.enabled && self.matches_trigger(&rule.trigger, &trigger) {
                    self.apply_single_validation_rule(rule, args, function_name)?;
                }
            }
        }

        Ok(())
    }

    /// Check if a trigger matches
    fn matches_trigger(&self, rule_trigger: &ValidationTrigger, actual_trigger: &ValidationTrigger) -> bool {
        match (rule_trigger, actual_trigger) {
            (ValidationTrigger::PreCall, ValidationTrigger::PreCall) => true,
            (ValidationTrigger::PostCall, ValidationTrigger::PostCall) => true,
            (ValidationTrigger::ParameterConversion(a), ValidationTrigger::ParameterConversion(b)) => a == b,
            (ValidationTrigger::ReturnConversion, ValidationTrigger::ReturnConversion) => true,
            (ValidationTrigger::Custom(a), ValidationTrigger::Custom(b)) => a == b,
            _ => false,
        }
    }

    /// Apply a single validation rule
    fn apply_single_validation_rule(
        &self,
        rule: &ValidationRule,
        args: &[Value],
        function_name: &str,
    ) -> SafetyResult<()> {
        match &rule.validator {
            ValidationFunction::NullPointerCheck => {
                for (i, arg) in args.iter().enumerate() {
                    if matches!(arg, Value::Nil) {
                        return Err(Box::new(SafetyError::NullPointerDereference {
                            parameter: i,
                            context: rule.name.clone(),
                        }));
                    }
                }
            }
            ValidationFunction::BoundsCheck { min, max } => {
                for (i, arg) in args.iter().enumerate() {
                    let val = match arg {
                        Value::Literal(Literal::ExactInteger(val)) => *val as f64,
                        Value::Literal(Literal::InexactReal(val)) => *val,
                        _ => continue,
                    };
                    if val < (*min as f64) || val > (*max as f64) {
                        return Err(Box::new(SafetyError::BoundaryViolation {
                            operation: rule.name.clone(),
                            description: format!("value {val} not in range [{min}..{max}]"),
                        }));
                    }
                }
            }
            ValidationFunction::StringValidation => {
                // Validate string parameters
                for (i, arg) in args.iter().enumerate() {
                    if let Value::Literal(Literal::String(s)) = arg {
                        if s.contains('\0') && !s.ends_with('\0') {
                            return Err(Box::new(SafetyError::BoundaryViolation {
                                operation: "string validation".to_string(),
                                description: "string contains null character but is not null-terminated".to_string(),
                            }));
                        }
                    }
                }
            }
            _ => {
                // Other validation functions would be implemented here
            }
        }

        Ok(())
    }

    /// Get a function signature
    pub fn get_function_signature(&self, function_name: &str) -> Option<FunctionSignature> {
        let signatures = self.signatures.read().unwrap();
        signatures.get(function_name).cloned()
    }

    /// List all registered functions
    pub fn list_registered_functions(&self) -> Vec<String> {
        let signatures = self.signatures.read().unwrap();
        signatures.keys().cloned().collect()
    }

    /// Get safety statistics
    pub fn stats(&self) -> SafetyStats {
        self.stats.read().unwrap().clone()
    }

    /// Clear all registrations
    pub fn clear(&self) {
        let mut signatures = self.signatures.write().unwrap();
        signatures.clear();
        
        let mut rules = self.validation_rules.write().unwrap();
        rules.clear();
    }
}

/// Stack depth guard for automatic cleanup
pub struct StackDepthGuard {
    validator: Arc<TypeSafetyValidator>,
}

impl StackDepthGuard {
    pub fn new(validator: Arc<TypeSafetyValidator>) -> Self {
        Self { validator }
    }
}

impl Drop for StackDepthGuard {
    fn drop(&mut self) {
        let mut depth = self.validator.stack_depth.write().unwrap();
        if *depth > 0 {
            *depth -= 1;
        }
    }
}

lazy_static::lazy_static! {
    /// Global type safety validator instance
    pub static ref GLOBAL_TYPE_SAFETY_VALIDATOR: TypeSafetyValidator = TypeSafetyValidator::new();
}

/// Convenience functions for global validator
pub fn register_function_signature(signature: FunctionSignature) -> SafetyResult<()> {
    GLOBAL_TYPE_SAFETY_VALIDATOR.register_function_signature(signature)
}

pub fn validate_function_call(
    function_name: &str,
    args: &[Value],
    function_ptr: *const u8,
) -> SafetyResult<()> {
    GLOBAL_TYPE_SAFETY_VALIDATOR.validate_function_call(function_name, args, function_ptr)
}

pub fn validate_function_completion(
    function_name: &str,
    return_value: &Value,
) -> SafetyResult<()> {
    GLOBAL_TYPE_SAFETY_VALIDATOR.validate_function_completion(function_name, return_value)
}

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

    #[test]
    fn test_validator_creation() {
        let validator = TypeSafetyValidator::new();
        let stats = validator.stats();
        assert_eq!(stats.total_validations, 0);
    }

    #[test]
    fn test_function_signature_registration() {
        let validator = TypeSafetyValidator::new();
        let signature = FunctionSignature {
            name: "test_function".to_string(),
            parameters: vec![CType::CInt, CType::CString],
            return_type: CType::CInt,
            variadic: false,
            safe: true,
            constraints: vec![TypeConstraint::NonNull(1)],
        };

        validator.register_function_signature(signature.clone()).unwrap();
        
        let retrieved = validator.get_function_signature("test_function").unwrap();
        assert_eq!(retrieved.name, "test_function");
        assert_eq!(retrieved.parameters.len(), 2);
    }

    #[test]
    fn test_parameter_type_validation() {
        let validator = TypeSafetyValidator::new();
        let signature = FunctionSignature {
            name: "test_function".to_string(),
            parameters: vec![CType::CInt],
            return_type: CType::CInt,
            variadic: false,
            safe: true,
            constraints: vec![],
        };

        validator.register_function_signature(signature).unwrap();

        // Valid call
        let args = vec![Value::Literal(Literal::Number(42.0))];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(result.is_ok());

        // Invalid call - wrong type
        let args = vec![Value::Literal(Literal::String("hello".to_string()))];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(matches!(result, Err(ref err) if matches!(**err, SafetyError::RuntimeTypeCheck { .. })));
    }

    #[test]
    fn test_null_pointer_constraint() {
        let validator = TypeSafetyValidator::new();
        let signature = FunctionSignature {
            name: "test_function".to_string(),
            parameters: vec![CType::CString],
            return_type: CType::CInt,
            variadic: false,
            safe: true,
            constraints: vec![TypeConstraint::NonNull(0)],
        };

        validator.register_function_signature(signature).unwrap();

        // Valid call
        let args = vec![Value::Literal(Literal::String("hello".to_string()))];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(result.is_ok());

        // Invalid call - null pointer
        let args = vec![Value::Nil];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(matches!(result, Err(ref err) if matches!(**err, SafetyError::NullPointerDereference { .. })));
    }

    #[test]
    fn test_bounds_constraint() {
        let validator = TypeSafetyValidator::new();
        let signature = FunctionSignature {
            name: "test_function".to_string(),
            parameters: vec![CType::CInt],
            return_type: CType::CInt,
            variadic: false,
            safe: true,
            constraints: vec![TypeConstraint::Bounds {
                parameter: 0,
                min: 0,
                max: 100,
            }],
        };

        validator.register_function_signature(signature).unwrap();

        // Valid call
        let args = vec![Value::Literal(Literal::Number(50.0))];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(result.is_ok());

        // Invalid call - out of bounds
        let args = vec![Value::Literal(Literal::Number(150.0))];
        let result = validator.validate_function_call("test_function", &args, ptr::null());
        assert!(matches!(result, Err(ref err) if matches!(**err, SafetyError::BoundaryViolation { .. })));
    }

    #[test]
    fn test_validation_rules() {
        let validator = TypeSafetyValidator::new();
        
        let rule = ValidationRule {
            name: "null_check".to_string(),
            trigger: ValidationTrigger::PreCall,
            validator: ValidationFunction::NullPointerCheck,
            enabled: true,
        };

        validator.add_validation_rule("test_function".to_string(), rule);

        // This would fail with null check
        let args = vec![Value::Nil];
        let result = validator.apply_validation_rules("test_function", &args, ValidationTrigger::PreCall);
        assert!(matches!(result, Err(ref err) if matches!(**err, SafetyError::NullPointerDereference { .. })));
    }
}