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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Runtime reflection and introspection system.
//!
//! This module provides comprehensive reflection capabilities for Lambdust,
//! allowing programs to inspect types, metadata, environments, and execution
//! context at runtime.

use crate::eval::{Value, Environment, StackTrace, StackFrame, PrimitiveProcedure};
use crate::ast::{Formals, Literal};
use crate::diagnostics::{Error, Result, Span};
use std::collections::HashMap;
use std::sync::Arc;
use std::rc::Rc;

/// Detailed type information for runtime values.
#[derive(Debug, Clone, PartialEq)]
pub enum TypeInfo {
    /// Primitive types
    /// Boolean value type
    Boolean,
    /// Numeric value type
    Number,
    /// String value type
    String,
    /// Character value type
    Character,
    /// Bytevector value type
    Bytevector,
    /// Symbol value type
    Symbol,
    /// Keyword value type
    Keyword,
    /// Null/nil value type
    Nil,
    /// Unspecified value type
    Unspecified,
    
    /// Compound types
    /// Pair/cons cell type
    Pair,
    /// Vector container type
    Vector,
    /// Hash table type
    Hashtable,
    
    /// Advanced container types
    /// Advanced hash table with extended features
    AdvancedHashTable,
    /// Double-ended queue (ideque) type
    Ideque,
    /// Priority queue type
    PriorityQueue,
    /// Ordered set type
    OrderedSet,
    /// List-based queue type
    ListQueue,
    /// Random access list type
    RandomAccessList,
    /// Set type  
    Set,
    /// Bag (multiset) type
    Bag,
    /// Generator type (SRFI-121)
    Generator,
    
    /// Procedure types
    /// User-defined procedure type
    Procedure {
        /// Procedure arity information
        arity: ArityInfo,
        /// Optional procedure name
        name: Option<String>
    },
    /// Case-lambda procedure type
    CaseLambda {
        /// Available clause arities
        clauses: Vec<ArityInfo>
    },
    /// Built-in primitive procedure type
    Primitive {
        /// Primitive procedure name
        name: String,
        /// Primitive arity information
        arity: ArityInfo
    },
    /// Continuation type
    Continuation {
        /// Continuation identifier
        id: String
    },
    /// Syntax/macro type
    Syntax {
        /// Optional syntax name
        name: Option<String>
    },
    
    /// Advanced types
    /// I/O port type
    Port {
        /// Port operation mode
        mode: String,
        /// Port direction (input/output)
        direction: String
    },
    /// Promise/delay type
    Promise {
        /// Whether promise has been forced
        forced: bool
    },
    /// Type object type
    Type {
        /// Type name
        type_name: String
    },
    /// Foreign/external type
    Foreign {
        /// Foreign type name
        type_name: String
    },
    /// Error object type
    ErrorObject {
        /// Error category
        category: String
    },
    /// Character set type
    CharSet,
    /// Parameter object type
    Parameter {
        /// Optional parameter name
        name: Option<String>
    },
    /// Record type
    Record {
        /// Record type name
        type_name: String
    },
    
    /// Concurrency types
    /// Future/async computation type
    Future {
        /// Future execution status
        status: String
    },
    /// Communication channel type
    Channel {
        /// Optional channel capacity
        capacity: Option<usize>
    },
    /// Mutual exclusion lock type
    Mutex {
        /// Whether mutex is currently locked
        locked: bool
    },
    /// Semaphore synchronization type
    Semaphore {
        /// Available permits
        permits: usize
    },
    /// Atomic counter type
    AtomicCounter {
        /// Current counter value
        value: i64
    },
    /// Distributed computing node type
    DistributedNode {
        /// Node identifier
        node_id: String
    },
    /// Opaque/black-box type
    Opaque {
        /// Opaque type name
        type_name: String
    },
}

