Skip to main content

rumdl_lib/utils/
regex_cache.rs

1//!
2//! Cached Regex Patterns and Fast Content Checks for Markdown Linting
3//!
4//! This module provides a centralized collection of pre-compiled, cached regex patterns
5//! for all major Markdown constructs (headings, lists, code blocks, links, images, etc.).
6//! It also includes fast-path utility functions for quickly checking if content
7//! potentially contains certain Markdown elements, allowing rules to skip expensive
8//! processing when unnecessary.
9//!
10//! # Performance
11//!
12//! All regexes are compiled once at startup using `lazy_static`, avoiding repeated
13//! compilation and improving performance across the linter. Use these shared patterns
14//! in rules instead of compiling new regexes.
15//!
16//! # Usage
17//!
18//! - Use the provided statics for common Markdown patterns.
19//! - Use the `regex_lazy!` macro for ad-hoc regexes that are not predefined.
20//! - Use the utility functions for fast content checks before running regexes.
21
22use fancy_regex::Regex as FancyRegex;
23use regex::Regex;
24use std::collections::HashMap;
25use std::sync::LazyLock;
26use std::sync::{Arc, Mutex};
27
28/// Global regex cache for dynamic patterns
29#[derive(Debug)]
30pub struct RegexCache {
31    cache: HashMap<String, Arc<Regex>>,
32    usage_stats: HashMap<String, u64>,
33}
34
35impl Default for RegexCache {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl RegexCache {
42    pub fn new() -> Self {
43        Self {
44            cache: HashMap::new(),
45            usage_stats: HashMap::new(),
46        }
47    }
48
49    /// Get or compile a regex pattern
50    pub fn get_regex(&mut self, pattern: &str) -> Result<Arc<Regex>, regex::Error> {
51        if let Some(regex) = self.cache.get(pattern) {
52            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
53            return Ok(regex.clone());
54        }
55
56        let regex = Arc::new(Regex::new(pattern)?);
57        self.cache.insert(pattern.to_string(), regex.clone());
58        *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
59        Ok(regex)
60    }
61
62    /// Get cache statistics
63    pub fn get_stats(&self) -> HashMap<String, u64> {
64        self.usage_stats.clone()
65    }
66
67    /// Clear cache (useful for testing)
68    pub fn clear(&mut self) {
69        self.cache.clear();
70        self.usage_stats.clear();
71    }
72}
73
74/// Global regex cache instance
75static GLOBAL_REGEX_CACHE: LazyLock<Arc<Mutex<RegexCache>>> = LazyLock::new(|| Arc::new(Mutex::new(RegexCache::new())));
76
77/// Get a regex from the global cache
78///
79/// If the mutex is poisoned (another thread panicked while holding the lock),
80/// this function recovers by clearing the cache and continuing. This ensures
81/// the library never panics due to mutex poisoning.
82pub fn get_cached_regex(pattern: &str) -> Result<Arc<Regex>, regex::Error> {
83    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
84        // Recover from poisoned mutex by clearing the cache
85        let mut guard = poisoned.into_inner();
86        guard.clear();
87        guard
88    });
89    cache.get_regex(pattern)
90}
91
92/// Get cache usage statistics
93///
94/// If the mutex is poisoned, returns an empty HashMap rather than panicking.
95pub fn get_cache_stats() -> HashMap<String, u64> {
96    match GLOBAL_REGEX_CACHE.lock() {
97        Ok(cache) => cache.get_stats(),
98        Err(_) => HashMap::new(),
99    }
100}
101
102/// Macro for defining a lazily-initialized, cached regex pattern.
103///
104/// Use this for ad-hoc regexes that are not already defined in this module.
105///
106/// # Panics
107///
108/// This macro will panic at initialization if the regex pattern is invalid.
109/// This is intentional for compile-time constant patterns - we want to catch
110/// invalid patterns during development, not at runtime.
111///
112/// # Example
113///
114/// ```
115/// use std::sync::LazyLock;
116/// use rumdl_lib::regex_lazy;
117/// let my_re = regex_lazy!(r"^foo.*bar$");
118/// assert!(my_re.is_match("foobar"));
119/// ```
120#[macro_export]
121macro_rules! regex_lazy {
122    ($pattern:expr) => {{
123        static REGEX: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new($pattern).unwrap());
124        &*REGEX
125    }};
126}
127
128/// Macro for getting regex from global cache.
129///
130/// # Panics
131///
132/// Panics if the regex pattern is invalid. This is acceptable for static patterns
133/// where we want to fail fast during development.
134#[macro_export]
135macro_rules! regex_cached {
136    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_regex($pattern).expect("Failed to compile regex") }};
137}
138
139// Also make the macro available directly from this module
140pub use crate::regex_lazy;
141
142// =============================================================================
143// URL REGEX PATTERNS - Centralized URL Detection
144// =============================================================================
145//
146// ## Pattern Hierarchy (use the most specific pattern for your needs):
147//
148// | Pattern              | Use Case                                    | Parens | Trailing Punct |
149// |----------------------|---------------------------------------------|--------|----------------|
150// | URL_STANDARD_REGEX   | MD034 bare URL detection with auto-fix      | Yes    | Captured*      |
151// | URL_WWW_REGEX        | www.domain URLs without protocol            | Yes    | Captured*      |
152// | URL_IPV6_REGEX       | IPv6 URLs like https://[::1]/path           | Yes    | Captured*      |
153// | URL_QUICK_CHECK_REGEX| Fast early-exit check (contains URL?)       | N/A    | N/A            |
154// | URL_SIMPLE_REGEX     | Content detection, line length exemption    | No     | Excluded       |
155//
156// *Trailing punctuation is captured by the regex; use trim_trailing_punctuation() to clean.
157//
158// ## Design Principles:
159// 1. Parentheses in paths are allowed for Wikipedia-style URLs (Issue #240)
160// 2. Host portion excludes / so path is captured separately
161// 3. Unbalanced trailing parens are handled by trim_trailing_punctuation()
162// 4. All patterns exclude angle brackets <> to avoid matching autolinks
163//
164// ## URL Structure: protocol://host[:port][/path][?query][#fragment]
165
166/// Pattern for standard HTTP(S)/FTP(S) URLs with full path support.
167///
168/// Use this for bare URL detection where you need the complete URL including
169/// Wikipedia-style parentheses in paths. Trailing punctuation like `,;.!?` may
170/// be captured and should be trimmed by the caller.
171///
172/// # Examples
173/// - `https://example.com/path_(with_parens)?query#fragment`
174/// - `https://en.wikipedia.org/wiki/Rust_(programming_language)`
175pub const URL_STANDARD_STR: &str = concat!(
176    r#"(?:https?|ftps?|ftp)://"#, // Protocol
177    r#"(?:"#,
178    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host OR
179    r#"|"#,
180    r#"[^\s<>\[\]()\\'\"`/]+"#, // Standard host (no parens, no /)
181    r#")"#,
182    r#"(?::\d+)?"#,                 // Optional port
183    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,  // Optional path (allows parens)
184    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#, // Optional query (allows parens)
185    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,  // Optional fragment (allows parens)
186);
187
188/// Pattern for www URLs without protocol.
189///
190/// Matches URLs starting with `www.` that lack a protocol prefix.
191/// These should be converted to proper URLs or flagged as bare URLs.
192/// Supports port, path, query string, and fragment like URL_STANDARD_STR.
193///
194/// # Examples
195/// - `www.example.com`
196/// - `www.example.com:8080`
197/// - `www.example.com/path`
198/// - `www.example.com?query=value`
199/// - `www.example.com#section`
200pub const URL_WWW_STR: &str = concat!(
201    r#"www\.(?:[a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}"#, // www.domain.tld
202    r#"(?::\d+)?"#,                                        // Optional port
203    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,                         // Optional path (allows parens)
204    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#,                        // Optional query (allows parens)
205    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,                         // Optional fragment (allows parens)
206);
207
208/// Pattern for IPv6 URLs specifically.
209///
210/// Matches URLs with IPv6 addresses in brackets, including zone identifiers.
211/// Examples: `https://[::1]/path`, `https://[fe80::1%eth0]:8080/`
212pub const URL_IPV6_STR: &str = concat!(
213    r#"(?:https?|ftps?|ftp)://"#,
214    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host in brackets
215    r#"(?::\d+)?"#,                   // Optional port
216    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,    // Optional path
217    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#,   // Optional query
218    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,    // Optional fragment
219);
220
221/// Pattern for XMPP URIs per GFM extended autolinks specification.
222///
223/// XMPP URIs use the format `xmpp:user@domain/resource` (without `://`).
224/// Reference: <https://github.github.com/gfm/#autolinks-extension->
225///
226/// # Examples
227/// - `xmpp:foo@bar.baz`
228/// - `xmpp:foo@bar.baz/txt`
229pub const XMPP_URI_STR: &str = r#"xmpp:[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:/[^\s<>\[\]\\'\"`]*)?"#;
230
231/// Quick check pattern for early exits.
232///
233/// Use this for fast pre-filtering before running more expensive patterns.
234/// Matches if the text likely contains a URL or email address.
235/// Includes `xmpp:` for GFM extended autolinks.
236pub const URL_QUICK_CHECK_STR: &str = r#"(?:https?|ftps?|ftp|xmpp)://|xmpp:|@|www\."#;
237
238/// Simple URL pattern for content detection.
239///
240/// Less strict pattern that excludes trailing sentence punctuation (.,).
241/// Use for line length exemption checks or content characteristic detection
242/// where you just need to know if a URL exists, not extract it precisely.
243pub const URL_SIMPLE_STR: &str = r#"(?:https?|ftps?|ftp)://[^\s<>]+[^\s<>.,]"#;
244
245// Pre-compiled static patterns for performance
246
247/// Standard URL regex - primary pattern for bare URL detection (MD034).
248/// See [`URL_STANDARD_STR`] for documentation.
249pub static URL_STANDARD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_STANDARD_STR).unwrap());
250
251/// WWW URL regex - for URLs starting with www. without protocol.
252/// See [`URL_WWW_STR`] for documentation.
253pub static URL_WWW_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_WWW_STR).unwrap());
254
255/// IPv6 URL regex - for URLs with IPv6 addresses.
256/// See [`URL_IPV6_STR`] for documentation.
257pub static URL_IPV6_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_IPV6_STR).unwrap());
258
259/// Quick check regex - fast early-exit test.
260/// See [`URL_QUICK_CHECK_STR`] for documentation.
261pub static URL_QUICK_CHECK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_QUICK_CHECK_STR).unwrap());
262
263/// Simple URL regex - for content detection and line length exemption.
264/// See [`URL_SIMPLE_STR`] for documentation.
265pub static URL_SIMPLE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_SIMPLE_STR).unwrap());
266
267/// Alias for `URL_SIMPLE_REGEX`. Used by MD013 for line length exemption.
268pub static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| URL_SIMPLE_REGEX.clone());
269
270/// XMPP URI regex - for GFM extended autolinks.
271/// See [`XMPP_URI_STR`] for documentation.
272pub static XMPP_URI_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(XMPP_URI_STR).unwrap());
273
274// Heading patterns
275pub static ATX_HEADING_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+|$)").unwrap());
276
277// List patterns
278pub static UNORDERED_LIST_MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)([*+-])(\s+)").unwrap());
279pub static ORDERED_LIST_MARKER_REGEX: LazyLock<Regex> =
280    LazyLock::new(|| Regex::new(r"^(\s*)(\d+)([.)])(\s+)").unwrap());
281
282// Emphasis patterns
283
284// MD037 specific emphasis patterns - improved to avoid false positives
285// Only match emphasis with spaces that are actually complete emphasis blocks
286// Use word boundaries and negative lookbehind/lookahead to avoid matching across emphasis boundaries
287pub static ASTERISK_EMPHASIS: LazyLock<Regex> =
288    LazyLock::new(|| Regex::new(r"(?:^|[^*])\*(\s+[^*]+\s*|\s*[^*]+\s+)\*(?:[^*]|$)").unwrap());
289pub static UNDERSCORE_EMPHASIS: LazyLock<Regex> =
290    LazyLock::new(|| Regex::new(r"(?:^|[^_])_(\s+[^_]+\s*|\s*[^_]+\s+)_(?:[^_]|$)").unwrap());
291pub static DOUBLE_UNDERSCORE_EMPHASIS: LazyLock<Regex> =
292    LazyLock::new(|| Regex::new(r"(?:^|[^_])__(\s+[^_]+\s*|\s*[^_]+\s+)__(?:[^_]|$)").unwrap());
293// Code block patterns
294pub static FENCED_CODE_BLOCK_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```(?:[^`\r\n]*)$").unwrap());
295pub static FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```\s*$").unwrap());
296
297// HTML patterns
298pub static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*)>").unwrap());
299pub static HTML_TAG_QUICK_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z]").unwrap());
300
301// Image patterns
302pub static IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
303
304// Blockquote patterns
305pub static BLOCKQUOTE_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*>+\s*)").unwrap());
306
307/// Check if a line is blank in the context of blockquotes.
308///
309/// A line is considered "blank" if:
310/// - It's empty or contains only whitespace
311/// - It's a blockquote continuation line with no content (e.g., ">", ">>", "> ")
312///
313/// This is essential for rules like MD058 (blanks-around-tables), MD065 (blanks-around-horizontal-rules),
314/// and any other rule that needs to detect blank lines that might be inside blockquotes.
315///
316/// # Examples
317/// ```
318/// use rumdl_lib::utils::regex_cache::is_blank_in_blockquote_context;
319///
320/// assert!(is_blank_in_blockquote_context(""));           // Empty line
321/// assert!(is_blank_in_blockquote_context("   "));        // Whitespace only
322/// assert!(is_blank_in_blockquote_context(">"));          // Blockquote continuation
323/// assert!(is_blank_in_blockquote_context("> "));         // Blockquote with trailing space
324/// assert!(is_blank_in_blockquote_context(">>"));         // Nested blockquote
325/// assert!(is_blank_in_blockquote_context("> > "));       // Spaced nested blockquote
326/// assert!(!is_blank_in_blockquote_context("> text"));    // Blockquote with content
327/// assert!(!is_blank_in_blockquote_context("text"));      // Regular text
328/// ```
329pub fn is_blank_in_blockquote_context(line: &str) -> bool {
330    if line.trim().is_empty() {
331        return true;
332    }
333    // Check if line is a blockquote prefix with no content after it
334    // Handle spaced nested blockquotes like "> > " by recursively checking remainder
335    if let Some(m) = BLOCKQUOTE_PREFIX_RE.find(line) {
336        let remainder = &line[m.end()..];
337        // The remainder should be empty/whitespace OR another blockquote prefix (for spaced nesting)
338        is_blank_in_blockquote_context(remainder)
339    } else {
340        false
341    }
342}
343
344// MD013 specific patterns
345pub static IMAGE_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^!\[.*?\]\[.*?\]$").unwrap());
346pub static LINK_REF_PATTERN: LazyLock<Regex> =
347    LazyLock::new(|| Regex::new(r#"^\[.*?\]:\s*\S+(\s+["'(].*)?\s*$"#).unwrap());
348pub static ABBREVIATION: LazyLock<Regex> = LazyLock::new(|| {
349    Regex::new(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|vs|etc|i\.e|e\.g|Inc|Corp|Ltd|Co|St|Ave|Blvd|Rd|Ph\.D|M\.D|B\.A|M\.A|Ph\.D|U\.S|U\.K|U\.N|N\.Y|L\.A|D\.C)\.\s+[A-Z]").unwrap()
350});
351pub static LIST_ITEM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\d+\.\s+").unwrap());
352
353// Email pattern
354pub static EMAIL_PATTERN: LazyLock<Regex> =
355    LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap());
356
357// Third lazy_static block for link and image patterns used by MD052 and text_reflow
358// Reference link patterns (shared by MD052 and text_reflow)
359// Pattern to match reference links: [text][reference] or [text][]
360pub static REF_LINK_REGEX: LazyLock<FancyRegex> =
361    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
362
363// Pattern for shortcut reference links: [reference]
364// Must not be preceded by ] or ) (to avoid matching second part of [text][ref])
365// Must not be followed by [ or ( (to avoid matching first part of [text][ref] or [text](url))
366// The capturing group handles nested brackets to support cases like [`Union[T, None]`]
367pub static SHORTCUT_REF_REGEX: LazyLock<FancyRegex> =
368    LazyLock::new(|| FancyRegex::new(r"(?<![\\)\]])\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\](?!\s*[\[\(])").unwrap());
369
370// Inline link with fancy regex for better escaping handling (used by text_reflow)
371pub static INLINE_LINK_FANCY_REGEX: LazyLock<FancyRegex> =
372    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]+)\]\(([^)]+)\)").unwrap());
373
374// Inline image (used by MD052 and text_reflow)
375pub static INLINE_IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
376
377// Linked images (clickable badges) - all 4 variants
378// Must be detected before inline_image and inline_link to treat as atomic units
379//
380// Limitation: Alt text containing brackets like [![[v1.0]](img)](link) is not supported.
381// The [^\]]* pattern cannot match nested brackets. This is rare in practice.
382//
383// Pattern 1: Inline image in inline link - [![alt](img-url)](link-url)
384pub static LINKED_IMAGE_INLINE_INLINE: LazyLock<Regex> =
385    LazyLock::new(|| Regex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)").unwrap());
386
387// Pattern 2: Reference image in inline link - [![alt][img-ref]](link-url)
388pub static LINKED_IMAGE_REF_INLINE: LazyLock<Regex> =
389    LazyLock::new(|| Regex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\(([^)]+)\)").unwrap());
390
391// Pattern 3: Inline image in reference link - [![alt](img-url)][link-ref]
392pub static LINKED_IMAGE_INLINE_REF: LazyLock<Regex> =
393    LazyLock::new(|| Regex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\[([^\]]*)\]").unwrap());
394
395// Pattern 4: Reference image in reference link - [![alt][img-ref]][link-ref]
396pub static LINKED_IMAGE_REF_REF: LazyLock<Regex> =
397    LazyLock::new(|| Regex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\[([^\]]*)\]").unwrap());
398
399// Reference image: ![alt][ref] or ![alt][]
400pub static REF_IMAGE_REGEX: LazyLock<Regex> =
401    LazyLock::new(|| Regex::new(r"!\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
402
403// Footnote reference: [^note]
404pub static FOOTNOTE_REF_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[\^([^\]]+)\]").unwrap());
405
406// Wiki-style links: [[wiki]] or [[wiki|display text]]
407pub static WIKI_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[\[([^\]]+)\]\]").unwrap());
408
409// Math formulas: $inline$ or $$display$$
410pub static INLINE_MATH_REGEX: LazyLock<FancyRegex> =
411    LazyLock::new(|| FancyRegex::new(r"(?<!\$)\$(?!\$)([^\$]+)\$(?!\$)").unwrap());
412pub static DISPLAY_MATH_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\$\$([^\$]+)\$\$").unwrap());
413
414// Emoji shortcodes: :emoji:
415pub static EMOJI_SHORTCODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r":([a-zA-Z0-9_+-]+):").unwrap());
416
417// HTML tags (opening, closing, self-closing)
418pub static HTML_TAG_PATTERN: LazyLock<Regex> =
419    LazyLock::new(|| Regex::new(r"</?[a-zA-Z][^>]*>|<[a-zA-Z][^>]*/\s*>").unwrap());
420
421// HTML entities: &nbsp; &mdash; etc
422pub static HTML_ENTITY_REGEX: LazyLock<Regex> =
423    LazyLock::new(|| Regex::new(r"&[a-zA-Z][a-zA-Z0-9]*;|&#\d+;|&#x[0-9a-fA-F]+;").unwrap());
424
425// Hugo/Go template shortcodes: {{< figure ... >}} and {{% shortcode %}}
426// Matches both delimiters: {{< ... >}} (shortcode) and {{% ... %}} (template)
427// Handles multi-line content with embedded quotes and newlines
428pub static HUGO_SHORTCODE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\{[<%][\s\S]*?[%>]\}\}").unwrap());
429
430// HTML heading pattern (matches <h1> through <h6> tags)
431// Uses FancyRegex because the pattern requires a backreference (\1)
432pub static HTML_HEADING_PATTERN: LazyLock<FancyRegex> =
433    LazyLock::new(|| FancyRegex::new(r"^\s*<h([1-6])(?:\s[^>]*)?>.*</h\1>\s*$").unwrap());
434
435/// Escapes a string to be used in a regex pattern
436pub fn escape_regex(s: &str) -> String {
437    let mut result = String::with_capacity(s.len() * 2);
438
439    for c in s.chars() {
440        // Use matches! for O(1) lookup instead of array.contains() which is O(n)
441        if matches!(
442            c,
443            '.' | '+' | '*' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\'
444        ) {
445            result.push('\\');
446        }
447        result.push(c);
448    }
449
450    result
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456
457    #[test]
458    fn test_regex_cache_new() {
459        let cache = RegexCache::new();
460        assert!(cache.cache.is_empty());
461        assert!(cache.usage_stats.is_empty());
462    }
463
464    #[test]
465    fn test_regex_cache_default() {
466        let cache = RegexCache::default();
467        assert!(cache.cache.is_empty());
468        assert!(cache.usage_stats.is_empty());
469    }
470
471    #[test]
472    fn test_get_regex_compilation() {
473        let mut cache = RegexCache::new();
474
475        // First call compiles and caches
476        let regex1 = cache.get_regex(r"\d+").unwrap();
477        assert_eq!(cache.cache.len(), 1);
478        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&1));
479
480        // Second call returns cached version
481        let regex2 = cache.get_regex(r"\d+").unwrap();
482        assert_eq!(cache.cache.len(), 1);
483        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&2));
484
485        // Both should be the same Arc
486        assert!(Arc::ptr_eq(&regex1, &regex2));
487    }
488
489    #[test]
490    fn test_get_regex_invalid_pattern() {
491        let mut cache = RegexCache::new();
492        let result = cache.get_regex(r"[unterminated");
493        assert!(result.is_err());
494        assert!(cache.cache.is_empty());
495    }
496
497    #[test]
498    fn test_get_stats() {
499        let mut cache = RegexCache::new();
500
501        // Use some patterns
502        let _ = cache.get_regex(r"\d+").unwrap();
503        let _ = cache.get_regex(r"\d+").unwrap();
504        let _ = cache.get_regex(r"\w+").unwrap();
505
506        let stats = cache.get_stats();
507        assert_eq!(stats.get(r"\d+"), Some(&2));
508        assert_eq!(stats.get(r"\w+"), Some(&1));
509    }
510
511    #[test]
512    fn test_clear_cache() {
513        let mut cache = RegexCache::new();
514
515        // Add some patterns
516        let _ = cache.get_regex(r"\d+").unwrap();
517
518        assert!(!cache.cache.is_empty());
519        assert!(!cache.usage_stats.is_empty());
520
521        // Clear cache
522        cache.clear();
523
524        assert!(cache.cache.is_empty());
525        assert!(cache.usage_stats.is_empty());
526    }
527
528    #[test]
529    fn test_global_cache_functions() {
530        // Test get_cached_regex
531        let regex1 = get_cached_regex(r"\d{3}").unwrap();
532        let regex2 = get_cached_regex(r"\d{3}").unwrap();
533        assert!(Arc::ptr_eq(&regex1, &regex2));
534
535        // Test stats
536        let stats = get_cache_stats();
537        assert!(stats.contains_key(r"\d{3}"));
538    }
539
540    #[test]
541    fn test_regex_lazy_macro() {
542        let re = regex_lazy!(r"^test.*end$");
543        assert!(re.is_match("test something end"));
544        assert!(!re.is_match("test something"));
545
546        // The macro creates a new static for each invocation location,
547        // so we can't test pointer equality across different invocations
548        // But we can test that the regex works correctly
549        let re2 = regex_lazy!(r"^start.*finish$");
550        assert!(re2.is_match("start and finish"));
551        assert!(!re2.is_match("start without end"));
552    }
553
554    #[test]
555    fn test_escape_regex() {
556        assert_eq!(escape_regex("a.b"), "a\\.b");
557        assert_eq!(escape_regex("a+b*c"), "a\\+b\\*c");
558        assert_eq!(escape_regex("(test)"), "\\(test\\)");
559        assert_eq!(escape_regex("[a-z]"), "\\[a-z\\]");
560        assert_eq!(escape_regex("normal text"), "normal text");
561
562        // Test all special characters
563        assert_eq!(escape_regex(".$^{[(|)*+?\\"), "\\.\\$\\^\\{\\[\\(\\|\\)\\*\\+\\?\\\\");
564
565        // Test empty string
566        assert_eq!(escape_regex(""), "");
567
568        // Test mixed content
569        assert_eq!(escape_regex("test.com/path?query=1"), "test\\.com/path\\?query=1");
570    }
571
572    #[test]
573    fn test_static_regex_patterns() {
574        // Test URL patterns
575        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
576        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
577        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com"));
578        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
579
580        // Test heading patterns
581        assert!(ATX_HEADING_REGEX.is_match("# Heading"));
582        assert!(ATX_HEADING_REGEX.is_match("  ## Indented"));
583        assert!(ATX_HEADING_REGEX.is_match("### "));
584        assert!(!ATX_HEADING_REGEX.is_match("Not a heading"));
585
586        // Test list patterns
587        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("* Item"));
588        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("- Item"));
589        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("+ Item"));
590        assert!(ORDERED_LIST_MARKER_REGEX.is_match("1. Item"));
591        assert!(ORDERED_LIST_MARKER_REGEX.is_match("99. Item"));
592
593        // Test HTML patterns
594        assert!(HTML_TAG_REGEX.is_match("<div>"));
595        assert!(HTML_TAG_REGEX.is_match("<span class='test'>"));
596
597        // Test blockquote pattern
598        assert!(BLOCKQUOTE_PREFIX_RE.is_match("> Quote"));
599        assert!(BLOCKQUOTE_PREFIX_RE.is_match("  > Indented quote"));
600        assert!(BLOCKQUOTE_PREFIX_RE.is_match(">> Nested"));
601    }
602
603    #[test]
604    fn test_thread_safety() {
605        use std::thread;
606
607        let handles: Vec<_> = (0..10)
608            .map(|i| {
609                thread::spawn(move || {
610                    let pattern = format!(r"\d{{{i}}}");
611                    let regex = get_cached_regex(&pattern).unwrap();
612                    assert!(regex.is_match(&"1".repeat(i)));
613                })
614            })
615            .collect();
616
617        for handle in handles {
618            handle.join().unwrap();
619        }
620    }
621
622    // ==========================================================================
623    // Comprehensive URL Regex Tests
624    // ==========================================================================
625
626    #[test]
627    fn test_url_standard_basic() {
628        // Basic HTTP/HTTPS URLs
629        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
630        assert!(URL_STANDARD_REGEX.is_match("http://example.com"));
631        assert!(URL_STANDARD_REGEX.is_match("https://example.com/"));
632        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path"));
633        assert!(URL_STANDARD_REGEX.is_match("ftp://files.example.com"));
634        assert!(URL_STANDARD_REGEX.is_match("ftps://secure.example.com"));
635
636        // Should not match non-URLs
637        assert!(!URL_STANDARD_REGEX.is_match("not a url"));
638        assert!(!URL_STANDARD_REGEX.is_match("example.com"));
639        assert!(!URL_STANDARD_REGEX.is_match("www.example.com"));
640    }
641
642    #[test]
643    fn test_url_standard_with_path() {
644        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page"));
645        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page.html"));
646        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page/"));
647    }
648
649    #[test]
650    fn test_url_standard_with_query() {
651        assert!(URL_STANDARD_REGEX.is_match("https://example.com?query=value"));
652        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value"));
653        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?a=1&b=2"));
654    }
655
656    #[test]
657    fn test_url_standard_with_fragment() {
658        assert!(URL_STANDARD_REGEX.is_match("https://example.com#section"));
659        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path#section"));
660        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value#section"));
661    }
662
663    #[test]
664    fn test_url_standard_with_port() {
665        assert!(URL_STANDARD_REGEX.is_match("https://example.com:8080"));
666        assert!(URL_STANDARD_REGEX.is_match("https://example.com:443/path"));
667        assert!(URL_STANDARD_REGEX.is_match("http://localhost:3000"));
668        assert!(URL_STANDARD_REGEX.is_match("https://192.168.1.1:8080/path"));
669    }
670
671    #[test]
672    fn test_url_standard_wikipedia_style_parentheses() {
673        // Wikipedia-style URLs with parentheses in path (Issue #240)
674        let url = "https://en.wikipedia.org/wiki/Rust_(programming_language)";
675        assert!(URL_STANDARD_REGEX.is_match(url));
676
677        // Verify the full URL is captured
678        let cap = URL_STANDARD_REGEX.find(url).unwrap();
679        assert_eq!(cap.as_str(), url);
680
681        // Multiple parentheses pairs
682        let url2 = "https://example.com/path_(foo)_(bar)";
683        let cap2 = URL_STANDARD_REGEX.find(url2).unwrap();
684        assert_eq!(cap2.as_str(), url2);
685    }
686
687    #[test]
688    fn test_url_standard_ipv6() {
689        // IPv6 addresses in URLs
690        assert!(URL_STANDARD_REGEX.is_match("https://[::1]/path"));
691        assert!(URL_STANDARD_REGEX.is_match("https://[2001:db8::1]:8080/path"));
692        assert!(URL_STANDARD_REGEX.is_match("http://[fe80::1%eth0]/"));
693    }
694
695    #[test]
696    fn test_url_www_basic() {
697        // www URLs without protocol
698        assert!(URL_WWW_REGEX.is_match("www.example.com"));
699        assert!(URL_WWW_REGEX.is_match("www.example.co.uk"));
700        assert!(URL_WWW_REGEX.is_match("www.sub.example.com"));
701
702        // Should not match plain domains without www
703        assert!(!URL_WWW_REGEX.is_match("example.com"));
704
705        // Note: https://www.example.com DOES match because it contains "www."
706        // The URL_WWW_REGEX is designed to find www. URLs that lack a protocol
707        // Use URL_STANDARD_REGEX for full URLs with protocols
708        assert!(URL_WWW_REGEX.is_match("https://www.example.com"));
709    }
710
711    #[test]
712    fn test_url_www_with_path() {
713        assert!(URL_WWW_REGEX.is_match("www.example.com/path"));
714        assert!(URL_WWW_REGEX.is_match("www.example.com/path/to/page"));
715        assert!(URL_WWW_REGEX.is_match("www.example.com/path_(with_parens)"));
716    }
717
718    #[test]
719    fn test_url_ipv6_basic() {
720        // IPv6 specific patterns
721        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
722        assert!(URL_IPV6_REGEX.is_match("http://[2001:db8::1]/path"));
723        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1]:8080/path"));
724        assert!(URL_IPV6_REGEX.is_match("ftp://[::ffff:192.168.1.1]/file"));
725    }
726
727    #[test]
728    fn test_url_ipv6_with_zone_id() {
729        // IPv6 with zone identifiers
730        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1%eth0]/path"));
731        assert!(URL_IPV6_REGEX.is_match("http://[fe80::1%25eth0]:8080/"));
732    }
733
734    #[test]
735    fn test_url_simple_detection() {
736        // Simple pattern for content characteristic detection
737        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
738        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
739        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com/file.zip"));
740        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
741    }
742
743    #[test]
744    fn test_url_quick_check() {
745        // Quick check pattern for early exits
746        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
747        assert!(URL_QUICK_CHECK_REGEX.is_match("http://example.com"));
748        assert!(URL_QUICK_CHECK_REGEX.is_match("ftp://files.com"));
749        assert!(URL_QUICK_CHECK_REGEX.is_match("www.example.com"));
750        assert!(URL_QUICK_CHECK_REGEX.is_match("user@example.com"));
751        assert!(!URL_QUICK_CHECK_REGEX.is_match("just plain text"));
752    }
753
754    #[test]
755    fn test_url_edge_cases() {
756        // URLs with special characters that should be excluded
757        let url = "https://example.com/path";
758        assert!(URL_STANDARD_REGEX.is_match(url));
759
760        // URL followed by punctuation - the regex captures trailing punctuation
761        // because trimming is done by `trim_trailing_punctuation()` in the rule
762        let text = "Check https://example.com, it's great!";
763        let cap = URL_STANDARD_REGEX.find(text).unwrap();
764        // The comma IS captured by the regex - rule-level trimming handles this
765        assert!(cap.as_str().ends_with(','));
766
767        // URL in angle brackets should still be found
768        let text2 = "See <https://example.com> for more";
769        assert!(URL_STANDARD_REGEX.is_match(text2));
770
771        // URL ending at angle bracket should stop at >
772        let cap2 = URL_STANDARD_REGEX.find(text2).unwrap();
773        assert!(!cap2.as_str().contains('>'));
774    }
775
776    #[test]
777    fn test_url_with_complex_paths() {
778        // Complex real-world URLs
779        let urls = [
780            "https://github.com/owner/repo/blob/main/src/file.rs#L123",
781            "https://docs.example.com/api/v2/endpoint?format=json&page=1",
782            "https://cdn.example.com/assets/images/logo.png?v=2023",
783            "https://search.example.com/results?q=test+query&filter=all",
784        ];
785
786        for url in urls {
787            assert!(URL_STANDARD_REGEX.is_match(url), "Should match: {url}");
788        }
789    }
790
791    #[test]
792    fn test_url_pattern_strings_are_valid() {
793        // Verify patterns compile into valid regexes by accessing them
794        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
795        assert!(URL_WWW_REGEX.is_match("www.example.com"));
796        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
797        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
798        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
799    }
800
801    // =========================================================================
802    // Tests for is_blank_in_blockquote_context
803    // This is a shared utility used by MD058, MD065, and other rules that need
804    // to detect blank lines inside blockquotes (Issue #305)
805    // =========================================================================
806
807    #[test]
808    fn test_is_blank_in_blockquote_context_regular_blanks() {
809        // Regular blank lines
810        assert!(is_blank_in_blockquote_context(""));
811        assert!(is_blank_in_blockquote_context("   "));
812        assert!(is_blank_in_blockquote_context("\t"));
813        assert!(is_blank_in_blockquote_context("  \t  "));
814    }
815
816    #[test]
817    fn test_is_blank_in_blockquote_context_blockquote_blanks() {
818        // Blockquote continuation lines with no content (should be treated as blank)
819        assert!(is_blank_in_blockquote_context(">"));
820        assert!(is_blank_in_blockquote_context("> "));
821        assert!(is_blank_in_blockquote_context(">  "));
822        assert!(is_blank_in_blockquote_context(">>"));
823        assert!(is_blank_in_blockquote_context(">> "));
824        assert!(is_blank_in_blockquote_context(">>>"));
825        assert!(is_blank_in_blockquote_context(">>> "));
826    }
827
828    #[test]
829    fn test_is_blank_in_blockquote_context_spaced_nested() {
830        // Spaced nested blockquotes ("> > " style)
831        assert!(is_blank_in_blockquote_context("> > "));
832        assert!(is_blank_in_blockquote_context("> > > "));
833        assert!(is_blank_in_blockquote_context(">  >  "));
834    }
835
836    #[test]
837    fn test_is_blank_in_blockquote_context_with_leading_space() {
838        // Blockquote with leading whitespace
839        assert!(is_blank_in_blockquote_context("  >"));
840        assert!(is_blank_in_blockquote_context("  > "));
841        assert!(is_blank_in_blockquote_context("  >>"));
842    }
843
844    #[test]
845    fn test_is_blank_in_blockquote_context_not_blank() {
846        // Lines with actual content (should NOT be treated as blank)
847        assert!(!is_blank_in_blockquote_context("text"));
848        assert!(!is_blank_in_blockquote_context("> text"));
849        assert!(!is_blank_in_blockquote_context(">> text"));
850        assert!(!is_blank_in_blockquote_context("> | table |"));
851        assert!(!is_blank_in_blockquote_context("| table |"));
852        assert!(!is_blank_in_blockquote_context("> # Heading"));
853        assert!(!is_blank_in_blockquote_context(">text")); // No space after > but has text
854    }
855
856    #[test]
857    fn test_is_blank_in_blockquote_context_edge_cases() {
858        // Edge cases
859        assert!(!is_blank_in_blockquote_context(">a")); // Content immediately after >
860        assert!(!is_blank_in_blockquote_context("> a")); // Single char content
861        assert!(is_blank_in_blockquote_context(">   ")); // Multiple spaces after >
862        assert!(!is_blank_in_blockquote_context(">  text")); // Multiple spaces before content
863    }
864}