pascal 0.1.8

A modern Pascal compiler with build/intepreter/package manager built with Rust
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
//! Enhanced parser error recovery for Pascal compiler
//! 
//! Provides sophisticated error recovery mechanisms including:
//! - Context-aware synchronization points
//! - Error classification and recovery strategies
//! - Comprehensive error reporting with suggestions
//! - Parse state management for better recovery

use crate::lexer::Lexer;
use crate::tokens::Token;
use crate::enhanced_error::{SourceLocation, Diagnostic, ErrorSuggestion, DiagnosticSeverity};

/// Recovery strategy for parsing errors
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecoveryStrategy {
    /// Skip tokens until a synchronization point is found
    Synchronize,
    /// Insert a missing token and continue
    InsertMissing,
    /// Replace incorrect token with expected one
    ReplaceIncorrect,
    /// Abort parsing for this construct
    Abort,
}

/// Error classification for better recovery decisions
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorType {
    /// Missing tokens (semicolons, end, etc.)
    MissingToken,
    /// Unexpected tokens in context
    UnexpectedToken,
    /// Syntax errors in expressions
    ExpressionError,
    /// Declaration errors
    DeclarationError,
    /// Statement errors
    StatementError,
    /// Type errors
    TypeError,
}

/// Enhanced parse result with error information
pub type EnhancedParseResult<T> = Result<T, ParseErrorInfo>;

/// Parse error information with enhanced details
#[derive(Debug, Clone)]
pub struct ParseErrorInfo {
    pub error_type: ErrorType,
    pub location: SourceLocation,
    pub message: String,
    pub expected_tokens: Vec<Token>,
    pub found_token: Option<Token>,
    pub suggestions: Vec<ErrorSuggestion>,
    pub recovery_strategy: RecoveryStrategy,
}

impl ParseErrorInfo {
    /// Create a new parse error
    pub fn new(error_type: ErrorType, location: SourceLocation, message: String) -> Self {
        Self {
            error_type,
            location,
            message,
            expected_tokens: Vec::new(),
            found_token: None,
            suggestions: Vec::new(),
            recovery_strategy: RecoveryStrategy::Synchronize,
        }
    }

    /// Add expected tokens
    pub fn with_expected(mut self, tokens: Vec<Token>) -> Self {
        self.expected_tokens = tokens;
        self
    }

    /// Add found token
    pub fn with_found(mut self, token: Option<Token>) -> Self {
        self.found_token = token;
        self
    }

    /// Add suggestions
    pub fn with_suggestions(mut self, suggestions: Vec<ErrorSuggestion>) -> Self {
        self.suggestions = suggestions;
        self
    }

    /// Set recovery strategy
    pub fn with_recovery_strategy(mut self, strategy: RecoveryStrategy) -> Self {
        self.recovery_strategy = strategy;
        self
    }

    /// Convert to diagnostic for reporting
    pub fn to_diagnostic(&self, source_manager: &crate::enhanced_error::SourceManager) -> Diagnostic {
        let severity = DiagnosticSeverity::Error;
        let mut diagnostic = Diagnostic::error(self.location, self.message);

        // Add suggestions
        diagnostic = diagnostic.with_suggestions(self.suggestions.clone());

        // Add error code
        let error_code = match self.error_type {
            ErrorType::MissingToken => "E001",
            ErrorType::UnexpectedToken => "E002",
            ErrorType::ExpressionError => "E003",
            ErrorType::DeclarationError => "E004",
            ErrorType::StatementError => "E005",
            ErrorType::TypeError => "E006",
        };
        diagnostic = diagnostic.with_code(error_code.to_string());

        diagnostic
    }
}

/// Enhanced parser with sophisticated error recovery
pub struct EnhancedParser<'a> {
    lexer: Lexer<'a>,
    source: &'a str,
    current_token: Option<Token>,
    current_location: SourceLocation,
    errors: Vec<ParseErrorInfo>,
    recovery_state: RecoveryState,
}

/// Parser state for managing recovery
#[derive(Debug, Clone)]
pub struct RecoveryState {
    pub recovery_depth: usize,
    pub last_error_position: SourceLocation,
    pub sync_points: Vec<SyncPoint>,
    pub in_recovery_mode: bool,
    pub recovery_count: usize,
}

/// Synchronization point for error recovery
#[derive(Debug, Clone)]
pub struct SyncPoint {
    pub tokens: Vec<Token>,
    pub description: String,
    pub priority: SyncPriority,
}

/// Priority level for synchronization points
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SyncPriority {
    High,    // Critical statements (end, ;, .)
    Medium,  // Block boundaries (begin, do, then)
    Low,     // Expression boundaries (,), [, etc.)
}

