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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*******************************************************************************
* Copyright 2021 Stefan Majewsky <majewsky@gmx.net>
* SPDX-License-Identifier: Apache-2.0
* Refer to the file "LICENSE" for details.
*******************************************************************************/

//! Parsing utilities for the build and test phases of the `jmdict` crate.
//!
//! This code is in a separate crate because, if we put it in the `jmdict` crate itself, its
//! `build.rs` could not import it.
//!
//! # Compatibility promise
//!
//! **There is none.** Although this crate is published on crates.io for technical reasons, this
//! crate is internal to the `jmdict` crate. Its API may change at any time, including in
//! bugfix releases. Use the [API provided by the `jmdict` crate](https://docs.rs/jmdict/) instead.

use jmdict_enums::{
    AllGlossLanguage, AllPartOfSpeech, Dialect, Enum, GlossLanguage, GlossType, KanjiInfo,
    PartOfSpeech, Priority, PriorityInCorpus, ReadingInfo, SenseInfo, SenseTopic,
};
use json::JsonValue;
use std::convert::TryInto;

mod entrypack;
use entrypack::EntryPack;

pub struct RawEntry<'a> {
    pub ent_seq: u32,
    pub k_ele: Vec<RawKanjiElement<'a>>,
    pub r_ele: Vec<RawReadingElement<'a>>,
    pub sense: Vec<RawSense<'a>>,
}

pub struct RawKanjiElement<'a> {
    pub keb: &'a str,
    pub ke_inf: Vec<KanjiInfo>,
    pub ke_pri: Priority,
}

pub struct RawReadingElement<'a> {
    pub reb: &'a str,
    pub re_nokanji: bool,
    pub re_restr: Vec<&'a str>,
    pub re_inf: Vec<ReadingInfo>,
    pub re_pri: Priority,
}

pub struct RawSense<'a> {
    pub stagk: Vec<&'a str>,
    pub stagr: Vec<&'a str>,
    pub pos: Vec<PartOfSpeech>,
    pub xref: Vec<&'a str>,
    pub ant: Vec<&'a str>,
    pub field: Vec<SenseTopic>,
    pub misc: Vec<SenseInfo>,
    pub s_inf: Vec<&'a str>,
    pub lsource: Vec<RawLSource<'a>>,
    pub dial: Vec<Dialect>,
    pub gloss: Vec<RawGloss<'a>>,
}

pub struct RawLSource<'a> {
    //NOTE: We do not use the GlossLanguage enum for the lang attribute, because doing so would add
    //a very long tail of rare loanword source languages to that enum. (Also, we could not restrict
    //variants of GlossLanguage to feature flags in the way we currently do.)
    pub text: &'a str,
    pub lang: &'a str,
    pub is_partial: bool,
    pub is_wasei: bool,
}

pub struct RawGloss<'a> {
    //NOTE: g_gend and pri are not mapped since they do not actually occur in any entries
    pub text: &'a str,
    pub lang: GlossLanguage,
    pub g_type: GlossType,
}

///Strategy for processing a JMdict file.
pub trait Visitor {
    fn process_entry(&mut self, entry: &RawEntry);

    ///This is called once for each file that was read from disk. The build script uses this to
    ///generate `cargo:rerun-if-changed` directives.
    fn notify_data_file_path(&mut self, _path: &str) {}
}

///Options for traversing a JMdict file. This controls which entries the [Visitor] visits, and
///which parts of the entries it sees.
pub struct Options {
    pub is_db_minimal: bool,
    pub with_uncommon: bool,
    pub with_archaic: bool,
}

///Entry point for this file. All other functions are called directly or indirectly from this fn.
pub fn process_dictionary<V: Visitor>(v: &mut V, opts: Options) {
    let entrypack = EntryPack::locate_or_download();
    v.notify_data_file_path(&entrypack.path.to_string_lossy());

    for entry_str in entrypack.contents().split('\n') {
        if !entry_str.is_empty() {
            let entry_obj = json::parse(entry_str).unwrap();
            if let Some(entry_raw) = RawEntry::from_obj(&entry_obj, &opts) {
                if opts.is_db_minimal && entry_raw.ent_seq >= 1010000 {
                    //for db-minimal, only process entries from data/entries-100.json
                    return;
                }
                v.process_entry(&entry_raw);
            }
        }
    }
}

