logicaffeine_lexicon/runtime.rs
1//! Runtime lexicon loading for development builds.
2//!
3//! This module provides dynamic JSON-based lexicon loading as an alternative
4//! to compile-time code generation. Enable with the `dynamic-lexicon` feature.
5//!
6//! # Architecture
7//!
8//! The runtime lexicon trades compile-time safety for faster iteration during
9//! development. Instead of generating Rust code from `lexicon.json` at build time,
10//! this module embeds the JSON and parses it once at runtime when `LexiconIndex::new()`
11//! is called.
12//!
13//! # When to Use
14//!
15//! - **Development**: Use `dynamic-lexicon` for faster edit-compile cycles when
16//! modifying the lexicon.
17//! - **Production**: Disable this feature for compile-time validation and
18//! slightly faster startup.
19//!
20//! # JSON Format
21//!
22//! The lexicon file must contain three top-level arrays:
23//!
24//! - `nouns`: Array of `NounEntry` objects with `lemma`, optional `forms`, `features`, and `sort`
25//! - `verbs`: Array of `VerbEntry` objects with `lemma`, `class`, optional `forms`, and `features`
26//! - `adjectives`: Array of `AdjectiveEntry` objects with `lemma`, `regular`, and `features`
27//!
28//! # Example
29//!
30//! ```
31//! use logicaffeine_lexicon::runtime::LexiconIndex;
32//!
33//! let lexicon = LexiconIndex::new();
34//! let proper_nouns = lexicon.proper_nouns();
35//! assert!(!proper_nouns.is_empty());
36//! ```
37//!
38//! # Type Disambiguation
39//!
40//! This module defines its own `VerbEntry`, `NounEntry`, and `AdjectiveEntry` types
41//! for JSON deserialization. These are distinct from `crate::VerbEntry` and other types
42//! in the parent `crate::types` module, which are used for compile-time generated lookups.
43
44use crate::LEXICON_JSON;
45use rand::seq::SliceRandom;
46use serde::Deserialize;
47use std::collections::HashMap;
48
49/// Deserialized lexicon data from lexicon.json.
50#[derive(Deserialize, Debug)]
51pub struct LexiconData {
52 /// All noun entries including proper nouns and common nouns.
53 pub nouns: Vec<NounEntry>,
54 /// All verb entries with Vendler class and features.
55 pub verbs: Vec<VerbEntry>,
56 /// All adjective entries with gradability info.
57 pub adjectives: Vec<AdjectiveEntry>,
58}
59
60/// A noun entry from the lexicon database.
61#[derive(Deserialize, Debug, Clone)]
62pub struct NounEntry {
63 /// Base form of the noun (e.g., "dog", "Mary").
64 pub lemma: String,
65 /// Irregular inflected forms: "plural" → "mice", etc.
66 #[serde(default)]
67 pub forms: HashMap<String, String>,
68 /// Grammatical/semantic features: "Animate", "Proper", "Countable".
69 #[serde(default)]
70 pub features: Vec<String>,
71 /// Semantic sort for type checking: "Human", "Physical", "Abstract".
72 #[serde(default)]
73 pub sort: Option<String>,
74}
75
76/// A verb entry from the lexicon database.
77#[derive(Deserialize, Debug, Clone)]
78pub struct VerbEntry {
79 /// Base/infinitive form of the verb (e.g., "run", "give").
80 pub lemma: String,
81 /// Vendler Aktionsart class: "State", "Activity", "Accomplishment", "Achievement".
82 pub class: String,
83 /// Irregular inflected forms: "past" → "ran", "participle" → "run".
84 #[serde(default)]
85 pub forms: HashMap<String, String>,
86 /// Grammatical/semantic features: "Transitive", "Ditransitive", "Control".
87 #[serde(default)]
88 pub features: Vec<String>,
89}
90
91/// An adjective entry from the lexicon database.
92#[derive(Deserialize, Debug, Clone)]
93pub struct AdjectiveEntry {
94 /// Base/positive form of the adjective (e.g., "tall", "happy").
95 pub lemma: String,
96 /// Whether comparative/superlative follow regular -er/-est pattern.
97 #[serde(default)]
98 pub regular: bool,
99 /// Semantic features: "Gradable", "Subsective", "NonIntersective".
100 #[serde(default)]
101 pub features: Vec<String>,
102}
103
104/// Index for querying the lexicon by features, sorts, and classes.
105pub struct LexiconIndex {
106 data: LexiconData,
107}
108
109impl LexiconIndex {
110 /// Load and parse the lexicon from the embedded JSON file.
111 pub fn new() -> Self {
112 Self::from_json(LEXICON_JSON).expect("Failed to parse lexicon.json")
113 }
114
115 /// Parse a lexicon from a caller-supplied JSON document (same format as
116 /// `lexicon.json`). This is how targets that fetch the lexicon at runtime —
117 /// the web app pulls it from `/data/lexicon.json` — build an index without
118 /// carrying the embedded copy in their binary.
119 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
120 let data: LexiconData = serde_json::from_str(json)?;
121 Ok(Self { data })
122 }
123
124 /// Get all nouns marked with the "Proper" feature (names).
125 pub fn proper_nouns(&self) -> Vec<&NounEntry> {
126 self.data
127 .nouns
128 .iter()
129 .filter(|n| n.features.iter().any(|f| f == "Proper"))
130 .collect()
131 }
132
133 /// Get all nouns NOT marked as proper (common nouns).
134 pub fn common_nouns(&self) -> Vec<&NounEntry> {
135 self.data
136 .nouns
137 .iter()
138 .filter(|n| !n.features.iter().any(|f| f == "Proper"))
139 .collect()
140 }
141
142 /// Get all nouns with a specific feature (case-insensitive).
143 pub fn nouns_with_feature(&self, feature: &str) -> Vec<&NounEntry> {
144 self.data
145 .nouns
146 .iter()
147 .filter(|n| n.features.iter().any(|f| f.eq_ignore_ascii_case(feature)))
148 .collect()
149 }
150
151 /// Get all nouns with a specific semantic sort (case-insensitive).
152 pub fn nouns_with_sort(&self, sort: &str) -> Vec<&NounEntry> {
153 self.data
154 .nouns
155 .iter()
156 .filter(|n| {
157 n.sort
158 .as_ref()
159 .map(|s| s.eq_ignore_ascii_case(sort))
160 .unwrap_or(false)
161 })
162 .collect()
163 }
164
165 /// Get all verbs with a specific feature (case-insensitive).
166 pub fn verbs_with_feature(&self, feature: &str) -> Vec<&VerbEntry> {
167 self.data
168 .verbs
169 .iter()
170 .filter(|v| v.features.iter().any(|f| f.eq_ignore_ascii_case(feature)))
171 .collect()
172 }
173
174 /// Get all verbs with a specific Vendler class (case-insensitive).
175 pub fn verbs_with_class(&self, class: &str) -> Vec<&VerbEntry> {
176 self.data
177 .verbs
178 .iter()
179 .filter(|v| v.class.eq_ignore_ascii_case(class))
180 .collect()
181 }
182
183 /// Get all verbs that are intransitive (no Transitive/Ditransitive feature).
184 pub fn intransitive_verbs(&self) -> Vec<&VerbEntry> {
185 self.data
186 .verbs
187 .iter()
188 .filter(|v| {
189 !v.features.iter().any(|f| {
190 f.eq_ignore_ascii_case("Transitive") || f.eq_ignore_ascii_case("Ditransitive")
191 })
192 })
193 .collect()
194 }
195
196 /// Returns all verbs that take a direct object.
197 ///
198 /// Includes both transitive verbs (two-place predicates) and ditransitive verbs
199 /// (three-place predicates). Verbs are matched if they have either the `"Transitive"`
200 /// or `"Ditransitive"` feature (case-insensitive).
201 pub fn transitive_verbs(&self) -> Vec<&VerbEntry> {
202 self.data
203 .verbs
204 .iter()
205 .filter(|v| {
206 v.features
207 .iter()
208 .any(|f| f.eq_ignore_ascii_case("Transitive"))
209 || v.features
210 .iter()
211 .any(|f| f.eq_ignore_ascii_case("Ditransitive"))
212 })
213 .collect()
214 }
215
216 /// Returns all adjectives with a specific feature (case-insensitive).
217 ///
218 /// Common features include `"Intersective"`, `"Subsective"`, `"NonIntersective"`,
219 /// and `"Gradable"`. See [`crate::Feature`] for the full list.
220 pub fn adjectives_with_feature(&self, feature: &str) -> Vec<&AdjectiveEntry> {
221 self.data
222 .adjectives
223 .iter()
224 .filter(|a| a.features.iter().any(|f| f.eq_ignore_ascii_case(feature)))
225 .collect()
226 }
227
228 /// Returns all adjectives with intersective semantics.
229 ///
230 /// Intersective adjectives combine with nouns via set intersection:
231 /// "red ball" denotes things that are both red and balls. This is a convenience
232 /// method equivalent to `adjectives_with_feature("Intersective")`.
233 pub fn intersective_adjectives(&self) -> Vec<&AdjectiveEntry> {
234 self.adjectives_with_feature("Intersective")
235 }
236
237 /// Selects a random proper noun from the lexicon.
238 ///
239 /// Returns `None` if the lexicon contains no proper nouns.
240 pub fn random_proper_noun(&self, rng: &mut impl rand::Rng) -> Option<&NounEntry> {
241 self.proper_nouns().choose(rng).copied()
242 }
243
244 /// Selects a random common noun from the lexicon.
245 ///
246 /// Returns `None` if the lexicon contains no common nouns.
247 pub fn random_common_noun(&self, rng: &mut impl rand::Rng) -> Option<&NounEntry> {
248 self.common_nouns().choose(rng).copied()
249 }
250
251 /// Selects a random verb from the lexicon.
252 ///
253 /// Returns `None` if the lexicon contains no verbs.
254 pub fn random_verb(&self, rng: &mut impl rand::Rng) -> Option<&VerbEntry> {
255 self.data.verbs.choose(rng)
256 }
257
258 /// Selects a random intransitive verb from the lexicon.
259 ///
260 /// Returns `None` if the lexicon contains no intransitive verbs.
261 pub fn random_intransitive_verb(&self, rng: &mut impl rand::Rng) -> Option<&VerbEntry> {
262 self.intransitive_verbs().choose(rng).copied()
263 }
264
265 /// Selects a random transitive or ditransitive verb from the lexicon.
266 ///
267 /// Returns `None` if the lexicon contains no transitive verbs.
268 pub fn random_transitive_verb(&self, rng: &mut impl rand::Rng) -> Option<&VerbEntry> {
269 self.transitive_verbs().choose(rng).copied()
270 }
271
272 /// Selects a random adjective from the lexicon.
273 ///
274 /// Returns `None` if the lexicon contains no adjectives.
275 pub fn random_adjective(&self, rng: &mut impl rand::Rng) -> Option<&AdjectiveEntry> {
276 self.data.adjectives.choose(rng)
277 }
278
279 /// Selects a random intersective adjective from the lexicon.
280 ///
281 /// Returns `None` if the lexicon contains no intersective adjectives.
282 pub fn random_intersective_adjective(
283 &self,
284 rng: &mut impl rand::Rng,
285 ) -> Option<&AdjectiveEntry> {
286 self.intersective_adjectives().choose(rng).copied()
287 }
288}
289
290/// Creates a [`LexiconIndex`] by loading and parsing the embedded lexicon JSON.
291///
292/// Equivalent to calling [`LexiconIndex::new()`].
293impl Default for LexiconIndex {
294 fn default() -> Self {
295 Self::new()
296 }
297}
298
299/// Computes the plural form of a noun.
300///
301/// Returns the irregular plural if one is defined in the noun's `forms` map under
302/// the `"plural"` key. Otherwise, applies English pluralization rules:
303///
304/// - Sibilants (`-s`, `-x`, `-ch`, `-sh`) → append `-es` ("box" → "boxes")
305/// - Consonant + `y` → replace `y` with `-ies` ("city" → "cities")
306/// - Vowel + `y` (`-ay`, `-ey`, `-oy`, `-uy`) → append `-s` ("day" → "days")
307/// - Default → append `-s` ("dog" → "dogs")
308///
309/// # Arguments
310///
311/// * `noun` - The noun entry containing the lemma and optional irregular forms.
312///
313/// # Examples
314///
315/// ```
316/// use logicaffeine_lexicon::runtime::{NounEntry, pluralize};
317/// use std::collections::HashMap;
318///
319/// // Regular noun
320/// let dog = NounEntry {
321/// lemma: "dog".to_string(),
322/// forms: HashMap::new(),
323/// features: vec![],
324/// sort: None,
325/// };
326/// assert_eq!(pluralize(&dog), "dogs");
327///
328/// // Irregular noun
329/// let mouse = NounEntry {
330/// lemma: "mouse".to_string(),
331/// forms: [("plural".to_string(), "mice".to_string())].into(),
332/// features: vec![],
333/// sort: None,
334/// };
335/// assert_eq!(pluralize(&mouse), "mice");
336/// ```
337pub fn pluralize(noun: &NounEntry) -> String {
338 if let Some(plural) = noun.forms.get("plural") {
339 plural.clone()
340 } else {
341 let lemma = noun.lemma.to_lowercase();
342 if lemma.ends_with('s')
343 || lemma.ends_with('x')
344 || lemma.ends_with("ch")
345 || lemma.ends_with("sh")
346 {
347 format!("{}es", lemma)
348 } else if lemma.ends_with('y')
349 && !lemma.ends_with("ay")
350 && !lemma.ends_with("ey")
351 && !lemma.ends_with("oy")
352 && !lemma.ends_with("uy")
353 {
354 format!("{}ies", &lemma[..lemma.len() - 1])
355 } else {
356 format!("{}s", lemma)
357 }
358 }
359}
360
361/// Computes the third-person singular present tense form of a verb.
362///
363/// Returns the irregular form if one is defined in the verb's `forms` map under
364/// the `"present3s"` key. Otherwise, applies English conjugation rules:
365///
366/// - Sibilants and `-o` (`-s`, `-x`, `-ch`, `-sh`, `-o`) → append `-es` ("go" → "goes")
367/// - Consonant + `y` → replace `y` with `-ies` ("fly" → "flies")
368/// - Vowel + `y` (`-ay`, `-ey`, `-oy`, `-uy`) → append `-s` ("play" → "plays")
369/// - Default → append `-s` ("run" → "runs")
370///
371/// # Arguments
372///
373/// * `verb` - The verb entry containing the lemma and optional irregular forms.
374///
375/// # Examples
376///
377/// ```
378/// use logicaffeine_lexicon::runtime::{VerbEntry, present_3s};
379/// use std::collections::HashMap;
380///
381/// let run = VerbEntry {
382/// lemma: "run".to_string(),
383/// class: "Activity".to_string(),
384/// forms: HashMap::new(),
385/// features: vec![],
386/// };
387/// assert_eq!(present_3s(&run), "runs");
388///
389/// let go = VerbEntry {
390/// lemma: "go".to_string(),
391/// class: "Activity".to_string(),
392/// forms: [("present3s".to_string(), "goes".to_string())].into(),
393/// features: vec![],
394/// };
395/// assert_eq!(present_3s(&go), "goes");
396/// ```
397pub fn present_3s(verb: &VerbEntry) -> String {
398 match verb.forms.get("present3s") {
399 Some(form) => form.clone(),
400 None => crate::present_3s_of(&verb.lemma),
401 }
402}
403
404/// Computes the past tense form of a verb.
405///
406/// Returns the irregular form if one is defined in the verb's `forms` map under
407/// the `"past"` key. Otherwise, applies English past tense rules:
408///
409/// - Ends in `-e` → append `-d` ("love" → "loved")
410/// - Consonant + `y` → replace `y` with `-ied` ("carry" → "carried")
411/// - Vowel + `y` (`-ay`, `-ey`, `-oy`, `-uy`) → append `-ed` ("play" → "played")
412/// - Default → append `-ed` ("walk" → "walked")
413///
414/// # Arguments
415///
416/// * `verb` - The verb entry containing the lemma and optional irregular forms.
417///
418/// # Examples
419///
420/// ```
421/// use logicaffeine_lexicon::runtime::{VerbEntry, past_tense};
422/// use std::collections::HashMap;
423///
424/// let walk = VerbEntry {
425/// lemma: "walk".to_string(),
426/// class: "Activity".to_string(),
427/// forms: HashMap::new(),
428/// features: vec![],
429/// };
430/// assert_eq!(past_tense(&walk), "walked");
431///
432/// let run = VerbEntry {
433/// lemma: "run".to_string(),
434/// class: "Activity".to_string(),
435/// forms: [("past".to_string(), "ran".to_string())].into(),
436/// features: vec![],
437/// };
438/// assert_eq!(past_tense(&run), "ran");
439/// ```
440pub fn past_tense(verb: &VerbEntry) -> String {
441 if let Some(form) = verb.forms.get("past") {
442 form.clone()
443 } else {
444 let lemma = verb.lemma.to_lowercase();
445 if lemma.ends_with('e') {
446 format!("{}d", lemma)
447 } else if lemma.ends_with('y')
448 && !lemma.ends_with("ay")
449 && !lemma.ends_with("ey")
450 && !lemma.ends_with("oy")
451 && !lemma.ends_with("uy")
452 {
453 format!("{}ied", &lemma[..lemma.len() - 1])
454 } else {
455 format!("{}ed", lemma)
456 }
457 }
458}
459
460/// Computes the gerund (present participle) form of a verb.
461///
462/// Returns the irregular form if one is defined in the verb's `forms` map under
463/// the `"gerund"` key. Otherwise, applies English gerund formation rules:
464///
465/// - Ends in `-e` (but not `-ee`) → drop `e` and append `-ing` ("make" → "making")
466/// - Ends in `-ee` → append `-ing` without dropping ("see" → "seeing")
467/// - Default → append `-ing` ("run" → "running")
468///
469/// Note: This implementation does not handle consonant doubling (e.g., "run" → "running"
470/// should double the 'n', but this produces "runing"). For accurate results with such
471/// verbs, provide an irregular form in the `forms` map.
472///
473/// # Arguments
474///
475/// * `verb` - The verb entry containing the lemma and optional irregular forms.
476///
477/// # Examples
478///
479/// ```
480/// use logicaffeine_lexicon::runtime::{VerbEntry, gerund};
481/// use std::collections::HashMap;
482///
483/// let make = VerbEntry {
484/// lemma: "make".to_string(),
485/// class: "Activity".to_string(),
486/// forms: HashMap::new(),
487/// features: vec![],
488/// };
489/// assert_eq!(gerund(&make), "making");
490///
491/// let see = VerbEntry {
492/// lemma: "see".to_string(),
493/// class: "Activity".to_string(),
494/// forms: HashMap::new(),
495/// features: vec![],
496/// };
497/// assert_eq!(gerund(&see), "seeing");
498/// ```
499pub fn gerund(verb: &VerbEntry) -> String {
500 if let Some(form) = verb.forms.get("gerund") {
501 form.clone()
502 } else {
503 let lemma = verb.lemma.to_lowercase();
504 if lemma.ends_with('e') && !lemma.ends_with("ee") {
505 format!("{}ing", &lemma[..lemma.len() - 1])
506 } else {
507 format!("{}ing", lemma)
508 }
509 }
510}
511
512#[cfg(test)]
513#[path = "../../logicaffeine_tests/unit/logicaffeine_lexicon/runtime/tests.rs"]
514mod tests;