lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
//! English Porter2 (Snowball) stemmer plus lemma heuristics.
//!
//! Search indexing emits both the exact lowercase surface token and algorithmic
//! roots/lemmas (for example `"Cuting"` -> `["cuting", "cut", "cute"]` and
//! `"Cutting"` -> `["cutting", "cut"]`), so exact and root queries match.

use core::str;

/// Suffix rewrite rule `(suffix, replacement)`.
type Rule = (&'static [u8], &'static [u8]);

/// Shortest word Porter2 stems.
const MIN_STEM_LEN: usize = 3;
/// Shortest stem kept by the lemma heuristics.
const MIN_LEMMA_LEN: usize = 3;
/// Shortest form emitted after possessive or apostrophe removal.
const MIN_BASE_LEN: usize = 2;

/// Prefixes whose R1 starts right after them.
const R1_PREFIX: &[&[u8]] = &[b"gener", b"commun", b"arsen"];
/// Step 1b suffixes, longest first among overlapping ones (`eedly` before `edly`).
const STEP1B: &[&[u8]] = &[b"eedly", b"ingly", b"edly", b"eed", b"ing", b"ed"];
const STEP2: &[Rule] = &[
  (b"ization", b"ize"),
  (b"ational", b"ate"),
  (b"fulness", b"ful"),
  (b"ousness", b"ous"),
  (b"iveness", b"ive"),
  (b"tional", b"tion"),
  (b"biliti", b"ble"),
  (b"lessli", b"less"),
  (b"entli", b"ent"),
  (b"ation", b"ate"),
  (b"alism", b"al"),
  (b"aliti", b"al"),
  (b"ousli", b"ous"),
  (b"iviti", b"ive"),
  (b"fulli", b"ful"),
  (b"enci", b"ence"),
  (b"anci", b"ance"),
  (b"abli", b"able"),
  (b"izer", b"ize"),
  (b"ator", b"ate"),
  (b"alli", b"al"),
  (b"bli", b"ble"),
  (b"ogi", b"og"),
  (b"li", b""),
];
const STEP3: &[Rule] = &[
  (b"ational", b"ate"),
  (b"tional", b"tion"),
  (b"alize", b"al"),
  (b"icate", b"ic"),
  (b"iciti", b"ic"),
  (b"ative", b""),
  (b"ical", b"ic"),
  (b"ness", b""),
  (b"ful", b""),
];
const STEP4: &[Rule] = &[
  (b"ement", b""),
  (b"ance", b""),
  (b"ence", b""),
  (b"able", b""),
  (b"ible", b""),
  (b"ment", b""),
  (b"ant", b""),
  (b"ent", b""),
  (b"ism", b""),
  (b"ate", b""),
  (b"iti", b""),
  (b"ous", b""),
  (b"ive", b""),
  (b"ize", b""),
  (b"ion", b""),
  (b"al", b""),
  (b"er", b""),
  (b"ic", b""),
];

/// Snowball exceptional forms, dispatched before stemming.
fn exception(w: &[u8]) -> Option<&'static [u8]> {
  match w {
    b"skis" => Some(b"ski"),
    b"skies" => Some(b"sky"),
    b"dying" => Some(b"die"),
    b"lying" => Some(b"lie"),
    b"tying" => Some(b"tie"),
    b"idly" => Some(b"idl"),
    b"gently" => Some(b"gentl"),
    b"ugly" => Some(b"ugli"),
    b"early" => Some(b"earli"),
    b"only" => Some(b"onli"),
    b"singly" => Some(b"singl"),
    b"sky" => Some(b"sky"),
    b"news" => Some(b"news"),
    b"howe" => Some(b"howe"),
    b"atlas" => Some(b"atlas"),
    b"cosmos" => Some(b"cosmos"),
    b"bias" => Some(b"bias"),
    b"andes" => Some(b"andes"),
    _ => None,
  }
}

/// Words left untouched after Step 1a.
fn is_invariant_1a(w: &[u8]) -> bool {
  matches!(
    w,
    b"inning"
      | b"outing"
      | b"canning"
      | b"herring"
      | b"earring"
      | b"proceed"
      | b"exceed"
      | b"succeed"
  )
}

/// ASCII vowel; after Y-marking, every remaining lowercase `y` is a vowel.
#[inline]
const fn is_vowel(b: u8) -> bool {
  matches!(b, b'a' | b'e' | b'i' | b'o' | b'u' | b'y')
}

