1
use std::collections::{HashMap, HashSet};
2
use std::env;
3
use std::fmt::Display;
4

            
5
use thiserror::Error;
6

            
7
use crate::bug;
8
use crate::stats::RewriterStats;
9
use uniplate::Uniplate;
10

            
11
use crate::rule_engine::{Reduction, Rule, RuleSet};
12
use crate::{
13
    ast::Expression,
14
    rule_engine::resolve_rules::{
15
        get_rule_priorities, get_rules_vec, ResolveRulesError as ResolveError,
16
    },
17
    Model,
18
};
19

            
20
#[derive(Debug)]
21
struct RuleResult<'a> {
22
    rule: &'a Rule<'a>,
23
    reduction: Reduction,
24
}
25

            
26
/// Represents errors that can occur during the model rewriting process.
27
///
28
/// This enum captures errors that occur when trying to resolve or apply rules in the model.
29
#[derive(Debug, Error)]
30
pub enum RewriteError {
31
    ResolveRulesError(ResolveError),
32
}
33

            
34
impl Display for RewriteError {
35
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36
        match self {
37
            RewriteError::ResolveRulesError(e) => write!(f, "Error resolving rules: {}", e),
38
        }
39
    }
40
}
41

            
42
impl From<ResolveError> for RewriteError {
43
    fn from(error: ResolveError) -> Self {
44
        RewriteError::ResolveRulesError(error)
45
    }
46
}
47

            
48
/// Checks if the OPTIMIZATIONS environment variable is set to "1".
49
///
50
/// # Returns
51
/// - true if the environment variable is set to "1".
52
/// - false if the environment variable is not set or set to any other value.
53
1350
fn optimizations_enabled() -> bool {
54
1350
    match env::var("OPTIMIZATIONS") {
55
120
        Ok(val) => val == "1",
56
1230
        Err(_) => false, // Assume optimizations are disabled if the environment variable is not set
57
    }
58
1350
}
59

            
60
/// Rewrites the given model by applying a set of rules to all its constraints.
61
///
62
/// This function iteratively applies transformations to the model's constraints using the specified rule sets.
63
/// It returns a modified version of the model with all applicable rules applied, ensuring that any side-effects
64
/// such as updates to the symbol table and top-level constraints are properly reflected in the returned model.
65
///
66
/// # Parameters
67
/// - `model`: A reference to the [`Model`] to be rewritten. The function will clone this model to produce a modified version.
68
/// - `rule_sets`: A vector of references to [`RuleSet`]s that define the rules to be applied to the model's constraints.
69
///   Each `RuleSet` is expected to contain a collection of rules that can transform one or more constraints
70
///   within the model. The lifetime parameter `'a` ensures that the rules' references are valid for the
71
///   duration of the function execution.
72
///
73
/// # Returns
74
/// - `Ok(Model)`: If successful, it returns a modified copy of the [`Model`] after all applicable rules have been
75
///   applied. This new model includes any side-effects such as updates to the symbol table or modifications
76
///   to the constraints.
77
/// - `Err(RewriteError)`: If an error occurs during rule application (e.g., invalid rules or failed constraints),
78
///   it returns a [`RewriteError`] with details about the failure.
79
///
80
/// # Side-Effects
81
/// - When the model is rewritten, related data structures such as the symbol table (which tracks variable names and types)
82
///   or other top-level constraints may also be updated to reflect these changes. These updates are applied to the returned model,
83
///   ensuring that all related components stay consistent and aligned with the changes made during the rewrite.
84
/// - The function collects statistics about the rewriting process, including the number of rule applications
85
///   and the total runtime of the rewriter. These statistics are then stored in the model's context for
86
///   performance monitoring and analysis.
87
///
88
/// # Example
89
/// - Using `rewrite_model` with the Expression `a + min(x, y)`
90
///
91
///   Initial expression: a + min(x, y)
92
///   A model containing the expression is created. The variables of the model are represented by a SymbolTable and contain a,x,y.
93
///   The contraints of the initail model is the expression itself.
94
///
95
///   After getting the rules by their priorities and getting additional statistics the while loop of single interations is executed.
96
///   Details for this process can be found in [`rewrite_iteration`] documentation.
97
///
98
///   The loop is exited only when no more rules can be applied, when rewrite_iteration returns None and [`while let Some(step) = None`] occurs
99
///
100
///
101
///   Will result in side effects ((d<=x ^ d<=y) being the [`new_top`] and the model will now be a conjuction of that and (a+d)
102
///   Rewritten expression: ((a + d) ^ (d<=x ^ d<=y))
103
///
104
/// # Performance Considerations
105
/// - The function checks if optimizations are enabled before applying rules, which may affect the performance
106
///   of the rewriting process.
107
/// - Depending on the size of the model and the number of rules, the rewriting process might take a significant
108
///   amount of time. Use the statistics collected (`rewriter_run_time` and `rewriter_rule_application_attempts`)
109
///   to monitor and optimize performance.
110
///
111
/// # Panics
112
/// - This function may panic if the model's context is unavailable or if there is an issue with locking the context.
113
///
114
/// # See Also
115
/// - [`get_rule_priorities`]: Retrieves the priorities for the given rules.
116
/// - [`rewrite_iteration`]: Executes a single iteration of rewriting the model using the specified rules.
117
675
pub fn rewrite_model<'a>(
118
675
    model: &Model,
