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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Integration layer for coexistence between standard and monadic evaluators.
//!
//! This module provides a unified interface that allows both evaluators
//! to coexist, with intelligent routing based on expression analysis
//! and performance requirements.

use crate::eval::{
    Value, Environment, Evaluator as StandardEvaluator,
    monadic_architecture::{
        MonadicEvaluationOrchestrator, MonadicEvaluationInput, MonadicEvaluationResult,
        MonadicComputation,
    },
    operational_semantics::EvaluationContext,
};
use crate::ast::{Expr, Spanned};
use crate::diagnostics::{Result, Error, Span};
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// Unified evaluator that intelligently routes between standard and monadic evaluation.
///
/// This follows the Strategy pattern, where the evaluation strategy is chosen
/// dynamically based on the characteristics of the expression and current context.
#[derive(Debug)]
pub struct HybridEvaluator {
    /// Standard tree-walking evaluator
    standard_evaluator: StandardEvaluator,
    
    /// Monadic evaluator orchestrator
    monadic_orchestrator: Arc<MonadicEvaluationOrchestrator>,
    
    /// Configuration for evaluation strategy selection
    strategy_config: EvaluationStrategyConfiguration,
    
    /// Performance metrics collector
    metrics: PerformanceMetricsCollector,
    
    /// Expression analyzer for routing decisions
    expression_analyzer: ExpressionAnalyzer,
}

/// Configuration for evaluation strategy selection
#[derive(Debug, Clone)]
pub struct EvaluationStrategyConfiguration {
    /// Threshold for switching to monadic evaluator based on effect complexity
    effect_complexity_threshold: f64,
    
    /// Whether to enable automatic strategy switching
    enable_auto_switching: bool,
    
    /// Force monadic evaluation for expressions containing call/cc
    force_monadic_for_call_cc: bool,
    
    /// Force monadic evaluation for IO operations
    force_monadic_for_io: bool,
    
    /// Performance threshold for switching strategies (in milliseconds)
    performance_threshold_ms: u64,
    
    /// Whether to enable parallel evaluation comparison
    enable_parallel_comparison: bool,
}

/// Performance metrics collector for evaluation strategy optimization
#[derive(Debug, Default)]
pub struct PerformanceMetricsCollector {
    /// Metrics for standard evaluator
    standard_metrics: EvaluatorMetrics,
    
    /// Metrics for monadic evaluator
    monadic_metrics: EvaluatorMetrics,
    
    /// Configuration
    config: MetricsConfiguration,
}

/// Performance metrics for an evaluator
#[derive(Debug, Clone, Default)]
pub struct EvaluatorMetrics {
    /// Total number of evaluations
    pub evaluation_count: u64,
    
    /// Total evaluation time
    pub total_time_ns: u64,
    
    /// Average evaluation time
    pub average_time_ns: u64,
    
    /// Memory usage statistics
    pub memory_usage: MemoryUsageStats,
    
    /// Error count
    pub error_count: u64,
    
    /// Success rate (0.0 to 1.0)
    pub success_rate: f64,
    
    /// Specific feature usage
    pub feature_usage: FeatureUsageStats,
}

/// Memory usage statistics
#[derive(Debug, Clone, Default)]
pub struct MemoryUsageStats {
    /// Peak memory usage in bytes
    pub peak_memory_bytes: usize,
    
    /// Average memory usage in bytes
    pub average_memory_bytes: usize,
    
    /// Number of allocations
    pub allocation_count: u64,
    
    /// Number of garbage collections triggered
    pub gc_count: u64,
}

/// Feature usage statistics
#[derive(Debug, Clone, Default)]
pub struct FeatureUsageStats {
    /// Number of call/cc uses
    pub call_cc_count: u64,
    
    /// Number of IO operations
    pub io_operation_count: u64,
    
    /// Number of state operations
    pub state_operation_count: u64,
    
    /// Number of error handling operations
    pub error_handling_count: u64,
    
    /// Maximum stack depth reached
    pub max_stack_depth: usize,
    
    /// Number of tail calls optimized
    pub tail_calls_optimized: u64,
}

/// Configuration for metrics collection
#[derive(Debug, Clone)]
pub struct MetricsConfiguration {
    /// Whether to enable detailed metrics collection
    pub enable_detailed_metrics: bool,
    
    /// Whether to enable memory profiling
    pub enable_memory_profiling: bool,
    
