kabosu 0.7.0.1 → 0.7.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,680 +1,397 @@
1
1
  use magnus::typed_data::Obj;
2
2
  use magnus::value::{Opaque, ReprValue};
3
- use magnus::{gc, DataTypeFunctions, Error, RArray, RString, Ruby, TypedData, Value};
3
+ use magnus::{
4
+ gc, DataTypeFunctions, Error, IntoValue, RArray, RString, Ruby, TryConvert, TypedData, Value,
5
+ };
4
6
  use std::cell::OnceCell;
5
- use std::collections::HashMap;
6
- use std::sync::{Arc, Mutex, OnceLock};
7
- use sudachi::analysis::morpheme::{Morpheme as SudachiMorpheme, SingleMorpheme};
8
- use sudachi::analysis::Mode;
9
- use sudachi::dic::dictionary::JapaneseDictionary;
7
+ use std::collections::hash_map::DefaultHasher;
8
+ use std::hash::{Hash, Hasher};
9
+ use std::mem::size_of;
10
+ use std::sync::Arc;
11
+ use sudachi::analysis::morpheme::{MorphemeRef, MorphemeView, SingleMorpheme};
10
12
  use sudachi::dic::subset::InfoSubset;
11
13
  use sudachi::dic::word_id::WordId;
12
- use sudachi::dic::DictionaryAccess;
13
- use sudachi::text_normalizer::TextNormalizer;
14
14
 
15
- use crate::errors::sudachi_error;
15
+ use crate::dictionary::{Dict, PosTable};
16
+ use crate::errors::{catch_panic, dictionary_error, tokenization_error};
17
+ use crate::morpheme_list::RbMorphemeList;
16
18
  use crate::parsing::parse_mode;
17
19
 
