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

            
3
use conjure_cp::ast::sat_decision::AmoEncoding;
4
use conjure_cp::ast::{AbstractLiteral, Literal, Name};
5
use conjure_cp::pipeline::{Config, Pipeline};
6
use conjure_cp::settings::{
7
    self, Channelling, Heuristic, Parser, QuantifiedExpander, SolverFamily,
8
};
9
use conjure_cp::solutions::SolutionOptions;
10
use conjure_cp_rules as _;
11

            
12
const PARAMETERISED: &str =
13
    "language Essence 1.3\ngiven n : int\nfind x : int(1..3)\nsuch that x <= n";
14

            
15
17
fn all_solutions() -> SolutionOptions {
16
17
    SolutionOptions {
17
17
        number_of_solutions: 0,
18
17
        ..Default::default()
19
17
    }
20
17
}
21

            
22
2
fn solve_parameterised(solver: SolverFamily) {
23
2
    let pipeline = Pipeline::new(Config {
24
2
        solver,
25
2
        ..Default::default()
26
2
    })
27
2
    .unwrap();
28
2
    let model = pipeline
29
2
        .compile(PARAMETERISED, Some("language Essence 1.3\nletting n be 2"))
30
2
        .unwrap();
31
2
    let solutions = pipeline.solve(model, &all_solutions()).unwrap();
32
2
    let values: BTreeSet<_> = solutions
33
2
        .iter()
34
4
        .map(|solution| match solution.get(&Name::user("x")).unwrap() {
35
4
            Literal::Int(value) => *value,
36
            value => panic!("expected integer x, got {value}"),
37
4
        })
38
        .collect();
39
2
    assert_eq!(values, BTreeSet::from([1, 2]));
40
2
    assert_eq!(solutions.len(), 2);
41
2
}
42

            
43
#[test]
44
1
fn minion_compiles_and_solves_source_and_parameters_in_memory() {
45
1
    solve_parameterised(SolverFamily::Minion);
46
1
}
47

            
48
2
fn check_constant_models(solver: SolverFamily) {
49
2
    let pipeline = Pipeline::new(Config {
50
2
        solver,
51
2
        ..Default::default()
52
2
    })
53
2
    .unwrap();
54
2
    let satisfiable = pipeline.compile("such that true", None).unwrap();
55
2
    assert_eq!(
56
2
        pipeline.solve(satisfiable, &all_solutions()).unwrap(),
57
2
        vec![BTreeMap::new()]
58
    );
59
2
    let unsatisfiable = pipeline.compile("such that false", None).unwrap();
60
2
    assert!(
61
2
        pipeline
62
2
            .solve(unsatisfiable, &all_solutions())
63
2
            .unwrap()
64
2
            .is_empty()
65
    );
66
2
}
67

            
68
#[test]
69
1
fn minion_distinguishes_empty_assignments_from_unsatisfiable_constant_models() {
70
1
    check_constant_models(SolverFamily::Minion);
71
1
}
72

            
73
#[cfg(any(feature = "sat-batsat", feature = "sat-cadical"))]
74
#[test]
75
1
fn sat_distinguishes_empty_assignments_from_unsatisfiable_constant_models() {
76
1
    check_constant_models(SolverFamily::Sat);
77
1
}
78

            
79
#[test]
80
1
fn solutions_reconstruct_structured_values_and_remove_auxiliaries() {
81
1
    let pipeline = Pipeline::new(Config::default()).unwrap();
82
1
    let model = pipeline
83
1
        .compile("find s : set (size 1) of int(1..2)", None)
84
1
        .unwrap();
85
1
    let solutions = pipeline.solve(model, &all_solutions()).unwrap();
86
1
    assert_eq!(solutions.len(), 2);
87
1
    for solution in &solutions {
88
2
        assert_eq!(solution.len(), 1);
89
2
        assert!(matches!(
90
2
            solution.get(&Name::user("s")),
91
            Some(Literal::AbstractLiteral(AbstractLiteral::Set(_)))
92
        ));
93
    }
94
1
    for value in [1, 2] {
95
2
        assert!(
96
2
            solutions
97
2
                .iter()
98
3
                .any(|solution| solution.get(&Name::user("s"))
99
3
                    == Some(&Literal::AbstractLiteral(AbstractLiteral::Set(vec![
100
3
                        Literal::Int(value)
101
3
                    ]))))
102
        );
103
    }
104
1
}
105

            
106
#[cfg(any(feature = "sat-batsat", feature = "sat-cadical"))]
107
#[test]
108
1
fn sat_compiles_and_solves_source_and_parameters_in_memory() {
109
1
    solve_parameterised(SolverFamily::Sat);
110
1
}
111

            
112
#[test]
113
1
fn invalid_rules_and_input_return_errors_and_allow_the_next_run() {
114
1
    let error = Pipeline::new(Config {
115
1
        extra_rule_sets: vec!["nonexistent-fuzzer-rules".into()],
116
1
        ..Default::default()
117
1
    })
118
1
    .err()
119
1
    .unwrap();
120
1
    assert!(error.to_string().contains("could not resolve rule sets"));
121

            
122
1
    let pipeline = Pipeline::new(Config::default()).unwrap();
123
1
    assert!(pipeline.parse("find x : int(").is_err());
124
1
    assert!(pipeline.compile(PARAMETERISED, None).is_err());
125
1
    let model = pipeline.compile("find x : bool", None).unwrap();
126
1
    assert_eq!(pipeline.solve(model, &all_solutions()).unwrap().len(), 2);
127
1
}
128

            
129
#[test]
130
1
fn native_file_parsing_and_io_errors() {
131
1
    let directory = tempfile::tempdir().unwrap();
132
1
    let path = directory.path().join("model.essence");
133
1
    std::fs::write(&path, "find x : bool").unwrap();
134
1
    let pipeline = Pipeline::new(Config::default()).unwrap();
135
1
    let model = pipeline.parse_file(&path).unwrap();
136
1
    let model = pipeline.rewrite(model).unwrap();
137
1
    assert_eq!(pipeline.solve(model, &all_solutions()).unwrap().len(), 2);
138
1
    assert!(
139
1
        pipeline
140
1
            .parse_file(directory.path().join("missing.essence"))
141
1
            .is_err()
142
    );
143
1
}
144

            
145
#[cfg(unix)]
146
#[test]
147
1
fn non_utf8_paths_return_io_errors_without_panicking() {
148
    use std::ffi::OsString;
149
    use std::os::unix::ffi::OsStringExt;
150

            
151
1
    let directory = tempfile::tempdir().unwrap();
152
1
    let path = directory
153
1
        .path()
154
1
        .join(OsString::from_vec(b"missing-\xff.essence".to_vec()));
155
1
    let pipeline = Pipeline::new(Config::default()).unwrap();
156
1
    assert!(pipeline.parse_file(path).is_err());
157
1
}
158

            
159
#[test]
160
1
fn models_from_another_pipeline_are_rejected() {
161
1
    let first = Pipeline::new(Config::default()).unwrap();
162
1
    let second = Pipeline::new(Config::default()).unwrap();
163
1
    let model = first.parse("find x : bool").unwrap();
164
1
    let error = second.rewrite(model).err().unwrap();
165
1
    assert!(error.to_string().contains("different pipeline context"));
166

            
167
1
    let model = first.compile("find x : bool", None).unwrap();
168
1
    let error = second.solve(model, &all_solutions()).err().unwrap();
169
1
    assert!(error.to_string().contains("different pipeline context"));
170
1
}
171

            
172
#[test]
173
1
fn repeated_seeded_runs_restore_the_callers_settings_and_random_stream() {
174
1
    settings::with_saved_settings(|| {
175
1
        settings::set_current_parser(Parser::ViaConjure);
176
1
        settings::set_current_solver_family(SolverFamily::Z3);
177
1
        settings::set_comprehension_expander(QuantifiedExpander::ViaSolverAc);
178
1
        settings::set_heuristic(Heuristic::Interactive);
179
1
        settings::set_channelling(Channelling::Uniform);
180
1
        settings::set_amo_encoding(Some(AmoEncoding::Pairwise));
181
1
        settings::set_heuristic_responses(vec![2]);
182
1
        settings::set_heuristic_seed(99);
183
1
        let expected_next_random = settings::next_heuristic_random_index(997);
184
1
        settings::set_heuristic_seed(99);
185

            
186
1
        let random = Pipeline::new(Config {
187
1
            heuristic: Heuristic::Random,
188
1
            seed: 42,
189
1
            ..Default::default()
190
1
        })
191
1
        .unwrap();
192
1
        let compact = Pipeline::new(Config::default()).unwrap();
193
1
        let source = "find x, y : int(0..3)\nsuch that x + y = 3";
194
1
        let first = random.compile(source, None).unwrap();
195
1
        let first_text = first.to_string();
196
1
        let first_solutions = random.solve(first, &all_solutions()).unwrap();
197
1
        let other = compact.compile(source, None).unwrap();
198
1
        assert_eq!(compact.solve(other, &all_solutions()).unwrap().len(), 4);
199
1
        let repeated = random.compile(source, None).unwrap();
200
1
        assert_eq!(repeated.to_string(), first_text);
201
1
        let repeated_solutions = random.solve(repeated, &all_solutions()).unwrap();
202
1
        assert_eq!(repeated_solutions, first_solutions);
203

            
204
1
        assert_eq!(settings::current_parser(), Parser::ViaConjure);
205
1
        assert_eq!(settings::current_solver_family(), SolverFamily::Z3);
206
1
        assert_eq!(
207
1
            settings::comprehension_expander(),
208
1
            QuantifiedExpander::ViaSolverAc
209
        );
210
1
        assert_eq!(settings::heuristic(), Heuristic::Interactive);
211
1
        assert_eq!(settings::channelling(), Channelling::Uniform);
212
1
        assert_eq!(settings::amo_encoding(), Some(AmoEncoding::Pairwise));
213
1
        assert_eq!(
214
1
            settings::next_heuristic_random_index(997),
215
1
            expected_next_random
216
        );
217
1
        assert_eq!(settings::next_heuristic_interactive_index(&["a", "b"]), 1);
218
1
    });
219
1
}
220

            
221
#[cfg(any(feature = "sat-batsat", feature = "sat-cadical"))]
222
#[test]
223
1
fn interleaved_solver_families_use_their_own_configuration() {
224
1
    let minion = Pipeline::new(Config::default()).unwrap();
225
1
    let sat = Pipeline::new(Config {
226
1
        solver: SolverFamily::Sat,
227
1
        ..Default::default()
228
1
    })
229
1
    .unwrap();
230
1
    let source = "find x : bool";
231
1
    let minion_model = minion.compile(source, None).unwrap();
232
1
    let sat_model = sat.compile(source, None).unwrap();
233
1
    let minion_solutions = minion.solve(minion_model, &all_solutions()).unwrap();
234
1
    let sat_solutions = sat.solve(sat_model, &all_solutions()).unwrap();
235
1
    assert_eq!(minion_solutions.len(), 2);
236
1
    assert_eq!(sat_solutions.len(), 2);
237
1
    for value in [false, true] {
238
2
        let expected = std::collections::BTreeMap::from([(Name::user("x"), Literal::Bool(value))]);
239
2
        assert!(minion_solutions.contains(&expected));
240
2
        assert!(sat_solutions.contains(&expected));
241
    }
242
1
    assert!(
243
1
        minion_solutions
244
1
            .iter()
245
2
            .all(|solution| sat_solutions.contains(solution))
246
    );
247
1
}
248

            
249
#[test]
250
1
fn optimisation_retains_the_optimum() {
251
1
    let pipeline = Pipeline::new(Config::default()).unwrap();
252
1
    let model = pipeline
253
1
        .compile("find x : int(0..5)\nmaximising x", None)
254
1
        .unwrap();
255
1
    let solutions = pipeline.solve(model, &SolutionOptions::default()).unwrap();
256
1
    assert_eq!(solutions.len(), 1);
257
1
    assert_eq!(solutions[0].get(&Name::user("x")), Some(&Literal::Int(5)));
258
1
}
259

            
260
#[test]
261
1
fn dominance_rewrites_use_the_pipeline_settings_during_solving() {
262
1
    settings::with_saved_settings(|| {
263
1
        settings::set_current_solver_family(SolverFamily::Z3);
264
1
        settings::set_current_rewriter(settings::Rewriter::Rewrite(
265
1
            settings::RewriteConfig::baseline(),
266
1
        ));
267
1
        let pipeline = Pipeline::new(Config::default()).unwrap();
268
1
        let model = pipeline
269
1
            .compile(
270
1
                "find x : bool\ndominance relation (!x) /\\ fromSolution(x)",
271
1
                None,
272
1
            )
273
1
            .unwrap();
274
1
        let solutions = pipeline.solve(model, &all_solutions()).unwrap();
275
1
        assert_eq!(solutions.len(), 1);
276
1
        assert_eq!(
277
1
            solutions[0].get(&Name::user("x")),
278
1
            Some(&Literal::Bool(false))
279
        );
280
1
        assert_eq!(settings::current_solver_family(), SolverFamily::Z3);
281
1
        assert_eq!(
282
1
            settings::current_rewriter(),
283
1
            settings::Rewriter::Rewrite(settings::RewriteConfig::baseline())
284
        );
285
1
    });
286
1
}
287

            
288
#[test]
289
1
fn solver_backed_comprehensions_work_on_a_fresh_thread() {
290
1
    std::thread::spawn(|| {
291
1
        assert_eq!(settings::try_current_solver_family(), None);
292
1
        let pipeline = Pipeline::new(Config {
293
1
            comprehension_expander: QuantifiedExpander::ViaSolver,
294
1
            ..Default::default()
295
1
        })
296
1
        .unwrap();
297
1
        let model = pipeline
298
1
            .compile(
299
1
                "find x : int(1..3)\nsuch that x = sum([i | i : int(1..2)])",
300
1
                None,
301
1
            )
302
1
            .unwrap();
303
1
        let solutions = pipeline.solve(model, &all_solutions()).unwrap();
304
1
        assert_eq!(solutions.len(), 1);
305
1
        assert_eq!(solutions[0].get(&Name::user("x")), Some(&Literal::Int(3)));
306
1
        assert_eq!(settings::try_current_solver_family(), None);
307
1
    })
308
    .join()
309
    .unwrap();
310
1
}
311

            
312
#[cfg(not(feature = "z3"))]
313
#[test]
314
fn selecting_z3_without_the_feature_returns_an_error() {
315
    let error = Pipeline::new(Config {
316
        solver: SolverFamily::Z3,
317
        ..Default::default()
318
    })
319
    .err()
320
    .unwrap();
321
    assert!(
322
        error
323
            .to_string()
324
            .contains("Z3 solver support was not compiled in")
325
    );
326
}
327

            
328
#[cfg(not(any(
329
    feature = "sat-batsat",
330
    all(feature = "sat-cadical", not(target_family = "wasm"))
331
)))]
332
#[test]
333
fn selecting_sat_without_a_backend_returns_an_error() {
334
    let error = Pipeline::new(Config {
335
        solver: SolverFamily::Sat,
336
        ..Default::default()
337
    })
338
    .err()
339
    .unwrap();
340
    assert!(
341
        error
342
            .to_string()
343
            .contains("SAT solver support was not compiled in")
344
    );
345
}