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
#![allow(unused_variables)]
//! Regular expression engine for SRFI-135 Text processing.
//!
//! This module implements a PCRE-compatible regular expression engine
//! with Unicode support, named capture groups, and efficient matching.

use crate::diagnostics::{Error as DiagnosticError, Result};
use crate::eval::value::{Value, PrimitiveProcedure, PrimitiveImpl, ThreadSafeEnvironment};
use crate::effects::Effect;
use crate::stdlib::text::Text;
use std::sync::Arc;
// use regex::Captures; // Removed external regex dependency
use crate::regex::compat::{LightRegex, Captures as LightCaptures};
use std::collections::HashMap;

// ============= REGEX ENGINE =============

/// Regular expression compiled for text processing.
/// Note: This is a simplified implementation. Full regex support
/// would require the regex crate.
#[derive(Debug, Clone)]
pub struct TextRegex {
    /// Original pattern string
    pattern: String,
    /// Regex flags
    flags: RegexFlags,
    /// Compiled regex using internal engine
    regex: LightRegex,
}

/// Regular expression compilation flags.
#[derive(Debug, Clone, Copy)]
pub struct RegexFlags {
    /// Case-insensitive matching
    pub case_insensitive: bool,
    /// Multi-line mode (^ and $ match line boundaries)
    pub multiline: bool,
    /// Dot matches newline
    pub dot_matches_newline: bool,
    /// Unicode mode (default true)
    pub unicode: bool,
    /// Extended syntax (ignore whitespace and comments)
    pub extended: bool,
    /// Swap greed of quantifiers
    pub swap_greed: bool,
}

/// Match result from regex operations.
#[derive(Debug, Clone)]
pub struct TextMatchResult {
    /// The matched text
    pub matched_text: Text,
    /// Start position (character index)
    pub start: usize,
    /// End position (character index)
    pub end: usize,
    /// Captured groups (indexed)
    pub groups: Vec<Option<Text>>,
    /// Named capture groups
    pub named_groups: HashMap<String, Option<Text>>,
}

/// Match iterator for finding all matches.
pub struct TextMatchIter<'t> {
    regex: &'t TextRegex,
    text: &'t Text,
    last_end: usize,
}

impl TextRegex {
    /// Compiles a regular expression with default flags.
    /// Note: This is a simplified implementation without actual regex compilation.
    pub fn new(pattern: &str) -> Result<Self> {
        Self::with_flags(pattern, RegexFlags::default())
    }

    /// Compiles a regular expression with specific flags.
    /// Note: Uses internal lightweight regex engine.
    pub fn with_flags(pattern: &str, flags: RegexFlags) -> Result<Self> {
        // Build regex with flags using internal engine
        let builder = crate::regex::compat::RegexBuilder::new(pattern)
            .case_insensitive(flags.case_insensitive)
            .multi_line(flags.multiline)
            .dot_matches_new_line(flags.dot_matches_newline)
            .unicode(flags.unicode);
        
        let regex = builder.build().map_err(|e| DiagnosticError::runtime_error(
            format!("Invalid regex pattern: {e}"),
            None
        ))?;
        
        Ok(Self {
            pattern: pattern.to_string(),
            flags,
            regex,
        })
    }

    /// Gets the original pattern string.
    pub fn pattern(&self) -> &str {
        &self.pattern
    }

    /// Gets the regex flags.
    pub fn flags(&self) -> RegexFlags {
        self.flags
    }

    /// Tests if the pattern matches anywhere in the text.
    /// Note: Uses internal lightweight regex engine.
    pub fn is_match(&self, text: &Text) -> bool {
        let text_str = text.to_string();
        self.regex.is_match(&text_str)
    }

    /// Finds the first match in the text.
    /// Note: Uses internal lightweight regex engine.
    pub fn find(&self, text: &Text) -> Option<TextMatchResult> {
        let text_str = text.to_string();
        if let Some(m) = self.regex.find(&text_str) {
            let start_char = text_str[..m.start()].chars().count();
            let end_char = text_str[..m.end()].chars().count();
            let matched_text = text.substring(start_char, end_char)?;
            
            Some(TextMatchResult {
                matched_text,
                start: start_char,
                end: end_char,
                groups: vec![],
                named_groups: HashMap::new(),
            })
        } else {
            None
        }
    }

