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