lexf 0.1.0

Zero-unsafe multilingual morphological expander and query normalizer for search indexing
Documentation
//! Zero-unsafe canonical text folding (case, width, digits, diacritics, CJK).

use crate::{
  script::{Kind, Script, classify_mask},
  table_gen::{FOLD_CHAR, TC_TO_SC},
};

/// Result of surface normalization so callers skip redundant classification and ASCII checks.
#[derive(Clone, Copy, Debug)]
pub(crate) struct SurfaceMeta {
  pub(crate) kind: Kind,
  pub(crate) ascii: bool,
}

/// Offset from fullwidth ASCII (`!`..`~`) down to ASCII.
const FULLWIDTH_SHIFT: u32 = 0xFEE0;
/// Offset from Katakana (`ァ`..`ヶ`) down to Hiragana (`ぁ`..`ゖ`).
const KANA_SHIFT: u32 = 0x60;
/// Halfwidth Katakana voiced (dakuten) and semi-voiced (handakuten) marks.
const HALF_VOICED: char = '\u{FF9E}';
const HALF_SEMI_VOICED: char = '\u{FF9F}';
/// Combining Kana voiced and semi-voiced marks (NFD).
const COMB_VOICED: char = '\u{3099}';
const COMB_SEMI_VOICED: char = '\u{309A}';
/// Combining diaeresis (NFD umlaut).
const COMB_DIAERESIS: char = '\u{0308}';
/// First halfwidth Katakana letter mapped by [`HALF_KANA`].
const HALF_KANA_START: u32 = 0xFF66;
/// Fullwidth forms of halfwidth Katakana `U+FF66..=U+FF9D`.
const HALF_KANA: [char; 56] = [
  'ヲ', 'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ャ', 'ュ', 'ョ', 'ッ', 'ー', 'ア', 'イ', 'ウ', 'エ', 'オ',
  'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ',
  'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ',
  'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ン',
];
/// Zero code points of all 75 non-ASCII, non-fullwidth Unicode `Nd` decimal digit blocks (sorted).
const DIGIT_ZERO: [u32; 75] = [
  0x0660, 0x06F0, 0x07C0, 0x0966, 0x09E6, 0x0A66, 0x0AE6, 0x0B66, 0x0BE6, 0x0C66, 0x0CE6, 0x0D66,
  0x0DE6, 0x0E50, 0x0ED0, 0x0F20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90,
  0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0x104A0,
  0x10D30, 0x10D40, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0, 0x11650,
  0x116C0, 0x116D0, 0x116DA, 0x11730, 0x118E0, 0x11950, 0x11BF0, 0x11C50, 0x11D50, 0x11DA0,
  0x11DE0, 0x11F50, 0x16130, 0x16A60, 0x16AC0, 0x16B50, 0x16D70, 0x1CCF0, 0x1D7CE, 0x1D7D8,
  0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, 0x1E5F1, 0x1E950, 0x1FBF0,
];

