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    fancy_cache: HashMap<String, Arc<FancyRegex>>,
33    usage_stats: HashMap<String, u64>,
34}
35
36impl Default for RegexCache {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl RegexCache {
43    pub fn new() -> Self {
44        Self {
45            cache: HashMap::new(),
46            fancy_cache: HashMap::new(),
47            usage_stats: HashMap::new(),
48        }
49    }
50
51    /// Get or compile a regex pattern
52    pub fn get_regex(&mut self, pattern: &str) -> Result<Arc<Regex>, regex::Error> {
53        if let Some(regex) = self.cache.get(pattern) {
54            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
55            return Ok(regex.clone());
56        }
57
58        let regex = Arc::new(Regex::new(pattern)?);
59        self.cache.insert(pattern.to_string(), regex.clone());
60        *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
61        Ok(regex)
62    }
63
64    /// Get or compile a fancy regex pattern
65    pub fn get_fancy_regex(&mut self, pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
66        if let Some(regex) = self.fancy_cache.get(pattern) {
67            *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
68            return Ok(regex.clone());
69        }
70
71        match FancyRegex::new(pattern) {
72            Ok(regex) => {
73                let arc_regex = Arc::new(regex);
74                self.fancy_cache.insert(pattern.to_string(), arc_regex.clone());
75                *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
76                Ok(arc_regex)
77            }
78            Err(e) => Err(Box::new(e)),
79        }
80    }
81
82    /// Get cache statistics
83    pub fn get_stats(&self) -> HashMap<String, u64> {
84        self.usage_stats.clone()
85    }
86
87    /// Clear cache (useful for testing)
88    pub fn clear(&mut self) {
89        self.cache.clear();
90        self.fancy_cache.clear();
91        self.usage_stats.clear();
92    }
93}
94
95/// Global regex cache instance
96static GLOBAL_REGEX_CACHE: LazyLock<Arc<Mutex<RegexCache>>> = LazyLock::new(|| Arc::new(Mutex::new(RegexCache::new())));
97
98/// Get a regex from the global cache
99///
100/// If the mutex is poisoned (another thread panicked while holding the lock),
101/// this function recovers by clearing the cache and continuing. This ensures
102/// the library never panics due to mutex poisoning.
103pub fn get_cached_regex(pattern: &str) -> Result<Arc<Regex>, regex::Error> {
104    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
105        // Recover from poisoned mutex by clearing the cache
106        let mut guard = poisoned.into_inner();
107        guard.clear();
108        guard
109    });
110    cache.get_regex(pattern)
111}
112
113/// Get a fancy regex from the global cache
114///
115/// If the mutex is poisoned (another thread panicked while holding the lock),
116/// this function recovers by clearing the cache and continuing. This ensures
117/// the library never panics due to mutex poisoning.
118pub fn get_cached_fancy_regex(pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
119    let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
120        // Recover from poisoned mutex by clearing the cache
121        let mut guard = poisoned.into_inner();
122        guard.clear();
123        guard
124    });
125    cache.get_fancy_regex(pattern)
126}
127
128/// Get cache usage statistics
129///
130/// If the mutex is poisoned, returns an empty HashMap rather than panicking.
131pub fn get_cache_stats() -> HashMap<String, u64> {
132    match GLOBAL_REGEX_CACHE.lock() {
133        Ok(cache) => cache.get_stats(),
134        Err(_) => HashMap::new(),
135    }
136}
137
138/// Macro for defining a lazily-initialized, cached regex pattern.
139///
140/// Use this for ad-hoc regexes that are not already defined in this module.
141///
142/// # Panics
143///
144/// This macro will panic at initialization if the regex pattern is invalid.
145/// This is intentional for compile-time constant patterns - we want to catch
146/// invalid patterns during development, not at runtime.
147///
148/// # Example
149///
150/// ```
151/// use rumdl_lib::regex_lazy;
152/// let my_re = regex_lazy!(r"^foo.*bar$");
153/// assert!(my_re.is_match("foobar"));
154/// ```
155#[macro_export]
156macro_rules! regex_lazy {
157    ($pattern:expr) => {{
158        static REGEX: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new($pattern).unwrap());
159        &*REGEX
160    }};
161}
162
163/// Macro for getting regex from global cache.
164///
165/// # Panics
166///
167/// Panics if the regex pattern is invalid. This is acceptable for static patterns
168/// where we want to fail fast during development.
169#[macro_export]
170macro_rules! regex_cached {
171    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_regex($pattern).expect("Failed to compile regex") }};
172}
173
174/// Macro for getting fancy regex from global cache.
175///
176/// # Panics
177///
178/// Panics if the regex pattern is invalid. This is acceptable for static patterns
179/// where we want to fail fast during development.
180#[macro_export]
181macro_rules! fancy_regex_cached {
182    ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_fancy_regex($pattern).expect("Failed to compile fancy regex") }};
183}
184
185// Also make the macro available directly from this module
186pub use crate::regex_lazy;
187
188// =============================================================================
189// URL REGEX PATTERNS - Centralized URL Detection
190// =============================================================================
191//
192// ## Pattern Hierarchy (use the most specific pattern for your needs):
193//
194// | Pattern              | Use Case                                    | Parens | Trailing Punct |
195// |----------------------|---------------------------------------------|--------|----------------|
196// | URL_STANDARD_REGEX   | MD034 bare URL detection with auto-fix      | Yes    | Captured*      |
197// | URL_WWW_REGEX        | www.domain URLs without protocol            | Yes    | Captured*      |
198// | URL_IPV6_REGEX       | IPv6 URLs like https://[::1]/path           | Yes    | Captured*      |
199// | URL_QUICK_CHECK_REGEX| Fast early-exit check (contains URL?)       | N/A    | N/A            |
200// | URL_SIMPLE_REGEX     | Content detection, line length exemption    | No     | Excluded       |
201//
202// *Trailing punctuation is captured by the regex; use trim_trailing_punctuation() to clean.
203//
204// ## Design Principles:
205// 1. Parentheses in paths are allowed for Wikipedia-style URLs (Issue #240)
206// 2. Host portion excludes / so path is captured separately
207// 3. Unbalanced trailing parens are handled by trim_trailing_punctuation()
208// 4. All patterns exclude angle brackets <> to avoid matching autolinks
209//
210// ## URL Structure: protocol://host[:port][/path][?query][#fragment]
211
212/// Pattern for standard HTTP(S)/FTP(S) URLs with full path support.
213///
214/// Use this for bare URL detection where you need the complete URL including
215/// Wikipedia-style parentheses in paths. Trailing punctuation like `,;.!?` may
216/// be captured and should be trimmed by the caller.
217///
218/// # Examples
219/// - `https://example.com/path_(with_parens)?query#fragment`
220/// - `https://en.wikipedia.org/wiki/Rust_(programming_language)`
221pub const URL_STANDARD_STR: &str = concat!(
222    r#"(?:https?|ftps?|ftp)://"#, // Protocol
223    r#"(?:"#,
224    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host OR
225    r#"|"#,
226    r#"[^\s<>\[\]()\\'\"`/]+"#, // Standard host (no parens, no /)
227    r#")"#,
228    r#"(?::\d+)?"#,                 // Optional port
229    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,  // Optional path (allows parens)
230    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#, // Optional query (allows parens)
231    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,  // Optional fragment (allows parens)
232);
233
234/// Pattern for www URLs without protocol.
235///
236/// Matches URLs starting with `www.` that lack a protocol prefix.
237/// These should be converted to proper URLs or flagged as bare URLs.
238pub const URL_WWW_STR: &str = concat!(
239    r#"www\.(?:[a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}"#, // www.domain.tld
240    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,                         // Optional path (allows parens)
241);
242
243/// Pattern for IPv6 URLs specifically.
244///
245/// Matches URLs with IPv6 addresses in brackets, including zone identifiers.
246/// Examples: `https://[::1]/path`, `https://[fe80::1%eth0]:8080/`
247pub const URL_IPV6_STR: &str = concat!(
248    r#"(?:https?|ftps?|ftp)://"#,
249    r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, // IPv6 host in brackets
250    r#"(?::\d+)?"#,                   // Optional port
251    r#"(?:/[^\s<>\[\]\\'\"`]*)?"#,    // Optional path
252    r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#,   // Optional query
253    r#"(?:#[^\s<>\[\]\\'\"`]*)?"#,    // Optional fragment
254);
255
256/// Quick check pattern for early exits.
257///
258/// Use this for fast pre-filtering before running more expensive patterns.
259/// Matches if the text likely contains a URL or email address.
260pub const URL_QUICK_CHECK_STR: &str = r#"(?:https?|ftps?|ftp)://|@|www\."#;
261
262/// Simple URL pattern for content detection.
263///
264/// Less strict pattern that excludes trailing sentence punctuation (.,).
265/// Use for line length exemption checks or content characteristic detection
266/// where you just need to know if a URL exists, not extract it precisely.
267pub const URL_SIMPLE_STR: &str = r#"(?:https?|ftps?|ftp)://[^\s<>]+[^\s<>.,]"#;
268
269// Pre-compiled static patterns for performance
270
271/// Standard URL regex - primary pattern for bare URL detection (MD034).
272/// See [`URL_STANDARD_STR`] for documentation.
273pub static URL_STANDARD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_STANDARD_STR).unwrap());
274
275/// WWW URL regex - for URLs starting with www. without protocol.
276/// See [`URL_WWW_STR`] for documentation.
277pub static URL_WWW_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_WWW_STR).unwrap());
278
279/// IPv6 URL regex - for URLs with IPv6 addresses.
280/// See [`URL_IPV6_STR`] for documentation.
281pub static URL_IPV6_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_IPV6_STR).unwrap());
282
283/// Quick check regex - fast early-exit test.
284/// See [`URL_QUICK_CHECK_STR`] for documentation.
285pub static URL_QUICK_CHECK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_QUICK_CHECK_STR).unwrap());
286
287/// Simple URL regex - for content detection and line length exemption.
288/// See [`URL_SIMPLE_STR`] for documentation.
289pub static URL_SIMPLE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_SIMPLE_STR).unwrap());
290
291/// Alias for `URL_SIMPLE_REGEX`. Used by MD013 for line length exemption.
292pub static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| URL_SIMPLE_REGEX.clone());
293
294// Heading patterns
295pub static ATX_HEADING_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+|$)").unwrap());
296pub static CLOSED_ATX_HEADING_REGEX: LazyLock<Regex> =
297    LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+)(.*)(\s+)(#+)(\s*)$").unwrap());
298pub static SETEXT_HEADING_REGEX: LazyLock<Regex> =
299    LazyLock::new(|| Regex::new(r"^(\s*)[^\s]+.*\n(\s*)(=+|-+)\s*$").unwrap());
300pub static TRAILING_PUNCTUATION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.,:);!?]$").unwrap());
301
302// ATX heading patterns for MD051 and other rules
303pub static ATX_HEADING_WITH_CAPTURE: LazyLock<Regex> =
304    LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.+?)(?:\s+#*\s*)?$").unwrap());
305pub static SETEXT_HEADING_WITH_CAPTURE: LazyLock<FancyRegex> =
306    LazyLock::new(|| FancyRegex::new(r"^([^\n]+)\n([=\-])\2+\s*$").unwrap());
307
308// List patterns
309pub static UNORDERED_LIST_MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)([*+-])(\s+)").unwrap());
310pub static ORDERED_LIST_MARKER_REGEX: LazyLock<Regex> =
311    LazyLock::new(|| Regex::new(r"^(\s*)(\d+)([.)])(\s+)").unwrap());
312pub static LIST_MARKER_ANY_REGEX: LazyLock<Regex> =
313    LazyLock::new(|| Regex::new(r"^(\s*)(?:([*+-])|(\d+)[.)])(\s+)").unwrap());
314
315// Code block patterns
316pub static FENCED_CODE_BLOCK_START_REGEX: LazyLock<Regex> =
317    LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(.*)$").unwrap());
318pub static FENCED_CODE_BLOCK_END_REGEX: LazyLock<Regex> =
319    LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(\s*)$").unwrap());
320pub static INDENTED_CODE_BLOCK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})(.*)$").unwrap());
321pub static CODE_FENCE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(`{3,}|~{3,})").unwrap());
322
323// Emphasis patterns
324pub static EMPHASIS_REGEX: LazyLock<FancyRegex> =
325    LazyLock::new(|| FancyRegex::new(r"(\s|^)(\*{1,2}|_{1,2})(?=\S)(.+?)(?<=\S)(\2)(\s|$)").unwrap());
326pub static SPACE_IN_EMPHASIS_REGEX: LazyLock<FancyRegex> =
327    LazyLock::new(|| FancyRegex::new(r"(\*|_)(\s+)(.+?)(\s+)(\1)").unwrap());
328
329// MD037 specific emphasis patterns - improved to avoid false positives
330// Only match emphasis with spaces that are actually complete emphasis blocks
331// Use word boundaries and negative lookbehind/lookahead to avoid matching across emphasis boundaries
332pub static ASTERISK_EMPHASIS: LazyLock<Regex> =
333    LazyLock::new(|| Regex::new(r"(?:^|[^*])\*(\s+[^*]+\s*|\s*[^*]+\s+)\*(?:[^*]|$)").unwrap());
334pub static UNDERSCORE_EMPHASIS: LazyLock<Regex> =
335    LazyLock::new(|| Regex::new(r"(?:^|[^_])_(\s+[^_]+\s*|\s*[^_]+\s+)_(?:[^_]|$)").unwrap());
336pub static DOUBLE_UNDERSCORE_EMPHASIS: LazyLock<Regex> =
337    LazyLock::new(|| Regex::new(r"(?:^|[^_])__(\s+[^_]+\s*|\s*[^_]+\s+)__(?:[^_]|$)").unwrap());
338pub static DOUBLE_ASTERISK_EMPHASIS: LazyLock<FancyRegex> =
339    LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\s+\*\*").unwrap());
340pub static DOUBLE_ASTERISK_SPACE_START: LazyLock<FancyRegex> =
341    LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\*\*").unwrap());
342pub static DOUBLE_ASTERISK_SPACE_END: LazyLock<FancyRegex> =
343    LazyLock::new(|| FancyRegex::new(r"\*\*([^*]+?)\s+\*\*").unwrap());
344
345// Code block patterns
346pub static FENCED_CODE_BLOCK_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```(?:[^`\r\n]*)$").unwrap());
347pub static FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```\s*$").unwrap());
348pub static ALTERNATE_FENCED_CODE_BLOCK_START: LazyLock<Regex> =
349    LazyLock::new(|| Regex::new(r"^(\s*)~~~(?:[^~\r\n]*)$").unwrap());
350pub static ALTERNATE_FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)~~~\s*$").unwrap());
351pub static INDENTED_CODE_BLOCK_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})").unwrap());
352
353// HTML patterns
354pub static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*)>").unwrap());
355pub static HTML_SELF_CLOSING_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*/)>").unwrap());
356pub static HTML_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z][^>]*>").unwrap());
357pub static HTML_OPENING_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)<[a-zA-Z][^>]*>").unwrap());
358pub static HTML_TAG_QUICK_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z]").unwrap());
359
360// Link patterns for MD051 and other rules
361pub static LINK_REFERENCE_DEFINITION_REGEX: LazyLock<Regex> =
362    LazyLock::new(|| Regex::new(r"^\s*\[([^\]]+)\]:\s+(.+)$").unwrap());
363pub static INLINE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());
364pub static LINK_TEXT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]").unwrap());
365pub static LINK_REGEX: LazyLock<FancyRegex> =
366    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]*)\]\(([^)#]*)#([^)]+)\)").unwrap());
367pub static EXTERNAL_URL_REGEX: LazyLock<FancyRegex> =
368    LazyLock::new(|| FancyRegex::new(r"^(https?://|ftp://|www\.|[^/]+\.[a-z]{2,})").unwrap());
369
370// Image patterns
371pub static IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
372
373// Whitespace patterns
374pub static TRAILING_WHITESPACE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+$").unwrap());
375pub static MULTIPLE_BLANK_LINES_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
376
377// Front matter patterns
378pub static FRONT_MATTER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^---\n.*?\n---\n").unwrap());
379
380// MD051 specific patterns
381pub static INLINE_CODE_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"`[^`]+`").unwrap());
382pub static BOLD_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*(.+?)\*\*").unwrap());
383pub static BOLD_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"__(.+?)__").unwrap());
384pub static ITALIC_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*([^*]+?)\*").unwrap());
385pub static ITALIC_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"_([^_]+?)_").unwrap());
386pub static LINK_TEXT_FULL_REGEX: LazyLock<FancyRegex> =
387    LazyLock::new(|| FancyRegex::new(r"\[([^\]]*)\]\([^)]*\)").unwrap());
388pub static STRIKETHROUGH_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"~~(.+?)~~").unwrap());
389pub static MULTIPLE_HYPHENS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-{2,}").unwrap());
390pub static TOC_SECTION_START: LazyLock<Regex> =
391    LazyLock::new(|| Regex::new(r"^#+\s*(?:Table of Contents|Contents|TOC)\s*$").unwrap());
392
393// Blockquote patterns
394pub static BLOCKQUOTE_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*>+\s*)").unwrap());
395
396// MD013 specific patterns
397pub static IMAGE_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^!\[.*?\]\[.*?\]$").unwrap());
398pub static LINK_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[.*?\]:\s*https?://\S+$").unwrap());
399/// Greedy URL pattern for finding URLs in text for length calculation.
400///
401/// Pattern `https?://\S+` matches until whitespace, which may include trailing
402/// punctuation. This is intentional for MD013 line length calculation where
403/// we replace URLs with fixed-length placeholders.
404///
405/// For precise URL extraction, use `URL_STANDARD_REGEX` instead.
406pub static URL_IN_TEXT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://\S+").unwrap());
407pub static SENTENCE_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.!?]\s+[A-Z]").unwrap());
408pub static ABBREVIATION: LazyLock<Regex> = LazyLock::new(|| {
409    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()
410});
411pub static DECIMAL_NUMBER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d+\.\s*\d+").unwrap());
412pub static LIST_ITEM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\d+\.\s+").unwrap());
413pub static REFERENCE_LINK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\[([^\]]*)\]").unwrap());
414
415// Email pattern
416pub static EMAIL_PATTERN: LazyLock<Regex> =
417    LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap());
418
419// Third lazy_static block for link and image patterns used by MD052 and text_reflow
420// Reference link patterns (shared by MD052 and text_reflow)
421// Pattern to match reference links: [text][reference] or [text][]
422pub static REF_LINK_REGEX: LazyLock<FancyRegex> =
423    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
424
425// Pattern for shortcut reference links: [reference]
426// Must not be preceded by ] or ) (to avoid matching second part of [text][ref])
427// Must not be followed by [ or ( (to avoid matching first part of [text][ref] or [text](url))
428// The capturing group handles nested brackets to support cases like [`Union[T, None]`]
429pub static SHORTCUT_REF_REGEX: LazyLock<FancyRegex> =
430    LazyLock::new(|| FancyRegex::new(r"(?<![\\)\]])\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\](?!\s*[\[\(])").unwrap());
431
432// Inline link with fancy regex for better escaping handling (used by text_reflow)
433pub static INLINE_LINK_FANCY_REGEX: LazyLock<FancyRegex> =
434    LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]+)\]\(([^)]+)\)").unwrap());
435
436// Inline image with fancy regex (used by MD052 and text_reflow)
437pub static INLINE_IMAGE_FANCY_REGEX: LazyLock<FancyRegex> =
438    LazyLock::new(|| FancyRegex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
439
440// Linked images (clickable badges) - all 4 variants
441// Must be detected before inline_image and inline_link to treat as atomic units
442//
443// Limitation: Alt text containing brackets like [![[v1.0]](img)](link) is not supported.
444// The [^\]]* pattern cannot match nested brackets. This is rare in practice.
445//
446// Pattern 1: Inline image in inline link - [![alt](img-url)](link-url)
447pub static LINKED_IMAGE_INLINE_INLINE: LazyLock<FancyRegex> =
448    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)").unwrap());
449
450// Pattern 2: Reference image in inline link - [![alt][img-ref]](link-url)
451pub static LINKED_IMAGE_REF_INLINE: LazyLock<FancyRegex> =
452    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\(([^)]+)\)").unwrap());
453
454// Pattern 3: Inline image in reference link - [![alt](img-url)][link-ref]
455pub static LINKED_IMAGE_INLINE_REF: LazyLock<FancyRegex> =
456    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\[([^\]]*)\]").unwrap());
457
458// Pattern 4: Reference image in reference link - [![alt][img-ref]][link-ref]
459pub static LINKED_IMAGE_REF_REF: LazyLock<FancyRegex> =
460    LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\[([^\]]*)\]").unwrap());
461
462// Reference image: ![alt][ref] or ![alt][]
463pub static REF_IMAGE_REGEX: LazyLock<FancyRegex> =
464    LazyLock::new(|| FancyRegex::new(r"!\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
465
466// Footnote reference: [^note]
467pub static FOOTNOTE_REF_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\^([^\]]+)\]").unwrap());
468
469// Strikethrough with fancy regex: ~~text~~
470pub static STRIKETHROUGH_FANCY_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"~~([^~]+)~~").unwrap());
471
472// Wiki-style links: [[wiki]] or [[wiki|display text]]
473pub static WIKI_LINK_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\[([^\]]+)\]\]").unwrap());
474
475// Math formulas: $inline$ or $$display$$
476pub static INLINE_MATH_REGEX: LazyLock<FancyRegex> =
477    LazyLock::new(|| FancyRegex::new(r"(?<!\$)\$(?!\$)([^\$]+)\$(?!\$)").unwrap());
478pub static DISPLAY_MATH_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\$\$([^\$]+)\$\$").unwrap());
479
480// Emoji shortcodes: :emoji:
481pub static EMOJI_SHORTCODE_REGEX: LazyLock<FancyRegex> =
482    LazyLock::new(|| FancyRegex::new(r":([a-zA-Z0-9_+-]+):").unwrap());
483
484// HTML tags (opening, closing, self-closing)
485pub static HTML_TAG_PATTERN: LazyLock<FancyRegex> =
486    LazyLock::new(|| FancyRegex::new(r"</?[a-zA-Z][^>]*>|<[a-zA-Z][^>]*/\s*>").unwrap());
487
488// HTML entities: &nbsp; &mdash; etc
489pub static HTML_ENTITY_REGEX: LazyLock<FancyRegex> =
490    LazyLock::new(|| FancyRegex::new(r"&[a-zA-Z][a-zA-Z0-9]*;|&#\d+;|&#x[0-9a-fA-F]+;").unwrap());
491
492// Fourth lazy_static block for additional patterns
493// HTML comment patterns
494pub static HTML_COMMENT_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--").unwrap());
495pub static HTML_COMMENT_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-->").unwrap());
496pub static HTML_COMMENT_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--[\s\S]*?-->").unwrap());
497
498// HTML heading pattern (matches <h1> through <h6> tags)
499pub static HTML_HEADING_PATTERN: LazyLock<FancyRegex> =
500    LazyLock::new(|| FancyRegex::new(r"^\s*<h([1-6])(?:\s[^>]*)?>.*</h\1>\s*$").unwrap());
501
502// Heading quick check pattern
503pub static HEADING_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^(?:\s*)#").unwrap());
504
505// Horizontal rule patterns
506pub static HR_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\-{3,}\s*$").unwrap());
507pub static HR_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\*{3,}\s*$").unwrap());
508pub static HR_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^_{3,}\s*$").unwrap());
509pub static HR_SPACED_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\-\s+){2,}\-\s*$").unwrap());
510pub static HR_SPACED_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\*\s+){2,}\*\s*$").unwrap());
511pub static HR_SPACED_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(_\s+){2,}_\s*$").unwrap());
512
513/// Utility functions for quick content checks
514/// Check if content contains any headings (quick check before regex)
515pub fn has_heading_markers(content: &str) -> bool {
516    content.contains('#')
517}
518
519/// Check if content contains any lists (quick check before regex)
520pub fn has_list_markers(content: &str) -> bool {
521    content.contains('*')
522        || content.contains('-')
523        || content.contains('+')
524        || (content.contains('.') && content.contains(|c: char| c.is_ascii_digit()))
525}
526
527/// Check if content contains any code blocks (quick check before regex)
528pub fn has_code_block_markers(content: &str) -> bool {
529    content.contains("```") || content.contains("~~~") || content.contains("\n    ")
530    // Indented code block potential
531}
532
533/// Check if content contains any emphasis markers (quick check before regex)
534pub fn has_emphasis_markers(content: &str) -> bool {
535    content.contains('*') || content.contains('_')
536}
537
538/// Check if content contains any HTML tags (quick check before regex)
539pub fn has_html_tags(content: &str) -> bool {
540    content.contains('<') && (content.contains('>') || content.contains("/>"))
541}
542
543/// Check if content contains any links (quick check before regex)
544pub fn has_link_markers(content: &str) -> bool {
545    (content.contains('[') && content.contains(']'))
546        || content.contains("http://")
547        || content.contains("https://")
548        || content.contains("ftp://")
549}
550
551/// Check if content contains any images (quick check before regex)
552pub fn has_image_markers(content: &str) -> bool {
553    content.contains("![")
554}
555
556/// Optimize URL detection by implementing a character-by-character scanner
557/// that's much faster than regex for cases where we know there's no URL
558pub fn contains_url(content: &str) -> bool {
559    // Fast check - if these substrings aren't present, there's no URL
560    if !content.contains("://") {
561        return false;
562    }
563
564    let chars: Vec<char> = content.chars().collect();
565    let mut i = 0;
566
567    while i < chars.len() {
568        // Look for the start of a URL protocol
569        if i + 2 < chars.len()
570            && ((chars[i] == 'h' && chars[i + 1] == 't' && chars[i + 2] == 't')
571                || (chars[i] == 'f' && chars[i + 1] == 't' && chars[i + 2] == 'p'))
572        {
573            // Scan forward to find "://"
574            let mut j = i;
575            while j + 2 < chars.len() {
576                if chars[j] == ':' && chars[j + 1] == '/' && chars[j + 2] == '/' {
577                    return true;
578                }
579                j += 1;
580
581                // Don't scan too far ahead for the protocol
582                if j > i + 10 {
583                    break;
584                }
585            }
586        }
587        i += 1;
588    }
589
590    false
591}
592
593/// Escapes a string to be used in a regex pattern
594pub fn escape_regex(s: &str) -> String {
595    let mut result = String::with_capacity(s.len() * 2);
596
597    for c in s.chars() {
598        // Use matches! for O(1) lookup instead of array.contains() which is O(n)
599        if matches!(
600            c,
601            '.' | '+' | '*' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\'
602        ) {
603            result.push('\\');
604        }
605        result.push(c);
606    }
607
608    result
609}
610
611#[cfg(test)]
612mod tests {
613    use super::*;
614
615    #[test]
616    fn test_regex_cache_new() {
617        let cache = RegexCache::new();
618        assert!(cache.cache.is_empty());
619        assert!(cache.fancy_cache.is_empty());
620        assert!(cache.usage_stats.is_empty());
621    }
622
623    #[test]
624    fn test_regex_cache_default() {
625        let cache = RegexCache::default();
626        assert!(cache.cache.is_empty());
627        assert!(cache.fancy_cache.is_empty());
628        assert!(cache.usage_stats.is_empty());
629    }
630
631    #[test]
632    fn test_get_regex_compilation() {
633        let mut cache = RegexCache::new();
634
635        // First call compiles and caches
636        let regex1 = cache.get_regex(r"\d+").unwrap();
637        assert_eq!(cache.cache.len(), 1);
638        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&1));
639
640        // Second call returns cached version
641        let regex2 = cache.get_regex(r"\d+").unwrap();
642        assert_eq!(cache.cache.len(), 1);
643        assert_eq!(cache.usage_stats.get(r"\d+"), Some(&2));
644
645        // Both should be the same Arc
646        assert!(Arc::ptr_eq(&regex1, &regex2));
647    }
648
649    #[test]
650    fn test_get_regex_invalid_pattern() {
651        let mut cache = RegexCache::new();
652        let result = cache.get_regex(r"[unterminated");
653        assert!(result.is_err());
654        assert!(cache.cache.is_empty());
655    }
656
657    #[test]
658    fn test_get_fancy_regex_compilation() {
659        let mut cache = RegexCache::new();
660
661        // First call compiles and caches
662        let regex1 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
663        assert_eq!(cache.fancy_cache.len(), 1);
664        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&1));
665
666        // Second call returns cached version
667        let regex2 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
668        assert_eq!(cache.fancy_cache.len(), 1);
669        assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&2));
670
671        // Both should be the same Arc
672        assert!(Arc::ptr_eq(&regex1, &regex2));
673    }
674
675    #[test]
676    fn test_get_fancy_regex_invalid_pattern() {
677        let mut cache = RegexCache::new();
678        let result = cache.get_fancy_regex(r"(?<=invalid");
679        assert!(result.is_err());
680        assert!(cache.fancy_cache.is_empty());
681    }
682
683    #[test]
684    fn test_get_stats() {
685        let mut cache = RegexCache::new();
686
687        // Use some patterns
688        let _ = cache.get_regex(r"\d+").unwrap();
689        let _ = cache.get_regex(r"\d+").unwrap();
690        let _ = cache.get_regex(r"\w+").unwrap();
691        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
692
693        let stats = cache.get_stats();
694        assert_eq!(stats.get(r"\d+"), Some(&2));
695        assert_eq!(stats.get(r"\w+"), Some(&1));
696        assert_eq!(stats.get(r"(?<=foo)bar"), Some(&1));
697    }
698
699    #[test]
700    fn test_clear_cache() {
701        let mut cache = RegexCache::new();
702
703        // Add some patterns
704        let _ = cache.get_regex(r"\d+").unwrap();
705        let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
706
707        assert!(!cache.cache.is_empty());
708        assert!(!cache.fancy_cache.is_empty());
709        assert!(!cache.usage_stats.is_empty());
710
711        // Clear cache
712        cache.clear();
713
714        assert!(cache.cache.is_empty());
715        assert!(cache.fancy_cache.is_empty());
716        assert!(cache.usage_stats.is_empty());
717    }
718
719    #[test]
720    fn test_global_cache_functions() {
721        // Test get_cached_regex
722        let regex1 = get_cached_regex(r"\d{3}").unwrap();
723        let regex2 = get_cached_regex(r"\d{3}").unwrap();
724        assert!(Arc::ptr_eq(&regex1, &regex2));
725
726        // Test get_cached_fancy_regex
727        let fancy1 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
728        let fancy2 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
729        assert!(Arc::ptr_eq(&fancy1, &fancy2));
730
731        // Test stats
732        let stats = get_cache_stats();
733        assert!(stats.contains_key(r"\d{3}"));
734        assert!(stats.contains_key(r"(?<=test)ing"));
735    }
736
737    #[test]
738    fn test_regex_lazy_macro() {
739        let re = regex_lazy!(r"^test.*end$");
740        assert!(re.is_match("test something end"));
741        assert!(!re.is_match("test something"));
742
743        // The macro creates a new static for each invocation location,
744        // so we can't test pointer equality across different invocations
745        // But we can test that the regex works correctly
746        let re2 = regex_lazy!(r"^start.*finish$");
747        assert!(re2.is_match("start and finish"));
748        assert!(!re2.is_match("start without end"));
749    }
750
751    #[test]
752    fn test_has_heading_markers() {
753        assert!(has_heading_markers("# Heading"));
754        assert!(has_heading_markers("Text with # symbol"));
755        assert!(!has_heading_markers("Text without heading marker"));
756    }
757
758    #[test]
759    fn test_has_list_markers() {
760        assert!(has_list_markers("* Item"));
761        assert!(has_list_markers("- Item"));
762        assert!(has_list_markers("+ Item"));
763        assert!(has_list_markers("1. Item"));
764        assert!(!has_list_markers("Text without list markers"));
765    }
766
767    #[test]
768    fn test_has_code_block_markers() {
769        assert!(has_code_block_markers("```code```"));
770        assert!(has_code_block_markers("~~~code~~~"));
771        assert!(has_code_block_markers("Text\n    indented code"));
772        assert!(!has_code_block_markers("Text without code blocks"));
773    }
774
775    #[test]
776    fn test_has_emphasis_markers() {
777        assert!(has_emphasis_markers("*emphasis*"));
778        assert!(has_emphasis_markers("_emphasis_"));
779        assert!(has_emphasis_markers("**bold**"));
780        assert!(has_emphasis_markers("__bold__"));
781        assert!(!has_emphasis_markers("no emphasis"));
782    }
783
784    #[test]
785    fn test_has_html_tags() {
786        assert!(has_html_tags("<div>content</div>"));
787        assert!(has_html_tags("<br/>"));
788        assert!(has_html_tags("<img src='test.jpg'>"));
789        assert!(!has_html_tags("no html tags"));
790        assert!(!has_html_tags("less than < but no tag"));
791    }
792
793    #[test]
794    fn test_has_link_markers() {
795        assert!(has_link_markers("[text](url)"));
796        assert!(has_link_markers("[reference][1]"));
797        assert!(has_link_markers("http://example.com"));
798        assert!(has_link_markers("https://example.com"));
799        assert!(has_link_markers("ftp://example.com"));
800        assert!(!has_link_markers("no links here"));
801    }
802
803    #[test]
804    fn test_has_image_markers() {
805        assert!(has_image_markers("![alt text](image.png)"));
806        assert!(has_image_markers("![](image.png)"));
807        assert!(!has_image_markers("[link](url)"));
808        assert!(!has_image_markers("no images"));
809    }
810
811    #[test]
812    fn test_contains_url() {
813        assert!(contains_url("http://example.com"));
814        assert!(contains_url("Text with https://example.com link"));
815        assert!(contains_url("ftp://example.com"));
816        assert!(!contains_url("Text without URL"));
817        assert!(!contains_url("http not followed by ://"));
818
819        // Edge cases
820        assert!(!contains_url("http"));
821        assert!(!contains_url("https"));
822        assert!(!contains_url("://"));
823        assert!(contains_url("Visit http://site.com now"));
824        assert!(contains_url("See https://secure.site.com/path"));
825    }
826
827    #[test]
828    fn test_contains_url_performance() {
829        // Test early exit for strings without "://"
830        let long_text = "a".repeat(10000);
831        assert!(!contains_url(&long_text));
832
833        // Test with URL at the end
834        let text_with_url = format!("{long_text}https://example.com");
835        assert!(contains_url(&text_with_url));
836    }
837
838    #[test]
839    fn test_escape_regex() {
840        assert_eq!(escape_regex("a.b"), "a\\.b");
841        assert_eq!(escape_regex("a+b*c"), "a\\+b\\*c");
842        assert_eq!(escape_regex("(test)"), "\\(test\\)");
843        assert_eq!(escape_regex("[a-z]"), "\\[a-z\\]");
844        assert_eq!(escape_regex("normal text"), "normal text");
845
846        // Test all special characters
847        assert_eq!(escape_regex(".$^{[(|)*+?\\"), "\\.\\$\\^\\{\\[\\(\\|\\)\\*\\+\\?\\\\");
848
849        // Test empty string
850        assert_eq!(escape_regex(""), "");
851
852        // Test mixed content
853        assert_eq!(escape_regex("test.com/path?query=1"), "test\\.com/path\\?query=1");
854    }
855
856    #[test]
857    fn test_static_regex_patterns() {
858        // Test URL patterns
859        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
860        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
861        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com"));
862        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
863
864        // Test heading patterns
865        assert!(ATX_HEADING_REGEX.is_match("# Heading"));
866        assert!(ATX_HEADING_REGEX.is_match("  ## Indented"));
867        assert!(ATX_HEADING_REGEX.is_match("### "));
868        assert!(!ATX_HEADING_REGEX.is_match("Not a heading"));
869
870        // Test list patterns
871        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("* Item"));
872        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("- Item"));
873        assert!(UNORDERED_LIST_MARKER_REGEX.is_match("+ Item"));
874        assert!(ORDERED_LIST_MARKER_REGEX.is_match("1. Item"));
875        assert!(ORDERED_LIST_MARKER_REGEX.is_match("99. Item"));
876
877        // Test code block patterns
878        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```"));
879        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```rust"));
880        assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("~~~"));
881        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("```"));
882        assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("~~~"));
883
884        // Test emphasis patterns
885        assert!(BOLD_ASTERISK_REGEX.is_match("**bold**"));
886        assert!(BOLD_UNDERSCORE_REGEX.is_match("__bold__"));
887        assert!(ITALIC_ASTERISK_REGEX.is_match("*italic*"));
888        assert!(ITALIC_UNDERSCORE_REGEX.is_match("_italic_"));
889
890        // Test HTML patterns
891        assert!(HTML_TAG_REGEX.is_match("<div>"));
892        assert!(HTML_TAG_REGEX.is_match("<span class='test'>"));
893        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<br/>"));
894        assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<img src='test'/>"));
895
896        // Test whitespace patterns
897        assert!(TRAILING_WHITESPACE_REGEX.is_match("line with spaces   "));
898        assert!(TRAILING_WHITESPACE_REGEX.is_match("tabs\t\t"));
899        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n"));
900        assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n\n"));
901
902        // Test blockquote pattern
903        assert!(BLOCKQUOTE_PREFIX_RE.is_match("> Quote"));
904        assert!(BLOCKQUOTE_PREFIX_RE.is_match("  > Indented quote"));
905        assert!(BLOCKQUOTE_PREFIX_RE.is_match(">> Nested"));
906    }
907
908    #[test]
909    fn test_thread_safety() {
910        use std::thread;
911
912        let handles: Vec<_> = (0..10)
913            .map(|i| {
914                thread::spawn(move || {
915                    let pattern = format!(r"\d{{{i}}}");
916                    let regex = get_cached_regex(&pattern).unwrap();
917                    assert!(regex.is_match(&"1".repeat(i)));
918                })
919            })
920            .collect();
921
922        for handle in handles {
923            handle.join().unwrap();
924        }
925    }
926
927    // ==========================================================================
928    // Comprehensive URL Regex Tests
929    // ==========================================================================
930
931    #[test]
932    fn test_url_standard_basic() {
933        // Basic HTTP/HTTPS URLs
934        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
935        assert!(URL_STANDARD_REGEX.is_match("http://example.com"));
936        assert!(URL_STANDARD_REGEX.is_match("https://example.com/"));
937        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path"));
938        assert!(URL_STANDARD_REGEX.is_match("ftp://files.example.com"));
939        assert!(URL_STANDARD_REGEX.is_match("ftps://secure.example.com"));
940
941        // Should not match non-URLs
942        assert!(!URL_STANDARD_REGEX.is_match("not a url"));
943        assert!(!URL_STANDARD_REGEX.is_match("example.com"));
944        assert!(!URL_STANDARD_REGEX.is_match("www.example.com"));
945    }
946
947    #[test]
948    fn test_url_standard_with_path() {
949        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page"));
950        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page.html"));
951        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page/"));
952    }
953
954    #[test]
955    fn test_url_standard_with_query() {
956        assert!(URL_STANDARD_REGEX.is_match("https://example.com?query=value"));
957        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value"));
958        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?a=1&b=2"));
959    }
960
961    #[test]
962    fn test_url_standard_with_fragment() {
963        assert!(URL_STANDARD_REGEX.is_match("https://example.com#section"));
964        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path#section"));
965        assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value#section"));
966    }
967
968    #[test]
969    fn test_url_standard_with_port() {
970        assert!(URL_STANDARD_REGEX.is_match("https://example.com:8080"));
971        assert!(URL_STANDARD_REGEX.is_match("https://example.com:443/path"));
972        assert!(URL_STANDARD_REGEX.is_match("http://localhost:3000"));
973        assert!(URL_STANDARD_REGEX.is_match("https://192.168.1.1:8080/path"));
974    }
975
976    #[test]
977    fn test_url_standard_wikipedia_style_parentheses() {
978        // Wikipedia-style URLs with parentheses in path (Issue #240)
979        let url = "https://en.wikipedia.org/wiki/Rust_(programming_language)";
980        assert!(URL_STANDARD_REGEX.is_match(url));
981
982        // Verify the full URL is captured
983        let cap = URL_STANDARD_REGEX.find(url).unwrap();
984        assert_eq!(cap.as_str(), url);
985
986        // Multiple parentheses pairs
987        let url2 = "https://example.com/path_(foo)_(bar)";
988        let cap2 = URL_STANDARD_REGEX.find(url2).unwrap();
989        assert_eq!(cap2.as_str(), url2);
990    }
991
992    #[test]
993    fn test_url_standard_ipv6() {
994        // IPv6 addresses in URLs
995        assert!(URL_STANDARD_REGEX.is_match("https://[::1]/path"));
996        assert!(URL_STANDARD_REGEX.is_match("https://[2001:db8::1]:8080/path"));
997        assert!(URL_STANDARD_REGEX.is_match("http://[fe80::1%eth0]/"));
998    }
999
1000    #[test]
1001    fn test_url_www_basic() {
1002        // www URLs without protocol
1003        assert!(URL_WWW_REGEX.is_match("www.example.com"));
1004        assert!(URL_WWW_REGEX.is_match("www.example.co.uk"));
1005        assert!(URL_WWW_REGEX.is_match("www.sub.example.com"));
1006
1007        // Should not match plain domains without www
1008        assert!(!URL_WWW_REGEX.is_match("example.com"));
1009
1010        // Note: https://www.example.com DOES match because it contains "www."
1011        // The URL_WWW_REGEX is designed to find www. URLs that lack a protocol
1012        // Use URL_STANDARD_REGEX for full URLs with protocols
1013        assert!(URL_WWW_REGEX.is_match("https://www.example.com"));
1014    }
1015
1016    #[test]
1017    fn test_url_www_with_path() {
1018        assert!(URL_WWW_REGEX.is_match("www.example.com/path"));
1019        assert!(URL_WWW_REGEX.is_match("www.example.com/path/to/page"));
1020        assert!(URL_WWW_REGEX.is_match("www.example.com/path_(with_parens)"));
1021    }
1022
1023    #[test]
1024    fn test_url_ipv6_basic() {
1025        // IPv6 specific patterns
1026        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1027        assert!(URL_IPV6_REGEX.is_match("http://[2001:db8::1]/path"));
1028        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1]:8080/path"));
1029        assert!(URL_IPV6_REGEX.is_match("ftp://[::ffff:192.168.1.1]/file"));
1030    }
1031
1032    #[test]
1033    fn test_url_ipv6_with_zone_id() {
1034        // IPv6 with zone identifiers
1035        assert!(URL_IPV6_REGEX.is_match("https://[fe80::1%eth0]/path"));
1036        assert!(URL_IPV6_REGEX.is_match("http://[fe80::1%25eth0]:8080/"));
1037    }
1038
1039    #[test]
1040    fn test_url_simple_detection() {
1041        // Simple pattern for content characteristic detection
1042        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1043        assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
1044        assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com/file.zip"));
1045        assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
1046    }
1047
1048    #[test]
1049    fn test_url_quick_check() {
1050        // Quick check pattern for early exits
1051        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1052        assert!(URL_QUICK_CHECK_REGEX.is_match("http://example.com"));
1053        assert!(URL_QUICK_CHECK_REGEX.is_match("ftp://files.com"));
1054        assert!(URL_QUICK_CHECK_REGEX.is_match("www.example.com"));
1055        assert!(URL_QUICK_CHECK_REGEX.is_match("user@example.com"));
1056        assert!(!URL_QUICK_CHECK_REGEX.is_match("just plain text"));
1057    }
1058
1059    #[test]
1060    fn test_url_edge_cases() {
1061        // URLs with special characters that should be excluded
1062        let url = "https://example.com/path";
1063        assert!(URL_STANDARD_REGEX.is_match(url));
1064
1065        // URL followed by punctuation - the regex captures trailing punctuation
1066        // because trimming is done by `trim_trailing_punctuation()` in the rule
1067        let text = "Check https://example.com, it's great!";
1068        let cap = URL_STANDARD_REGEX.find(text).unwrap();
1069        // The comma IS captured by the regex - rule-level trimming handles this
1070        assert!(cap.as_str().ends_with(','));
1071
1072        // URL in angle brackets should still be found
1073        let text2 = "See <https://example.com> for more";
1074        assert!(URL_STANDARD_REGEX.is_match(text2));
1075
1076        // URL ending at angle bracket should stop at >
1077        let cap2 = URL_STANDARD_REGEX.find(text2).unwrap();
1078        assert!(!cap2.as_str().contains('>'));
1079    }
1080
1081    #[test]
1082    fn test_url_with_complex_paths() {
1083        // Complex real-world URLs
1084        let urls = [
1085            "https://github.com/owner/repo/blob/main/src/file.rs#L123",
1086            "https://docs.example.com/api/v2/endpoint?format=json&page=1",
1087            "https://cdn.example.com/assets/images/logo.png?v=2023",
1088            "https://search.example.com/results?q=test+query&filter=all",
1089        ];
1090
1091        for url in urls {
1092            assert!(URL_STANDARD_REGEX.is_match(url), "Should match: {url}");
1093        }
1094    }
1095
1096    #[test]
1097    fn test_url_pattern_strings_are_valid() {
1098        // Verify patterns compile into valid regexes by accessing them
1099        assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
1100        assert!(URL_WWW_REGEX.is_match("www.example.com"));
1101        assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1102        assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1103        assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1104    }
1105}