ggen-core 26.6.25

Core graph-aware code generation engine
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
//! Poka-yoke (error prevention) types for lifecycle system
//!
//! This module provides type-level error prevention patterns that make certain
//! errors impossible at compile time.
//!
//! # Poka-Yoke Principle
//!
//! "Make invalid states unrepresentable" - Use the type system to prevent entire
//! classes of errors rather than detecting them at runtime.

use super::error::Result;
use std::path::{Path, PathBuf};

// ============================================================================
// NON-EMPTY PATH TYPE
// ============================================================================

/// Path that is guaranteed to be non-empty at type level
///
/// **Poka-yoke**: Type system prevents empty paths. Cannot construct a
/// `NonEmptyPath` from an empty string - the constructor returns `Err`.
///
/// # Invariants
/// - Inner path is never empty (enforced at construction)
/// - Type system prevents using empty paths where non-empty required
///
/// # Example
///
/// ```rust
/// use crate::lifecycle::poka_yoke::NonEmptyPath;
/// use std::path::PathBuf;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // ✅ Valid: Non-empty path
/// let path = NonEmptyPath::new(PathBuf::from("output.rs"))?;
/// assert_eq!(path.as_path().to_str(), Some("output.rs"));
///
/// // ❌ Invalid: Empty path rejected at construction
/// let empty = NonEmptyPath::new(PathBuf::from(""));
/// assert!(empty.is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NonEmptyPath(PathBuf);

/// Error type for empty path construction
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmptyPathError;

impl std::fmt::Display for EmptyPathError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Path cannot be empty")
    }
}

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

impl NonEmptyPath {
    /// Create a new non-empty path
    ///
    /// Returns `Err(EmptyPathError)` if path is empty.
    ///
    /// **Poka-yoke**: Empty paths rejected at construction - cannot create invalid state.
    pub fn new(path: PathBuf) -> std::result::Result<Self, EmptyPathError> {
        if path.as_os_str().is_empty() {
            Err(EmptyPathError)
        } else {
            Ok(Self(path))
        }
    }

    /// Create from string (convenience method)
    ///
    /// Note: This is a convenience method. For trait-based parsing, use `FromStr::from_str`.
    pub fn from_string(s: &str) -> std::result::Result<Self, EmptyPathError> {
        if s.is_empty() {
            Err(EmptyPathError)
        } else {
            Ok(Self(PathBuf::from(s)))
        }
    }

    /// Get the inner path
    pub fn as_path(&self) -> &Path {
        &self.0
    }

    /// Get the inner PathBuf (consuming)
    pub fn into_path_buf(self) -> PathBuf {
        self.0
    }

    /// Join with another path component
    ///
    /// **Poka-yoke**: Result is guaranteed non-empty (base path is non-empty)
    pub fn join(&self, path: impl AsRef<Path>) -> NonEmptyPath {
        // Safety: Base path is non-empty, so result is non-empty
        NonEmptyPath(self.0.join(path))
    }
}

impl std::str::FromStr for NonEmptyPath {
    type Err = EmptyPathError;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        if s.is_empty() {
            Err(EmptyPathError)
        } else {
            Ok(Self(PathBuf::from(s)))
        }
    }
}

impl AsRef<Path> for NonEmptyPath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

impl std::fmt::Display for NonEmptyPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

// ============================================================================
// NON-EMPTY STRING TYPE
// ============================================================================

/// String that is guaranteed to be non-empty at type level
///
/// **Poka-yoke**: Type system prevents empty strings. Cannot construct a
/// `NonEmptyString` from an empty string.
///
/// # Invariants
/// - Inner string is never empty (enforced at construction)
/// - Type system prevents using empty strings where non-empty required
///
/// # Example
///
/// ```rust
/// use crate::lifecycle::poka_yoke::NonEmptyString;
///
/// // ✅ Valid: Non-empty string
/// let s = NonEmptyString::new("hello".to_string()).unwrap();
/// assert_eq!(s.as_str(), "hello");
///
/// // ❌ Invalid: Empty string rejected at construction
/// let empty = NonEmptyString::new("".to_string());
/// assert!(empty.is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct NonEmptyString(String);