trait Object<'a>: Sized {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self>;

    fn collect(array: &'a JsonValue, opts: &'_ Options) -> Vec<Self> {
        assert!(array.is_null() || array.is_array());
        array
            .members()
            .filter_map(|obj| Self::from_obj(obj, opts))
            .collect()
    }

    fn collect_or_none(array: &'a JsonValue, opts: &'_ Options) -> Option<Vec<Self>> {
        let vec = Self::collect(array, opts);
        if vec.is_empty() {
            None
        } else {
            Some(vec)
        }
    }
}

impl<'a> Object<'a> for RawEntry<'a> {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self> {
        Some(Self {
            ent_seq: obj["n"].as_u32().unwrap(),
            k_ele: RawKanjiElement::collect(&obj["K"], opts),
            r_ele: RawReadingElement::collect_or_none(&obj["R"], opts)?,
            sense: RawSense::collect_or_none(&obj["S"], opts)?,
        })
    }
}

impl<'a> Object<'a> for RawKanjiElement<'a> {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self> {
        if !opts.with_uncommon && obj["p"].is_empty() {
            return None;
        }
        Some(Self {
            keb: obj["t"].as_str().unwrap(),
            ke_inf: Object::collect(&obj["i"], opts),
            ke_pri: parse_prio(Object::collect(&obj["p"], opts)),
        })
    }
}

impl<'a> Object<'a> for RawReadingElement<'a> {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self> {
        if !opts.with_uncommon && obj["p"].is_empty() {
            return None;
        }
        Some(Self {
            reb: obj["t"].as_str().unwrap(),
            re_nokanji: obj["n"].as_bool().unwrap_or(false),
            re_restr: Object::collect(&obj["r"], opts),
            re_inf: Object::collect(&obj["i"], opts),
            re_pri: parse_prio(Object::collect(&obj["p"], opts)),
        })
    }
}

fn parse_prio(markers: Vec<&str>) -> Priority {
    use PriorityInCorpus::*;
    let mut result = Priority {
        news: Absent,
        ichimango: Absent,
        loanwords: Absent,
        additional: Absent,
        frequency_bucket: 0,
    };
    for marker in markers {
        match marker {
            "news1" => result.news = merge_cprio(result.news, Primary),
            "news2" => result.news = merge_cprio(result.news, Secondary),
            "ichi1" => result.ichimango = merge_cprio(result.ichimango, Primary),
            "ichi2" => result.ichimango = merge_cprio(result.ichimango, Secondary),
            "gai1" => result.loanwords = merge_cprio(result.loanwords, Primary),
            "gai2" => result.loanwords = merge_cprio(result.loanwords, Secondary),
            "spec1" => result.additional = merge_cprio(result.additional, Primary),
            "spec2" => result.additional = merge_cprio(result.additional, Secondary),
            _ => match parse_freq_bucket(marker) {
                Some(bucket) => {
                    if result.frequency_bucket == 0 || result.frequency_bucket > bucket {
                        result.frequency_bucket = bucket;
                    }
                }
                None => {
                    panic!("unknown priority marker: {}", marker);
                }
            },
        };
    }
    result
}

fn merge_cprio(old: PriorityInCorpus, new: PriorityInCorpus) -> PriorityInCorpus {
    use PriorityInCorpus::*;
    match (old, new) {
        (Absent, _) => new,
        (_, Primary) => Primary,
        (Primary, _) => Primary,
        (Secondary, _) => Secondary,
    }
}