119
675
    rule_sets: &Vec<&'a RuleSet<'a>>,
120
675
) -> Result<Model, RewriteError> {
121
675
    let rule_priorities = get_rule_priorities(rule_sets)?;
122
675
    let rules = get_rules_vec(&rule_priorities);
123
675
    let mut new_model = model.clone();
124
675
    let mut stats = RewriterStats {
125
675
        is_optimization_enabled: Some(optimizations_enabled()),
126
675
        rewriter_run_time: None,
127
675
        rewriter_rule_application_attempts: Some(0),
128
675
        rewriter_rule_applications: Some(0),
129
675
    };
130
675

            
131
675
    // Check if optimizations are enabled
132
675
    let apply_optimizations = optimizations_enabled();
133
675

            
134
675
    let start = std::time::Instant::now();
135

            
136
    //the while loop is exited when None is returned implying the sub-expression is clean
137
17835
    while let Some(step) = rewrite_iteration(
138
17835
        &new_model.constraints,
139
17835
        &new_model,
140
17835
        &rules,
141
17835
        apply_optimizations,
142
17835
        &mut stats,
143
17835
    ) {
144
17160
        step.apply(&mut new_model); // Apply side-effects (e.g. symbol table updates)
145
17160
    }
146
675
    stats.rewriter_run_time = Some(start.elapsed());
147
675
    model.context.write().unwrap().stats.add_rewriter_run(stats);
148
675
    Ok(new_model)
149
675
}
150

            
151
/// Attempts to apply a set of rules to the given expression and its sub-expressions in the model.
152
///
153
/// This function recursively traverses the provided expression, applying any applicable rules from the given set.
154
/// If a rule is successfully applied to the expression or any of its sub-expressions, it returns a `Reduction`
155
/// containing the new expression, modified top-level constraints, and any changes to symbols. If no rules can be
156
/// applied at any level, it returns `None`.
157
///
158
/// # Parameters
159
/// - `expression`: A reference to the [`Expression`] to be rewritten. This is the main expression that the function
160
///   attempts to modify using the given rules.
161
/// - `model`: A reference to the [`Model`] that provides context and additional constraints for evaluating the rules.
162
/// - `rules`: A vector of references to [`Rule`]s that define the transformations to apply to the expression.
163
/// - `apply_optimizations`: A boolean flag that indicates whether optimization checks should be applied during the rewriting process.
164
///   If `true`, the function skips already "clean" (fully optimized or processed) expressions and marks them accordingly
165
///   to avoid redundant work.
166
/// - `stats`: A mutable reference to [`RewriterStats`] to collect statistics about the rule application process, such as
167
///   the number of rules applied and the time taken for each iteration.
168
///
169
/// # Returns
170
/// - `Some(<Reduction>)`: A [`Reduction`] containing the new expression and any associated modifications if a rule was applied
171
///   to `expr` or one of its sub-expressions.
172
/// - `None`: If no rule is applicable to the expression or any of its sub-expressions.
173
///
174
/// # Side-Effects
175
/// - If `apply_optimizations` is enabled, the function will skip "clean" expressions and mark successfully rewritten
176
///   expressions as "dirty". This is done to avoid unnecessary recomputation of expressions that have already been
177
///   optimized or processed.
178
///
179
/// # Example
180
/// - Recursively applying [`rewrite_iteration`]  to [`a + min(x, y)`]
181
///
182
///   Initially [`if apply_optimizations && expression.is_clean()`] is not true yet since intially our expression is dirty.
183
///
184
///   [`apply_results`] returns a null vector since no rules can be applied at the top level.
185
///   After calling function [`children`] on the expression a vector of sub-expression [`[a, min(x, y)]`] is returned.
186
///
187
///   The function iterates through the vector of the children from the top expression and calls itself.
188
///
189
///   [rewrite_iteration] on on the child [`a`] returns None, but on [`min(x, y)`] returns a [`Reduction`] object [`red`].
190
///   In this case, a rule (min simplification) can apply:
191
///   - d is added to the SymbolTable and the variables field is updated in the model. new_top is the side effects: (d<=x ^ d<=y)
192
///   - [`red = Reduction::new(new_expression = d, new_top, symbols)`];
193
///   - [`sub[1] = red.new_expression`] - Updates the second element in the vector of sub-expressions from [`min(x, y)`] to [`d`]
194
///
195
///   Since a child expression [`min(x, y)`] was rewritten to d, the parent expression [`a + min(x, y)`] is updated with the new child [`a+d`].
196
///   New [`Reduction`] is returned containing the modifications
197
///
198
///   The condition [`Some(step) = Some(new reduction)`] in the while loop in [`rewrite_model`] is met -> side effects are applied.
199
///
200
///   No more rules in our example can apply to the modified model -> mark all the children as clean and return a pure [`Reduction`].
201
///   [`return Some(Reduction::pure(expression))`]
202
///
203
///   On the last execution of rewrite_iteration condition [`apply_optimizations && expression.is_clean()`] is met, [`None`] is returned.
204
///
205
///
206
/// # Notes
207
/// - This function works recursively, meaning it traverses all sub-expressions within the given `expression` to find the
208
///   first rule that can be applied. If a rule is applied, it immediately returns the modified expression and stops
209
///   further traversal for that branch.
210
7187070
fn rewrite_iteration<'a>(
211
7187070
    expression: &'a Expression,
