component_model 0.17.0

Revolutionary type-safe component assignment for Rust. Build complex objects with zero boilerplate using derive macros and type-driven field setting. Perfect for configuration builders, fluent APIs, and object composition patterns.
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
# Task 008: Advanced Type System - Enum Support

## ๐ŸŽฏ **Objective**

Extend component model to support enum types with variant-specific component assignment, enabling type-safe configuration for different modes, states, and union-like data structures.

## ๐Ÿ“‹ **Current State**

Component model only works with structs:
```rust
#[derive(ComponentModel)]
struct Config 
{
  mode: String,  // "development" | "production" | "testing"
  database: String, // Could be different for each mode
}

// Must handle enum logic manually
let config = Config::default()
  .impute("production")
  .impute("postgres://prod-db:5432/app");

// Manual validation required
if config.mode == "production" && !config.database.starts_with("postgres://") {
  panic!("Production requires PostgreSQL");
}
```

## ๐ŸŽฏ **Target State**

Native enum support with variant-specific components:
```rust
#[derive(ComponentModel)]
enum DatabaseConfig 
{
  #[component(default)]
  Development {
    #[component(default = "localhost")]
    host: String,
    #[component(default = "5432")]
    port: u16,
  },
  
  Production {
    #[component(validate = "is_secure_connection")]
    connection_string: String,
    #[component(default = "50")]
    pool_size: usize,
  },
  
  InMemory,
}

// Type-safe variant assignment
let db_config = DatabaseConfig::Development::default()
  .impute("dev-db.local")
  .impute(5433u16);

// Or assign to existing enum
let mut config = DatabaseConfig::InMemory;
config.assign_variant(DatabaseConfig::Production {
  connection_string: "".to_string(),
  pool_size: 0,
});
config.assign("postgres://secure:pass@prod-db:5432/app");
config.assign(100usize);
```

## ๐Ÿ“ **Detailed Requirements**

### **Core Enum Traits**

#### **EnumAssign Trait**
```rust
pub trait EnumAssign<T, IntoT> {
  type Error;
  
  fn assign_to_variant(&mut self, component: IntoT) -> Result<(), Self::Error>;
  fn impute_to_variant(self, component: IntoT) -> Result<Self, Self::Error>
  where
    Self: Sized;
}

pub trait VariantAssign<V, T, IntoT> {
  type Error;
  
  fn assign_to_variant(&mut self, variant: V, component: IntoT) -> Result<(), Self::Error>;
  fn switch_to_variant(self, variant: V) -> Self;
}
```

#### **Variant Construction**
```rust
pub trait VariantConstructor<T> {
  fn construct_variant(components: T) -> Self;
  fn variant_name(&self) -> &'static str;
  fn variant_fields(&self) -> Vec<(&'static str, &'static str)>; // (field_name, type_name)
}
```

### **Enum Derive Implementation**

#### **Simple Enum (Unit Variants)**
```rust
#[derive(ComponentModel)]
enum LogLevel 
{
  Debug,
  Info, 
  Warn,
  Error,
}

// Generates string-based assignment
impl Assign<LogLevel, &str> for LogLevel 
{
  fn assign(&mut self, component: &str) -> Result<(), ComponentError> 
{
    *self = match component.to_lowercase().as_str() {
      "debug" => LogLevel::Debug,
      "info" => LogLevel::Info,
      "warn" => LogLevel::Warn,
      "error" => LogLevel::Error,
      _ => return Err(ComponentError::InvalidVariant {
        provided: component.to_string(),
        expected: vec!["debug", "info", "warn", "error"],
      }),
    };
    Ok(())
  }
}

// Usage
let mut level = LogLevel::Info;
level.assign("debug").unwrap();
assert!(matches!(level, LogLevel::Debug));
```

