1
#![allow(clippy::arc_with_non_send_sync)]
2

            
3
use std::{collections::BTreeSet, fmt::Display};
4

            
5
use crate::bug_assert;
6
use conjure_cp_core::ast::ReturnType;
7
use itertools::Itertools as _;
8
use parking_lot::RwLockReadGuard;
9
use serde::{Deserialize, Serialize};
10
use serde_with::serde_as;
11
use uniplate::{Biplate, Uniplate};
12

            
13
use super::{
14
    DeclarationPtr, Domain, DomainPtr, Expression, Model, Name, Range, SymbolTable, SymbolTablePtr,
15
    Typeable,
16
    ac_operators::ACOperatorKind,
17
    categories::{Category, CategoryOf},
18
    serde::{AsId, PtrAsInner},
19
};
20

            
21
#[serde_as]
22
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug, Uniplate)]
23
#[biplate(to=Expression)]
24
#[biplate(to=Name)]
25
#[biplate(to=DeclarationPtr)]
26
pub enum ComprehensionQualifier {
27
    ExpressionGenerator {
28
        #[serde_as(as = "AsId")]
29
        ptr: DeclarationPtr,
30
    },
31
    Generator {
32
        #[serde_as(as = "AsId")]
33
        ptr: DeclarationPtr,
34
    },
35
    Condition(Expression),
36
}
37

            
38
/// A comprehension.
39
#[serde_as]
40
#[derive(Clone, PartialEq, Eq, Hash, Uniplate, Serialize, Deserialize, Debug)]
41
#[biplate(to=Expression)]
42
#[biplate(to=SymbolTable)]
43
#[biplate(to=SymbolTablePtr)]
44
#[non_exhaustive]
45
pub struct Comprehension {
46
    pub return_expression: Expression,
47
    pub qualifiers: Vec<ComprehensionQualifier>,
48
    /// When this comprehension appears inside an AC operator, records which operator so
49
    /// expansion can apply the correct skip semantics for symbolic guards.
50
    #[serde(default)]
51
    pub skip_operator: Option<ACOperatorKind>,
52
    #[doc(hidden)]
53
    #[serde_as(as = "PtrAsInner")]
54
    pub symbols: SymbolTablePtr,
55
}
56

            
57
impl Comprehension {
58
270514
    pub fn domain_of(&self) -> Option<DomainPtr> {
59
270514
        let return_expr_domain = self.return_expression.domain_of()?;
60

            
61
        // return a list (matrix with index domain int(1..)) of return_expr elements
62
270390
        Some(Domain::matrix(
63
270390
            return_expr_domain,
64
270390
            vec![Domain::int(vec![Range::UnboundedR(1)])],
65
270390
        ))
66
270514
    }
67

            
68
1117691
    pub fn return_expression(self) -> Expression {
69
1117691
        self.return_expression
70
1117691
    }
71

            
72
    pub fn replace_return_expression(&mut self, new_expr: Expression) {
73
        self.return_expression = new_expr;
74
    }
75

            
76
9994703
    pub fn symbols(&self) -> RwLockReadGuard<'_, SymbolTable> {
77
9994703
        self.symbols.read()
78
9994703
    }
79

            
80
1197858
    pub fn quantified_vars(&self) -> Vec<Name> {
81
1197858
        self.qualifiers
82
1197858
            .iter()
83
2250426
            .filter_map(|q| match q {
84
271606
                ComprehensionQualifier::ExpressionGenerator { ptr } => Some(ptr.name().clone()),
85
1576691
                ComprehensionQualifier::Generator { ptr } => Some(ptr.name().clone()),
86
402129
                ComprehensionQualifier::Condition(_) => None,
87
2250426
            })
88
            .collect()
89
1197858
    }
90

            
91
6714
    pub fn generator_conditions(&self) -> Vec<Expression> {
92
6714
        self.qualifiers
93
6714
            .iter()
94
9416
            .filter_map(|q| match q {
95
                ComprehensionQualifier::Condition(c) => Some(c.clone()),
96
9416
                ComprehensionQualifier::Generator { .. } => None,
97
                ComprehensionQualifier::ExpressionGenerator { .. } => None,
98
9416
            })
99
            .collect()
100
6714
    }
