use std::collections::BTreeSet;
const STOPWORDS: &[&str] = &[
"a", "an", "and", "are", "as", "at", "be", "been", "being", "by", "can", "could", "do", "does",
"for", "from", "has", "have", "in", "into", "is", "it", "its", "may", "might", "of", "on",
"or", "should", "such", "that", "the", "their", "them", "there", "these", "they", "this",
"those", "to", "via", "was", "were", "will", "with", "would", "you", "your",
];
pub(crate) fn tokenize_raw(text: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let chars: Vec<char> = text.chars().collect();
for (i, &ch) in chars.iter().enumerate() {
if !ch.is_alphanumeric() {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
continue;
}
if ch.is_uppercase() && !current.is_empty() {
let prev = chars[i - 1];
let next_is_lower = chars.get(i + 1).is_some_and(|c| c.is_lowercase());
if prev.is_lowercase()
|| prev.is_ascii_digit()
|| (prev.is_uppercase() && next_is_lower)
{
tokens.push(std::mem::take(&mut current));
}
}
for lower in ch.to_lowercase() {
current.push(lower);
}
}
if !current.is_empty() {
tokens.push(current);
}
tokens
}
pub(crate) fn stem_token(token: &str) -> String {
if token.len() <= 3 {
return token.to_string();
}
if let Some(base) = token.strip_suffix("ies") {
if base.len() >= 2 {
return format!("{base}y");
}
}
if let Some(base) = token.strip_suffix("ing") {
if base.len() >= 3 {
return base.to_string();
}
}
if let Some(base) = token.strip_suffix("ed") {
if base.len() >= 3 {
return base.to_string();
}
}
if let Some(base) = token.strip_suffix("es") {
if base.len() >= 3
&& (base.ends_with("ch")
|| base.ends_with("sh")
|| base.ends_with('s')
|| base.ends_with('x')
|| base.ends_with('z'))
{
return base.to_string();
}
}
if let Some(base) = token.strip_suffix('s') {
if base.len() >= 3 && !base.ends_with('s') && !base.ends_with('u') {
return base.to_string();
}
}
token.to_string()
}
pub(crate) fn canonicalize_term(term: &str) -> String {
let stemmed = stem_token(term);
match stemmed.as_str() {
"find" | "search" | "lookup" | "query" | "locate" | "grep" | "discover" => {
"search".to_string()
}
"get" | "fetch" | "retriev" | "retrieve" | "read" | "load" | "obtain" | "inspect" => {
"get".to_string()
}
"list" | "ls" | "enumerat" | "enumerate" | "browse" => "list".to_string(),
"delet" | "delete" | "remov" | "remove" | "drop" | "eras" | "erase" | "destroy"
| "purg" | "purge" | "rm" => "delete".to_string(),
"creat" | "create" | "add" | "new" | "mak" | "make" | "insert" | "generat" | "generate" => {
"create".to_string()
}
"updat" | "update" | "edit" | "modify" | "modifi" | "patch" | "chang" | "change"
| "set" | "mutat" | "mutate" => "update".to_string(),
"doc" | "document" | "documentation" => "doc".to_string(),
"repo" | "repository" => "repo".to_string(),
"msg" | "message" => "message".to_string(),
"dir" | "directory" | "folder" => "dir".to_string(),
"cfg" | "config" | "configuration" => "config".to_string(),
"usr" | "user" => "user".to_string(),
"auth" | "authentication" | "authorization" => "auth".to_string(),
"multipl" | "multiple" | "several" | "batch" | "bulk" | "many" => "multiple".to_string(),
"snippet" | "excerpt" => "snippet".to_string(),
_ => stemmed,
}
}
pub(crate) fn tokenize_semantic(text: &str) -> Vec<String> {
tokenize_raw(text)
.into_iter()
.filter(|t| t.len() >= 2 && !STOPWORDS.contains(&t.as_str()))
.map(|t| canonicalize_term(&t))
.collect()
}
pub(crate) fn tokenize_stemmed(text: &str) -> Vec<String> {
tokenize_raw(text)
.into_iter()
.filter(|t| t.len() >= 2 && !STOPWORDS.contains(&t.as_str()))
.map(|t| stem_token(&t))
.collect()
}
pub(crate) fn estimate_tokens(text: &str) -> usize {
let trimmed = text.trim();
if trimmed.is_empty() {
return 0;
}
let char_est = (trimmed.chars().count() as f32 / 4.0).ceil() as usize;
let word_est = (trimmed.split_whitespace().count() as f32 * 1.3).ceil() as usize;
char_est.max(word_est)
}
pub(crate) fn jaccard_sets(a: &BTreeSet<String>, b: &BTreeSet<String>) -> f32 {
if a.is_empty() && b.is_empty() {
return 0.0;
}
let inter = a.intersection(b).count();
let union = a.union(b).count();
if union == 0 {
0.0
} else {
inter as f32 / union as f32
}
}
pub(crate) fn char_trigrams(text: &str) -> BTreeSet<String> {
let normalized: String = text
.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(char::to_lowercase)
.collect();
let chars: Vec<char> = normalized.chars().collect();
let mut grams = BTreeSet::new();
if chars.len() < 3 {
if !normalized.is_empty() {
grams.insert(normalized);
}
return grams;
}
for window in chars.windows(3) {
grams.insert(window.iter().collect());
}
grams
}
pub(crate) fn contains_non_negated_term(haystack_lower: &str, term: &str) -> bool {
let words: Vec<&str> = haystack_lower
.split(|c: char| !c.is_alphanumeric() && c != '-' && c != '\'')
.filter(|w| !w.is_empty())
.collect();
const NEGATIONS: &[&str] = &[
"not",
"no",
"never",
"without",
"cannot",
"can't",
"won't",
"doesn't",
"don't",
"non",
"read-only",
"readonly",
"non-destructive",
];
for (idx, &word) in words.iter().enumerate() {
let matched = word == term
|| (term.len() >= 4 && word.starts_with(term))
|| stem_token(word) == stem_token(term);
if !matched {
continue;
}
let window_start = idx.saturating_sub(3);
let negated = words[window_start..idx]
.iter()
.any(|w| NEGATIONS.contains(w));
if !negated {
return true;
}
}
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ActionPolarity {
Read,
Write,
Neutral,
}
pub(crate) fn infer_polarity(name: &str, read_only_hint: Option<bool>) -> ActionPolarity {
if let Some(ro) = read_only_hint {
return if ro {
ActionPolarity::Read
} else {
ActionPolarity::Write
};
}
let tokens = tokenize_raw(name);
for tok in tokens.iter().take(2) {
match tok.as_str() {
"get" | "list" | "read" | "fetch" | "find" | "search" | "query" | "describe"
| "inspect" | "show" | "view" | "lookup" | "check" | "analyze" | "audit"
| "evaluate" | "count" | "status" | "diff" | "log" => return ActionPolarity::Read,
"create" | "delete" | "remove" | "drop" | "destroy" | "update" | "edit" | "modify"
| "patch" | "write" | "set" | "put" | "post" | "add" | "insert" | "upsert" | "send"
| "publish" | "purge" | "reset" | "revoke" | "archive" | "reply" | "append"
| "move" | "copy" | "merge" | "commit" | "checkout" | "click" | "fill" | "navigate" => {
return ActionPolarity::Write
}
_ => {}
}
}
ActionPolarity::Neutral
}
pub(crate) fn leading_name_verb(name: &str, verbs: &[&str]) -> Option<String> {
let tokens = tokenize_raw(name);
tokens
.into_iter()
.take(2)
.find(|t| verbs.contains(&t.as_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn splits_camel_and_snake_case() {
assert_eq!(
tokenize_raw("getUserHTTPResponse_v2"),
vec!["get", "user", "http", "response", "v2"]
);
}
#[test]
fn canonicalizes_verb_synonyms() {
assert_eq!(canonicalize_term("find"), canonicalize_term("search"));
assert_eq!(canonicalize_term("documents"), canonicalize_term("docs"));
assert_eq!(canonicalize_term("remove"), canonicalize_term("delete"));
}
#[test]
fn respects_negation_window() {
assert!(!contains_non_negated_term(
"read-only lookup; does not delete or modify files",
"delete"
));
assert!(contains_non_negated_term(
"permanently deletes the selected repository",
"delete"
));
}
}