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
use std::{cell::RefCell, collections::HashMap, fmt::Display, path::PathBuf, rc::Rc};
use tree_sitter::{Node, Parser};
use tree_sitter_md::LANGUAGE;

use crate::{
    config::{QuickmarkConfig, RuleSeverity},
    rules::{Rule, ALL_RULES},
    tree_sitter_walker::TreeSitterWalker,
};

#[derive(Debug, Clone)]
pub struct CharPosition {
    pub line: usize,
    pub character: usize,
}

#[derive(Debug, Clone)]
pub struct Range {
    pub start: CharPosition,
    pub end: CharPosition,
}
#[derive(Debug)]
pub struct Location {
    pub file_path: PathBuf,
    pub range: Range,
}

#[derive(Debug)]
pub struct RuleViolation {
    location: Location,
    message: String,
    rule: &'static Rule,
    pub(crate) severity: RuleSeverity,
}

impl RuleViolation {
    pub fn new(rule: &'static Rule, message: String, file_path: PathBuf, range: Range) -> Self {
        Self {
            rule,
            message,
            location: Location { file_path, range },
            severity: RuleSeverity::Error, // Default, will be overridden by MultiRuleLinter
        }
    }

    pub fn location(&self) -> &Location {
        &self.location
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn rule(&self) -> &'static Rule {
        self.rule
    }

    pub fn severity(&self) -> &RuleSeverity {
        &self.severity
    }
}

/// Convert from tree-sitter range to library range
pub fn range_from_tree_sitter(ts_range: &tree_sitter::Range) -> Range {
    Range {
        start: CharPosition {
            line: ts_range.start_point.row,
            character: ts_range.start_point.column,
        },
        end: CharPosition {
            line: ts_range.end_point.row,
            character: ts_range.end_point.column,
        },
    }
}

impl Display for RuleViolation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}:{}:{} {}/{} {}",
            self.location().file_path.to_string_lossy(),
            self.location().range.start.line,
            self.location().range.start.character,
            self.rule().id,
            self.rule().alias,
            self.message()
        )
    }
}

/// **SINGLE-USE CONTRACT**: Context instances are designed for one-time use only.
///
/// Each Context instance should be used to analyze exactly one source document.
/// The lazy initialization of caches (lines, node_cache) happens once and the
/// context becomes immutable after that point.
///
#[derive(Debug)]
pub struct Context {
    pub file_path: PathBuf,
    pub config: QuickmarkConfig,
    /// Raw text lines for line-based rules (MD013, MD010, etc.) - initialized once per document
    pub lines: RefCell<Vec<String>>,
    /// Cached AST nodes filtered by type for efficient access - initialized once per document
    pub node_cache: RefCell<HashMap<String, Vec<NodeInfo>>>,
    /// Original document content for byte-based access - initialized once per document
    pub document_content: RefCell<String>,
}

/// Lightweight node information for caching
#[derive(Debug, Clone)]
pub struct NodeInfo {
    pub line_start: usize,
    pub line_end: usize,
    pub kind: String,
}

impl Context {
    pub fn new(
        file_path: PathBuf,
        config: QuickmarkConfig,
        source: &str,
        root_node: &Node,
    ) -> Self {
        // Parse lines in a way that's compatible with markdownlint's line counting
        // markdownlint counts a trailing newline as creating an additional empty line
        let mut lines: Vec<String> = source.lines().map(String::from).collect();

        // If the source ends with a newline, add an empty line to match markdownlint's behavior
        if source.ends_with('\n') {
            lines.push(String::new());
        }
        let node_cache = Self::build_node_cache(root_node);

        Self {
            file_path,
            config,
            lines: RefCell::new(lines),
            node_cache: RefCell::new(node_cache),
            document_content: RefCell::new(source.to_string()),
        }
    }