/// Writes the canonical surface form: lowercase, ASCII width and digits, unified
/// apostrophes/dashes/spaces, fullwidth Katakana, composed Kana/umlaut NFD marks,
/// and stripped combining marks.
///
/// Accented letters are kept; [`fold_diacritic_into`] removes them.
pub(crate) fn normalize_surface_into(input: &str, out: &mut String) -> SurfaceMeta {
  out.clear();
  if input.is_ascii() {
    out.push_str(input);
    out.make_ascii_lowercase();
    let mut mask = 0_u16;
    for &b in out.as_bytes() {
      let s = if b.is_ascii_digit() {
        Script::Digit
      } else if b.is_ascii_lowercase() {
        Script::Latin
      } else {
        Script::Other
      };
      mask |= s.bit();
    }
    return SurfaceMeta {
      kind: classify_mask(mask),
      ascii: true,
    };
  }

  let mut mask = 0_u16;

  for ch in input.chars() {
    if ch.is_ascii() {
      push_norm(out, &mut mask, ch.to_ascii_lowercase());
      continue;
    }
    match ch {
      // Always ASCII, so the `u8` cast is lossless.
      '!'..='~' => {
        push_norm(
          out,
          &mut mask,
          char::from((ch as u32 - FULLWIDTH_SHIFT) as u8).to_ascii_lowercase(),
        );
      }
      '\u{3000}' | '\u{00A0}' => push_norm(out, &mut mask, ' '),
      '\u{2018}' | '\u{2019}' | '\u{02BC}' => push_norm(out, &mut mask, '\''),
      '\u{2010}'..='\u{2013}' | '\u{2212}' => push_norm(out, &mut mask, '-'),
      HALF_VOICED | HALF_SEMI_VOICED | COMB_VOICED | COMB_SEMI_VOICED => {
        if let Some(prev) = out.pop() {
          let voiced = matches!(ch, HALF_VOICED | COMB_VOICED);
          let composed = compose_kana_mark(prev, voiced);
          // Re-adding `composed`'s bit is idempotent since base already set the script bit.
          push_norm(out, &mut mask, composed);
        }
      }
      COMB_DIAERESIS => {
        if let Some(umlaut) = out.chars().next_back().and_then(|c| match c {
          'a' => Some('ä'),
          'o' => Some('ö'),
          'u' => Some('ü'),
          _ => None,
        }) {
          out.pop();
          push_norm(out, &mut mask, umlaut);
        }
      }
      _ => {
        if let Some(d) = decimal_digit(ch) {
          push_norm(out, &mut mask, d);
        } else if let Some(full) = halfwidth_kana(ch) {
          push_norm(out, &mut mask, full);
        } else {
          // Marks lowercase to themselves, so filtering after lowering also drops
          // the combining dot produced by `İ`.
          for low in ch.to_lowercase().filter(|&c| !is_ignorable_mark(c)) {
            let mapped = match low {
              'ς' => 'σ',
              'ё' => 'е',
              c => c,
            };
            push_norm(out, &mut mask, mapped);
          }
        }
      }
    }
  }

  let trimmed_len = out.trim_end().len();
  out.truncate(trimmed_len);

  SurfaceMeta {
    kind: classify_mask(mask),
    ascii: out.is_ascii(),
  }
}

#[inline]
fn push_norm(out: &mut String, mask: &mut u16, ch: char) {
  if out.is_empty() && ch.is_whitespace() {
    return;
  }
  *mask |= Script::of(ch).bit();
  out.push(ch);
}

/// Converts Traditional Hanzi to Simplified via the OpenCC table; returns whether any char changed.
pub(crate) fn trad_to_simp_into(input: &str, out: &mut String) -> bool {
  map_char_into(input, out, |ch| lookup(TC_TO_SC, ch).unwrap_or(ch))
}

/// Converts Katakana (`ァ..ヶ`) to Hiragana (`ぁ..ゖ`); returns whether any char changed.
pub(crate) fn katakana_to_hiragana_into(input: &str, out: &mut String) -> bool {
  map_char_into(input, out, |ch| match ch {
    'ァ'..='ヶ' => char::from_u32(ch as u32 - KANA_SHIFT).unwrap_or(ch),
    _ => ch,
  })
}

/// Unifies Arabic alef/hamza, taa marbuta, and alef maqsura variants; returns whether any char changed.
pub(crate) fn fold_ar_into(input: &str, out: &mut String) -> bool {
  map_char_into(input, out, |ch| match ch {
    'أ' | 'إ' | 'آ' => 'ا',
    'ة' => 'ه',
    'ى' => 'ي',
    _ => ch,
  })
}

/// Multi-char lowercase ligature foldings handled outside the single-char table.
#[inline]
const fn fold_ligature(ch: char) -> Option<&'static str> {
  match ch {
    'ß' => Some("ss"),
    'æ' | 'ǽ' => Some("ae"),
    'œ' => Some("oe"),
    'þ' => Some("th"),
    'ij' => Some("ij"),
    'dž' | 'dz' => Some("dz"),
    'lj' => Some("lj"),
    'nj' => Some("nj"),
    _ => None,
  }
}

/// Folds Latin/Cyrillic/Greek diacritics and ligatures (`ß->ss`, `é->e`, `æ->ae`)
/// on an already-normalized lowercase `surface`; returns whether any char changed.
pub(crate) fn fold_diacritic_into(surface: &str, out: &mut String) -> bool {
  out.clear();
  let mut changed = false;
  for ch in surface.chars() {
    if ch.is_ascii() {
      out.push(ch);
    } else if let Some(lig) = fold_ligature(ch) {
      out.push_str(lig);
      changed = true;
    } else if let Some(c) = lookup(FOLD_CHAR, ch) {
      out.push(c);
      changed = true;
    } else {
      out.push(ch);
    }
  }
  changed
}