212
7187070
    model: &'a Model,
213
7187070
    rules: &'a Vec<&'a Rule<'a>>,
214
7187070
    apply_optimizations: bool,
215
7187070
    stats: &mut RewriterStats,
216
7187070
) -> Option<Reduction> {
217
7187070
    if apply_optimizations && expression.is_clean() {
218
        // Skip processing this expression if it's clean
219
        return None;
220
7187070
    }
221
7187070

            
222
7187070
    // Mark the expression as clean - will be marked dirty if any rule is applied
223
7187070
    let mut expression = expression.clone();
224
7187070

            
225
7187070
    let rule_results = apply_all_rules(&expression, model, rules, stats);
226
7187070
    if let Some(new) = choose_rewrite(&rule_results, &expression) {
227
        // If a rule is applied, mark the expression as dirty
228
17160
        return Some(new);
229
7169910
    }
230
7169910

            
231
7169910
    let mut sub = expression.children();
232
7169910
    for i in 0..sub.len() {
233
7169235
        if let Some(red) = rewrite_iteration(&sub[i], model, rules, apply_optimizations, stats) {
234
20850
            sub[i] = red.new_expression;
235
20850
            let res = expression.with_children(sub.clone());
236
20850
            return Some(Reduction::new(res, red.new_top, red.symbols));
237
7148385
        }
238
    }
239
    // If all children are clean, mark this expression as clean
240
7149060
    if apply_optimizations {
241
        assert!(expression.children().iter().all(|c| c.is_clean()));
242
        expression.set_clean(true);
243
        return Some(Reduction::pure(expression));
244
7149060
    }
245
7149060
    None
246
7187070
}
247

            
248
/// Applies all the given rules to a specific expression within the model.
249
///
250
/// This function iterates through the provided rules and attempts to apply each rule to the given `expression`.
251
/// If a rule is successfully applied, it creates a [`RuleResult`] containing the original rule and the resulting
252
/// [`Reduction`]. The statistics (`stats`) are updated to reflect the number of rule application attempts and successful
253
/// applications.
254
///
255
/// The function does not modify the provided `expression` directly. Instead, it collects all applicable rule results
256
/// into a vector, which can then be used for further processing or selection (e.g., with [`choose_rewrite`]).
257
///
258
/// # Parameters
259
/// - `expression`: A reference to the [`Expression`] that will be evaluated against the given rules. This is the main
260
///   target for rule transformations and is expected to remain unchanged during the function execution.
261
/// - `model`: A reference to the [`Model`] that provides context for rule evaluation, such as constraints and symbols.
262
///   Rules may depend on information in the model to determine if they can be applied.
263
/// - `rules`: A vector of references to [`Rule`]s that define the transformations to be applied to the expression.
264
///   Each rule is applied independently, and all applicable rules are collected.
265
/// - `stats`: A mutable reference to [`RewriterStats`] used to track statistics about rule application, such as
266
///   the number of attempts and successful applications.
267
///
268
/// # Returns
269
/// - A `Vec<RuleResult>` containing all rule applications that were successful. Each element in the vector represents
270
///   a rule that was applied to the given `expression` along with the resulting transformation.
271
/// - An empty vector if no rules were applicable to the expression.
272
///
273
/// # Side-Effects
274
/// - The function updates the provided `stats` with the number of rule application attempts and successful applications.
275
/// - Debug or trace logging may be performed to track which rules were applicable or not for a given expression.
276
///
277
/// # Example
278
///
279
/// let applicable_rules = apply_all_rules(&expr, &model, &rules, &mut stats);
280
/// if !applicable_rules.is_empty() {
281
///     for result in applicable_rules {
282
///         println!("Rule applied: {:?}", result.rule);
283
///     }
284
/// }
285
///
286
///
287
/// # Notes
288
/// - This function does not modify the input `expression` or `model` directly. The returned `RuleResult` vector
289
///   provides information about successful transformations, allowing the caller to decide how to process them.
290
/// - The function performs independent rule applications. If rules have dependencies or should be applied in a
291
///   specific order, consider handling that logic outside of this function.
292
///
293
/// # See Also
294
/// - [`choose_rewrite`]: Chooses a single reduction from the rule results provided by `apply_all_rules`.
295
7187070
fn apply_all_rules<'a>(
296
7187070
    expression: &'a Expression,
