lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
//! Snowball Russian stemmer over normalized (`ё -> е`) UTF-8.

use super::{next_region, strip_in};

/// Perfective gerund endings that must follow `а`/`я`.
const GERUND_1: &[&str] = &["вшись", "вши", "в"];
/// Perfective gerund endings with no preceding-letter condition.
const GERUND_2: &[&str] = &["ившись", "ывшись", "ивши", "ывши", "ив", "ыв"];
const REFLEXIVE: &[&str] = &["ся", "сь"];
const ADJECTIVE: &[&str] = &[
  "ими", "ыми", "его", "ого", "ему", "ому", "ее", "ие", "ые", "ое", "ей", "ий", "ый", "ой", "ем",
  "им", "ым", "ом", "их", "ых", "ую", "юю", "ая", "яя", "ою", "ею",
];
/// Participle endings that must follow `а`/`я`.
const PARTICIPLE_1: &[&str] = &["ем", "нн", "вш", "ющ", "щ"];
const PARTICIPLE_2: &[&str] = &["ивш", "ывш", "ующ"];
/// Verb endings that must follow `а`/`я`.
const VERB_1: &[&str] = &[
  "ешь", "нно", "йте", "ете", "ла", "на", "ли", "ем", "ло", "но", "ет", "ют", "ны", "ть", "й", "л",
  "н",
];
const VERB_2: &[&str] = &[
  "ейте", "уйте", "ила", "ыла", "ена", "ите", "или", "ыли", "ило", "ыло", "ено", "ует", "уют",
  "ены", "ить", "ыть", "ишь", "ую", "ей", "уй", "ил", "ыл", "им", "ым", "ен", "ят", "ит", "ыт",
  "ю",
];
const NOUN: &[&str] = &[
  "иями", "ями", "ами", "ией", "иям", "ием", "иях", "ев", "ов", "ие", "ье", "еи", "ии", "ей", "ой",
  "ий", "ям", "ем", "ам", "ом", "ах", "ях", "ию", "ью", "ия", "ья", "у", "ю", "е", "о", "а", "я",
  "ы", "и", "ь", "й",
];
const DERIVATIONAL: &[&str] = &["ость", "ост"];
const SUPERLATIVE: &[&str] = &["ейше", "ейш"];
const I: &[&str] = &["и"];
const SOFT_SIGN: &[&str] = &["ь"];
const NN: &str = "нн";
const N: char = 'н';

const fn is_vowel(ch: char) -> bool {
  matches!(ch, 'а' | 'е' | 'и' | 'о' | 'у' | 'ы' | 'э' | 'ю' | 'я')
}

/// Emits the Snowball stem of `surface`, using `buf` as the working copy.
pub(crate) fn emit(surface: &str, buf: &mut String, out: &mut impl FnMut(&str)) {
  // RV: region after the first vowel; every suffix below must lie inside it.
  let Some(rv) = surface
    .char_indices()
    .find(|&(_, ch)| is_vowel(ch))
    .map(|(i, ch)| i + ch.len_utf8())
  else {
    return;
  };
  let r2 = next_region(surface, next_region(surface, 0, is_vowel), is_vowel);
  buf.clear();
  buf.push_str(surface);

  // Step 1.
  if !strip_group(buf, rv, GERUND_1, GERUND_2) {
    strip_in(buf, rv, REFLEXIVE);
    if strip_in(buf, rv, ADJECTIVE) {
      strip_group(buf, rv, PARTICIPLE_1, PARTICIPLE_2);
    } else if !strip_group(buf, rv, VERB_1, VERB_2) {
      strip_in(buf, rv, NOUN);
    }
  }
  // Step 2.
  strip_in(buf, rv, I);
  // Step 3.
  strip_in(buf, r2, DERIVATIONAL);
  // Step 4.
  if !undouble_n(buf, rv) {
    if strip_in(buf, rv, SUPERLATIVE) {
      undouble_n(buf, rv);
    } else {
      strip_in(buf, rv, SOFT_SIGN);
    }
  }
  out(buf);
}

/// Strips a group-1 suffix preceded by `а`/`я` inside RV, else a group-2 suffix.
fn strip_group(buf: &mut String, rv: usize, g1: &[&str], g2: &[&str]) -> bool {
  let hit = g1.iter().find_map(|suf| {
    let end = buf.len().checked_sub(suf.len())?;
    (end >= rv && buf.ends_with(suf) && buf[rv..end].ends_with(['а', 'я'])).then_some(end)
  });
  match hit {
    Some(end) => {
      buf.truncate(end);
      true
    }
    None => strip_in(buf, rv, g2),
  }
}

/// Undoubles a final `нн` inside RV.
fn undouble_n(buf: &mut String, rv: usize) -> bool {
  let hit = buf.len() >= rv + NN.len() && buf.ends_with(NN);
  if hit {
    buf.truncate(buf.len() - N.len_utf8());
  }
  hit
}