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
//! Numeric literal parsing and validation for Lambdust.
//!
//! This module provides comprehensive parsing and validation for all numeric
//! formats supported by R7RS Scheme, including:
//! - Integers (decimal, binary, octal, hexadecimal)
//! - Real numbers (floats with optional exponents)
//! - Rational numbers (exact fractions)
//! - Complex numbers (rectangular and polar forms)
//!
//! The parsing follows R7RS numeric syntax precisely while providing
//! detailed error reporting for invalid formats.

use crate::diagnostics::{Error, Result, Span};

/// Validates an integer literal according to R7RS syntax.
pub fn validate_integer(text: &str, span: Span) -> Result<()> {
    if text.is_empty() {
        return Err(Box::new(Error::lex_error("Empty integer literal", span)))
    }

    let text = text.trim();
    
    // Handle sign
    let (_sign_len, unsigned) = match text.chars().next() {
        Some('+') | Some('-') => (1, &text[1..]),
        _ => (0, text),
    };

    if unsigned.is_empty() {
        return Err(Box::new(Error::lex_error("Integer literal cannot be just a sign", span)))
    }

    // Check for different number bases
    if unsigned.starts_with("0x") || unsigned.starts_with("0X") {
        // Hexadecimal
        let hex_digits = &unsigned[2..];
        if hex_digits.is_empty() {
            return Err(Box::new(Error::lex_error("Hexadecimal literal must have digits after 0x", span)))
        }
        for ch in hex_digits.chars() {
            if !ch.is_ascii_hexdigit() {
                return Err(Box::new(Error::lex_error(
                    format!("Invalid hexadecimal digit: '{ch}'"), 
                    span
                )))
            }
        }
    } else if unsigned.starts_with("0b") || unsigned.starts_with("0B") {
        // Binary
        let bin_digits = &unsigned[2..];
        if bin_digits.is_empty() {
            return Err(Box::new(Error::lex_error("Binary literal must have digits after 0b", span)))
        }
        for ch in bin_digits.chars() {
            if !matches!(ch, '0' | '1') {
                return Err(Box::new(Error::lex_error(
                    format!("Invalid binary digit: '{ch}'"), 
                    span
                )))
            }
        }
    } else if unsigned.starts_with("0o") || unsigned.starts_with("0O") {
        // Octal
        let oct_digits = &unsigned[2..];
        if oct_digits.is_empty() {
            return Err(Box::new(Error::lex_error("Octal literal must have digits after 0o", span)))
        }
        for ch in oct_digits.chars() {
            if !('0'..='7').contains(&ch) {
                return Err(Box::new(Error::lex_error(
                    format!("Invalid octal digit: '{ch}'"), 
                    span
                )))
            }
        }
    } else {
        // Decimal
        for ch in unsigned.chars() {
            if !ch.is_ascii_digit() {
                return Err(Box::new(Error::lex_error(
                    format!("Invalid decimal digit: '{ch}'"), 
                    span
                )))
            }
        }
    }

    Ok(())
}

/// Validates a real (floating-point) number literal according to R7RS syntax.
pub fn validate_real(text: &str, span: Span) -> Result<()> {
    if text.is_empty() {
        return Err(Box::new(Error::lex_error("Empty real number literal", span)))
    }

    let text = text.trim();
    
    // Handle sign
    let unsigned = match text.chars().next() {
        Some('+') | Some('-') => &text[1..],
        _ => text,
    };

    if unsigned.is_empty() {
        return Err(Box::new(Error::lex_error("Real number literal cannot be just a sign", span)))
    }

    // Check for scientific notation
    let (mantissa, exponent) = if let Some(e_pos) = unsigned.find(['e', 'E']) {
        let mantissa = &unsigned[..e_pos];
        let exponent = &unsigned[e_pos + 1..];
        
        if exponent.is_empty() {
            return Err(Box::new(Error::lex_error("Exponent cannot be empty", span)))
        }
        
        // Validate exponent (must be integer)
        let exp_unsigned = match exponent.chars().next() {
            Some('+') | Some('-') => &exponent[1..],
            _ => exponent,
        };
        
        if exp_unsigned.is_empty() {
            return Err(Box::new(Error::lex_error("Exponent cannot be just a sign", span)))
        }
        
        for ch in exp_unsigned.chars() {
            if !ch.is_ascii_digit() {
                return Err(Box::new(Error::lex_error(
                    format!("Invalid digit in exponent: '{ch}'"), 
                    span
                )))
            }
        }
        
        (mantissa, Some(exponent))
    } else {
        (unsigned, None)
    };

    // Validate mantissa
    if mantissa.is_empty() {
        return Err(Box::new(Error::lex_error("Mantissa cannot be empty", span)))
    }

    let dot_count = mantissa.matches('.').count();
    if dot_count > 1 {
        return Err(Box::new(Error::lex_error("Real number cannot have multiple decimal points", span)))
    }

    if dot_count == 0 && exponent.is_none() {
        return Err(Box::new(Error::lex_error("Real number must have decimal point or exponent", span)))
    }

    // Check that all characters are digits or decimal point
    for ch in mantissa.chars() {
        if !ch.is_ascii_digit() && ch != '.' {
            return Err(Box::new(Error::lex_error(
                format!("Invalid character in real number: '{ch}'"), 
                span
            )))
        }
    }

    // Ensure there's at least one digit
    if !mantissa.chars().any(|c| c.is_ascii_digit()) {
        return Err(Box::new(Error::lex_error("Real number must contain at least one digit", span)))
    }

    Ok(())
}