#### **Complex Enum (Struct Variants)**
```rust
#[derive(ComponentModel)]
enum ServerMode 
{
  Development {
    #[component(default = "127.0.0.1")]
    host: String,
    #[component(default = "8080")]
    port: u16,
    #[component(default = "true")]
    hot_reload: bool,
  },
  
  Production {
    #[component(validate = "is_secure_host")]
    host: String,
    #[component(validate = "is_secure_port")]
    port: u16,
    #[component(default = "100")]
    max_connections: usize,
  },
  
  Testing {
    #[component(default = "test")]
    database: String,
  },
}

// Generated variant constructors
impl ServerMode 
{
  pub fn development() -> Self 
{
    Self::Development {
      host: "127.0.0.1".to_string(),
      port: 8080,
      hot_reload: true,
    }
  }
  
  pub fn production() -> Self 
{
    Self::Production {
      host: "".to_string(),
      port: 0,
      max_connections: 100,
    }
  }
  
  pub fn testing() -> Self 
{
    Self::Testing {
      database: "test".to_string(),
    }
  }
}

// Generated component assignment
impl EnumAssign<String, &str> for ServerMode 
{
  type Error = ComponentError;
  
  fn assign_to_variant(&mut self, component: &str) -> Result<(), Self::Error> 
{
    match self {
      Self::Development { host, .. } => {
        *host = component.to_string();
        Ok(())
      },
      Self::Production { host, .. } => {
        is_secure_host(component)?;
        *host = component.to_string();
        Ok(())
      },
      Self::Testing { .. } => {
        Err(ComponentError::IncompatibleVariant {
          variant: "Testing",
          component_type: "String",
        })
      },
    }
  }
}

impl EnumAssign<u16, u16> for ServerMode 
{
  type Error = ComponentError;
  
  fn assign_to_variant(&mut self, component: u16) -> Result<(), Self::Error> 
{
    match self {
      Self::Development { port, .. } => {
        *port = component;
        Ok(())
      },
      Self::Production { port, .. } => {
        is_secure_port(component)?;
        *port = component;
        Ok(())
      },
      Self::Testing { .. } => {
        Err(ComponentError::IncompatibleVariant {
          variant: "Testing", 
          component_type: "u16",
        })
      },
    }
  }
}
```

### **Variant Switching and Migration**

#### **Safe Variant Switching**
```rust
impl ServerMode 
{
  pub fn switch_to_development(self) -> Self 
{
    match self {
      Self::Development { .. } => self, // Already correct variant
      Self::Production { host, .. } => {
        // Migrate from production to development
        Self::Development {
          host: if host.is_empty() { "127.0.0.1".to_string() } else { host },
          port: 8080,
          hot_reload: true,
        }
      },
      Self::Testing { .. } => {
        // Default development config
        Self::development()
      },
    }
  }
  
  pub fn try_switch_to_production(self) -> Result<Self, ValidationError> 
{
    match self {
      Self::Production { .. } => Ok(self),
      Self::Development { host, port, .. } => {
        // Validate before switching
        is_secure_host(&host)?;
        is_secure_port(port)?;
        
        Ok(Self::Production {
          host,
          port,
          max_connections: 100,
        })
      },
      Self::Testing { .. } => {
        Err(ValidationError::InvalidTransition {
          from: "Testing",
          to: "Production",
          reason: "Cannot migrate test config to production".to_string(),
        })
      },
    }
  }
}
```

### **Pattern Matching Integration**

#### **Component Query by Variant**
```rust
impl ServerMode 
{
  pub fn get_host(&self) -> Option<&str> 
{
    match self {
      Self::Development { host, .. } | Self::Production { host, .. } => Some(host),
      Self::Testing { .. } => None,
    }
  }
  
  pub fn get_port(&self) -> Option<u16> 
{
    match self {
      Self::Development { port, .. } | Self::Production { port, .. } => Some(*port),
      Self::Testing { .. } => None,
    }
  }
  
  pub fn supports_component<T: ComponentType>(&self) -> bool 
{
    match (T::type_name(), self.variant_name()) {
      ("String", "Development") => true,
      ("String", "Production") => true, 
      ("u16", "Development") => true,
      ("u16", "Production") => true,
      ("bool", "Development") => true,
      ("usize", "Production") => true,
      ("String", "Testing") => true, // database field
      _ => false,
    }
  }
}
```