297
7187070
    model: &'a Model,
298
7187070
    rules: &'a Vec<&'a Rule<'a>>,
299
7187070
    stats: &mut RewriterStats,
300
7187070
) -> Vec<RuleResult<'a>> {
301
7187070
    let mut results = Vec::new();
302
244402815
    for rule in rules {
303
237215745
        match rule.apply(expression, model) {
304
17580
            Ok(red) => {
305
17580
                log::info!(
306
                    "Rule applicable: {} ({:?}), to expression: {}, resulting in: {}",
307
                    rule.name,
308
                    rule.rule_sets,
309
                    expression,
310
                    red.new_expression
311
                );
312
17580
                stats.rewriter_rule_application_attempts =
313
17580
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
314
17580
                stats.rewriter_rule_applications =
315
17580
                    Some(stats.rewriter_rule_applications.unwrap() + 1);
316
17580
                // Assert no clean children
317
17580
                // assert!(!red.new_expression.children().iter().any(|c| c.is_clean()), "Rule that caused assertion to fail: {:?}", rule.name);
318
17580
                // assert!(!red.new_expression.children().iter().any(|c| c.children().iter().any(|c| c.is_clean())));
319
17580
                results.push(RuleResult {
320
17580
                    rule,
321
17580
                    reduction: red,
322
17580
                });
323
            }
324
            Err(_) => {
325
237198165
                log::trace!(
326
                    "Rule attempted but not applied: {} ({:?}), to expression: {}",
327
                    rule.name,
328
                    rule.rule_sets,
329
                    expression
330
                );
331
237198165
                stats.rewriter_rule_application_attempts =
332
237198165
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
333
237198165
                continue;
334
            }
335
        }
336
    }
337
7187070
    results