/// Arity information for procedures.
#[derive(Debug, Clone, PartialEq)]
pub enum ArityInfo {
    /// Fixed arity (exact number of arguments)
    Fixed(usize),
    /// Variable arity (minimum arguments + rest)
    Variable { 
        /// Minimum number of required arguments.
        min: usize, 
        /// Whether there is a rest parameter.
        rest: bool 
    },
    /// Case-lambda style (multiple possible arities)
    Multiple(Vec<ArityInfo>),
}

/// Metadata information for runtime values.
#[derive(Debug, Clone)]
pub struct MetadataInfo {
    /// Source location if available
    pub source: Option<Span>,
    /// Documentation string
    pub documentation: Option<String>,
    /// Custom metadata fields
    pub fields: HashMap<String, Value>,
    /// Creation timestamp
    pub created_at: std::time::SystemTime,
    /// Type annotations
    pub type_annotations: Vec<String>,
}

/// Environment inspection information.
#[derive(Debug, Clone)]
pub struct EnvironmentInfo {
    /// Bound variables and their values
    pub bindings: HashMap<String, Value>,
    /// Parent environment (if any)
    pub parent: Option<Rc<Environment>>,
    /// Generation number
    pub generation: u64,
    /// Environment type (global, local, macro, etc.)
    pub env_type: EnvironmentType,
    /// Creation context
    pub creation_context: Option<String>,
}

/// Classification of different environment contexts in the runtime system.
/// 
/// Different environment types provide varying levels of access and security
/// for executing code in different contexts.
#[derive(Debug, Clone, PartialEq)]
pub enum EnvironmentType {
    /// Global environment scope
    Global,
    /// Local environment scope
    Local,
    /// Macro expansion environment
    Macro,
    /// Module-level environment
    Module,
    /// Dynamic environment for parameter objects
    Dynamic,
    /// Sandboxed environment for security
    Sandbox,
}

/// Detailed information about a single stack frame during execution.
/// 
/// Provides debugging and introspection capabilities by capturing
/// procedure context, bindings, and call information.
#[derive(Debug, Clone)]
pub struct FrameInfo {
    /// Procedure name (if available)
    pub procedure_name: Option<String>,
    /// Source location
    pub location: Option<Span>,
    /// Local bindings at this frame
    pub local_bindings: HashMap<String, Value>,
    /// Frame type
    pub frame_type: String,
    /// Call arguments (if available)
    pub arguments: Option<Vec<Value>>,
}

/// Runtime object introspection and analysis utility.
/// 
/// Provides caching and efficient inspection of runtime values,
/// including type analysis and metadata extraction.
#[derive(Debug, Default)]
pub struct ObjectInspector {
    /// Cache for type information
    type_cache: HashMap<*const Value, TypeInfo>,
    /// Cache for metadata
    metadata_cache: HashMap<*const Value, MetadataInfo>,
}

impl ObjectInspector {
    /// Creates a new object inspector.
    pub fn new() -> Self {
        Self {
            type_cache: HashMap::new(),
            metadata_cache: HashMap::new(),
        }
    }