fn has_vowel(w: &[u8]) -> bool {
  w.iter().any(|&b| is_vowel(b))
}

const fn is_double(b: u8) -> bool {
  matches!(
    b,
    b'b' | b'd' | b'f' | b'g' | b'm' | b'n' | b'p' | b'r' | b't'
  )
}

#[inline]
const fn ends_double(w: &[u8]) -> bool {
  matches!(w, [.., a, b] if *a == *b && is_double(*b))
}

const fn is_li_end(b: u8) -> bool {
  matches!(
    b,
    b'c' | b'd' | b'e' | b'g' | b'h' | b'k' | b'm' | b'n' | b'r' | b't'
  )
}

/// Snowball short syllable at the end of `w`.
fn ends_short(w: &[u8]) -> bool {
  match *w {
    [a, b] => is_vowel(a) && !is_vowel(b),
    [.., a, b, c] => {
      !is_vowel(a) && is_vowel(b) && !is_vowel(c) && !matches!(c, b'w' | b'x' | b'Y')
    }
    _ => false,
  }
}

/// Region start after the first vowel/non-vowel pair at or after `start`.
fn region(w: &[u8], start: usize) -> usize {
  w.get(start..)
    .and_then(|t| t.windows(2).position(|p| is_vowel(p[0]) && !is_vowel(p[1])))
    .map_or(w.len(), |i| start + i + 2)
}

/// Replaces the longest suffix from `list` if it starts at or after `min` and `ok(suffix, stem)` holds.
fn replace(w: &mut Vec<u8>, list: &[Rule], min: usize, ok: impl Fn(&[u8], &[u8]) -> bool) {
  if let Some(&(suf, rep)) = list.iter().find(|(suf, _)| w.ends_with(suf)) {
    let at = w.len() - suf.len();
    if at >= min && ok(suf, &w[..at]) {
      w.truncate(at);
      w.extend_from_slice(rep);
    }
  }
}

/// Runs Snowball English (Porter2) on lowercase ASCII `word`, using `w` as the buffer.
fn porter2<'a>(word: &str, w: &'a mut Vec<u8>) -> &'a [u8] {
  w.clear();
  w.extend_from_slice(word.as_bytes());
  if w.len() < MIN_STEM_LEN {
    return w;
  }
  if let Some(rep) = exception(w) {
    w.clear();
    w.extend_from_slice(rep);
    return w;
  }
  // Mark consonant `y` (initial or after a vowel) as `Y`.
  let mut prev_vowel = true;
  for b in w.iter_mut() {
    if *b == b'y' && prev_vowel {
      *b = b'Y';
    }
    prev_vowel = is_vowel(*b);
  }
  run_step(w);
  w.iter_mut().filter(|b| **b == b'Y').for_each(|b| *b = b'y');
  w
}

/// Porter2 steps 0-5 on a Y-marked word.
fn run_step(w: &mut Vec<u8>) {
  let r1 = R1_PREFIX
    .iter()
    .find(|p| w.starts_with(p))
    .map_or_else(|| region(w, 0), |p| p.len());
  let r2 = region(w, r1);

  // Step 0: strip `'s'`, `'s`, `'`.
  if let Some(suf) = [b"'s'".as_slice(), b"'s", b"'"]
    .into_iter()
    .find(|s| w.ends_with(s))
  {
    w.truncate(w.len() - suf.len());
  }

  // Step 1a.
  if w.ends_with(b"sses") {
    w.truncate(w.len() - 2);
  } else if w.ends_with(b"ied") || w.ends_with(b"ies") {
    // `ies` -> `i` after 2+ letters, else `ie`.
    w.truncate(w.len() - if w.len() > 4 { 2 } else { 1 });
  } else if !(w.ends_with(b"us") || w.ends_with(b"ss"))
    && w.ends_with(b"s")
    && has_vowel(&w[..w.len().saturating_sub(2)])
  {
    w.pop();
  }
  if is_invariant_1a(w) {
    return;
  }

  // Step 1b.
  if let Some(&suf) = STEP1B.iter().find(|s| w.ends_with(s)) {
    let at = w.len() - suf.len();
    if suf.starts_with(b"eed") {
      if at >= r1 {
        w.truncate(at + 2);
      }
    } else if has_vowel(&w[..at]) {
      w.truncate(at);
      if w.ends_with(b"at") || w.ends_with(b"bl") || w.ends_with(b"iz") {
        w.push(b'e');
      } else if ends_double(w) {
        w.pop();
      } else if w.len() <= r1 && ends_short(w) {
        w.push(b'e');
      }
    }
  }

  // Step 1c: final y/Y -> i after a non-vowel that is not the first letter.
  if let [_, .., p, last @ (b'y' | b'Y')] = w.as_mut_slice()
    && !is_vowel(*p)
  {
    *last = b'i';
  }

  // Step 2.
  replace(w, STEP2, r1, |suf, stem| match suf {
    b"ogi" => stem.last() == Some(&b'l'),
    b"li" => stem.last().is_some_and(|&b| is_li_end(b)),
    _ => true,
  });
  // Step 3.
  replace(w, STEP3, r1, |suf, stem| {
    suf != b"ative" || stem.len() >= r2
  });
  // Step 4.
  replace(w, STEP4, r2, |suf, stem| {
    suf != b"ion" || matches!(stem.last(), Some(b's' | b't'))
  });

  // Step 5.
  if let Some(stem) = w.strip_suffix(b"e") {
    if w.len() > r2 || (w.len() > r1 && !ends_short(stem)) {
      w.pop();
    }
  } else if w.ends_with(b"ll") && w.len() > r2 {
    w.pop();
  }
}