    /// Sample rate for metrics collection (0.0 to 1.0)
    pub sample_rate: f64,
    
    /// Maximum number of metrics entries to keep
    pub max_metrics_entries: usize,
}

/// Expression analyzer that determines the best evaluation strategy
#[derive(Debug, Default)]
pub struct ExpressionAnalyzer {
    /// Analysis configuration
    config: AnalysisConfiguration,
    
    /// Cache for analysis results
    analysis_cache: std::collections::HashMap<ExpressionSignature, AnalysisResult>,
}

/// Configuration for expression analysis
#[derive(Debug, Clone)]
pub struct AnalysisConfiguration {
    /// Whether to enable deep analysis (traverse entire AST)
    pub enable_deep_analysis: bool,
    
    /// Whether to cache analysis results
    pub enable_caching: bool,
    
    /// Maximum cache size
    pub max_cache_size: usize,
    
    /// Whether to consider performance history in analysis
    pub consider_performance_history: bool,
}

/// Signature for identifying expressions in the cache
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExpressionSignature {
    /// Hash of the expression structure
    pub structure_hash: u64,
    
    /// Depth of the expression tree
    pub depth: usize,
    
    /// Number of nodes in the expression
    pub node_count: usize,
    
    /// Feature flags (call/cc, IO, etc.)
    pub feature_flags: u32,
}

/// Result of expression analysis
#[derive(Debug, Clone)]
pub struct AnalysisResult {
    /// Recommended evaluation strategy
    pub recommended_strategy: EvaluationStrategy,
    
    /// Confidence in the recommendation (0.0 to 1.0)
    pub confidence: f64,
    
    /// Estimated effect complexity
    pub effect_complexity: f64,
    
    /// Expected performance characteristics
    pub performance_prediction: PerformancePrediction,
    
    /// Features detected in the expression
    pub detected_features: Vec<DetectedFeature>,
    
    /// Reasons for the recommendation
    pub reasoning: Vec<String>,
}

/// Evaluation strategies
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvaluationStrategy {
    /// Use the standard tree-walking evaluator
    Standard,
    
    /// Use the monadic evaluator
    Monadic,
    
    /// Use both evaluators in parallel for comparison
    Parallel,
    
    /// Adaptive strategy that may switch during evaluation
    Adaptive,
}

/// Performance prediction for an evaluation strategy
#[derive(Debug, Clone)]
pub struct PerformancePrediction {
    /// Estimated execution time in nanoseconds
    pub estimated_time_ns: u64,
    
    /// Estimated memory usage in bytes
    pub estimated_memory_bytes: usize,
    
    /// Estimated success probability (0.0 to 1.0)
    pub success_probability: f64,
    
    /// Confidence in the prediction (0.0 to 1.0)
    pub prediction_confidence: f64,
}

/// Features detected in expressions
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DetectedFeature {
    /// Contains call/cc
    CallCC,
    
    /// Contains IO operations
    IOOperations,
    
    /// Contains state operations
    StateOperations,
    
    /// Contains error handling
    ErrorHandling,
    
    /// Deep recursion detected
    DeepRecursion,
    
    /// Complex control flow
    ComplexControlFlow,
    
    /// Monadic operations
    MonadicOperations,
    
    /// Custom feature
    Custom(String),
}

/// Adapter for the standard evaluator to work with the hybrid interface
#[derive(Debug)]
pub struct StandardEvaluatorAdapter {
    /// The wrapped standard evaluator
    evaluator: StandardEvaluator,
}

/// Adapter for the monadic evaluator to work with the hybrid interface
#[derive(Debug)]
pub struct MonadicEvaluatorAdapter {
    /// The wrapped monadic orchestrator
    orchestrator: Arc<MonadicEvaluationOrchestrator>,
}

/// Unified evaluation result that can come from either evaluator
#[derive(Debug, Clone)]
pub enum UnifiedEvaluationResult {
    /// Result from standard evaluator
    Standard {
        /// The evaluated value.
        value: Value,
        /// Performance and evaluation metrics.
        metrics: StandardEvaluationMetrics,
    },
    
    /// Result from monadic evaluator
    Monadic {
        /// The monadic computation result.
        computation: MonadicComputation<Value>,
        /// Detailed evaluation result with metrics.
        result: Box<MonadicEvaluationResult>,
    },
    