/// Validates a rational number literal according to R7RS syntax.
pub fn validate_rational(text: &str, span: Span) -> Result<()> {
    if text.is_empty() {
        return Err(Box::new(Error::lex_error("Empty rational number literal", span)))
    }

    let text = text.trim();
    
    // Handle sign
    let unsigned = match text.chars().next() {
        Some('+') | Some('-') => &text[1..],
        _ => text,
    };

    if unsigned.is_empty() {
        return Err(Box::new(Error::lex_error("Rational number literal cannot be just a sign", span)))
    }

    // Split on '/'
    let parts: Vec<&str> = unsigned.split('/').collect();
    if parts.len() != 2 {
        return Err(Box::new(Error::lex_error("Rational number must have exactly one '/' character", span)))
    }

    let numerator = parts[0];
    let denominator = parts[1];

    // Validate numerator
    if numerator.is_empty() {
        return Err(Box::new(Error::lex_error("Rational number numerator cannot be empty", span)))
    }
    
    for ch in numerator.chars() {
        if !ch.is_ascii_digit() {
            return Err(Box::new(Error::lex_error(
                format!("Invalid digit in numerator: '{ch}'"), 
                span
            )))
        }
    }

    // Validate denominator
    if denominator.is_empty() {
        return Err(Box::new(Error::lex_error("Rational number denominator cannot be empty", span)))
    }
    
    if denominator == "0" {
        return Err(Box::new(Error::lex_error("Rational number denominator cannot be zero", span)))
    }
    
    for ch in denominator.chars() {
        if !ch.is_ascii_digit() {
            return Err(Box::new(Error::lex_error(
                format!("Invalid digit in denominator: '{ch}'"), 
                span
            )))
        }
    }

    Ok(())
}

/// Validates a complex number literal according to R7RS syntax.
pub fn validate_complex(text: &str, span: Span) -> Result<()> {
    if text.is_empty() {
        return Err(Box::new(Error::lex_error("Empty complex number literal", span)))
    }

    let text = text.trim();

    // Handle special cases: +i, -i, i
    if text == "i" || text == "+i" || text == "-i" {
        return Ok(());
    }

    if !text.ends_with('i') {
        return Err(Box::new(Error::lex_error("Complex number must end with 'i'", span)))
    }

    let without_i = &text[..text.len() - 1];
    
    // Find the position of + or - that separates real and imaginary parts
    // We need to be careful not to match the sign at the beginning
    let mut split_pos = None;
    let mut depth = 0;
    
    for (i, ch) in without_i.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth -= 1,
            '+' | '-' if depth == 0 && i > 0 => {
                // Check if this is not part of an exponent
                let prev_chars: Vec<char> = without_i[..i].chars().rev().take(2).collect();
                if !prev_chars.is_empty() && matches!(prev_chars[0], 'e' | 'E') {
                    continue; // This is an exponent sign
                }
                split_pos = Some(i);
                break;
            }
            _ => {}
        }
    }

    if let Some(pos) = split_pos {
        // Has both real and imaginary parts
        let real_part = &without_i[..pos];
        let imag_part = &without_i[pos..];
        
        // Validate real part
        if !real_part.is_empty() {
            if real_part.contains('.') || real_part.contains(['e', 'E']) {
                validate_real(real_part, span)?;
            } else if real_part.contains('/') {
                validate_rational(real_part, span)?;
            } else {
                validate_integer(real_part, span)?;
            }
        }
        
        // Validate imaginary part (without the sign)
        let imag_unsigned = if imag_part.starts_with(['+', '-']) {
            &imag_part[1..]
        } else {
            imag_part
        };
        
        if !imag_unsigned.is_empty() {
            if imag_unsigned.contains('.') || imag_unsigned.contains(['e', 'E']) {
                validate_real(&format!("{}{}",
                    if imag_part.starts_with(['+', '-']) { &imag_part[..1] } else { "" },
                    imag_unsigned
                ), span)?;
            } else if imag_unsigned.contains('/') {
                validate_rational(&format!("{}{}",
                    if imag_part.starts_with(['+', '-']) { &imag_part[..1] } else { "" },
                    imag_unsigned
                ), span)?;
            } else {
                validate_integer(&format!("{}{}",
                    if imag_part.starts_with(['+', '-']) { &imag_part[..1] } else { "" },
                    imag_unsigned
                ), span)?;
            }
        }
    } else {
        // Only imaginary part
        if without_i.is_empty() {
            return Err(Box::new(Error::lex_error("Complex number 'i' must have a coefficient", span)))
        }
        
        // Validate the coefficient
        if without_i.contains('.') || without_i.contains(['e', 'E']) {
            validate_real(without_i, span)?;
        } else if without_i.contains('/') {
            validate_rational(without_i, span)?;
        } else {
            validate_integer(without_i, span)?;
        }
    }

    Ok(())
}