impl<'a> EnhancedParser<'a> {
    /// Create a new enhanced parser
    pub fn new(source: &'a str) -> Self {
        let mut lexer = Lexer::new(source);
        let (current_token, location) = Self::next_token_with_loc(&mut lexer, source);

        Self {
            lexer,
            source,
            current_token,
            current_location: location,
            errors: Vec::new(),
            recovery_state: RecoveryState::new(),
        }
    }

    /// Create recovery state
    pub fn new() -> RecoveryState {
        RecoveryState {
            recovery_depth: 0,
            last_error_position: SourceLocation::new(0, 1, 1, 0, 0),
            sync_points: Vec::new(),
            in_recovery_mode: false,
            recovery_count: 0,
        }
    }

    /// Internal token advance with location tracking
    fn next_token_with_loc(lexer: &mut Lexer, source: &str) -> (Option<Token>, SourceLocation) {
        match lexer.next() {
            Some(Ok((start, token, _end))) => {
                let loc = Self::offset_to_location(source, start);
                (Some(token), loc)
            }
            _ => (
                None,
                SourceLocation {
                    line: 1,
                    column: 1,
                    offset: 0,
                },
            ),
        }
    }

    /// Convert byte offset to line/column
    fn offset_to_location(source: &str, offset: usize) -> SourceLocation {
        let mut line = 1;
        let mut col = 1;
        for (i, ch) in source.char_indices() {
            if i >= offset {
                break;
            }
            if ch == '\n' {
                line += 1;
                col = 1;
            } else {
                col += 1;
            }
        }
        SourceLocation {
            line,
            column: col,
            offset,
        }
    }

    /// Get current source location
    pub fn location(&self) -> SourceLocation {
        self.current_location
    }

    /// Advance to next token
    pub fn advance(&mut self) {
        let (token, loc) = Self::next_token_with_loc(&mut self.lexer, self.source);
        self.current_token = token;
        self.current_location = loc;
    }

    /// Peek at current token
    pub fn peek(&self) -> Option<&Token> {
        self.current_token.as_ref()
    }

    /// Check if current token matches expected
    pub fn check(&self, token: &Token) -> bool {
        self.peek() == Some(token)
    }

    /// Consume token if it matches, otherwise error with location
    pub fn consume(&mut self, expected: Token) -> EnhancedParseResult<Token> {
        if self.check(&expected) {
            let token = self.current_token.take().unwrap();
            self.advance();
            Ok(token)
        } else {
            let found = self.peek().cloned();
            self.report_error(
                ErrorType::UnexpectedToken,
                format!("Expected {:?}, found {:?}", expected, found),
                Some(expected),
                found,
            )
        }
    }

    /// Consume token with error recovery
    pub fn consume_with_recovery(
        &mut self,
        expected: Token,
        sync_points: &[SyncPoint],
    ) -> EnhancedParseResult<Token> {
        match self.consume(expected.clone()) {
            Ok(token) => Ok(token),
            Err(e) => {
                self.handle_error(e, sync_points);
                Ok(expected) // Return expected token to continue parsing
            }
        }
    }

    /// Report a parsing error with recovery
    fn report_error(
        &mut self,
        error_type: ErrorType,
        message: String,
        expected: Option<Token>,
        found: Option<Token>,
    ) -> EnhancedParseResult<Token> {
        let error = ParseErrorInfo::new(error_type, self.current_location, message)
            .with_found(found)
            .with_recovery_strategy(self.determine_recovery_strategy(error_type));

        // Add suggestions based on error type
        let suggestions = self.generate_suggestions(error_type, &expected, &found);
        if !suggestions.is_empty() {
            error.with_suggestions(suggestions);
        }

        self.errors.push(error);
        Err(self.errors.last().unwrap().clone())
    }

    /// Determine recovery strategy based on error type
    fn determine_recovery_strategy(&mut self, error_type: ErrorType) -> RecoveryStrategy {
        // Enter recovery mode if we're recovering too much
        if self.recovery_state.recovery_count > 5 {
            return RecoveryStrategy::Abort;
        }

        match error_type {
            ErrorType::MissingToken => RecoveryStrategy::InsertMissing,
            ErrorType::UnexpectedToken => RecoveryStrategy::Synchronize,
            ErrorType::ExpressionError => RecoveryStrategy::Synchronize,
            ErrorType::DeclarationError => RecoveryStrategy::Synchronize,
            ErrorType::StatementError => RecoveryStrategy::Synchronize,
            ErrorType::TypeError => RecoveryStrategy::Synchronize,
        }
    }