    /// Result from parallel evaluation (both evaluators)
    Parallel {
        /// Result from the standard evaluator.
        standard_result: Value,
        /// Result from the monadic evaluator.
        monadic_result: MonadicComputation<Value>,
        /// Performance comparison between evaluators.
        performance_comparison: PerformanceComparison,
    },
}

/// Metrics from standard evaluation
#[derive(Debug, Clone)]
pub struct StandardEvaluationMetrics {
    /// Evaluation time
    pub evaluation_time_ns: u64,
    
    /// Stack depth reached
    pub max_stack_depth: usize,
    
    /// Number of function calls
    pub function_calls: u64,
    
    /// Memory allocated
    pub memory_allocated: usize,
}

/// Performance comparison between evaluators
#[derive(Debug, Clone)]
pub struct PerformanceComparison {
    /// Time taken by standard evaluator
    pub standard_time_ns: u64,
    
    /// Time taken by monadic evaluator
    pub monadic_time_ns: u64,
    
    /// Memory used by standard evaluator
    pub standard_memory_bytes: usize,
    
    /// Memory used by monadic evaluator
    pub monadic_memory_bytes: usize,
    
    /// Whether results were identical
    pub results_identical: bool,
    
    /// Winner (which performed better)
    pub winner: EvaluationStrategy,
    
    /// Performance difference ratio
    pub performance_ratio: f64,
}

// ================================
// IMPLEMENTATION
// ================================

impl HybridEvaluator {
    /// Create a new hybrid evaluator
    pub fn new(
        standard_evaluator: StandardEvaluator,
        monadic_orchestrator: Arc<MonadicEvaluationOrchestrator>,
    ) -> Self {
        Self {
            standard_evaluator,
            monadic_orchestrator,
            strategy_config: EvaluationStrategyConfiguration::default(),
            metrics: PerformanceMetricsCollector::new(),
            expression_analyzer: ExpressionAnalyzer::new(),
        }
    }
    
    /// Create a hybrid evaluator with custom configuration
    pub fn with_config(
        standard_evaluator: StandardEvaluator,
        monadic_orchestrator: Arc<MonadicEvaluationOrchestrator>,
        config: EvaluationStrategyConfiguration,
    ) -> Self {
        Self {
            standard_evaluator,
            monadic_orchestrator,
            strategy_config: config,
            metrics: PerformanceMetricsCollector::new(),
            expression_analyzer: ExpressionAnalyzer::new(),
        }
    }
    
