logicaffeine-kernel 0.9.16

Pure Calculus of Constructions type theory - NO LEXICON
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Parser for Kernel Term syntax.
//!
//! Parses the following grammar:
//! ```text
//! term   ::= lambda | forall | fix | match | arrow
//! arrow  ::= app ("->" arrow)?
//! app    ::= atom+
//! atom   ::= "(" term ")" | sort | ident
//! sort   ::= "Prop" | "Type" | "Type" digit+
//! lambda ::= "fun" ident ":" term "=>" term
//! forall ::= "forall" ident ":" term "," term
//! fix    ::= "fix" ident "=>" term
//! match  ::= "match" term "return" term "with" ("|" ident+ "=>" term)+
//! ```

use crate::{Literal, Term, Universe};
use super::error::ParseError;
use std::collections::HashSet;

/// Recursive descent parser for Term syntax.
pub struct TermParser<'a> {
    input: &'a str,
    pos: usize,
    /// Variables currently in scope (bound by lambda, forall, fix, or match case)
    bound_vars: HashSet<String>,
}

impl<'a> TermParser<'a> {
    /// Parse a term from input string.
    pub fn parse(input: &'a str) -> Result<Term, ParseError> {
        let mut parser = Self {
            input,
            pos: 0,
            bound_vars: HashSet::new(),
        };
        let term = parser.parse_term()?;
        parser.skip_whitespace();
        Ok(term)
    }

    /// Parse a term (top-level).
    fn parse_term(&mut self) -> Result<Term, ParseError> {
        self.skip_whitespace();

        if self.peek_keyword("fun") {
            self.parse_lambda()
        } else if self.peek_keyword("forall") {
            self.parse_forall()
        } else if self.peek_keyword("fix") {
            self.parse_fix()
        } else if self.peek_keyword("match") {
            self.parse_match()
        } else {
            self.parse_arrow()
        }
    }

    /// Parse arrow type: A -> B -> C (right associative)
    fn parse_arrow(&mut self) -> Result<Term, ParseError> {
        let left = self.parse_app()?;

        self.skip_whitespace();
        if self.try_consume("->") {
            let right = self.parse_arrow()?;
            // A -> B is sugar for Π(_:A). B
            Ok(Term::Pi {
                param: "_".to_string(),
                param_type: Box::new(left),
                body_type: Box::new(right),
            })
        } else {
            Ok(left)
        }
    }

    /// Parse application: f x y z (left associative)
    fn parse_app(&mut self) -> Result<Term, ParseError> {
        let mut func = self.parse_atom()?;

        loop {
            self.skip_whitespace();
            // Check if we can parse another atom
            // Stop at: ), ->, =>, ,, |, with, return, end, ., EOF, or keywords
            if self.at_end()
                || self.peek_char(')')
                || self.peek_char('.')
                || self.peek_char(',')
                || self.peek_char('|')
                || self.peek_str("->")
                || self.peek_str("=>")
                || self.peek_keyword("with")
                || self.peek_keyword("return")
                || self.peek_keyword("end")
            {
                break;
            }

            let arg = self.parse_atom()?;
            func = Term::App(Box::new(func), Box::new(arg));
        }

        Ok(func)
    }

