anyrepair 0.2.4

A comprehensive Rust crate for repairing malformed structured data including JSON, YAML, XML, TOML, CSV, INI, Markdown, and Diff with format auto-detection
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
//! Markdown repair module
//!
//! Provides comprehensive Markdown repair functionality with multiple strategies
//! for fixing common Markdown issues from LLM outputs.

use crate::error::Result;
use crate::traits::{Repair, RepairStrategy, Validator};
use regex::Regex;
use std::sync::OnceLock;

// ============================================================================
// Markdown Validator
// ============================================================================

/// Markdown validator
pub struct MarkdownValidator;

impl Validator for MarkdownValidator {
    fn is_valid(&self, content: &str) -> bool {
        // Basic markdown validation
        if content.is_empty() {
            return true;
        }

        // Check for balanced markers
        let bold_count = content.matches("**").count();
        let _italic_count = content.matches('*').count();
        let code_fence_count = content.matches("```").count();

        // Bold should be balanced
        if !bold_count.is_multiple_of(2) {
            return false;
        }

        // Code fences should be balanced
        if !code_fence_count.is_multiple_of(2) {
            return false;
        }

        // Check for malformed headers (# without space)
        for line in content.lines() {
            let trimmed = line.trim_start();
            if trimmed.starts_with('#') {
                // Count leading #
                let hash_count = trimmed.chars().take_while(|c| *c == '#').count();
                if hash_count <= 6 {
                    // Check if there's a space after the hashes
                    if let Some(ch) = trimmed.chars().nth(hash_count)
                        && ch != ' ' && ch != '\n' {
                            return false; // Malformed header
                        }
                }
            }
        }

        // Basic structure check
        

        !content.contains("[[") && !content.contains("]]")
    }

    fn validate(&self, content: &str) -> Vec<String> {
        let mut errors = Vec::new();

        if content.is_empty() {
            return errors;
        }

        // Check for unbalanced bold markers
        let bold_count = content.matches("**").count();
        if !bold_count.is_multiple_of(2) {
            errors.push("Unbalanced bold markers (**)".to_string());
        }

        // Check for unbalanced code fences
        let code_fence_count = content.matches("```").count();
        if !code_fence_count.is_multiple_of(2) {
            errors.push("Unbalanced code block fences (```)".to_string());
        }

        // Check for malformed links
        if content.contains("[[") || content.contains("]]") {
            errors.push("Malformed link syntax".to_string());
        }

        errors
    }
}

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

    #[test]
    fn test_valid_markdown() {
        let validator = MarkdownValidator;
        assert!(validator.is_valid("# Header\n\nSome content"));
    }

    #[test]
    fn test_invalid_markdown_unbalanced_bold() {
        let validator = MarkdownValidator;
        assert!(!validator.is_valid("**bold text"));
    }

    #[test]
    fn test_invalid_markdown_unbalanced_code() {
        let validator = MarkdownValidator;
        assert!(!validator.is_valid("```\ncode"));
    }

    #[test]
    fn test_validate_errors() {
        let validator = MarkdownValidator;
        let errors = validator.validate("**bold text");
        assert!(!errors.is_empty());
    }
}

// ============================================================================
// Regex Cache
// ============================================================================

/// Cached regex patterns for Markdown performance optimization
pub struct MarkdownRegexCache {
    pub header_spacing: Regex,
    pub code_block_fences: Regex,
    pub list_items: Regex,
    pub link_formatting: Regex,
    pub bold_italic: Regex,
}

