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,113 +1,73 @@
1
- use magnus::{Error, RArray, Ruby};
2
- use std::sync::Arc;
3
- use sudachi::dic::dictionary::JapaneseDictionary;
1
+ use std::ops::Range;
4
2
 
5
- use crate::morpheme::{rb_morpheme_from_data, MorphemeData};
3
+ use sudachi::analysis::morpheme::Morpheme;
6
4
 
7
- /// Group raw `MorphemeData` into jpdb-style chips.
8
- pub(crate) fn group_morphemes_rust(
9
- morphemes: &[MorphemeData],
10
- dict: &Arc<JapaneseDictionary>,
11
- debug: bool,
12
- ) -> Result<RArray, Error> {
13
- let ruby = Ruby::get().unwrap();
14
- let mut groups: Vec<Vec<MorphemeData>> = Vec::with_capacity(morphemes.len());
5
+ use crate::dictionary::Dict;
6
+ use crate::morpheme_list::Analysis;
15
7
 
16
- for m in morphemes {
17
- if let Some(last_group) = groups.last_mut() {
18
- let head = &last_group[0];
19
- let prev = last_group.last().unwrap();
20
- if is_content_word(head.pos_id, dict) && extends_group(m, prev, dict) {
21
- last_group.push(m.clone());
8
+ /// Groups a list into jpdb-style chips: a content word plus the inflectional
9
+ /// suffixes and auxiliaries that cling to it. Returns the index range of each
10
+ /// group; together the ranges cover the list in order.
11
+ pub(crate) fn group_ranges(list: &Analysis) -> Vec<Range<usize>> {
12
+ let mut groups: Vec<Range<usize>> = Vec::with_capacity(list.len());
13
+
14
+ for index in 0..list.len() {
15
+ if let Some(group) = groups.last_mut() {
16
+ let head = list.get(group.start);
17
+ let prev = list.get(index - 1);
18
+ if is_content_word(&head) && extends_group(&list.get(index), &prev) {
19
+ group.end = index + 1;
22
20
  continue;
23
21
  }
24
22
  }
25
- groups.push(vec![m.clone()]);
23
+ groups.push(index..index + 1);
26
24
  }
27
25
 
28
- let result = ruby.ary_new();
29
- for group in groups {
30
- let group_ary = ruby.ary_new();
31
- for data in group {
32
- group_ary.push(rb_morpheme_from_data(data, dict.clone(), debug))?;
33
- }
34
- result.push(group_ary)?;
35
- }
36
- Ok(result)
26
+ groups
37
27
  }
38
28
 
39
- // POS helpers
29
+ fn pos<'a>(m: &'a Morpheme<'_, Dict>, level: usize) -> Option<&'a str> {
30
+ m.part_of_speech().get(level).map(String::as_str)
31
+ }
40
32
 
41
- fn is_content_word(pos_id: u16, dict: &JapaneseDictionary) -> bool {
33
+ fn is_content_word(m: &Morpheme<'_, Dict>) -> bool {
42
34
  !matches!(
43
- dict.grammar()
44
- .pos_components(pos_id)
45
- .first()
46
- .map(|s| s.as_str()),
47
- Some("助詞") | Some("助動詞") | Some("補助記号") | Some("記号") | Some("空白")
35
+ pos(m, 0),
36
+ Some("助詞" | "助動詞" | "補助記号" | "記号" | "空白")
48
37
  )
49
38
  }
50
39
 
51
- fn extends_group(m: &MorphemeData, prev: &MorphemeData, dict: &JapaneseDictionary) -> bool {
52
- let comps = dict.grammar().pos_components(m.pos_id);
53
- let pos0 = comps.first().map(|s| s.as_str());
54
- let pos1 = comps.get(1).map(|s| s.as_str());
55
-
56
- match pos0 {
40
+ fn extends_group(m: &Morpheme<'_, Dict>, prev: &Morpheme<'_, Dict>) -> bool {
41
+ match pos(m, 0) {
57
42
  Some("助動詞") => true,
58
43
  Some("助詞") => {
59
- if is_clause_boundary(m.surface.as_str(), m.pos_id, dict) {
44
+ if is_clause_boundary(m) {
60
45
  return false;
61
46
  }
62
- if pos1 == Some("接続助詞") {
63
- return true;
47
+ match pos(m, 1) {
48
+ Some("接続助詞") => true,
49
+ // 副助詞 clings to a preceding verb/adjective (e.g. たり/だり)
50
+ Some("副助詞") => matches!(pos(prev, 0), Some("動詞" | "形容詞" | "形状詞")),
51
+ _ => false,
64
52
  }
65
- // 副助詞 clings to preceding verb/adjective (e.g. たり/だり)
66
- if pos1 == Some("副助詞") && is_verb_adj_adv(prev.pos_id, dict) {
67
- return true;
68
- }
69
- false
70
53
  }
54
+ // te-form auxiliary chain: て/で + いる/ある/くる/etc. Compound verbs
55
+ // (V+V) are deliberately left apart: the caller looks those up itself.
71
56
  Some("動詞") => {
72
- if pos1 != Some("非自立可能") {
73
- return false;
74
- }
75
- // te-form auxiliary chain: て/で + いる/ある/くる/etc.
76
- let prev_pos0 = dict
77
- .grammar()
78
- .pos_components(prev.pos_id)
79
- .first()
80
- .map(|s| s.as_str());
81
- if prev_pos0 == Some("助詞") && (prev.surface == "て" || prev.surface == "で") {
82
- return true;
83
- }
84
- // compound verb (V+V) intentionally skipped — caller handles DB lookup
85
- false
57
+ pos(m, 1) == Some("非自立可能")
58
+ && pos(prev, 0) == Some("助詞")
59
+ && matches!(&*prev.surface(), "て" | "で")
86
60
  }
87
61
  _ => false,
88
62
  }
89
63
  }
90
64
 
91
- fn is_clause_boundary(surface: &str, pos_id: u16, dict: &JapaneseDictionary) -> bool {
92
- let comps = dict.grammar().pos_components(pos_id);
93
- let pos0 = comps.first().map(|s| s.as_str());
94
- let pos1 = comps.get(1).map(|s| s.as_str());
95
-
96
- if pos0 == Some("助詞") {
97
- if is_clause_boundary_particle(surface) {
98
- return true;
99
- }
100
- // contrastive が (接続助詞) is a boundary, unlike subject が (格助詞)
101
- if pos1 == Some("接続助詞") && surface == "が" {
102
- return true;
103
- }
104
- }
105
- false
106
- }
107
-
108
- fn is_clause_boundary_particle(surface: &str) -> bool {
65
+ /// Whether a particle starts a new clause rather than attaching to the word
66
+ /// before it.
67
+ fn is_clause_boundary(particle: &Morpheme<'_, Dict>) -> bool {
68
+ let surface = particle.surface();
109
69
  matches!(
110
- surface,
70
+ &*surface,
111
71
  "ながら"
112
72
  | "たら"
113
73
  | "ば"
@@ -124,14 +84,6 @@ fn is_clause_boundary_particle(surface: &str) -> bool {
124
84
  | "かどうか"
125
85
  | "とも"
126
86
  )
127
- }
128
-
129
- fn is_verb_adj_adv(pos_id: u16, dict: &JapaneseDictionary) -> bool {
130
- matches!(
131
- dict.grammar()
132
- .pos_components(pos_id)
133
- .first()
134
- .map(|s| s.as_str()),
135
- Some("動詞") | Some("形容詞") | Some("形状詞")
136
- )
87
+ // contrastive が (接続助詞) is a boundary, unlike subject が (格助詞)
88
+ || (pos(particle, 1) == Some("接続助詞") && &*surface == "が")
137
89
  }
@@ -1,3 +1,24 @@
1
+ //! Ruby bindings for sudachi.rs.
2
+ //!
3
+ //! # Threads
4
+ //!
5
+ //! Everything here runs while holding the GVL, except the closures handed to
6
+ //! `nogvl::without_gvl`: the analysis in `Tokenizer#tokenize`, the lexicon scan
7
+ //! in `Dictionary#lookup_all_entries` and sentence splitting. Those closures
8
+ //! see only Rust data that is either exclusively theirs (an analyzer checked
9
+ //! out of its pool, an owned `String`) or immutable and `Sync` (the
10
+ //! dictionary), and never a Ruby object: `without_gvl` requires `Send`, which
11
+ //! magnus values are not.
12
+ //!
13
+ //! Two types are `!Sync` on purpose and rely on the GVL instead:
14
+ //! `RbMorphemeList` (sudachi.rs shares its input buffer through an `Rc`) and
15
+ //! `RbMorpheme` (its String caches are `OnceCell`s). Both are only reachable
16
+ //! through Ruby objects, so only one thread touches them at a time.
17
+ //!
18
+ //! The extension is deliberately NOT marked Ractor-safe: without a GVL shared
19
+ //! by all callers the paragraph above stops being true. Ruby therefore raises
20
+ //! `Ractor::UnsafeError` when a non-main Ractor calls in.
21
+
1
22
  // sudachi::error::SudachiError is a large external enum; boxing it to satisfy
2
23
  // clippy::result_large_err would churn Result signatures throughout the crate
3
24
  // for no real benefit on these cold error paths.
@@ -7,10 +28,10 @@ mod dictionary;
7
28
  mod errors;
8
29
  mod grouping;
9
30
  mod morpheme;
31
+ mod morpheme_list;
10
32
  mod nogvl;
11
33
  mod parsing;
12
34
  mod splitter;
13
- mod token_batch;
14
35
  mod tokenizer;
15
36
  mod user_dict;
16
37
 
@@ -18,28 +39,29 @@ use magnus::{function, method, Error, Module, Object, Ruby};
18
39
 
19
40
  use dictionary::RbDictionary;
20
41
  use morpheme::RbMorpheme;
21
- use splitter::{split_sentences, split_sentences_with_ranges};
22
- use token_batch::RbTokenBatch;
42
+ use morpheme_list::RbMorphemeList;
43
+ use splitter::split_sentences;
44
+
23
45
  use tokenizer::RbTokenizer;
24
46
 
25
47
  #[magnus::init]
26
48
  fn init(ruby: &Ruby) -> Result<(), Error> {
27
49
  let module = ruby.define_module("Kabosu")?;
50
+ errors::define_classes(ruby, module)?;
28
51
 
29
- // Internal sentence splitter APIs. Ruby wraps these with keywords.
30
- module.define_module_function("_split_sentences", function!(split_sentences, 3))?;
31
- module.define_module_function(
32
- "_split_sentences_with_ranges",
33
- function!(split_sentences_with_ranges, 3),
34
- )?;
52
+ module.define_module_function("_split_sentences", function!(split_sentences, 4))?;
35
53
 
36
54
  module.define_module_function("_build_user_dict", function!(user_dict::build_user_dict, 4))?;
37
55
 
56
+ // Methods named with a leading underscore are the native halves of
57
+ // public methods that lib/kabosu.rb defines with keyword arguments and
58
+ // argument checks. Ruby makes them private.
59
+
38
60
  // Kabosu::Dictionary
39
61
  let dict_class = module.define_class("Dictionary", ruby.class_object())?;
40
- dict_class.define_singleton_method("new", function!(RbDictionary::new, 3))?;
41
- dict_class.define_method("lookup", method!(RbDictionary::lookup, 1))?;
42
- dict_class.define_method("create", method!(RbDictionary::create, 3))?;
62
+ dict_class.define_singleton_method("_new", function!(RbDictionary::new, 3))?;
63
+ dict_class.define_method("_tokenizer", method!(RbDictionary::tokenizer, 3))?;
64
+ dict_class.define_method("_lookup", method!(RbDictionary::lookup, 1))?;
43
65
  dict_class.define_method("_each_entry", method!(RbDictionary::each_entry, 0))?;
44
66
  dict_class.define_method(
45
67
  "_lookup_all_entries",
@@ -47,26 +69,50 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
47
69
  )?;
48
70
  dict_class.define_method("_oov_morpheme", method!(RbDictionary::oov_morpheme, 5))?;
49
71
  dict_class.define_method("normalize", method!(RbDictionary::normalize, 1))?;
72
+ dict_class.define_method("pos_list", method!(RbDictionary::pos_list, 0))?;
73
+ dict_class.define_method("pos_of", method!(RbDictionary::pos_of, 1))?;
50
74
 
51
- // Kabosu::TokenBatch (internal lazy token container)
52
- let batch_class = module.define_class("TokenBatch", ruby.class_object())?;
53
- batch_class.define_method("size", method!(RbTokenBatch::size, 0))?;
54
- batch_class.define_method("internal_cost", method!(RbTokenBatch::internal_cost, 0))?;
55
- batch_class.define_method("morpheme_at", method!(RbTokenBatch::morpheme_at, 1))?;
56
- batch_class.define_method("surfaces", method!(RbTokenBatch::surfaces, 0))?;
57
- batch_class.define_method("group_morphemes", method!(RbTokenBatch::group_morphemes, 0))?;
75
+ // Kabosu::NativeMorphemeList: one analysis result, wrapped by the Ruby
76
+ // Kabosu::MorphemeList.
77
+ let list_class = module.define_class("NativeMorphemeList", ruby.class_object())?;
78
+ list_class.define_method("size", method!(RbMorphemeList::size, 0))?;
79
+ list_class.define_method("internal_cost", method!(RbMorphemeList::internal_cost, 0))?;
80
+ list_class.define_method("morpheme_at", method!(RbMorphemeList::morpheme_at, 1))?;
81
+ list_class.define_method("morphemes", method!(RbMorphemeList::morphemes, 0))?;
82
+ list_class.define_method("surfaces", method!(RbMorphemeList::surfaces, 0))?;
83
+ list_class.define_method("reading_forms", method!(RbMorphemeList::reading_forms, 0))?;
84
+ list_class.define_method(
85
+ "dictionary_forms",
86
+ method!(RbMorphemeList::dictionary_forms, 0),
87
+ )?;
88
+ list_class.define_method(
89
+ "normalized_forms",
90
+ method!(RbMorphemeList::normalized_forms, 0),
91
+ )?;
92
+ list_class.define_method(
93
+ "parts_of_speech",
94
+ method!(RbMorphemeList::parts_of_speech, 0),
95
+ )?;
96
+ list_class.define_method("total_costs", method!(RbMorphemeList::total_costs, 0))?;
97
+ list_class.define_method(
98
+ "group_morphemes",
99
+ method!(RbMorphemeList::group_morphemes, 0),
100
+ )?;
58
101
 
59
102
  // Kabosu::Tokenizer
60
103
  let tok_class = module.define_class("Tokenizer", ruby.class_object())?;
61
- tok_class.define_method("tokenize", method!(RbTokenizer::tokenize, 1))?;
104
+ tok_class.define_method("_tokenize", method!(RbTokenizer::tokenize, 1))?;
105
+ tok_class.define_method("_tokenize_batch", method!(RbTokenizer::tokenize_batch, 1))?;
62
106
  tok_class.define_method("mode", method!(RbTokenizer::mode, 0))?;
63
107
  tok_class.define_method("fields", method!(RbTokenizer::fields, 0))?;
64
108
  tok_class.define_method("debug?", method!(RbTokenizer::is_debug, 0))?;
65
- tok_class.define_method("internal_cost", method!(RbTokenizer::internal_cost, 0))?;
66
109
 
67
110
  // Kabosu::Morpheme
68
111
  let morph_class = module.define_class("Morpheme", ruby.class_object())?;
69
112
  morph_class.define_method("surface", method!(RbMorpheme::surface, 0))?;
113
+ // SudachiPy's name for the surface before any projection. kabosu has no
114
+ // projections, so it is the surface.
115
+ morph_class.define_method("raw_surface", method!(RbMorpheme::surface, 0))?;
70
116
  morph_class.define_method("part_of_speech", method!(RbMorpheme::part_of_speech, 0))?;
71
117
  morph_class.define_method(
72
118
  "part_of_speech_id",
@@ -107,9 +153,13 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
107
153
  morph_class.define_method("total_cost", method!(RbMorpheme::total_cost, 0))?;
108
154
  morph_class.define_method("system?", method!(RbMorpheme::is_system, 0))?;
109
155
  morph_class.define_method("user?", method!(RbMorpheme::is_user, 0))?;
110
- morph_class.define_method("split", method!(RbMorpheme::split, 3))?;
156
+ morph_class.define_method("_split", method!(RbMorpheme::split, 2))?;
157
+ morph_class.define_method("length", method!(RbMorpheme::length, 0))?;
158
+ morph_class.define_method("==", method!(RbMorpheme::is_equal, 1))?;
159
+ morph_class.define_method("eql?", method!(RbMorpheme::is_equal, 1))?;
160
+ morph_class.define_method("hash", method!(RbMorpheme::hash, 0))?;
111
161
  morph_class.define_method("inspect", method!(RbMorpheme::inspect, 0))?;
112
- morph_class.define_method("to_s", method!(RbMorpheme::to_s, 0))?;
162
+ morph_class.define_method("to_s", method!(RbMorpheme::surface, 0))?;
113
163
 
114
164
  Ok(())
115
165
  }