    /// Gets detailed type information for a value.
    pub fn get_type_info(&mut self, value: &Value) -> TypeInfo {
        // Check cache first
        let ptr = value as *const Value;
        if let Some(cached) = self.type_cache.get(&ptr) {
            return cached.clone();
        }

        let type_info = match value {
            Value::Literal(Literal::Boolean(_)) => TypeInfo::Boolean,
            Value::Literal(Literal::ExactInteger(_)) | Value::Literal(Literal::InexactReal(_)) | Value::Literal(Literal::Number(_)) => TypeInfo::Number,
            Value::Literal(Literal::Rational { .. }) => TypeInfo::Number,
            Value::Literal(Literal::Complex { .. }) => TypeInfo::Number,
            Value::Literal(Literal::String(_)) => TypeInfo::String,
            Value::Literal(Literal::Character(_)) => TypeInfo::Character,
            Value::Literal(Literal::Bytevector(_)) => TypeInfo::Bytevector,
            Value::Literal(Literal::Nil) => TypeInfo::Nil,
            Value::Literal(Literal::Unspecified) => TypeInfo::Unspecified,
            Value::Symbol(_) => TypeInfo::Symbol,
            Value::Keyword(_) => TypeInfo::Keyword,
            Value::Nil => TypeInfo::Nil,
            Value::Unspecified => TypeInfo::Unspecified,
            Value::Pair(_, _) => TypeInfo::Pair,
            Value::MutablePair(_, _) => TypeInfo::Pair,
            Value::Vector(_) => TypeInfo::Vector,
            Value::Hashtable(_) => TypeInfo::Hashtable,
            Value::AdvancedHashTable(_) => TypeInfo::AdvancedHashTable,
            Value::Ideque(_) => TypeInfo::Ideque,
            Value::PriorityQueue(_) => TypeInfo::PriorityQueue,
            Value::OrderedSet(_) => TypeInfo::OrderedSet,
            Value::ListQueue(_) => TypeInfo::ListQueue,
            Value::RandomAccessList(_) => TypeInfo::RandomAccessList,
            
            Value::Procedure(proc) => {
                let arity = self.analyze_formals(&proc.formals);
                TypeInfo::Procedure {
                    arity,
                    name: proc.name.clone(),
                }
            }
            
            Value::CaseLambda(case_lambda) => {
                let clauses = case_lambda.clauses.iter()
                    .map(|clause| self.analyze_formals(&clause.formals))
                    .collect();
                TypeInfo::CaseLambda { clauses }
            }
            
            Value::Primitive(prim) => {
                let arity = self.analyze_primitive_arity(&prim.name);
                TypeInfo::Primitive {
                    name: prim.name.clone(),
                    arity,
                }
            }
            
            Value::Continuation(cont) => {
                TypeInfo::Continuation {
                    id: format!("cont-{}", cont.id),
                }
            }
            
            Value::Syntax(_syntax) => {
                TypeInfo::Syntax {
                    name: None, // Placeholder - would extract actual name
                }
            }
            
            Value::Port(port) => {
                TypeInfo::Port {
                    mode: format!("{:?}", port.mode),
                    direction: format!("{:?}", port.direction),
                }
            }
            
            Value::Promise(_promise) => {
                let forced = false; // Placeholder - would check actual forced state
                TypeInfo::Promise { forced }
            }
            
            Value::Type(_type_val) => {
                TypeInfo::Type {
                    type_name: "type".to_string(), // Placeholder - would extract actual type name
                }
            }
            
            Value::Foreign(_foreign) => {
                TypeInfo::Foreign {
                    type_name: "foreign".to_string(), // Placeholder - would extract actual type name
                }
            }
            
            Value::ErrorObject(_error) => {
                TypeInfo::ErrorObject {
                    category: "error".to_string(), // Placeholder - would extract actual category
                }
            }
            
            Value::CharSet(_) => TypeInfo::CharSet,
            
            Value::Parameter(_param) => {
                TypeInfo::Parameter {
                    name: None, // Placeholder - would extract actual parameter name
                }
            }
            
            Value::Record(_record) => {
                TypeInfo::Record {
                    type_name: "record".to_string(), // Placeholder - would extract actual type name
                }
            }
            
            // Concurrency types (only available with async-runtime)
            #[cfg(feature = "async-runtime")]
            Value::Future(_future) => {
                TypeInfo::Future {
                    status: "pending".to_string(), // Placeholder - would check actual status
                }
            }
            
            #[cfg(feature = "async-runtime")]
            Value::Channel(_channel) => {
                TypeInfo::Channel {
                    capacity: None, // Placeholder - would extract actual capacity
                }
            }
            
            #[cfg(feature = "async-runtime")]
            Value::Mutex(_mutex) => {
                TypeInfo::Mutex {
                    locked: false, // Placeholder - would check actual state
                }
            }
            
            #[cfg(feature = "async-runtime")]
            Value::Semaphore(_semaphore) => {
                TypeInfo::Semaphore {
                    permits: 0, // Placeholder - would extract actual permits
                }
            }
            
            #[cfg(feature = "async-runtime")]
            Value::AtomicCounter(_counter) => {
                TypeInfo::AtomicCounter {
                    value: 0, // Placeholder - would extract actual value
                }
            }
            
            #[cfg(feature = "async-runtime")]
            Value::DistributedNode(_node) => {
                TypeInfo::DistributedNode {
                    node_id: "unknown".to_string(), // Placeholder - would extract actual node ID
                }
            }
            
            Value::MutableString(_) => TypeInfo::String,

            Value::Set(_) => TypeInfo::Set,

            Value::Bag(_) => TypeInfo::Bag,

            Value::Generator(_) => TypeInfo::Generator,

            Value::Opaque(_opaque) => {
                TypeInfo::Opaque {
                    type_name: "opaque".to_string(), // Placeholder - would extract actual type name
                }
            }
        };

        // Cache the result
        self.type_cache.insert(ptr, type_info.clone());
        type_info
    }