impl MarkdownRegexCache {
    pub fn new() -> Result<Self> {
        Ok(Self {
            header_spacing: Regex::new(r#"(?m)^(#{1,6})([^#\s])"#)?,
            code_block_fences: Regex::new(r#"(?m)^```(\w+)?$"#)?,
            list_items: Regex::new(r#"(?m)^(\s*)(\d+\.)([^ ])"#)?,
            link_formatting: Regex::new(r#"\[([^\]]+)\]\(([^)]+)\)"#)?,
            bold_italic: Regex::new(r#"\*\*([^*]+)\*\*|\*([^*]+)\*"#)?,
        })
    }
}

static MARKDOWN_REGEX_CACHE: OnceLock<MarkdownRegexCache> = OnceLock::new();

pub fn get_markdown_regex_cache() -> &'static MarkdownRegexCache {
    MARKDOWN_REGEX_CACHE.get_or_init(|| {
        MarkdownRegexCache::new().expect("Failed to initialize Markdown regex cache")
    })
}

// ============================================================================
// Repair Strategies
// ============================================================================

/// Strategy to fix header spacing
pub struct FixHeaderSpacingStrategy;

impl RepairStrategy for FixHeaderSpacingStrategy {
    fn name(&self) -> &str {
        "FixHeaderSpacing"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let cache = get_markdown_regex_cache();
        Ok(cache
            .header_spacing
            .replace_all(content, "$1 $2")
            .to_string())
    }

    fn priority(&self) -> u8 {
        100
    }
}

/// Strategy to fix code block fences
pub struct FixCodeBlockFencesStrategy;

impl RepairStrategy for FixCodeBlockFencesStrategy {
    fn name(&self) -> &str {
        "FixCodeBlockFences"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        let mut result = String::new();
        let mut in_code_block = false;

        for line in lines {
            if line.trim().starts_with("```") {
                in_code_block = !in_code_block;
                result.push_str(line);
            } else {
                result.push_str(line);
            }
            result.push('\n');
        }

        Ok(result.trim_end().to_string())
    }

    fn priority(&self) -> u8 {
        90
    }
}

/// Strategy to fix list formatting
pub struct FixListFormattingStrategy;

impl RepairStrategy for FixListFormattingStrategy {
    fn name(&self) -> &str {
        "FixListFormatting"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let cache = get_markdown_regex_cache();
        Ok(cache.list_items.replace_all(content, "$1$2 $3").to_string())
    }

    fn priority(&self) -> u8 {
        85
    }
}

/// Strategy to fix link formatting
pub struct FixLinkFormattingStrategy;

impl RepairStrategy for FixLinkFormattingStrategy {
    fn name(&self) -> &str {
        "FixLinkFormatting"
    }

    fn apply(&self, content: &str) -> Result<String> {
        // Validate and fix link syntax
        let mut result = content.to_string();

        // Fix common link issues
        result = result.replace("[ ", "[");
        result = result.replace(" ]", "]");
        result = result.replace("( ", "(");
        result = result.replace(" )", ")");

        Ok(result)
    }

    fn priority(&self) -> u8 {
        80
    }
}

/// Strategy to fix bold and italic formatting
pub struct FixBoldItalicStrategy;

impl RepairStrategy for FixBoldItalicStrategy {
    fn name(&self) -> &str {
        "FixBoldItalic"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = content.to_string();

        // Fix unmatched bold markers
        let bold_count = result.matches("**").count();
        if !bold_count.is_multiple_of(2) {
            result.push_str("**");
        }

        // Fix unmatched italic markers
        let italic_count = result.matches('*').count();
        if !italic_count.is_multiple_of(2) {
            result.push('*');
        }

        Ok(result)
    }

    fn priority(&self) -> u8 {
        75
    }
}

/// Strategy to add missing newlines
pub struct AddMissingNewlinesStrategy;

impl RepairStrategy for AddMissingNewlinesStrategy {
    fn name(&self) -> &str {
        "AddMissingNewlines"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        let mut result = String::new();

        for (i, line) in lines.iter().enumerate() {
            result.push_str(line);

            // Add newline after headers and code blocks
            if (line.trim().starts_with('#') || line.trim().starts_with("```"))
                && i < lines.len() - 1 && !lines[i + 1].is_empty() {
                    result.push('\n');
                }

            result.push('\n');
        }

        Ok(result.trim_end().to_string())
    }

    fn priority(&self) -> u8 {
        70
    }
}

/// Strategy to fix table formatting
pub struct FixTableFormattingStrategy;

impl RepairStrategy for FixTableFormattingStrategy {
    fn name(&self) -> &str {
        "FixTableFormatting"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        let mut result = String::new();

        for line in lines.iter() {
            if line.contains('|') {
                // Ensure proper spacing around pipes
                let fixed = line.replace("| ", "|").replace(" |", "|");
                let fixed = fixed.replace("|", " | ");
                result.push_str(&fixed);
            } else {
                result.push_str(line);
            }
            result.push('\n');
        }

        Ok(result.trim_end().to_string())
    }

    fn priority(&self) -> u8 {
        65
    }
}

/// Strategy to fix nested lists
pub struct FixNestedListsStrategy;

impl RepairStrategy for FixNestedListsStrategy {
    fn name(&self) -> &str {
        "FixNestedLists"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let lines: Vec<&str> = content.lines().collect();
        let mut result = String::new();

        for line in lines {
            let trimmed = line.trim_start();
            let indent = line.len() - trimmed.len();

            // Fix list item formatting
            if trimmed.starts_with('-') || trimmed.starts_with('*') || trimmed.starts_with('+') {
                let marker = trimmed.chars().next().unwrap();
                let content_part = trimmed.trim_start_matches([marker, ' ']);
                result.push_str(&format!(
                    "{}{} {}",
                    " ".repeat(indent),
                    marker,
                    content_part
                ));
            } else {
                result.push_str(line);
            }
            result.push('\n');
        }

        Ok(result.trim_end().to_string())
    }

    fn priority(&self) -> u8 {
        60
    }
}

/// Strategy to fix image syntax
pub struct FixImageSyntaxStrategy;

impl RepairStrategy for FixImageSyntaxStrategy {
    fn name(&self) -> &str {
        "FixImageSyntax"
    }

    fn apply(&self, content: &str) -> Result<String> {
        let mut result = content.to_string();

        // Fix common image syntax issues
        result = result.replace("![ ", "![");
        result = result.replace(" ]", "]");
        result = result.replace("( ", "(");
        result = result.replace(" )", ")");

        Ok(result)
    }

    fn priority(&self) -> u8 {
        55
    }
}

// ============================================================================
// Markdown Repairer
// ============================================================================

/// Markdown repairer that can fix common Markdown issues
///
/// Uses trait-based composition with GenericRepairer for better modularity
pub struct MarkdownRepairer {
    inner: crate::repairer_base::GenericRepairer,
}

impl MarkdownRepairer {
    /// Create a new Markdown repairer
    pub fn new() -> Self {
        let strategies: Vec<Box<dyn RepairStrategy>> = vec![
            Box::new(FixHeaderSpacingStrategy),
            Box::new(FixCodeBlockFencesStrategy),
            Box::new(FixListFormattingStrategy),
            Box::new(FixLinkFormattingStrategy),
            Box::new(FixBoldItalicStrategy),
            Box::new(AddMissingNewlinesStrategy),
            Box::new(FixTableFormattingStrategy),
            Box::new(FixNestedListsStrategy),
            Box::new(FixImageSyntaxStrategy),
        ];

        let validator: Box<dyn Validator> = Box::new(MarkdownValidator);
        let inner = crate::repairer_base::GenericRepairer::new(validator, strategies);

        Self { inner }
    }
}

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

impl Repair for MarkdownRepairer {
    fn repair(&mut self, content: &str) -> Result<String> {
        self.inner.repair(content)
    }

    fn needs_repair(&self, content: &str) -> bool {
        self.inner.needs_repair(content)
    }

    fn confidence(&self, content: &str) -> f64 {
        if self.inner.validator().is_valid(content) {
            return 1.0;
        }

        let mut score: f64 = 0.0;

        // Check for markdown structure
        if content.contains('#') {
            score += 0.2;
        }

        if content.contains("```") {
            score += 0.2;
        }

        if content.contains('[') && content.contains(']') {
            score += 0.2;
        }

        if content.contains('*') || content.contains('_') {
            score += 0.2;
        }

        if content.contains('-') || content.contains('+') {
            score += 0.1;
        }

        score.min(1.0_f64)
    }
}

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

    #[test]
    fn test_markdown_repairer_creation() {
        let repairer = MarkdownRepairer::new();
        assert!(!repairer.inner.strategies().is_empty());
    }

    #[test]
    fn test_markdown_repairer_default() {
        let repairer = MarkdownRepairer::default();
        assert!(!repairer.inner.strategies().is_empty());
    }

    #[test]
    fn test_markdown_confidence_valid() {
        let repairer = MarkdownRepairer::new();
        let confidence = repairer.confidence("# Header\n\nContent");
        assert_eq!(confidence, 1.0);
    }

    #[test]
    fn test_markdown_confidence_invalid() {
        let repairer = MarkdownRepairer::new();
        let confidence = repairer.confidence("**bold text");
        assert!(confidence < 1.0);
        assert!(confidence > 0.0);
    }

    #[test]
    fn test_markdown_needs_repair() {
        let repairer = MarkdownRepairer::new();
        assert!(!repairer.needs_repair("# Header\n\nContent"));
        assert!(repairer.needs_repair("**bold text"));
    }
}