### **Advanced Enum Patterns**

#### **Nested Enums**
```rust
#[derive(ComponentModel)]
enum DatabaseType 
{
  Postgres {
    #[component(nested)]
    connection: PostgresConfig,
  },
  Mysql {
    #[component(nested)]
    connection: MysqlConfig,
  },
  Sqlite {
    #[component(validate = "file_exists")]
    file_path: PathBuf,
  },
}

#[derive(ComponentModel)]
struct PostgresConfig 
{
  host: String,
  port: u16,
  sslmode: String,
}
```

#### **Generic Enum Support**
```rust
#[derive(ComponentModel)]
enum Result<T, E> 
{
  Ok(T),
  Err(E),
}

#[derive(ComponentModel)]
enum Option<T> 
{
  Some(T),
  None,
}

// Usage with component assignment
let mut result: Result<String, String> = Result::Ok("".to_string());
result.assign_to_variant("success_value".to_string()); // Assigns to Ok variant

let mut option: Option<i32> = Option::None;
option.assign_to_variant(42); // Changes to Some(42)
```

### **Union-Type Support**

#### **Either Pattern**
```rust
#[derive(ComponentModel)]
enum Either<L, R> 
{
  Left(L),
  Right(R),
}

impl<L, R, T> Assign<Either<L, R>, T> for Either<L, R>
where
  T: TryInto<L> + TryInto<R>,
{
  fn assign(&mut self, component: T) 
{
    // Try left first, then right
    if let Ok(left_val) = component.try_into() {
      *self = Either::Left(left_val);
    } else if let Ok(right_val) = component.try_into() {
      *self = Either::Right(right_val);
    }
    // Could implement priority or explicit variant selection
  }
}
```

## ๐Ÿ—‚๏ธ **File Changes**

### **New Files**
- `component_model_meta/src/enum_derive.rs` - Enum derive implementation
- `component_model_types/src/enum_traits.rs` - Enum-specific traits
- `component_model_types/src/variant.rs` - Variant handling utilities
- `component_model_types/src/pattern_match.rs` - Pattern matching helpers
- `examples/enum_config_example.rs` - Comprehensive enum examples
- `examples/state_machine_example.rs` - State machine with enums

### **Modified Files**
- `component_model_meta/src/lib.rs` - Export enum derive
- `component_model_types/src/lib.rs` - Export enum traits
- `component_model/src/lib.rs` - Re-export enum functionality

## โšก **Implementation Steps**

### **Phase 1: Basic Enum Support (Week 1)**
1. Implement simple enum derive (unit variants only)
2. Add string-based variant assignment
3. Create basic error types for enum operations
4. Unit tests for simple enums

### **Phase 2: Struct Variants (Week 2)**
1. Add support for struct-like enum variants
2. Implement field-level component assignment within variants
3. Add variant switching and migration
4. Validation integration for enum fields

### **Phase 3: Advanced Features (Week 2-3)**
1. Generic enum support
2. Nested enums and complex patterns
3. Pattern matching helpers and utilities
4. Performance optimization and comprehensive testing

## ๐Ÿงช **Testing Strategy**