101

            
102
    /// Builds a temporary model containing generator qualifiers and guards.
103
6714
    pub fn to_generator_model(&self) -> Model {
104
6714
        let mut model = self.empty_model_with_symbols();
105
6714
        model.add_constraints(self.generator_conditions());
106
6714
        model
107
6714
    }
108

            
109
    /// Builds a temporary model containing the return expression only.
110
6714
    pub fn to_return_expression_model(&self) -> Model {
111
6714
        let mut model = self.empty_model_with_symbols();
112
6714
        model.add_constraint(self.return_expression.clone());
113
6714
        model
114
6714
    }
115

            
116
13428
    fn empty_model_with_symbols(&self) -> Model {
117
13428
        let parent = self.symbols.read().parent().clone();
118
13428
        let mut model = if let Some(parent) = parent {
119
13428
            Model::new_in_parent_scope(parent)
120
        } else {
121
            Model::default()
122
        };
123
13428
        *model.symbols_ptr_unchecked_mut() = self.symbols.clone();
124
13428
        model
125
13428
    }
126

            
127
    /// Adds a guard to the comprehension.
128
    ///
129
    /// Returns false if the guard references non-quantified decision variables.
130
    pub fn add_quantified_guard(&mut self, guard: Expression) -> bool {
131
        if self.is_quantified_guard(&guard) {
132
            self.qualifiers
133
                .push(ComprehensionQualifier::Condition(guard));
134
            true
135
        } else {
136
            false
137
        }
138
    }
139

            
140
    /// True iff expr does not reference non-quantified decision variables.
141
1785
    pub fn is_quantified_guard(&self, expr: &Expression) -> bool {
142
1785
        let quantified: BTreeSet<Name> = self.quantified_vars().into_iter().collect();
143
1785
        is_quantified_guard(&self.symbols.read(), &quantified, expr)
144
1785
    }
145
}
146

            
147
impl Typeable for Comprehension {
148
    /// A comprehension is a collection, so its type is a matrix of the return expression's type.
149
    ///
150
    /// This agrees with [`Comprehension::domain_of`], which reports a matrix domain. Reporting the
151
    /// element type here instead made every "is this a collection?" test quietly miss
152
    /// comprehensions.
153
186
    fn return_type(&self) -> ReturnType {
154
186
        ReturnType::Matrix(Box::new(self.return_expression.return_type()))
155
186
    }
156
}
157

            
158
impl Display for Comprehension {
159
83925
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160
83925
        let generators_and_guards = self
161
83925
            .qualifiers
162
83925
            .iter()
163
141741
            .map(|qualifier| match qualifier {
164
                ComprehensionQualifier::Generator { ptr } => {
165
112530
                    let domain = ptr.domain().expect("generator declaration has domain");
166
112530
                    format!("{} : {domain}", ptr.name())
167
                }
168
                ComprehensionQualifier::ExpressionGenerator { ptr } => {
169
11178
                    let name = ptr.name();
170
11178
                    if let Some(expr) = ptr.as_quantified_expr() {
171
11178
                        format!("{name} <- {expr}")
172
                    } else {
173
                        panic!("Oh nein! Dat is nicht gut!")
174
                    }
175
                }
176
18033
                ComprehensionQualifier::Condition(expr) => format!("{expr}"),
177
141741
            })
178
83925
            .join(", ");
179

            
180
83925
        write!(
181
83925
            f,
182
83925
            "[ {} | {generators_and_guards} ]",
183
83925
            self.return_expression
184
        )
185
83925
    }
