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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +118 -0
- data/README.md +151 -65
- data/ext/kabosu/src/dictionary.rs +200 -93
- data/ext/kabosu/src/errors.rs +114 -8
- data/ext/kabosu/src/grouping.rs +44 -92
- data/ext/kabosu/src/lib.rs +73 -23
- data/ext/kabosu/src/morpheme.rs +289 -572
- data/ext/kabosu/src/morpheme_list.rs +204 -0
- data/ext/kabosu/src/nogvl.rs +108 -14
- data/ext/kabosu/src/parsing.rs +104 -118
- data/ext/kabosu/src/splitter.rs +62 -102
- data/ext/kabosu/src/tokenizer.rs +298 -140
- data/ext/kabosu/src/user_dict.rs +47 -22
- data/lib/kabosu/morpheme_list.rb +129 -115
- data/lib/kabosu/pos_matcher.rb +119 -28
- data/lib/kabosu/release.rake +7 -10
- data/lib/kabosu/version.rb +1 -1
- data/lib/kabosu.rb +207 -158
- metadata +12 -5
- data/ext/kabosu/src/token_batch.rs +0 -60
|
@@ -1,16 +1,27 @@
|
|
|
1
|
-
use magnus::value::ReprValue;
|
|
2
|
-
use magnus::{Error, RArray, Ruby, Value};
|
|
1
|
+
use magnus::value::{Opaque, ReprValue};
|
|
2
|
+
use magnus::{gc, DataTypeFunctions, Error, Integer, RArray, RString, Ruby, TypedData, Value};
|
|
3
|
+
use std::mem::size_of;
|
|
3
4
|
use std::path::Path;
|
|
4
5
|
use std::sync::Arc;
|
|
6
|
+
use sudachi::analysis::mlist::MorphemeList;
|
|
7
|
+
use sudachi::analysis::node::ResultNode;
|
|
8
|
+
use sudachi::analysis::Node;
|
|
5
9
|
use sudachi::config::{Config, ConfigBuilder};
|
|
6
10
|
use sudachi::dic::dictionary::JapaneseDictionary;
|
|
11
|
+
use sudachi::dic::subset::InfoSubset;
|
|
12
|
+
use sudachi::dic::word_id::WordId;
|
|
13
|
+
use sudachi::dic::DictionaryAccess;
|
|
14
|
+
use sudachi::error::SudachiResult;
|
|
15
|
+
use sudachi::input_text::InputBuffer;
|
|
7
16
|
use sudachi::text_normalizer::TextNormalizer;
|
|
8
17
|
|
|
9
|
-
use crate::errors::
|
|
10
|
-
|
|
11
|
-
data_from_single, dictionary_id_of, rb_morpheme_from_data, MorphemeData, PrefixMap,
|
|
18
|
+
use crate::errors::{
|
|
19
|
+
arg_error, config_error, dictionary_error, dictionary_load_error, kabosu_error, lookup_error,
|
|
12
20
|
};
|
|
13
|
-
use crate::
|
|
21
|
+
use crate::morpheme::{Entry, RbMorpheme};
|
|
22
|
+
use crate::morpheme_list::RbMorphemeList;
|
|
23
|
+
use crate::nogvl::without_gvl;
|
|
24
|
+
use crate::parsing::{parse_mode, parse_subset, push_utf8};
|
|
14
25
|
use crate::tokenizer::RbTokenizer;
|
|
15
26
|
|
|
16
27
|
fn build_dictionary_config(
|
|
@@ -18,8 +29,13 @@ fn build_dictionary_config(
|
|
|
18
29
|
system_dict_path: Option<String>,
|
|
19
30
|
user_dicts: Vec<String>,
|
|
20
31
|
) -> Result<Config, Error> {
|
|
21
|
-
let mut builder =
|
|
22
|
-
.map_err(
|
|
32
|
+
let mut builder =
|
|
33
|
+
ConfigBuilder::from_opt_file(config_path.as_deref().map(Path::new)).map_err(|e| {
|
|
34
|
+
config_error(format_args!(
|
|
35
|
+
"{}: {e}",
|
|
36
|
+
config_path.as_deref().unwrap_or("default config")
|
|
37
|
+
))
|
|
38
|
+
})?;
|
|
23
39
|
|
|
24
40
|
if let Some(system_dict_path) = system_dict_path {
|
|
25
41
|
builder = builder.system_dict(system_dict_path);
|
|
@@ -34,125 +50,215 @@ fn build_dictionary_config(
|
|
|
34
50
|
Ok(builder.push_embedded().build())
|
|
35
51
|
}
|
|
36
52
|
|
|
37
|
-
|
|
53
|
+
/// Every part of speech of a dictionary as a frozen Ruby Array of frozen
|
|
54
|
+
/// Arrays of frozen Strings, indexed by POS id. Built once per dictionary and
|
|
55
|
+
/// shared by reference with everything made from it, so a morpheme's
|
|
56
|
+
/// `part_of_speech` is an array lookup and can never be another dictionary's.
|
|
57
|
+
#[derive(Clone, Copy)]
|
|
58
|
+
pub(crate) struct PosTable(Opaque<RArray>);
|
|
59
|
+
|
|
60
|
+
impl PosTable {
|
|
61
|
+
fn build(ruby: &Ruby, dict: &JapaneseDictionary) -> Result<Self, Error> {
|
|
62
|
+
let pos_list = &dict.grammar().pos_list;
|
|
63
|
+
let table = ruby.ary_new_capa(pos_list.len());
|
|
64
|
+
for pos in pos_list.iter() {
|
|
65
|
+
let components = ruby.ary_new_capa(pos.len());
|
|
66
|
+
for component in pos.iter() {
|
|
67
|
+
// Interned, so the few hundred POS share their component Strings.
|
|
68
|
+
components.push(ruby.str_new(component).to_interned_str())?;
|
|
69
|
+
}
|
|
70
|
+
components.freeze();
|
|
71
|
+
table.push(components)?;
|
|
72
|
+
}
|
|
73
|
+
table.freeze();
|
|
74
|
+
Ok(Self(Opaque::from(table)))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
pub(crate) fn get(&self, ruby: &Ruby, pos_id: u16) -> Result<RArray, Error> {
|
|
78
|
+
ruby.get_inner(self.0).entry(pos_id as isize)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
fn array(&self, ruby: &Ruby) -> RArray {
|
|
82
|
+
ruby.get_inner(self.0)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
pub(crate) fn mark(&self, marker: &gc::Marker) {
|
|
86
|
+
marker.mark(self.0);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// The dictionary handle everything native shares.
|
|
91
|
+
pub(crate) type Dict = Arc<JapaneseDictionary>;
|
|
92
|
+
|
|
93
|
+
#[derive(TypedData)]
|
|
94
|
+
#[magnus(class = "Kabosu::Dictionary", mark, size, free_immediately)]
|
|
38
95
|
pub(crate) struct RbDictionary {
|
|
39
|
-
inner:
|
|
96
|
+
inner: Dict,
|
|
97
|
+
pos_table: PosTable,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
impl DataTypeFunctions for RbDictionary {
|
|
101
|
+
fn mark(&self, marker: &gc::Marker) {
|
|
102
|
+
self.pos_table.mark(marker);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// The dictionary files themselves are memory-mapped, not allocated.
|
|
106
|
+
fn size(&self) -> usize {
|
|
107
|
+
size_of::<Self>() + size_of::<JapaneseDictionary>()
|
|
108
|
+
}
|
|
40
109
|
}
|
|
41
110
|
|
|
42
111
|
impl RbDictionary {
|
|
43
112
|
pub(crate) fn new(
|
|
113
|
+
ruby: &Ruby,
|
|
44
114
|
config_path: Option<String>,
|
|
45
115
|
system_dict_path: Option<String>,
|
|
46
|
-
|
|
116
|
+
user_dicts: Option<Vec<String>>,
|
|
47
117
|
) -> Result<Self, Error> {
|
|
48
|
-
let user_dicts =
|
|
49
|
-
let
|
|
50
|
-
|
|
118
|
+
let user_dicts = user_dicts.unwrap_or_default();
|
|
119
|
+
let load = |user_dicts: Vec<String>| -> Result<SudachiResult<JapaneseDictionary>, Error> {
|
|
120
|
+
let cfg =
|
|
121
|
+
build_dictionary_config(config_path.clone(), system_dict_path.clone(), user_dicts)?;
|
|
122
|
+
Ok(JapaneseDictionary::from_cfg(&cfg))
|
|
123
|
+
};
|
|
124
|
+
let dict = load(user_dicts.clone())?.map_err(|error| {
|
|
125
|
+
// The config is to blame only for a dictionary it named itself:
|
|
126
|
+
// when the system dictionary is its own and the load succeeds
|
|
127
|
+
// without the user dictionaries passed in, those are at fault.
|
|
128
|
+
let dict_from_config = system_dict_path.is_none()
|
|
129
|
+
&& (user_dicts.is_empty() || !matches!(load(Vec::new()), Ok(Ok(_))));
|
|
130
|
+
dictionary_load_error(&error, dict_from_config)
|
|
131
|
+
})?;
|
|
51
132
|
|
|
52
133
|
Ok(Self {
|
|
134
|
+
pos_table: PosTable::build(ruby, &dict)?,
|
|
53
135
|
inner: Arc::new(dict),
|
|
54
136
|
})
|
|
55
137
|
}
|
|
56
138
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
let ruby = Ruby::get().unwrap();
|
|
62
|
-
let ary = ruby.ary_new();
|
|
63
|
-
let lexicon = self.inner.lexicon();
|
|
139
|
+
/// The dictionary itself, for native code that outlives this call.
|
|
140
|
+
pub(crate) fn shared(&self) -> Dict {
|
|
141
|
+
self.inner.clone()
|
|
142
|
+
}
|
|
64
143
|
|
|
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
|
-
head_word_length: info.index_form_length(),
|
|
94
|
-
};
|
|
95
|
-
ary.push(rb_morpheme_from_data(data, self.inner.clone(), false))?;
|
|
144
|
+
fn entry(&self, word_id: WordId) -> SudachiResult<RbMorpheme> {
|
|
145
|
+
let entry = Entry::from_word_id(self.inner.clone(), word_id, InfoSubset::all())?;
|
|
146
|
+
Ok(RbMorpheme::standalone(entry, self.pos_table))
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// Every dictionary entry that is a prefix of `text`, as one list over
|
|
150
|
+
/// `text`. The query goes through the input-text plugins first, exactly as
|
|
151
|
+
/// tokenization does (so カボス and ABC find their entries), and the
|
|
152
|
+
/// input buffer maps each hit back onto the original text. One pass,
|
|
153
|
+
/// linear in the length of the query.
|
|
154
|
+
pub(crate) fn lookup(&self, text: RString) -> Result<RbMorphemeList, Error> {
|
|
155
|
+
let dict = &self.inner;
|
|
156
|
+
let mut input = InputBuffer::new();
|
|
157
|
+
push_utf8(text, input.reset())?;
|
|
158
|
+
input.start_build().map_err(lookup_error)?;
|
|
159
|
+
for plugin in dict.input_text_plugins() {
|
|
160
|
+
plugin.rewrite(&mut input).map_err(lookup_error)?;
|
|
161
|
+
}
|
|
162
|
+
input.build(dict.grammar()).map_err(lookup_error)?;
|
|
163
|
+
|
|
164
|
+
let lexicon = dict.lexicon();
|
|
165
|
+
let mut nodes = Vec::new();
|
|
166
|
+
for hit in lexicon.lookup(input.current().as_bytes(), 0) {
|
|
167
|
+
let info = lexicon.get_word_info(hit.word_id).map_err(lookup_error)?;
|
|
168
|
+
// Both ends fit in 16 bits: the input is capped at 49149 bytes.
|
|
169
|
+
let end_c = input.ch_idx(hit.end) as u16;
|
|
170
|
+
let node = Node::new(0, end_c, 0, 0, 0, hit.word_id);
|
|
171
|
+
nodes.push(ResultNode::new(node, 0, 0, hit.end as u16, info));
|
|
96
172
|
}
|
|
97
173
|
|
|
98
|
-
|
|
174
|
+
let list = MorphemeList::from_components(dict.clone(), input, nodes, InfoSubset::all());
|
|
175
|
+
Ok(RbMorphemeList::new(list, self.pos_table, None))
|
|
99
176
|
}
|
|
100
177
|
|
|
101
178
|
/// Yields every public lexicon entry (system dictionary first, then each
|
|
102
179
|
/// user dictionary) as a standalone morpheme.
|
|
103
180
|
pub(crate) fn each_entry(ruby: &Ruby, rb_self: &Self) -> Result<Value, Error> {
|
|
104
|
-
for
|
|
105
|
-
let
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
let _: Value = ruby.yield_value(
|
|
181
|
+
for word_id in rb_self.inner.lexicon().word_ids() {
|
|
182
|
+
let entry = word_id
|
|
183
|
+
.and_then(|word_id| rb_self.entry(word_id))
|
|
184
|
+
.map_err(dictionary_error)?;
|
|
185
|
+
let _: Value = ruby.yield_value(entry)?;
|
|
109
186
|
}
|
|
110
187
|
Ok(ruby.qnil().as_value())
|
|
111
188
|
}
|
|
112
189
|
|
|
113
190
|
/// Every entry whose normalized headword equals the normalized `surface`,
|
|
114
191
|
/// found by scanning the whole lexicon, so entries that are not indexed for
|
|
115
|
-
/// lookup are found too.
|
|
116
|
-
pub(crate) fn lookup_all_entries(
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
let
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
192
|
+
/// lookup are found too. The scan runs with the GVL released.
|
|
193
|
+
pub(crate) fn lookup_all_entries(
|
|
194
|
+
ruby: &Ruby,
|
|
195
|
+
rb_self: &Self,
|
|
196
|
+
surface: String,
|
|
197
|
+
) -> Result<RArray, Error> {
|
|
198
|
+
let dict: &JapaneseDictionary = &rb_self.inner;
|
|
199
|
+
let word_ids = without_gvl(|| -> SudachiResult<Vec<WordId>> {
|
|
200
|
+
let found = dict.lookup_all_entries_subset(&surface, InfoSubset::HEADWORD)?;
|
|
201
|
+
Ok(found.iter().map(|entry| entry.word_id()).collect())
|
|
202
|
+
})
|
|
203
|
+
.map_err(|stopped| {
|
|
204
|
+
stopped.into_error(|message| {
|
|
205
|
+
lookup_error(format_args!(
|
|
206
|
+
"panic while scanning the dictionary: {message}"
|
|
207
|
+
))
|
|
208
|
+
})
|
|
209
|
+
})?
|
|
210
|
+
.map_err(lookup_error)?;
|
|
211
|
+
|
|
212
|
+
let entries = ruby.ary_new_capa(word_ids.len());
|
|
213
|
+
for word_id in word_ids {
|
|
214
|
+
entries.push(rb_self.entry(word_id).map_err(lookup_error)?)?;
|
|
129
215
|
}
|
|
130
|
-
Ok(
|
|
216
|
+
Ok(entries)
|
|
131
217
|
}
|
|
132
218
|
|
|
133
219
|
pub(crate) fn oov_morpheme(
|
|
134
220
|
&self,
|
|
135
|
-
pos_id:
|
|
221
|
+
pos_id: i64,
|
|
136
222
|
surface: String,
|
|
137
223
|
reading: Option<String>,
|
|
138
224
|
normalized_form: Option<String>,
|
|
139
225
|
dictionary_form: Option<String>,
|
|
140
|
-
) -> Result<
|
|
141
|
-
let
|
|
142
|
-
|
|
143
|
-
.oov_morpheme_with_forms(
|
|
144
|
-
pos_id,
|
|
145
|
-
&surface,
|
|
146
|
-
reading.as_deref().unwrap_or(&surface),
|
|
147
|
-
normalized_form.as_deref().unwrap_or(&surface),
|
|
148
|
-
dictionary_form.as_deref().unwrap_or(&surface),
|
|
149
|
-
)
|
|
150
|
-
.map_err(sudachi_error)?;
|
|
151
|
-
Ok(rb_morpheme_from_data(
|
|
152
|
-
data_from_single(&single),
|
|
226
|
+
) -> Result<RbMorpheme, Error> {
|
|
227
|
+
let invalid_pos = || arg_error(format_args!("invalid part-of-speech id {pos_id}"));
|
|
228
|
+
let entry = Entry::oov(
|
|
153
229
|
self.inner.clone(),
|
|
154
|
-
|
|
155
|
-
|
|
230
|
+
u16::try_from(pos_id).map_err(|_| invalid_pos())?,
|
|
231
|
+
surface.clone(),
|
|
232
|
+
reading.unwrap_or_else(|| surface.clone()),
|
|
233
|
+
normalized_form.unwrap_or_else(|| surface.clone()),
|
|
234
|
+
dictionary_form.unwrap_or(surface),
|
|
235
|
+
)
|
|
236
|
+
.map_err(|_| invalid_pos())?;
|
|
237
|
+
Ok(RbMorpheme::standalone(entry, self.pos_table))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/// Every part of speech of this dictionary, indexed by POS id: the frozen
|
|
241
|
+
/// table itself, not a copy.
|
|
242
|
+
pub(crate) fn pos_list(ruby: &Ruby, rb_self: &Self) -> RArray {
|
|
243
|
+
rb_self.pos_table.array(ruby)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/// The part of speech with this id, or nil when there is none.
|
|
247
|
+
pub(crate) fn pos_of(
|
|
248
|
+
ruby: &Ruby,
|
|
249
|
+
rb_self: &Self,
|
|
250
|
+
pos_id: Value,
|
|
251
|
+
) -> Result<Option<RArray>, Error> {
|
|
252
|
+
// Not converted: 1.5 is not the id 1.
|
|
253
|
+
let pos_id = Integer::from_value(pos_id)
|
|
254
|
+
.ok_or_else(|| Error::new(ruby.exception_type_error(), "pos_id must be an Integer"))?;
|
|
255
|
+
let table = rb_self.pos_table.array(ruby);
|
|
256
|
+
// An id too large for any integer type is, like any other id out of
|
|
257
|
+
// range, not one this dictionary has.
|
|
258
|
+
match pos_id.to_usize() {
|
|
259
|
+
Ok(index) if index < table.len() => table.entry(index as isize).map(Some),
|
|
260
|
+
_ => Ok(None),
|
|
261
|
+
}
|
|
156
262
|
}
|
|
157
263
|
|
|
158
264
|
/// The text after this dictionary's input-text plugins: what tokenization
|
|
@@ -160,19 +266,20 @@ impl RbDictionary {
|
|
|
160
266
|
pub(crate) fn normalize(&self, text: String) -> Result<String, Error> {
|
|
161
267
|
TextNormalizer::from_shared_dictionary(self.inner.clone())
|
|
162
268
|
.normalize(&text)
|
|
163
|
-
.map_err(
|
|
269
|
+
.map_err(kabosu_error)
|
|
164
270
|
}
|
|
165
271
|
|
|
166
|
-
pub(crate) fn
|
|
272
|
+
pub(crate) fn tokenizer(
|
|
167
273
|
&self,
|
|
168
|
-
|
|
274
|
+
mode: Option<Value>,
|
|
169
275
|
fields: Option<Value>,
|
|
170
276
|
debug: Option<bool>,
|
|
171
277
|
) -> Result<RbTokenizer, Error> {
|
|
172
278
|
let subset = parse_subset(fields)?;
|
|
173
|
-
let mode = parse_mode(
|
|
279
|
+
let mode = parse_mode(mode)?;
|
|
174
280
|
Ok(RbTokenizer::new(
|
|
175
281
|
self.inner.clone(),
|
|
282
|
+
self.pos_table,
|
|
176
283
|
mode,
|
|
177
284
|
subset,
|
|
178
285
|
debug.unwrap_or(false),
|
data/ext/kabosu/src/errors.rs
CHANGED
|
@@ -1,12 +1,118 @@
|
|
|
1
|
-
|
|
1
|
+
//! The `Kabosu::Error` hierarchy. The classes are defined here, by the
|
|
2
|
+
//! extension, so native code raises the right one itself; nothing downstream
|
|
3
|
+
//! has to guess a class from an error message.
|
|
2
4
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
+
use std::fmt::Display;
|
|
6
|
+
|
|
7
|
+
use magnus::value::Lazy;
|
|
8
|
+
use magnus::{Error, ExceptionClass, Module, RModule, Ruby};
|
|
9
|
+
use sudachi::dic::description::DescriptionError;
|
|
10
|
+
use sudachi::error::SudachiError;
|
|
11
|
+
|
|
12
|
+
fn kabosu_class(ruby: &Ruby, name: &str) -> ExceptionClass {
|
|
13
|
+
ruby.class_object()
|
|
14
|
+
.const_get::<_, RModule>("Kabosu")
|
|
15
|
+
.and_then(|module| module.const_get(name))
|
|
16
|
+
.unwrap_or_else(|_| panic!("Kabosu::{name} is not defined"))
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
static ERROR: Lazy<ExceptionClass> = Lazy::new(|ruby| kabosu_class(ruby, "Error"));
|
|
20
|
+
static CONFIG_ERROR: Lazy<ExceptionClass> = Lazy::new(|ruby| kabosu_class(ruby, "ConfigError"));
|
|
21
|
+
static DICTIONARY_ERROR: Lazy<ExceptionClass> =
|
|
22
|
+
Lazy::new(|ruby| kabosu_class(ruby, "DictionaryError"));
|
|
23
|
+
static LOOKUP_ERROR: Lazy<ExceptionClass> = Lazy::new(|ruby| kabosu_class(ruby, "LookupError"));
|
|
24
|
+
static TOKENIZATION_ERROR: Lazy<ExceptionClass> =
|
|
25
|
+
Lazy::new(|ruby| kabosu_class(ruby, "TokenizationError"));
|
|
26
|
+
static SENTENCE_SPLIT_ERROR: Lazy<ExceptionClass> =
|
|
27
|
+
Lazy::new(|ruby| kabosu_class(ruby, "SentenceSplitError"));
|
|
28
|
+
|
|
29
|
+
pub(crate) fn define_classes(ruby: &Ruby, module: RModule) -> Result<(), Error> {
|
|
30
|
+
let base = module.define_error("Error", ruby.exception_standard_error())?;
|
|
31
|
+
for name in [
|
|
32
|
+
"ConfigError",
|
|
33
|
+
"DictionaryError",
|
|
34
|
+
"LookupError",
|
|
35
|
+
"TokenizationError",
|
|
36
|
+
"SentenceSplitError",
|
|
37
|
+
] {
|
|
38
|
+
module.define_error(name, base)?;
|
|
39
|
+
}
|
|
40
|
+
Ok(())
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
fn raise(class: &'static Lazy<ExceptionClass>, msg: impl Display) -> Error {
|
|
44
|
+
let ruby = Ruby::get().expect("errors are only built while holding the GVL");
|
|
45
|
+
Error::new(ruby.get_inner(class), msg.to_string())
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
pub(crate) fn arg_error(msg: impl Display) -> Error {
|
|
49
|
+
let ruby = Ruby::get().expect("errors are only built while holding the GVL");
|
|
50
|
+
Error::new(ruby.exception_arg_error(), msg.to_string())
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// A failure with no more specific class, e.g. while normalizing text.
|
|
54
|
+
pub(crate) fn kabosu_error(msg: impl Display) -> Error {
|
|
55
|
+
raise(&ERROR, msg)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
pub(crate) fn config_error(msg: impl Display) -> Error {
|
|
59
|
+
raise(&CONFIG_ERROR, msg)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
pub(crate) fn dictionary_error(msg: impl Display) -> Error {
|
|
63
|
+
raise(&DICTIONARY_ERROR, msg)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
pub(crate) fn lookup_error(msg: impl Display) -> Error {
|
|
67
|
+
raise(&LOOKUP_ERROR, msg)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
pub(crate) fn tokenization_error(msg: impl Display) -> Error {
|
|
71
|
+
raise(&TOKENIZATION_ERROR, msg)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
pub(crate) fn sentence_split_error(msg: impl Display) -> Error {
|
|
75
|
+
raise(&SENTENCE_SPLIT_ERROR, msg)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// The error under any `with_context` wrappers.
|
|
79
|
+
fn root_cause(error: &SudachiError) -> &SudachiError {
|
|
80
|
+
match error {
|
|
81
|
+
SudachiError::ErrWithContext { cause, .. } => root_cause(cause),
|
|
82
|
+
other => other,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/// Classifies a failure to load a dictionary. `dict_from_config` says the
|
|
87
|
+
/// dictionary that failed was named by the config file rather than passed in,
|
|
88
|
+
/// in which case a dictionary that cannot be loaded is the config's fault.
|
|
89
|
+
pub(crate) fn dictionary_load_error(error: &SudachiError, dict_from_config: bool) -> Error {
|
|
90
|
+
match root_cause(error) {
|
|
91
|
+
SudachiError::ConfigError(_) => config_error(error),
|
|
92
|
+
SudachiError::InvalidDescription(DescriptionError::V0Version) => dictionary_error(format!(
|
|
93
|
+
"{error}: a system or user dictionary is in the pre-V1 format, which sudachi.rs 0.7+ \
|
|
94
|
+
cannot read. Install a current SudachiDict (rake kabosu:install) and rebuild user \
|
|
95
|
+
dictionaries against it."
|
|
96
|
+
)),
|
|
97
|
+
_ if dict_from_config => config_error(error),
|
|
98
|
+
_ => dictionary_error(error),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// The message of a caught panic, for errors raised in its place.
|
|
103
|
+
pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
|
|
104
|
+
if let Some(s) = payload.downcast_ref::<&str>() {
|
|
105
|
+
s
|
|
106
|
+
} else if let Some(s) = payload.downcast_ref::<String>() {
|
|
107
|
+
s
|
|
108
|
+
} else {
|
|
109
|
+
"unknown panic"
|
|
110
|
+
}
|
|
5
111
|
}
|
|
6
112
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
113
|
+
/// Runs `func`, turning a panic into an error message instead of letting
|
|
114
|
+
/// magnus raise it as an unrescuable `fatal`.
|
|
115
|
+
pub(crate) fn catch_panic<T>(doing: &str, func: impl FnOnce() -> T) -> Result<T, String> {
|
|
116
|
+
std::panic::catch_unwind(std::panic::AssertUnwindSafe(func))
|
|
117
|
+
.map_err(|panic| format!("panic while {doing}: {}", panic_message(&*panic)))
|
|
12
118
|
}
|