1use std::collections::{HashMap, HashSet};
2use std::fmt;
3
4use serde::{Deserialize, Serialize};
5use unicode_normalization::UnicodeNormalization;
6
7use crate::builtin_grammar::GrammarNode;
8use crate::natural_language::canonical_natural_language;
9use crate::read_structured_data_lino;
10use crate::structured_text_parser::parse_natural_language_cst;
11
12const MAXIMUM_SAFE_INTEGER: u64 = (1_u64 << 53) - 1;
13
14#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
16#[serde(rename_all = "camelCase", deny_unknown_fields)]
17pub struct ControlledLanguageUse {
18 pub lemma: String,
19 pub part_of_speech: String,
20 pub meaning: Option<String>,
21}
22
23#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
25#[serde(rename_all = "camelCase", deny_unknown_fields)]
26pub struct ControlledLanguageAnalysis {
27 pub lemma: String,
28 pub part_of_speech: String,
29 pub meaning: Option<String>,
30 #[serde(default)]
31 pub features: Vec<String>,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
36#[serde(rename_all = "camelCase", deny_unknown_fields)]
37pub struct ControlledLanguageReplacement {
38 pub surface: String,
39 pub replacement: String,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
44#[serde(rename_all = "camelCase", deny_unknown_fields)]
45pub struct ControlledLanguageProhibition {
46 pub lemma: String,
47 pub replacement: String,
48 #[serde(default)]
49 pub surface_replacements: Vec<ControlledLanguageReplacement>,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
54#[serde(rename_all = "camelCase", deny_unknown_fields)]
55pub struct ControlledLanguageForm {
56 pub surface: String,
57 pub analyses: Vec<ControlledLanguageAnalysis>,
58}
59
60#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
62#[serde(rename_all = "camelCase", deny_unknown_fields)]
63pub struct ControlledLanguageRules {
64 pub maximum_sentence_words: u64,
65 pub maximum_noun_cluster: u64,
66 pub active_voice: bool,
67 pub one_instruction_per_sentence: bool,
68 #[serde(default)]
69 pub passive_auxiliaries: Vec<String>,
70 #[serde(default)]
71 pub base_verb_instructions: bool,
72 #[serde(default)]
73 pub instruction_connectors: Vec<String>,
74}
75
76#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
78#[serde(rename_all = "camelCase", deny_unknown_fields)]
79pub struct ControlledLanguageProfile {
80 pub language: String,
81 pub approved: Vec<ControlledLanguageUse>,
82 #[serde(default)]
83 pub forbidden: Vec<ControlledLanguageProhibition>,
84 #[serde(default)]
85 pub forms: Vec<ControlledLanguageForm>,
86 pub rules: ControlledLanguageRules,
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct ControlledLanguageWord<'a> {
92 pub text: &'a str,
93 pub start: usize,
94 pub end: usize,
95}
96
97#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
99#[serde(rename_all = "camelCase")]
100pub struct ControlledLanguageDiagnostic {
101 pub rule_id: &'static str,
102 pub start: usize,
103 pub end: usize,
104 pub message: &'static str,
105 pub replacement: Option<String>,
106}
107
108#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct ControlledLanguageError(String);
111
112impl fmt::Display for ControlledLanguageError {
113 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114 formatter.write_str(&self.0)
115 }
116}
117
118impl std::error::Error for ControlledLanguageError {}
119
120fn error(message: impl Into<String>) -> ControlledLanguageError {
121 ControlledLanguageError(message.into())
122}
123
124fn normalize(text: &str) -> String {
125 text.nfc()
126 .collect::<String>()
127 .to_lowercase()
128 .nfc()
129 .collect()
130}
131
132fn require_text(value: &str) -> Result<&str, ControlledLanguageError> {
133 if value.trim().is_empty() {
134 return Err(error("Expected nonempty controlled language text"));
135 }
136 Ok(value)
137}
138
139fn validate_analysis(
140 analysis: &mut ControlledLanguageAnalysis,
141) -> Result<(), ControlledLanguageError> {
142 analysis.lemma = normalize(require_text(&analysis.lemma)?);
143 if !matches!(
144 analysis.part_of_speech.as_str(),
145 "ADJ"
146 | "ADP"
147 | "ADV"
148 | "AUX"
149 | "CCONJ"
150 | "DET"
151 | "INTJ"
152 | "NOUN"
153 | "NUM"
154 | "PART"
155 | "PRON"
156 | "PROPN"
157 | "PUNCT"
158 | "SCONJ"
159 | "SYM"
160 | "VERB"
161 | "X"
162 ) {
163 return Err(error("Expected a Universal Dependencies part of speech"));
164 }
165 if let Some(meaning) = &analysis.meaning {
166 require_text(meaning)?;
167 }
168 for feature in &analysis.features {
169 require_text(feature)?;
170 }
171 Ok(())
172}
173
174struct Prohibition<'a> {
175 replacement: &'a str,
176 surfaces: HashMap<String, &'a str>,
177}
178
179impl Prohibition<'_> {
180 fn replacement(&self, surface: &str) -> &str {
181 self.surfaces
182 .get(surface)
183 .copied()
184 .unwrap_or(self.replacement)
185 }
186}
187
188struct CompiledProfile<'a> {
189 language: &'static str,
190 approved: HashMap<String, Vec<ControlledLanguageAnalysis>>,
191 forbidden: HashMap<String, Prohibition<'a>>,
192 forms: HashMap<String, Vec<ControlledLanguageAnalysis>>,
193 rules: &'a ControlledLanguageRules,
194 passive_auxiliaries: HashSet<String>,
195 instruction_connectors: HashSet<String>,
196}
197
198fn add_unique<T>(
199 entries: &mut HashMap<String, T>,
200 key: String,
201 entry: T,
202) -> Result<(), ControlledLanguageError> {
203 match entries.entry(key) {
204 std::collections::hash_map::Entry::Vacant(slot) => {
205 slot.insert(entry);
206 Ok(())
207 }
208 std::collections::hash_map::Entry::Occupied(slot) => Err(error(format!(
209 "Duplicate controlled language entry: {}",
210 slot.key()
211 ))),
212 }
213}
214
215fn compile_profile(
216 profile: &ControlledLanguageProfile,
217) -> Result<CompiledProfile<'_>, ControlledLanguageError> {
218 let language = canonical_natural_language(&profile.language)
219 .ok_or_else(|| error("Unsupported controlled language"))?;
220 let mut approved: HashMap<String, Vec<_>> = HashMap::new();
221 for entry in &profile.approved {
222 let mut analysis = ControlledLanguageAnalysis {
223 lemma: entry.lemma.clone(),
224 part_of_speech: entry.part_of_speech.clone(),
225 meaning: entry.meaning.clone(),
226 features: Vec::new(),
227 };
228 validate_analysis(&mut analysis)?;
229 approved
230 .entry(analysis.lemma.clone())
231 .or_default()
232 .push(analysis);
233 }
234 let mut forbidden = HashMap::new();
235 for entry in &profile.forbidden {
236 let lemma = normalize(require_text(&entry.lemma)?);
237 let replacement = require_text(&entry.replacement)?;
238 let mut surfaces = HashMap::new();
239 for entry in &entry.surface_replacements {
240 add_unique(
241 &mut surfaces,
242 normalize(require_text(&entry.surface)?),
243 require_text(&entry.replacement)?,
244 )?;
245 }
246 add_unique(
247 &mut forbidden,
248 lemma,
249 Prohibition {
250 replacement,
251 surfaces,
252 },
253 )?;
254 }
255 let mut forms = HashMap::new();
256 for entry in &profile.forms {
257 let mut analyses = entry.analyses.clone();
258 if analyses.is_empty() {
259 return Err(error("Expected at least one analysis for a word form"));
260 }
261 for analysis in &mut analyses {
262 validate_analysis(analysis)?;
263 }
264 add_unique(
265 &mut forms,
266 normalize(require_text(&entry.surface)?),
267 analyses,
268 )?;
269 }
270 let rules = &profile.rules;
271 for limit in [rules.maximum_sentence_words, rules.maximum_noun_cluster] {
272 if !(1..=MAXIMUM_SAFE_INTEGER).contains(&limit) {
273 return Err(error("Expected a positive word limit"));
274 }
275 }
276 let words = |values: &[String]| -> Result<HashSet<String>, ControlledLanguageError> {
277 values
278 .iter()
279 .map(|value| require_text(value).map(normalize))
280 .collect()
281 };
282 Ok(CompiledProfile {
283 language,
284 approved,
285 forbidden,
286 forms,
287 rules,
288 passive_auxiliaries: words(&rules.passive_auxiliaries)?,
289 instruction_connectors: words(&rules.instruction_connectors)?,
290 })
291}
292
293pub fn parse_controlled_language_profile(
295 text: &str,
296) -> Result<ControlledLanguageProfile, ControlledLanguageError> {
297 let document = read_structured_data_lino(text).map_err(error)?;
298 let profile = serde_json::from_value(document)
299 .map_err(|failure| error(format!("Invalid controlled language profile: {failure}")))?;
300 compile_profile(&profile)?;
301 Ok(profile)
302}
303
304pub fn load_controlled_language_profile(
306 language: &str,
307) -> Result<ControlledLanguageProfile, ControlledLanguageError> {
308 let text = match canonical_natural_language(language) {
309 Some("English") => include_str!("data/controlled-language-english.lino"),
310 Some("Russian") => include_str!("data/controlled-language-russian.lino"),
311 _ => {
312 return Err(error(
313 "No bundled controlled language profile for this language",
314 ));
315 }
316 };
317 parse_controlled_language_profile(text)
318}
319
320fn integer(text: &str) -> bool {
321 !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
322}
323
324fn numeric(text: &str) -> bool {
325 text.split_once(['.', ',']).map_or_else(
326 || integer(text),
327 |(left, right)| integer(left) && integer(right),
328 )
329}
330
331fn sentence_words<'a>(source: &'a str, sentence: &GrammarNode) -> Vec<ControlledLanguageWord<'a>> {
332 let mut words: Vec<ControlledLanguageWord<'a>> = Vec::new();
333 let mut preceding_integer = false;
334 for node in sentence.children.iter().filter(|node| node.term == "word") {
335 let text = &source[node.start..node.end];
336 if let Some(preceding) = words.last_mut() {
337 let gap = &source[preceding.end..node.start];
338 let decimal = matches!(gap, "." | ",") && preceding_integer && integer(text);
339 if matches!(gap, "'" | "’" | "-") || decimal {
340 preceding.text = &source[preceding.start..node.end];
341 preceding.end = node.end;
342 preceding_integer = false;
343 continue;
344 }
345 }
346 words.push(ControlledLanguageWord {
347 text,
348 start: node.start,
349 end: node.end,
350 });
351 preceding_integer = integer(text);
352 }
353 words
354}
355
356struct AnalyzedWord<'a> {
357 word: ControlledLanguageWord<'a>,
358 surface: String,
359 analyses: Vec<ControlledLanguageAnalysis>,
360 gap: &'a str,
361}
362
363impl AnalyzedWord<'_> {
364 fn every_analysis(&self, predicate: impl FnMut(&ControlledLanguageAnalysis) -> bool) -> bool {
365 !self.analyses.is_empty() && self.analyses.iter().all(predicate)
366 }
367
368 fn is_noun(&self) -> bool {
369 self.every_analysis(|analysis| matches!(analysis.part_of_speech.as_str(), "NOUN" | "PROPN"))
370 }
371}
372
373fn whitespace(text: &str) -> bool {
374 text.chars().all(char::is_whitespace)
375}
376
377fn add_diagnostic(
378 result: &mut Vec<ControlledLanguageDiagnostic>,
379 rule_id: &'static str,
380 first: &AnalyzedWord<'_>,
381 last: &AnalyzedWord<'_>,
382 message: &'static str,
383 replacement: Option<String>,
384) {
385 result.push(ControlledLanguageDiagnostic {
386 rule_id,
387 start: first.word.start,
388 end: last.word.end,
389 message,
390 replacement,
391 });
392}
393
394fn check_vocabulary(
395 result: &mut Vec<ControlledLanguageDiagnostic>,
396 word: &AnalyzedWord<'_>,
397 profile: &CompiledProfile<'_>,
398) {
399 if numeric(word.word.text) {
400 return;
401 }
402 let direct = profile.forbidden.get(&word.surface);
403 let alternative = word
404 .analyses
405 .first()
406 .and_then(|analysis| profile.forbidden.get(&analysis.lemma));
407 if let Some(forbidden) = direct.or(alternative) {
408 let replacement = forbidden.replacement(&word.surface);
409 let mut alternatives = word.analyses.iter().map(|analysis| {
410 profile
411 .forbidden
412 .get(&analysis.lemma)
413 .map(|entry| entry.replacement(&word.surface))
414 });
415 if direct.is_some() || alternatives.clone().all(|entry| entry.is_some()) {
416 let consensual =
417 direct.is_some() || alternatives.all(|entry| entry == Some(replacement));
418 add_diagnostic(
419 result,
420 "forbidden-word",
421 word,
422 word,
423 "Replace this forbidden word.",
424 consensual.then(|| replacement.to_owned()),
425 );
426 return;
427 }
428 }
429 if word.analyses.iter().any(|analysis| {
430 profile.approved.get(&analysis.lemma).is_some_and(|uses| {
431 uses.iter().any(|usage| {
432 usage.part_of_speech == analysis.part_of_speech
433 && (usage.meaning.is_none() || usage.meaning == analysis.meaning)
434 })
435 })
436 }) {
437 return;
438 }
439 let known = profile.approved.contains_key(&word.surface)
440 || word
441 .analyses
442 .iter()
443 .any(|analysis| profile.approved.contains_key(&analysis.lemma));
444 let (rule, message) = if known {
445 (
446 "unapproved-word-use",
447 "Use this word with an approved part of speech and meaning.",
448 )
449 } else {
450 ("unknown-word", "Use a word from the approved vocabulary.")
451 };
452 add_diagnostic(result, rule, word, word, message, None);
453}
454
455fn feature(analysis: &ControlledLanguageAnalysis, expected: &str) -> bool {
456 analysis.features.iter().any(|value| value == expected)
457}
458
459fn check_sentence(
460 result: &mut Vec<ControlledLanguageDiagnostic>,
461 words: &[AnalyzedWord<'_>],
462 profile: &CompiledProfile<'_>,
463) {
464 let rules = profile.rules;
465 if words.len() as u64 > rules.maximum_sentence_words {
466 add_diagnostic(
467 result,
468 "sentence-length",
469 &words[0],
470 &words[words.len() - 1],
471 "Shorten this sentence.",
472 None,
473 );
474 }
475 let mut auxiliary = None;
476 let mut first_command = None;
477 let mut last_command = None;
478 let mut first_noun = 0;
479 let mut noun_count = 0_u64;
480 let mut base_verb_position = true;
481 for (index, word) in words.iter().enumerate() {
482 check_vocabulary(result, word, profile);
483 let separated = !whitespace(word.gap);
484 if separated {
485 auxiliary = None;
486 }
487 let noun = word.is_noun();
488 if !noun || separated {
489 noun_count = 0;
490 }
491 if noun {
492 if noun_count == 0 {
493 first_noun = index;
494 }
495 noun_count += 1;
496 if noun_count > rules.maximum_noun_cluster
497 && words
498 .get(index + 1)
499 .is_none_or(|next| !whitespace(next.gap) || !next.is_noun())
500 {
501 add_diagnostic(
502 result,
503 "noun-cluster",
504 &words[first_noun],
505 word,
506 "Break up this noun cluster, for example with a preposition.",
507 None,
508 );
509 }
510 }
511 if rules.active_voice {
512 if word.every_analysis(|analysis| {
513 analysis.part_of_speech == "VERB"
514 && (feature(analysis, "Voice=Pass")
515 || (auxiliary.is_some()
516 && feature(analysis, "VerbForm=Part")
517 && feature(analysis, "Tense=Past")))
518 }) {
519 add_diagnostic(
520 result,
521 "active-voice",
522 auxiliary.unwrap_or(word),
523 word,
524 "Use the active voice.",
525 None,
526 );
527 auxiliary = None;
528 } else if word.every_analysis(|analysis| {
529 profile.passive_auxiliaries.contains(&analysis.lemma)
530 && matches!(analysis.part_of_speech.as_str(), "AUX" | "VERB")
531 }) {
532 auxiliary = Some(word);
533 } else if !word.every_analysis(|analysis| {
534 matches!(analysis.part_of_speech.as_str(), "ADV" | "PART")
535 }) {
536 auxiliary = None;
537 }
538 }
539 base_verb_position |=
540 first_command.is_some() && word.gap.strip_prefix([',', ';']).is_some_and(whitespace);
541 if rules.one_instruction_per_sentence
542 && word.every_analysis(|analysis| {
543 analysis.part_of_speech == "VERB"
544 && (feature(analysis, "Mood=Imp")
545 || (rules.base_verb_instructions
546 && base_verb_position
547 && feature(analysis, "VerbForm=Inf")))
548 })
549 {
550 first_command.get_or_insert(index);
551 last_command = Some(index);
552 base_verb_position = false;
553 } else if first_command.is_some() && profile.instruction_connectors.contains(&word.surface)
554 {
555 base_verb_position = true;
556 } else if !word.every_analysis(|analysis| {
557 analysis.part_of_speech == "ADV"
558 || (analysis.part_of_speech == "AUX" && analysis.lemma == "do")
559 || (analysis.part_of_speech == "PART" && feature(analysis, "Polarity=Neg"))
560 }) {
561 base_verb_position = false;
562 }
563 }
564 if let (Some(first), Some(last)) = (first_command, last_command)
565 && first != last
566 {
567 add_diagnostic(
568 result,
569 "one-instruction",
570 &words[first],
571 &words[last],
572 "Write each instruction in its own sentence.",
573 None,
574 );
575 }
576}
577
578pub fn check_controlled_language(
580 source: &str,
581 profile: &ControlledLanguageProfile,
582) -> Result<Vec<ControlledLanguageDiagnostic>, ControlledLanguageError> {
583 check_controlled_language_with_morphology(source, profile, |words| {
584 vec![Vec::new(); words.len()]
585 })
586}
587
588pub fn check_controlled_language_with_morphology(
591 source: &str,
592 profile: &ControlledLanguageProfile,
593 mut analyze_sentence: impl FnMut(
594 &[ControlledLanguageWord<'_>],
595 ) -> Vec<Vec<ControlledLanguageAnalysis>>,
596) -> Result<Vec<ControlledLanguageDiagnostic>, ControlledLanguageError> {
597 let compiled = compile_profile(profile)?;
598 let tree = parse_natural_language_cst(source, compiled.language);
599 if tree.is_error || tree.has_error {
600 return Err(error(
601 "The natural language parser could not analyze the complete text",
602 ));
603 }
604 let mut result = Vec::new();
605 for sentence in tree.children {
606 let words = sentence_words(source, &sentence);
607 if words.is_empty() {
608 continue;
609 }
610 let analyses = analyze_sentence(&words);
611 if analyses.len() != words.len() {
612 return Err(error("Expected one morphology list per sentence word"));
613 }
614 let mut analyzed = Vec::with_capacity(words.len());
615 let mut end = sentence.start;
616 for (word, mut analyses) in words.into_iter().zip(analyses) {
617 let surface = normalize(word.text);
618 if analyses.is_empty() {
619 if let Some(profile_analyses) = compiled.forms.get(&surface) {
620 analyses.clone_from(profile_analyses);
621 } else if let Some(profile_analyses) = compiled.approved.get(&surface) {
622 analyses.clone_from(profile_analyses);
623 for analysis in &mut analyses {
624 analysis.meaning = None;
625 }
626 }
627 } else {
628 for analysis in &mut analyses {
629 validate_analysis(analysis)?;
630 }
631 }
632 analyzed.push(AnalyzedWord {
633 word,
634 surface,
635 analyses,
636 gap: &source[end..word.start],
637 });
638 end = word.end;
639 }
640 check_sentence(&mut result, &analyzed, &compiled);
641 }
642 result.sort_by_key(|finding| (finding.start, finding.end, finding.rule_id));
643 Ok(result)
644}