### **Unit Tests**
```rust
#[cfg(test)]
mod tests {
  use super::*;
  
  #[test]
  fn test_simple_enum_assignment() 
{
    #[derive(ComponentModel, PartialEq, Debug)]
    enum Color 
{
      Red,
      Green,
      Blue,
    }
    
    let mut color = Color::Red;
    color.assign("green").unwrap();
    assert_eq!(color, Color::Green);
    
    assert!(color.assign("purple").is_err());
  }
  
  #[test]
  fn test_struct_variant_assignment() 
{
    #[derive(ComponentModel)]
    enum ServerConfig 
{
      Development { host: String, port: u16 },
      Production { host: String, port: u16, ssl: bool },
    }
    
    let mut config = ServerConfig::Development {
      host: "localhost".to_string(),
      port: 8080,
    };
    
    config.assign_to_variant("api.example.com").unwrap();
    config.assign_to_variant(3000u16).unwrap();
    
    match config {
      ServerConfig::Development { host, port } => {
        assert_eq!(host, "api.example.com");
        assert_eq!(port, 3000);
      },
      _ => panic!("Wrong variant"),
    }
  }
  
  #[test]
  fn test_variant_switching() 
{
    #[derive(ComponentModel)]
    enum Mode 
{
      Dev { debug: bool },
      Prod { optimized: bool },
    }
    
    let dev_mode = Mode::Dev { debug: true };
    let prod_mode = dev_mode.switch_to_variant(Mode::Prod { optimized: false });
    
    match prod_mode {
      Mode::Prod { optimized } => assert!(!optimized),
      _ => panic!("Failed to switch variant"),
    }
  }
}
```

### **Integration Tests**
```rust
// tests/enum_integration.rs
#[test]
fn test_complex_enum_config() 
{
  #[derive(ComponentModel)]
  enum AppEnvironment 
{
    Development {
      #[component(default = "localhost")]
      db_host: String,
      #[component(default = "3000")]
      port: u16,
      #[component(default = "true")]
      hot_reload: bool,
    },
    
    Production {
      #[component(validate = "is_production_db")]
      db_connection_string: String,
      #[component(validate = "is_https_port")]
      port: u16,
      #[component(default = "1000")]
      max_connections: usize,
    },
  }
  
  // Test development configuration
  let mut dev_config = AppEnvironment::Development {
    db_host: "".to_string(),
    port: 0,
    hot_reload: false,
  };
  
  dev_config.assign_to_variant("dev-db.local").unwrap();
  dev_config.assign_to_variant(4000u16).unwrap();
  dev_config.assign_to_variant(true).unwrap();
  
  // Test migration to production
  let prod_config = dev_config.try_switch_to_production().unwrap();
  
  match prod_config {
    AppEnvironment::Production { port, max_connections, .. } => {
      assert_eq!(port, 443); // Should validate and use HTTPS port
      assert_eq!(max_connections, 1000);
    },
    _ => panic!("Migration failed"),
  }
}
```

## ๐Ÿ“Š **Success Metrics**

- [ ] Support for unit, tuple, and struct enum variants  
- [ ] Type-safe component assignment within variants
- [ ] Variant switching with validation and migration
- [ ] Generic enum support (Option<T>, Result<T,E>, Either<L,R>)
- [ ] Clear error messages for invalid variant operations
- [ ] Zero runtime overhead vs manual enum handling

## ๐Ÿšง **Potential Challenges**

1. **Type Complexity**: Generic enums with complex constraints
   - **Solution**: Careful trait bounds and incremental implementation

2. **Pattern Matching**: Generating efficient match statements
   - **Solution**: Optimize generated code and benchmark performance

3. **Variant Migration**: Complex data transformations between variants
   - **Solution**: User-defined migration functions and validation

4. **Error Handling**: Clear errors for variant-specific operations
   - **Solution**: Structured error types with context information

## ๐Ÿ”„ **Dependencies**

- **Requires**: 
  - Task 001 (Single Derive Macro) for attribute parsing
  - Task 003 (Validation) for variant validation
- **Blocks**: None
- **Related**: All configuration tasks benefit from enum support

## ๐Ÿ“… **Timeline**

- **Week 1**: Simple enum support (unit variants)
- **Week 2**: Struct variants and field assignment
- **Week 2-3**: Advanced features, generics, and optimization

## ๐Ÿ’ก **Future Enhancements**

- **State Machines**: First-class state machine support with transitions
- **Pattern Matching Macros**: Advanced pattern matching helpers
- **Serialization**: Seamless serde integration for enum variants
- **GraphQL Integration**: Generate GraphQL union types from enums
- **Database Mapping**: Map enum variants to database columns/tables