    /// Finds all matches in the text.
    pub fn find_all(&self, text: &Text) -> Vec<TextMatchResult> {
        let text_str = text.to_string();
        self.regex
            .find_iter(&text_str)
            .filter_map(|m| {
                let start_char = text_str[..m.start()].chars().count();
                let end_char = text_str[..m.end()].chars().count();
                let matched_text = text.substring(start_char, end_char)?;
                
                Some(TextMatchResult {
                    matched_text,
                    start: start_char,
                    end: end_char,
                    groups: vec![],
                    named_groups: HashMap::new(),
                })
            })
            .collect()
    }

    /// Creates an iterator over all matches.
    pub fn find_iter<'t>(&'t self, text: &'t Text) -> TextMatchIter<'t> {
        TextMatchIter {
            regex: self,
            text,
            last_end: 0,
        }
    }

    /// Replaces the first match with replacement text.
    pub fn replace(&self, text: &Text, replacement: &Text) -> Text {
        let text_str = text.to_string();
        let replacement_str = replacement.to_string();
        let result = self.regex.replace(&text_str, &replacement_str);
        Text::from_string(result.into_owned())
    }

    /// Replaces all matches with replacement text.
    pub fn replace_all(&self, text: &Text, replacement: &Text) -> Text {
        let text_str = text.to_string();
        let replacement_str = replacement.to_string();
        let result = self.regex.replace_all(&text_str, &replacement_str);
        Text::from_string(result.into_owned())
    }

    /// Replaces matches using a callback function.
    pub fn replace_all_with<F>(&self, text: &Text, replacer: F) -> Text
    where
        F: Fn(&TextMatchResult) -> Text,
    {
        let text_str = text.to_string();
        let result = self.regex.replace_all_fn(&text_str, |m| {
            let start_char = text_str[..m.start()].chars().count();
            let end_char = text_str[..m.end()].chars().count();
            if let Some(matched_text) = text.substring(start_char, end_char) {
                let match_result = TextMatchResult {
                    matched_text: matched_text.clone(),
                    start: start_char,
                    end: end_char,
                    groups: vec![],
                    named_groups: HashMap::new(),
                };
                replacer(&match_result).to_string()
            } else {
                String::new()
            }
        });
        
        Text::from_string(result.into_owned())
    }

    /// Splits the text by the regex pattern.
    pub fn split(&self, text: &Text) -> Vec<Text> {
        let text_str = text.to_string();
        self.regex
            .split(&text_str)
            .map(|part| Text::from_string(part.to_string()))
            .collect()
    }

    /// Splits the text by the regex pattern with limit.
    pub fn splitn(&self, text: &Text, limit: usize) -> Vec<Text> {
        let text_str = text.to_string();
        self.regex
            .splitn(&text_str, limit)
            .map(|part| Text::from_string(part.to_string()))
            .collect()
    }

    // captures_to_match_result method removed - no longer needed with internal engine
}

impl<'t> Iterator for TextMatchIter<'t> {
    type Item = TextMatchResult;

    fn next(&mut self) -> Option<Self::Item> {
        if self.last_end > self.text.char_length() {
            return None;
        }

        let remaining_text = self.text.substring(self.last_end, self.text.char_length())?;
        let match_result = self.regex.find(&remaining_text)?;
        
        // Adjust positions to be relative to original text
        let adjusted_result = TextMatchResult {
            matched_text: match_result.matched_text,
            start: match_result.start + self.last_end,
            end: match_result.end + self.last_end,
            groups: match_result.groups,
            named_groups: match_result.named_groups,
        };
        
        self.last_end = adjusted_result.end;
        Some(adjusted_result)
    }
}

impl Default for RegexFlags {
    fn default() -> Self {
        Self {
            case_insensitive: false,
            multiline: false,
            dot_matches_newline: false,
            unicode: true,
            extended: false,
            swap_greed: false,
        }
    }
}

impl RegexFlags {
    /// Creates flags for case-insensitive matching.
    pub fn case_insensitive() -> Self {
        Self {
            case_insensitive: true,
            ..Default::default()
        }
    }

    /// Creates flags for multiline matching.
    pub fn multiline() -> Self {
        Self {
            multiline: true,
            ..Default::default()
        }
    }

    /// Creates flags with all common options enabled.
    pub fn extended() -> Self {
        Self {
            case_insensitive: true,
            multiline: true,
            dot_matches_newline: true,
            unicode: true,
            extended: true,
            swap_greed: false,
        }
    }
}

// ============= SCHEME BINDINGS =============