    /// Gets metadata information for a value.
    pub fn get_metadata_info(&mut self, value: &Value) -> MetadataInfo {
        let ptr = value as *const Value;
        if let Some(cached) = self.metadata_cache.get(&ptr) {
            return cached.clone();
        }

        let metadata = match value {
            Value::Procedure(proc) => MetadataInfo {
                source: proc.source,
                documentation: proc.metadata.get("doc").and_then(|v| v.as_string().map(|s| s.to_string())),
                fields: proc.metadata.clone(),
                created_at: std::time::SystemTime::now(), // Would be better to track actual creation time
                type_annotations: vec!["procedure".to_string()],
            },
            
            Value::CaseLambda(case_lambda) => MetadataInfo {
                source: case_lambda.source,
                documentation: case_lambda.metadata.get("doc").and_then(|v| v.as_string().map(|s| s.to_string())),
                fields: case_lambda.metadata.clone(),
                created_at: std::time::SystemTime::now(),
                type_annotations: vec!["case-lambda".to_string()],
            },
            
            Value::Primitive(_prim) => MetadataInfo {
                source: None,
                documentation: None, // Placeholder - would extract from actual primitive
                fields: HashMap::new(),
                created_at: std::time::SystemTime::now(),
                type_annotations: vec!["primitive".to_string()],
            },
            
            _ => MetadataInfo {
                source: None,
                documentation: None,
                fields: HashMap::new(),
                created_at: std::time::SystemTime::now(),
                type_annotations: vec![],
            },
        };

        self.metadata_cache.insert(ptr, metadata.clone());
        metadata
    }

    /// Analyzes formals to determine arity.
    fn analyze_formals(&self, formals: &Formals) -> ArityInfo {
        match formals {
            Formals::Fixed(params) => ArityInfo::Fixed(params.len()),
            Formals::Variable(_) => ArityInfo::Variable { min: 0, rest: true },
            Formals::Mixed { fixed, .. } => ArityInfo::Variable {
                min: fixed.len(),
                rest: true,
            },
            Formals::Keyword { fixed, .. } => ArityInfo::Variable {
                min: fixed.len(),
                rest: true,
            },
        }
    }

    /// Analyzes primitive arity (simplified - would need actual primitive info).
    fn analyze_primitive_arity(&self, name: &str) -> ArityInfo {
        match name {
            "+" | "*" | "and" | "or" => ArityInfo::Variable { min: 0, rest: true },
            "-" | "/" => ArityInfo::Variable { min: 1, rest: true },
            "=" | "<" | ">" | "<=" | ">=" => ArityInfo::Variable { min: 2, rest: true },
            "cons" => ArityInfo::Fixed(2),
            "car" | "cdr" | "not" | "null?" | "pair?" => ArityInfo::Fixed(1),
            "if" => ArityInfo::Variable { min: 2, rest: false }, // Special form, but for analysis
            _ => ArityInfo::Variable { min: 0, rest: true }, // Unknown arity
        }
    }
}