    /// Generate suggestions for error recovery
    fn generate_suggestions(
        &self,
        error_type: ErrorType,
        expected: &Option<Token>,
        found: &Option<Token>,
    ) -> Vec<ErrorSuggestion> {
        let mut suggestions = Vec::new();

        match error_type {
            ErrorType::MissingToken => {
                if let Some(expected_token) = expected {
                    let suggestion = match expected_token {
                        Token::Semicolon => {
                            ErrorSuggestion::with_replacement(
                                "Missing semicolon".to_string(),
                                ";".to_string(),
                            )
                        },
                        Token::Dot => {
                            ErrorSuggestion::with_replacement(
                                "Missing period".to_string(),
                                ".".to_string(),
                            )
                        },
                        Token::End => {
                            ErrorSuggestion::with_replacement(
                                "Missing 'end' keyword".to_string(),
                                "end".to_string(),
                            )
                        },
                        _ => ErrorSuggestion::new(format!("Consider adding {:?}", expected_token)),
                    };
                    suggestions.push(suggestion);
                }
            },
            ErrorType::UnexpectedToken => {
                if let Some(found_token) = found {
                    let suggestion = match found_token {
                        Token::Identifier(_) => {
                            ErrorSuggestion::new("Unexpected identifier".to_string())
                        },
                        Token::Number(_) => {
                            ErrorSuggestion::new("Unexpected number".to_string())
                        },
                        Token::StringLiteral(_) => {
                            ErrorSuggestion::new("Unexpected string".to_string())
                        },
                        _ => ErrorSuggestion::new(format!("Unexpected token {:?}", found_token)),
                    };
                    suggestions.push(suggestion);
                }
            },
            _ => {}
        }

        suggestions
    }

    /// Handle parsing error with recovery
    fn handle_error(&mut self, error: ParseErrorInfo, sync_points: &[SyncPoint]) {
        self.recovery_state.recovery_count += 1;
        
        // Enter recovery mode
        self.recovery_state.in_recovery_mode = true;
        self.recovery_state.recovery_depth += 1;
        
        // Apply recovery strategy
        match error.recovery_strategy {
            RecoveryStrategy::Synchronize => {
                self.synchronize(sync_points);
            },
            RecoveryStrategy::InsertMissing => {
                self.insert_missing_token(&error);
            },
            RecoveryStrategy::ReplaceIncorrect => {
                self.replace_incorrect_token(&error);
            },
            RecoveryStrategy::Abort => {
                self.abort_recovery();
            },
        }
        
        // Exit recovery mode
        self.recovery_state.in_recovery_mode = false;
        self.recovery_state.recovery_depth = self.recovery_state.recovery_depth.saturating_sub(1);
    }

    /// Synchronize parser after error
    pub fn synchronize(&mut self, sync_points: &[SyncPoint]) {
        let mut best_sync_point = None;
        let mut best_priority = SyncPriority::Low;
        
        // Find the best synchronization point
        for sync_point in sync_points {
            if sync_point.tokens.contains(self.peek().unwrap_or(&Token::Eof)) {
                if sync_point.priority > best_priority {
                    best_priority = sync_point.priority;
                    best_sync_point = Some(sync_point);
                }
            }
        }
        
        if let Some(sync_point) = best_sync_point {
            eprintln!("[parser] Synchronizing at: {}", sync_point.description);
        }
        
        // Advance until we find a synchronization point
        while let Some(token) = self.peek() {
            if self.is_sync_token(token, sync_points) {
                break;
            }
            self.advance();
        }
    }

    /// Check if token is a synchronization point
    fn is_sync_token(&self, token: &Token, sync_points: &[SyncPoint]) -> bool {
        for sync_point in sync_points {
            if sync_point.tokens.contains(token) {
                return true;
            }
        }
        false
    }

    /// Insert missing token
    fn insert_missing_token(&mut self, error: &ParseErrorInfo) {
        eprintln!("[parser] Inserting missing token at {}", error.location.format());
        // In a real implementation, this would insert the token into the token stream
        self.advance();
    }

    /// Replace incorrect token
    fn replace_incorrect_token(&mut self, error: &ParseErrorInfo) {
        eprintln!("[parser] Replacing incorrect token at {}", error.location.format());
        // In a real implementation, this would replace the token in the token stream
        self.advance();
    }

    /// Abort recovery for this construct
    fn abort_recovery(&mut self) {
        eprintln!("[parser] Aborting recovery due to excessive errors");
        self.recovery_state.recovery_count = 0;
    }