18
- #[derive(Clone)]
19
- pub(crate) struct MorphemeData {
20
- pub(crate) surface: String,
21
- pub(crate) dictionary_form: String,
22
- pub(crate) normalized_form: String,
23
- pub(crate) reading_form: String,
24
- pub(crate) pos_id: u16,
25
- pub(crate) word_id_raw: u32,
26
- pub(crate) is_oov: bool,
27
- pub(crate) dictionary_id: i32,
28
- pub(crate) is_system: bool,
29
- pub(crate) is_user: bool,
30
- pub(crate) begin: usize,
31
- pub(crate) end: usize,
32
- pub(crate) begin_c: usize,
33
- pub(crate) end_c: usize,
34
- pub(crate) total_cost: i32,
35
- // Bytes of the normalized index form (upstream's index_form_length). Known
36
- // for every node, OOV and joined ones included, so it is not a lazy field.
37
- pub(crate) head_word_length: usize,
20
+ /// A morpheme that stands on its own rather than inside an analyzed text: a
21
+ /// dictionary entry or a hand-made OOV word. Its offsets cover its own surface.
22
+ pub(crate) type Entry = SingleMorpheme<Dict>;
23
+
24
+ enum Backing {
25
+ /// The `index`-th morpheme of an analysis result. The list is a Ruby
26
+ /// object, kept alive by `mark`.
27
+ Listed {
28
+ list: Opaque<Obj<RbMorphemeList>>,
29
+ index: usize,
30
+ },
31
+ Standalone(Box<Entry>),
38
32
  }
39
33
 
40
- pub(crate) fn build_morpheme_data<T>(m: &SudachiMorpheme<'_, T>) -> MorphemeData
41
- where
42
- T: DictionaryAccess,
43
- {
44
- let surface = {
45
- let s = m.surface();
46
- s.to_string()
47
- };
48
-
49
- MorphemeData {
50
- surface,
51
- dictionary_form: m.dictionary_form().to_string(),
52
- normalized_form: m.normalized_form().to_string(),
53
- reading_form: m.reading_form().to_string(),
54
- pos_id: m.part_of_speech_id(),
55
- word_id_raw: m.word_id().as_raw(),
56
- is_oov: m.is_oov(),
57
- dictionary_id: m.dictionary_id(),
58
- is_system: m.word_id().is_system(),
59
- is_user: m.word_id().is_user(),
60
- begin: m.begin(),
61
- end: m.end(),
62
- begin_c: m.begin_c(),
63
- end_c: m.end_c(),
64
- total_cost: m.total_cost(),
65
- head_word_length: m.get_word_info().index_form_length(),
66
- }
34
+ #[derive(TypedData)]
35
+ #[magnus(class = "Kabosu::Morpheme", mark, size, free_immediately)]
36
+ pub(crate) struct RbMorpheme {
37
+ backing: Backing,
38
+ pos_table: PosTable,
39
+ // The two Strings callers ask for over and over, built on first ask and
40
+ // handed out again after that. Measured on a real workload: 16.5 `surface`
41
+ // and 6.0 `dictionary_form` calls per morpheme. The other accessors are
42
+ // asked about once each and build a new String per call.
43
+ surface: OnceCell<Opaque<RString>>,
44
+ dictionary_form: OnceCell<Opaque<RString>>,
67
45
  }
68
46
 
69
- /// A morpheme that stands on its own rather than inside a tokenized sentence:
70
- /// a dictionary entry or a hand-made OOV word. Offsets cover its own surface
71
- /// (the headword, for entries) and there is no path cost.
72
- pub(crate) fn data_from_single<D>(m: &SingleMorpheme<D>) -> MorphemeData
73
- where
74
- D: DictionaryAccess + Clone,
75
- {
76
- let wid = m.word_id();
77
- MorphemeData {
78
- surface: m.surface().to_string(),
79
- dictionary_form: m.dictionary_form().to_string(),
80
- normalized_form: m.normalized_form().to_string(),
81
- reading_form: m.reading_form().to_string(),
82
- pos_id: m.part_of_speech_id(),
83
- word_id_raw: wid.as_raw(),
84
- is_oov: m.is_oov(),
85
- dictionary_id: dictionary_id_of(wid),
86
- is_system: wid.is_system(),
87
- is_user: wid.is_user(),
88
- begin: m.begin(),
89
- end: m.end(),
90
- begin_c: m.begin_c(),
91
- end_c: m.end_c(),
92
- total_cost: 0,
93
- head_word_length: m.get_word_info().index_form_length(),
47
+ impl DataTypeFunctions for RbMorpheme {
48
+ // The list, the cached Strings and the POS table are reachable only from
49
+ // Rust, so the GC cannot see them without being told. The table is marked
50
+ // here too so that it outlives the dictionary object it came from.
51
+ fn mark(&self, marker: &gc::Marker) {
52
+ if let Backing::Listed { list, .. } = &self.backing {
53
+ marker.mark(*list);
54
+ }
55
+ self.pos_table.mark(marker);
56
+ for cached in [&self.surface, &self.dictionary_form] {
57
+ if let Some(string) = cached.get() {
58
+ marker.mark(*string);
59
+ }
60
+ }
94
61
  }
95
- }
96
62
 
97
- #[derive(Clone, Copy)]
98
- struct CachedRArray(RArray);
99
- unsafe impl Send for CachedRArray {}
100
-
101
- static POS_CACHE: OnceLock<Mutex<HashMap<(usize, u16), CachedRArray>>> = OnceLock::new();
102
-
103
- pub(crate) fn rb_morpheme_from_data(
104
- data: MorphemeData,
105
- dict: Arc<JapaneseDictionary>,
106
- debug: bool,
107
- ) -> RbMorpheme {
108
- RbMorpheme {
109
- data,
110
- dict,
111
- debug,
112
- word_fields: OnceCell::new(),
113
- surface_cache: OnceCell::new(),
114
- dictionary_form_cache: OnceCell::new(),
115
- pos_cache: OnceCell::new(),
63
+ fn size(&self) -> usize {
64
+ size_of::<Self>()
65
+ + match self.backing {
66
+ Backing::Listed { .. } => 0,
67
+ Backing::Standalone(_) => size_of::<Entry>(),
68
+ }
116
69
  }
117
70
  }
118
71
 
119
- // One frozen Ruby String per slot, built on first ask.
120
- //
121
- // FROZEN ON PURPOSE, and not only for safety: `+str` returns self for a mutable
122
- // String and a mutable COPY for a frozen one, so a shared mutable value would let
123
- // an innocent `buf = +m.surface; buf << other` write straight through into the
124
- // cache and corrupt every later read. Frozen, that idiom keeps working unchanged
125
- // and anything else fails loudly instead of silently.
126
- fn frozen_string(ruby: &Ruby, cell: &OnceCell<Opaque<RString>>, source: &str) -> RString {
127
- let cached = cell.get_or_init(|| {
128
- let rstr = ruby.str_new(source);
129
- rstr.as_value().freeze();
130
- Opaque::from(rstr)
131
- });
132
- ruby.get_inner(*cached)
72
+ type View<'a> = &'a dyn MorphemeView<Dictionary = Dict>;
73
+
74
+ // Every String a morpheme returns is frozen. Not only for safety: `+str`
75
+ // returns self for a mutable String and a mutable COPY for a frozen one, so a
76
+ // cached mutable String would let an innocent `buf = +m.surface; buf << other`
77
+ // write straight through into the cache and corrupt every later read. Frozen,
78
+ // that idiom keeps working and anything else fails loudly. The uncached
79
+ // accessors are frozen as well so that all of them behave alike.
80
+ fn frozen_string(ruby: &Ruby, text: &str) -> RString {
81
+ let string = ruby.str_new(text);
82
+ string.freeze();
83
+ string
133
84
  }
134
85
 
135
- // sudachi.rs 0.7 made `WordId::from_raw` crate-private; `new` rebuilds the same
136
- // value from its 4-bit dictionary and 28-bit entry halves.
137
- pub(crate) fn word_id_from_raw(raw: u32) -> WordId {
138
- WordId::new((raw >> 28) as u8, raw & 0x0fff_ffff)
86
+ fn cached_string(
87
+ ruby: &Ruby,
88
+ cell: &OnceCell<Opaque<RString>>,
89
+ text: impl FnOnce() -> RString,
90
+ ) -> RString {
91
+ ruby.get_inner(*cell.get_or_init(|| Opaque::from(text())))
139
92
  }
140
93
 
141
- pub(crate) fn dictionary_id_of(wid: WordId) -> i32 {
142
- if wid.is_oov() {
143
- -1
144
- } else {
145
- wid.dict().as_raw() as i32
94
+ fn word_ids_to_array(ruby: &Ruby, ids: &[WordId]) -> Result<RArray, Error> {
95
+ let array = ruby.ary_new_capa(ids.len());
96
+ for id in ids {
97
+ array.push(id.as_raw())?;
146
98
  }
99
+ Ok(array)
147
100
  }
148
101
 
149
- /// Character boundaries of `text` plus the byte length that each character
150
- /// prefix normalizes to under the dictionary's input-text plugins. Dictionary
151
- /// lengths (index_form_length, lookup ends) count normalized bytes, so this is
152
- /// what maps them back onto the original text.
153
- pub(crate) struct PrefixMap {
154
- pub(crate) byte_boundaries: Vec<usize>,
155
- normalized_lens: Vec<usize>,
156
- }
157
-
158
- impl PrefixMap {
159
- pub(crate) fn new(dict: &Arc<JapaneseDictionary>, text: &str) -> Result<Self, Error> {
160
- let mut byte_boundaries: Vec<usize> = text.char_indices().map(|(i, _)| i).collect();
161
- byte_boundaries.push(text.len());
162
-
163
- let mut normalizer = TextNormalizer::from_shared_dictionary(dict.clone());
164
- let mut normalized_lens = Vec::with_capacity(byte_boundaries.len());
165
- normalized_lens.push(0);
166
- for &end in &byte_boundaries[1..] {
167
- let normalized = normalizer.normalize(&text[..end]).map_err(sudachi_error)?;
168
- normalized_lens.push(normalized.len());
102
+ // The accessors take `&Ruby` as their first parameter instead of calling
103
+ // `Ruby::get()`: magnus hands the handle over for free, while `Ruby::get()`
104
+ // costs a thread-local access on every call.
105
+ impl RbMorpheme {
106
+ pub(crate) fn listed(list: Obj<RbMorphemeList>, index: usize) -> Self {
107
+ Self {
108
+ backing: Backing::Listed {
109
+ list: Opaque::from(list),
110
+ index,
111
+ },
112
+ pos_table: list.pos_table(),
113
+ surface: OnceCell::new(),
114
+ dictionary_form: OnceCell::new(),
169
115
  }
170
-
171
- Ok(Self {
172
- byte_boundaries,
173
- normalized_lens,
174
- })
175
- }
176
-
177
- pub(crate) fn char_len(&self) -> usize {
178
- self.byte_boundaries.len() - 1
179
116
  }
180
117
 
181
- /// The LAST character boundary at or after `from` whose prefix normalizes
182
- /// to at most `target` bytes. Last, because characters the plugins fold away
183
- /// (a run of 〜, a closed yomigana bracket) belong to the word before them.
184
- pub(crate) fn char_end(&self, from: usize, target: usize) -> usize {
185
- (from..self.normalized_lens.len())
186
- .rev()
187
- .find(|&k| self.normalized_lens[k] <= target)
188
- .unwrap_or(from)
189
- }
190
- }
191
-
192
- fn ids_to_array<T: magnus::IntoValue + Copy>(ids: &[T]) -> Result<RArray, Error> {
193
- let ruby = Ruby::get().unwrap();
194
- let ary = ruby.ary_new_capa(ids.len());
195
- for &id in ids {
196
- ary.push(id)?;
197
- }
198
- Ok(ary)
199
- }
200
-
201
- #[derive(TypedData)]
202
- #[magnus(class = "Kabosu::Morpheme", mark)]
203
- pub(crate) struct RbMorpheme {
204
- data: MorphemeData,
205
- dict: Arc<JapaneseDictionary>,
206
- debug: bool,
207
- word_fields: OnceCell<LazyWordFields>,
208
- // Ruby objects handed to the same caller over and over: built once per
209
- // morpheme rather than once per call. See `surface` for the reasoning and
210
- // for why they are frozen.
211
- surface_cache: OnceCell<Opaque<RString>>,
212
- dictionary_form_cache: OnceCell<Opaque<RString>>,
213
- pos_cache: OnceCell<Opaque<RArray>>,
214
- }
215
-
216
- impl DataTypeFunctions for RbMorpheme {
217
- // The cached surface is reachable only from Rust, so the GC cannot see it
218
- // without being told. Missing this would let a live String be collected.
219
- fn mark(&self, marker: &gc::Marker) {
220
- if let Some(cached) = self.surface_cache.get() {
221
- marker.mark(*cached);
222
- }
223
- if let Some(cached) = self.dictionary_form_cache.get() {
224
- marker.mark(*cached);
225
- }
226
- if let Some(cached) = self.pos_cache.get() {
227
- marker.mark(*cached);
118
+ pub(crate) fn standalone(entry: Entry, pos_table: PosTable) -> Self {
119
+ Self {
120
+ backing: Backing::Standalone(Box::new(entry)),
121
+ pos_table,
122
+ surface: OnceCell::new(),
123
+ dictionary_form: OnceCell::new(),
228
124
  }
229
125
  }
230
- }
231
-
232
- struct LazyWordFields {
233
- synonym_group_ids: Vec<i32>,
234
- dictionary_form_word_id: i64,
235
- a_unit_split: Vec<u32>,
236
- b_unit_split: Vec<u32>,
237
- c_unit_split: Vec<u32>,
238
- word_structure: Vec<u32>,
239
- user_data: String,
240
- }
241
126
 
242
- impl RbMorpheme {
243
- fn fallback_word_fields(&self) -> LazyWordFields {
244
- LazyWordFields {
245
- synonym_group_ids: Vec::new(),
246
- dictionary_form_word_id: -1,
247
- a_unit_split: Vec::new(),
248
- b_unit_split: Vec::new(),
249
- c_unit_split: Vec::new(),
250
- word_structure: Vec::new(),
251
- user_data: String::new(),
127
+ fn view<R>(&self, ruby: &Ruby, read: impl FnOnce(View<'_>) -> R) -> R {
128
+ match &self.backing {
129
+ Backing::Listed { list, index } => read(&ruby.get_inner(*list).analysis().get(*index)),
130
+ Backing::Standalone(entry) => read(entry.as_ref()),
252
131
  }
253
132
  }
254
133
 
255
- fn resolve_word_fields(&self) -> &LazyWordFields {
256
- self.word_fields.get_or_init(|| {
257
- if self.data.is_oov || self.data.dictionary_id < 0 {
258
- return self.fallback_word_fields();
259
- }
260
-
261
- let wid = word_id_from_raw(self.data.word_id_raw);
262
-
263
- let info_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
264
- self.dict.lexicon().get_word_info(wid)
265
- }));
266
-
267
- match info_result {
268
- Ok(Ok(info)) => LazyWordFields {
269
- synonym_group_ids: info.synonym_group_ids().to_vec(),
270
- // V1 dictionaries point a word that is its own dictionary
271
- // form at itself; v0.6 stored -1 there, which callers rely on.
272
- dictionary_form_word_id: match info.borrow_data().dictionary_form_word_id() {
273
- d if d == wid => -1,
274
- d => i64::from(d.as_raw()),
275
- },
276
- a_unit_split: info.a_unit_split().iter().map(WordId::as_raw).collect(),
277
- b_unit_split: info.b_unit_split().iter().map(WordId::as_raw).collect(),
278
- c_unit_split: info.c_unit_split().iter().map(WordId::as_raw).collect(),
279
- word_structure: info.word_structure().iter().map(WordId::as_raw).collect(),
280
- user_data: info.user_data().to_string(),
281
- },
282
- _ => self.fallback_word_fields(),
283
- }
134
+ pub(crate) fn surface(ruby: &Ruby, rb_self: &Self) -> RString {
135
+ cached_string(ruby, &rb_self.surface, || {
136
+ rb_self.view(ruby, |m| frozen_string(ruby, &m.surface()))
284
137
  })
285
138
  }
286
139
 
287
- fn split_ids_from_lexicon(&self, mode: Mode) -> Result<Vec<u32>, Error> {
288
- if self.data.is_oov || self.data.dictionary_id < 0 {
289
- return Ok(Vec::new());
290
- }
291
- let wid = word_id_from_raw(self.data.word_id_raw);
292
-
293
- let info_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
294
- self.dict.lexicon().get_word_info(wid)
295
- }));
296
- let info = match info_result {
297
- Ok(Ok(info)) => info,
298
- Ok(Err(e)) => return Err(sudachi_error(e)),
299
- Err(_) => return Err(sudachi_error("panic while reading word info for split")),
300
- };
301
- let ids = match mode {
302
- Mode::A => info.a_unit_split(),
303
- Mode::B => info.b_unit_split(),
304
- Mode::C => &[],
305
- };
306
- Ok(ids.iter().map(WordId::as_raw).collect())
140
+ pub(crate) fn dictionary_form(ruby: &Ruby, rb_self: &Self) -> RString {
141
+ cached_string(ruby, &rb_self.dictionary_form, || {
142
+ rb_self.view(ruby, |m| frozen_string(ruby, m.dictionary_form()))
143
+ })
307
144
  }
308
145
 
309
- fn split_ids_for_mode(&self, mode: Mode) -> Result<Vec<u32>, Error> {
310
- match mode {
311
- Mode::A => {
312
- let ids = &self.resolve_word_fields().a_unit_split;
313
- if ids.is_empty() {
314
- self.split_ids_from_lexicon(mode)
315
- } else {
316
- Ok(ids.clone())
317
- }
318
- }
319
- Mode::B => {
320
- let ids = &self.resolve_word_fields().b_unit_split;
321
- if ids.is_empty() {
322
- self.split_ids_from_lexicon(mode)
323
- } else {
324
- Ok(ids.clone())
325
- }
326
- }
327
- Mode::C => Ok(Vec::new()),
328
- }
146
+ pub(crate) fn normalized_form(ruby: &Ruby, rb_self: &Self) -> RString {
147
+ rb_self.view(ruby, |m| frozen_string(ruby, m.normalized_form()))
329
148
  }
330
149
 
331
- // Mirrors upstream's node splitting: each child spans its index_form_length
332
- // in NORMALIZED bytes, mapped back onto the original surface. Sizing by the
333
- // child's own text instead misplaces every cut where normalization changes
334
- // the text (half-width kana, 〜 runs, yomigana).
335
- fn build_split_children(&self, split_ids: &[u32]) -> Result<Vec<MorphemeData>, Error> {
336
- let surface = &self.data.surface;
337
- let prefixes = PrefixMap::new(&self.dict, surface)?;
338
- let char_len = prefixes.char_len();
339
- let lexicon = self.dict.lexicon();
340
-
341
- let mut char_pos = 0usize;
342
- let mut normalized_end = 0usize;
343
- let mut result = Vec::with_capacity(split_ids.len());
344
-
345
- for (i, &raw_wid) in split_ids.iter().enumerate() {
346
- let wid = word_id_from_raw(raw_wid);
347
- let info_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
348
- lexicon.get_word_info(wid)
349
- }));
350
- let info = match info_result {
351
- Ok(Ok(info)) => info,
352
- Ok(Err(e)) => return Err(sudachi_error(e)),
353
- Err(_) => {
354
- return Err(sudachi_error(
355
- "panic while reading child word info for split",
356
- ))
357
- }
358
- };
359
-
360
- normalized_end += info.index_form_length();
361
- // The last child takes whatever is left, so the children always
362
- // cover the parent surface exactly.
363
- let end_char = if i + 1 == split_ids.len() {
364
- char_len
365
- } else {
366
- prefixes.char_end(char_pos, normalized_end)
367
- };
368
-
369
- let start_char = char_pos;
370
- let start_byte = prefixes.byte_boundaries[start_char];
371
- let end_byte = prefixes.byte_boundaries[end_char];
372
- char_pos = end_char;
373
-
374
- let child = MorphemeData {
375
- surface: surface[start_byte..end_byte].to_string(),
376
- dictionary_form: info.dictionary_form(lexicon).to_string(),
377
- normalized_form: info.normalized_form(lexicon).to_string(),
378
- reading_form: info.reading_form(lexicon).to_string(),
379
- pos_id: info.pos_id(),
380
- word_id_raw: raw_wid,
381
- is_oov: wid.is_oov(),
382
- dictionary_id: dictionary_id_of(wid),
383
- is_system: wid.is_system(),
384
- is_user: wid.is_user(),
385
- begin: self.data.begin + start_byte,
386
- end: self.data.begin + end_byte,
387
- begin_c: self.data.begin_c + start_char,
388
- end_c: self.data.begin_c + end_char,
389
- total_cost: self.data.total_cost,
390
- head_word_length: info.index_form_length(),
391
- };
392
- result.push(child);
393
- }
150
+ pub(crate) fn reading_form(ruby: &Ruby, rb_self: &Self) -> RString {
151
+ rb_self.view(ruby, |m| frozen_string(ruby, m.reading_form()))
152
+ }
394
153
 
395
- Ok(result)
396
- }
397
-
398
- // One frozen Ruby String per morpheme, not one per call.
399
- //
400
- // Callers ask this a lot: measured on a real tokenizer workload, 58,874 calls
401
- // across 3,569 distinct morphemes, 16.5 each, so 94% of the Strings this used
402
- // to allocate were identical copies of one already made. Returning `&str` let
403
- // magnus build a fresh RString every time.
404
- //
405
- // FROZEN ON PURPOSE, and not only for safety: `+str` returns self for a
406
- // mutable String and a mutable COPY for a frozen one, so a shared mutable
407
- // surface would let an innocent `buf = +m.surface; buf << other` write through
408
- // into the cache and corrupt every later read. Frozen, that idiom keeps
409
- // working unchanged and anything else fails loudly. `part_of_speech` freezes
410
- // what it caches for the same reason.
411
- // Takes `&Ruby` as its first parameter rather than calling `Ruby::get()`.
412
- // magnus hands that handle over for free (`Ruby::get_with` is
413
- // `Self(PhantomData)`, zero instructions), where `Ruby::get()` costs a
414
- // thread-local access, a RefCell borrow and a Result construction on EVERY
415
- // call — including the cache-hit path, whose only use for the handle is
416
- // `get_inner`, which discards it. With the allocations gone that round trip
417
- // was a real share of what these accessors still cost. `method!(.., 0)` in
418
- // lib.rs is unchanged: magnus resolves the &Ruby form on the fn pointer.
419
- pub(crate) fn surface(ruby: &Ruby, rb_self: &Self) -> RString {
420
- frozen_string(ruby, &rb_self.surface_cache, &rb_self.data.surface)
154
+ pub(crate) fn user_data(ruby: &Ruby, rb_self: &Self) -> RString {
155
+ rb_self.view(ruby, |m| frozen_string(ruby, m.user_data()))
421
156
  }
422
157
 
423
- // Asked more than any other method on this class: 35.7 times per morpheme on
424
- // a real workload. The process-wide POS_CACHE below already makes the ANSWER
425
- // free of allocation, but every one of those calls still took a global Mutex
426
- // and hashed a key to reach it. A morpheme's part of speech cannot change, so
427
- // the first ask is remembered here and the rest never reach the lock.
428
158
  pub(crate) fn part_of_speech(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
429
- if let Some(cached) = rb_self.pos_cache.get() {
430
- return Ok(ruby.get_inner(*cached));
431
- }
432
-
433
- let ary = rb_self.pos_from_shared_cache()?;
434
- let _ = rb_self.pos_cache.set(Opaque::from(ary));
435
- Ok(ary)
159
+ let pos_id = rb_self.view(ruby, |m| m.part_of_speech_id());
160
+ rb_self.pos_table.get(ruby, pos_id)
436
161
  }
437
162
 
438
- fn pos_from_shared_cache(&self) -> Result<RArray, Error> {
439
- let dict_ptr = Arc::as_ptr(&self.dict) as usize;
440
- let pos_id = self.data.pos_id;
441
-
442
- {
443
- let cache = POS_CACHE
444
- .get_or_init(|| Mutex::new(HashMap::new()))
445
- .lock()
446
- .unwrap();
447
- if let Some(&cached) = cache.get(&(dict_ptr, pos_id)) {
448
- return Ok(cached.0);
449
- }
450
- }
451
-
452
- let ruby = Ruby::get().unwrap();
453
- let ary = ruby.ary_new();
454
- for s in self.dict.grammar().pos_components(pos_id) {
455
- let rstr: RString = ruby.str_new(s);
456
- rstr.as_value().freeze();
457
- ary.push(rstr)?;
458
- }
459
- ary.as_value().freeze();
460
- // Pin permanently: POS combinations are bounded (~hundreds) and frozen
461
- // arrays are tiny. The cache lives for the process lifetime.
462
- gc::register_mark_object(ary);
463
-
464
- POS_CACHE
465
- .get_or_init(|| Mutex::new(HashMap::new()))
466
- .lock()
467
- .unwrap()
468
- .insert((dict_ptr, pos_id), CachedRArray(ary));
469
-
470
- Ok(ary)
163
+ pub(crate) fn part_of_speech_id(ruby: &Ruby, rb_self: &Self) -> u16 {
164
+ rb_self.view(ruby, |m| m.part_of_speech_id())
471
165
  }
472
166
 
473
- pub(crate) fn part_of_speech_id(&self) -> u16 {
474
- self.data.pos_id
167
+ pub(crate) fn is_oov(ruby: &Ruby, rb_self: &Self) -> bool {
168
+ rb_self.view(ruby, |m| m.is_oov())
475
169
  }
476
170
 
477
- // Cached like `surface`, and for the same measured reason: 6.0 calls per
478
- // morpheme on a real workload, so five of every six Strings this built were
479
- // a copy of one it had already built.
480
- pub(crate) fn dictionary_form(ruby: &Ruby, rb_self: &Self) -> RString {
481
- frozen_string(
482
- ruby,
483
- &rb_self.dictionary_form_cache,
484
- &rb_self.data.dictionary_form,
485
- )
171
+ pub(crate) fn is_system(ruby: &Ruby, rb_self: &Self) -> bool {
172
+ rb_self.view(ruby, |m| m.word_id().is_system())
486
173
  }
487
174
 
488
- pub(crate) fn normalized_form(&self) -> &str {
489
- &self.data.normalized_form
175
+ pub(crate) fn is_user(ruby: &Ruby, rb_self: &Self) -> bool {
176
+ rb_self.view(ruby, |m| m.word_id().is_user())
490
177
  }
491
178
 
492
- pub(crate) fn reading_form(&self) -> &str {
493
- &self.data.reading_form
179
+ pub(crate) fn dictionary_id(ruby: &Ruby, rb_self: &Self) -> i32 {
180
+ rb_self.view(ruby, |m| m.dictionary_id())
494
181
  }
495
182
 
496
- pub(crate) fn is_oov(&self) -> bool {
497
- self.data.is_oov
183
+ pub(crate) fn word_id(ruby: &Ruby, rb_self: &Self) -> u32 {
184
+ rb_self.view(ruby, |m| m.word_id().as_raw())
498
185
  }
499
186
 
500
- pub(crate) fn dictionary_id(&self) -> i32 {
501
- self.data.dictionary_id
187
+ /// The word id of the dictionary form, or -1 for a word that is its own
188
+ /// dictionary form (V1 dictionaries point such a word at itself), for OOV
189
+ /// words, and when the tokenizer's `fields` left the dictionary form out.
190
+ pub(crate) fn dictionary_form_word_id(ruby: &Ruby, rb_self: &Self) -> i64 {
191
+ rb_self.view(ruby, |m| {
192
+ let word_id = m.word_id();
193
+ if word_id.is_oov() || !m.subset().contains(InfoSubset::DICTIONARY_FORM) {
194
+ return -1;
195
+ }
196
+ match m.get_word_info().borrow_data().dictionary_form_word_id() {
197
+ form if form == word_id || form == WordId::INVALID => -1,
198
+ form => i64::from(form.as_raw()),
199
+ }
200
+ })
502
201
  }
503
202
 
504
- pub(crate) fn word_id(&self) -> u32 {
505
- self.data.word_id_raw
203
+ /// Bytes of the normalized index form (upstream's `index_form_length`).
204
+ pub(crate) fn head_word_length(ruby: &Ruby, rb_self: &Self) -> usize {
205
+ rb_self.view(ruby, |m| m.get_word_info().index_form_length())
506
206
  }
507
207
 
508
- pub(crate) fn dictionary_form_word_id(&self) -> i64 {
509
- self.resolve_word_fields().dictionary_form_word_id
208
+ pub(crate) fn begin(ruby: &Ruby, rb_self: &Self) -> usize {
209
+ rb_self.view(ruby, |m| m.begin())
510
210
  }
511
211
 
512
- pub(crate) fn head_word_length(&self) -> usize {
513
- self.data.head_word_length
212
+ pub(crate) fn end(ruby: &Ruby, rb_self: &Self) -> usize {
213
+ rb_self.view(ruby, |m| m.end())
514
214
  }
515
215
 
516
- pub(crate) fn begin(&self) -> usize {
517
- self.data.begin
216
+ pub(crate) fn begin_c(ruby: &Ruby, rb_self: &Self) -> usize {
217
+ rb_self.view(ruby, |m| m.begin_c())
518
218
  }
519
219
 
520
- pub(crate) fn end(&self) -> usize {
521
- self.data.end
220
+ pub(crate) fn end_c(ruby: &Ruby, rb_self: &Self) -> usize {
221
+ rb_self.view(ruby, |m| m.end_c())
522
222
  }
523
223
 
524
- pub(crate) fn begin_c(&self) -> usize {
525
- self.data.begin_c
224
+ /// Length in characters.
225
+ pub(crate) fn length(ruby: &Ruby, rb_self: &Self) -> usize {
226
+ rb_self.view(ruby, |m| m.end_c() - m.begin_c())
526
227
  }
527
228
 
528
- pub(crate) fn end_c(&self) -> usize {
529
- self.data.end_c
229
+ /// The cumulative lattice path cost up to this morpheme. Only meaningful
230
+ /// for mode-C tokenization results: sudachi.rs gives the pieces of a split
231
+ /// word `i32::MAX`, and standalone morphemes have no path at all.
232
+ pub(crate) fn total_cost(ruby: &Ruby, rb_self: &Self) -> i32 {
233
+ match &rb_self.backing {
234
+ Backing::Listed { list, index } => {
235
+ ruby.get_inner(*list).analysis().get(*index).total_cost()
236
+ }
237
+ Backing::Standalone(_) => 0,
238
+ }
530
239
  }
531
240
 
532
- pub(crate) fn synonym_group_ids(&self) -> Result<RArray, Error> {
533
- ids_to_array(&self.resolve_word_fields().synonym_group_ids)
241
+ pub(crate) fn synonym_group_ids(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
242
+ rb_self.view(ruby, |m| {
243
+ let ids = m.synonym_group_ids();
244
+ let array = ruby.ary_new_capa(ids.len());
245
+ for &id in ids {
246
+ array.push(id)?;
247
+ }
248
+ Ok(array)
249
+ })
534
250
  }
535
251
 
536
- pub(crate) fn a_unit_split(&self) -> Result<RArray, Error> {
537
- ids_to_array(&self.resolve_word_fields().a_unit_split)
252
+ pub(crate) fn a_unit_split(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
253
+ rb_self.view(ruby, |m| {
254
+ word_ids_to_array(ruby, m.get_word_info().a_unit_split())
255
+ })
538
256
  }
539
257
 
540
- pub(crate) fn b_unit_split(&self) -> Result<RArray, Error> {
541
- ids_to_array(&self.resolve_word_fields().b_unit_split)
258
+ pub(crate) fn b_unit_split(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
259
+ rb_self.view(ruby, |m| {
260
+ word_ids_to_array(ruby, m.get_word_info().b_unit_split())
261
+ })
542
262
  }
543
263
 
544
- pub(crate) fn c_unit_split(&self) -> Result<RArray, Error> {
545
- ids_to_array(&self.resolve_word_fields().c_unit_split)
264
+ pub(crate) fn c_unit_split(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
265
+ rb_self.view(ruby, |m| {
266
+ word_ids_to_array(ruby, m.get_word_info().c_unit_split())
267
+ })
546
268
  }
547
269
 
548
- pub(crate) fn user_data(&self) -> &str {
549
- &self.resolve_word_fields().user_data
270
+ pub(crate) fn word_structure(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
271
+ rb_self.view(ruby, |m| {
272
+ word_ids_to_array(ruby, m.get_word_info().word_structure())
273
+ })
550
274
  }
551
275
 
552
276
  pub(crate) fn dictionary_form_morpheme(
553
277
  ruby: &Ruby,
554
278
  rb_self: Obj<Self>,
555
279
  ) -> Result<Value, Error> {
556
- Self::form_morpheme(ruby, rb_self, InfoSubset::DICTIONARY_FORM)
280
+ Self::form_morpheme(ruby, rb_self, |m| m.dictionary_form_morpheme())
557
281
  }
558
282
 
559
283
  pub(crate) fn normalized_form_morpheme(
560
284
  ruby: &Ruby,
561
285
  rb_self: Obj<Self>,
562
286
  ) -> Result<Value, Error> {
563
- Self::form_morpheme(ruby, rb_self, InfoSubset::NORMALIZED_FORM)
287
+ Self::form_morpheme(ruby, rb_self, |m| m.normalized_form_morpheme())
564
288
  }
565
289
 
566
- // The dictionary entry this morpheme's dictionary/normalized form refers to,
567
- // as a standalone morpheme. A word that is its own form (and any OOV word)
568
- // answers with itself, the same object, as upstream does.
569
- fn form_morpheme(ruby: &Ruby, rb_self: Obj<Self>, form: InfoSubset) -> Result<Value, Error> {
570
- if rb_self.data.is_oov {
571
- return Ok(rb_self.as_value());
572
- }
573
-
574
- let wid = word_id_from_raw(rb_self.data.word_id_raw);
575
- let lexicon = rb_self.dict.lexicon();
576
- let info = lexicon
577
- .get_word_info_subset(wid, form)
578
- .map_err(sudachi_error)?;
579
- let data = info.borrow_data();
580
- let form_wid = if form == InfoSubset::DICTIONARY_FORM {
581
- data.dictionary_form_word_id()
582
- } else {
583
- data.normalized_form_word_id()
584
- };
585
-
586
- if form_wid == WordId::INVALID
587
- || form_wid == wid
588
- || form_wid.is_oov()
589
- || form_wid.is_special()
590
- {
591
- return Ok(rb_self.as_value());
592
- }
593
-
594
- let single = SingleMorpheme::from_word_id(&*rb_self.dict, form_wid, InfoSubset::all())
595
- .map_err(sudachi_error)?;
596
- let morpheme = rb_morpheme_from_data(
597
- data_from_single(&single),
598
- rb_self.dict.clone(),
599
- rb_self.debug,
600
- );
601
- Ok(ruby.obj_wrap(morpheme).as_value())
602
- }
603
-
604
- pub(crate) fn word_structure(&self) -> Result<RArray, Error> {
605
- ids_to_array(&self.resolve_word_fields().word_structure)
606
- }
607
-
608
- pub(crate) fn total_cost(&self) -> i32 {
609
- self.data.total_cost
610
- }
611
-
612
- pub(crate) fn is_system(&self) -> bool {
613
- self.data.is_system
614
- }
615
-
616
- pub(crate) fn is_user(&self) -> bool {
617
- self.data.is_user
290
+ // The dictionary entry this morpheme's dictionary/normalized form refers
291
+ // to, as a standalone morpheme. A word of an analysis that is its own
292
+ // form (and any OOV word of one) answers with itself, the same object. A
293
+ // standalone morpheme always answers with a new object: the entry of the
294
+ // form, or for a hand-made OOV morpheme a copy of itself.
295
+ fn form_morpheme(
296
+ ruby: &Ruby,
297
+ rb_self: Obj<Self>,
298
+ resolve: impl FnOnce(View<'_>) -> sudachi::error::SudachiResult<MorphemeRef<'_, Dict>>,
299
+ ) -> Result<Value, Error> {
300
+ rb_self.view(ruby, |m| match resolve(m).map_err(dictionary_error)? {
301
+ MorphemeRef::Single(entry) => {
302
+ let morpheme = Self::standalone(*entry, rb_self.pos_table);
303
+ Ok(ruby.obj_wrap(morpheme).as_value())
304
+ }
305
+ _ => Ok(rb_self.as_value()),
306
+ })
618
307
  }
619
308
 
309
+ /// The sub-units of this morpheme in a finer split mode, as sudachi.rs
310
+ /// computes them. Answers with a native list for a morpheme of an analysis
311
+ /// and with an Array for a standalone one; the Ruby side wraps either.
312
+ ///
313
+ /// With `add_single`, a morpheme that has no finer split answers with
314
+ /// itself instead of nothing.
620
315
  pub(crate) fn split(
621
- &self,
622
- mode_str: Option<String>,
623
- out: Option<RArray>,
624
- add_single: Option<bool>,
625
- ) -> Result<RArray, Error> {
626
- let ruby = Ruby::get().unwrap();
627
- let add_single = add_single.unwrap_or(true);
628
-
629
- let target_mode = parse_mode(mode_str.as_deref())?;
630
- let split_ids = self.split_ids_for_mode(target_mode)?;
631
- let children = if split_ids.is_empty() {
632
- Vec::new()
633
- } else {
634
- self.build_split_children(&split_ids)?
635
- };
636
-
637
- let ary = match out {
638
- Some(ary) => {
639
- ary.clear()?;
640
- ary
641
- }
642
- None => ruby.ary_new_capa(if children.is_empty() {
643
- 1
644
- } else {
645
- children.len()
646
- }),
647
- };
648
-
649
- if children.is_empty() {
650
- if add_single {
651
- ary.push(rb_morpheme_from_data(
652
- self.data.clone(),
653
- self.dict.clone(),
654
- self.debug,
655
- ))?;
316
+ ruby: &Ruby,
317
+ rb_self: &Self,
318
+ mode: Option<Value>,
319
+ add_single: bool,
320
+ ) -> Result<Value, Error> {
321
+ let mode = parse_mode(mode)?;
322
+
323
+ match &rb_self.backing {
324
+ Backing::Listed { list, index } => {
325
+ let source = ruby.get_inner(*list);
326
+ let analysis = source.analysis();
327
+ let mut parts = analysis.empty_clone();
328
+ // sudachi.rs unwraps while reading the sub-unit entries.
329
+ let was_split = catch_panic("splitting a morpheme", || {
330
+ analysis.split_into(mode, *index, &mut parts)
331
+ })
332
+ .map_err(tokenization_error)?
333
+ .map_err(tokenization_error)?;
334
+ if !was_split && add_single {
335
+ analysis.copy_slice(*index, *index + 1, &mut parts);
336
+ }
337
+ let parts = RbMorphemeList::sharing_input(parts, rb_self.pos_table);
338
+ Ok(ruby.obj_wrap(parts).as_value())
656
339
  }
657
- } else {
658
- for child in children {
659
- ary.push(rb_morpheme_from_data(child, self.dict.clone(), self.debug))?;
340
+ Backing::Standalone(entry) => {
341
+ let parts = entry.split(mode).map_err(tokenization_error)?;
342
+ let was_split = !matches!(&parts[..], [only] if only.word_id() == entry.word_id());
343
+ let array = ruby.ary_new_capa(parts.len());
344
+ if was_split || add_single {
345
+ for part in parts {
346
+ array.push(Self::standalone(part, rb_self.pos_table))?;
347
+ }
348
+ }
349
+ Ok(array.into_value_with(ruby))
660
350
  }
661
351
  }
662
-
663
- Ok(ary)
664
352
  }
665
353
 
666
- pub(crate) fn inspect(&self) -> String {
667
- format!(
668
- "#<Kabosu::Morpheme surface=\"{}\" pos_id={} reading=\"{}\" {}..{}>",
669
- self.data.surface,
670
- self.data.pos_id,
671
- self.reading_form(),
672
- self.data.begin_c,
673
- self.data.end_c,
674
- )
354
+ /// Two morphemes are equal when they are the same word of the same
355
+ /// dictionary with the same surface and offsets, whichever list or object
356
+ /// they were read through.
357
+ pub(crate) fn is_equal(ruby: &Ruby, rb_self: &Self, other: Value) -> bool {
358
+ let Ok(other) = <&Self>::try_convert(other) else {
359
+ return false;
360
+ };
361
+ if std::ptr::eq(rb_self, other) {
362
+ return true;
363
+ }
364
+ rb_self.view(ruby, |a| {
365
+ other.view(ruby, |b| {
366
+ a.word_id() == b.word_id()
367
+ && a.begin() == b.begin()
368
+ && a.end() == b.end()
369
+ && Arc::ptr_eq(a.dict(), b.dict())
370
+ && *a.surface() == *b.surface()
371
+ })
372
+ })
675
373
  }
676
374
 
677
- pub(crate) fn to_s(&self) -> &str {
678
- &self.data.surface
375
+ pub(crate) fn hash(ruby: &Ruby, rb_self: &Self) -> u64 {
376
+ let mut hasher = DefaultHasher::new();
377
+ rb_self.view(ruby, |m| {
378
+ (m.word_id().as_raw(), m.begin(), m.end()).hash(&mut hasher);
379
+ m.surface().hash(&mut hasher);
380
+ });
381
+ // Ruby wants a Fixnum.
382
+ hasher.finish() >> 2
383
+ }
384
+
385
+ pub(crate) fn inspect(ruby: &Ruby, rb_self: &Self) -> String {
386
+ rb_self.view(ruby, |m| {
387
+ format!(
388
+ "#<Kabosu::Morpheme surface={:?} pos_id={} reading={:?} {}..{}>",
389
+ &*m.surface(),
390
+ m.part_of_speech_id(),
391
+ m.reading_form(),
392
+ m.begin_c(),
393
+ m.end_c(),
394
+ )
395
+ })
679
396
  }
680
397
  }