/// Dynamic type inspection and hierarchy management system.
/// 
/// Provides runtime type checking, subtype relationships, and
/// type coercion capabilities for the reflection system.
#[derive(Debug, Default)]
pub struct TypeInspector {
    /// Type hierarchy cache
    type_hierarchy: HashMap<String, Vec<String>>,
}

impl TypeInspector {
    /// Creates a new type inspector.
    pub fn new() -> Self {
        let mut type_hierarchy = HashMap::new();
        
        // Initialize basic type hierarchy
        type_hierarchy.insert("value".to_string(), vec![]);
        type_hierarchy.insert("number".to_string(), vec!["value".to_string()]);
        type_hierarchy.insert("string".to_string(), vec!["value".to_string()]);
        type_hierarchy.insert("symbol".to_string(), vec!["value".to_string()]);
        type_hierarchy.insert("pair".to_string(), vec!["value".to_string()]);
        type_hierarchy.insert("procedure".to_string(), vec!["value".to_string()]);
        
        Self { type_hierarchy }
    }

    /// Checks if a value matches a type predicate.
    pub fn type_matches(&self, value: &Value, type_name: &str) -> bool {
        let actual_type = self.get_type_name(value);
        self.is_subtype(&actual_type, type_name)
    }

    /// Gets the type name for a value.
    pub fn get_type_name(&self, value: &Value) -> String {
        match value {
            Value::Literal(Literal::Boolean(_)) => "boolean".to_string(),
            Value::Literal(Literal::ExactInteger(_)) | Value::Literal(Literal::InexactReal(_)) => "number".to_string(),
            Value::Literal(Literal::String(_)) => "string".to_string(),
            Value::Literal(Literal::Character(_)) => "character".to_string(),
            Value::Symbol(_) => "symbol".to_string(),
            Value::Keyword(_) => "keyword".to_string(),
            Value::Nil => "null".to_string(),
            Value::Pair(_, _) => "pair".to_string(),
            Value::Vector(_) => "vector".to_string(),
            Value::Procedure(_) => "procedure".to_string(),
            Value::CaseLambda(_) => "case-lambda".to_string(),
            Value::Primitive(_) => "primitive".to_string(),
            Value::Port(_) => "port".to_string(),
            _ => "value".to_string(),
        }
    }

    /// Checks if one type is a subtype of another.
    pub fn is_subtype(&self, subtype: &str, supertype: &str) -> bool {
        if subtype == supertype {
            return true;
        }
        
        if let Some(parents) = self.type_hierarchy.get(subtype) {
            for parent in parents {
                if self.is_subtype(parent, supertype) {
                    return true;
                }
            }
        }
        
        false
    }

    /// Attempts to cast a value to a specific type.
    pub fn try_cast(&self, value: &Value, target_type: &str) -> Result<Value> {
        if self.type_matches(value, target_type) {
            return Ok(value.clone());
        }

        // Attempt automatic conversions
        match (value, target_type) {
            (Value::Literal(Literal::ExactInteger(n)), "string") => {
                Ok(Value::string(n.to_string()))
            }
            (Value::Literal(Literal::InexactReal(n)), "string") => {
                Ok(Value::string(n.to_string()))
            }
            (Value::Literal(Literal::String(s)), "number") => {
                if let Ok(n) = s.parse::<f64>() {
                    Ok(Value::number(n))
                } else {
                    Err(Box::new(Error::runtime_error(
                        format!("Cannot cast string '{s}' to number"),
                        None,
                    )))
                }
            }
            (Value::Symbol(sym), "string") => {
                match crate::utils::symbol_name(*sym) {
                    Some(name) => Ok(Value::string(name)),
                    None => Ok(Value::string(format!("symbol-{}", sym.0))),
                }
            }
            _ => Err(Box::new(Error::runtime_error(
                format!("Cannot cast {} to {}", self.get_type_name(value), target_type),
                None,
            ))),
        }
    }
}