/// Emits algorithmic lemmas and the Porter2 stem of a lowercase ASCII token.
///
/// For `"cuting"`, Porter2 yields `"cute"` while stripping `-ing` yields `"cut"`;
/// emitting both lets `"Cuting"` match `"cut"`, `"cute"`, or `"cuting"`. For
/// `"studies"`, `-ies -> -y` emits `"study"` alongside Porter2 `"studi"`.
pub(super) fn emit(token: &str, aux: &mut String, byte: &mut Vec<u8>, out: &mut impl FnMut(&str)) {
  if !token.is_ascii() {
    return;
  }
  let core = token.trim_start_matches('\'');
  if core.len() != token.len() && core.len() >= MIN_BASE_LEN {
    out(core);
  }
  let token = core;
  if token.len() < MIN_STEM_LEN {
    return;
  }
  let raw = token.as_bytes();
  if let Some(rep) = exception(raw) {
    if let Ok(stem) = str::from_utf8(rep) {
      out(stem);
    }
    return;
  }
  if is_invariant_1a(raw) {
    return;
  }

  // Possessives and clitics.
  if let Some(base) = token
    .strip_suffix("'s")
    .or_else(|| token.strip_suffix('\''))
  {
    if base.len() >= MIN_BASE_LEN {
      out(base);
    }
  } else if token.contains('\'') {
    aux.clear();
    for part in token.split('\'') {
      aux.push_str(part);
    }
    if aux.len() >= MIN_BASE_LEN {
      out(aux);
    }
  }

  // Bare `-ing`/`-ed` removal: "cuting" -> "cut", "cutting" -> "cut";
  // `-eed` is left to Porter2 so "speed" never yields "spe".
  if let Some(stem) = token
    .strip_suffix("ing")
    .or_else(|| token.strip_suffix("ed").filter(|s| !s.ends_with('e')))
    && stem.len() >= MIN_LEMMA_LEN
    && has_vowel(stem.as_bytes())
  {
    if ends_double(stem.as_bytes()) {
      out(&stem[..stem.len() - 1]);
    } else {
      out(stem);
    }
  }

  // `-ies`/`-ied` -> `-y`: "studies" -> "study", "tried" -> "try".
  if let Some(stem) = token
    .strip_suffix("ies")
    .or_else(|| token.strip_suffix("ied"))
    && stem.len() >= MIN_BASE_LEN
  {
    aux.clear();
    aux.push_str(stem);
    aux.push('y');
    out(aux);
  }

  // Plural `-es`: "boxes" -> "box", "classes" -> "class", "databases" -> "database".
  if let Some(stem) = token.strip_suffix("es")
    && stem.len() >= MIN_LEMMA_LEN
    && let [.., p, last] = *stem.as_bytes()
  {
    if matches!(
      (p, last),
      (_, b'x' | b'z') | (b's' | b'u', b's') | (b'c' | b's', b'h')
    ) {
      out(stem);
    } else if !is_vowel(last) {
      out(&token[..token.len() - 1]);
    }
  }

  if let Ok(stem) = str::from_utf8(porter2(token, byte)) {
    out(stem);
  }
}