1use crate::content::{ExerciseConfig, ExerciseType};
58use logicaffeine_language::runtime_lexicon::{
59 gerund, past_tense, pluralize, present_3s, LexiconIndex,
60};
61use logicaffeine_language::{compile, compile_all_scopes};
62use rand::seq::SliceRandom;
63use rand::Rng;
64use std::collections::HashMap;
65#[cfg(not(target_arch = "wasm32"))]
66use std::sync::LazyLock;
67#[cfg(target_arch = "wasm32")]
68use std::sync::OnceLock;
69
70#[cfg(not(target_arch = "wasm32"))]
74static LEXICON: LazyLock<LexiconIndex> = LazyLock::new(LexiconIndex::new);
75#[cfg(target_arch = "wasm32")]
76static LEXICON: OnceLock<LexiconIndex> = OnceLock::new();
77
78pub fn lexicon() -> Option<&'static LexiconIndex> {
81 #[cfg(not(target_arch = "wasm32"))]
82 {
83 Some(&LEXICON)
84 }
85 #[cfg(target_arch = "wasm32")]
86 {
87 LEXICON.get()
88 }
89}
90
91pub async fn ensure_lexicon() -> Result<(), String> {
93 #[cfg(target_arch = "wasm32")]
94 if LEXICON.get().is_none() {
95 let text = crate::ui::data_fetch::fetch_static_text("/data/lexicon.json").await?;
96 let index = LexiconIndex::from_json(&text)
97 .map_err(|e| format!("parsing /data/lexicon.json: {e}"))?;
98 let _ = LEXICON.set(index);
99 }
100 Ok(())
101}
102
103pub struct Generator {
108 lexicon: &'static LexiconIndex,
109}
110
111#[derive(Debug, Clone)]
115pub struct Challenge {
116 pub exercise_id: String,
118 pub prompt: String,
120 pub sentence: String,
122 pub answer: AnswerType,
124 pub hint: Option<String>,
126 pub explanation: Option<String>,
128}
129
130#[derive(Debug, Clone)]
132pub enum AnswerType {
133 FreeForm {
135 golden_logic: String,
137 },
138 MultipleChoice {
140 options: Vec<String>,
142 correct_index: usize,
144 },
145 Ambiguity {
147 readings: Vec<String>,
149 },
150}
151
152impl Generator {
153 const MAX_DRAWS: usize = 32;
158
159 pub fn new() -> Self {
161 Self {
162 lexicon: lexicon()
163 .expect("gated: LexiconGate resolves the lexicon before Learn content renders"),
164 }
165 }
166
167 pub fn generate(&self, exercise: &ExerciseConfig, rng: &mut impl Rng) -> Option<Challenge> {
174 match exercise.exercise_type {
175 ExerciseType::Translation => self.generate_translation(exercise, rng),
176 ExerciseType::MultipleChoice => self.generate_multiple_choice(exercise, rng),
177 ExerciseType::Ambiguity => self.generate_ambiguity(exercise, rng),
178 }
179 }
180
181 fn generate_translation(
182 &self,
183 exercise: &ExerciseConfig,
184 rng: &mut impl Rng,
185 ) -> Option<Challenge> {
186 let template = exercise.template.as_ref()?;
187
188 for _ in 0..Self::MAX_DRAWS {
192 let Some(sentence) = self.fill_template(template, &exercise.constraints, rng) else {
193 return None;
194 };
195 let Ok(golden_logic) = compile(&sentence) else {
196 continue;
197 };
198
199 return Some(Challenge {
200 exercise_id: exercise.id.clone(),
201 prompt: exercise.prompt.clone(),
202 sentence,
203 answer: AnswerType::FreeForm { golden_logic },
204 hint: exercise.hint.clone(),
205 explanation: exercise.explanation.clone(),
206 });
207 }
208 None
209 }
210
211 fn generate_multiple_choice(
212 &self,
213 exercise: &ExerciseConfig,
214 rng: &mut impl Rng,
215 ) -> Option<Challenge> {
216 let options = exercise.options.clone()?;
217 let correct_index = exercise.correct?;
218
219 let sentence = if let Some(template) = &exercise.template {
220 self.fill_template(template, &exercise.constraints, rng)?
221 } else {
222 exercise.prompt.clone()
223 };
224
225 Some(Challenge {
226 exercise_id: exercise.id.clone(),
227 prompt: exercise.prompt.clone(),
228 sentence,
229 answer: AnswerType::MultipleChoice {
230 options,
231 correct_index,
232 },
233 hint: exercise.hint.clone(),
234 explanation: exercise.explanation.clone(),
235 })
236 }
237
238 fn generate_ambiguity(
239 &self,
240 exercise: &ExerciseConfig,
241 rng: &mut impl Rng,
242 ) -> Option<Challenge> {
243 let template = exercise.template.as_ref()?;
244
245 for _ in 0..Self::MAX_DRAWS {
246 let Some(sentence) = self.fill_template(template, &exercise.constraints, rng) else {
247 return None;
248 };
249 let Ok(readings) = compile_all_scopes(&sentence) else {
250 continue;
251 };
252
253 return Some(Challenge {
254 exercise_id: exercise.id.clone(),
255 prompt: exercise.prompt.clone(),
256 sentence,
257 answer: AnswerType::Ambiguity { readings },
258 hint: exercise.hint.clone(),
259 explanation: exercise.explanation.clone(),
260 });
261 }
262 None
263 }
264
265 fn fill_template(
266 &self,
267 template: &str,
268 constraints: &HashMap<String, Vec<String>>,
269 rng: &mut impl Rng,
270 ) -> Option<String> {
271 let mut result = template.to_string();
272 let mut used_names: HashMap<String, String> = HashMap::new();
273
274 while let Some(start) = result.find('{') {
275 let end = result[start..].find('}')? + start;
276 let slot = &result[start + 1..end];
277
278 let (slot_type, modifier) = if let Some(colon_pos) = slot.find(':') {
279 (&slot[..colon_pos], Some(&slot[colon_pos + 1..]))
280 } else {
281 (slot, None)
282 };
283
284 let slot_constraints = constraints
285 .get(slot_type)
286 .map(|v| v.as_slice())
287 .unwrap_or(&[]);
288 let word =
289 self.fill_slot(slot_type, slot_constraints, modifier, &mut used_names, rng)?;
290
291 result = format!("{}{}{}", &result[..start], word, &result[end + 1..]);
292 }
293
294 Some(result)
295 }
296
297 fn fill_slot(
298 &self,
299 slot_type: &str,
300 constraints: &[String],
301 modifier: Option<&str>,
302 used_names: &mut HashMap<String, String>,
303 rng: &mut impl Rng,
304 ) -> Option<String> {
305 match slot_type {
306 "ProperName" => {
307 let key = format!("ProperName_{}", used_names.len());
308 if let Some(existing) = used_names.get(&key) {
309 return Some(existing.clone());
310 }
311
312 let proper_nouns = self.lexicon.proper_nouns();
313 let available: Vec<_> = proper_nouns
314 .iter()
315 .filter(|n| !used_names.values().any(|v| v == &n.lemma))
316 .copied()
317 .collect();
318
319 let entry = if !available.is_empty() {
320 available.choose(rng)?
321 } else {
322 proper_nouns.choose(rng)?
323 };
324 let name = entry.lemma.clone();
325 used_names.insert(key, name.clone());
326 Some(name)
327 }
328 "Noun" => {
329 let nouns = if constraints.is_empty() {
330 self.lexicon.common_nouns()
331 } else {
332 let mut filtered = Vec::new();
333 for constraint in constraints {
334 filtered.extend(self.lexicon.nouns_with_feature(constraint));
335 }
336 filtered
337 };
338
339 let entry = nouns.choose(rng)?;
340 let word = entry.lemma.to_lowercase();
341
342 match modifier {
343 Some("Plural") => Some(pluralize(entry)),
344 _ => Some(word),
345 }
346 }
347 "Verb" => {
348 let verbs = if constraints.contains(&"Intransitive".to_string()) {
349 self.lexicon.intransitive_verbs()
350 } else if constraints.contains(&"Transitive".to_string()) {
351 self.lexicon.transitive_verbs()
352 } else {
353 let mut result = Vec::new();
354 for constraint in constraints {
355 result.extend(self.lexicon.verbs_with_feature(constraint));
356 }
357 if result.is_empty() {
358 self.lexicon.intransitive_verbs()
359 } else {
360 result
361 }
362 };
363
364 let entry = verbs.choose(rng)?;
365
366 match modifier {
367 Some("Past") => Some(past_tense(entry)),
368 Some("Gerund") => Some(gerund(entry)),
369 Some("Present3s") => Some(present_3s(entry)),
370 _ => Some(entry.lemma.to_lowercase()),
371 }
372 }
373 "Adjective" => {
374 let adjectives = if constraints.contains(&"Intersective".to_string()) {
375 self.lexicon.intersective_adjectives()
376 } else if constraints.is_empty() {
377 self.lexicon.intersective_adjectives()
378 } else {
379 let mut result = Vec::new();
380 for constraint in constraints {
381 result.extend(self.lexicon.adjectives_with_feature(constraint));
382 }
383 result
384 };
385
386 let entry = adjectives.choose(rng)?;
387 Some(entry.lemma.to_lowercase())
388 }
389 _ => Some("thing".to_string()),
390 }
391 }
392}
393
394impl Default for Generator {
395 fn default() -> Self {
396 Self::new()
397 }
398}
399
400#[cfg(test)]
401#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_web/generator/tests.rs"]
402mod tests;