/// Error type for empty string construction
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmptyStringError;

impl std::fmt::Display for EmptyStringError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "String cannot be empty")
    }
}

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

impl NonEmptyString {
    /// Create a new non-empty string
    ///
    /// Returns `Err(EmptyStringError)` if string is empty.
    ///
    /// **Poka-yoke**: Empty strings rejected at construction.
    pub fn new(s: String) -> std::result::Result<Self, EmptyStringError> {
        if s.is_empty() {
            Err(EmptyStringError)
        } else {
            Ok(Self(s))
        }
    }

    /// Get the inner string
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Get the inner String (consuming)
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for NonEmptyString {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for NonEmptyString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ============================================================================
// BOUNDED INTEGER TYPES
// ============================================================================

/// Unsigned counter that uses saturating arithmetic
///
/// **Poka-yoke**: Cannot be negative (uses `u32`), cannot overflow (saturating arithmetic).
///
/// # Invariants
/// - Value is always >= 0 (enforced by type)
/// - Increment/decrement use saturating arithmetic (overflow/underflow prevented)
///
/// # Example
///
/// ```rust
/// use crate::lifecycle::poka_yoke::Counter;
///
/// let mut counter = Counter::new(0);
/// counter.increment();  // Safe - cannot overflow
/// assert_eq!(counter.get(), 1);
///
/// counter.decrement();  // Safe - cannot underflow (saturates at 0)
/// assert_eq!(counter.get(), 0);
///
/// counter.decrement();  // Saturates at 0
/// assert_eq!(counter.get(), 0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Counter {
    value: u32, // Poka-yoke: u32 prevents negative values
}

impl Counter {
    /// Create a new counter with initial value
    ///
    /// **Poka-yoke**: Takes `u32`, cannot be negative.
    pub fn new(value: u32) -> Self {
        Self { value }
    }

    /// Increment counter (saturating)
    ///
    /// **Poka-yoke**: Saturating add prevents overflow.
    pub fn increment(&mut self) {
        self.value = self.value.saturating_add(1);
    }

    /// Decrement counter (saturating)
    ///
    /// **Poka-yoke**: Saturating sub prevents underflow.
    pub fn decrement(&mut self) {
        self.value = self.value.saturating_sub(1);
    }

    /// Add to counter (saturating)
    pub fn add(&mut self, n: u32) {
        self.value = self.value.saturating_add(n);
    }

    /// Subtract from counter (saturating)
    pub fn sub(&mut self, n: u32) {
        self.value = self.value.saturating_sub(n);
    }

    /// Get current value
    pub fn get(&self) -> u32 {
        self.value
    }

    /// Reset counter to zero
    pub fn reset(&mut self) {
        self.value = 0;
    }
}

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

// ============================================================================
// TYPE-LEVEL FILE HANDLE STATES (OPTIONAL ENHANCEMENT)
// ============================================================================

use std::marker::PhantomData;

/// File handle in Open state
pub struct Open;

/// File handle in Closed state
pub struct Closed;

/// Type-level file handle that prevents use-after-close errors
///
/// **Poka-yoke**: Type system prevents reading from closed files.
/// Methods like `read()` only exist on `FileHandle<Open>`, not `FileHandle<Closed>`.
///
/// # Example
///
/// ```no_run
/// use crate::lifecycle::poka_yoke::{FileHandle, Open};
/// use std::path::Path;
///
/// // Open file (type: FileHandle<Open>)
/// let mut file = FileHandle::<Open>::open(Path::new("test.txt")).unwrap();
///
/// // Can read when open
/// let data = file.read().unwrap();
///
/// // Close file (consumes FileHandle<Open>, returns FileHandle<Closed>)
/// let closed = file.close();
///
/// // ❌ Compile error: cannot read from closed file
/// // closed.read(); // Method doesn't exist on FileHandle<Closed>
/// ```
#[derive(Debug)]
pub struct FileHandle<State> {
    file: std::fs::File,
    _state: PhantomData<State>,
}

impl FileHandle<Open> {
    /// Open a file in read mode
    ///
    /// Returns `FileHandle<Open>` - type system knows file is open.
    pub fn open(path: &Path) -> Result<Self> {
        let file = std::fs::File::open(path)?;
        Ok(Self {
            file,
            _state: PhantomData,
        })
    }