/// Writes German digraph foldings (`ä->ae`, `ö->oe`, `ü->ue`, `ß->ss`), folding any
/// other non-ASCII diacritics too so mixed forms stay clean ASCII.
///
/// Returns `true` if `surface` contains an umlaut, i.e. the output is a new form.
pub(crate) fn fold_umlaut_into(surface: &str, out: &mut String) -> bool {
  out.clear();
  let mut hit = false;
  for ch in surface.chars() {
    match ch {
      'ä' => {
        out.push_str("ae");
        hit = true;
      }
      'ö' => {
        out.push_str("oe");
        hit = true;
      }
      'ü' => {
        out.push_str("ue");
        hit = true;
      }
      _ if ch.is_ascii() => out.push(ch),
      _ => {
        if let Some(lig) = fold_ligature(ch) {
          out.push_str(lig);
        } else {
          out.push(lookup(FOLD_CHAR, ch).unwrap_or(ch));
        }
      }
    }
  }
  hit
}

/// Maps each character of `input` through `map` into `out`, returning whether any char changed.
fn map_char_into(input: &str, out: &mut String, mut map: impl FnMut(char) -> char) -> bool {
  out.clear();
  let mut changed = false;
  for ch in input.chars() {
    let mapped = map(ch);
    changed |= mapped != ch;
    out.push(mapped);
  }
  changed
}

/// Returns true if `ch` is a combining diacritical mark, Arabic harakat/tatweel, or soft hyphen.
#[inline]
fn is_ignorable_mark(ch: char) -> bool {
  matches!(
    ch as u32,
    0x00AD
      | 0x0300..=0x036F
      | 0x0610..=0x061A
      | 0x0640
      | 0x064B..=0x065F
      | 0x0670
      | 0x06D6..=0x06DC
      | 0x06DF..=0x06E4
      | 0x06E7..=0x06E8
      | 0x06EA..=0x06ED
      | 0x1AB0..=0x1AFF
      | 0x1DC0..=0x1DFF
      | 0xFE20..=0xFE2F
  )
}

/// Binary-searches a `char`-keyed table sorted by key.
#[inline]
fn lookup<V: Copy>(table: &[(char, V)], ch: char) -> Option<V> {
  table
    .binary_search_by_key(&ch, |&(k, _)| k)
    .ok()
    .map(|i| table[i].1)
}

/// Maps a non-ASCII Unicode decimal digit to its ASCII digit.
fn decimal_digit(ch: char) -> Option<char> {
  let cp = ch as u32;
  if cp < DIGIT_ZERO[0] || !ch.is_numeric() {
    return None;
  }
  let zero = DIGIT_ZERO[DIGIT_ZERO.partition_point(|&z| z <= cp).checked_sub(1)?];
  let d = cp - zero;
  // `d < 10`, so the `u8` cast is lossless.
  (d < 10).then(|| char::from(b'0' + d as u8))
}

/// Maps halfwidth Katakana (`U+FF66..=U+FF9D`) to fullwidth.
fn halfwidth_kana(ch: char) -> Option<char> {
  (ch as u32)
    .checked_sub(HALF_KANA_START)
    .and_then(|i| HALF_KANA.get(i as usize).copied())
}

/// Composes a fullwidth Katakana or Hiragana base with a (semi-)voiced mark; unknown pairs drop the mark.
fn compose_kana_mark(base: char, voiced: bool) -> char {
  if voiced {
    let shift = match base {
      'ウ' => return 'ヴ',
      'う' => return 'ゔ',
      'ワ'..='ヲ' => 8,
      'カ' | 'キ' | 'ク' | 'ケ' | 'コ' | 'サ' | 'シ' | 'ス' | 'セ' | 'ソ' | 'タ' | 'チ' | 'ツ'
      | 'テ' | 'ト' | 'ハ' | 'ヒ' | 'フ' | 'ヘ' | 'ホ' | 'か' | 'き' | 'く' | 'け' | 'こ'
      | 'さ' | 'し' | 'す' | 'せ' | 'そ' | 'た' | 'ち' | 'つ' | 'て' | 'と' | 'は' | 'ひ'
      | 'ふ' | 'へ' | 'ほ' => 1,
      _ => return base,
    };
    char::from_u32(base as u32 + shift).unwrap_or(base)
  } else {
    match base {
      'ハ' | 'ヒ' | 'フ' | 'ヘ' | 'ホ' | 'は' | 'ひ' | 'ふ' | 'へ' | 'ほ' => {
        char::from_u32(base as u32 + 2).unwrap_or(base)
      }
      _ => base,
    }
  }
}