elif-core 0.7.1

Core architecture foundation for the elif.rs LLM-friendly web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
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
//! Service token system for type-safe trait injection
//!
//! Provides a token-based dependency injection system that enables compile-time
//! validation of trait implementations and semantic service resolution.
//!
//! ## Overview
//!
//! The service token system allows developers to define semantic tokens that
//! represent specific services or traits, enabling dependency inversion through
//! token-based resolution rather than concrete type dependencies.
//!
//! ## Naming Convention
//!
//! **Important**: Service tokens should follow the naming convention of ending with "Token"
//! (e.g., `EmailServiceToken`, `DatabaseToken`). This convention is used by the `#[inject]`
//! macro to automatically detect token references (`&TokenType`) and differentiate them from
//! regular reference fields, preventing incorrect macro expansion and compiler errors.
//!
//! ## Usage
//!
//! ```rust
//! use elif_core::container::{ServiceToken, IocContainer};
//! use std::sync::Arc;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Define a service trait
//! trait EmailService: Send + Sync {
//!     fn send(&self, to: &str, subject: &str, body: &str) -> Result<(), String>;
//! }
//!
//! // Define a token for the service
//! struct EmailNotificationToken;
//! impl ServiceToken for EmailNotificationToken {
//!     type Service = dyn EmailService;
//! }
//!
//! // Define implementations
//! #[derive(Default)]
//! struct SmtpEmailService;
//! impl EmailService for SmtpEmailService {
//!     fn send(&self, to: &str, subject: &str, body: &str) -> Result<(), String> {
//!         println!("SMTP: Sending to {} - {}: {}", to, subject, body);
//!         Ok(())
//!     }
//! }
//!
//! // Register with container
//! let mut container = IocContainer::new();
//! container.bind_token::<EmailNotificationToken, SmtpEmailService>()?;
//! container.build()?;
//!
//! // Note: Trait object resolution is not yet fully implemented
//! // This will be available in a future version:
//! // let service = container.resolve_by_token::<EmailNotificationToken>()?;
//! // service.send("user@example.com", "Welcome", "Hello!")?;
//! # Ok(())
//! # }
//! ```

use crate::container::descriptor::ServiceId;
use std::any::TypeId;
use std::marker::PhantomData;

/// Trait for service tokens that provide compile-time trait-to-implementation mapping
///
/// Service tokens are zero-sized types that act as compile-time identifiers for
/// specific services or traits. They enable type-safe dependency resolution
/// through semantic naming rather than concrete type dependencies.
///
/// ## Design Principles
///
/// - **Zero Runtime Cost**: Tokens are zero-sized and only exist at compile time
/// - **Type Safety**: Prevents incorrect service resolution through type constraints
/// - **Semantic Naming**: Enables meaningful service identifiers like `EmailNotificationToken`
/// - **Trait Resolution**: Allows injection of trait objects rather than concrete types
///
/// ## Implementation Requirements
///
/// - Token must be a zero-sized struct
/// - Associated `Service` type must be `Send + Sync + 'static`
/// - Service type is typically a trait object (`dyn Trait`)
///
/// ## Examples
///
/// ### Basic Trait Token
/// ```rust
/// use elif_core::container::ServiceToken;
/// 
/// trait Database: Send + Sync {}
/// struct DatabaseToken;
/// impl ServiceToken for DatabaseToken {
///     type Service = dyn Database;
/// }
/// ```
///
/// ### Specialized Service Token
/// ```rust
/// use elif_core::container::ServiceToken;
/// 
/// trait CacheService: Send + Sync {
///     fn get(&self, key: &str) -> Option<String>;
/// }
/// 
/// struct CacheToken;
/// impl ServiceToken for CacheToken {
///     type Service = dyn CacheService;
/// }
///
/// struct RedisCache;
/// impl CacheService for RedisCache {
///     fn get(&self, _key: &str) -> Option<String> {
///         None // Mock implementation
///     }
/// }
/// ```
pub trait ServiceToken: Send + Sync + 'static {
    /// The service type this token represents
    ///
    /// This is typically a trait object (`dyn Trait`) but can be any type
    /// that implements `Send + Sync + 'static`.
    type Service: ?Sized + Send + Sync + 'static;

    /// Get the TypeId of the service type
    ///
    /// Used internally for service resolution and type checking.
    /// Default implementation should suffice for most use cases.
    fn service_type_id() -> TypeId
    where
        Self::Service: 'static,
    {
        TypeId::of::<Self::Service>()
    }

    /// Get the type name of the service
    ///
    /// Used for debugging and error messages.
    /// Default implementation should suffice for most use cases.
    fn service_type_name() -> &'static str {
        std::any::type_name::<Self::Service>()
    }

    /// Get the token type name
    ///
    /// Used for debugging and error messages.
    /// Default implementation should suffice for most use cases.
    fn token_type_name() -> &'static str {
        std::any::type_name::<Self>()
    }
}