    /// Read entire file contents
    ///
    /// **Poka-yoke**: Only available on `FileHandle<Open>` - cannot call on closed file.
    pub fn read(&mut self) -> Result<Vec<u8>> {
        use std::io::Read;
        let mut buffer = Vec::new();
        self.file.read_to_end(&mut buffer)?;
        Ok(buffer)
    }

    /// Close the file
    ///
    /// **Poka-yoke**: Consumes `FileHandle<Open>`, returns `FileHandle<Closed>`.
    /// After calling this, cannot call `read()` - type system prevents it.
    pub fn close(self) -> FileHandle<Closed> {
        FileHandle {
            file: self.file,
            _state: PhantomData,
        }
    }
}

impl FileHandle<Closed> {
    // No methods available - cannot read from closed file!
    // **Poka-yoke**: Compiler prevents calling `read()` on closed file.
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_non_empty_path_valid() {
        let path = NonEmptyPath::new(PathBuf::from("test.txt")).unwrap();
        assert_eq!(path.as_path(), Path::new("test.txt"));
    }

    #[test]
    fn test_non_empty_path_empty_rejected() {
        let empty = NonEmptyPath::new(PathBuf::from(""));
        assert!(empty.is_err());
        assert_eq!(empty.unwrap_err(), EmptyPathError);
    }

    #[test]
    fn test_non_empty_path_join() {
        let base: NonEmptyPath = "base".parse().unwrap();
        let joined = base.join("file.txt");
        assert!(joined.as_path().to_str().unwrap().contains("base"));
        assert!(joined.as_path().to_str().unwrap().contains("file.txt"));
    }

    #[test]
    fn test_non_empty_string_valid() {
        let s = NonEmptyString::new("hello".to_string()).unwrap();
        assert_eq!(s.as_str(), "hello");
    }

    #[test]
    fn test_non_empty_string_empty_rejected() {
        let empty = NonEmptyString::new("".to_string());
        assert!(empty.is_err());
        assert_eq!(empty.unwrap_err(), EmptyStringError);
    }

    #[test]
    fn test_counter_cannot_be_negative() {
        let mut counter = Counter::new(0);
        counter.decrement(); // Saturates at 0
        assert_eq!(counter.get(), 0);

        counter.decrement(); // Still 0
        assert_eq!(counter.get(), 0);
    }

    #[test]
    fn test_counter_cannot_overflow() {
        let mut counter = Counter::new(u32::MAX);
        counter.increment(); // Saturates at MAX
        assert_eq!(counter.get(), u32::MAX);
    }

    #[test]
    fn test_counter_normal_operations() {
        let mut counter = Counter::new(5);
        counter.increment();
        assert_eq!(counter.get(), 6);

        counter.decrement();
        assert_eq!(counter.get(), 5);

        counter.add(10);
        assert_eq!(counter.get(), 15);

        counter.sub(5);
        assert_eq!(counter.get(), 10);

        counter.reset();
        assert_eq!(counter.get(), 0);
    }

    #[test]
    fn test_file_handle_type_safety() {
        // This test demonstrates compile-time safety (cannot actually run without files)
        // The important part is that this compiles and shows correct types

        // Type annotations show type-level state
        let _open_handle: Result<FileHandle<Open>> = FileHandle::open(Path::new("nonexistent"));

        // If we had an open handle, we could:
        // let mut open = open_handle.unwrap();
        // let _data = open.read(); // ✅ Valid - file is open

        // After closing:
        // let closed = open.close();
        // closed.read(); // ❌ Compile error - method doesn't exist
    }

    // Compile-time error test (uncomment to verify it fails to compile)
    // #[test]
    // fn test_invalid_transition_compile_error() {
    //     use tempfile::TempDir;
    //     let temp = TempDir::new().unwrap();
    //     let path = temp.path().join("test.txt");
    //     std::fs::write(&path, b"test").unwrap();
    //
    //     let file = FileHandle::<Open>::open(&path).unwrap();
    //     let closed = file.close();
    //     closed.read(); // ❌ Should fail to compile: method `read` not found
    // }
}