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 { name, domain } => {
53
582
            let values = resolve_generator_values(name, domain)?;
54
582
            let quantified_declaration = lookup_quantified_declaration(comprehension, name)?;
55

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

            
69
642
    Ok(())
70
3978
}
71

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

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

            
86
582
fn lookup_quantified_declaration(
87
582
    comprehension: &Comprehension,
88
582
    name: &Name,
89
582
) -> Result<DeclarationPtr, SolverError> {
90
582
    comprehension.symbols().lookup_local(name).ok_or_else(|| {
91
        SolverError::ModelInvalid(format!(
92
            "quantified variable '{name}' is missing from local comprehension symbol table"
93
        ))
94
    })
95
582
}
96

            
97
3891
fn with_temporary_quantified_binding<T>(
98
3891
    quantified: &DeclarationPtr,
99
3891
    value: &Literal,
100
3891
    f: impl FnOnce() -> Result<T, SolverError>,
101
3891
) -> Result<T, SolverError> {
102
3891
    let mut targets = vec![quantified.clone()];
103
3891
    if let DeclarationKind::Quantified(inner) = &*quantified.kind()
104
3891
        && let Some(generator) = inner.generator()
105
    {
106
        targets.push(generator.clone());
107
3891
    }
108

            
109
3891
    let mut originals = Vec::with_capacity(targets.len());
110
3891
    for mut target in targets {
111
3891
        let old_kind = target.replace_kind(DeclarationKind::TemporaryValueLetting(
112
3891
            Expression::Atomic(Metadata::new(), Atom::Literal(value.clone())),
113
3891
        ));
114
3891
        originals.push((target, old_kind));
115
3891
    }
116

            
117
3891
    let result = f();
118

            
119
3891
    for (mut target, old_kind) in originals.into_iter().rev() {
120
3891
        let _ = target.replace_kind(old_kind);
121
3891
    }
122

            
123
3891
    result
124
3891
}
125

            
126
60
fn evaluate_guard(guard: &Expression) -> Result<bool, SolverError> {
127
60
    let simplified = simplify_expression(guard.clone());
128
60
    match eval_constant(&simplified) {
129
60
        Some(Literal::Bool(value)) => Ok(value),
130
        Some(other) => Err(SolverError::ModelInvalid(format!(
131
            "native comprehension guard must evaluate to Bool, got {other}: {guard}"
132
        ))),
133
        None => Err(SolverError::ModelInvalid(format!(
134
            "native comprehension expansion could not evaluate guard: {guard}"
135
        ))),
136
    }
137
60
}
138

            
139
3336
fn concretise_resolved_reference_atoms(expr: Expression) -> Expression {
140
66981
    expr.transform_bi(&|atom: Atom| match atom {
141
57936
        Atom::Reference(reference) => reference
142
57936
            .resolve_constant()
143
57936
            .map_or_else(|| Atom::Reference(reference), Atom::Literal),
144
9045
        other => other,
145
66981
    })
146
3336
}