xlog-logic 0.9.2

Parser, compiler, and optimizer for XLOG logic programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Stable diagnostic records for rule provenance and query proof traces.

use std::collections::{BTreeMap, BTreeSet};

use xlog_core::symbol;

use crate::ast::{AggOp, ArithExpr, Atom, BodyLiteral, CompOp, Program, Rule, Term};

/// Origin class for a rule visible through diagnostic introspection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleSourceKind {
    /// Authored in the parsed XLOG source.
    Source,
    /// Generated by a compiler or rewrite pass.
    Generated,
    /// Mined or induced by an external rule search path.
    Mined,
    /// Imported from a module boundary.
    Imported,
    /// Injected into a live runtime session.
    RuntimeInjected,
}

impl RuleSourceKind {
    /// Stable lowercase string used by CLI and pyxlog JSON/dict outputs.
    pub fn as_str(self) -> &'static str {
        match self {
            RuleSourceKind::Source => "source",
            RuleSourceKind::Generated => "generated",
            RuleSourceKind::Mined => "mined",
            RuleSourceKind::Imported => "imported",
            RuleSourceKind::RuntimeInjected => "runtime_injected",
        }
    }
}

/// Public rule provenance record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleProvenance {
    /// Stable rule identifier within the diagnostic report.
    pub rule_id: String,
    /// Formatted rule head, e.g. `reach(X, Y)`.
    pub head: String,
    /// Rule origin class.
    pub source_kind: RuleSourceKind,
    /// Source span when available from the parser.
    pub source_span: Option<String>,
    /// Stable hash of the source or generation trace.
    pub generation_trace_hash: Option<String>,
    /// Body relation ids that support this rule.
    pub support_relation_ids: Vec<String>,
    /// Counterexample relation ids when supplied by an induction path.
    pub counterexample_relation_ids: Vec<String>,
}

/// Public query proof trace record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct QueryProofTrace {
    /// Stable query identifier.
    pub query_id: String,
    /// Formatted source query atom.
    pub query: String,
    /// Internal answer relation for the query.
    pub answer_relation: String,
    /// Rule ids that can derive the query predicate.
    pub rule_ids: Vec<String>,
    /// Source facts named by the direct proof frontier.
    pub source_facts: Vec<String>,
    /// Rejected or negated alternatives encountered in the trace.
    pub rejected_alternatives: Vec<String>,
}

/// Build provenance for source rules and optional generated rewrite rules.
pub fn rule_provenance(
    program: &Program,
    generated_program: Option<&Program>,
) -> Vec<RuleProvenance> {
    let mut out = Vec::new();
    let mut source_keys = BTreeSet::new();

    for (idx, rule) in program.rules.iter().enumerate() {
        source_keys.insert(rule_key(rule));
        out.push(rule_record(idx, rule, RuleSourceKind::Source));
    }

    if let Some(generated) = generated_program {
        let mut generated_idx = 0usize;
        for rule in &generated.rules {
            if source_keys.contains(&rule_key(rule)) {
                continue;
            }
            out.push(rule_record(generated_idx, rule, RuleSourceKind::Generated));
            generated_idx += 1;
        }
    }

    out
}

/// Build source and generated rule-provenance records for a program.
pub fn build_rule_provenance(
    program: &Program,
    generated_predicates: &[String],
) -> Vec<RuleProvenance> {
    let mut out = rule_provenance(program, None);
    for (idx, predicate) in generated_predicates.iter().enumerate() {
        out.push(RuleProvenance {
            rule_id: format!("rule:generated:{}:{}", idx, predicate),
            head: predicate.clone(),
            source_kind: RuleSourceKind::Generated,
            source_span: None,
            generation_trace_hash: Some(stable_hash(&format!("generated:{}", predicate))),
            support_relation_ids: vec![predicate.clone()],
            counterexample_relation_ids: Vec::new(),
        });
    }
    out
}

