quickmark-core 1.1.0

Lightning-fast Markdown/CommonMark linter core library with tree-sitter based parsing
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
use serde::Deserialize;
use std::collections::HashSet;
use std::rc::Rc;
use tree_sitter::Node;

use crate::{
    linter::{CharPosition, Context, Range, RuleLinter, RuleViolation},
    rules::{Rule, RuleType},
};

// MD040-specific configuration types
#[derive(Debug, PartialEq, Clone, Deserialize, Default)]
pub struct MD040FencedCodeLanguageTable {
    #[serde(default)]
    pub allowed_languages: Vec<String>,
    #[serde(default)]
    pub language_only: bool,
}

pub(crate) struct MD040Linter {
    context: Rc<Context>,
    violations: Vec<RuleViolation>,
}

impl MD040Linter {
    pub fn new(context: Rc<Context>) -> Self {
        Self {
            context,
            violations: Vec::new(),
        }
    }

    /// Extracts the language identifier from a fenced code block's first line.
    /// This handles common variations like attributes (e.g., ```rust{{...}}).
    /// Returns `(Option<language>, has_extra_info)`. The language is a slice
    /// of the input line to avoid allocations.
    fn extract_code_block_language<'a>(&self, line: &'a str) -> (Option<&'a str>, bool) {
        let trimmed = line.trim_start();
        let marker = if trimmed.starts_with("```") {
            "```"
        } else if trimmed.starts_with("~~~") {
            "~~~"
        } else {
            return (None, false);
        };

        let info_string = trimmed[marker.len()..].trim();

        if info_string.is_empty() {
            return (None, false);
        }

        let mut parts = info_string.split_whitespace();
        // The unwrap is safe because we've checked that info_string is not empty.
        let language_part = parts.next().unwrap();
        let has_extra_info = parts.next().is_some();

        // The unwrap is safe because split always returns an iterator with at least one element.
        let language = language_part.split('{').next().unwrap();

        if language.is_empty() {
            (None, has_extra_info)
        } else {
            (Some(language), has_extra_info)
        }
    }
}

impl RuleLinter for MD040Linter {
    fn feed(&mut self, _node: &Node) {
        // MD040 uses Document pattern, not Token pattern
        // All processing happens in finalize()
    }

    fn finalize(&mut self) -> Vec<RuleViolation> {
        let config = &self.context.config.linters.settings.fenced_code_language;
        let node_cache = self.context.node_cache.borrow();
        let lines = self.context.lines.borrow();

        // For performance, convert allowed_languages to a HashSet if it's not empty.
        let allowed_languages_set: Option<HashSet<&str>> = if !config.allowed_languages.is_empty() {
            Some(
                config
                    .allowed_languages
                    .iter()
                    .map(String::as_str)
                    .collect(),
            )
        } else {
            None
        };

        if let Some(fenced_code_blocks) = node_cache.get("fenced_code_block") {
            for node_info in fenced_code_blocks {
                if let Some(first_line) = lines.get(node_info.line_start) {
                    let (language_opt, has_extra_info) =
                        self.extract_code_block_language(first_line);

                    let range = Range {
                        start: CharPosition {
                            line: node_info.line_start,
                            character: 0,
                        },
                        end: CharPosition {
                            line: node_info.line_start,
                            character: first_line.len(),
                        },
                    };

                    let language = match language_opt {
                        Some(lang) => lang,
                        None => {
                            self.violations.push(RuleViolation::new(
                                &MD040,
                                "Fenced code blocks should have a language specified".to_string(),
                                self.context.file_path.clone(),
                                range,
                            ));
                            continue;
                        }
                    };

                    if let Some(set) = &allowed_languages_set {
                        if !set.contains(language) {
                            self.violations.push(RuleViolation::new(
                                &MD040,
                                format!("\"{language}\" is not allowed"),
                                self.context.file_path.clone(),
                                range,
                            ));
                            continue;
                        }
                    }

                    // Check if language_only is true and there's extra metadata
                    if config.language_only && has_extra_info {
                        let range = Range {
                            start: CharPosition {
                                line: node_info.line_start,
                                character: 0,
                            },
                            end: CharPosition {
                                line: node_info.line_start,
                                character: first_line.len(),
                            },
                        };
                        let violation = RuleViolation::new(
                            &MD040,
                            format!(
                                "Info string contains more than language: \"{}\"",
                                first_line.trim()
                            ),
                            self.context.file_path.clone(),
                            range,
                        );
                        self.violations.push(violation);
                    }
                }
            }
        }

        std::mem::take(&mut self.violations)
    }
}

pub const MD040: Rule = Rule {
    id: "MD040",
    alias: "fenced-code-language",
    tags: &["code", "language"],
    description: "Fenced code blocks should have a language specified",
    rule_type: RuleType::Document,
    required_nodes: &["fenced_code_block"],
    new_linter: |context| Box::new(MD040Linter::new(context)),
};

#[cfg(test)]
mod test {
    use std::path::PathBuf;

    use crate::config::{LintersSettingsTable, MD040FencedCodeLanguageTable, RuleSeverity};
    use crate::linter::MultiRuleLinter;
    use crate::test_utils::test_helpers::test_config_with_settings;