/// Metadata for a service token binding
///
/// Contains compile-time information about a token-to-implementation binding
/// for use in dependency resolution and validation.
#[derive(Debug, Clone)]
pub struct TokenBinding {
    /// The token type identifier
    pub token_type_id: TypeId,
    /// The token type name (for debugging)
    pub token_type_name: &'static str,
    /// The service type identifier
    pub service_type_id: TypeId,
    /// The service type name (for debugging)
    pub service_type_name: &'static str,
    /// The implementation type identifier
    pub impl_type_id: TypeId,
    /// The implementation type name (for debugging)
    pub impl_type_name: &'static str,
    /// Optional named identifier for multiple implementations
    pub name: Option<String>,
}

impl TokenBinding {
    /// Create a new token binding
    pub fn new<Token, Impl>() -> Self
    where
        Token: ServiceToken,
        Impl: Send + Sync + 'static,
    {
        Self {
            token_type_id: TypeId::of::<Token>(),
            token_type_name: std::any::type_name::<Token>(),
            service_type_id: Token::service_type_id(),
            service_type_name: Token::service_type_name(),
            impl_type_id: TypeId::of::<Impl>(),
            impl_type_name: std::any::type_name::<Impl>(),
            name: None,
        }
    }

    /// Create a named token binding
    pub fn named<Token, Impl>(name: impl Into<String>) -> Self
    where
        Token: ServiceToken,
        Impl: Send + Sync + 'static,
    {
        let mut binding = Self::new::<Token, Impl>();
        binding.name = Some(name.into());
        binding
    }

    /// Create a ServiceId for this token binding
    pub fn to_service_id(&self) -> ServiceId {
        if let Some(name) = &self.name {
            ServiceId::named_by_ids(self.service_type_id, self.service_type_name, name.clone())
        } else {
            ServiceId::by_ids(self.service_type_id, self.service_type_name)
        }
    }

    /// Check if this binding matches a token type
    pub fn matches_token<Token: ServiceToken>(&self) -> bool {
        self.token_type_id == TypeId::of::<Token>()
    }

    /// Validate that the implementation can be cast to the service type
    ///
    /// This performs compile-time type checking to ensure the implementation
    /// actually implements the service trait.
    pub fn validate_implementation<Token, Impl>() -> Result<(), String>
    where
        Token: ServiceToken,
        Impl: Send + Sync + 'static,
    {
        let token_service_id = Token::service_type_id();
        let impl_type_id = TypeId::of::<Impl>();

        // Basic validation - ensure we have the right types
        if token_service_id == TypeId::of::<()>() {
            return Err(format!(
                "Invalid service type for token {}: service type appears to be ()",
                Token::token_type_name()
            ));
        }

        // Check that implementation and service are different types (avoid self-referential bindings)
        if token_service_id == impl_type_id {
            return Err(format!(
                "Token {} maps to itself: implementation type {} cannot be the same as service type {}",
                Token::token_type_name(),
                std::any::type_name::<Impl>(),
                Token::service_type_name()
            ));
        }

        // Validate type names for better error messages
        let token_name = Token::token_type_name();
        let service_name = Token::service_type_name();
        let impl_name = std::any::type_name::<Impl>();

        if token_name.is_empty() {
            return Err("Invalid token: token type name is empty".to_string());
        }

        if service_name.is_empty() {
            return Err(format!(
                "Invalid token {}: service type name is empty",
                token_name
            ));
        }

        if impl_name.is_empty() {
            return Err(format!(
                "Invalid implementation for token {}: implementation type name is empty",
                token_name
            ));
        }

        // Additional validation: check for common naming patterns
        if service_name.contains("dyn ") && impl_name.contains("dyn ") {
            return Err(format!(
                "Invalid binding for token {}: both service ({}) and implementation ({}) appear to be trait objects. Implementation should be a concrete type.",
                token_name,
                service_name,
                impl_name
            ));
        }

        // Success - validation passed
        Ok(())
    }
}

