1use std::collections::HashSet;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum SymbolKind {
11 Quantifier,
12 Connective,
13 Variable,
14 Predicate,
15 Constant,
16 Modal,
17 Identity,
18 Punctuation,
19 Temporal,
20 Role,
21}
22
23impl SymbolKind {
24 pub fn label(&self) -> &'static str {
25 match self {
26 SymbolKind::Quantifier => "Quantifier",
27 SymbolKind::Connective => "Connective",
28 SymbolKind::Variable => "Variable",
29 SymbolKind::Predicate => "Predicate",
30 SymbolKind::Constant => "Constant",
31 SymbolKind::Modal => "Modal",
32 SymbolKind::Identity => "Identity",
33 SymbolKind::Punctuation => "Punctuation",
34 SymbolKind::Temporal => "Temporal",
35 SymbolKind::Role => "Role",
36 }
37 }
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
42pub struct SymbolEntry {
43 pub symbol: String,
44 pub kind: SymbolKind,
45 pub description: String,
47 pub usage: String,
49}
50
51pub fn extract_symbols(logic: &str) -> Vec<SymbolEntry> {
53 extract_symbols_for(logic, &crate::formatter::UnicodeFormatter)
54}
55
56pub fn extract_symbols_for(logic: &str, view: &impl crate::formatter::LogicFormatter) -> Vec<SymbolEntry> {
59 let notation = Notation::of(view);
60 let mut entries = Vec::new();
61 let mut seen: HashSet<String> = HashSet::new();
62 extract_fixed_symbols(logic, ¬ation, &mut entries, &mut seen);
63 extract_applications(logic, ¬ation, &mut entries, &mut seen);
64 extract_variables(logic, ¬ation, &mut entries, &mut seen);
65 extract_constants(logic, ¬ation, &mut entries, &mut seen);
66 entries
67}
68
69const IDENTITY: (&str, &str) = ("=", "… is the same individual as …");
71const OUGHT: (&str, &str) = ("O", "it ought to be that …");
73
74pub fn notation() -> Vec<SymbolEntry> {
77 let notation = Notation::of(&crate::formatter::UnicodeFormatter);
78 let entry = |symbol: &str, kind: SymbolKind, meaning: &str| SymbolEntry {
79 usage: symbol.to_string(),
80 symbol: symbol.to_string(),
81 kind,
82 description: meaning.to_string(),
83 };
84 notation
85 .fixed
86 .iter()
87 .filter(|(symbol, _, _)| !symbol.is_empty())
88 .map(|(symbol, kind, meaning)| entry(symbol, *kind, meaning))
89 .chain([entry(IDENTITY.0, SymbolKind::Identity, IDENTITY.1), entry(OUGHT.0, SymbolKind::Modal, OUGHT.1)])
90 .collect()
91}
92
93struct Notation {
95 fixed: Vec<(String, SymbolKind, &'static str)>,
97 binders: Vec<(String, &'static str)>,
99 operators: Vec<(&'static str, &'static str, &'static str)>,
102}
103
104impl Notation {
105 fn of(view: &impl crate::formatter::LogicFormatter) -> Notation {
106 let spelled = |s: &str| s.trim().to_string();
107 let (every, some) = (spelled(&view.universal()), spelled(&view.existential()));
108 Notation {
109 fixed: vec![
110 (every.clone(), SymbolKind::Quantifier, "for every …"),
111 (some.clone(), SymbolKind::Quantifier, "there is at least one …"),
112 ("∃!".to_string(), SymbolKind::Quantifier, "there is exactly one …"),
113 ("MOST".to_string(), SymbolKind::Quantifier, "most …"),
114 ("FEW".to_string(), SymbolKind::Quantifier, "few …"),
115 (spelled(view.and()), SymbolKind::Connective, "… and …"),
116 (spelled(view.or()), SymbolKind::Connective, "… or …"),
117 (spelled(view.implies()), SymbolKind::Connective, "if … then …"),
118 (spelled(view.iff()), SymbolKind::Connective, "… exactly when …"),
119 (spelled(view.not()), SymbolKind::Connective, "it is not the case that …"),
120 (spelled(view.necessity()), SymbolKind::Modal, "necessarily …"),
121 (spelled(view.possibility()), SymbolKind::Modal, "possibly …"),
122 ],
123 binders: vec![(every, "∀"), (some, "∃")],
124 operators: vec![
125 (view.past(), "past tense — it was the case that …", "lies in the past"),
126 (view.future(), "future tense — it will be the case that …", "lies in the future"),
127 (view.progressive(), "progressive — … is going on", "is going on"),
128 (view.perfect(), "perfect — … has been completed", "has been completed"),
129 (view.habitual(), "habitual — … happens as a habit", "happens as a habit"),
130 (view.iterative(), "iterative — … happens again and again", "happens again and again"),
131 ],
132 }
133 }
134
135 fn is_fixed_word(&self, name: &str) -> bool {
137 self.fixed.iter().any(|(symbol, _, _)| symbol == name)
138 }
139}
140
141fn mentions(logic: &str, symbol: &str) -> bool {
144 if !symbol.chars().any(char::is_alphabetic) {
145 return logic.contains(symbol);
146 }
147 logic.match_indices(symbol).any(|(at, _)| {
148 let before = logic[..at].chars().next_back();
149 let after = logic[at + symbol.len()..].chars().next();
150 !before.is_some_and(|c| c.is_alphanumeric()) && !after.is_some_and(|c| c.is_alphanumeric())
151 })
152}
153
154fn extract_fixed_symbols(logic: &str, notation: &Notation, entries: &mut Vec<SymbolEntry>, seen: &mut HashSet<String>) {
156 let mut add = |symbol: &str, kind: SymbolKind, description: &str| {
157 if seen.insert(symbol.to_string()) {
158 entries.push(SymbolEntry { usage: symbol.to_string(), symbol: symbol.to_string(), kind, description: description.to_string() });
159 }
160 };
161 for (symbol, kind, meaning) in ¬ation.fixed {
162 if !symbol.is_empty() && mentions(logic, symbol) {
163 add(symbol, *kind, meaning);
164 }
165 }
166 if logic.contains("O_") {
167 add(OUGHT.0, SymbolKind::Modal, OUGHT.1);
168 }
169 if logic.contains(" = ") {
170 add(IDENTITY.0, SymbolKind::Identity, IDENTITY.1);
171 }
172}
173
174fn wraps_formula(chars: &[char], open: usize, notation: &Notation) -> bool {
177 let mut i = open + 1;
178 while i < chars.len() && chars[i] == ' ' {
179 i += 1;
180 }
181 let rest: String = chars[i..].iter().take(16).collect();
182 if rest.starts_with('(') || notation.fixed.iter().any(|(symbol, kind, _)| {
183 !symbol.is_empty() && *kind != SymbolKind::Connective && rest.starts_with(symbol.as_str())
184 }) || rest.starts_with('¬') || rest.starts_with("Not ") {
185 return true;
186 }
187 match chars.get(i) {
188 Some(c) if c.is_ascii_uppercase() => {
189 while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
190 i += 1;
191 }
192 chars.get(i) == Some(&'(')
193 }
194 _ => false,
195 }
196}
197
198fn arguments(chars: &[char], open: usize) -> (Vec<String>, usize) {
200 let mut depth = 0;
201 let mut args = Vec::new();
202 let mut current = String::new();
203 let mut i = open;
204 while i < chars.len() {
205 let c = chars[i];
206 match c {
207 '(' => {
208 depth += 1;
209 if depth > 1 {
210 current.push(c);
211 }
212 }
213 ')' => {
214 depth -= 1;
215 if depth == 0 {
216 args.push(current.trim().to_string());
217 return (args, i + 1);
218 }
219 current.push(c);
220 }
221 ',' if depth == 1 => args.push(std::mem::take(&mut current).trim().to_string()),
222 _ => current.push(c),
223 }
224 i += 1;
225 }
226 (args, i)
227}
228
229fn is_event(term: &str) -> bool {
231 term.starts_with('e') && term[1..].chars().all(|c| c.is_ascii_digit())
232}
233
234fn is_world(term: &str) -> bool {
236 term.len() > 1 && term.starts_with('w') && term[1..].chars().all(|c| c.is_ascii_digit())
237}
238
239fn article(noun: &str) -> &'static str {
240 if noun.starts_with(|c: char| "aeiou".contains(c)) { "an" } else { "a" }
241}
242
243fn reading(name: &str, args: &[String]) -> String {
247 use crate::lexicon::{analyze_word, LexiconTrait, StaticLexicon, WordAnalysis};
248 let lower = name.to_lowercase();
249 let noun = || match analyze_word(&lower) {
250 Some(WordAnalysis::Noun(meta)) => Some(meta.lemma.to_lowercase()),
251 Some(WordAnalysis::DerivedNoun { lemma, .. }) => Some(lemma.to_lowercase()),
252 None => None,
253 };
254 let verb = StaticLexicon.lookup_verb(&lower).map(|meta| meta.lemma.to_lowercase());
255 match (args, verb) {
256 ([], _) => format!("the proposition {name}"),
257 ([e], Some(verb)) if is_event(e) => format!("{e} is a {verb} event"),
258 ([a], Some(verb)) => format!("{a} {}", logicaffeine_lexicon::present_3s_of(&verb)),
259 ([a, rest @ ..], Some(verb)) => format!("{a} {} {}", logicaffeine_lexicon::present_3s_of(&verb), rest.join(" ")),
260 ([a], None) if StaticLexicon.lookup_adjective(&lower).is_some() => format!("{a} is {lower}"),
261 ([e], None) if lower.ends_with("ly") && noun().is_none() && is_event(e) => format!("{e} happens {lower}"),
264 ([a], None) if lower.ends_with("ly") && noun().is_none() => format!("{a} does it {lower}"),
265 ([a], None) => {
266 let noun = noun().unwrap_or(lower);
267 format!("{a} is {} {noun}", article(&noun))
268 }
269 (args, None) => format!("{} stand in the relation {name}", args.join(", ")),
270 }
271}
272
273fn extract_applications(logic: &str, notation: &Notation, entries: &mut Vec<SymbolEntry>, seen: &mut HashSet<String>) {
277 use crate::ast::ThematicRole;
278 let chars: Vec<char> = logic.chars().collect();
279 let mut i = 0;
280 while i < chars.len() {
281 if chars[i].is_ascii_uppercase() && (i == 0 || !chars[i - 1].is_ascii_alphanumeric()) {
282 let start = i;
283 while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
284 i += 1;
285 }
286 if i < chars.len() && chars[i] == '(' {
287 let name: String = chars[start..i].iter().collect();
288 if notation.is_fixed_word(&name) {
289 continue;
290 }
291 let (written, _) = arguments(&chars, i);
292 let args: Vec<String> = written.iter().filter(|a| !is_world(a)).cloned().collect();
293 let operator = notation.operators.iter().find(|(op, _, _)| *op == name);
294 let role = ThematicRole::ALL.iter().any(|r| r.name() == name) && args.len() >= 2;
295 let of_event = operator.map(|(_, _, of_event)| *of_event).or(match name.as_str() {
297 "Past" => Some("lies in the past"),
298 "Future" => Some("lies in the future"),
299 _ => None,
300 });
301 let placed = match (of_event, args.as_slice()) {
302 (Some(of_event), [e]) if is_event(e) => Some(format!("{e} {of_event}")),
303 _ => None,
304 };
305 let (kind, usage, description) = match (operator.filter(|_| wraps_formula(&chars, i, notation)), placed, role) {
306 (Some((_, meaning, _)), _, _) => (SymbolKind::Temporal, format!("{name}(…)"), meaning.to_string()),
307 (None, Some(placed), _) => (SymbolKind::Temporal, format!("{name}({})", written.join(", ")), placed),
308 (None, None, true) => (
309 SymbolKind::Role,
310 format!("{name}({})", written.join(", ")),
311 format!("{} is the {} of {}", args[1..].join(", "), name.to_lowercase(), args[0]),
312 ),
313 (None, None, false) => (SymbolKind::Predicate, format!("{name}({})", written.join(", ")), reading(&name, &args)),
314 };
315 if seen.insert(format!("{kind:?}_{name}")) {
316 entries.push(SymbolEntry { usage, symbol: name, kind, description });
317 }
318 continue;
319 }
320 continue;
321 }
322 i += 1;
323 }
324}
325
326fn extract_variables(logic: &str, notation: &Notation, entries: &mut Vec<SymbolEntry>, seen: &mut HashSet<String>) {
327 for (binder, quantifier) in ¬ation.binders {
330 for (at, _) in logic.match_indices(binder.as_str()) {
331 let after = logic[at + binder.len()..].trim_start_matches(|c: char| c == ' ' || c == '!' || c == '=' || c == '≥' || c == '≤' || c.is_ascii_digit());
332 let var: String = after
333 .chars()
334 .take(1)
335 .filter(char::is_ascii_lowercase)
336 .chain(after.chars().skip(1).take_while(char::is_ascii_digit))
337 .collect();
338 if var.is_empty() || after.chars().nth(var.len()).is_some_and(|c| c.is_ascii_alphabetic()) {
339 continue;
340 }
341 let description = match (is_event(&var), *quantifier) {
342 (true, _) => format!("an event, bound by {binder}"),
343 (false, "∀") => format!("any individual, bound by {binder}"),
344 (false, _) => format!("some individual, bound by {binder}"),
345 };
346 if seen.insert(format!("var_{var}")) {
347 entries.push(SymbolEntry { usage: var.clone(), symbol: var, kind: SymbolKind::Variable, description });
348 }
349 }
350 }
351}
352
353fn extract_constants(logic: &str, notation: &Notation, entries: &mut Vec<SymbolEntry>, seen: &mut HashSet<String>) {
354 let chars: Vec<char> = logic.chars().collect();
357 let mut i = 0;
358
359 while i < chars.len() {
360 if chars[i].is_ascii_uppercase() && (i == 0 || !chars[i - 1].is_ascii_alphanumeric()) {
361 let start = i;
362 while i < chars.len() && (chars[i].is_ascii_alphanumeric()) {
363 i += 1;
364 }
365 if i >= chars.len() || (chars[i] != '(' && chars[i] != '_') {
366 let constant: String = chars[start..i].iter().collect();
367 if !["MOST", "FEW", "ALL", "THE"].contains(&constant.as_str())
368 && !notation.is_fixed_word(&constant)
369 && seen.insert(format!("const_{}", constant))
370 {
371 entries.push(SymbolEntry {
372 usage: constant.clone(),
373 symbol: constant.clone(),
374 kind: SymbolKind::Constant,
375 description: "a particular individual".to_string(),
376 });
377 }
378 }
379 }
380 i += 1;
381 }
382}
383
384pub fn group_symbols_by_kind(entries: &[SymbolEntry]) -> Vec<(SymbolKind, Vec<&SymbolEntry>)> {
386 let kinds = [
387 SymbolKind::Quantifier,
388 SymbolKind::Connective,
389 SymbolKind::Modal,
390 SymbolKind::Temporal,
391 SymbolKind::Identity,
392 SymbolKind::Predicate,
393 SymbolKind::Role,
394 SymbolKind::Variable,
395 SymbolKind::Constant,
396 ];
397
398 kinds
399 .iter()
400 .filter_map(|&kind| {
401 let matching: Vec<_> = entries.iter().filter(|e| e.kind == kind).collect();
402 if matching.is_empty() {
403 None
404 } else {
405 Some((kind, matching))
406 }
407 })
408 .collect()
409}
410
411#[cfg(test)]
412#[path = "../../logicaffeine_tests/unit/logicaffeine_language/symbol_dict/tests.rs"]
413mod tests;
414