1
use std::collections::{BTreeMap, HashMap, HashSet};
2
use std::fmt::Debug;
3

            
4
use std::fs::File;
5
use std::fs::{read_to_string, OpenOptions};
6
use std::hash::Hash;
7
use std::io::Write;
8
use std::sync::{Arc, RwLock};
9

            
10
use conjure_core::ast::SerdeModel;
11
use conjure_core::context::Context;
12
use serde_json::{json, Error as JsonError, Value as JsonValue};
13

            
14
use conjure_core::error::Error;
15

            
16
use crate::ast::Name::UserName;
17
use crate::ast::{Literal, Name};
18
use crate::utils::conjure::minion_solutions_to_json;
19
use crate::utils::json::sort_json_object;
20
use crate::utils::misc::to_set;
21
use crate::Model as ConjureModel;
22

            
23
pub fn assert_eq_any_order<T: Eq + Hash + Debug + Clone>(a: &Vec<Vec<T>>, b: &Vec<Vec<T>>) {
24
    assert_eq!(a.len(), b.len());
25

            
26
    let mut a_rows: Vec<HashSet<T>> = Vec::new();
27
    for row in a {
28
        let hash_row = to_set(row);
29
        a_rows.push(hash_row);
30
    }
31

            
32
    let mut b_rows: Vec<HashSet<T>> = Vec::new();
33
    for row in b {
34
        let hash_row = to_set(row);
35
        b_rows.push(hash_row);
36
    }
37

            
38
    println!("{:?},{:?}", a_rows, b_rows);
39
    for row in a_rows {
40
        assert!(b_rows.contains(&row));
41
    }
42
}
43

            
44
1869
pub fn serialise_model(model: &ConjureModel) -> Result<String, JsonError> {
45
1869
    // A consistent sorting of the keys of json objects
46
1869
    // only required for the generated version
47
1869
    // since the expected version will already be sorted
48
1869
    let serde_model: SerdeModel = model.clone().into();
49
1869
    let generated_json = sort_json_object(&serde_json::to_value(serde_model)?, false);
50

            
51
    // serialise to string
52
1869
    let generated_json_str = serde_json::to_string_pretty(&generated_json)?;
53

            
54
1869
    Ok(generated_json_str)
55
1869
}
56

            
57
1869
pub fn save_model_json(
58
1869
    model: &ConjureModel,
59
1869
    path: &str,
60
1869
    test_name: &str,
61
1869
    test_stage: &str,
62
1869
    accept: bool,
63
1869
) -> Result<(), std::io::Error> {
64
1869
    let generated_json_str = serialise_model(model)?;
65

            
66
1869
    File::create(format!(
67
1869
        "{path}/{test_name}.generated-{test_stage}.serialised.json"
68
1869
    ))?
69
1869
    .write_all(generated_json_str.as_bytes())?;
70

            
71
1869
    if accept {
72
        std::fs::copy(
73
            format!("{path}/{test_name}.generated-{test_stage}.serialised.json"),
74
            format!("{path}/{test_name}.expected-{test_stage}.serialised.json"),
75
        )?;
76
1869
    }
77

            
78
1869
    Ok(())
79
1869
}
80

            
81
623
pub fn save_stats_json(
82
623
    context: Arc<RwLock<Context<'static>>>,
83
623
    path: &str,
84
623
    test_name: &str,
85
623
) -> Result<(), std::io::Error> {
86
623
    #[allow(clippy::unwrap_used)]
87
623
    let stats = context.read().unwrap().clone();
88
623
    let generated_json = sort_json_object(&serde_json::to_value(stats)?, false);
89

            
90
    // serialise to string
91
623
    let generated_json_str = serde_json::to_string_pretty(&generated_json)?;
92

            
93
623
    File::create(format!("{path}/{test_name}-stats.json"))?
94
623
        .write_all(generated_json_str.as_bytes())?;
95

            
96
623
    Ok(())
97
623
}
98

            
99
1869
pub fn read_model_json(
100
1869
    ctx: &Arc<RwLock<Context<'static>>>,
101
1869
    path: &str,
102
1869
    test_name: &str,
103
1869
    prefix: &str,
104
1869
    test_stage: &str,
105
1869
) -> Result<ConjureModel, std::io::Error> {
106
1869
    let expected_json_str = std::fs::read_to_string(format!(
107
1869
        "{path}/{test_name}.{prefix}-{test_stage}.serialised.json"
108
1869
    ))?;
109

            
110
1869
    let expected_model: SerdeModel = serde_json::from_str(&expected_json_str)?;
111

            
112
1869
    Ok(expected_model.initialise(ctx.clone()).unwrap())
113
1869
}
114

            
115
pub fn minion_solutions_from_json(
116
    serialized: &str,
117
) -> Result<Vec<HashMap<Name, Literal>>, anyhow::Error> {
118
    let json: JsonValue = serde_json::from_str(serialized)?;
119

            
120
    let json_array = json
121
        .as_array()
122
        .ok_or(Error::Parse("Invalid JSON".to_owned()))?;
123

            
124
    let mut solutions = Vec::new();
125

            
126
    for solution in json_array {
127
        let mut sol = HashMap::new();
128
        let solution = solution
129
            .as_object()
130
            .ok_or(Error::Parse("Invalid JSON".to_owned()))?;
131

            
132
        for (var_name, constant) in solution {
133
            let constant = match constant {
134
                JsonValue::Number(n) => {
135
                    let n = n
136
                        .as_i64()
137
                        .ok_or(Error::Parse("Invalid integer".to_owned()))?;
138
                    Literal::Int(n as i32)
139
                }
140
                JsonValue::Bool(b) => Literal::Bool(*b),
141
                _ => return Err(Error::Parse("Invalid constant".to_owned()).into()),
142
            };
143

            
144
            sol.insert(UserName(var_name.into()), constant);
145
        }
146

            
147
        solutions.push(sol);
148
    }
149

            
150
    Ok(solutions)
151
}
152

            
153
616
pub fn save_minion_solutions_json(
154
616
    solutions: &Vec<BTreeMap<Name, Literal>>,
155
616
    path: &str,
156
616
    test_name: &str,
157
616
    accept: bool,
158
616
) -> Result<JsonValue, std::io::Error> {
159
616
    let json_solutions = minion_solutions_to_json(solutions);
160

            
161
616
    let generated_json_str = serde_json::to_string_pretty(&json_solutions)?;
162

            
163
616
    File::create(format!(
164
616
        "{path}/{test_name}.generated-minion.solutions.json"
165
616
    ))?
166
616
    .write_all(generated_json_str.as_bytes())?;
167

            
168
616
    if accept {
169
        std::fs::copy(
170
            format!("{path}/{test_name}.generated-minion.solutions.json"),
171
            format!("{path}/{test_name}.expected-minion.solutions.json"),
172
        )?;
173
616
    }
174

            
175
616
    Ok(json_solutions)
176
616
}
177

            
178
616
pub fn read_minion_solutions_json(
179
616
    path: &str,
180
616
    test_name: &str,
181
616
    prefix: &str,
182
616
) -> Result<JsonValue, anyhow::Error> {
183
616
    let expected_json_str =
184
616
        std::fs::read_to_string(format!("{path}/{test_name}.{prefix}-minion.solutions.json"))?;
185

            
186
616
    let expected_solutions: JsonValue =
187
616
        sort_json_object(&serde_json::from_str(&expected_json_str)?, true);
188

            
189
616
    Ok(expected_solutions)
190
616
}
191

            
192
1246
pub fn read_rule_trace(
193
1246
    path: &str,
194
1246
    test_name: &str,
195
1246
    prefix: &str,
196
1246
    accept: bool,
197
1246
) -> Result<JsonValue, anyhow::Error> {
198
1246
    let filename = format!("{path}/{test_name}-{prefix}-rule-trace.json");
199

            
200
1246
    let rule_traces = if prefix == "generated" {
201
623
        count_and_sort_rules(&filename)?
202
    } else {
203
623
        let file_contents = std::fs::read_to_string(filename)?;
204
623
        serde_json::from_str(&file_contents)?
205
    };
206

            
207
1246
    if accept {
208
        std::fs::copy(
209
            format!("{path}/{test_name}-generated-rule-trace.json"),
210
            format!("{path}/{test_name}-expected-rule-trace.json"),
211
        )?;
212
1246
    }
213

            
214
1246
    Ok(rule_traces)
215
1246
}
216

            
217
623
pub fn count_and_sort_rules(filename: &str) -> Result<JsonValue, anyhow::Error> {
218
623
    let file_contents = read_to_string(filename)?;
219

            
220
623
    let sorted_json_rules = if file_contents.trim().is_empty() {
221
21
        let rule_count_message = json!({
222
21
            "Number of rules applied": 0,
223
21
        });
224
21
        rule_count_message
225
    } else {
226
602
        let rule_count = file_contents.lines().count();
227
602
        let mut sorted_json_rules = sort_json_rules(&file_contents)?;
228

            
229
602
        let rule_count_message = json!({
230
602
            "Number of rules applied": rule_count,
231
602
        });
232

            
233
602
        if let Some(array) = sorted_json_rules.as_array_mut() {
234
602
            array.push(rule_count_message);
235
602
        } else {
236
            return Err(anyhow::anyhow!("Expected JSON array"));
237
        }
238
602
        sort_json_object(&sorted_json_rules, false)
239
    };
240

            
241
623
    let generated_sorted_json_rules = serde_json::to_string_pretty(&sorted_json_rules)?;
242

            
243
623
    let mut file = OpenOptions::new()
244
623
        .write(true)
245
623
        .truncate(true)
246
623
        .open(filename)?;
247

            
248
623
    file.write_all(generated_sorted_json_rules.as_bytes())?;
249

            
250
623
    Ok(sorted_json_rules)
251
623
}
252

            
253
602
fn sort_json_rules(json_rule_traces: &str) -> Result<JsonValue, anyhow::Error> {
254
602
    let mut sorted_rule_traces = Vec::new();
255

            
256
5040
    for line in json_rule_traces.lines() {
257
5040
        let pretty_json = sort_json_object(&serde_json::from_str(line)?, true);
258
5040
        sorted_rule_traces.push(pretty_json);
259
    }
260

            
261
602
    Ok(JsonValue::Array(sorted_rule_traces))
262
602
}
263

            
264
1246
pub fn read_human_rule_trace(
265
1246
    path: &str,
266
1246
    test_name: &str,
267
1246
    prefix: &str,
268
1246
    accept: bool,
269
1246
) -> Result<Vec<String>, std::io::Error> {
270
1246
    let filename = format!("{path}/{test_name}-{prefix}-rule-trace-human.txt");
271
1246
    let rules_trace: Vec<String> = read_to_string(&filename)
272
1246
        .unwrap()
273
1246
        .lines()
274
1246
        .map(String::from)
275
1246
        .collect();
276
1246

            
277
1246
    if accept {
278
        std::fs::copy(
279
            format!("{path}/{test_name}-generated-rule-trace-human.txt"),
280
            format!("{path}/{test_name}-expected-rule-trace-human.txt"),
281
        )?;
282
1246
    }
283

            
284
1246
    Ok(rules_trace)
285
1246
}