/// Registry for token-based service bindings
///
/// Maintains a mapping from service tokens to their implementations
/// and provides lookup functionality for the IoC container.
#[derive(Debug, Default)]
pub struct TokenRegistry {
    /// All token bindings indexed by token type
    bindings: std::collections::HashMap<TypeId, Vec<TokenBinding>>,
    /// Default bindings (unnamed) indexed by token type  
    defaults: std::collections::HashMap<TypeId, TokenBinding>,
    /// Named bindings indexed by token type and name
    named: std::collections::HashMap<(TypeId, String), TokenBinding>,
}

impl TokenRegistry {
    /// Create a new token registry
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a token-to-implementation binding
    pub fn register<Token, Impl>(&mut self) -> Result<(), String>
    where
        Token: ServiceToken,
        Impl: Send + Sync + 'static,
    {
        // Validate the binding
        TokenBinding::validate_implementation::<Token, Impl>()?;

        let binding = TokenBinding::new::<Token, Impl>();
        let token_type_id = TypeId::of::<Token>();

        // Add to bindings list
        self.bindings
            .entry(token_type_id)
            .or_default()
            .push(binding.clone());

        // Set as default if no default exists
        self.defaults.entry(token_type_id).or_insert(binding);

        Ok(())
    }

    /// Register a named token-to-implementation binding
    pub fn register_named<Token, Impl>(&mut self, name: impl Into<String>) -> Result<(), String>
    where
        Token: ServiceToken,
        Impl: Send + Sync + 'static,
    {
        // Validate the binding
        TokenBinding::validate_implementation::<Token, Impl>()?;

        let name = name.into();
        let binding = TokenBinding::named::<Token, Impl>(&name);
        let token_type_id = TypeId::of::<Token>();

        // Add to bindings list
        self.bindings
            .entry(token_type_id)
            .or_default()
            .push(binding.clone());

        // Add to named bindings
        self.named.insert((token_type_id, name), binding);

        Ok(())
    }

    /// Get the default binding for a token type
    pub fn get_default<Token: ServiceToken>(&self) -> Option<&TokenBinding> {
        let token_type_id = TypeId::of::<Token>();
        self.defaults.get(&token_type_id)
    }

    /// Get a named binding for a token type
    pub fn get_named<Token: ServiceToken>(&self, name: &str) -> Option<&TokenBinding> {
        let token_type_id = TypeId::of::<Token>();
        self.named.get(&(token_type_id, name.to_string()))
    }

    /// Get all bindings for a token type
    pub fn get_all<Token: ServiceToken>(&self) -> Option<&Vec<TokenBinding>> {
        let token_type_id = TypeId::of::<Token>();
        self.bindings.get(&token_type_id)
    }

    /// Check if a token is registered
    pub fn contains<Token: ServiceToken>(&self) -> bool {
        let token_type_id = TypeId::of::<Token>();
        self.defaults.contains_key(&token_type_id)
    }

    /// Check if a named token is registered
    pub fn contains_named<Token: ServiceToken>(&self, name: &str) -> bool {
        let token_type_id = TypeId::of::<Token>();
        self.named.contains_key(&(token_type_id, name.to_string()))
    }

    /// Get all registered token types
    pub fn token_types(&self) -> Vec<TypeId> {
        self.defaults.keys().cloned().collect()
    }