    /// Get all parsing errors
    pub fn errors(&self) -> &[ParseErrorInfo] {
        &self.errors
    }

    /// Check if parsing completed with errors
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.errors.len()
    }

    /// Create default synchronization points
    pub fn create_default_sync_points() -> Vec<SyncPoint> {
        vec![
            SyncPoint {
                tokens: vec![Token::Semicolon],
                description: "Statement end".to_string(),
                priority: SyncPriority::High,
            },
            SyncPoint {
                tokens: vec![Token::End],
                description: "Block end".to_string(),
                priority: SyncPriority::High,
            },
            SyncPoint {
                tokens: vec![Token::Dot],
                description: "Program end".to_string(),
                priority: SyncPriority::High,
            },
            SyncPoint {
                tokens: vec![Token::Then, Token::Do, Token::Else],
                description: "Control flow".to_string(),
                priority: SyncPriority::Medium,
            },
            SyncPoint {
                tokens: vec![Token::Begin, Token::Program, Token::Var, Token::Type],
                description: "Declaration start".to_string(),
                priority: SyncPriority::Medium,
            },
            SyncPoint {
                tokens: vec![Token::LParen, Token::RParen, Token::LBracket, Token::RBracket],
                description: "Expression boundaries".to_string(),
                priority: SyncPriority::Low,
            },
        ]
    }

    /// Reset parser state
    pub fn reset(&mut self) {
        self.errors.clear();
        self.recovery_state = RecoveryState::new();
    }
}

/// Helper functions for common parsing operations
pub mod helpers {
    use super::*;

    /// Create error for missing semicolon
    pub fn missing_semicolon(location: SourceLocation) -> ParseErrorInfo {
        ParseErrorInfo::new(
            ErrorType::MissingToken,
            location,
            "Missing semicolon".to_string(),
        )
        .with_expected(vec![Token::Semicolon])
        .with_recovery_strategy(RecoveryStrategy::InsertMissing)
    }

    /// Create error for unexpected token
    pub fn unexpected_token(location: SourceLocation, found: Token) -> ParseErrorInfo {
        ParseErrorInfo::new(
            ErrorType::UnexpectedToken,
            location,
            format!("Unexpected token: {:?}", found),
        )
        .with_found(Some(found))
        .with_recovery_strategy(RecoveryStrategy::Synchronize)
    }

    /// Create error for mismatched parentheses
    pub fn mismatched_parentheses(location: SourceLocation, expected: Token, found: Token) -> ParseErrorInfo {
        ParseErrorInfo::new(
            ErrorType::ExpressionError,
            location,
            format!("Mismatched parentheses: expected {:?}, found {:?}", expected, found),
        )
        .with_expected(vec![expected])
        .with_found(Some(found))
        .with_recovery_strategy(RecoveryStrategy::ReplaceIncorrect)
    }

    /// Create error for incomplete declaration
    pub fn incomplete_declaration(location: SourceLocation, missing: &str) -> ParseErrorInfo {
        ParseErrorInfo::new(
            ErrorType::DeclarationError,
            location,
            format!("Incomplete declaration: missing {}", missing),
        )
        .with_recovery_strategy(RecoveryStrategy::Synchronize)
    }
}

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

    #[test]
    fn test_parser_creation() {
        let source = "program Test; begin end.";
        let parser = EnhancedParser::new(source);
        assert!(!parser.has_errors());
    }

    #[test]
    fn test_error_creation() {
        let location = SourceLocation::new(0, 1, 1, 0, 0);
        let error = ParseErrorInfo::new(ErrorType::MissingToken, location, "Test error".to_string());
        
        assert_eq!(error.error_type, ErrorType::MissingToken);
        assert_eq!(error.location, location);
        assert_eq!(error.message, "Test error");
    }

    #[test]
    fn test_sync_points() {
        let sync_points = EnhancedParser::create_default_sync_points();
        
        assert!(sync_points.len() > 0);
        assert!(sync_points.iter().any(|sp| sp.description == "Statement end"));
    }

    #[test]
    fn test_recovery_strategy() {
        let location = SourceLocation::new(0, 1, 1, 0, 0);
        let error = helpers::missing_semicolon(location);
        
        assert_eq!(error.recovery_strategy, RecoveryStrategy::InsertMissing);
    }

    #[test]
    fn test_suggestions() {
        let location = SourceLocation::new(0, 1, 1, 0, 0);
        let error = helpers::missing_semicolon(location);
        
        let suggestions = error.suggestions;
        assert!(!suggestions.is_empty());
        assert!(suggestions.iter().any(|s| s.message.contains("semicolon")));
    }
}