186
}
187

            
188
/// A builder for a comprehension.
189
#[derive(Clone, Debug, PartialEq, Eq)]
190
pub struct ComprehensionBuilder {
191
    qualifiers: Vec<ComprehensionQualifier>,
192
    // A single scope for generators and return expression.
193
    symbols: SymbolTablePtr,
194
    quantified_variables: BTreeSet<Name>,
195
}
196

            
197
impl ComprehensionBuilder {
198
512155
    pub fn new(symbol_table_ptr: SymbolTablePtr) -> Self {
199
512155
        ComprehensionBuilder {
200
512155
            qualifiers: vec![],
201
512155
            symbols: SymbolTablePtr::with_parent(symbol_table_ptr),
202
512155
            quantified_variables: BTreeSet::new(),
203
512155
        }
204
512155
    }
205

            
206
    /// Backwards-compatible parser API: same table for generators and return expression.
207
171100
    pub fn generator_symboltable(&mut self) -> SymbolTablePtr {
208
171100
        self.symbols.clone()
209
171100
    }
210

            
211
    /// Backwards-compatible parser API: same table for generators and return expression.
212
503446
    pub fn return_expr_symboltable(&mut self) -> SymbolTablePtr {
213
503446
        self.symbols.clone()
214
503446
    }
215

            
216
50870
    pub fn guard(mut self, guard: Expression) -> Self {
217
50870
        self.qualifiers
218
50870
            .push(ComprehensionQualifier::Condition(guard));
219
50870
        self
220
50870
    }
221

            
222
420619
    pub fn generator(mut self, declaration: DeclarationPtr) -> Self {
223
420619
        let name = declaration.name().clone();
224
        bug_assert!(!self.quantified_variables.contains(&name));
225

            
226
420619
        self.quantified_variables.insert(name.clone());
227

            
228
        // insert into comprehension scope as a local quantified variable
229
420619
        let quantified_decl = DeclarationPtr::new_quantified(name, declaration.domain().unwrap());
230
420619
        self.symbols.write().insert(quantified_decl.clone());
231

            
232
420619
        self.qualifiers.push(ComprehensionQualifier::Generator {
233
420619
            ptr: quantified_decl,
234
420619
        });
235

            
236
420619
        self
237
420619
    }
238

            
239
283399
    pub fn expression_generator(mut self, name: Name, expr: Expression) -> Self {
240
        bug_assert!(!self.quantified_variables.contains(&name));
241

            
242
283399
        self.quantified_variables.insert(name.clone());
243

            
244
        // insert into comprehension scope as a local quantified variable
245
283399
        let quantified_decl = DeclarationPtr::new_quantified_expr(name, expr);
246
283399
        self.symbols.write().insert(quantified_decl.clone());
247

            
248
283399
        self.qualifiers
249
283399
            .push(ComprehensionQualifier::ExpressionGenerator {
250
283399
                ptr: quantified_decl,
251
283399
            });
252

            
253
283399
        self
254
283399
    }
255

            
256
    /// Creates a comprehension with the given return expression.
257
    ///
258
    /// Guards are always stored as [`ComprehensionQualifier::Condition`] entries. When a guard
259
    /// references non-quantified decision variables, the enclosing AC operator applies the
260
    /// appropriate skip semantics during comprehension expansion.
261
512124
    pub fn with_return_value(self, expression: Expression) -> Comprehension {
262
512124
        Comprehension {
263
512124
            return_expression: expression,
264
512124
            qualifiers: self.qualifiers,
265
512124
            skip_operator: None,
266
512124
            symbols: self.symbols,
267
512124
        }
268
512124
    }
269
}
270

            
271
/// True iff the guard does not reference non-quantified decision variables.
272
1785
fn is_quantified_guard(
273
1785
    symbols: &SymbolTable,
274
1785
    quantified_variables: &BTreeSet<Name>,
275
1785
    guard: &Expression,
276
1785
) -> bool {
277
3769
    guard.universe_bi().iter().all(|name| {
278
3769
        quantified_variables.contains(name)
279
1599
            || symbols
280
1599
                .lookup(name)
281
204
                .is_some_and(|decl| decl.category_of() != Category::Decision)
282
3769
    })
283
1785
}