/// Creates regex operation bindings for the standard library.
pub fn create_regex_bindings(env: &Arc<ThreadSafeEnvironment>) {
    // Regex compilation
    bind_regex_construction(env);
    
    // Pattern matching
    bind_regex_matching(env);
    
    // Text replacement
    bind_regex_replacement(env);
    
    // Text splitting
    bind_regex_splitting(env);
}

/// Binds regex construction operations.
fn bind_regex_construction(env: &Arc<ThreadSafeEnvironment>) {
    // regex-compile
    env.define("regex-compile".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-compile".to_string(),
        arity_min: 1,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_regex_compile),
        effects: vec![Effect::Pure],
    })));
    
    // regex-compile-ci (case-insensitive)
    env.define("regex-compile-ci".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-compile-ci".to_string(),
        arity_min: 1,
        arity_max: Some(1),
        implementation: PrimitiveImpl::RustFn(primitive_regex_compile_ci),
        effects: vec![Effect::Pure],
    })));
}

/// Binds regex matching operations.
fn bind_regex_matching(env: &Arc<ThreadSafeEnvironment>) {
    // regex-match?
    env.define("regex-match?".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-match?".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_regex_match_p),
        effects: vec![Effect::Pure],
    })));
    
    // regex-search
    env.define("regex-search".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-search".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_regex_search),
        effects: vec![Effect::Pure],
    })));
    
    // regex-search-all
    env.define("regex-search-all".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-search-all".to_string(),
        arity_min: 2,
        arity_max: Some(2),
        implementation: PrimitiveImpl::RustFn(primitive_regex_search_all),
        effects: vec![Effect::Pure],
    })));
}

/// Binds regex replacement operations.
fn bind_regex_replacement(env: &Arc<ThreadSafeEnvironment>) {
    // regex-replace
    env.define("regex-replace".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-replace".to_string(),
        arity_min: 3,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_regex_replace),
        effects: vec![Effect::Pure],
    })));
    
    // regex-replace-all
    env.define("regex-replace-all".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-replace-all".to_string(),
        arity_min: 3,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_regex_replace_all),
        effects: vec![Effect::Pure],
    })));
}

/// Binds regex splitting operations.
fn bind_regex_splitting(env: &Arc<ThreadSafeEnvironment>) {
    // regex-split
    env.define("regex-split".to_string(), Value::Primitive(Arc::new(PrimitiveProcedure {
        name: "regex-split".to_string(),
        arity_min: 2,
        arity_max: Some(3),
        implementation: PrimitiveImpl::RustFn(primitive_regex_split),
        effects: vec![Effect::Pure],
    })));
}

// ============= PRIMITIVE IMPLEMENTATIONS =============

/// regex-compile operation
fn primitive_regex_compile(args: &[Value]) -> Result<Value> {
    if args.is_empty() || args.len() > 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-compile expects 1-2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-compile pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let flags = if args.len() > 1 {
        // Parse flags from string or other representation
        RegexFlags::default() // Simplified for now
    } else {
        RegexFlags::default()
    };
    
    let regex = TextRegex::with_flags(pattern, flags)?;
    
    // For now, we'll store the regex as a foreign object
    // In a complete implementation, we'd have a proper regex value type
    Ok(Value::string(format!("regex:{pattern}")))
}

/// regex-compile-ci operation
fn primitive_regex_compile_ci(args: &[Value]) -> Result<Value> {
    if args.len() != 1 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-compile-ci expects 1 argument, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-compile-ci pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let regex = TextRegex::with_flags(pattern, RegexFlags::case_insensitive())?;
    
    Ok(Value::string(format!("regex-ci:{pattern}")))
}

/// regex-match? predicate
fn primitive_regex_match_p(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-match? expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-match? pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let regex = TextRegex::new(pattern)?;
    
    Ok(Value::boolean(regex.is_match(&text)))
}

/// regex-search operation
fn primitive_regex_search(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-search expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-search pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let regex = TextRegex::new(pattern)?;
    
    match regex.find(&text) {
        Some(match_result) => {
            // Return a match object - for now, return the matched text
            Ok(match_result.matched_text.into())
        }
        None => Ok(Value::boolean(false)),
    }
}

/// regex-search-all operation
fn primitive_regex_search_all(args: &[Value]) -> Result<Value> {
    if args.len() != 2 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-search-all expects 2 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-search-all pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let regex = TextRegex::new(pattern)?;
    
    let matches = regex.find_all(&text);
    let match_values: Vec<Value> = matches
        .into_iter()
        .map(|m| m.matched_text.into())
        .collect();
    
    Ok(Value::list(match_values))
}

