1
use conjure_cp::{
2
    ast::{
3
        Atom, DeclarationKind, DeclarationPtr, DomainPtr, Expression, Literal, Metadata, Name,
4
        SymbolTable,
5
        comprehension::{Comprehension, ComprehensionQualifier},
6
        eval_constant,
7
    },
8
    solver::SolverError,
9
};
10
use uniplate::Biplate as _;
11

            
12
use super::via_solver_common::{lift_machine_references_into_parent_scope, simplify_expression};
13

            
14
/// Expands the comprehension without calling an external solver.
15
///
16
/// Algorithm:
17
/// 1. Recurse qualifiers left-to-right.
18
/// 2. For each generator value, temporarily bind the quantified declaration to a
19
///    `TemporaryValueLetting` and recurse.
20
/// 3. For each condition, evaluate and recurse only if true.
21
/// 4. At the leaf, evaluate the return expression under the active bindings.
22
54
pub fn expand_native(
23
54
    comprehension: Comprehension,
24
54
    parent_symbols: &mut SymbolTable,
25
54
) -> Result<Vec<Expression>, SolverError> {
26
54
    let mut expanded = Vec::new();
27
54
    expand_qualifiers(&comprehension, 0, &mut expanded, parent_symbols)?;
28
54
    Ok(expanded)
29
54
}
30

            
31
3978
fn expand_qualifiers(
32
3978
    comprehension: &Comprehension,
33
3978
    qualifier_index: usize,
34
3978
    expanded: &mut Vec<Expression>,
35
3978
    parent_symbols: &mut SymbolTable,
36
3978
) -> Result<(), SolverError> {
37
3978
    if qualifier_index == comprehension.qualifiers.len() {
38
3336
        let child_symbols = comprehension.symbols().clone();
39
3336
        let return_expression =
40
3336
            concretise_resolved_reference_atoms(comprehension.return_expression.clone());
41
3336
        let return_expression = simplify_expression(return_expression);
42
3336
        let return_expression = lift_machine_references_into_parent_scope(
43
3336
            return_expression,
44
3336
            &child_symbols,
45
3336
            parent_symbols,
46
        );
47
3336
        expanded.push(return_expression);
48
3336
        return Ok(());
49
642
    }
50

            
51
642
    match &comprehension.qualifiers[qualifier_index] {
52
582
        ComprehensionQualifier::Generator { ptr } => {
53
582
            let name = ptr.name().clone();
54
582
            let domain = ptr.domain().expect("generator declaration has domain");
55
582
            let values = resolve_generator_values(&name, &domain)?;
56

            
57
3891
            for literal in values {
58
3891
                with_temporary_quantified_binding(ptr, &literal, || {
59
3891
                    expand_qualifiers(comprehension, qualifier_index + 1, expanded, parent_symbols)
60
3891
                })?;
61
            }
62
        }
63
60
        ComprehensionQualifier::Condition(condition) => {
64
60
            if evaluate_guard(condition)? {
65
33
                expand_qualifiers(comprehension, qualifier_index + 1, expanded, parent_symbols)?;
66
27
            }
67
        }
68
    }
69

            
70
642
    Ok(())
71
3978
}
72

            
73
582
fn resolve_generator_values(name: &Name, domain: &DomainPtr) -> Result<Vec<Literal>, SolverError> {
74
582
    let resolved = domain.resolve().ok_or_else(|| {
75
        SolverError::ModelFeatureNotSupported(format!(
76
            "quantified variable '{name}' has unresolved domain after assigning previous generators: {domain}"
77
        ))
78
    })?;
79

            
80
582
    resolved.values().map(|iter| iter.collect()).map_err(|err| {
81
        SolverError::ModelFeatureNotSupported(format!(
82
            "quantified variable '{name}' has non-enumerable domain: {err}"
83
        ))
84
    })
85
582
}
86

            
87
3891
fn with_temporary_quantified_binding<T>(
88
3891
    quantified: &DeclarationPtr,
89
3891
    value: &Literal,
90
3891
    f: impl FnOnce() -> Result<T, SolverError>,
91
3891
) -> Result<T, SolverError> {
92
3891
    let mut targets = vec![quantified.clone()];
93
3891
    if let DeclarationKind::Quantified(inner) = &*quantified.kind()
94
3891
        && let Some(generator) = inner.generator()
95
    {
96
        targets.push(generator.clone());
97
3891
    }
98

            
99
3891
    let mut originals = Vec::with_capacity(targets.len());
100
3891
    for mut target in targets {
101
3891
        let old_kind = target.replace_kind(DeclarationKind::TemporaryValueLetting(
102
3891
            Expression::Atomic(Metadata::new(), Atom::Literal(value.clone())),
103
3891
        ));
104
3891
        originals.push((target, old_kind));
105
3891
    }
106

            
107
3891
    let result = f();
108

            
109
3891
    for (mut target, old_kind) in originals.into_iter().rev() {
110
3891
        let _ = target.replace_kind(old_kind);
111
3891
    }
112

            
113
3891
    result
114
3891
}
115

            
116
60
fn evaluate_guard(guard: &Expression) -> Result<bool, SolverError> {
117
60
    let simplified = simplify_expression(guard.clone());
118
60
    match eval_constant(&simplified) {
119
60
        Some(Literal::Bool(value)) => Ok(value),
120
        Some(other) => Err(SolverError::ModelInvalid(format!(
121
            "native comprehension guard must evaluate to Bool, got {other}: {guard}"
122
        ))),
123
        None => Err(SolverError::ModelInvalid(format!(
124
            "native comprehension expansion could not evaluate guard: {guard}"
125
        ))),
126
    }
127
60
}
128

            
129
3336
fn concretise_resolved_reference_atoms(expr: Expression) -> Expression {
130
66981
    expr.transform_bi(&|atom: Atom| match atom {
131
57936
        Atom::Reference(reference) => reference
132
57936
            .resolve_constant()
133
57936
            .map_or_else(|| Atom::Reference(reference), Atom::Literal),
134
9045
        other => other,
135
66981
    })
136
3336
}