Skip to main content

logicaffeine_compile/codegen_sva/
fol_to_verify.rs

1//! FOL → Bounded Verification IR Translation
2//!
3//! Translates Kripke-lowered LogicExpr to a bounded timestep model.
4//! World variables (w0, w1, ...) become timestep indices.
5//! Temporal accessibility predicates control the unrolling.
6
7use super::hw_pipeline::SignalMap;
8use super::sva_to_verify::BoundedExpr;
9use logicaffeine_base::Symbol;
10use logicaffeine_language::ast::logic::{
11    BinaryTemporalOp, LogicExpr, QuantifierKind, TemporalOperator, Term, ThematicRole,
12};
13use logicaffeine_language::token::TokenType;
14use logicaffeine_language::Interner;
15use std::collections::{HashMap, HashSet};
16
17/// Translator from Kripke-lowered FOL to bounded timestep model.
18pub struct FolTranslator<'a> {
19    interner: &'a Interner,
20    bound: u32,
21    /// Maps world variable symbols to fixed timesteps
22    world_map: HashMap<Symbol, u32>,
23    /// Accumulated signal declarations
24    declarations: HashSet<String>,
25    /// Optional signal map for FOL arg → SVA signal name mapping
26    signal_map: Option<&'a SignalMap>,
27    /// When true, collapse ∀x(P(x) → TruthPred(x)) to just P even without a signal map.
28    /// Used by the consistency checker to ensure contradictory specs produce conflicting variables.
29    collapse_truth_predicates: bool,
30}
31
32impl<'a> FolTranslator<'a> {
33    pub fn new(interner: &'a Interner, bound: u32) -> Self {
34        Self {
35            interner,
36            bound,
37            world_map: HashMap::new(),
38            declarations: HashSet::new(),
39            signal_map: None,
40            collapse_truth_predicates: false,
41        }
42    }
43
44    /// Enable truth predicate collapsing for consistency checking.
45    pub fn set_collapse_truth_predicates(&mut self, collapse: bool) {
46        self.collapse_truth_predicates = collapse;
47    }
48
49    /// Set a signal map for translating FOL argument names to SVA signal names.
50    pub fn set_signal_map(&mut self, map: &'a SignalMap) {
51        self.signal_map = Some(map);
52    }
53
54    /// Try to extract an accessibility predicate pattern from a quantifier body.
55    ///
56    /// For existential: body is `And(Reachable_Temporal(w_source, w_target), actual_body)`
57    /// Returns (source_world_symbol, actual_body, is_strictly_future)
58    fn extract_accessibility_from_existential<'b>(
59        &self,
60        body: &'b LogicExpr<'b>,
61        quantified_var: Symbol,
62    ) -> Option<(Symbol, &'b LogicExpr<'b>, bool)> {
63        if let LogicExpr::BinaryOp { left, op, right } = body {
64            if matches!(op, TokenType::And) {
65                if let LogicExpr::Predicate {
66                    name,
67                    args,
68                    world: None,
69                } = *left
70                {
71                    let pred_name = self.interner.resolve(*name);
72                    if pred_name == "Reachable_Temporal" || pred_name == "Accessible_Temporal" {
73                        if args.len() >= 2 {
74                            if let (Term::Variable(source), Term::Variable(target)) =
75                                (&args[0], &args[1])
76                            {
77                                if *target == quantified_var {
78                                    let strictly_future = pred_name == "Reachable_Temporal";
79                                    return Some((*source, right, strictly_future));
80                                }
81                            }
82                        }
83                    }
84                }
85            }
86        }
87        None
88    }
89
90    /// Try to extract an accessibility predicate pattern from a universal quantifier body.
91    ///
92    /// For universal: body is `Implies(Accessible_Temporal(w_source, w_target), actual_body)`
93    /// Returns (source_world_symbol, actual_body, predicate_name)
94    fn extract_accessibility_from_universal<'b>(
95        &self,
96        body: &'b LogicExpr<'b>,
97        quantified_var: Symbol,
98    ) -> Option<(Symbol, &'b LogicExpr<'b>, &'a str)> {
99        if let LogicExpr::BinaryOp { left, op, right } = body {
100            if matches!(op, TokenType::If | TokenType::Implies) {
101                if let LogicExpr::Predicate {
102                    name,
103                    args,
104                    world: None,
105                } = *left
106                {
107                    let pred_name = self.interner.resolve(*name);
108                    if pred_name == "Accessible_Temporal"
109                        || pred_name == "Reachable_Temporal"
110                        || pred_name == "Next_Temporal"
111                    {
112                        if args.len() >= 2 {
113                            if let (Term::Variable(source), Term::Variable(target)) =
114                                (&args[0], &args[1])
115                            {
116                                if *target == quantified_var {
117                                    return Some((*source, right, pred_name));
118                                }
119                            }
120                        }
121                    }
122                }
123            }
124        }
125        None
126    }
127
128    /// Translate a Kripke-lowered LogicExpr to bounded verification IR.
129    pub fn translate(&mut self, expr: &LogicExpr<'_>) -> BoundedExpr {
130        match expr {
131            // Predicates with world arguments → timestamped variables
132            LogicExpr::Predicate { name, args, world } => {
133                let pred_name = self.interner.resolve(*name).to_string();
134
135                // Accessibility predicates — evaluate ordering constraint
136                if pred_name == "Accessible_Temporal"
137                    || pred_name == "Reachable_Temporal"
138                    || pred_name == "Next_Temporal"
139                {
140                    // Extract source and target world timesteps from args
141                    if args.len() >= 2 {
142                        if let (Term::Variable(source), Term::Variable(target)) =
143                            (&args[0], &args[1])
144                        {
145                            let source_t = self.world_map.get(source).copied().unwrap_or(0);
146                            let target_t = self.world_map.get(target).copied().unwrap_or(0);
147
148                            return match pred_name.as_str() {
149                                "Accessible_Temporal" => BoundedExpr::Bool(target_t >= source_t),
150                                "Reachable_Temporal" => BoundedExpr::Bool(target_t > source_t),
151                                "Next_Temporal" => BoundedExpr::Bool(target_t == source_t + 1),
152                                _ => BoundedExpr::Bool(true),
153                            };
154                        }
155                    }
156                    // Fallback if args don't match expected structure
157                    return BoundedExpr::Bool(true);
158                }
159
160                // Regular predicate with world → timestamped variable
161                if let Some(w) = world {
162                    let timestep = self.world_map.get(w).copied().unwrap_or(0);
163
164                    // Check if the predicate name itself matches a signal declaration
165                    if let Some(signal_map) = self.signal_map {
166                        if let Some(sva_name) = signal_map.resolve(&pred_name) {
167                            let var_name = format!("{}@{}", sva_name, timestep);
168                            self.declarations.insert(var_name.clone());
169                            return BoundedExpr::Var(var_name);
170                        }
171                    }
172
173                    if args.is_empty() {
174                        let var_name = format!("{}@{}", pred_name, timestep);
175                        self.declarations.insert(var_name.clone());
176                        return BoundedExpr::Var(var_name);
177                    }
178                    // Multi-arg predicate: use first arg as signal name
179                    if let Some(arg) = args.first() {
180                        let arg_name = self.term_to_string(arg);
181
182                        // If signal map has this argument (constant/proper noun),
183                        // use the mapped signal name
184                        if let Some(signal_map) = self.signal_map {
185                            if let Some(sva_name) = signal_map.resolve(&arg_name) {
186                                let var_name = format!("{}@{}", sva_name, timestep);
187                                self.declarations.insert(var_name.clone());
188                                return BoundedExpr::Var(var_name);
189                            }
190                        }
191
192                        let var_name = format!("{}_{}_@{}", pred_name, arg_name, timestep);
193                        self.declarations.insert(var_name.clone());
194                        return BoundedExpr::Var(var_name);
195                    }
196                }
197
198                // Predicate without world → static (non-temporal)
199                let var_name = pred_name;
200                self.declarations.insert(var_name.clone());
201                BoundedExpr::Var(var_name)
202            }
203
204            // Universal quantifier over worlds → conjunction over timesteps
205            LogicExpr::Quantifier {
206                kind: QuantifierKind::Universal,
207                variable,
208                body,
209                ..
210            } => {
211                let var_name = self.interner.resolve(*variable).to_string();
212                if var_name.starts_with('w') {
213                    // Check for accessibility predicate pattern in body
214                    if let Some((source_world, actual_body, pred_kind)) =
215                        self.extract_accessibility_from_universal(body, *variable)
216                    {
217                        let source_t = self.world_map.get(&source_world).copied().unwrap_or(0);
218
219                        // Next_Temporal: exactly one timestep (source + 1)
220                        if pred_kind == "Next_Temporal" {
221                            let next_t = source_t + 1;
222                            self.world_map.insert(*variable, next_t);
223                            let step = self.translate(actual_body);
224                            self.world_map.remove(variable);
225                            return step;
226                        }
227
228                        let (start, end) = match pred_kind {
229                            "Accessible_Temporal" => (source_t, source_t + self.bound),
230                            "Reachable_Temporal" => (source_t + 1, source_t + 1 + self.bound),
231                            _ => (0, self.bound),
232                        };
233
234                        let mut result: Option<BoundedExpr> = None;
235                        for t in start..end {
236                            self.world_map.insert(*variable, t);
237                            let step = self.translate(actual_body);
238                            result = Some(match result {
239                                None => step,
240                                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(step)),
241                            });
242                        }
243                        self.world_map.remove(variable);
244                        return result.unwrap_or(BoundedExpr::Bool(true));
245                    }
246
247                    // Fallback: generic world quantifier — iterate 0..bound
248                    let mut result: Option<BoundedExpr> = None;
249                    for t in 0..self.bound {
250                        self.world_map.insert(*variable, t);
251                        let step = self.translate(body);
252                        result = Some(match result {
253                            None => step,
254                            Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(step)),
255                        });
256                    }
257                    self.world_map.remove(variable);
258                    result.unwrap_or(BoundedExpr::Bool(true))
259                } else {
260                    // Regular variable quantifier: check for signal collapsing pattern
261                    // ∀x(Restrictor(x,w) → TruthPredicate(x,w)) → just Restrictor@t
262                    // ∀x(Restrictor(x,w) → ¬TruthPredicate(x,w)) → ¬Restrictor@t
263                    if self.signal_map.is_some() || self.collapse_truth_predicates {
264                        if let LogicExpr::BinaryOp { left, right, op } = body {
265                            if matches!(op, TokenType::If | TokenType::Implies) {
266                                if self.is_truth_expr(right) {
267                                    // When collapsing, use just the restrictor predicate name
268                                    // (without variable suffix) for cross-sentence consistency.
269                                    let restrictor = if self.signal_map.is_some() {
270                                        // With signal map: normal translation (uses mapped name)
271                                        self.translate(left)
272                                    } else {
273                                        // Without signal map (consistency mode): use bare predicate name
274                                        self.translate_predicate_bare(left)
275                                    };
276                                    if matches!(right, LogicExpr::UnaryOp { .. }) {
277                                        return BoundedExpr::Not(Box::new(restrictor));
278                                    }
279                                    return restrictor;
280                                }
281                            }
282                        }
283                    }
284                    self.translate(body)
285                }
286            }
287
288            // Existential quantifier over worlds → disjunction over timesteps
289            LogicExpr::Quantifier {
290                kind: QuantifierKind::Existential,
291                variable,
292                body,
293                ..
294            } => {
295                let var_name = self.interner.resolve(*variable).to_string();
296                if var_name.starts_with('w') {
297                    // Check for accessibility predicate pattern in body
298                    if let Some((source_world, actual_body, strictly_future)) =
299                        self.extract_accessibility_from_existential(body, *variable)
300                    {
301                        let source_t = self.world_map.get(&source_world).copied().unwrap_or(0);
302                        let start = if strictly_future {
303                            source_t + 1
304                        } else {
305                            source_t
306                        };
307                        let end = start + self.bound;
308
309                        let mut result: Option<BoundedExpr> = None;
310                        for t in start..end {
311                            self.world_map.insert(*variable, t);
312                            let step = self.translate(actual_body);
313                            result = Some(match result {
314                                None => step,
315                                Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(step)),
316                            });
317                        }
318                        self.world_map.remove(variable);
319                        return result.unwrap_or(BoundedExpr::Bool(false));
320                    }
321
322                    // Fallback: generic world quantifier — iterate 0..bound
323                    let mut result: Option<BoundedExpr> = None;
324                    for t in 0..self.bound {
325                        self.world_map.insert(*variable, t);
326                        let step = self.translate(body);
327                        result = Some(match result {
328                            None => step,
329                            Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(step)),
330                        });
331                    }
332                    self.world_map.remove(variable);
333                    result.unwrap_or(BoundedExpr::Bool(false))
334                } else {
335                    self.translate(body)
336                }
337            }
338
339            // Binary connectives
340            LogicExpr::BinaryOp { left, op, right } => {
341                let l = self.translate(left);
342                let r = self.translate(right);
343                match op {
344                    TokenType::And => BoundedExpr::And(Box::new(l), Box::new(r)),
345                    TokenType::Or => BoundedExpr::Or(Box::new(l), Box::new(r)),
346                    TokenType::If | TokenType::Implies => {
347                        BoundedExpr::Implies(Box::new(l), Box::new(r))
348                    }
349                    _ => {
350                        // Other binary ops: default to And
351                        BoundedExpr::And(Box::new(l), Box::new(r))
352                    }
353                }
354            }
355
356            // Negation
357            LogicExpr::UnaryOp { operand, .. } => {
358                let inner = self.translate(operand);
359                BoundedExpr::Not(Box::new(inner))
360            }
361
362            // LTL temporal operators (if not already Kripke-lowered)
363            LogicExpr::Temporal { operator, body } => {
364                match operator {
365                    TemporalOperator::Always => {
366                        // G(P) → conjunction over all timesteps
367                        let mut result: Option<BoundedExpr> = None;
368                        for _t in 0..self.bound {
369                            // Temporarily set world mapping
370                            let step = self.translate(body);
371                            result = Some(match result {
372                                None => step,
373                                Some(acc) => BoundedExpr::And(Box::new(acc), Box::new(step)),
374                            });
375                        }
376                        result.unwrap_or(BoundedExpr::Bool(true))
377                    }
378                    TemporalOperator::Eventually => {
379                        let mut result: Option<BoundedExpr> = None;
380                        for _t in 0..self.bound {
381                            let step = self.translate(body);
382                            result = Some(match result {
383                                None => step,
384                                Some(acc) => BoundedExpr::Or(Box::new(acc), Box::new(step)),
385                            });
386                        }
387                        result.unwrap_or(BoundedExpr::Bool(false))
388                    }
389                    _ => self.translate(body),
390                }
391            }
392
393            // Binary temporal operators — each has distinct bounded semantics
394            LogicExpr::TemporalBinary {
395                operator,
396                left,
397                right,
398            } => {
399                let l = self.translate(left);
400                let r = self.translate(right);
401                match operator {
402                    BinaryTemporalOp::Until => self.unroll_until(&l, &r, 0),
403                    BinaryTemporalOp::Release => self.unroll_release(&l, &r, 0),
404                    BinaryTemporalOp::WeakUntil => {
405                        let until = self.unroll_until(&l, &r, 0);
406                        let always = self.unroll_always(&l, 0);
407                        BoundedExpr::Or(Box::new(until), Box::new(always))
408                    }
409                }
410            }
411
412            // Identity/equality
413            LogicExpr::Identity { left, right, .. } => {
414                let l = self.term_to_bounded(left);
415                let r = self.term_to_bounded(right);
416                BoundedExpr::Eq(Box::new(l), Box::new(r))
417            }
418
419            // Neo-Davidsonian event: extract verb + agent as signal name
420            LogicExpr::NeoEvent(data) => {
421                let verb_name = self.interner.resolve(data.verb).to_string();
422                let timestep = data
423                    .world
424                    .and_then(|w| self.world_map.get(&w).copied())
425                    .unwrap_or(0);
426
427                // Extract agent from roles for signal naming
428                let agent_name = data
429                    .roles
430                    .iter()
431                    .find(|(role, _)| matches!(role, ThematicRole::Agent))
432                    .map(|(_, term)| self.term_to_string(term));
433
434                if let Some(ref arg_name) = agent_name {
435                    if let Some(signal_map) = self.signal_map {
436                        if let Some(sva_name) = signal_map.resolve(arg_name) {
437                            let var_name = format!("{}@{}", sva_name, timestep);
438                            self.declarations.insert(var_name.clone());
439                            return BoundedExpr::Var(var_name);
440                        }
441                        if let Some(sva_name) = signal_map.resolve(&verb_name) {
442                            let var_name = format!("{}@{}", sva_name, timestep);
443                            self.declarations.insert(var_name.clone());
444                            return BoundedExpr::Var(var_name);
445                        }
446                    }
447                    let var_name = format!("{}_{}_@{}", verb_name, arg_name, timestep);
448                    self.declarations.insert(var_name.clone());
449                    BoundedExpr::Var(var_name)
450                } else {
451                    if let Some(signal_map) = self.signal_map {
452                        if let Some(sva_name) = signal_map.resolve(&verb_name) {
453                            let var_name = format!("{}@{}", sva_name, timestep);
454                            self.declarations.insert(var_name.clone());
455                            return BoundedExpr::Var(var_name);
456                        }
457                    }
458                    let var_name = format!("{}@{}", verb_name, timestep);
459                    self.declarations.insert(var_name.clone());
460                    BoundedExpr::Var(var_name)
461                }
462            }
463
464            // Modal: unwrap
465            LogicExpr::Modal { operand, .. } => self.translate(operand),
466
467            // Catch-all: fail closed (false, not true) for unhandled constructs.
468            // Unsupported constructs must NOT silently become vacuously true.
469            _ => BoundedExpr::Bool(false),
470        }
471    }
472
473    /// Translate a full Kripke-lowered expression as a property (for all timesteps).
474    pub fn translate_property(
475        &mut self,
476        expr: &LogicExpr<'_>,
477    ) -> super::sva_to_verify::TranslateResult {
478        let expr_result = self.translate(expr);
479        let declarations: Vec<String> = self.declarations.iter().cloned().collect();
480        super::sva_to_verify::TranslateResult {
481            expr: expr_result,
482            declarations,
483        }
484    }
485
486    /// Unroll φ U ψ (Until) to bounded depth.
487    fn unroll_until(&self, phi: &BoundedExpr, psi: &BoundedExpr, depth: u32) -> BoundedExpr {
488        if depth >= self.bound {
489            psi.clone()
490        } else {
491            let rest = self.unroll_until(phi, psi, depth + 1);
492            BoundedExpr::Or(
493                Box::new(psi.clone()),
494                Box::new(BoundedExpr::And(Box::new(phi.clone()), Box::new(rest))),
495            )
496        }
497    }
498
499    /// Unroll φ R ψ (Release) to bounded depth.
500    fn unroll_release(&self, phi: &BoundedExpr, psi: &BoundedExpr, depth: u32) -> BoundedExpr {
501        if depth >= self.bound {
502            psi.clone()
503        } else {
504            let rest = self.unroll_release(phi, psi, depth + 1);
505            BoundedExpr::And(
506                Box::new(psi.clone()),
507                Box::new(BoundedExpr::Or(Box::new(phi.clone()), Box::new(rest))),
508            )
509        }
510    }
511
512    /// Unroll G(φ) (Always) to bounded depth.
513    fn unroll_always(&self, phi: &BoundedExpr, depth: u32) -> BoundedExpr {
514        if depth >= self.bound {
515            phi.clone()
516        } else {
517            let rest = self.unroll_always(phi, depth + 1);
518            BoundedExpr::And(Box::new(phi.clone()), Box::new(rest))
519        }
520    }
521
522    /// Check if a LogicExpr is a truth predicate (hold/have/valid/active)
523    /// or a negation of one. Used for quantifier collapsing:
524    /// ∀x(Signal(x) → TruthPred(x)) → Signal
525    /// ∀x(Signal(x) → ¬TruthPred(x)) → ¬Signal
526    fn is_truth_expr(&self, expr: &LogicExpr<'_>) -> bool {
527        match expr {
528            LogicExpr::Predicate { name, .. } => {
529                let pred_name = self.interner.resolve(*name).to_string();
530                is_truth_predicate(&pred_name)
531            }
532            LogicExpr::NeoEvent(data) => {
533                let verb_name = self.interner.resolve(data.verb).to_string();
534                is_truth_predicate(&verb_name)
535            }
536            LogicExpr::UnaryOp { operand, .. } => self.is_truth_expr(operand),
537            _ => false,
538        }
539    }
540
541    /// Translate a restrictor predicate using just its name (no variable suffix).
542    /// Used in consistency mode to ensure cross-sentence variable consistency.
543    fn translate_predicate_bare(&mut self, expr: &LogicExpr<'_>) -> BoundedExpr {
544        match expr {
545            LogicExpr::Predicate { name, world, .. } => {
546                let pred_name = self.interner.resolve(*name).to_string();
547                let timestep = world
548                    .and_then(|w| self.world_map.get(&w).copied())
549                    .unwrap_or(0);
550                let var_name = format!("{}@{}", pred_name, timestep);
551                self.declarations.insert(var_name.clone());
552                BoundedExpr::Var(var_name)
553            }
554            _ => self.translate(expr),
555        }
556    }
557
558    fn term_to_string(&self, term: &Term<'_>) -> String {
559        match term {
560            Term::Constant(sym) | Term::Variable(sym) => self.interner.resolve(*sym).to_string(),
561            Term::Function(sym, _) => self.interner.resolve(*sym).to_string(),
562            _ => "unknown".to_string(),
563        }
564    }
565
566    fn term_to_bounded(&self, term: &Term<'_>) -> BoundedExpr {
567        let name = self.term_to_string(term);
568        BoundedExpr::Var(name)
569    }
570}
571
572/// Check if a predicate name is a "truth predicate" — a copula-like verb
573/// that means "the signal is true" in hardware context.
574/// When a signal map is present and the restrictor maps to a signal,
575/// truth predicates should be elided (the signal itself carries the boolean).
576fn is_truth_predicate(name: &str) -> bool {
577    let lower = name.to_lowercase();
578    matches!(
579        lower.as_str(),
580        "hold"
581            | "holds"
582            | "have"
583            | "has"
584            | "had"
585            | "valid"
586            | "active"
587            | "true"
588            | "assert"
589            | "asserted"
590    )
591}