summaryrefslogtreecommitdiffstats
path: root/vendor/elasticlunr-rs/src/lang/ar.rs
blob: d0a640edf2ba7dc750d7cb4835e382a81c58d20c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use super::Language;
use crate::pipeline::{Pipeline, PipelineFn};
use regex::Regex;

/// Arabic Language
/// 
/// Designed to be compatibile with the included Javascript implementation. See `js/lunr.ar.js`.
pub struct Arabic {}

impl Arabic {
    pub fn new() -> Self {
        Self {}
    }
}

impl Language for Arabic {
    fn name(&self) -> String {
        "Arabic".into()
    }
    fn code(&self) -> String {
        "ar".into()
    }

    fn tokenize(&self, text: &str) -> Vec<String> {
        super::tokenize_whitespace(text)
    }

    fn make_pipeline(&self) -> Pipeline {
        Pipeline {
            queue: vec![Box::new(Stemmer::new())],
        }
    }
}

struct Stemmer {
    diacritics: Regex,
    alefs: Regex,
}

impl Stemmer {
    pub fn new() -> Self {
        let diacritics = Regex::new("[\u{0640}\u{064b}-\u{065b}]").unwrap();
        let alefs = Regex::new("[\u{0622}\u{0623}\u{0625}\u{0671}\u{0649}]").unwrap();
        Self { diacritics, alefs }
    }
}

impl PipelineFn for Stemmer {
    fn name(&self) -> String {
        "stemmer-ar".into()
    }

    fn filter(&self, token: String) -> Option<String> {
        // remove diacritics and elongating character
        let result = self.diacritics.replace(&token, "");
        // replace all variations of alef (آأإٱى) to a plain alef (ا)
        let result = self.alefs.replace(&result, "\u{0627}");
        if result.is_empty() {
            None
        } else if result == token {
            Some(token)
        } else {
            Some(result.into())
        }
    }
}