/// regex-replace operation
fn primitive_regex_replace(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-replace expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-replace pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let replacement = Text::try_from(&args[2])?;
    
    let regex = TextRegex::new(pattern)?;
    let result = regex.replace(&text, &replacement);
    
    Ok(result.into())
}

/// regex-replace-all operation
fn primitive_regex_replace_all(args: &[Value]) -> Result<Value> {
    if args.len() != 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-replace-all expects 3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-replace-all pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let replacement = Text::try_from(&args[2])?;
    
    let regex = TextRegex::new(pattern)?;
    let result = regex.replace_all(&text, &replacement);
    
    Ok(result.into())
}

/// regex-split operation
fn primitive_regex_split(args: &[Value]) -> Result<Value> {
    if args.len() < 2 || args.len() > 3 {
        return Err(Box::new(DiagnosticError::runtime_error(
            format!("regex-split expects 2-3 arguments, got {}", args.len()),
            None,
        )));
    }
    
    let pattern = args[0].as_string().ok_or_else(|| {
        Box::new(DiagnosticError::runtime_error(
            "regex-split pattern must be a string".to_string(),
            None,
        ))
    })?;
    
    let text = Text::try_from(&args[1])?;
    let regex = TextRegex::new(pattern)?;
    
    let parts = if args.len() > 2 {
        let limit = args[2].as_integer().ok_or_else(|| {
            Box::new(DiagnosticError::runtime_error(
                "regex-split limit must be an integer".to_string(),
                None,
            ))
        })? as usize;
        regex.splitn(&text, limit)
    } else {
        regex.split(&text)
    };
    
    let part_values: Vec<Value> = parts.into_iter().map(|p| p.into()).collect();
    Ok(Value::list(part_values))
}

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

    #[test]
    fn test_regex_compilation() {
        let regex = TextRegex::new(r"\d+").unwrap();
        assert_eq!(regex.pattern(), r"\d+");
    }

    #[test]
    fn test_regex_matching() {
        let regex = TextRegex::new(r"\d+").unwrap();
        let text = Text::from_string_slice("abc123def");
        
        assert!(regex.is_match(&text));
        
        let match_result = regex.find(&text).unwrap();
        assert_eq!(match_result.matched_text.to_string(), "123");
        assert_eq!(match_result.start, 3);
        assert_eq!(match_result.end, 6);
    }

    #[test]
    fn test_regex_replacement() {
        let regex = TextRegex::new(r"\d+").unwrap();
        let text = Text::from_string_slice("abc123def456");
        let replacement = Text::from_string_slice("XXX");
        
        let result = regex.replace(&text, &replacement);
        assert_eq!(result.to_string(), "abcXXXdef456");
        
        let result_all = regex.replace_all(&text, &replacement);
        assert_eq!(result_all.to_string(), "abcXXXdefXXX");
    }

    #[test]
    fn test_regex_splitting() {
        let regex = TextRegex::new(r",\s*").unwrap();
        let text = Text::from_string_slice("a, b, c, d");
        
        let parts = regex.split(&text);
        assert_eq!(parts.len(), 4);
        assert_eq!(parts[0].to_string(), "a");
        assert_eq!(parts[1].to_string(), "b");
        assert_eq!(parts[2].to_string(), "c");
        assert_eq!(parts[3].to_string(), "d");
    }

    #[test]
    fn test_case_insensitive_regex() {
        let regex = TextRegex::with_flags(r"hello", RegexFlags::case_insensitive()).unwrap();
        let text = Text::from_string_slice("Hello World");
        
        assert!(regex.is_match(&text));
        
        let match_result = regex.find(&text).unwrap();
        assert_eq!(match_result.matched_text.to_string(), "Hello");
    }

    #[test]
    fn test_named_groups() {
        let regex = TextRegex::new(r"(?P<word>\w+)\s+(?P<number>\d+)").unwrap();
        let text = Text::from_string_slice("hello 123");
        
        let match_result = regex.find(&text).unwrap();
        
        assert!(match_result.named_groups.contains_key("word"));
        assert!(match_result.named_groups.contains_key("number"));
        
        if let Some(Some(word)) = match_result.named_groups.get("word") {
            assert_eq!(word.to_string(), "hello");
        }
        
        if let Some(Some(number)) = match_result.named_groups.get("number") {
            assert_eq!(number.to_string(), "123");
        }
    }
}