1use logicaffeine_proof::{ProofExpr, ProofTerm};
19use std::collections::BTreeSet;
20
21const ROLE_ORDER: &[&str] = &[
24 "Agent",
25 "Patient",
26 "Theme",
27 "Recipient",
28 "Goal",
29 "Source",
30 "Instrument",
31 "Location",
32 "Time",
33 "Manner",
34 "Result",
35 "Depictive",
36];
37
38pub fn fol_to_model_checker(
41 premises: &[ProofExpr],
42 goal: &ProofExpr,
43 english: &str,
44 fol: &str,
45) -> String {
46 fol_to_model_checker_impl(premises, goal, english, fol, true)
47}
48
49pub fn fol_to_model_checker_module(
53 premises: &[ProofExpr],
54 goal: &ProofExpr,
55 english: &str,
56 fol: &str,
57) -> String {
58 fol_to_model_checker_impl(premises, goal, english, fol, false)
59}
60
61fn fol_to_model_checker_impl(
62 premises: &[ProofExpr],
63 goal: &ProofExpr,
64 english: &str,
65 fol: &str,
66 emit_main: bool,
67) -> String {
68 let temporal = premises.iter().any(contains_temporal) || contains_temporal(goal);
69
70 let mut consts: BTreeSet<String> = BTreeSet::new();
71 let mut facts: BTreeSet<(String, Vec<String>)> = BTreeSet::new();
72 for p in premises {
73 collect(p, &mut consts, &mut facts);
74 }
75 collect(goal, &mut consts, &mut facts);
76
77 let header = doc_header(english, fol);
78 if temporal {
79 emit_temporal_module(premises, goal, &consts, &facts, &header, emit_main)
80 } else {
81 emit_world_module(premises, goal, &consts, &facts, &header, emit_main)
82 }
83}
84
85fn emit_world_module(
88 premises: &[ProofExpr],
89 goal: &ProofExpr,
90 consts: &BTreeSet<String>,
91 facts: &BTreeSet<(String, Vec<String>)>,
92 header: &str,
93 emit_main: bool,
94) -> String {
95 let mut body = entailment(premises, goal, &|e| emit_expr(e, "w"));
96 for f in free_vars_of(premises, goal) {
99 body = format!("w.domain.iter().all(|&{}| {})", sanitize_var(&f), body);
100 }
101 let main = if emit_main {
102 format!(
103 "\nfn main() {{\n let w = {demo};\n println!(\"holds = {{}}\", holds(&w));\n}}\n",
104 demo = demo_world(consts, facts),
105 )
106 } else {
107 String::new()
108 };
109 format!(
110 "{header}{world}\n\
111 /// Evaluate the rule against a world.\n\
112 pub fn holds(w: &World) -> bool {{\n {body}\n}}\n{main}",
113 header = header,
114 world = WORLD_DEF,
115 body = body,
116 main = main,
117 )
118}
119
120fn emit_temporal_module(
123 premises: &[ProofExpr],
124 goal: &ProofExpr,
125 consts: &BTreeSet<String>,
126 facts: &BTreeSet<(String, Vec<String>)>,
127 header: &str,
128 emit_main: bool,
129) -> String {
130 let mut body = entailment(premises, goal, &|e| emit_expr_trace(e, "0", 0));
131 for f in free_vars_of(premises, goal) {
133 body = format!(
134 "trace.first().map_or(true, |w| w.domain.iter().all(|&{}| {}))",
135 sanitize_var(&f),
136 body
137 );
138 }
139 let demo = demo_world(consts, facts);
140 let main = if emit_main {
141 format!(
142 "fn main() {{\n \
143 let trace = vec![{demo}, {demo}];\n \
144 println!(\"holds = {{}}\", holds(&trace));\n}}\n",
145 demo = demo,
146 )
147 } else {
148 String::new()
149 };
150 format!(
151 "{header}{world}\n\
152 /// Evaluate the temporal rule over a finite trace of worlds.\n\
153 pub fn holds(trace: &[World]) -> bool {{\n {body}\n}}\n\n\
154 /// Incremental monitor: feed worlds as they happen.\n\
155 #[derive(Default)]\n\
156 pub struct Monitor {{ trace: Vec<World> }}\n\n\
157 impl Monitor {{\n \
158 pub fn new() -> Self {{ Self::default() }}\n \
159 /// Append a world and report whether the rule still holds over the trace so far.\n \
160 pub fn step(&mut self, w: World) -> bool {{ self.trace.push(w); holds(&self.trace) }}\n}}\n\n\
161 {main}",
162 header = header,
163 world = WORLD_DEF,
164 body = body,
165 main = main,
166 )
167}
168
169fn entailment(
171 premises: &[ProofExpr],
172 goal: &ProofExpr,
173 emit: &dyn Fn(&ProofExpr) -> String,
174) -> String {
175 let g = emit(goal);
176 if premises.is_empty() {
177 g
178 } else {
179 let prem: Vec<String> = premises.iter().map(|p| emit(p)).collect();
180 format!("(!({}) || {})", prem.join(" && "), g)
181 }
182}
183
184const WORLD_DEF: &str = "\
186use std::collections::HashSet;\n\n\
187/// A finite world: named individuals (including events) and the facts that hold.\n\
188#[derive(Default, Clone)]\n\
189pub struct World {\n \
190pub domain: Vec<&'static str>,\n \
191pub facts: HashSet<(&'static str, Vec<&'static str>)>,\n}\n\n\
192impl World {\n \
193pub fn new() -> Self { Self::default() }\n \
194/// Add a named individual to the domain.\n \
195pub fn individual(mut self, name: &'static str) -> Self {\n \
196if !self.domain.contains(&name) { self.domain.push(name); }\n \
197self\n }\n \
198/// Assert `name(args...)`; any new individuals are added to the domain.\n \
199pub fn fact(mut self, name: &'static str, args: &[&'static str]) -> Self {\n \
200for &a in args { if !self.domain.contains(&a) { self.domain.push(a); } }\n \
201self.facts.insert((name, args.to_vec()));\n \
202self\n }\n \
203/// True iff `name(args...)` holds in this world.\n \
204pub fn pred(&self, name: &'static str, args: &[&'static str]) -> bool {\n \
205self.facts.contains(&(name, args.to_vec()))\n }\n}\n";
206
207fn doc_header(english: &str, fol: &str) -> String {
208 let one_line = |s: &str| {
209 s.lines()
210 .map(|l| l.trim())
211 .filter(|l| !l.is_empty())
212 .collect::<Vec<_>>()
213 .join(" | ")
214 };
215 let mut h = String::from("// Auto-generated rule from logic — a reusable World + `holds`.\n");
216 let e = one_line(english);
217 if !e.is_empty() {
218 h.push_str(&format!("// English: {}\n", e));
219 }
220 let f = one_line(fol);
221 if !f.is_empty() {
222 h.push_str(&format!("// FOL: {}\n", f));
223 }
224 h.push('\n');
225 h
226}
227
228fn demo_world(consts: &BTreeSet<String>, facts: &BTreeSet<(String, Vec<String>)>) -> String {
230 let mut chain = String::from("World::new()");
231 for (name, args) in facts {
232 let a: Vec<String> = args.iter().map(|x| format!("{:?}", x)).collect();
233 chain.push_str(&format!(".fact({:?}, &[{}])", name, a.join(", ")));
234 }
235 let in_fact: BTreeSet<&String> = facts.iter().flat_map(|(_, a)| a.iter()).collect();
237 for c in consts {
238 if !in_fact.contains(c) {
239 chain.push_str(&format!(".individual({:?})", c));
240 }
241 }
242 chain
243}
244
245fn emit_expr(e: &ProofExpr, world: &str) -> String {
248 match e {
249 ProofExpr::Predicate { name, args, .. } => {
250 let a: Vec<String> = args.iter().map(emit_term).collect();
251 format!("{}.pred({:?}, &[{}])", world, name, a.join(", "))
252 }
253 ProofExpr::Atom(s) => format!("{}.pred({:?}, &[])", world, s),
254 ProofExpr::Identity(a, b) => format!("({} == {})", emit_term(a), emit_term(b)),
255 ProofExpr::And(l, r) => format!("({} && {})", emit_expr(l, world), emit_expr(r, world)),
256 ProofExpr::Or(l, r) => format!("({} || {})", emit_expr(l, world), emit_expr(r, world)),
257 ProofExpr::Implies(l, r) => {
258 format!("(!{} || {})", emit_expr(l, world), emit_expr(r, world))
259 }
260 ProofExpr::Iff(l, r) => format!("({} == {})", emit_expr(l, world), emit_expr(r, world)),
261 ProofExpr::Not(x) => format!("(!{})", emit_expr(x, world)),
262 ProofExpr::ForAll { variable, body } => format!(
263 "{}.domain.iter().all(|&{}| {})",
264 world,
265 sanitize_var(variable),
266 emit_expr(body, world)
267 ),
268 ProofExpr::Exists { variable, body } => format!(
269 "{}.domain.iter().any(|&{}| {})",
270 world,
271 sanitize_var(variable),
272 emit_expr(body, world)
273 ),
274 ProofExpr::NeoEvent {
277 event_var,
278 verb,
279 roles,
280 } => {
281 let e = sanitize_var(event_var);
282 let mut sorted = roles.clone();
283 sorted.sort_by_key(|(r, _)| {
284 ROLE_ORDER
285 .iter()
286 .position(|x| x == r)
287 .unwrap_or(ROLE_ORDER.len())
288 });
289 let mut parts = vec![format!("{}.pred({:?}, &[{}])", world, verb, e)];
290 for (role, term) in &sorted {
291 parts.push(format!(
292 "{}.pred({:?}, &[{}, {}])",
293 world,
294 role,
295 e,
296 emit_term(term)
297 ));
298 }
299 format!(
300 "{}.domain.iter().any(|&{}| {})",
301 world,
302 e,
303 parts.join(" && ")
304 )
305 }
306 other => format!("true /* unsupported: {} */", variant_name(other)),
307 }
308}
309
310fn emit_expr_trace(e: &ProofExpr, idx: &str, depth: usize) -> String {
313 if !contains_temporal(e) {
315 return emit_expr(e, &format!("(&trace[{}])", idx));
316 }
317 match e {
318 ProofExpr::Temporal { operator, body } => {
319 let v = format!("i{}", depth);
320 let inner = emit_expr_trace(body, &v, depth + 1);
321 match operator.as_str() {
322 "Always" => format!(
323 "({idx}..trace.len()).all(|{v}| {inner})",
324 idx = idx,
325 v = v,
326 inner = inner
327 ),
328 "Eventually" | "Future" => {
329 format!(
330 "({idx}..trace.len()).any(|{v}| {inner})",
331 idx = idx,
332 v = v,
333 inner = inner
334 )
335 }
336 "Past" => format!(
337 "(0..={idx}).any(|{v}| {inner})",
338 idx = idx,
339 v = v,
340 inner = inner
341 ),
342 "Next" => format!(
343 "{{ let {v} = {idx} + 1; {v} < trace.len() && {inner} }}",
344 v = v,
345 idx = idx,
346 inner = inner
347 ),
348 _ => format!(
349 "({idx}..trace.len()).all(|{v}| {inner})",
350 idx = idx,
351 v = v,
352 inner = inner
353 ),
354 }
355 }
356 ProofExpr::TemporalBinary {
357 operator,
358 left,
359 right,
360 } => {
361 let k = format!("k{}", depth);
362 let j = format!("j{}", depth);
363 let r_at_k = emit_expr_trace(right, &k, depth + 1);
364 let l_at_j = emit_expr_trace(left, &j, depth + 1);
365 match operator.as_str() {
366 "Release" => format!(
367 "({idx}..trace.len()).all(|{k}| {r} || ({idx}..{k}).any(|{j}| {l}))",
368 idx = idx,
369 k = k,
370 j = j,
371 r = r_at_k,
372 l = l_at_j
373 ),
374 "WeakUntil" => {
375 let l_all = emit_expr_trace(left, &j, depth + 1);
376 format!(
377 "(({idx}..trace.len()).all(|{j}| {l_all})) || (({idx}..trace.len()).any(|{k}| {r} && ({idx}..{k}).all(|{j}| {l})))",
378 idx = idx, k = k, j = j, l_all = l_all, r = r_at_k, l = l_at_j
379 )
380 }
381 _ => format!(
383 "({idx}..trace.len()).any(|{k}| {r} && ({idx}..{k}).all(|{j}| {l}))",
384 idx = idx,
385 k = k,
386 j = j,
387 r = r_at_k,
388 l = l_at_j
389 ),
390 }
391 }
392 ProofExpr::And(l, r) => {
393 format!(
394 "({} && {})",
395 emit_expr_trace(l, idx, depth),
396 emit_expr_trace(r, idx, depth)
397 )
398 }
399 ProofExpr::Or(l, r) => {
400 format!(
401 "({} || {})",
402 emit_expr_trace(l, idx, depth),
403 emit_expr_trace(r, idx, depth)
404 )
405 }
406 ProofExpr::Implies(l, r) => {
407 format!(
408 "(!{} || {})",
409 emit_expr_trace(l, idx, depth),
410 emit_expr_trace(r, idx, depth)
411 )
412 }
413 ProofExpr::Iff(l, r) => {
414 format!(
415 "({} == {})",
416 emit_expr_trace(l, idx, depth),
417 emit_expr_trace(r, idx, depth)
418 )
419 }
420 ProofExpr::Not(x) => format!("(!{})", emit_expr_trace(x, idx, depth)),
421 _ => emit_expr(e, &format!("(&trace[{}])", idx)),
424 }
425}
426
427fn free_vars_of(premises: &[ProofExpr], goal: &ProofExpr) -> BTreeSet<String> {
430 let mut out = BTreeSet::new();
431 let mut bound: Vec<String> = Vec::new();
432 for p in premises {
433 free_vars(p, &mut bound, &mut out);
434 }
435 free_vars(goal, &mut bound, &mut out);
436 out
437}
438
439fn free_vars(e: &ProofExpr, bound: &mut Vec<String>, out: &mut BTreeSet<String>) {
440 match e {
441 ProofExpr::Predicate { args, .. } => {
442 for a in args {
443 free_term(a, bound, out);
444 }
445 }
446 ProofExpr::Identity(a, b) => {
447 free_term(a, bound, out);
448 free_term(b, bound, out);
449 }
450 ProofExpr::And(l, r)
451 | ProofExpr::Or(l, r)
452 | ProofExpr::Implies(l, r)
453 | ProofExpr::Iff(l, r) => {
454 free_vars(l, bound, out);
455 free_vars(r, bound, out);
456 }
457 ProofExpr::Not(x) => free_vars(x, bound, out),
458 ProofExpr::ForAll { variable, body } | ProofExpr::Exists { variable, body } => {
459 bound.push(variable.clone());
460 free_vars(body, bound, out);
461 bound.pop();
462 }
463 ProofExpr::Temporal { body, .. } => free_vars(body, bound, out),
464 ProofExpr::TemporalBinary { left, right, .. } => {
465 free_vars(left, bound, out);
466 free_vars(right, bound, out);
467 }
468 ProofExpr::NeoEvent {
469 event_var, roles, ..
470 } => {
471 bound.push(event_var.clone());
472 for (_, t) in roles {
473 free_term(t, bound, out);
474 }
475 bound.pop();
476 }
477 _ => {}
478 }
479}
480
481fn free_term(t: &ProofTerm, bound: &[String], out: &mut BTreeSet<String>) {
482 match t {
483 ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v) => {
484 if !bound.contains(v) {
485 out.insert(v.clone());
486 }
487 }
488 ProofTerm::Function(_, args) | ProofTerm::Group(args) => {
489 for a in args {
490 free_term(a, bound, out);
491 }
492 }
493 ProofTerm::Constant(_) => {}
494 }
495}
496
497fn contains_temporal(e: &ProofExpr) -> bool {
498 match e {
499 ProofExpr::Temporal { .. } | ProofExpr::TemporalBinary { .. } => true,
500 ProofExpr::And(l, r)
501 | ProofExpr::Or(l, r)
502 | ProofExpr::Implies(l, r)
503 | ProofExpr::Iff(l, r) => contains_temporal(l) || contains_temporal(r),
504 ProofExpr::Not(x) => contains_temporal(x),
505 ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => contains_temporal(body),
506 _ => false,
507 }
508}
509
510fn emit_term(t: &ProofTerm) -> String {
511 match t {
512 ProofTerm::Constant(c) => format!("{:?}", c),
513 ProofTerm::Variable(v) | ProofTerm::BoundVarRef(v) => sanitize_var(v),
514 ProofTerm::Function(name, _) => format!("{:?}", name),
515 ProofTerm::Group(_) => "\"?\"".to_string(),
516 }
517}
518
519fn sanitize_var(v: &str) -> String {
520 let cleaned: String = v
521 .chars()
522 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
523 .collect();
524 format!("v_{}", cleaned)
525}
526
527fn collect(
528 e: &ProofExpr,
529 consts: &mut BTreeSet<String>,
530 facts: &mut BTreeSet<(String, Vec<String>)>,
531) {
532 match e {
533 ProofExpr::Predicate { name, args, .. } => {
534 for a in args {
535 collect_term(a, consts);
536 }
537 let mut ground = Vec::new();
538 let mut all_const = true;
539 for a in args {
540 match a {
541 ProofTerm::Constant(c) => ground.push(c.clone()),
542 _ => {
543 all_const = false;
544 break;
545 }
546 }
547 }
548 if all_const {
549 facts.insert((name.clone(), ground));
550 }
551 }
552 ProofExpr::Atom(s) => {
553 facts.insert((s.clone(), vec![]));
554 }
555 ProofExpr::Identity(a, b) => {
556 collect_term(a, consts);
557 collect_term(b, consts);
558 }
559 ProofExpr::And(l, r)
560 | ProofExpr::Or(l, r)
561 | ProofExpr::Implies(l, r)
562 | ProofExpr::Iff(l, r) => {
563 collect(l, consts, facts);
564 collect(r, consts, facts);
565 }
566 ProofExpr::Not(x) => collect(x, consts, facts),
567 ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
568 collect(body, consts, facts)
569 }
570 ProofExpr::Temporal { body, .. } => collect(body, consts, facts),
571 ProofExpr::TemporalBinary { left, right, .. } => {
572 collect(left, consts, facts);
573 collect(right, consts, facts);
574 }
575 ProofExpr::NeoEvent { roles, .. } => {
576 for (_, term) in roles {
577 collect_term(term, consts);
578 }
579 }
580 _ => {}
581 }
582}
583
584fn collect_term(t: &ProofTerm, consts: &mut BTreeSet<String>) {
585 match t {
586 ProofTerm::Constant(c) => {
587 consts.insert(c.clone());
588 }
589 ProofTerm::Function(_, args) | ProofTerm::Group(args) => {
590 for a in args {
591 collect_term(a, consts);
592 }
593 }
594 _ => {}
595 }
596}
597
598fn variant_name(e: &ProofExpr) -> &'static str {
599 match e {
600 ProofExpr::Modal { .. } => "modal",
601 ProofExpr::Counterfactual { .. } => "counterfactual",
602 ProofExpr::Lambda { .. } => "lambda",
603 ProofExpr::App(..) => "application",
604 ProofExpr::Ctor { .. } => "constructor",
605 ProofExpr::Match { .. } => "match",
606 ProofExpr::Fixpoint { .. } => "fixpoint",
607 ProofExpr::Temporal { .. } | ProofExpr::TemporalBinary { .. } => "temporal",
608 _ => "construct",
609 }
610}