/// Build direct proof traces for source queries.
pub fn query_proof_traces(
    program: &Program,
    provenance: &[RuleProvenance],
) -> Vec<QueryProofTrace> {
    let mut rule_ids_by_head: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for entry in provenance {
        rule_ids_by_head
            .entry(head_predicate(&entry.head).to_string())
            .or_default()
            .push(entry.rule_id.clone());
    }

    program
        .queries
        .iter()
        .enumerate()
        .map(|(idx, query)| {
            let query_pred = query.atom.predicate.clone();
            let deriving_rules: Vec<&Rule> = program
                .rules
                .iter()
                .filter(|rule| !rule.is_fact() && rule.head.predicate == query_pred)
                .collect();
            let rule_ids = rule_ids_by_head
                .get(&query_pred)
                .cloned()
                .unwrap_or_default();
            let source_facts = source_facts_for_rules(program, &deriving_rules);
            let rejected_alternatives = deriving_rules
                .iter()
                .flat_map(|rule| {
                    rule.body.iter().filter_map(|lit| match lit {
                        BodyLiteral::Negated(atom) => Some(format!("not {}", format_atom(atom))),
                        _ => None,
                    })
                })
                .collect::<Vec<_>>();

            QueryProofTrace {
                query_id: format!("query:source:{}:{}", idx, format_atom(&query.atom)),
                query: format_atom(&query.atom),
                answer_relation: format!("__xlog_query_{}", idx),
                rule_ids,
                source_facts,
                rejected_alternatives,
            }
        })
        .collect()
}

/// Build coarse proof traces that name source rules and source facts per query.
pub fn build_query_proof_traces(program: &Program) -> Vec<QueryProofTrace> {
    let provenance = rule_provenance(program, None);
    query_proof_traces(program, &provenance)
}

fn rule_record(idx: usize, rule: &Rule, source_kind: RuleSourceKind) -> RuleProvenance {
    let head = format_atom(&rule.head);
    let prefix = source_kind.as_str();
    RuleProvenance {
        rule_id: format!("rule:{}:{}:{}", prefix, idx, stable_hash(&rule_key(rule))),
        head,
        source_kind,
        source_span: Some(format!("rule_index:{}", idx)),
        generation_trace_hash: Some(stable_hash(&rule_key(rule))),
        support_relation_ids: support_relation_ids(rule),
        counterexample_relation_ids: Vec::new(),
    }
}

