lling-llang 0.1.0

WFST framework for text normalization and grammar correction
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
//! Structural validation for LaTeX documents.
//!
//! Provides validation beyond CFG parsing: brace matching, environment
//! pairing, math delimiter balance, and other structural constraints.

use std::collections::VecDeque;

/// Result of validating a LaTeX token sequence.
#[derive(Debug, Clone)]
pub struct ValidationResult {
    /// Whether the sequence is valid.
    pub is_valid: bool,
    /// List of issues found.
    pub issues: Vec<ValidationIssue>,
}

impl ValidationResult {
    /// Create a valid result with no issues.
    pub fn valid() -> Self {
        Self {
            is_valid: true,
            issues: Vec::new(),
        }
    }

    /// Create an invalid result with issues.
    pub fn invalid(issues: Vec<ValidationIssue>) -> Self {
        Self {
            is_valid: false,
            issues,
        }
    }

    /// Add an issue to the result.
    pub fn add_issue(&mut self, issue: ValidationIssue) {
        if issue.severity == IssueSeverity::Error {
            self.is_valid = false;
        }
        self.issues.push(issue);
    }

    /// Check if there are any errors (not just warnings).
    pub fn has_errors(&self) -> bool {
        self.issues
            .iter()
            .any(|i| i.severity == IssueSeverity::Error)
    }

    /// Get only the error issues.
    pub fn errors(&self) -> impl Iterator<Item = &ValidationIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Error)
    }

    /// Get only the warning issues.
    pub fn warnings(&self) -> impl Iterator<Item = &ValidationIssue> {
        self.issues
            .iter()
            .filter(|i| i.severity == IssueSeverity::Warning)
    }
}

/// A validation issue found in the document.
#[derive(Debug, Clone)]
pub struct ValidationIssue {
    /// Severity of the issue.
    pub severity: IssueSeverity,
    /// Type of issue.
    pub kind: IssueKind,
    /// Position in the token sequence (if applicable).
    pub position: Option<usize>,
    /// Human-readable message.
    pub message: String,
}

impl ValidationIssue {
    /// Create an error issue.
    pub fn error(kind: IssueKind, position: Option<usize>, message: impl Into<String>) -> Self {
        Self {
            severity: IssueSeverity::Error,
            kind,
            position,
            message: message.into(),
        }
    }

    /// Create a warning issue.
    pub fn warning(kind: IssueKind, position: Option<usize>, message: impl Into<String>) -> Self {
        Self {
            severity: IssueSeverity::Warning,
            kind,
            position,
            message: message.into(),
        }
    }
}

/// Severity of a validation issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueSeverity {
    /// An error that makes the document invalid.
    Error,
    /// A warning that may indicate a problem.
    Warning,
}

/// Type of validation issue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IssueKind {
    /// Unmatched opening brace.
    UnmatchedOpenBrace,
    /// Unmatched closing brace.
    UnmatchedCloseBrace,
    /// Unmatched opening bracket.
    UnmatchedOpenBracket,
    /// Unmatched closing bracket.
    UnmatchedCloseBracket,
    /// Unmatched opening parenthesis.
    UnmatchedOpenParen,
    /// Unmatched closing parenthesis.
    UnmatchedCloseParen,
    /// Mismatched environment begin/end.
    EnvironmentMismatch,
    /// Missing environment end.
    MissingEnvironmentEnd,
    /// Extra environment end.
    ExtraEnvironmentEnd,
    /// Unmatched math delimiter.
    UnmatchedMathDelimiter,
    /// Nested math mode (e.g., $ inside $).
    NestedMathMode,
    /// Invalid command argument count.
    InvalidArgumentCount,
    /// Unknown environment.
    UnknownEnvironment,
    /// Empty required argument.
    EmptyRequiredArgument,
}

/// Validator for LaTeX structural constraints.
pub struct LatexValidator {
    /// Whether to validate environment names.
    validate_environments: bool,
    /// Whether to validate command argument counts.
    validate_arguments: bool,
    /// Whether to allow nested math modes.
    allow_nested_math: bool,
    /// Known environment names.
    known_environments: Vec<String>,
}

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