/// Global metadata storage and access system for runtime objects.
/// 
/// Provides persistent metadata attachment and retrieval for values
/// across their lifetime in the runtime system.
#[derive(Debug)]
pub struct MetadataAccess {
    /// Global metadata store
    metadata_store: HashMap<String, HashMap<String, Value>>,
}

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

impl MetadataAccess {
    /// Creates a new metadata access system.
    pub fn new() -> Self {
        Self {
            metadata_store: HashMap::new(),
        }
    }

    /// Gets metadata for an object by key.
    pub fn get_metadata(&self, object_id: &str, key: &str) -> Option<&Value> {
        self.metadata_store.get(object_id)?.get(key)
    }

    /// Sets metadata for an object.
    pub fn set_metadata(&mut self, object_id: String, key: String, value: Value) {
        self.metadata_store
            .entry(object_id)
            .or_default()
            .insert(key, value);
    }

    /// Gets all metadata for an object.
    pub fn get_all_metadata(&self, object_id: &str) -> Option<&HashMap<String, Value>> {
        self.metadata_store.get(object_id)
    }

    /// Removes metadata for an object.
    pub fn remove_metadata(&mut self, object_id: &str, key: &str) -> Option<Value> {
        self.metadata_store.get_mut(object_id)?.remove(key)
    }
}

/// Comprehensive reflection and introspection system.
/// 
/// Integrates all reflection capabilities including object inspection,
/// type analysis, and metadata access for complete runtime introspection.
#[derive(Debug)]
pub struct ReflectionSystem {
    /// Object inspector
    object_inspector: ObjectInspector,
    /// Type inspector
    type_inspector: TypeInspector,
    /// Metadata access
    metadata_access: MetadataAccess,
    /// Type cache for performance
    pub type_cache: HashMap<String, TypeInfo>,
}

impl ReflectionSystem {
    /// Creates a new reflection system.
    pub fn new() -> Self {
        Self {
            object_inspector: ObjectInspector::new(),
            type_inspector: TypeInspector::new(),
            metadata_access: MetadataAccess::new(),
            type_cache: HashMap::new(),
        }
    }

    /// Gets a mutable reference to the object inspector.
    pub fn object_inspector(&mut self) -> &mut ObjectInspector {
        &mut self.object_inspector
    }

    /// Inspects a value and returns detailed information.
    pub fn inspect_value(&mut self, value: &Value) -> ValueInspection {
        ValueInspection {
            type_info: self.object_inspector.get_type_info(value),
            metadata: self.object_inspector.get_metadata_info(value),
            type_name: self.type_inspector.get_type_name(value),
        }
    }

    /// Inspects an environment.
    pub fn inspect_environment(&self, env: &Environment) -> EnvironmentInfo {
        EnvironmentInfo {
            bindings: env.bindings.borrow().clone(),
            parent: env.parent.clone(),
            generation: env.generation,
            env_type: self.classify_environment(env),
            creation_context: None, // Would need to track this during environment creation
        }
    }

    /// Inspects a stack trace.
    pub fn inspect_stack_trace(&self, stack_trace: &StackTrace) -> Vec<FrameInfo> {
        stack_trace.frames.iter().map(|frame| {
            self.inspect_frame(frame)
        }).collect()
    }

    /// Inspects a single stack frame.
    pub fn inspect_frame(&self, frame: &StackFrame) -> FrameInfo {
        FrameInfo {
            procedure_name: frame.name.clone(),
            location: frame.location,
            local_bindings: HashMap::new(), // Would need access to frame's environment
            frame_type: format!("{:?}", frame.frame_type),
            arguments: Some(Vec::new()), // StackFrame doesn't store arguments
        }
    }

    /// Classifies an environment type.
    fn classify_environment(&self, env: &Environment) -> EnvironmentType {
        // This is a simplified classification - would need more context
        if env.parent.is_none() {
            EnvironmentType::Global
        } else {
            EnvironmentType::Local
        }
    }

