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
132
pub fn expand_native(
23
132
    comprehension: Comprehension,
24
132
    parent_symbols: &mut SymbolTable,
25
132
) -> Result<Vec<Expression>, SolverError> {
26
132
    let mut expanded = Vec::new();
27
132
    expand_qualifiers(&comprehension, 0, &mut expanded, parent_symbols)?;
28
132
    Ok(expanded)
29
132
}
30

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

            
51
1308
    match &comprehension.qualifiers[qualifier_index] {
52
1188
        ComprehensionQualifier::Generator { name, domain } => {
53
1188
            let values = resolve_generator_values(name, domain)?;
54
1188
            let quantified_declaration = lookup_quantified_declaration(comprehension, name)?;
55

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

            
69
1308
    Ok(())
70
8040
}
71

            
72
1188
fn resolve_generator_values(name: &Name, domain: &DomainPtr) -> Result<Vec<Literal>, SolverError> {
73
1188
    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
1188
    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
1188
}
85

            
86
1188
fn lookup_quantified_declaration(
87
1188
    comprehension: &Comprehension,
88
1188
    name: &Name,
89
1188
) -> Result<DeclarationPtr, SolverError> {
90
1188
    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
1188
}
96

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

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

            
117
7842
    let result = f();
118

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

            
123
7842
    result
124
7842
}
125

            
126
120
fn evaluate_guard(guard: &Expression) -> Result<bool, SolverError> {
127
120
    let simplified = simplify_expression(guard.clone());
128
120
    match eval_constant(&simplified) {
129
120
        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
120
}
138

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