    /// Get statistics about registered tokens
    pub fn stats(&self) -> TokenRegistryStats {
        TokenRegistryStats {
            total_tokens: self.bindings.len(), // Count unique token types from all bindings
            total_bindings: self.bindings.values().map(|v| v.len()).sum(),
            named_bindings: self.named.len(),
        }
    }

    /// Validate all token bindings in the registry
    ///
    /// Returns a list of validation errors found across all registered tokens.
    /// This method can be used to validate the entire registry after registration.
    pub fn validate_all_bindings(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Check for duplicate bindings
        for (token_type_id, bindings) in &self.bindings {
            if bindings.is_empty() {
                errors.push(format!(
                    "Token type {:?} has empty bindings list",
                    token_type_id
                ));
                continue;
            }

            // Check for consistency in token bindings
            let first_binding = &bindings[0];
            for binding in bindings.iter().skip(1) {
                if binding.token_type_id != first_binding.token_type_id {
                    errors.push(format!(
                        "Inconsistent token type IDs in bindings for token type {:?}",
                        token_type_id
                    ));
                }

                if binding.service_type_id != first_binding.service_type_id {
                    errors.push(format!(
                        "Inconsistent service type IDs for token {}: {} vs {}",
                        binding.token_type_name,
                        binding.service_type_name,
                        first_binding.service_type_name
                    ));
                }
            }

            // Check for named bindings consistency
            for binding in bindings {
                if let Some(name) = &binding.name {
                    if !self
                        .named
                        .contains_key(&(binding.token_type_id, name.clone()))
                    {
                        errors.push(format!(
                            "Named binding {} for token {} exists in bindings list but not in named map",
                            name,
                            binding.token_type_name
                        ));
                    }
                }
            }
        }

        // Check for orphaned named bindings
        for ((token_type_id, name), binding) in &self.named {
            if !self.bindings.contains_key(token_type_id) {
                errors.push(format!(
                    "Named binding {} for token {} exists in named map but token has no bindings",
                    name, binding.token_type_name
                ));
            }
        }

        errors
    }

    /// Check if a token has conflicting bindings
    pub fn has_binding_conflicts<Token: ServiceToken>(&self) -> Vec<String> {
        let mut conflicts = Vec::new();
        let token_type_id = TypeId::of::<Token>();

        if let Some(bindings) = self.bindings.get(&token_type_id) {
            // Check for multiple default bindings (shouldn't happen but good to check)
            let default_count = self.defaults.contains_key(&token_type_id) as usize;
            if default_count == 0 && !bindings.is_empty() {
                conflicts.push(format!(
                    "Token {} has bindings but no default binding",
                    Token::token_type_name()
                ));
            }

            // Check for duplicate named bindings (shouldn't happen due to HashMap)
            let mut seen_names = std::collections::HashSet::new();
            for binding in bindings {
                if let Some(name) = &binding.name {
                    if !seen_names.insert(name.clone()) {
                        conflicts.push(format!(
                            "Token {} has duplicate named binding: {}",
                            Token::token_type_name(),
                            name
                        ));
                    }
                }
            }
        }

        conflicts
    }

    /// Get detailed information about a token for debugging
    pub fn get_token_info<Token: ServiceToken>(&self) -> Option<TokenInfo> {
        let token_type_id = TypeId::of::<Token>();
        let bindings = self.bindings.get(&token_type_id)?;
        let default_binding = self.defaults.get(&token_type_id);

        let named_bindings: Vec<String> = self
            .named
            .iter()
            .filter_map(|((tid, name), _)| {
                if *tid == token_type_id {
                    Some(name.clone())
                } else {
                    None
                }
            })
            .collect();

        Some(TokenInfo {
            token_name: Token::token_type_name().to_string(),
            service_name: Token::service_type_name().to_string(),
            total_bindings: bindings.len(),
            has_default: default_binding.is_some(),
            named_bindings,
            implementation_types: bindings
                .iter()
                .map(|b| b.impl_type_name.to_string())
                .collect(),
        })
    }

    /// Clear all bindings (for testing)
    #[cfg(test)]
    pub fn clear(&mut self) {
        self.bindings.clear();
        self.defaults.clear();
        self.named.clear();
    }
}