    /// Installs reflection primitives into an environment.
    pub fn install_primitives(&self, env: &Rc<Environment>) -> Result<()> {
        // Type inspection primitives
        env.define("type-of".to_string(), Value::Primitive(Arc::new(
            PrimitiveProcedure {
                name: "type-of".to_string(),
                arity_min: 1,
                arity_max: Some(1),
                implementation: crate::eval::PrimitiveImpl::Native(primitive_type_of),
                effects: vec![],
            }
        )));

        env.define("type-name".to_string(), Value::Primitive(Arc::new(
            PrimitiveProcedure {
                name: "type-name".to_string(),
                implementation: crate::eval::PrimitiveImpl::Native(primitive_type_name),
                arity_min: 1,
                arity_max: Some(1),
                effects: vec![],
            }
        )));

        // Metadata access primitives
        env.define("get-metadata".to_string(), Value::Primitive(Arc::new(
            PrimitiveProcedure {
                name: "get-metadata".to_string(),
                implementation: crate::eval::PrimitiveImpl::Native(primitive_get_metadata),
                arity_min: 2,
                arity_max: Some(2),
                effects: vec![],
            }
        )));

        // Environment inspection primitives
        env.define("environment-bindings".to_string(), Value::Primitive(Arc::new(
            PrimitiveProcedure {
                name: "environment-bindings".to_string(),
                implementation: crate::eval::PrimitiveImpl::Native(primitive_environment_bindings),
                arity_min: 1,
                arity_max: Some(1),
                effects: vec![],
            }
        )));

        // Stack trace primitives
        env.define("current-stack-trace".to_string(), Value::Primitive(Arc::new(
            PrimitiveProcedure {
                name: "current-stack-trace".to_string(),
                implementation: crate::eval::PrimitiveImpl::Native(primitive_current_stack_trace),
                arity_min: 0,
                arity_max: Some(0),
                effects: vec![],
            }
        )));

        Ok(())
    }
}

/// Comprehensive inspection results for a runtime value.
/// 
/// Combines type information, metadata, environment context,
/// and analysis results into a complete introspection report.
#[derive(Debug, Clone)]
pub struct ValueInspection {
    /// Detailed type information
    pub type_info: TypeInfo,
    /// Metadata information
    pub metadata: MetadataInfo,
    /// Simple type name
    pub type_name: String,
}

// Primitive implementations
fn primitive_type_of(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("type-of expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    let mut inspector = ObjectInspector::new();
    let type_info = inspector.get_type_info(&args[0]);
    
    // Convert TypeInfo to a Scheme value representation
    let type_symbol = match type_info {
        TypeInfo::Boolean => "boolean",
        TypeInfo::Number => "number",
        TypeInfo::String => "string",
        TypeInfo::Character => "character",
        TypeInfo::Symbol => "symbol",
        TypeInfo::Keyword => "keyword",
        TypeInfo::Nil => "null",
        TypeInfo::Pair => "pair",
        TypeInfo::Vector => "vector",
        TypeInfo::Procedure { .. } => "procedure",
        TypeInfo::Primitive { .. } => "primitive",
        _ => "unknown",
    };

    Ok(Value::symbol(crate::utils::intern_symbol(type_symbol)))
}

fn primitive_type_name(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(Error::runtime_error(
            format!("type-name expects 1 argument, got {}", args.len()),
            None,
        )));
    }

    let inspector = TypeInspector::new();
    let type_name = inspector.get_type_name(&args[0]);
    Ok(Value::string(type_name))
}

fn primitive_get_metadata(_args: &[Value]) -> Result<Value> {
    // Placeholder implementation
    Ok(Value::Nil)
}

fn primitive_environment_bindings(_args: &[Value]) -> Result<Value> {
    // Placeholder implementation
    Ok(Value::Nil)
}

fn primitive_current_stack_trace(_args: &[Value]) -> Result<Value> {
    // Placeholder implementation - would need access to current evaluator
    Ok(Value::Nil)
}

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