impl LatexValidator {
    /// Create a new validator with default settings.
    pub fn new() -> Self {
        Self {
            validate_environments: true,
            validate_arguments: true,
            allow_nested_math: false,
            known_environments: default_environments(),
        }
    }

    /// Configure whether to validate environment names.
    pub fn with_environment_validation(mut self, validate: bool) -> Self {
        self.validate_environments = validate;
        self
    }

    /// Configure whether to validate command arguments.
    pub fn with_argument_validation(mut self, validate: bool) -> Self {
        self.validate_arguments = validate;
        self
    }

    /// Configure whether to allow nested math modes.
    pub fn with_nested_math(mut self, allow: bool) -> Self {
        self.allow_nested_math = allow;
        self
    }

    /// Add a known environment name.
    pub fn add_environment(mut self, name: impl Into<String>) -> Self {
        self.known_environments.push(name.into());
        self
    }

    /// Validate a sequence of LaTeX tokens represented as strings.
    pub fn validate(&self, tokens: &[&str]) -> ValidationResult {
        let mut result = ValidationResult::valid();

        // Check brace balance
        self.validate_braces(tokens, &mut result);

        // Check environment matching
        self.validate_environments(tokens, &mut result);

        // Check math delimiter matching
        self.validate_math_delimiters(tokens, &mut result);

        result
    }