    fn test_config_default() -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("fenced-code-language", RuleSeverity::Error)],
            LintersSettingsTable {
                fenced_code_language: MD040FencedCodeLanguageTable {
                    allowed_languages: vec![],
                    language_only: false,
                },
                ..Default::default()
            },
        )
    }

    fn test_config_with_allowed_languages(
        allowed_languages: Vec<&str>,
    ) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("fenced-code-language", RuleSeverity::Error)],
            LintersSettingsTable {
                fenced_code_language: MD040FencedCodeLanguageTable {
                    allowed_languages: allowed_languages.iter().map(|s| s.to_string()).collect(),
                    language_only: false,
                },
                ..Default::default()
            },
        )
    }

    fn test_config_with_language_only(language_only: bool) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("fenced-code-language", RuleSeverity::Error)],
            LintersSettingsTable {
                fenced_code_language: MD040FencedCodeLanguageTable {
                    allowed_languages: vec![],
                    language_only,
                },
                ..Default::default()
            },
        )
    }

    fn test_config_with_both_options(
        allowed_languages: Vec<&str>,
        language_only: bool,
    ) -> crate::config::QuickmarkConfig {
        test_config_with_settings(
            vec![("fenced-code-language", RuleSeverity::Error)],
            LintersSettingsTable {
                fenced_code_language: MD040FencedCodeLanguageTable {
                    allowed_languages: allowed_languages.iter().map(|s| s.to_string()).collect(),
                    language_only,
                },
                ..Default::default()
            },
        )
    }

    #[test]
    fn test_fenced_code_with_language_no_violations() {
        let config = test_config_default();
        let input = "# Test

```rust
fn main() {
    println!(\"Hello, World!\");
}
```

```javascript
console.log('Hello, World!');
```

```text
Plain text content
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();
        assert_eq!(md040_violations.len(), 0);
    }

    #[test]
    fn test_fenced_code_without_language_violations() {
        let config = test_config_default();
        let input = "# Test

```
def hello():
    print(\"Hello, World!\")
```

```rust
fn main() {
    println!(\"Hello, World!\");
}
```

```
console.log('Hello, World!');
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 2 violations: the two fenced code blocks without languages
        assert_eq!(md040_violations.len(), 2);
    }

    #[test]
    fn test_allowed_languages_specific_list() {
        let config = test_config_with_allowed_languages(vec!["rust", "python"]);
        let input = "# Test

```rust
fn main() {}
```

```python
def hello(): pass
```

```javascript
console.log('not allowed');
```

```
no language specified
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 2 violations: javascript (not in allowed list) and no language
        assert_eq!(md040_violations.len(), 2);
        assert!(md040_violations
            .iter()
            .any(|v| v.message().contains("javascript")));
    }

    #[test]
    fn test_language_only_option_no_extra_info() {
        let config = test_config_with_language_only(true);
        let input = "# Test

```rust
fn main() {}
```

```python {.line-numbers}
def hello(): pass
```

```javascript copy
console.log('Hello');
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 2 violations: python and javascript have extra info beyond language
        assert_eq!(md040_violations.len(), 2);
    }

    #[test]
    fn test_language_only_option_language_only_allowed() {
        let config = test_config_with_language_only(true);
        let input = "# Test

```rust
fn main() {}
```

```python
def hello(): pass
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find no violations: both have only language specified
        assert_eq!(md040_violations.len(), 0);
    }

    #[test]
    fn test_combined_options() {
        let config = test_config_with_both_options(vec!["rust", "python"], true);
        let input = "# Test

```rust
fn main() {}
```

```python copy
def hello(): pass
```

```javascript
console.log('Hello');
```

```
no language
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 3 violations:
        // 1. python has extra info (violates language_only)
        // 2. javascript not in allowed list
        // 3. no language specified
        assert_eq!(md040_violations.len(), 3);
    }

    #[test]
    fn test_indented_code_blocks_ignored() {
        let config = test_config_default();
        let input = "# Test

    def hello():
        print(\"This is indented code\")

```
def hello():
    print(\"This is fenced code without language\")
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find only 1 violation: the fenced code block without language
        // Indented code blocks should be ignored
        assert_eq!(md040_violations.len(), 1);
    }

    #[test]
    fn test_case_sensitivity_in_languages() {
        let config = test_config_with_allowed_languages(vec!["rust", "PYTHON"]);
        let input = "# Test

```Rust
fn main() {}
```

```python
def hello(): pass
```

```PYTHON
def hello(): pass
```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 2 violations: "Rust" and "python" don't match case-sensitive allowed list
        assert_eq!(md040_violations.len(), 2);
    }

    #[test]
    fn test_empty_fenced_code_blocks() {
        let config = test_config_default();
        let input = "# Test

```

```

```rust

```";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 1 violation: the first block has no language
        assert_eq!(md040_violations.len(), 1);
    }

    #[test]
    fn test_tildes_fenced_code_blocks() {
        let config = test_config_default();
        let input = "# Test

~~~
def hello():
    print(\"Hello\")
~~~

~~~python
def hello():
    print(\"Hello\")
~~~";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        let md040_violations: Vec<_> = violations
            .iter()
            .filter(|v| v.rule().id == "MD040")
            .collect();

        // Should find 1 violation: the first block has no language
        assert_eq!(md040_violations.len(), 1);
    }
}