/// Parses an integer literal into its numeric value.
pub fn parse_integer(text: &str) -> Option<i64> {
    let text = text.trim();
    
    // Handle different bases
    if text.starts_with("0x") || text.starts_with("0X") {
        i64::from_str_radix(&text[2..], 16).ok()
    } else if text.starts_with("0b") || text.starts_with("0B") {
        i64::from_str_radix(&text[2..], 2).ok()
    } else if text.starts_with("0o") || text.starts_with("0O") {
        i64::from_str_radix(&text[2..], 8).ok()
    } else {
        text.parse().ok()
    }
}

/// Parses a real number literal into its numeric value.
pub fn parse_real(text: &str) -> Option<f64> {
    text.trim().parse().ok()
}

/// Represents a rational number as numerator/denominator.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rational {
    pub numerator: i64,
    pub denominator: u64,
}

impl Rational {
    /// Creates a new rational number, automatically reducing to lowest terms.
    pub fn new(numerator: i64, denominator: u64) -> Option<Self> {
        if denominator == 0 {
            return None;
        }
        
        let gcd = gcd(numerator.unsigned_abs(), denominator);
        Some(Self {
            numerator: numerator / gcd as i64,
            denominator: denominator / gcd,
        })
    }
    
    /// Converts to floating point approximation.
    pub fn to_f64(&self) -> f64 {
        self.numerator as f64 / self.denominator as f64
    }
}

/// Parses a rational number literal.
pub fn parse_rational(text: &str) -> Option<Rational> {
    let text = text.trim();
    
    let (sign, unsigned) = match text.chars().next() {
        Some('-') => (-1, &text[1..]),
        Some('+') => (1, &text[1..]),
        _ => (1, text),
    };
    
    let parts: Vec<&str> = unsigned.split('/').collect();
    if parts.len() != 2 {
        return None;
    }
    
    let numerator: u64 = parts[0].parse().ok()?;
    let denominator: u64 = parts[1].parse().ok()?;
    
    Rational::new(sign * numerator as i64, denominator)
}

/// Represents a complex number.
#[derive(Debug, Clone, PartialEq)]
pub struct Complex {
    pub real: f64,
    pub imag: f64,
}

impl Complex {
    /// Creates a new complex number.
    pub fn new(real: f64, imag: f64) -> Self {
        Self { real, imag }
    }
    
    /// Creates a purely imaginary number.
    pub fn imaginary(imag: f64) -> Self {
        Self::new(0.0, imag)
    }
    
    /// Creates a purely real number.
    pub fn real(real: f64) -> Self {
        Self::new(real, 0.0)
    }
}

/// Parses a complex number literal.
pub fn parse_complex(text: &str) -> Option<Complex> {
    let text = text.trim();
    
    // Handle special cases
    match text {
        "i" => return Some(Complex::imaginary(1.0)),
        "+i" => return Some(Complex::imaginary(1.0)),
        "-i" => return Some(Complex::imaginary(-1.0)),
        _ => {}
    }
    
    if !text.ends_with('i') {
        return None;
    }
    
    let without_i = &text[..text.len() - 1];
    
    // Find split position for real and imaginary parts
    let mut split_pos = None;
    for (i, ch) in without_i.char_indices() {
        if matches!(ch, '+' | '-') && i > 0 {
            // Check if this is not part of an exponent
            let prev_char = without_i.chars().nth(i - 1)?;
            if !matches!(prev_char, 'e' | 'E') {
                split_pos = Some(i);
                break;
            }
        }
    }
    
    if let Some(pos) = split_pos {
        // Both real and imaginary parts
        let real_part = &without_i[..pos];
        let imag_part = &without_i[pos..];
        
        let real = if real_part.is_empty() {
            0.0
        } else {
            real_part.parse().ok()?
        };
        
        let imag = if imag_part == "+" {
            1.0
        } else if imag_part == "-" {
            -1.0
        } else {
            imag_part.parse().ok()?
        };
        
        Some(Complex::new(real, imag))
    } else {
        // Only imaginary part
        let imag = if without_i.is_empty() {
            1.0
        } else {
            without_i.parse().ok()?
        };
        
        Some(Complex::imaginary(imag))
    }
}