    /// Get the full document content as a string reference
    /// Returns a reference to the original document content stored during initialization
    pub fn get_document_content(&self) -> std::cell::Ref<'_, String> {
        self.document_content.borrow()
    }

    /// Build cache of nodes filtered by type for efficient rule access
    fn build_node_cache(root_node: &Node) -> HashMap<String, Vec<NodeInfo>> {
        let mut cache = HashMap::new();
        Self::collect_nodes_recursive(root_node, &mut cache);
        cache
    }

    fn collect_nodes_recursive(node: &Node, cache: &mut HashMap<String, Vec<NodeInfo>>) {
        let kind = node.kind();
        let kind_string = kind.to_string();
        let node_info = NodeInfo {
            line_start: node.start_position().row,
            line_end: node.end_position().row,
            kind: kind_string.clone(),
        };

        // Add to cache for this node type
        cache
            .entry(kind_string)
            .or_default()
            .push(node_info.clone());

        // Add to cache for pattern-based lookups (e.g., all heading types)
        if kind.contains("heading") {
            cache
                .entry("*heading*".to_string())
                .or_default()
                .push(node_info);
        }

        // Recursively process children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                Self::collect_nodes_recursive(&child, cache);
            }
        }
    }

    /// Get cached nodes of specific types - optimized equivalent of filterByTypesCached
    pub fn get_nodes(&self, node_types: &[&str]) -> Vec<NodeInfo> {
        let cache = self.node_cache.borrow();
        let mut result = Vec::new();
        for node_type in node_types {
            if let Some(nodes) = cache.get(*node_type) {
                result.extend(nodes.iter().cloned());
            }
        }
        result
    }

    /// Get the most specific node type that contains a given line number
    pub fn get_node_type_for_line(&self, line_number: usize) -> String {
        let cache = self.node_cache.borrow();
        // Find the most specific (smallest range) node that contains this line
        let mut best_match: Option<&NodeInfo> = None;
        let mut smallest_range = usize::MAX;

        for nodes in cache.values() {
            for node in nodes {
                if line_number >= node.line_start && line_number <= node.line_end {
                    let range_size = node.line_end - node.line_start;
                    if range_size < smallest_range {
                        smallest_range = range_size;
                        best_match = Some(node);
                    }
                }
            }
        }

        best_match
            .map(|n| n.kind.clone())
            .unwrap_or_else(|| "text".to_string())
    }
}

/// **SINGLE-USE CONTRACT**: RuleLinter instances are designed for one-time use only.
///
/// Each RuleLinter instance should be used to analyze exactly one source document
/// and then discarded. This eliminates the complexity of state management and cleanup:
///
/// - No reset/cleanup methods needed
/// - No state contamination between different documents
/// - Simpler, more predictable behavior
///
/// After calling `analyze()` on a `MultiRuleLinter`, the entire linter and all its
/// rule instances become invalid and should not be reused.
///
/// ## Usage Pattern
/// ```rust,no_run
/// # use quickmark_core::linter::MultiRuleLinter;
/// # use quickmark_core::config::QuickmarkConfig;
/// # use std::path::PathBuf;
/// # let path = PathBuf::new();
/// # let config: QuickmarkConfig = unimplemented!();
/// # let source1 = "";
/// # let source2 = "";
///
/// // Correct: Create fresh linter for each document
/// let mut linter1 = MultiRuleLinter::new_for_document(path.clone(), config.clone(), source1);
/// let violations1 = linter1.analyze(); // Use once, then discard
///
/// // Create new linter for next document
/// let mut linter2 = MultiRuleLinter::new_for_document(path, config, source2);
/// let violations2 = linter2.analyze(); // Fresh linter, no contamination
/// ```
pub trait RuleLinter {
    /// Process a single AST node and accumulate state for violation detection.
    ///
    /// **CONTRACT**: This method will be called exactly once per AST node
    /// for a single document analysis session. Rule linters have access to the
    /// document content and parsed data through their initialized Context.
    fn feed(&mut self, node: &Node);

    /// Called after all nodes have been processed to return all violations found.
    ///
    /// **CONTRACT**: This method will be called exactly once at the end of document analysis.
    fn finalize(&mut self) -> Vec<RuleViolation>;
}
/// **SINGLE-USE CONTRACT**: MultiRuleLinter instances are designed for one-time use only.
///
/// Create a fresh MultiRuleLinter for each document you want to analyze using `new_for_document()`.
/// After calling `analyze()`, the linter and all its rule instances should be discarded.
pub struct MultiRuleLinter {
    linters: Vec<Box<dyn RuleLinter>>,
    tree: Option<tree_sitter::Tree>,
    config: QuickmarkConfig,
}