    /// Validate brace, bracket, and parenthesis matching.
    fn validate_braces(&self, tokens: &[&str], result: &mut ValidationResult) {
        let mut stack: Vec<(char, usize)> = Vec::new();

        for (pos, token) in tokens.iter().enumerate() {
            match *token {
                "{" => stack.push(('{', pos)),
                "}" => {
                    if let Some((open, _)) = stack.pop() {
                        if open != '{' {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::UnmatchedCloseBrace,
                                Some(pos),
                                format!(
                                    "Closing brace at position {} doesn't match opening '{}'",
                                    pos, open
                                ),
                            ));
                        }
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::UnmatchedCloseBrace,
                            Some(pos),
                            format!("Unmatched closing brace at position {}", pos),
                        ));
                    }
                }
                "[" => stack.push(('[', pos)),
                "]" => {
                    if let Some((open, _)) = stack.pop() {
                        if open != '[' {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::UnmatchedCloseBracket,
                                Some(pos),
                                format!(
                                    "Closing bracket at position {} doesn't match opening '{}'",
                                    pos, open
                                ),
                            ));
                        }
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::UnmatchedCloseBracket,
                            Some(pos),
                            format!("Unmatched closing bracket at position {}", pos),
                        ));
                    }
                }
                "(" => stack.push(('(', pos)),
                ")" => {
                    if let Some((open, _)) = stack.pop() {
                        if open != '(' {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::UnmatchedCloseParen,
                                Some(pos),
                                format!(
                                    "Closing paren at position {} doesn't match opening '{}'",
                                    pos, open
                                ),
                            ));
                        }
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::UnmatchedCloseParen,
                            Some(pos),
                            format!("Unmatched closing parenthesis at position {}", pos),
                        ));
                    }
                }
                _ => {}
            }
        }

        // Check for unclosed delimiters
        for (open, pos) in stack {
            let kind = match open {
                '{' => IssueKind::UnmatchedOpenBrace,
                '[' => IssueKind::UnmatchedOpenBracket,
                '(' => IssueKind::UnmatchedOpenParen,
                _ => continue,
            };
            result.add_issue(ValidationIssue::error(
                kind,
                Some(pos),
                format!("Unclosed '{}' at position {}", open, pos),
            ));
        }
    }

    /// Validate environment begin/end matching.
    fn validate_environments(&self, tokens: &[&str], result: &mut ValidationResult) {
        let mut env_stack: VecDeque<(String, usize)> = VecDeque::new();
        let mut i = 0;

        while i < tokens.len() {
            if tokens[i] == "\\begin" && i + 3 < tokens.len() {
                // Look for pattern: \begin { envname }
                if tokens[i + 1] == "{" && tokens[i + 3] == "}" {
                    let env_name = tokens[i + 2].to_string();

                    // Check for unknown environment
                    if self.validate_environments && !self.known_environments.contains(&env_name) {
                        result.add_issue(ValidationIssue::warning(
                            IssueKind::UnknownEnvironment,
                            Some(i),
                            format!("Unknown environment '{}' at position {}", env_name, i),
                        ));
                    }

                    env_stack.push_back((env_name, i));
                    i += 4;
                    continue;
                }
            }

            if tokens[i] == "\\end" && i + 3 < tokens.len() {
                // Look for pattern: \end { envname }
                if tokens[i + 1] == "{" && tokens[i + 3] == "}" {
                    let env_name = tokens[i + 2].to_string();

                    if let Some((open_name, open_pos)) = env_stack.pop_back() {
                        if open_name != env_name {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::EnvironmentMismatch,
                                Some(i),
                                format!(
                                    "Environment mismatch: \\begin{{{}}} at {} closed by \\end{{{}}} at {}",
                                    open_name, open_pos, env_name, i
                                ),
                            ));
                        }
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::ExtraEnvironmentEnd,
                            Some(i),
                            format!(
                                "Extra \\end{{{}}} at position {} without matching \\begin",
                                env_name, i
                            ),
                        ));
                    }

                    i += 4;
                    continue;
                }
            }

            i += 1;
        }

        // Check for unclosed environments
        while let Some((name, pos)) = env_stack.pop_front() {
            result.add_issue(ValidationIssue::error(
                IssueKind::MissingEnvironmentEnd,
                Some(pos),
                format!(
                    "Unclosed environment '{}' starting at position {}",
                    name, pos
                ),
            ));
        }
    }

    /// Validate math delimiter matching.
    fn validate_math_delimiters(&self, tokens: &[&str], result: &mut ValidationResult) {
        let mut in_inline_math = false;
        let mut in_display_math = false;
        let mut inline_start: Option<usize> = None;
        let mut display_start: Option<usize> = None;

        for (pos, token) in tokens.iter().enumerate() {
            match *token {
                "$" => {
                    if in_display_math {
                        // Check if this might be closing $$
                        continue;
                    }
                    if in_inline_math {
                        in_inline_math = false;
                        inline_start = None;
                    } else {
                        if !self.allow_nested_math && in_display_math {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::NestedMathMode,
                                Some(pos),
                                format!("Nested math mode at position {}", pos),
                            ));
                        }
                        in_inline_math = true;
                        inline_start = Some(pos);
                    }
                }
                "$$" => {
                    if in_display_math {
                        in_display_math = false;
                        display_start = None;
                    } else {
                        if !self.allow_nested_math && in_inline_math {
                            result.add_issue(ValidationIssue::error(
                                IssueKind::NestedMathMode,
                                Some(pos),
                                format!("Nested display math mode at position {}", pos),
                            ));
                        }
                        in_display_math = true;
                        display_start = Some(pos);
                    }
                }
                "\\[" => {
                    if !self.allow_nested_math && (in_inline_math || in_display_math) {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::NestedMathMode,
                            Some(pos),
                            format!("Nested display math mode at position {}", pos),
                        ));
                    }
                    in_display_math = true;
                    display_start = Some(pos);
                }
                "\\]" => {
                    if in_display_math {
                        in_display_math = false;
                        display_start = None;
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::UnmatchedMathDelimiter,
                            Some(pos),
                            format!("Unmatched \\] at position {}", pos),
                        ));
                    }
                }
                "\\(" => {
                    if !self.allow_nested_math && (in_inline_math || in_display_math) {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::NestedMathMode,
                            Some(pos),
                            format!("Nested inline math mode at position {}", pos),
                        ));
                    }
                    in_inline_math = true;
                    inline_start = Some(pos);
                }
                "\\)" => {
                    if in_inline_math {
                        in_inline_math = false;
                        inline_start = None;
                    } else {
                        result.add_issue(ValidationIssue::error(
                            IssueKind::UnmatchedMathDelimiter,
                            Some(pos),
                            format!("Unmatched \\) at position {}", pos),
                        ));
                    }
                }
                _ => {}
            }
        }

        // Check for unclosed math modes
        if let Some(pos) = inline_start {
            result.add_issue(ValidationIssue::error(
                IssueKind::UnmatchedMathDelimiter,
                Some(pos),
                format!("Unclosed inline math starting at position {}", pos),
            ));
        }
        if let Some(pos) = display_start {
            result.add_issue(ValidationIssue::error(
                IssueKind::UnmatchedMathDelimiter,
                Some(pos),
                format!("Unclosed display math starting at position {}", pos),
            ));
        }
    }
}