/// Computes the greatest common divisor using Euclid's algorithm.
fn gcd(a: u64, b: u64) -> u64 {
    if b == 0 {
        a
    } else {
        gcd(b, a % b)
    }
}

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

    #[test]
    fn test_integer_validation() {
        let span = Span::new(0, 3);
        
        assert!(validate_integer("123", span).is_ok());
        assert!(validate_integer("+123", span).is_ok());
        assert!(validate_integer("-123", span).is_ok());
        assert!(validate_integer("0x1F", span).is_ok());
        assert!(validate_integer("0b1010", span).is_ok());
        assert!(validate_integer("0o777", span).is_ok());
        
        assert!(validate_integer("", span).is_err());
        assert!(validate_integer("+", span).is_err());
        assert!(validate_integer("12.3", span).is_err());
        assert!(validate_integer("0xGG", span).is_err());
    }

    #[test]
    fn test_real_validation() {
        let span = Span::new(0, 5);
        
        assert!(validate_real("123.45", span).is_ok());
        assert!(validate_real(".123", span).is_ok());
        assert!(validate_real("123.", span).is_ok());
        assert!(validate_real("1e10", span).is_ok());
        assert!(validate_real("1.23e-4", span).is_ok());
        assert!(validate_real("+1.23", span).is_ok());
        assert!(validate_real("-1.23", span).is_ok());
        
        assert!(validate_real("", span).is_err());
        assert!(validate_real("123", span).is_err()); // No decimal point or exponent
        assert!(validate_real("1.2.3", span).is_err());
        assert!(validate_real("1e", span).is_err());
    }

    #[test]
    fn test_rational_validation() {
        let span = Span::new(0, 5);
        
        assert!(validate_rational("1/2", span).is_ok());
        assert!(validate_rational("22/7", span).is_ok());
        assert!(validate_rational("+3/4", span).is_ok());
        assert!(validate_rational("-5/6", span).is_ok());
        
        assert!(validate_rational("", span).is_err());
        assert!(validate_rational("1/0", span).is_err());
        assert!(validate_rational("1/", span).is_err());
        assert!(validate_rational("/2", span).is_err());
        assert!(validate_rational("1/2/3", span).is_err());
    }

    #[test]
    fn test_complex_validation() {
        let span = Span::new(0, 5);
        
        assert!(validate_complex("3+4i", span).is_ok());
        assert!(validate_complex("3-4i", span).is_ok());
        assert!(validate_complex("3i", span).is_ok());
        assert!(validate_complex("+3i", span).is_ok());
        assert!(validate_complex("-3i", span).is_ok());
        assert!(validate_complex("i", span).is_ok());
        assert!(validate_complex("+i", span).is_ok());
        assert!(validate_complex("-i", span).is_ok());
        assert!(validate_complex("1.5+2.5i", span).is_ok());
        
        assert!(validate_complex("", span).is_err());
        assert!(validate_complex("3+4", span).is_err()); // No 'i'
    }

    #[test]
    fn test_integer_parsing() {
        assert_eq!(parse_integer("123"), Some(123));
        assert_eq!(parse_integer("-123"), Some(-123));
        assert_eq!(parse_integer("0x1F"), Some(31));
        assert_eq!(parse_integer("0b1010"), Some(10));
        assert_eq!(parse_integer("0o10"), Some(8));
        
        assert_eq!(parse_integer("invalid"), None);
    }

    #[test]
    fn test_rational_parsing() {
        assert_eq!(parse_rational("1/2"), Some(Rational::new(1, 2).unwrap()));
        assert_eq!(parse_rational("6/9"), Some(Rational::new(2, 3).unwrap())); // Reduced
        assert_eq!(parse_rational("-3/4"), Some(Rational::new(-3, 4).unwrap()));
        
        assert_eq!(parse_rational("invalid"), None);
        assert_eq!(parse_rational("1/0"), None);
    }

    #[test]
    fn test_complex_parsing() {
        assert_eq!(parse_complex("3+4i"), Some(Complex::new(3.0, 4.0)));
        assert_eq!(parse_complex("3-4i"), Some(Complex::new(3.0, -4.0)));
        assert_eq!(parse_complex("3i"), Some(Complex::new(0.0, 3.0)));
        assert_eq!(parse_complex("i"), Some(Complex::new(0.0, 1.0)));
        assert_eq!(parse_complex("-i"), Some(Complex::new(0.0, -1.0)));
        
        assert_eq!(parse_complex("invalid"), None);
    }

    #[test]
    fn test_gcd() {
        assert_eq!(gcd(12, 8), 4);
        assert_eq!(gcd(17, 13), 1);
        assert_eq!(gcd(100, 25), 25);
    }
}