    /// Evaluate an expression using the optimal strategy
    pub async fn evaluate(
        &mut self,
        expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<UnifiedEvaluationResult> {
        // Analyze the expression to determine the best strategy
        let analysis = self.expression_analyzer.analyze_expression(expr)?;
        
        match analysis.recommended_strategy {
            EvaluationStrategy::Standard => {
                self.evaluate_with_standard(expr, env).await
            }
            
            EvaluationStrategy::Monadic => {
                self.evaluate_with_monadic(expr, env).await
            }
            
            EvaluationStrategy::Parallel => {
                self.evaluate_with_both(expr, env).await
            }
            
            EvaluationStrategy::Adaptive => {
                self.evaluate_adaptively(expr, env).await
            }
        }
    }
    
    /// Evaluate using the standard evaluator
    async fn evaluate_with_standard(
        &mut self,
        expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<UnifiedEvaluationResult> {
        let start_time = Instant::now();
        
        // Evaluate using the standard evaluator directly
        let result = self.standard_evaluator.eval(expr, env)?;
        
        let evaluation_time = start_time.elapsed().as_nanos() as u64;
        
        // Update metrics
        self.metrics.update_standard_metrics(evaluation_time, true);
        
        Ok(UnifiedEvaluationResult::Standard {
            value: result,
            metrics: StandardEvaluationMetrics {
                evaluation_time_ns: evaluation_time,
                max_stack_depth: 0, // Would be tracked by actual implementation
                function_calls: 0,   // Would be tracked by actual implementation
                memory_allocated: 0, // Would be tracked by actual implementation
            },
        })
    }
    
    /// Evaluate using the monadic evaluator
    async fn evaluate_with_monadic(
        &mut self,
        expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<UnifiedEvaluationResult> {
        let start_time = Instant::now();
        
        // Create adapter for monadic evaluator
        let mut adapter = MonadicEvaluatorAdapter::new(self.monadic_orchestrator.clone());
        let result = adapter.evaluate(expr, env).await?;
        
        let evaluation_time = start_time.elapsed().as_nanos() as u64;
        
        // Update metrics
        self.metrics.update_monadic_metrics(evaluation_time, true);
        
        Ok(result)
    }
    
    /// Evaluate using both evaluators in parallel
    async fn evaluate_with_both(
        &mut self,
        expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<UnifiedEvaluationResult> {
        // Launch both evaluations sequentially to avoid borrow conflicts
        let standard_result = self.evaluate_with_standard(expr, env.clone()).await;
        let monadic_result = self.evaluate_with_monadic(expr, env).await;
        
        let standard_result = standard_result?;
        let monadic_result = monadic_result?;
        
        // Extract results and compare performance
        match (standard_result, monadic_result) {
            (
                UnifiedEvaluationResult::Standard { value: std_value, metrics: std_metrics },
                UnifiedEvaluationResult::Monadic { computation, result },
            ) => {
                // Create performance comparison
                let performance_comparison = PerformanceComparison {
                    standard_time_ns: std_metrics.evaluation_time_ns,
                    monadic_time_ns: result.metrics.evaluation_time_ns,
                    standard_memory_bytes: std_metrics.memory_allocated,
                    monadic_memory_bytes: result.metrics.memory_allocated,
                    results_identical: false, // Would need to compare actual results
                    winner: if std_metrics.evaluation_time_ns < result.metrics.evaluation_time_ns {
                        EvaluationStrategy::Standard
                    } else {
                        EvaluationStrategy::Monadic
                    },
                    performance_ratio: std_metrics.evaluation_time_ns as f64 / result.metrics.evaluation_time_ns as f64,
                };
                
                Ok(UnifiedEvaluationResult::Parallel {
                    standard_result: std_value,
                    monadic_result: computation,
                    performance_comparison,
                })
            }
            
            _ => {
                Err(Box::new(Error::runtime_error(
                    "Unexpected result types from parallel evaluation".to_string(),
                    None,
                )))
            }
        }
    }
    
    /// Adaptive evaluation that may switch strategies during execution
    async fn evaluate_adaptively(
        &mut self,
        expr: &Spanned<Expr>,
        env: Rc<Environment>,
    ) -> Result<UnifiedEvaluationResult> {
        // Start with the recommended strategy based on analysis
        let analysis = self.expression_analyzer.analyze_expression(expr)?;
        let initial_strategy = if analysis.confidence > 0.8 {
            analysis.recommended_strategy
        } else {
            // Low confidence - use parallel evaluation to gather data
            EvaluationStrategy::Parallel
        };
        
        match initial_strategy {
            EvaluationStrategy::Standard => self.evaluate_with_standard(expr, env).await,
            EvaluationStrategy::Monadic => self.evaluate_with_monadic(expr, env).await,
            EvaluationStrategy::Parallel => self.evaluate_with_both(expr, env).await,
            EvaluationStrategy::Adaptive => {
                // Fallback to standard for now
                self.evaluate_with_standard(expr, env).await
            }
        }
    }
    
    /// Get performance metrics
    pub fn metrics(&self) -> &PerformanceMetricsCollector {
        &self.metrics
    }
    
    /// Get strategy configuration
    pub fn strategy_config(&self) -> &EvaluationStrategyConfiguration {
        &self.strategy_config
    }
    
    /// Update strategy configuration
    pub fn update_strategy_config(&mut self, config: EvaluationStrategyConfiguration) {
        self.strategy_config = config;
    }
}

impl ExpressionAnalyzer {
    /// Create a new expression analyzer
    pub fn new() -> Self {
        Self {
            config: AnalysisConfiguration::default(),
            analysis_cache: std::collections::HashMap::new(),
        }
    }
    
    /// Analyze an expression and recommend an evaluation strategy
    pub fn analyze_expression(&mut self, expr: &Spanned<Expr>) -> Result<AnalysisResult> {
        // Generate signature for caching
        let signature = self.generate_signature(expr);
        
        // Check cache first
        if self.config.enable_caching {
            if let Some(cached_result) = self.analysis_cache.get(&signature) {
                return Ok(cached_result.clone());
            }
        }
        
        // Perform analysis
        let result = self.perform_analysis(expr, &signature)?;
        
        // Cache the result
        if self.config.enable_caching && self.analysis_cache.len() < self.config.max_cache_size {
            self.analysis_cache.insert(signature, result.clone());
        }
        
        Ok(result)
    }
    
    /// Generate a signature for an expression
    fn generate_signature(&self, expr: &Spanned<Expr>) -> ExpressionSignature {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        std::hash::Hash::hash(&format!("{:?}", expr.inner), &mut hasher);
        
        ExpressionSignature {
            structure_hash: std::hash::Hasher::finish(&hasher),
            depth: Self::calculate_depth(&expr.inner),
            node_count: Self::count_nodes(&expr.inner),
            feature_flags: self.extract_feature_flags(&expr.inner),
        }
    }
    
    /// Perform the actual analysis
    fn perform_analysis(&self, expr: &Spanned<Expr>, signature: &ExpressionSignature) -> Result<AnalysisResult> {
        let mut detected_features = Vec::new();
        let mut reasoning = Vec::new();
        let mut effect_complexity = 0.0;
        
        // Analyze for specific features
        if Self::contains_call_cc(&expr.inner) {
            detected_features.push(DetectedFeature::CallCC);
            effect_complexity += 0.8;
            reasoning.push("Contains call/cc - high effect complexity".to_string());
        }
        
        if self.contains_io_operations(&expr.inner) {
            detected_features.push(DetectedFeature::IOOperations);
            effect_complexity += 0.6;
            reasoning.push("Contains IO operations".to_string());
        }
        
        if self.contains_state_operations(&expr.inner) {
            detected_features.push(DetectedFeature::StateOperations);
            effect_complexity += 0.4;
            reasoning.push("Contains state operations".to_string());
        }
        
        if signature.depth > 10 {
            detected_features.push(DetectedFeature::DeepRecursion);
            effect_complexity += 0.3;
            reasoning.push("Deep expression nesting detected".to_string());
        }
        
        // Determine recommended strategy
        let recommended_strategy = if effect_complexity > 0.7 {
            EvaluationStrategy::Monadic
        } else if effect_complexity > 0.3 {
            EvaluationStrategy::Parallel // Test both to gather data
        } else {
            EvaluationStrategy::Standard
        };
        
        let confidence = if !(0.2..=0.8).contains(&effect_complexity) {
            0.9 // High confidence for clear cases
        } else {
            0.5 // Lower confidence for borderline cases
        };
        
        Ok(AnalysisResult {
            recommended_strategy,
            confidence,
            effect_complexity,
            performance_prediction: PerformancePrediction {
                estimated_time_ns: (signature.node_count as u64) * 1000, // Rough estimate
                estimated_memory_bytes: signature.node_count * 64,       // Rough estimate
                success_probability: 0.95,
                prediction_confidence: 0.6,
            },
            detected_features,
            reasoning,
        })
    }
    
    /// Check if expression contains call/cc
    fn contains_call_cc(expr: &Expr) -> bool {
        match expr {
            Expr::CallCC(_) => true,
            Expr::Application { operator, operands } => {
                Self::contains_call_cc(&operator.inner) ||
                operands.iter().any(|arg| Self::contains_call_cc(&arg.inner))
            }
            Expr::If { test: cond, consequent: then_branch, alternative: else_branch } => {
                Self::contains_call_cc(&cond.inner) ||
                Self::contains_call_cc(&then_branch.inner) ||
                else_branch.as_ref().is_some_and(|e| Self::contains_call_cc(&e.inner))
            }
            Expr::Lambda { body, .. } => {
                body.iter().any(|e| Self::contains_call_cc(&e.inner))
            }
            _ => false,
        }
    }
    
    /// Check if expression contains IO operations
    fn contains_io_operations(&self, expr: &Expr) -> bool {
        match expr {
            Expr::Application { operator, .. } => {
                if let Expr::Identifier(name) = &operator.inner {
                    matches!(name.as_str(), "display" | "write" | "read" | "open-input-file" | "open-output-file")
                } else {
                    false
                }
            }
            _ => false,
        }
    }
    
    /// Check if expression contains state operations
    fn contains_state_operations(&self, expr: &Expr) -> bool {
        match expr {
            Expr::Application { operator, .. } => {
                if let Expr::Identifier(name) = &operator.inner {
                    matches!(name.as_str(), "set!" | "vector-set!" | "string-set!")
                } else {
                    false
                }
            }
            _ => false,
        }
    }
    
    /// Calculate the depth of an expression tree
    fn calculate_depth(expr: &Expr) -> usize {
        match expr {
            Expr::Application { operator, operands } => {
                let op_depth = Self::calculate_depth(&operator.inner);
                let max_operand_depth = operands.iter()
                    .map(|arg| Self::calculate_depth(&arg.inner))
                    .max()
                    .unwrap_or(0);
                1 + op_depth.max(max_operand_depth)
            }
            
            Expr::If { test: cond, consequent: then_branch, alternative: else_branch } => {
                let cond_depth = Self::calculate_depth(&cond.inner);
                let then_depth = Self::calculate_depth(&then_branch.inner);
                let else_depth = else_branch.as_ref()
                    .map_or(0, |e| Self::calculate_depth(&e.inner));
                1 + cond_depth.max(then_depth.max(else_depth))
            }
            
            Expr::Lambda { body, .. } => {
                1 + body.iter()
                    .map(|e| Self::calculate_depth(&e.inner))
                    .max()
                    .unwrap_or(0)
            }
            
            _ => 1,
        }
    }
    
    /// Count the number of nodes in an expression tree
    fn count_nodes(expr: &Expr) -> usize {
        match expr {
            Expr::Application { operator, operands } => {
                1 + Self::count_nodes(&operator.inner) +
                operands.iter().map(|arg| Self::count_nodes(&arg.inner)).sum::<usize>()
            }
            
            Expr::If { test: cond, consequent: then_branch, alternative: else_branch } => {
                1 + Self::count_nodes(&cond.inner) + 
                Self::count_nodes(&then_branch.inner) +
                else_branch.as_ref().map_or(0, |e| Self::count_nodes(&e.inner))
            }
            
            Expr::Lambda { body, .. } => {
                1 + body.iter().map(|e| Self::count_nodes(&e.inner)).sum::<usize>()
            }
            
            _ => 1,
        }
    }
    
    /// Extract feature flags as a bitmask
    fn extract_feature_flags(&self, expr: &Expr) -> u32 {
        let mut flags = 0u32;
        
        if Self::contains_call_cc(expr) { flags |= 1; }
        if self.contains_io_operations(expr) { flags |= 2; }
        if self.contains_state_operations(expr) { flags |= 4; }
        
        flags
    }
}

impl StandardEvaluatorAdapter {
    /// Create a new adapter for the standard evaluator
    pub fn new(evaluator: StandardEvaluator) -> Self {
        Self { evaluator }
    }
    
    /// Evaluate an expression using the standard evaluator
    pub fn evaluate(&mut self, expr: &Spanned<Expr>, env: Rc<Environment>) -> Result<Value> {
        // This would delegate to the actual standard evaluator
        // For now, we return a placeholder
        Ok(Value::Unspecified)
    }
}

impl MonadicEvaluatorAdapter {
    /// Create a new adapter for the monadic evaluator
    pub fn new(orchestrator: Arc<MonadicEvaluationOrchestrator>) -> Self {
        Self { orchestrator }
    }
    
    /// Evaluate an expression using the monadic evaluator
    pub async fn evaluate(&mut self, expr: &Spanned<Expr>, env: Rc<Environment>) -> Result<UnifiedEvaluationResult> {
        let context = EvaluationContext::empty(env.clone());
        let input = MonadicEvaluationInput {
            expression: expr.clone(),
            environment: env,
            expected_monad: None,
            context,
        };
        
        // This would delegate to the actual monadic orchestrator
        // For now, we return a placeholder
        let result = MonadicEvaluationResult {
            computation: MonadicComputation::Pure(Value::Unspecified),
            metadata: crate::eval::monadic_architecture::EvaluationMetadata {
                steps_taken: 1,
                max_stack_depth: 1,
                monads_used: vec![],
                tail_call_optimized: false,
            },
            effects: vec![],
            metrics: crate::eval::monadic_architecture::EvaluationMetrics {
                evaluation_time_ns: 1000,
                memory_allocated: 1024,
                continuations_captured: 0,
                io_operations: 0,
            },
        };
        
        Ok(UnifiedEvaluationResult::Monadic {
            computation: result.computation.clone(),
            result: Box::new(result),
        })
    }
}

impl PerformanceMetricsCollector {
    /// Create a new metrics collector
    pub fn new() -> Self {
        Self {
            standard_metrics: EvaluatorMetrics::new(),
            monadic_metrics: EvaluatorMetrics::new(),
            config: MetricsConfiguration::default(),
        }
    }
    
    /// Update metrics for the standard evaluator
    pub fn update_standard_metrics(&mut self, evaluation_time_ns: u64, success: bool) {
        self.standard_metrics.update(evaluation_time_ns, success);
    }
    
    /// Update metrics for the monadic evaluator
    pub fn update_monadic_metrics(&mut self, evaluation_time_ns: u64, success: bool) {
        self.monadic_metrics.update(evaluation_time_ns, success);
    }
    
    /// Get standard evaluator metrics
    pub fn standard_metrics(&self) -> &EvaluatorMetrics {
        &self.standard_metrics
    }
    
    /// Get monadic evaluator metrics
    pub fn monadic_metrics(&self) -> &EvaluatorMetrics {
        &self.monadic_metrics
    }
}

impl EvaluatorMetrics {
    /// Create new empty metrics
    pub fn new() -> Self {
        Self {
            evaluation_count: 0,
            total_time_ns: 0,
            average_time_ns: 0,
            memory_usage: MemoryUsageStats {
                peak_memory_bytes: 0,
                average_memory_bytes: 0,
                allocation_count: 0,
                gc_count: 0,
            },
            error_count: 0,
            success_rate: 1.0,
            feature_usage: FeatureUsageStats {
                call_cc_count: 0,
                io_operation_count: 0,
                state_operation_count: 0,
                error_handling_count: 0,
                max_stack_depth: 0,
                tail_calls_optimized: 0,
            },
        }
    }
    
    /// Update metrics with new evaluation data
    pub fn update(&mut self, evaluation_time_ns: u64, success: bool) {
        self.evaluation_count += 1;
        self.total_time_ns += evaluation_time_ns;
        self.average_time_ns = self.total_time_ns / self.evaluation_count;
        
        if !success {
            self.error_count += 1;
        }
        
        self.success_rate = (self.evaluation_count - self.error_count) as f64 / self.evaluation_count as f64;
    }
}

// Default implementations

impl Default for EvaluationStrategyConfiguration {
    fn default() -> Self {
        Self {
            effect_complexity_threshold: 0.5,
            enable_auto_switching: true,
            force_monadic_for_call_cc: true,
            force_monadic_for_io: false,
            performance_threshold_ms: 100,
            enable_parallel_comparison: false,
        }
    }
}

impl Default for MetricsConfiguration {
    fn default() -> Self {
        Self {
            enable_detailed_metrics: true,
            enable_memory_profiling: false,
            sample_rate: 1.0,
            max_metrics_entries: 10000,
        }
    }
}

impl Default for AnalysisConfiguration {
    fn default() -> Self {
        Self {
            enable_deep_analysis: true,
            enable_caching: true,
            max_cache_size: 1000,
            consider_performance_history: true,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Literal;
    
    #[test]
    fn test_expression_analyzer() {
        let mut analyzer = ExpressionAnalyzer::new();
        
        // Test simple expression
        let expr = Spanned {
            inner: Expr::Literal(Literal::Number(42.0)),
            span: Span::default(),
        };
        
        let analysis = analyzer.analyze_expression(&expr).unwrap();
        assert_eq!(analysis.recommended_strategy, EvaluationStrategy::Standard);
        assert!(analysis.confidence > 0.5);
    }
    
    #[test]
    fn test_call_cc_detection() {
        let analyzer = ExpressionAnalyzer::new();
        
        let call_cc_expr = Expr::CallCC(Box::new(Spanned {
            inner: Expr::Identifier("proc".to_string()),
            span: Span::default(),
        }));
        
        assert!(ExpressionAnalyzer::contains_call_cc(&call_cc_expr));
    }
    
    #[test]
    fn test_io_operation_detection() {
        let analyzer = ExpressionAnalyzer::new();
        
        let io_expr = Expr::Application {
            operator: Box::new(Spanned {
                inner: Expr::Identifier("display".to_string()),
                span: Span::default(),
            }),
            operands: vec![Spanned {
                inner: Expr::Literal(Literal::String("Hello".to_string())),
                span: Span::default(),
            }],
        };
        
        assert!(analyzer.contains_io_operations(&io_expr));
    }
    
    #[test]
    fn test_performance_metrics() {
        let mut collector = PerformanceMetricsCollector::new();
        
        collector.update_standard_metrics(1000000, true);
        collector.update_standard_metrics(2000000, true);
        
        let metrics = collector.standard_metrics();
        assert_eq!(metrics.evaluation_count, 2);
        assert_eq!(metrics.average_time_ns, 1500000);
        assert_eq!(metrics.success_rate, 1.0);
    }
}