fn support_relation_ids(rule: &Rule) -> Vec<String> {
    rule.body_predicates()
        .into_iter()
        .map(str::to_string)
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

fn source_facts_for_rules(program: &Program, rules: &[&Rule]) -> Vec<String> {
    let wanted: BTreeSet<String> = rules
        .iter()
        .flat_map(|rule| {
            rule.body
                .iter()
                .filter_map(|lit| lit.atom().map(|atom| atom.predicate.clone()))
        })
        .collect();

    let mut facts = BTreeSet::new();
    for fact in program.facts() {
        if wanted.contains(&fact.head.predicate) {
            facts.insert(format!("{}.", format_atom(&fact.head)));
        }
    }
    facts.into_iter().collect()
}

fn rule_key(rule: &Rule) -> String {
    let mut out = format_atom(&rule.head);
    if !rule.body.is_empty() {
        let body = rule
            .body
            .iter()
            .map(format_body_literal)
            .collect::<Vec<_>>()
            .join(", ");
        out.push_str(" :- ");
        out.push_str(&body);
    }
    out
}

fn head_predicate(head: &str) -> &str {
    head.split_once('(').map(|(pred, _)| pred).unwrap_or(head)
}

/// Format an atom in source-like syntax.
pub fn format_atom(atom: &Atom) -> String {
    let args = atom
        .terms
        .iter()
        .map(format_term)
        .collect::<Vec<_>>()
        .join(", ");
    format!("{}({})", atom.predicate, args)
}

fn format_body_literal(lit: &BodyLiteral) -> String {
    match lit {
        BodyLiteral::Positive(atom) => format_atom(atom),
        BodyLiteral::Negated(atom) => format!("not {}", format_atom(atom)),
        BodyLiteral::Epistemic(lit) => format_epistemic_literal(lit),
        BodyLiteral::Comparison(comparison) => format!(
            "{} {} {}",
            format_term(&comparison.left),
            format_comp_op(comparison.op),
            format_term(&comparison.right)
        ),
        BodyLiteral::IsExpr(is_expr) => {
            format!("{} is {}", is_expr.target, format_arith_expr(&is_expr.expr))
        }
        BodyLiteral::Univ(univ) => {
            format!(
                "{} =.. {}",
                format_term(&univ.term),
                format_term(&univ.parts)
            )
        }
    }
}

fn format_epistemic_literal(lit: &crate::ast::EpistemicLiteral) -> String {
    let op = match lit.op {
        crate::ast::EpistemicOp::Know => "know",
        crate::ast::EpistemicOp::Possible => "possible",
    };
    if lit.negated {
        format!("not {} {}", op, format_atom(&lit.atom))
    } else {
        format!("{} {}", op, format_atom(&lit.atom))
    }
}

fn format_term(term: &Term) -> String {
    match term {
        Term::Variable(name) => name.clone(),
        Term::Anonymous => "_".to_string(),
        Term::Integer(value) => value.to_string(),
        Term::Float(value) => value.to_string(),
        Term::String(value) => format!("\"{}\"", value),
        Term::Symbol(id) => symbol::resolve(*id),
        Term::List(items) => {
            let values = items.iter().map(format_term).collect::<Vec<_>>().join(", ");
            format!("[{}]", values)
        }
        Term::Cons { head, tail } => {
            format!("[{} | {}]", format_term(head), format_term(tail))
        }
        Term::Compound { functor, args } => {
            let values = args.iter().map(format_term).collect::<Vec<_>>().join(", ");
            format!("{}({})", functor, values)
        }
        Term::PredRef(name) => name.clone(),
        Term::Aggregate(agg) => format!("{}({})", format_agg_op(agg.op), agg.variable),
    }
}

fn format_arith_expr(expr: &ArithExpr) -> String {
    match expr {
        ArithExpr::Variable(name) => name.clone(),
        ArithExpr::Integer(value) => value.to_string(),
        ArithExpr::Float(value) => value.to_string(),
        ArithExpr::Add(left, right) => {
            format!(
                "({} + {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Sub(left, right) => {
            format!(
                "({} - {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Mul(left, right) => {
            format!(
                "({} * {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Div(left, right) => {
            format!(
                "({} / {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Mod(left, right) => {
            format!(
                "({} % {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Abs(value) => format!("abs({})", format_arith_expr(value)),
        ArithExpr::Min(left, right) => {
            format!(
                "min({}, {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Max(left, right) => {
            format!(
                "max({}, {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Pow(left, right) => {
            format!(
                "pow({}, {})",
                format_arith_expr(left),
                format_arith_expr(right)
            )
        }
        ArithExpr::Cast(value, ty) => format!("cast({}, {:?})", format_arith_expr(value), ty),
        ArithExpr::FuncCall { name, args } => {
            let values = args
                .iter()
                .map(format_arith_expr)
                .collect::<Vec<_>>()
                .join(", ");
            format!("{}({})", name, values)
        }
        ArithExpr::Conditional {
            cond_left,
            cond_op,
            cond_right,
            then_expr,
            else_expr,
        } => format!(
            "if {} {} {} then {} else {}",
            format_arith_expr(cond_left),
            format_comp_op(*cond_op),
            format_arith_expr(cond_right),
            format_arith_expr(then_expr),
            format_arith_expr(else_expr)
        ),
    }
}

fn format_comp_op(op: CompOp) -> &'static str {
    match op {
        CompOp::Eq => "==",
        CompOp::Ne => "!=",
        CompOp::Lt => "<",
        CompOp::Le => "<=",
        CompOp::Gt => ">",
        CompOp::Ge => ">=",
    }
}

fn format_agg_op(op: AggOp) -> &'static str {
    match op {
        AggOp::Count => "count",
        AggOp::Sum => "sum",
        AggOp::Min => "min",
        AggOp::Max => "max",
        AggOp::LogSumExp => "logsumexp",
    }
}

fn stable_hash(value: &str) -> String {
    let mut hash = 0xcbf29ce484222325u64;
    for byte in value.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("{:016x}", hash)
}