Skip to main content

tensorlogic_compiler/import/
mod.rs

1//! Logic Expression Import
2//!
3//! This module provides parsers for importing logic expressions from various
4//! external logic frameworks and formats.
5//!
6//! ## Supported Formats
7//!
8//! - **Prolog**: Standard Prolog syntax with predicates, conjunctions, disjunctions
9//! - **S-Expression**: Lisp-like S-expression format for nested logic
10//! - **TPTP**: TPTP (Thousands of Problems for Theorem Provers) format
11//!
12//! ## Examples
13//!
14//! ```
15//! use tensorlogic_compiler::import::prolog::parse_prolog;
16//!
17//! // Parse Prolog-style rule
18//! let expr = parse_prolog("mortal(X) :- human(X).").unwrap();
19//! ```
20//!
21//! ```no_run
22//! use tensorlogic_compiler::import::sexpr::parse_sexpr;
23//!
24//! // Parse S-expression
25//! let expr = parse_sexpr("(forall x (=> (human x) (mortal x)))").unwrap();
26//! ```
27
28pub mod prolog;
29pub mod sexpr;
30pub mod tptp;
31
32pub use prolog::parse_prolog;
33pub use sexpr::parse_sexpr;
34pub use tptp::parse_tptp;
35
36use anyhow::{anyhow, Result};
37
38/// Auto-detect format and parse logic expression
39///
40/// This function attempts to auto-detect the format based on syntax patterns
41/// and parse accordingly.
42///
43/// # Examples
44///
45/// ```
46/// use tensorlogic_compiler::import::parse_auto;
47///
48/// // Prolog format
49/// let expr1 = parse_auto("mortal(socrates).").unwrap();
50///
51/// // S-expression format
52/// let expr2 = parse_auto("(and (P x) (Q x))").unwrap();
53/// ```
54pub fn parse_auto(input: &str) -> Result<tensorlogic_ir::TLExpr> {
55    let trimmed = input.trim();
56
57    // Detect format based on syntax (check TPTP before S-expr to avoid false positives)
58    if trimmed.starts_with("fof(") || trimmed.starts_with("cnf(") {
59        // TPTP format
60        parse_tptp(trimmed)
61    } else if trimmed.starts_with('(') {
62        // S-expression format
63        parse_sexpr(trimmed)
64    } else if trimmed.contains(":-") || trimmed.contains('.') {
65        // Prolog format
66        parse_prolog(trimmed)
67    } else {
68        Err(anyhow!(
69            "Unable to auto-detect format for input: {}",
70            trimmed
71        ))
72    }
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use tensorlogic_ir::TLExpr;
79
80    #[test]
81    fn test_auto_detect_sexpr() {
82        let expr = parse_auto("(and (P x) (Q x))").unwrap();
83        assert!(matches!(expr, TLExpr::And(_, _)));
84    }
85
86    #[test]
87    fn test_auto_detect_prolog() {
88        let expr = parse_auto("mortal(X).").unwrap();
89        assert!(matches!(expr, TLExpr::Pred { .. }));
90    }
91
92    #[test]
93    fn test_auto_detect_unknown() {
94        let result = parse_auto("random text without structure");
95        assert!(result.is_err());
96    }
97}