/// Default list of known LaTeX environments.
fn default_environments() -> Vec<String> {
    vec![
        // Document structure
        "document",
        "abstract",
        "titlepage",
        // Sectioning
        "part",
        "chapter",
        "section",
        "subsection",
        // Lists
        "itemize",
        "enumerate",
        "description",
        // Math
        "equation",
        "equation*",
        "align",
        "align*",
        "gather",
        "gather*",
        "multline",
        "multline*",
        "split",
        "cases",
        "aligned",
        "gathered",
        // Matrices
        "matrix",
        "pmatrix",
        "bmatrix",
        "vmatrix",
        "Vmatrix",
        "Bmatrix",
        // Floats
        "figure",
        "figure*",
        "table",
        "table*",
        // Tables
        "tabular",
        "tabular*",
        "array",
        "tabularx",
        // Theorems
        "theorem",
        "lemma",
        "corollary",
        "proposition",
        "definition",
        "example",
        "remark",
        "proof",
        // Formatting
        "center",
        "flushleft",
        "flushright",
        "quote",
        "quotation",
        "verse",
        // Code
        "verbatim",
        "lstlisting",
        // Bibliography
        "thebibliography",
        // Misc
        "minipage",
        "picture",
        "tikzpicture",
    ]
    .into_iter()
    .map(String::from)
    .collect()
}

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

    #[test]
    fn test_valid_braces() {
        let validator = LatexValidator::new();
        let tokens = vec!["{", "content", "}"];
        let result = validator.validate(&tokens);
        assert!(result.is_valid);
    }

    #[test]
    fn test_unmatched_open_brace() {
        let validator = LatexValidator::new();
        let tokens = vec!["{", "content"];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::UnmatchedOpenBrace));
    }

    #[test]
    fn test_unmatched_close_brace() {
        let validator = LatexValidator::new();
        let tokens = vec!["content", "}"];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::UnmatchedCloseBrace));
    }

    #[test]
    fn test_valid_environment() {
        let validator = LatexValidator::new();
        let tokens = vec![
            "\\begin", "{", "equation", "}", "x", "\\end", "{", "equation", "}",
        ];
        let result = validator.validate(&tokens);
        assert!(result.is_valid);
    }

    #[test]
    fn test_mismatched_environment() {
        let validator = LatexValidator::new();
        let tokens = vec![
            "\\begin", "{", "equation", "}", "x", "\\end", "{", "align", "}",
        ];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::EnvironmentMismatch));
    }

    #[test]
    fn test_unclosed_environment() {
        let validator = LatexValidator::new();
        let tokens = vec!["\\begin", "{", "equation", "}", "x"];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::MissingEnvironmentEnd));
    }

    #[test]
    fn test_valid_inline_math() {
        let validator = LatexValidator::new();
        let tokens = vec!["$", "x", "$"];
        let result = validator.validate(&tokens);
        assert!(result.is_valid);
    }

    #[test]
    fn test_unclosed_inline_math() {
        let validator = LatexValidator::new();
        let tokens = vec!["$", "x"];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::UnmatchedMathDelimiter));
    }

    #[test]
    fn test_unknown_environment_warning() {
        let validator = LatexValidator::new();
        let tokens = vec![
            "\\begin", "{", "myenv", "}", "x", "\\end", "{", "myenv", "}",
        ];
        let result = validator.validate(&tokens);
        // Should be valid but have a warning
        assert!(result.is_valid);
        assert!(result
            .issues
            .iter()
            .any(|i| i.kind == IssueKind::UnknownEnvironment));
    }

    #[test]
    fn test_nested_brackets() {
        let validator = LatexValidator::new();
        let tokens = vec!["{", "[", "(", ")", "]", "}"];
        let result = validator.validate(&tokens);
        assert!(result.is_valid);
    }

    #[test]
    fn test_mismatched_brackets() {
        let validator = LatexValidator::new();
        let tokens = vec!["{", "[", "}", "]"];
        let result = validator.validate(&tokens);
        assert!(!result.is_valid);
    }
}