///Parses a frequency bucket marker for the news corpus, e.g. "nf18" => Some(18).
fn parse_freq_bucket(marker: &str) -> Option<u16> {
    //NOTE: This would be easier with a regex library, but I'm definitely not pulling in an entire
    //regex crate for just this one thing.

    let mut c = marker.chars();
    if c.next()? != 'n' {
        return None;
    }
    if c.next()? != 'f' {
        return None;
    }
    let tens = c.next()?.to_digit(10)? as u16;
    let ones = c.next()?.to_digit(10)? as u16;
    if c.next().is_some() {
        return None;
    }
    let result = 10 * tens + ones;

    //only nf01..nf48 are allowed
    if result == 0 || result > 48 {
        None
    } else {
        Some(result)
    }
}

impl<'a> Object<'a> for RawSense<'a> {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self> {
        let misc = Object::collect(&obj["m"], opts);
        if !opts.with_archaic && misc.contains(&SenseInfo::Archaism) {
            return None;
        }

        Some(Self {
            stagk: Object::collect(&obj["stagk"], opts),
            stagr: Object::collect(&obj["stagr"], opts),
            pos: Object::collect(&obj["p"], opts),
            xref: Object::collect(&obj["xref"], opts),
            ant: Object::collect(&obj["ant"], opts),
            field: Object::collect(&obj["f"], opts),
            misc,
            s_inf: Object::collect(&obj["i"], opts),
            lsource: Object::collect(&obj["L"], opts),
            dial: Object::collect(&obj["dial"], opts),
            gloss: Object::collect_or_none(&obj["G"], opts)?,
        })
    }
}

impl<'a> Object<'a> for RawLSource<'a> {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        let is_partial = match obj["type"].as_str().unwrap_or("full") {
            "full" => false,
            "part" => true,
            val => panic!("unknown ls_type: {}", val),
        };
        let is_wasei = match obj["wasei"].as_str().unwrap_or("n") {
            "n" => false,
            "y" => true,
            val => panic!("unknown ls_wasei: {}", val),
        };
        Some(Self {
            text: obj["t"].as_str().unwrap(),
            lang: obj["l"].as_str().unwrap_or("eng"),
            is_partial,
            is_wasei,
        })
    }
}

impl<'a> Object<'a> for RawGloss<'a> {
    fn from_obj(obj: &'a JsonValue, opts: &'_ Options) -> Option<Self> {
        Some(Self {
            text: obj["t"].as_str().unwrap(),
            lang: GlossLanguage::from_obj(&obj["l"], opts)?,
            g_type: optional_enum(&obj["g_type"], "", "GlossType"),
        })
    }
}

impl<'a> Object<'a> for &'a str {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(obj.as_str().unwrap())
    }
}

impl<'a> Object<'a> for Dialect {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(required_enum(obj, "Dialect"))
    }
}

impl<'a> Object<'a> for GlossLanguage {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        let lang: AllGlossLanguage = optional_enum(obj, "eng", "AllGlossLanguage");
        lang.try_into().ok()
    }
}

impl<'a> Object<'a> for KanjiInfo {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(required_enum(obj, "KanjiInfo"))
    }
}

impl<'a> Object<'a> for PartOfSpeech {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        let lang: AllPartOfSpeech = optional_enum(obj, "eng", "AllPartOfSpeech");
        lang.try_into().ok()
    }
}

impl<'a> Object<'a> for ReadingInfo {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(required_enum(obj, "ReadingInfo"))
    }
}

impl<'a> Object<'a> for SenseInfo {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(required_enum(obj, "SenseInfo"))
    }
}

impl<'a> Object<'a> for SenseTopic {
    fn from_obj(obj: &'a JsonValue, _opts: &'_ Options) -> Option<Self> {
        Some(required_enum(obj, "SenseTopic"))
    }
}

fn optional_enum<E: Enum>(obj: &JsonValue, default: &'static str, enum_name: &'static str) -> E {
    let code = obj.as_str().unwrap_or(default);
    match E::from_code(code) {
        Some(val) => val,
        None => panic!("unknown {} representation: {}", enum_name, code),
    }
}

fn required_enum<E: Enum>(obj: &JsonValue, enum_name: &'static str) -> E {
    let code = obj.as_str().unwrap();
    match E::from_code(code) {
        Some(val) => val,
        None => panic!("unknown {} representation: {}", enum_name, code),
    }
}