Skip to main content

lindera_dependency/
embedded.rs

1//! The models embedded in the build.
2//!
3//! A feature of the crate embeds the model that a release of Lindera
4//! publishes for a dictionary: `embed-model-ipadic` the one for IPADIC,
5//! and `embed-model-unidic`, `embed-model-unidic-cwj` and
6//! `embed-model-unidic-csj` the ones for the three UniDic dictionaries. The
7//! bytes are part of the program, and [`model`] reads them where they are.
8//!
9//! A model is named by its dictionary, and written as the embedded
10//! dictionary is, `embedded://ipadic`: what [`dictionary_of`] reads, for the
11//! command and the token filter, which take a path or this.
12//!
13//! ```
14//! use lindera_dependency::embedded;
15//!
16//! assert_eq!(embedded::dictionary_of("embedded://ipadic"), Some("ipadic"));
17//! assert_eq!(embedded::dictionary_of("models/ipadic.model"), None);
18//!
19//! match embedded::model("ipadic") {
20//!     // A build with `embed-model-ipadic`.
21//!     Ok(model) => assert_eq!(model.dictionary(), "ipadic"),
22//!     // Any other build: the error names the feature.
23//!     Err(error) => assert!(error.to_string().contains("embed-model-ipadic")),
24//! }
25//! ```
26//!
27//! Where the bytes come from at build time is in the model file page of the
28//! documentation: the archive of a release for a build of the published
29//! crate, and a file named by the variable of the model, such as
30//! `LINDERA_BUILD_DEPENDENCY_MODEL_IPADIC_FILE`, for a build from the
31//! repository.
32
33use crate::error::{Error, Result};
34use crate::model::Model;
35
36/// What a model embedded in the build is written with, before the name of
37/// its dictionary.
38pub const SCHEME: &str = "embedded://";
39
40/// The dictionaries a feature of this crate can embed a model for, each
41/// with its feature.
42const KNOWN: [(&str, &str); 4] = [
43    ("ipadic", "embed-model-ipadic"),
44    ("unidic", "embed-model-unidic"),
45    ("unidic-cwj", "embed-model-unidic-cwj"),
46    ("unidic-csj", "embed-model-unidic-csj"),
47];
48
49/// The model for IPADIC, as the build script put it in `OUT_DIR`.
50#[cfg(feature = "embed-model-ipadic")]
51static IPADIC: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dependency-ipadic.model"));
52
53/// The model for UniDic (unidic-mecab 2.1.2).
54#[cfg(feature = "embed-model-unidic")]
55static UNIDIC: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dependency-unidic.model"));
56
57/// The model for UniDic CWJ.
58#[cfg(feature = "embed-model-unidic-cwj")]
59static UNIDIC_CWJ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dependency-unidic-cwj.model"));
60
61/// The model for UniDic CSJ.
62#[cfg(feature = "embed-model-unidic-csj")]
63static UNIDIC_CSJ: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/dependency-unidic-csj.model"));
64
65/// The dictionary of an embedded model, from how it is written.
66///
67/// # Arguments
68///
69/// * `model` - What names a model: a path, or `embedded://<dictionary>`.
70///
71/// # Returns
72///
73/// The name of the dictionary for `embedded://<dictionary>`, and `None` for
74/// anything else, which is then a path.
75pub fn dictionary_of(model: &str) -> Option<&str> {
76    model.strip_prefix(SCHEME)
77}
78
79/// The bytes of the model embedded for a dictionary.
80///
81/// # Arguments
82///
83/// * `dictionary` - The name of the dictionary, as `ipadic`.
84///
85/// # Returns
86///
87/// The bytes of the model file, or an [`Error::Embedded`]: for a dictionary
88/// no feature embeds a model for, for a build without the feature (the
89/// message names it), and for a documentation build, which embeds an empty
90/// file.
91pub fn bytes(dictionary: &str) -> Result<&'static [u8]> {
92    let Some((_, feature)) = KNOWN.iter().find(|(name, _)| *name == dictionary) else {
93        let known: Vec<&str> = KNOWN.iter().map(|(name, _)| *name).collect();
94        return Err(Error::Embedded(format!(
95            "no model can be embedded for the dictionary {dictionary}: there are models for {}",
96            known.join(", ")
97        )));
98    };
99    let embedded: Option<&'static [u8]> = match dictionary {
100        #[cfg(feature = "embed-model-ipadic")]
101        "ipadic" => Some(IPADIC),
102        #[cfg(feature = "embed-model-unidic")]
103        "unidic" => Some(UNIDIC),
104        #[cfg(feature = "embed-model-unidic-cwj")]
105        "unidic-cwj" => Some(UNIDIC_CWJ),
106        #[cfg(feature = "embed-model-unidic-csj")]
107        "unidic-csj" => Some(UNIDIC_CSJ),
108        _ => None,
109    };
110    answer(dictionary, feature, embedded)
111}
112
113/// What [`bytes`] answers for what the build embedded.
114///
115/// # Arguments
116///
117/// * `dictionary` - The name of the dictionary.
118/// * `feature` - The feature that embeds its model.
119/// * `embedded` - The bytes the build embedded, or `None` for a build
120///   without the feature.
121///
122/// # Returns
123///
124/// The bytes, or an [`Error::Embedded`] for none and for an empty file.
125fn answer(
126    dictionary: &str,
127    feature: &str,
128    embedded: Option<&'static [u8]>,
129) -> Result<&'static [u8]> {
130    match embedded {
131        None => Err(Error::Embedded(format!(
132            "the model for {dictionary} is not embedded in this build: it needs a build with the \
133             feature `{feature}` of lindera-dependency, which lindera, its command and its \
134             bindings forward as `embed-dependency-{dictionary}`"
135        ))),
136        Some([]) => Err(Error::Embedded(format!(
137            "the model for {dictionary} is empty in this build: a documentation build embeds no \
138             model"
139        ))),
140        Some(bytes) => Ok(bytes),
141    }
142}
143
144/// The model embedded for a dictionary.
145///
146/// # Arguments
147///
148/// * `dictionary` - The name of the dictionary, as `ipadic`.
149///
150/// # Returns
151///
152/// The model, which reads the bytes of the program in place; or the error
153/// of [`bytes`], or of [`Model::new`] for bytes that are not a model file of
154/// this version.
155pub fn model(dictionary: &str) -> Result<Model<&'static [u8]>> {
156    Model::new(bytes(dictionary)?)
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn a_model_is_named_as_an_embedded_dictionary_is() {
165        assert_eq!(dictionary_of("embedded://ipadic"), Some("ipadic"));
166        assert_eq!(dictionary_of("embedded://"), Some(""));
167        assert_eq!(dictionary_of("ipadic"), None);
168        assert_eq!(dictionary_of("/models/embedded://ipadic"), None);
169        assert_eq!(dictionary_of("file:///models/ipadic.model"), None);
170    }
171
172    #[test]
173    fn a_dictionary_without_a_model_names_the_ones_there_are() {
174        let message = bytes("ko-dic").unwrap_err().to_string();
175        assert!(message.contains("ko-dic"), "{message}");
176        assert!(
177            message.contains("models for ipadic, unidic, unidic-cwj, unidic-csj"),
178            "{message}"
179        );
180        assert!(matches!(model("").unwrap_err(), Error::Embedded(_)));
181    }
182
183    #[cfg(not(feature = "embed-model-ipadic"))]
184    #[test]
185    fn a_build_without_the_feature_names_it() {
186        let message = bytes("ipadic").unwrap_err().to_string();
187        assert!(message.contains("not embedded in this build"), "{message}");
188        assert!(message.contains("`embed-model-ipadic`"), "{message}");
189        assert!(message.contains("`embed-dependency-ipadic`"), "{message}");
190        assert!(matches!(model("ipadic").unwrap_err(), Error::Embedded(_)));
191    }
192
193    #[cfg(feature = "embed-model-ipadic")]
194    #[test]
195    fn the_embedded_model_is_for_its_dictionary() {
196        let model = model("ipadic").expect("embedded model");
197        assert_eq!(model.dictionary(), "ipadic");
198        assert!(model.chunker().is_some());
199        assert!(model.parser().is_some());
200    }
201
202    /// Whether the build has the feature of a dictionary.
203    fn has_feature(dictionary: &str) -> bool {
204        match dictionary {
205            "ipadic" => cfg!(feature = "embed-model-ipadic"),
206            "unidic" => cfg!(feature = "embed-model-unidic"),
207            "unidic-cwj" => cfg!(feature = "embed-model-unidic-cwj"),
208            "unidic-csj" => cfg!(feature = "embed-model-unidic-csj"),
209            other => panic!("no feature for {other}"),
210        }
211    }
212
213    #[test]
214    fn every_model_is_embedded_by_its_feature_and_by_no_other() {
215        for (dictionary, feature) in KNOWN {
216            assert_eq!(feature, format!("embed-model-{dictionary}"));
217            match model(dictionary) {
218                Ok(model) => {
219                    assert!(has_feature(dictionary), "{dictionary}");
220                    // The model of one dictionary is not the one of another.
221                    assert_eq!(model.dictionary(), dictionary);
222                    assert!(model.chunker().is_some() && model.parser().is_some());
223                }
224                Err(error) => {
225                    assert!(!has_feature(dictionary), "{dictionary}: {error}");
226                    let message = error.to_string();
227                    assert!(message.contains(&format!("`{feature}`")), "{message}");
228                    assert!(
229                        message.contains(&format!("`embed-dependency-{dictionary}`")),
230                        "{message}"
231                    );
232                }
233            }
234        }
235    }
236
237    #[test]
238    fn the_build_script_has_a_model_for_every_dictionary() {
239        let script = include_str!("../build.rs");
240        for (dictionary, feature) in KNOWN {
241            let variable = dictionary.to_uppercase().replace('-', "_");
242            for text in [
243                format!("cfg!(feature = \"{feature}\")"),
244                format!("\"lindera-dependency-{dictionary}\""),
245                format!("\"prebuilt-{dictionary}.json\""),
246                format!("\"LINDERA_BUILD_DEPENDENCY_MODEL_{variable}_FILE\""),
247                format!("\"dependency-{dictionary}.model\""),
248            ] {
249                assert!(script.contains(&text), "build.rs has no {text}");
250            }
251        }
252        let count = script.matches("cfg!(feature = \"embed-model-").count();
253        assert_eq!(count, KNOWN.len());
254    }
255
256    #[test]
257    fn the_empty_file_of_a_documentation_build_is_an_error() {
258        let message = answer("ipadic", "embed-model-ipadic", Some(&[]))
259            .unwrap_err()
260            .to_string();
261        assert!(message.contains("is empty in this build"), "{message}");
262        assert_eq!(
263            answer("ipadic", "embed-model-ipadic", Some(b"bytes")).unwrap(),
264            b"bytes"
265        );
266        let message = answer("ipadic", "embed-model-ipadic", None)
267            .unwrap_err()
268            .to_string();
269        assert!(message.contains("`embed-model-ipadic`"), "{message}");
270    }
271
272    #[test]
273    fn the_build_script_pins_the_format_version_this_crate_reads() {
274        let script = include_str!("../build.rs");
275        let line = format!("format_version: {},", crate::model::VERSION);
276        assert_eq!(script.matches("format_version: ").count(), 1);
277        assert!(script.contains(&line), "build.rs has no `{line}`");
278    }
279}