338
7187070
}
339

            
340
/// Chooses the first applicable rule result from a list of rule applications.
341
///
342
/// This function selects a reduction from the provided `RuleResult` list, prioritizing the first rule
343
/// that successfully transforms the expression. This strategy can be modified in the future to incorporate
344
/// more complex selection criteria, such as prioritizing rules based on cost, complexity, or other heuristic metrics.
345
///
346
/// The function also checks the priorities of all the applicable rules and detects if there are multiple rules of the same proirity
347
///
348
/// # Parameters
349
/// - `results`: A slice of [`RuleResult`] containing potential rule applications to be considered. Each element
350
///   represents a rule that was successfully applied to the expression, along with the resulting transformation.
351
/// -  `initial_expression`: [`Expression`] before the rule tranformation.
352
///
353
/// # Returns
354
/// - `Some(<Reduction>)`: Returns a [`Reduction`] representing the first rule's application if there is at least one
355
///   rule that produced a successful transformation.
356
/// - `None`: If no rule applications are available in the `results` slice (i.e., it is empty), it returns `None`.
357
///
358
/// # Example
359
///
360
/// let rule_results = vec![rule1_result, rule2_result];
361
/// if let Some(reduction) = choose_rewrite(&rule_results) {
362
/// Process the chosen reduction
363
/// }
364
///
365
7187070
fn choose_rewrite<'a>(
366
7187070
    results: &[RuleResult],
367
7187070
    initial_expression: &'a Expression,
368
7187070
) -> Option<Reduction> {
369
7187070
    //in the case where multiple rules are applicable
370
7187070
    if results.len() > 1 {
371
345
        let expr = results[0].reduction.new_expression.clone();
372
765
        let rules: Vec<_> = results.iter().map(|result| &result.rule).collect();
373
345

            
374
345
        check_priority(rules.clone(), &initial_expression, &expr);
375
7186725
    }
376

            
377
7187070
    if results.is_empty() {
378
7169910
        return None;
379
17160
    }
380
17160
    // Return the first result for now
381
17160
    Some(results[0].reduction.clone())
382
7187070
}
383

            
384
/// Function filters all the applicable rules based on their priority.
385
/// In the case where there are multiple rules of the same prioriy, a bug! is thrown listing all those duplicates.
386
/// Otherwise, if there are multiple rules applicable but they all have different priorities, a warning message is dispalyed.
387
///
388
/// # Parameters
389
/// - `rules`: a vector of [`Rule`] containing all the applicable rules and their metadata for a specific expression.
390
/// - `initial_expression`: [`Expression`] before rule the tranformation.
391
/// - `new_expr`: [`Expression`] after the rule transformation.
392
///
393
345
fn check_priority<'a>(
394
345
    rules: Vec<&&Rule<'_>>,
395
345
    initial_expr: &'a Expression,
396
345
    new_expr: &'a Expression,
397
345
) {
398
345
    //getting the rule sets from the applicable rules
399
765
    let rule_sets: Vec<_> = rules.iter().map(|rule| &rule.rule_sets).collect();
400
345

            
401
345
    //a map with keys being rule priorities and their values neing all the rules of that priority found in the rule_sets
402
345
    let mut rules_by_priorities: HashMap<u16, Vec<&str>> = HashMap::new();
403

            
404
    //iterates over each rule_set and groups by the rule priority
405
1110
    for rule_set in &rule_sets {
406
765
        if let Some((name, priority)) = rule_set.get(0) {
407
765
            rules_by_priorities
408
765
                .entry(*priority)
409
765
                .or_insert(Vec::new())
410
765
                .push(*name);
411
765
        }
412
    }
413

            
414
    //filters the map, retaining only entries where there is more than 1 rule of the same priority
415
345
    let duplicate_rules: HashMap<u16, Vec<&str>> = rules_by_priorities
416
345
        .into_iter()
417
765
        .filter(|(_, group)| group.len() > 1)
418
345
        .collect();
419
345

            
420
345
    if !duplicate_rules.is_empty() {
421
        //accumulates all duplicates into a formatted message
422
        let mut message = String::from(format!("Found multiple rules of the same priority applicable to to expression: {:?} \n resulting in expression: {:?}", initial_expr, new_expr));
423
        for (priority, rules) in &duplicate_rules {
424
            message.push_str(&format!("Priority {:?} \n Rules: {:?}", priority, rules));
425
        }
426
        bug!("{}", message);
427

            
428
    //no duplicate rules of the same priorities were found in the set of applicable rules
429
    } else {
430
345
        log::warn!("Multiple rules of different priorities are applicable to expression {:?} \n resulting in expression: {:?}
431
        \n Rules{:?}", initial_expr, new_expr, rules)
432
    }
433
345
}