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
1530
fn optimizations_enabled() -> bool {
54
1530
    match env::var("OPTIMIZATIONS") {
55
136
        Ok(val) => val == "1",
56
1394
        Err(_) => false, // Assume optimizations are disabled if the environment variable is not set
57
    }
58
1530
}
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
765
pub fn rewrite_model<'a>(
118
765
    model: &Model,
119
765
    rule_sets: &Vec<&'a RuleSet<'a>>,
120
765
) -> Result<Model, RewriteError> {
121
765
    let rule_priorities = get_rule_priorities(rule_sets)?;
122
765
    let rules = get_rules_vec(&rule_priorities);
123
765
    let mut new_model = model.clone();
124
765
    let mut stats = RewriterStats {
125
765
        is_optimization_enabled: Some(optimizations_enabled()),
126
765
        rewriter_run_time: None,
127
765
        rewriter_rule_application_attempts: Some(0),
128
765
        rewriter_rule_applications: Some(0),
129
765
    };
130
765

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

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

            
136
    //the while loop is exited when None is returned implying the sub-expression is clean
137
20213
    while let Some(step) = rewrite_iteration(
138
20213
        &new_model.constraints,
139
20213
        &new_model,
140
20213
        &rules,
141
20213
        apply_optimizations,
142
20213
        &mut stats,
143
20213
    ) {
144
19448
        step.apply(&mut new_model); // Apply side-effects (e.g. symbol table updates)
145
19448
    }
146
765
    stats.rewriter_run_time = Some(start.elapsed());
147
765
    model.context.write().unwrap().stats.add_rewriter_run(stats);
148
765
    Ok(new_model)
149
765
}
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
8145346
fn rewrite_iteration<'a>(
211
8145346
    expression: &'a Expression,
212
8145346
    model: &'a Model,
213
8145346
    rules: &'a Vec<&'a Rule<'a>>,
214
8145346
    apply_optimizations: bool,
215
8145346
    stats: &mut RewriterStats,
216
8145346
) -> Option<Reduction> {
217
8145346
    if apply_optimizations && expression.is_clean() {
218
        // Skip processing this expression if it's clean
219
        return None;
220
8145346
    }
221
8145346

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

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

            
231
8125898
    let mut sub = expression.children();
232
8125898
    for i in 0..sub.len() {
233
8125133
        if let Some(red) = rewrite_iteration(&sub[i], model, rules, apply_optimizations, stats) {
234
23630
            sub[i] = red.new_expression;
235
23630
            let res = expression.with_children(sub.clone());
236
23630
            return Some(Reduction::new(res, red.new_top, red.symbols));
237
8101503
        }
238
    }
239
    // If all children are clean, mark this expression as clean
240
8102268
    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
8102268
    }
245
8102268
    None
246
8145346
}
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
8145346
fn apply_all_rules<'a>(
296
8145346
    expression: &'a Expression,
297
8145346
    model: &'a Model,
298
8145346
    rules: &'a Vec<&'a Rule<'a>>,
299
8145346
    stats: &mut RewriterStats,
300
8145346
) -> Vec<RuleResult<'a>> {
301
8145346
    let mut results = Vec::new();
302
276989857
    for rule in rules {
303
268844511
        match rule.apply(expression, model) {
304
19924
            Ok(red) => {
305
19924
                log::info!(
306
                    "Rule applicable: {} ({:?}), to expression: {}, resulting in: {}",
307
                    rule.name,
308
                    rule.rule_sets,
309
                    expression,
310
                    red.new_expression
311
                );
312
19924
                stats.rewriter_rule_application_attempts =
313
19924
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
314
19924
                stats.rewriter_rule_applications =
315
19924
                    Some(stats.rewriter_rule_applications.unwrap() + 1);
316
19924
                // Assert no clean children
317
19924
                // assert!(!red.new_expression.children().iter().any(|c| c.is_clean()), "Rule that caused assertion to fail: {:?}", rule.name);
318
19924
                // assert!(!red.new_expression.children().iter().any(|c| c.children().iter().any(|c| c.is_clean())));
319
19924
                results.push(RuleResult {
320
19924
                    rule,
321
19924
                    reduction: red,
322
19924
                });
323
            }
324
            Err(_) => {
325
268824587
                log::trace!(
326
                    "Rule attempted but not applied: {} ({:?}), to expression: {}",
327
                    rule.name,
328
                    rule.rule_sets,
329
                    expression
330
                );
331
268824587
                stats.rewriter_rule_application_attempts =
332
268824587
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
333
268824587
                continue;
334
            }
335
        }
336
    }
337
8145346
    results
338
8145346
}
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
8145346
fn choose_rewrite<'a>(
366
8145346
    results: &[RuleResult],
367
8145346
    initial_expression: &'a Expression,
368
8145346
) -> Option<Reduction> {
369
8145346
    //in the case where multiple rules are applicable
370
8145346
    if results.len() > 1 {
371
391
        let expr = results[0].reduction.new_expression.clone();
372
867
        let rules: Vec<_> = results.iter().map(|result| &result.rule).collect();
373
391

            
374
391
        check_priority(rules.clone(), &initial_expression, &expr);
375
8144955
    }
376

            
377
8145346
    if results.is_empty() {
378
8125898
        return None;
379
19448
    }
380
19448
    // Return the first result for now
381
19448
    Some(results[0].reduction.clone())
382
8145346
}
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
391
fn check_priority<'a>(
394
391
    rules: Vec<&&Rule<'_>>,
395
391
    initial_expr: &'a Expression,
396
391
    new_expr: &'a Expression,
397
391
) {
398
391
    //getting the rule sets from the applicable rules
399
867
    let rule_sets: Vec<_> = rules.iter().map(|rule| &rule.rule_sets).collect();
400
391

            
401
391
    //a map with keys being rule priorities and their values neing all the rules of that priority found in the rule_sets
402
391
    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
1258
    for rule_set in &rule_sets {
406
867
        if let Some((name, priority)) = rule_set.get(0) {
407
867
            rules_by_priorities
408
867
                .entry(*priority)
409
867
                .or_insert(Vec::new())
410
867
                .push(*name);
411
867
        }
412
    }
413

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

            
420
391
    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
391
        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
391
}