/// Statistics about token registry usage
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenRegistryStats {
    /// Total number of distinct token types
    pub total_tokens: usize,
    /// Total number of bindings (including named variants)
    pub total_bindings: usize,
    /// Number of named bindings
    pub named_bindings: usize,
}

/// Detailed information about a specific token for debugging and validation
#[derive(Debug, Clone)]
pub struct TokenInfo {
    /// The token type name
    pub token_name: String,
    /// The service type name this token represents
    pub service_name: String,
    /// Total number of bindings for this token
    pub total_bindings: usize,
    /// Whether this token has a default binding
    pub has_default: bool,
    /// List of named binding identifiers
    pub named_bindings: Vec<String>,
    /// List of implementation type names
    pub implementation_types: Vec<String>,
}

/// Helper trait for working with token references in injection
///
/// This trait is implemented for reference types (`&Token`) to enable
/// seamless resolution of tokens through references in dependency injection.
pub trait TokenReference {
    /// The token type this reference points to
    type Token: ServiceToken;

    /// Get the token type
    fn token_type() -> PhantomData<Self::Token> {
        PhantomData
    }
}

impl<T: ServiceToken> TokenReference for &T {
    type Token = T;
}

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

    // Test service trait
    trait TestService: Send + Sync {
        #[allow(dead_code)]
        fn test(&self) -> String;
    }

    // Test token
    struct TestToken;
    impl ServiceToken for TestToken {
        type Service = dyn TestService;
    }

    // Test implementation
    struct TestImpl;
    impl TestService for TestImpl {
        fn test(&self) -> String {
            "test".to_string()
        }
    }

    #[test]
    fn test_service_token_trait() {
        assert_eq!(
            TestToken::token_type_name(),
            "elif_core::container::tokens::tests::TestToken"
        );
        assert_eq!(
            TestToken::service_type_name(),
            "dyn elif_core::container::tokens::tests::TestService"
        );
    }

    #[test]
    fn test_token_binding_creation() {
        let binding = TokenBinding::new::<TestToken, TestImpl>();

        assert_eq!(binding.token_type_id, TypeId::of::<TestToken>());
        assert_eq!(binding.service_type_id, TypeId::of::<dyn TestService>());
        assert_eq!(binding.impl_type_id, TypeId::of::<TestImpl>());
        assert!(binding.name.is_none());
    }

    #[test]
    fn test_named_token_binding() {
        let binding = TokenBinding::named::<TestToken, TestImpl>("primary");

        assert_eq!(binding.name, Some("primary".to_string()));
        assert!(binding.matches_token::<TestToken>());
    }

    #[test]
    fn test_token_registry_basic() {
        let mut registry = TokenRegistry::new();

        assert!(!registry.contains::<TestToken>());

        registry.register::<TestToken, TestImpl>().unwrap();

        assert!(registry.contains::<TestToken>());

        let binding = registry.get_default::<TestToken>().unwrap();
        assert!(binding.matches_token::<TestToken>());
    }

    #[test]
    fn test_token_registry_named() {
        let mut registry = TokenRegistry::new();

        registry
            .register_named::<TestToken, TestImpl>("primary")
            .unwrap();

        assert!(registry.contains_named::<TestToken>("primary"));
        assert!(!registry.contains_named::<TestToken>("secondary"));

        let binding = registry.get_named::<TestToken>("primary").unwrap();
        assert_eq!(binding.name, Some("primary".to_string()));
    }

    #[test]
    fn test_token_registry_stats() {
        let mut registry = TokenRegistry::new();

        registry.register::<TestToken, TestImpl>().unwrap();
        registry
            .register_named::<TestToken, TestImpl>("primary")
            .unwrap();

        let stats = registry.stats();
        assert_eq!(stats.total_tokens, 1);
        assert_eq!(stats.total_bindings, 2);
        assert_eq!(stats.named_bindings, 1);
    }

    #[test]
    fn test_token_reference() {
        let _phantom: PhantomData<TestToken> = <&TestToken as TokenReference>::token_type();
        // This test mainly ensures the TokenReference trait compiles correctly
    }
}