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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/* Access to the unicode database.
   See also: https://docs.python.org/3/library/unicodedata.html
*/

use crate::function::OptionalArg;
use crate::obj::objstr::PyStringRef;
use crate::obj::objtype::PyClassRef;
use crate::pyobject::{PyClassImpl, PyObject, PyObjectRef, PyResult, PyValue};
use crate::vm::VirtualMachine;

use itertools::Itertools;
use unic::bidi::BidiClass;
use unic::char::property::EnumeratedCharProperty;
use unic::normal::StrNormalForm;
use unic::ucd::category::GeneralCategory;
use unic::ucd::{Age, Name};
use unic_common::version::UnicodeVersion;

pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
    let ctx = &vm.ctx;

    let ucd_class = PyUCD::make_class(ctx);

    let ucd = PyObject::new(PyUCD::default(), ucd_class.clone(), None);

    let ucd_3_2_0 = PyObject::new(
        PyUCD {
            unic_version: UnicodeVersion {
                major: 3,
                minor: 2,
                micro: 0,
            },
        },
        ucd_class.clone(),
        None,
    );

    let module = py_module!(vm, "unicodedata", {
        "UCD" => ucd_class.into_object(),
        "ucd_3_2_0" => ucd_3_2_0,
        // we do unidata_version here because the getter tries to do PyUCD::class() before
        // the module is in the VM
        "unidata_version" => ctx.new_str(PyUCD::default().unic_version.to_string()),
    });

    for attr in ["category", "lookup", "name", "bidirectional", "normalize"]
        .iter()
        .copied()
    {
        extend_module!(vm, &module, {
            attr => vm.get_attribute(ucd.clone(), attr).unwrap(),
        });
    }

    module
}

#[pyclass]
#[derive(Debug)]
struct PyUCD {
    unic_version: UnicodeVersion,
}

impl PyValue for PyUCD {
    fn class(vm: &VirtualMachine) -> PyClassRef {
        vm.class("unicodedata", "UCD")
    }
}

impl Default for PyUCD {
    #[inline(always)]
    fn default() -> Self {
        PyUCD {
            unic_version: unic::UNICODE_VERSION,
        }
    }
}

#[pyimpl]
impl PyUCD {
    fn check_age(&self, c: char) -> bool {
        Age::of(c).map_or(false, |age| age.actual() <= self.unic_version)
    }

    fn extract_char(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<Option<char>> {
        let c = character.as_str().chars().exactly_one().map_err(|_| {
            vm.new_type_error("argument must be an unicode character, not str".to_owned())
        })?;

        if self.check_age(c) {
            Ok(Some(c))
        } else {
            Ok(None)
        }
    }

    #[pymethod]
    fn category(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
        Ok(self
            .extract_char(character, vm)?
            .map_or(GeneralCategory::Unassigned, GeneralCategory::of)
            .abbr_name()
            .to_owned())
    }

    #[pymethod]
    fn lookup(&self, name: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
        // TODO: we might want to use unic_ucd instead of unicode_names2 for this too, if possible:
        if let Some(character) = unicode_names2::character(name.as_str()) {
            if self.check_age(character) {
                return Ok(character.to_string());
            }
        }
        Err(vm.new_lookup_error(format!("undefined character name '{}'", name)))
    }

    #[pymethod]
    fn name(
        &self,
        character: PyStringRef,
        default: OptionalArg<PyObjectRef>,
        vm: &VirtualMachine,
    ) -> PyResult {
        let c = self.extract_char(character, vm)?;

        if let Some(c) = c {
            if self.check_age(c) {
                if let Some(name) = Name::of(c) {
                    return Ok(vm.new_str(name.to_string()));
                }
            }
        }
        match default {
            OptionalArg::Present(obj) => Ok(obj),
            OptionalArg::Missing => Err(vm.new_value_error("character name not found!".to_owned())),
        }
    }

    #[pymethod]
    fn bidirectional(&self, character: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
        let bidi = match self.extract_char(character, vm)? {
            Some(c) => BidiClass::of(c).abbr_name(),
            None => "",
        };
        Ok(bidi.to_owned())
    }

    #[pymethod]
    fn normalize(
        &self,
        form: PyStringRef,
        unistr: PyStringRef,
        vm: &VirtualMachine,
    ) -> PyResult<String> {
        let text = unistr.as_str();
        let normalized_text = match form.as_str() {
            "NFC" => text.nfc().collect::<String>(),
            "NFKC" => text.nfkc().collect::<String>(),
            "NFD" => text.nfd().collect::<String>(),
            "NFKD" => text.nfkd().collect::<String>(),
            _ => return Err(vm.new_value_error("invalid normalization form".to_owned())),
        };

        Ok(normalized_text)
    }

    #[pyproperty]
    fn unidata_version(&self) -> String {
        self.unic_version.to_string()
    }
}