impl MultiRuleLinter {
    /// **SINGLE-USE API ENFORCEMENT**: Create a MultiRuleLinter bound to a specific document.
    ///
    /// This constructor enforces the single-use contract by:
    /// 1. Taking the document content immediately
    /// 2. Parsing and initializing the context cache upfront
    /// 3. Creating rule linters with pre-initialized context
    /// 4. Making the linter ready for immediate use with `analyze()`
    ///
    /// After calling `analyze()`, this linter instance should be discarded.
    pub fn new_for_document(file_path: PathBuf, config: QuickmarkConfig, document: &str) -> Self {
        // Early exit optimization: Check if any rules are enabled before expensive operations
        let active_rules: Vec<_> = ALL_RULES
            .iter()
            .filter(|r| {
                config
                    .linters
                    .severity
                    .get(r.alias)
                    .map(|severity| *severity != RuleSeverity::Off)
                    .unwrap_or(false)
            })
            .collect();

        // If no rules are active, create minimal linter that does no work
        if active_rules.is_empty() {
            return Self {
                linters: Vec::new(),
                tree: None,
                config,
            };
        }

        // Parse the document only when we have active rules
        let mut parser = Parser::new();
        parser
            .set_language(&LANGUAGE.into())
            .expect("Error loading Markdown grammar");
        let tree = parser.parse(document, None).expect("Parse failed");

        // Create context with pre-initialized cache only for active rules
        let context = Rc::new(Context::new(
            file_path,
            config.clone(),
            document,
            &tree.root_node(),
        ));

        // Create rule linters for active rules only
        let linters = active_rules
            .iter()
            .map(|r| ((r.new_linter)(context.clone())))
            .collect();

        Self {
            linters,
            tree: Some(tree),
            config,
        }
    }

    /// Analyze the document that was provided during construction.
    ///
    /// **SINGLE-USE CONTRACT**: This method should be called exactly once.
    /// After calling this method, the linter instance should be discarded.
    pub fn analyze(&mut self) -> Vec<RuleViolation> {
        // Early exit optimization: If no linters are active, return immediately
        if self.linters.is_empty() {
            return Vec::new();
        }

        // If we have linters but no tree (shouldn't happen), return empty
        let tree = match &self.tree {
            Some(tree) => tree,
            None => return Vec::new(),
        };

        let walker = TreeSitterWalker::new(tree);

        // Feed all nodes to all linters
        walker.walk(|node| {
            for linter in &mut self.linters {
                linter.feed(&node);
            }
        });

        // Collect all violations from finalize and inject severity from config
        let mut violations = Vec::new();
        for linter in &mut self.linters {
            let mut linter_violations = linter.finalize();
            // Inject severity into each violation based on current config
            for violation in &mut linter_violations {
                let severity = self
                    .config
                    .linters
                    .severity
                    .get(violation.rule().alias)
                    .cloned()
                    .unwrap_or(RuleSeverity::Error);
                violation.severity = severity;
            }
            violations.extend(linter_violations);
        }

        violations
    }
}

#[cfg(test)]
mod test {
    use std::{collections::HashMap, path::PathBuf};

    use crate::{
        config::{self, QuickmarkConfig, RuleSeverity},
        rules::{md001::MD001, md003::MD003, md013::MD013},
    };

    use super::MultiRuleLinter;

    #[test]
    fn test_multiple_violations() {
        let severity: HashMap<_, _> = vec![
            (MD001.alias.to_string(), RuleSeverity::Error),
            (MD003.alias.to_string(), RuleSeverity::Error),
            (MD013.alias.to_string(), RuleSeverity::Error),
        ]
        .into_iter()
        .collect();

        let config = QuickmarkConfig {
            linters: config::LintersTable {
                severity,
                settings: config::LintersSettingsTable {
                    heading_style: config::MD003HeadingStyleTable {
                        style: config::HeadingStyle::ATX,
                    },
                    ..Default::default()
                },
            },
        };

        // This creates a setext h1 after an ATX h1, which should violate:
        // MD003: mixes ATX and setext styles when ATX is enforced
        // It's also at the wrong level for MD001 testing, so let's use a different approach
        let input = "
# First heading
Second heading
==============
#### Fourth level
";

        let mut linter = MultiRuleLinter::new_for_document(PathBuf::from("test.md"), config, input);
        let violations = linter.analyze();
        assert_eq!(
            2,
            violations.len(),
            "Should find both MD001 and MD003 violations"
        );
        assert_eq!(MD001.id, violations[0].rule().id);
        assert_eq!(4, violations[0].location().range.start.line);
        assert_eq!(MD003.id, violations[1].rule().id);
        assert_eq!(2, violations[1].location().range.start.line);
    }
}