Skip to main content

aft_base/
query_shape.rs

1use regex::Regex;
2use std::collections::{HashMap, HashSet};
3use std::sync::LazyLock;
4
5static CAMEL_CASE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[a-z][A-Z]").unwrap());
6static SNAKE_CASE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[a-z]_[a-z]").unwrap());
7static PASCAL_CASE_RE: LazyLock<Regex> =
8    LazyLock::new(|| Regex::new(r"^[A-Z][a-z]+[A-Z]").unwrap());
9static ACRONYM_PASCAL_RE: LazyLock<Regex> =
10    LazyLock::new(|| Regex::new(r"\b[A-Z]{2,}[A-Z][a-z]").unwrap());
11static DOT_PATH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[a-zA-Z]\.[a-zA-Z]").unwrap());
12static FILE_PATH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[/\\].*\.\w{1,5}$").unwrap());
13static HEX_CODE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"0x[A-Fa-f0-9]+").unwrap());
14static ERROR_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\bERR_\w+").unwrap());
15static NUMERIC_ERROR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\bE\d{4,}").unwrap());
16static TYPESCRIPT_ERROR_RE: LazyLock<Regex> =
17    LazyLock::new(|| Regex::new(r"\bTS\d{4,}\b").unwrap());
18static HTTP_STATUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b[1-5]\d{2}\b").unwrap());
19static IDENTIFIER_TOKEN_RE: LazyLock<Regex> = LazyLock::new(|| {
20    Regex::new(r"\b[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*\b").unwrap()
21});
22
23static WINDOWS_ABS_PATH_RE: LazyLock<Regex> =
24    LazyLock::new(|| Regex::new(r"^[A-Za-z]:[\\/][A-Za-z0-9_.\-+?\\/' ]+$").unwrap());
25static WINDOWS_REL_PATH_RE: LazyLock<Regex> =
26    LazyLock::new(|| Regex::new(r"^[A-Za-z0-9_.\-+?' ]+(\\[A-Za-z0-9_.\-+?' ]+)+$").unwrap());
27static POSIX_ABS_PATH_RE: LazyLock<Regex> =
28    LazyLock::new(|| Regex::new(r"^/[A-Za-z0-9_.\-+?/' ]+$").unwrap());
29static POSIX_REL_PATH_RE: LazyLock<Regex> =
30    LazyLock::new(|| Regex::new(r"^[A-Za-z0-9_.\-+?' ]+(/[A-Za-z0-9_.\-+?' ]+)+$").unwrap());
31static UNC_PATH_RE: LazyLock<Regex> =
32    LazyLock::new(|| Regex::new(r"^\\\\[A-Za-z0-9_.\-+?\\']+$").unwrap());
33static FILENAME_EXEMPTION_RE: LazyLock<Regex> =
34    LazyLock::new(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_.\-+'? ]*\.[A-Za-z0-9]{1,8}$").unwrap());
35static BRACE_QUANTIFIER_RE: LazyLock<Regex> =
36    LazyLock::new(|| Regex::new(r"\{\d+(?:,\d*)?\}").unwrap());
37static NAMED_CAPTURE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\(\?P<[^>]+>").unwrap());
38static CHAR_RANGE_RE: LazyLock<Regex> =
39    LazyLock::new(|| Regex::new(r"[A-Za-z0-9]-[A-Za-z0-9]").unwrap());
40
41const QUESTION_WORDS: &[&str] = &[
42    "how", "what", "where", "why", "when", "which", "who", "does",
43];
44
45const CONTENT_STOP_WORDS: &[&str] = &[
46    "and", "are", "been", "but", "does", "for", "from", "had", "has", "have", "how", "into", "its",
47    "not", "of", "on", "that", "the", "their", "then", "there", "these", "this", "those", "was",
48    "were", "what", "when", "where", "which", "who", "why", "with", "would",
49];
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum QueryKind {
53    Identifier,
54    Mixed,
55    ErrorCode,
56    Path,
57    Regex,
58    NaturalLanguage,
59}
60
61#[derive(Debug, Clone, Copy, PartialEq)]
62pub struct ShapeWeights {
63    pub semantic: f32,
64    pub lexical: f32,
65    pub should_use_lexical: bool,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq)]
69pub struct QueryShape {
70    pub kind: QueryKind,
71    pub weights: ShapeWeights,
72}
73
74pub fn classify(query: &str) -> QueryShape {
75    let trimmed = query.trim();
76    if trimmed.is_empty() {
77        return shape(QueryKind::NaturalLanguage);
78    }
79
80    if pre_tier_exempt(trimmed).is_some() {
81        return shape(QueryKind::Path);
82    }
83
84    if looks_like_regex(trimmed) {
85        return shape(QueryKind::Regex);
86    }
87
88    let words: Vec<&str> = trimmed.split_whitespace().collect();
89    let word_count = words.len();
90    let first_word_lower = words[0].to_ascii_lowercase();
91
92    if FILE_PATH_RE.is_match(trimmed) {
93        return shape(QueryKind::Path);
94    }
95
96    let has_question_word = QUESTION_WORDS.contains(&first_word_lower.as_str());
97    let is_long_phrase = word_count > 2;
98    let is_two_word_concept = is_two_word_lowercase_concept(&words);
99    let has_natural_language_signals = has_question_word || is_long_phrase || is_two_word_concept;
100    let has_error_code = contains_error_code(trimmed, word_count);
101
102    if has_error_code && has_natural_language_signals {
103        return shape(QueryKind::Mixed);
104    }
105
106    if has_error_code {
107        return shape(QueryKind::ErrorCode);
108    }
109
110    let has_code_identifier = CAMEL_CASE_RE.is_match(trimmed)
111        || SNAKE_CASE_RE.is_match(trimmed)
112        || PASCAL_CASE_RE.is_match(trimmed)
113        || ACRONYM_PASCAL_RE.is_match(trimmed)
114        || DOT_PATH_RE.is_match(trimmed);
115
116    if has_code_identifier && has_natural_language_signals {
117        return shape(QueryKind::Mixed);
118    }
119
120    if has_code_identifier || (word_count <= 2 && !has_natural_language_signals) {
121        return shape(QueryKind::Identifier);
122    }
123
124    shape(QueryKind::NaturalLanguage)
125}
126
127pub fn extract_tokens(query: &str, shape: &QueryShape) -> Vec<String> {
128    match shape.kind {
129        QueryKind::NaturalLanguage | QueryKind::Regex => Vec::new(),
130        QueryKind::Path => extract_path_tokens(query),
131        QueryKind::ErrorCode => extract_error_code_tokens(query),
132        QueryKind::Identifier => extract_identifier_tokens(query, false),
133        QueryKind::Mixed => extract_identifier_tokens(query, true),
134    }
135}
136
137/// Tokens supplied to the trigram search during hybrid retrieval and a lexical
138/// retry after zero results. Natural-language queries contribute normalized
139/// content words with stopwords removed. Regex retries prefer explicit
140/// code-shaped tokens before falling back to identifier-shaped text.
141pub fn extract_lexical_tokens(query: &str, shape: &QueryShape) -> Vec<String> {
142    match shape.kind {
143        QueryKind::NaturalLanguage => extract_content_tokens(query),
144        QueryKind::Regex => {
145            let explicit = extract_explicit_code_tokens(query);
146            if explicit.is_empty() {
147                extract_identifier_tokens(query, false)
148            } else {
149                explicit
150            }
151        }
152        _ => extract_tokens(query, shape),
153    }
154}
155
156/// Legacy wrapper that delegates natural-language token extraction.
157pub fn extract_short_nl_lexical_tokens(query: &str) -> Vec<String> {
158    extract_content_tokens(query)
159}
160
161/// Unique lowercase natural-language tokens with stopwords and words shorter
162/// than the three-character trigram minimum removed.
163pub fn extract_content_tokens(text: &str) -> Vec<String> {
164    let mut tokens = Vec::new();
165    for mat in IDENTIFIER_TOKEN_RE.find_iter(text) {
166        let token = mat.as_str().to_ascii_lowercase();
167        if token.chars().count() < 3 || CONTENT_STOP_WORDS.contains(&token.as_str()) {
168            continue;
169        }
170        push_unique(&mut tokens, &token);
171    }
172    tokens
173}
174
175/// Return whether every normalized query content token occurs in the supplied
176/// text slice. Exact-tier fusion supplies at most three consecutive source lines
177/// and exits as soon as every requested token has been observed.
178pub fn contains_all_content_tokens(text: &str, tokens: &[String]) -> bool {
179    #[cfg(any(test, feature = "test-support"))]
180    crate::search_hot_path_measurements::record(|counts| counts.token_scans += 1);
181    if tokens.is_empty() {
182        return false;
183    }
184    let mut remaining = tokens.iter().map(String::as_str).collect::<HashSet<_>>();
185    for mat in IDENTIFIER_TOKEN_RE.find_iter(text) {
186        let token = mat.as_str().to_ascii_lowercase();
187        remaining.remove(token.as_str());
188        if remaining.is_empty() {
189            return true;
190        }
191    }
192    false
193}
194
195/// Find the narrowest all-token window of at most three source lines. Tracking
196/// the most recent line for each token avoids rejoining overlapping windows;
197/// identifier matches cannot span the newline separators used by those windows.
198pub fn minimum_content_token_window(text: &str, tokens: &[String]) -> Option<usize> {
199    if tokens.is_empty() {
200        return None;
201    }
202    let mut last_seen = tokens
203        .iter()
204        .map(|token| (token.as_str(), None::<usize>))
205        .collect::<HashMap<_, _>>();
206    let mut best = None;
207    for (line_index, line) in text.lines().enumerate() {
208        #[cfg(any(test, feature = "test-support"))]
209        crate::search_hot_path_measurements::record(|counts| counts.token_lines_scanned += 1);
210        for found in IDENTIFIER_TOKEN_RE.find_iter(line) {
211            let word = found.as_str();
212            let lower = if word.bytes().any(|byte| byte.is_ascii_uppercase()) {
213                std::borrow::Cow::Owned(word.to_ascii_lowercase())
214            } else {
215                std::borrow::Cow::Borrowed(word)
216            };
217            if let Some(position) = last_seen.get_mut(lower.as_ref()) {
218                *position = Some(line_index);
219            }
220        }
221        let oldest = last_seen.values().try_fold(usize::MAX, |oldest, position| {
222            position.map(|position| oldest.min(position))
223        });
224        if let Some(oldest) = oldest {
225            let width = line_index - oldest + 1;
226            if width <= 3 && best.is_none_or(|previous| width < previous) {
227                best = Some(width);
228                if width == 1 {
229                    return best;
230                }
231            }
232        }
233    }
234    best
235}
236
237pub fn is_type_concept_identifier_query(query: &str, shape: &QueryShape) -> bool {
238    if shape.kind != QueryKind::Identifier {
239        return false;
240    }
241
242    let mut identifier_token_count = 0;
243    let mut has_type_token = false;
244    let mut has_lowercase_concept_word = false;
245
246    for mat in IDENTIFIER_TOKEN_RE.find_iter(query) {
247        let token = mat.as_str();
248        identifier_token_count += 1;
249        has_type_token |= is_type_concept_type_token(token);
250        has_lowercase_concept_word |= is_dictionary_style_lowercase_word(token);
251    }
252
253    identifier_token_count >= 2 && has_type_token && has_lowercase_concept_word
254}
255
256fn is_type_concept_type_token(token: &str) -> bool {
257    token
258        .chars()
259        .next()
260        .is_some_and(|first| first.is_ascii_uppercase())
261        && (is_titlecase_word(token)
262            || PASCAL_CASE_RE.is_match(token)
263            || ACRONYM_PASCAL_RE.is_match(token))
264}
265
266/// Code-shaped tokens that are explicit enough to use for semantic name priors
267/// inside natural-language queries. Bare prose words are excluded: a lone
268/// capitalized word like "Engine" is too ambiguous unless quoted, while adjacent
269/// TitleCase words are treated as one qualified name such as "Engine.Index".
270pub fn extract_explicit_code_tokens(query: &str) -> Vec<String> {
271    let mut tokens = Vec::new();
272
273    push_quoted_code_tokens(query, &mut tokens);
274    let title_spans = push_adjacent_titlecase_tokens(query, 0, &mut tokens);
275    for mat in IDENTIFIER_TOKEN_RE.find_iter(query) {
276        if span_is_covered(&title_spans, mat.start(), mat.end()) {
277            continue;
278        }
279        let token = mat.as_str();
280        if is_code_identifier_token(token) {
281            push_unique(&mut tokens, token);
282        }
283    }
284
285    tokens
286}
287
288pub fn pre_tier_exempt(query: &str) -> Option<&'static str> {
289    if let Some(kind) = check_url_exemption(query) {
290        return Some(kind);
291    }
292    check_path_exemption(query)
293}
294
295pub fn looks_like_regex(query: &str) -> bool {
296    crate::pattern_compile::detect_unsupported_features(query).is_some()
297        || tier_a_regex_signal(query)
298        || tier_b_character_class(query)
299        || tier_c_adjacent_meta(query)
300}
301
302fn check_url_exemption(query: &str) -> Option<&'static str> {
303    let parsed = url::Url::parse(query).ok()?;
304    if !matches!(parsed.scheme(), "http" | "https" | "file" | "ftp" | "ssh") {
305        return None;
306    }
307    if has_regex_meta_sequences(query) || has_obvious_regex_chars(query) {
308        return None;
309    }
310    Some("url")
311}
312
313fn check_path_exemption(query: &str) -> Option<&'static str> {
314    let kind = if WINDOWS_ABS_PATH_RE.is_match(query) {
315        "windows_abs"
316    } else if WINDOWS_REL_PATH_RE.is_match(query) {
317        "windows_rel"
318    } else if POSIX_ABS_PATH_RE.is_match(query) {
319        "posix_abs"
320    } else if POSIX_REL_PATH_RE.is_match(query) {
321        "posix_rel"
322    } else if UNC_PATH_RE.is_match(query) {
323        "unc"
324    } else if FILENAME_EXEMPTION_RE.is_match(query) {
325        "filename"
326    } else {
327        return None;
328    };
329    if has_path_regex_meta_sequences(query) || has_obvious_regex_chars(query) {
330        return None;
331    }
332    Some(kind)
333}
334
335fn contains_error_code(query: &str, word_count: usize) -> bool {
336    HEX_CODE_RE.is_match(query)
337        || ERROR_PREFIX_RE.is_match(query)
338        || NUMERIC_ERROR_RE.is_match(query)
339        || TYPESCRIPT_ERROR_RE.is_match(query)
340        || has_http_status(query, word_count)
341}
342
343fn has_http_status(query: &str, word_count: usize) -> bool {
344    HTTP_STATUS_RE.is_match(query)
345        && (word_count <= 3 || query.to_ascii_lowercase().contains("http"))
346}
347
348fn is_two_word_lowercase_concept(words: &[&str]) -> bool {
349    words.len() == 2
350        && words
351            .iter()
352            .all(|word| is_dictionary_style_lowercase_word(word))
353}
354
355fn is_dictionary_style_lowercase_word(word: &str) -> bool {
356    word.len() >= 3 && word.bytes().all(|byte| byte.is_ascii_lowercase())
357}
358
359fn has_regex_meta_sequences(query: &str) -> bool {
360    query.contains(".+")
361        || query.contains(".*")
362        || query.contains(".?")
363        || query.contains(r"\n")
364        || query.contains(r"\t")
365        || query.contains(r"\r")
366        || query.contains(r"\b")
367        || query.contains(r"\B")
368        || query.contains(r"\w")
369        || query.contains(r"\W")
370        || query.contains(r"\d")
371        || query.contains(r"\D")
372        || query.contains(r"\s")
373        || query.contains(r"\S")
374        || query.contains(r"\p{")
375        || query.contains(r"\x")
376        || query.contains(r"\u{")
377        || has_escaped_regex_metachar(query)
378}
379
380fn has_path_regex_meta_sequences(query: &str) -> bool {
381    query.contains(".+")
382        || query.contains(".*")
383        || query.contains(".?")
384        || query.contains(r"\p{")
385        || query.contains(r"\x")
386        || query.contains(r"\u{")
387        || has_path_context_regex_escape(query)
388        || has_escaped_regex_metachar(query)
389}
390
391fn has_path_context_regex_escape(query: &str) -> bool {
392    let chars = query.char_indices().collect::<Vec<_>>();
393    for index in 0..chars.len().saturating_sub(1) {
394        if chars[index].1 != '\\' {
395            continue;
396        }
397        let escaped = chars[index + 1].1;
398        if matches!(escaped, 'b' | 'B' | 'w' | 'W' | 'd' | 'D' | 's' | 'S')
399            && path_escape_looks_like_regex(&chars, index + 1)
400        {
401            return true;
402        }
403    }
404    false
405}
406
407fn path_escape_looks_like_regex(chars: &[(usize, char)], escaped_index: usize) -> bool {
408    let Some((_, next)) = chars.get(escaped_index + 1) else {
409        return true;
410    };
411
412    matches!(
413        *next,
414        '*' | '+' | '?' | '{' | '(' | '[' | '|' | '^' | '$' | '\\' | '/'
415    )
416}
417
418fn has_escaped_regex_metachar(query: &str) -> bool {
419    let mut escaped = false;
420    for ch in query.chars() {
421        if escaped {
422            if is_escaped_metachar(ch) {
423                return true;
424            }
425            escaped = false;
426            continue;
427        }
428        escaped = ch == '\\';
429    }
430    false
431}
432
433fn has_obvious_regex_chars(query: &str) -> bool {
434    query.contains('*')
435        || query.contains('[')
436        || query.contains(']')
437        || query.contains('(')
438        || query.contains(')')
439        || query.contains('|')
440        || query.contains('{')
441        || query.contains('}')
442}
443
444fn tier_a_regex_signal(query: &str) -> bool {
445    query.contains("(?:")
446        || NAMED_CAPTURE_RE.is_match(query)
447        || ["(?i)", "(?m)", "(?s)", "(?x)"]
448            .iter()
449            .any(|signal| query.contains(signal))
450        || [
451            r"\b", r"\B", r"\w", r"\W", r"\d", r"\D", r"\s", r"\S", r"\p{", r"\x", r"\u{", r"\n",
452            r"\t", r"\r",
453        ]
454        .iter()
455        .any(|signal| query.contains(signal))
456        || has_brace_quantifier(query)
457        || has_anchored_identifier(query)
458        || has_contextual_escaped_metachar(query)
459}
460
461fn has_brace_quantifier(query: &str) -> bool {
462    for matched in BRACE_QUANTIFIER_RE.find_iter(query) {
463        if matched.start() > 0
464            && query[..matched.start()]
465                .chars()
466                .last()
467                .is_some_and(|ch| !ch.is_whitespace())
468        {
469            return true;
470        }
471    }
472    false
473}
474
475fn has_anchored_identifier(query: &str) -> bool {
476    let trimmed = query.trim();
477    if let Some(rest) = trimmed.strip_prefix('^') {
478        if leading_identifier_len(rest) >= 3 {
479            return true;
480        }
481    }
482    if let Some(rest) = trimmed.strip_suffix('$') {
483        if trailing_identifier_len(rest) >= 3 {
484            return true;
485        }
486    }
487    false
488}
489
490fn leading_identifier_len(text: &str) -> usize {
491    text.chars()
492        .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_')
493        .count()
494}
495
496fn trailing_identifier_len(text: &str) -> usize {
497    text.chars()
498        .rev()
499        .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_')
500        .count()
501}
502
503fn has_contextual_escaped_metachar(query: &str) -> bool {
504    let chars: Vec<char> = query.chars().collect();
505    let mut index = 0usize;
506    while index + 1 < chars.len() {
507        if chars[index] == '\\' && is_escaped_metachar(chars[index + 1]) {
508            let literal_after = chars[index + 2..]
509                .iter()
510                .filter(|ch| ch.is_ascii_alphanumeric() || **ch == '_')
511                .count();
512            if literal_after >= 2 {
513                return true;
514            }
515            index += 2;
516        } else {
517            index += 1;
518        }
519    }
520    false
521}
522
523fn is_escaped_metachar(ch: char) -> bool {
524    matches!(
525        ch,
526        '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$'
527    )
528}
529
530fn tier_b_character_class(query: &str) -> bool {
531    for content in bracket_contents(query) {
532        if content.starts_with('^')
533            || CHAR_RANGE_RE.is_match(&content)
534            || [r"\w", r"\d", r"\s", r"\W", r"\D", r"\S"]
535                .iter()
536                .any(|signal| content.contains(signal))
537            || multi_char_non_identifier_class(&content)
538        {
539            return true;
540        }
541    }
542    false
543}
544
545fn bracket_contents(query: &str) -> Vec<String> {
546    let mut contents = Vec::new();
547    let mut escaped = false;
548    let mut start = None;
549    for (index, ch) in query.char_indices() {
550        if escaped {
551            escaped = false;
552            continue;
553        }
554        if ch == '\\' {
555            escaped = true;
556            continue;
557        }
558        match ch {
559            '[' if start.is_none() => start = Some(index + ch.len_utf8()),
560            ']' => {
561                if let Some(open) = start.take() {
562                    contents.push(query[open..index].to_string());
563                }
564            }
565            _ => {}
566        }
567    }
568    contents
569}
570
571fn multi_char_non_identifier_class(content: &str) -> bool {
572    let char_count = content.chars().count();
573    char_count >= 2
574        && !content.chars().any(|ch| {
575            ch.is_ascii_alphanumeric() || ch == '_' || ch == '"' || ch == '\'' || ch == ';'
576        })
577}
578
579fn tier_c_adjacent_meta(query: &str) -> bool {
580    has_dot_quantifier(query)
581        || has_literal_atom_quantifier(query)
582        || has_regex_pipe(query)
583        || escaped_paren_count(query) >= 2
584}
585
586fn has_dot_quantifier(query: &str) -> bool {
587    [".*", ".+", ".?"]
588        .iter()
589        .any(|signal| query.contains(signal) && query.trim().len() > signal.len())
590}
591
592fn has_literal_atom_quantifier(query: &str) -> bool {
593    let chars = query.char_indices().collect::<Vec<_>>();
594    for (index, (byte_index, ch)) in chars.iter().copied().enumerate() {
595        if !is_bare_quantifier(ch) || is_escaped_at(query, byte_index) {
596            continue;
597        }
598        if chars
599            .get(index + 1)
600            .is_some_and(|(_, next)| is_bare_quantifier(*next))
601        {
602            continue;
603        }
604        if ch == '?'
605            && (sentence_final_question_mark_in_phrase(query, byte_index)
606                || question_mark_is_code_shape(&chars, index))
607        {
608            continue;
609        }
610        if previous_is_literal_atom(&chars, index) {
611            return true;
612        }
613    }
614    false
615}
616
617fn sentence_final_question_mark_in_phrase(query: &str, byte_index: usize) -> bool {
618    query[byte_index + '?'.len_utf8()..].trim().is_empty()
619        && query[..byte_index].split_whitespace().count() > 1
620}
621
622fn question_mark_is_code_shape(chars: &[(usize, char)], question_index: usize) -> bool {
623    question_mark_is_optional_chain(chars, question_index)
624        || question_mark_after_empty_call(chars, question_index)
625        || question_mark_after_index_expression(chars, question_index)
626        || question_mark_is_typescript_optional(chars, question_index)
627}
628
629fn question_mark_is_optional_chain(chars: &[(usize, char)], question_index: usize) -> bool {
630    chars
631        .get(question_index + 1)
632        .is_some_and(|(_, next)| *next == '.')
633        && question_index
634            .checked_sub(1)
635            .and_then(|previous_index| chars.get(previous_index))
636            .is_some_and(|(_, previous)| is_code_expression_tail(*previous))
637}
638
639fn question_mark_after_empty_call(chars: &[(usize, char)], question_index: usize) -> bool {
640    let Some(call_open_index) = question_index.checked_sub(2) else {
641        return false;
642    };
643    chars
644        .get(question_index - 1)
645        .is_some_and(|(_, previous)| *previous == ')')
646        && chars
647            .get(call_open_index)
648            .is_some_and(|(_, open)| *open == '(')
649        && call_open_index
650            .checked_sub(1)
651            .and_then(|callee_index| chars.get(callee_index))
652            .is_some_and(|(_, callee_tail)| is_code_expression_tail(*callee_tail))
653}
654
655fn question_mark_after_index_expression(chars: &[(usize, char)], question_index: usize) -> bool {
656    if chars
657        .get(question_index.checked_sub(1).unwrap_or(usize::MAX))
658        .is_none_or(|(_, previous)| *previous != ']')
659    {
660        return false;
661    }
662
663    let mut depth = 0usize;
664    for index in (0..question_index).rev() {
665        match chars[index].1 {
666            ']' => depth += 1,
667            '[' => {
668                depth = depth.saturating_sub(1);
669                if depth == 0 {
670                    return index
671                        .checked_sub(1)
672                        .and_then(|target_index| chars.get(target_index))
673                        .is_some_and(|(_, target_tail)| is_code_expression_tail(*target_tail));
674                }
675            }
676            _ => {}
677        }
678    }
679    false
680}
681
682fn question_mark_is_typescript_optional(chars: &[(usize, char)], question_index: usize) -> bool {
683    let previous_is_identifier = question_index
684        .checked_sub(1)
685        .and_then(|previous_index| chars.get(previous_index))
686        .is_some_and(|(_, previous)| is_identifier_tail(*previous));
687    if !previous_is_identifier {
688        return false;
689    }
690    if chars
691        .get(question_index + 1)
692        .is_none_or(|(_, next)| *next != ':')
693    {
694        return false;
695    }
696
697    chars
698        .get(question_index + 2)
699        .is_none_or(|(_, after_colon)| {
700            after_colon.is_whitespace()
701                || after_colon.is_ascii_alphabetic()
702                || matches!(*after_colon, '_' | '{' | '[' | '(' | '"' | '\'')
703        })
704}
705
706fn is_code_expression_tail(ch: char) -> bool {
707    is_identifier_tail(ch) || matches!(ch, ')' | ']')
708}
709
710fn is_identifier_tail(ch: char) -> bool {
711    ch.is_ascii_alphanumeric() || matches!(ch, '_' | '$')
712}
713
714fn previous_is_literal_atom(chars: &[(usize, char)], quantifier_index: usize) -> bool {
715    let Some((_, previous)) = quantifier_index
716        .checked_sub(1)
717        .and_then(|previous_index| chars.get(previous_index))
718    else {
719        return false;
720    };
721
722    previous.is_ascii_alphanumeric() || *previous == '_' || *previous == ')' || *previous == ']'
723}
724
725fn is_bare_quantifier(ch: char) -> bool {
726    matches!(ch, '*' | '+' | '?')
727}
728
729fn is_escaped_at(query: &str, byte_index: usize) -> bool {
730    let backslash_count = query[..byte_index]
731        .chars()
732        .rev()
733        .take_while(|ch| *ch == '\\')
734        .count();
735    backslash_count % 2 == 1
736}
737
738fn has_regex_pipe(query: &str) -> bool {
739    for (index, ch) in query.char_indices() {
740        if ch != '|' {
741            continue;
742        }
743        let left = trailing_identifier_len(&query[..index]);
744        let right = leading_identifier_len(&query[index + ch.len_utf8()..]);
745        if left >= 3 && right >= 3 {
746            return true;
747        }
748    }
749    false
750}
751
752fn escaped_paren_count(query: &str) -> usize {
753    let mut count = 0usize;
754    let mut escaped = false;
755    for ch in query.chars() {
756        if escaped {
757            if ch == '(' || ch == ')' {
758                count += 1;
759            }
760            escaped = false;
761            continue;
762        }
763        escaped = ch == '\\';
764    }
765    count
766}
767
768fn push_quoted_code_tokens(query: &str, tokens: &mut Vec<String>) {
769    let mut open: Option<(char, usize)> = None;
770    let mut escaped = false;
771
772    for (index, ch) in query.char_indices() {
773        if escaped {
774            escaped = false;
775            continue;
776        }
777        if ch == '\\' {
778            escaped = true;
779            continue;
780        }
781
782        if let Some((delimiter, content_start)) = open {
783            if ch == delimiter {
784                let content = &query[content_start..index];
785                let title_spans = push_adjacent_titlecase_tokens(content, content_start, tokens);
786                for mat in IDENTIFIER_TOKEN_RE.find_iter(content) {
787                    let start = content_start + mat.start();
788                    let end = content_start + mat.end();
789                    if !span_is_covered(&title_spans, start, end) {
790                        push_unique(tokens, mat.as_str());
791                    }
792                }
793                open = None;
794            }
795        } else if matches!(ch, '"' | '\'' | '`') {
796            open = Some((ch, index + ch.len_utf8()));
797        }
798    }
799}
800
801fn push_adjacent_titlecase_tokens(
802    text: &str,
803    base_offset: usize,
804    tokens: &mut Vec<String>,
805) -> Vec<(usize, usize)> {
806    let mut covered_spans = Vec::new();
807    let mut current: Vec<(usize, usize, &str)> = Vec::new();
808    let mut previous_end: Option<usize> = None;
809
810    for mat in IDENTIFIER_TOKEN_RE.find_iter(text) {
811        let token = mat.as_str();
812        let adjacent_to_current = previous_end.is_some_and(|end| {
813            !current.is_empty() && text[end..mat.start()].chars().all(|ch| ch.is_whitespace())
814        });
815        if is_titlecase_word(token) && (current.is_empty() || adjacent_to_current) {
816            current.push((base_offset + mat.start(), base_offset + mat.end(), token));
817        } else {
818            flush_titlecase_sequence(&mut current, &mut covered_spans, tokens);
819            if is_titlecase_word(token) {
820                current.push((base_offset + mat.start(), base_offset + mat.end(), token));
821            }
822        }
823        previous_end = Some(mat.end());
824    }
825
826    flush_titlecase_sequence(&mut current, &mut covered_spans, tokens);
827    covered_spans
828}
829
830fn flush_titlecase_sequence(
831    current: &mut Vec<(usize, usize, &str)>,
832    covered_spans: &mut Vec<(usize, usize)>,
833    tokens: &mut Vec<String>,
834) {
835    if current.len() >= 2 {
836        let qualified = current
837            .iter()
838            .map(|(_, _, token)| *token)
839            .collect::<Vec<_>>()
840            .join(".");
841        push_unique(tokens, &qualified);
842        covered_spans.extend(current.iter().map(|(start, end, _)| (*start, *end)));
843    }
844    current.clear();
845}
846
847fn span_is_covered(spans: &[(usize, usize)], start: usize, end: usize) -> bool {
848    spans
849        .iter()
850        .any(|(span_start, span_end)| start >= *span_start && end <= *span_end)
851}
852
853fn is_titlecase_word(token: &str) -> bool {
854    if token.contains(['.', '_', '$']) {
855        return false;
856    }
857    let mut chars = token.chars();
858    let Some(first) = chars.next() else {
859        return false;
860    };
861    if !first.is_ascii_uppercase() {
862        return false;
863    }
864
865    let mut has_letter_after_first = false;
866    let mut has_lowercase = false;
867    for ch in chars {
868        if !ch.is_ascii_alphanumeric() {
869            return false;
870        }
871        if ch.is_ascii_alphabetic() {
872            has_letter_after_first = true;
873        }
874        if ch.is_ascii_lowercase() {
875            has_lowercase = true;
876        }
877    }
878
879    has_letter_after_first && (has_lowercase || token.chars().all(|ch| !ch.is_ascii_lowercase()))
880}
881
882fn extract_path_tokens(query: &str) -> Vec<String> {
883    let mut tokens = Vec::new();
884    for segment in query
885        .split(['/', '\\'])
886        .filter(|segment| !segment.is_empty())
887    {
888        if segment.contains('.') {
889            if let Some(stem) = segment.rsplit_once('.').map(|(stem, _)| stem) {
890                push_unique(&mut tokens, stem);
891            }
892        }
893        push_unique(&mut tokens, segment);
894    }
895    tokens
896}
897
898fn extract_error_code_tokens(query: &str) -> Vec<String> {
899    let mut tokens = Vec::new();
900    for regex in [
901        &*HEX_CODE_RE,
902        &*ERROR_PREFIX_RE,
903        &*NUMERIC_ERROR_RE,
904        &*TYPESCRIPT_ERROR_RE,
905        &*HTTP_STATUS_RE,
906    ] {
907        for mat in regex.find_iter(query) {
908            push_unique(&mut tokens, mat.as_str());
909        }
910    }
911    if tokens.is_empty() && !query.trim().is_empty() {
912        push_unique(&mut tokens, query.trim());
913    }
914    tokens
915}
916
917fn extract_identifier_tokens(query: &str, require_code_shape: bool) -> Vec<String> {
918    let mut tokens = Vec::new();
919    for mat in IDENTIFIER_TOKEN_RE.find_iter(query) {
920        let token = mat.as_str();
921        if require_code_shape && !is_code_identifier_token(token) {
922            continue;
923        }
924        push_unique(&mut tokens, token);
925    }
926    tokens
927}
928
929fn is_code_identifier_token(token: &str) -> bool {
930    CAMEL_CASE_RE.is_match(token)
931        || SNAKE_CASE_RE.is_match(token)
932        || PASCAL_CASE_RE.is_match(token)
933        || ACRONYM_PASCAL_RE.is_match(token)
934        || DOT_PATH_RE.is_match(token)
935        || ERROR_PREFIX_RE.is_match(token)
936        || NUMERIC_ERROR_RE.is_match(token)
937        || TYPESCRIPT_ERROR_RE.is_match(token)
938}
939
940fn push_unique(tokens: &mut Vec<String>, token: &str) {
941    if !token.is_empty() && !tokens.iter().any(|existing| existing == token) {
942        tokens.push(token.to_string());
943    }
944}
945
946fn shape(kind: QueryKind) -> QueryShape {
947    QueryShape {
948        kind,
949        weights: weights_for(kind),
950    }
951}
952
953fn weights_for(kind: QueryKind) -> ShapeWeights {
954    match kind {
955        QueryKind::Identifier => ShapeWeights {
956            semantic: 0.2,
957            lexical: 0.8,
958            should_use_lexical: true,
959        },
960        QueryKind::Path | QueryKind::ErrorCode => ShapeWeights {
961            semantic: 0.1,
962            lexical: 0.9,
963            should_use_lexical: true,
964        },
965        QueryKind::Regex => ShapeWeights {
966            semantic: 0.0,
967            lexical: 1.0,
968            should_use_lexical: false,
969        },
970        QueryKind::NaturalLanguage => ShapeWeights {
971            semantic: 0.6,
972            lexical: 0.4,
973            should_use_lexical: false,
974        },
975        QueryKind::Mixed => ShapeWeights {
976            semantic: 0.4,
977            lexical: 0.6,
978            should_use_lexical: true,
979        },
980    }
981}
982
983#[cfg(test)]
984mod tests {
985    use super::*;
986
987    fn kind(query: &str) -> QueryKind {
988        classify(query).kind
989    }
990
991    #[test]
992    fn url_exemptions_allow_common_literal_url_punctuation() {
993        for query in [
994            "https://api.io/path",
995            "https://api.io/foo?q=test",
996            "https://api.io/foo+bar",
997            "https://api.io/foo@bar",
998            "https://api.io/foo#anchor",
999        ] {
1000            assert_eq!(pre_tier_exempt(query), Some("url"), "{query}");
1001            assert_ne!(kind(query), QueryKind::Regex, "{query}");
1002        }
1003    }
1004
1005    #[test]
1006    fn url_exemptions_reject_regex_sequences() {
1007        for query in [
1008            "https://.*",
1009            "https://api.io/.+",
1010            "file://[^ ]+",
1011            "file:///tmp/.+",
1012            r"https://api.io/users/\w+",
1013        ] {
1014            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1015        }
1016    }
1017
1018    #[test]
1019    fn path_and_filename_exemptions_allow_literal_punctuation() {
1020        for (query, expected) in [
1021            (r"C:\new\test", "windows_abs"),
1022            (r"src\bin\main.rs", "windows_rel"),
1023            (r"src\tab\main.ts", "windows_rel"),
1024            (r"packages\opencode-plugin\src", "windows_rel"),
1025            ("/usr/local/bin", "posix_abs"),
1026            ("/Users/John Doe/Documents", "posix_abs"),
1027            ("/home/user/.gitignore", "posix_abs"),
1028            ("v1/release/notes.md", "posix_rel"),
1029            ("/home/user/jeff's-folder", "posix_abs"),
1030            ("C++/parser/main.cpp", "posix_rel"),
1031            ("foo+bar/baz.ts", "posix_rel"),
1032            ("is_valid?.ts", "filename"),
1033            ("Cargo.lock", "filename"),
1034            ("tsconfig.json", "filename"),
1035        ] {
1036            assert_eq!(pre_tier_exempt(query), Some(expected), "{query}");
1037            assert_eq!(kind(query), QueryKind::Path, "{query}");
1038        }
1039        assert_eq!(pre_tier_exempt("foo?"), None);
1040    }
1041
1042    #[test]
1043    fn path_exemptions_reject_regex_sequences() {
1044        for query in [
1045            "src/.*",
1046            "src/.+",
1047            r"C:\bin\foo*.exe",
1048            r"C:\Users\\w+",
1049            r"src\w+\main.ts",
1050        ] {
1051            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1052        }
1053    }
1054
1055    #[test]
1056    fn tier_a_and_c_regex_signals_route_to_regex() {
1057        for query in [
1058            "^export",
1059            "foo$",
1060            "^main$",
1061            r"foo\.bar",
1062            r"\(method\)",
1063            r"\bTODO\b",
1064            ".*foo",
1065            "foo|bar",
1066            "(?:foo)",
1067            "(?P<n>foo)",
1068            "(?i)Todo",
1069            r"\p{Lu}",
1070            r"\xFF",
1071            r"\u{1F600}",
1072            "a{3}",
1073            // Bare escape sequences route to regex via Tier A. Caveat: `foo\n`
1074            // and similar single-backslash-escape after literal text are
1075            // genuinely ambiguous with Windows path segments (e.g., file `n`
1076            // in directory `foo`) and stay on the path/exemption path.
1077            r"\n",
1078            r"\t",
1079            r"\r",
1080            r"\tindent",
1081        ] {
1082            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1083        }
1084    }
1085
1086    #[test]
1087    fn character_classes_route_only_when_they_look_like_classes() {
1088        for query in ["[a-z]+", "[^abc]", r"[\w]+"] {
1089            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1090        }
1091        for query in [
1092            "arr[0]",
1093            "obj[key]",
1094            "config[\"key\"]",
1095            "#[derive]",
1096            "Vec<[u8; 32]>",
1097        ] {
1098            assert_ne!(kind(query), QueryKind::Regex, "{query}");
1099        }
1100    }
1101
1102    #[test]
1103    fn unsupported_regex_syntax_still_routes_to_regex_for_compile_error() {
1104        for query in [
1105            "(?=foo)",
1106            "(?!foo)",
1107            "(?<=foo)",
1108            "(?<!foo)",
1109            "(?P=name)",
1110            r"\1",
1111            "foo*+",
1112            "(?>foo)",
1113        ] {
1114            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1115        }
1116    }
1117
1118    #[test]
1119    fn explicit_code_tokens_for_natural_language_skip_bare_capitalized_words() {
1120        assert!(extract_explicit_code_tokens("Engine implementations").is_empty());
1121        assert_eq!(
1122            extract_explicit_code_tokens("find `Engine` and engine_factory"),
1123            vec!["Engine".to_string(), "engine_factory".to_string()]
1124        );
1125        assert_eq!(
1126            extract_explicit_code_tokens("Engine Index"),
1127            vec!["Engine.Index".to_string()]
1128        );
1129        assert_eq!(
1130            extract_explicit_code_tokens("use Engine.Index and AllocationService"),
1131            vec!["Engine.Index".to_string(), "AllocationService".to_string()]
1132        );
1133    }
1134
1135    #[test]
1136    fn two_word_lowercase_concepts_route_to_natural_language() {
1137        for query in ["retry logic", "auth flow", "cache invalidation"] {
1138            assert_eq!(kind(query), QueryKind::NaturalLanguage, "{query}");
1139        }
1140    }
1141
1142    #[test]
1143    fn identifierish_short_queries_stay_identifier() {
1144        for query in ["useState hook", "parseConfig", "parse_config option"] {
1145            assert_eq!(kind(query), QueryKind::Identifier, "{query}");
1146        }
1147    }
1148
1149    #[test]
1150    fn question_mark_code_shapes_do_not_route_to_regex() {
1151        for query in ["foo()?", "optional?.length", "user?.name", "arr[0]?"] {
1152            assert_ne!(kind(query), QueryKind::Regex, "{query}");
1153        }
1154    }
1155
1156    #[test]
1157    fn question_mark_regex_quantifiers_still_route_to_regex() {
1158        for query in ["colou?r", "https?"] {
1159            assert_eq!(kind(query), QueryKind::Regex, "{query}");
1160        }
1161    }
1162
1163    #[test]
1164    fn content_tokens_share_identifier_boundaries_and_drop_stopwords() {
1165        let tokens =
1166            extract_content_tokens("How is RequestAdapter wired into the built-in browser yet?");
1167        assert_eq!(
1168            tokens,
1169            ["requestadapter", "wired", "built", "browser", "yet"]
1170        );
1171        assert!(contains_all_content_tokens(
1172            "The browser keeps RequestAdapter; it will be WIRED once built.",
1173            &tokens[..4],
1174        ));
1175        assert!(!contains_all_content_tokens(
1176            "The browser is wired.",
1177            &tokens[..4],
1178        ));
1179    }
1180
1181    #[test]
1182    fn weak_regex_like_punctuation_does_not_route_to_regex() {
1183        for query in [
1184            "^id",
1185            "id$",
1186            "^",
1187            "$",
1188            "$HOME",
1189            r"\.",
1190            "array.length",
1191            "foo()",
1192            "map.get(key)",
1193            "a|b",
1194        ] {
1195            assert_ne!(kind(query), QueryKind::Regex, "{query}");
1196        }
1197    }
1198}
1199
1200#[cfg(test)]
1201mod hot_path_tests {
1202    use super::*;
1203
1204    pub(super) fn reference_window(text: &str, tokens: &[String]) -> Option<usize> {
1205        let lines = text.lines().collect::<Vec<_>>();
1206        (1..=3).find(|width| {
1207            lines.len() >= *width
1208                && lines
1209                    .windows(*width)
1210                    .any(|window| contains_all_content_tokens(&window.join("\n"), tokens))
1211        })
1212    }
1213
1214    #[test]
1215    fn minimum_window_matches_joined_window_reference() {
1216        let token_sets = [
1217            vec![],
1218            vec!["alpha".to_string()],
1219            vec!["alpha".to_string(), "beta".to_string()],
1220            vec![
1221                "alpha".to_string(),
1222                "alpha".to_string(),
1223                "gamma".to_string(),
1224            ],
1225            vec!["ALPHA".to_string()],
1226            vec!["alpha.beta".to_string(), "$value".to_string()],
1227        ];
1228        for text in [
1229            "",
1230            "ALPHA\nbeta",
1231            "alpha\n\n\nbeta",
1232            "alpha\nbeta\nalpha beta",
1233            "αalpha\nbeta",
1234            "alpha\r\nbeta\rgamma",
1235            "alpha.beta\n$value",
1236            "alpha\nbeta\ngamma\nalpha gamma",
1237        ] {
1238            for tokens in &token_sets {
1239                assert_eq!(
1240                    minimum_content_token_window(text, tokens),
1241                    reference_window(text, tokens),
1242                    "text={text:?}, tokens={tokens:?}"
1243                );
1244            }
1245        }
1246        let tokens = vec!["alpha".to_string(), "beta".to_string(), "gamma".to_string()];
1247        for seed in 0u64..100 {
1248            let mut state = seed + 1;
1249            let mut text = String::new();
1250            for _ in 0..80 {
1251                state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
1252                text.push_str(
1253                    [
1254                        "alpha\n",
1255                        "BETA\r\n",
1256                        "gamma\n",
1257                        "other\n",
1258                        "alpha beta gamma\n",
1259                        "\n",
1260                    ][(state >> 32) as usize % 6],
1261                );
1262            }
1263            assert_eq!(
1264                minimum_content_token_window(&text, &tokens),
1265                reference_window(&text, &tokens),
1266                "seed={seed}"
1267            );
1268        }
1269    }
1270
1271    #[test]
1272    fn minimum_window_does_not_allocate_per_overlapping_window() {
1273        let tokens = vec!["alpha".to_string(), "beta".to_string()];
1274        let text = format!("alpha\n{}beta\n", "unrelated\n".repeat(1000));
1275        minimum_content_token_window("warmup", &tokens);
1276        let (actual, allocations) =
1277            crate::test_allocations::count(|| minimum_content_token_window(&text, &tokens));
1278        assert_eq!(actual, None);
1279        assert!(
1280            allocations < 64,
1281            "unexpected per-window allocations: {allocations}"
1282        );
1283    }
1284}