    /// Parse an atom: (term), number, string, sort, or identifier
    fn parse_atom(&mut self) -> Result<Term, ParseError> {
        self.skip_whitespace();

        // Check for negative number
        if self.peek_char('-') {
            if let Some(lit) = self.try_parse_negative_number() {
                return Ok(lit);
            }
        }

        // Check for positive number
        if let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                return self.parse_number_literal();
            }
        }

        // Check for string literal
        if self.peek_char('"') {
            return self.parse_string_literal();
        }

        if self.peek_char('(') {
            self.parse_parens()
        } else {
            self.parse_ident_or_sort()
        }
    }

    /// Parse a positive integer literal
    fn parse_number_literal(&mut self) -> Result<Term, ParseError> {
        let start = self.pos;

        while let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                self.advance();
            } else {
                break;
            }
        }

        let num_str = &self.input[start..self.pos];
        let value: i64 = num_str
            .parse()
            .map_err(|_| ParseError::InvalidNumber(num_str.to_string()))?;

        Ok(Term::Lit(Literal::Int(value)))
    }

    /// Parse a string literal: "contents"
    fn parse_string_literal(&mut self) -> Result<Term, ParseError> {
        self.expect_char('"')?;

        // Collect characters until closing quote
        let mut content = String::new();
        loop {
            match self.peek() {
                Some('"') => {
                    self.advance();
                    break;
                }
                Some('\\') => {
                    // Handle escape sequences
                    self.advance();
                    match self.peek() {
                        Some('n') => {
                            content.push('\n');
                            self.advance();
                        }
                        Some('t') => {
                            content.push('\t');
                            self.advance();
                        }
                        Some('\\') => {
                            content.push('\\');
                            self.advance();
                        }
                        Some('"') => {
                            content.push('"');
                            self.advance();
                        }
                        Some(c) => {
                            content.push(c);
                            self.advance();
                        }
                        None => return Err(ParseError::UnexpectedEof),
                    }
                }
                Some(c) => {
                    content.push(c);
                    self.advance();
                }
                None => return Err(ParseError::UnexpectedEof),
            }
        }

        Ok(Term::Lit(Literal::Text(content)))
    }

    /// Try to parse a negative number, returning None if not a number
    fn try_parse_negative_number(&mut self) -> Option<Term> {
        // Look ahead: - followed by digit
        if !self.peek_char('-') {
            return None;
        }
        let after_dash = self.pos + 1;
        if after_dash >= self.input.len() {
            return None;
        }
        let next = self.input[after_dash..].chars().next()?;
        if !next.is_ascii_digit() {
            return None;
        }

        // Consume the dash
        self.advance();

        // Parse the number
        let start = self.pos;
        while let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                self.advance();
            } else {
                break;
            }
        }

        let num_str = &self.input[start..self.pos];
        let value: i64 = num_str.parse().ok()?;

        Some(Term::Lit(Literal::Int(-value)))
    }

    /// Parse parenthesized term
    fn parse_parens(&mut self) -> Result<Term, ParseError> {
        self.expect_char('(')?;
        let term = self.parse_term()?;
        self.skip_whitespace();
        self.expect_char(')')?;
        Ok(term)
    }

    /// Parse identifier or sort (Prop, Type, Type0, etc.)
    fn parse_ident_or_sort(&mut self) -> Result<Term, ParseError> {
        let ident = self.parse_ident()?;

        match ident.as_str() {
            "Prop" => Ok(Term::Sort(Universe::Prop)),
            "Type" => {
                // Check for Type followed by a number
                self.skip_whitespace();
                if let Some(n) = self.try_parse_number() {
                    Ok(Term::Sort(Universe::Type(n)))
                } else {
                    Ok(Term::Sort(Universe::Type(0)))
                }
            }
            _ => {
                // Check for TypeN (e.g., Type0, Type1)
                if ident.starts_with("Type") {
                    if let Ok(n) = ident[4..].parse::<u32>() {
                        return Ok(Term::Sort(Universe::Type(n)));
                    }
                }
                // Check if this is a bound variable
                if self.bound_vars.contains(&ident) {
                    Ok(Term::Var(ident))
                } else {
                    Ok(Term::Global(ident))
                }
            }
        }
    }

    /// Parse lambda: fun x : T => body
    fn parse_lambda(&mut self) -> Result<Term, ParseError> {
        self.consume_keyword("fun")?;
        self.skip_whitespace();
        let param = self.parse_ident()?;
        self.skip_whitespace();
        self.expect_char(':')?;
        let param_type = self.parse_term()?;
        self.skip_whitespace();
        self.expect_str("=>")?;

        // Add param to bound variables, parse body, then remove
        let was_bound = self.bound_vars.contains(&param);
        self.bound_vars.insert(param.clone());
        let body = self.parse_term()?;
        if !was_bound {
            self.bound_vars.remove(&param);
        }

        Ok(Term::Lambda {
            param,
            param_type: Box::new(param_type),
            body: Box::new(body),
        })
    }

    /// Parse forall: forall x : T, body
    fn parse_forall(&mut self) -> Result<Term, ParseError> {
        self.consume_keyword("forall")?;
        self.skip_whitespace();
        let param = self.parse_ident()?;
        self.skip_whitespace();
        self.expect_char(':')?;
        let param_type = self.parse_term()?;
        self.skip_whitespace();
        self.expect_char(',')?;

        // Add param to bound variables, parse body, then remove
        let was_bound = self.bound_vars.contains(&param);
        self.bound_vars.insert(param.clone());
        let body_type = self.parse_term()?;
        if !was_bound {
            self.bound_vars.remove(&param);
        }

        Ok(Term::Pi {
            param,
            param_type: Box::new(param_type),
            body_type: Box::new(body_type),
        })
    }

    /// Parse fix: fix f => body
    fn parse_fix(&mut self) -> Result<Term, ParseError> {
        self.consume_keyword("fix")?;
        self.skip_whitespace();
        let name = self.parse_ident()?;
        self.skip_whitespace();
        self.expect_str("=>")?;

        // Add name to bound variables, parse body, then remove
        let was_bound = self.bound_vars.contains(&name);
        self.bound_vars.insert(name.clone());
        let body = self.parse_term()?;
        if !was_bound {
            self.bound_vars.remove(&name);
        }

        Ok(Term::Fix {
            name,
            body: Box::new(body),
        })
    }

    /// Parse match: match e return M with | C1 x => t1 | C2 y z => t2 end
    fn parse_match(&mut self) -> Result<Term, ParseError> {
        self.consume_keyword("match")?;
        self.skip_whitespace();
        let discriminant = self.parse_app()?;
        self.skip_whitespace();
        self.consume_keyword("return")?;
        self.skip_whitespace();
        let motive = self.parse_app()?;
        self.skip_whitespace();
        self.consume_keyword("with")?;

        let mut cases = Vec::new();
        loop {
            self.skip_whitespace();
            if !self.try_consume("|") {
                break;
            }
            self.skip_whitespace();

            // Parse pattern: C x y z (constructor with binders)
            let case_term = self.parse_case_body()?;
            cases.push(case_term);
        }

        // Consume optional 'end' keyword
        self.skip_whitespace();
        let _ = self.try_consume_keyword("end");

        Ok(Term::Match {
            discriminant: Box::new(discriminant),
            motive: Box::new(motive),
            cases,
        })
    }

    /// Parse a match case body: C x y => term becomes λx. λy. term
    ///
    /// The first identifier is the constructor name (skipped), the rest are binders.
    fn parse_case_body(&mut self) -> Result<Term, ParseError> {
        // First identifier is the constructor name (skip it)
        self.skip_whitespace();
        let _ctor_name = self.parse_ident()?;

        // Collect binders until =>
        let mut binders = Vec::new();
        loop {
            self.skip_whitespace();
            if self.peek_str("=>") {
                break;
            }
            let ident = self.parse_ident()?;
            binders.push(ident);
        }
        self.expect_str("=>")?;

        // Add all binders to bound vars
        let mut previously_bound = Vec::new();
        for binder in &binders {
            previously_bound.push(self.bound_vars.contains(binder));
            self.bound_vars.insert(binder.clone());
        }

        let mut body = self.parse_term()?;

        // Remove binders that weren't previously bound
        for (i, binder) in binders.iter().enumerate() {
            if !previously_bound[i] {
                self.bound_vars.remove(binder);
            }
        }

        // Wrap in lambdas from right to left
        // We don't know the types, so we use a placeholder
        for binder in binders.into_iter().rev() {
            body = Term::Lambda {
                param: binder,
                param_type: Box::new(Term::Global("_".to_string())), // Placeholder type
                body: Box::new(body),
            };
        }

        Ok(body)
    }

    // =========================================================================
    // Low-level parsing utilities
    // =========================================================================

    /// Parse an identifier (alphanumeric + underscore, starting with letter/underscore)
    fn parse_ident(&mut self) -> Result<String, ParseError> {
        self.skip_whitespace();
        let start = self.pos;

        // First character must be letter or underscore
        if let Some(c) = self.peek() {
            if !c.is_alphabetic() && c != '_' {
                return Err(ParseError::Expected {
                    expected: "identifier".to_string(),
                    found: format!("{}", c),
                });
            }
        } else {
            return Err(ParseError::UnexpectedEof);
        }

        // Consume alphanumeric and underscore
        while let Some(c) = self.peek() {
            if c.is_alphanumeric() || c == '_' {
                self.advance();
            } else {
                break;
            }
        }

        let ident = self.input[start..self.pos].to_string();
        if ident.is_empty() {
            Err(ParseError::InvalidIdent("empty".to_string()))
        } else {
            Ok(ident)
        }
    }

    /// Try to parse a number, returning None if not present
    fn try_parse_number(&mut self) -> Option<u32> {
        self.skip_whitespace();
        let start = self.pos;

        while let Some(c) = self.peek() {
            if c.is_ascii_digit() {
                self.advance();
            } else {
                break;
            }
        }

        if self.pos > start {
            self.input[start..self.pos].parse().ok()
        } else {
            None
        }
    }

    /// Skip whitespace
    fn skip_whitespace(&mut self) {
        while let Some(c) = self.peek() {
            if c.is_whitespace() {
                self.advance();
            } else {
                break;
            }
        }
    }

    /// Peek at current character
    fn peek(&self) -> Option<char> {
        self.input[self.pos..].chars().next()
    }

    /// Check if we're at a specific character
    fn peek_char(&self, c: char) -> bool {
        self.peek() == Some(c)
    }

    /// Check if input starts with a string at current position
    fn peek_str(&self, s: &str) -> bool {
        self.input[self.pos..].starts_with(s)
    }

    /// Check if input starts with a keyword (followed by non-alphanumeric)
    fn peek_keyword(&self, keyword: &str) -> bool {
        if !self.peek_str(keyword) {
            return false;
        }
        // Check that keyword is not part of a longer identifier
        let after = self.pos + keyword.len();
        if after >= self.input.len() {
            return true;
        }
        let next_char = self.input[after..].chars().next();
        !next_char.map(|c| c.is_alphanumeric() || c == '_').unwrap_or(false)
    }

    /// Advance position by one character
    fn advance(&mut self) {
        if let Some(c) = self.peek() {
            self.pos += c.len_utf8();
        }
    }

    /// Check if at end of input
    fn at_end(&self) -> bool {
        self.pos >= self.input.len()
    }

    /// Try to consume a string, returning true if successful
    fn try_consume(&mut self, s: &str) -> bool {
        if self.peek_str(s) {
            self.pos += s.len();
            true
        } else {
            false
        }
    }

    /// Try to consume a keyword, returning true if successful
    fn try_consume_keyword(&mut self, keyword: &str) -> bool {
        self.skip_whitespace();
        if self.peek_keyword(keyword) {
            self.pos += keyword.len();
            true
        } else {
            false
        }
    }

    /// Expect a specific character
    fn expect_char(&mut self, expected: char) -> Result<(), ParseError> {
        self.skip_whitespace();
        if self.peek_char(expected) {
            self.advance();
            Ok(())
        } else {
            Err(ParseError::Expected {
                expected: format!("'{}'", expected),
                found: self.peek().map(|c| c.to_string()).unwrap_or("EOF".to_string()),
            })
        }
    }

    /// Expect a specific string
    fn expect_str(&mut self, expected: &str) -> Result<(), ParseError> {
        self.skip_whitespace();
        if self.try_consume(expected) {
            Ok(())
        } else {
            let found: String = self.input[self.pos..].chars().take(expected.len()).collect();
            Err(ParseError::Expected {
                expected: format!("'{}'", expected),
                found: if found.is_empty() { "EOF".to_string() } else { found },
            })
        }
    }

    /// Consume a keyword (must be followed by non-alphanumeric)
    fn consume_keyword(&mut self, keyword: &str) -> Result<(), ParseError> {
        self.skip_whitespace();
        if self.peek_keyword(keyword) {
            self.pos += keyword.len();
            Ok(())
        } else {
            Err(ParseError::Expected {
                expected: keyword.to_string(),
                found: self.peek().map(|c| c.to_string()).unwrap_or("EOF".to_string()),
            })
        }
    }

    /// Get remaining input (for debugging)
    #[allow(dead_code)]
    fn remaining(&self) -> &str {
        &self.input[self.pos..]
    }
}

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

    #[test]
    fn test_parse_global() {
        let term = TermParser::parse("Zero").unwrap();
        assert!(matches!(term, Term::Global(ref s) if s == "Zero"));
    }

    #[test]
    fn test_parse_sort() {
        let term = TermParser::parse("Type").unwrap();
        assert!(matches!(term, Term::Sort(Universe::Type(0))));

        let term2 = TermParser::parse("Prop").unwrap();
        assert!(matches!(term2, Term::Sort(Universe::Prop)));
    }

    #[test]
    fn test_parse_app() {
        let term = TermParser::parse("Succ Zero").unwrap();
        if let Term::App(func, arg) = term {
            assert!(matches!(*func, Term::Global(ref s) if s == "Succ"));
            assert!(matches!(*arg, Term::Global(ref s) if s == "Zero"));
        } else {
            panic!("Expected App");
        }
    }

    #[test]
    fn test_parse_parens() {
        let term = TermParser::parse("(Succ Zero)").unwrap();
        assert!(matches!(term, Term::App(..)));
    }

    #[test]
    fn test_parse_arrow() {
        let term = TermParser::parse("Nat -> Nat").unwrap();
        if let Term::Pi { param, param_type, body_type } = term {
            assert_eq!(param, "_");
            assert!(matches!(*param_type, Term::Global(ref s) if s == "Nat"));
            assert!(matches!(*body_type, Term::Global(ref s) if s == "Nat"));
        } else {
            panic!("Expected Pi");
        }
    }

    #[test]
    fn test_parse_lambda() {
        let term = TermParser::parse("fun x : Nat => Succ x").unwrap();
        if let Term::Lambda { param, body, .. } = term {
            assert_eq!(param, "x");
            // Body should use Var for bound x
            if let Term::App(_, arg) = *body {
                assert!(matches!(*arg, Term::Var(ref s) if s == "x"));
            } else {
                panic!("Expected App in lambda body");
            }
        } else {
            panic!("Expected Lambda");
        }
    }

    #[test]
    fn test_parse_lambda_bound_var() {
        let term = TermParser::parse("fun n : Nat => Succ n").unwrap();
        if let Term::Lambda { body, .. } = term {
            if let Term::App(_, arg) = *body {
                assert!(
                    matches!(*arg, Term::Var(ref s) if s == "n"),
                    "Expected Var(n), got {:?}",
                    arg
                );
            } else {
                panic!("Expected App in lambda body");
            }
        } else {
            panic!("Expected Lambda");
        }
    }
}