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

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

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

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

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

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

            
231
8129859
    let mut sub = expression.children();
232
8129859
    for i in 0..sub.len() {
233
8129026
        if let Some(red) = rewrite_iteration(&sub[i], model, rules, apply_optimizations, stats) {
234
24871
            sub[i] = red.new_expression;
235
24871
            let res = expression.with_children(sub.clone());
236
24871
            return Some(Reduction::new(res, red.new_top, red.symbols));
237
8104155
        }
238
    }
239
    // If all children are clean, mark this expression as clean
240
8104988
    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
8104988
    }
245
8104988
    None
246
8150429
}
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
8150429
fn apply_all_rules<'a>(
296
8150429
    expression: &'a Expression,
297
8150429
    model: &'a Model,
298
8150429
    rules: &'a Vec<&'a Rule<'a>>,
299
8150429
    stats: &mut RewriterStats,
300
8150429
) -> Vec<RuleResult<'a>> {
301
8150429
    let mut results = Vec::new();
302
293478786
    for rule in rules {
303
285328357
        match rule.apply(expression, model) {
304
21097
            Ok(red) => {
305
21097
                stats.rewriter_rule_application_attempts =
306
21097
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
307
21097
                stats.rewriter_rule_applications =
308
21097
                    Some(stats.rewriter_rule_applications.unwrap() + 1);
309
21097
                // Assert no clean children
310
21097
                // assert!(!red.new_expression.children().iter().any(|c| c.is_clean()), "Rule that caused assertion to fail: {:?}", rule.name);
311
21097
                // assert!(!red.new_expression.children().iter().any(|c| c.children().iter().any(|c| c.is_clean())));
312
21097
                results.push(RuleResult {
313
21097
                    rule,
314
21097
                    reduction: red,
315
21097
                });
316
21097
            }
317
            Err(_) => {
318
285307260
                log::trace!(
319
                    "Rule attempted but not applied: {} ({:?}), to expression: {}",
320
                    rule.name,
321
                    rule.rule_sets,
322
                    expression
323
                );
324
285307260
                stats.rewriter_rule_application_attempts =
325
285307260
                    Some(stats.rewriter_rule_application_attempts.unwrap() + 1);
326
285307260
                continue;
327
            }
328
        }
329
    }
330
8150429
    results
331
8150429
}
332

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

            
367
442
        check_priority(rules.clone(), &initial_expression, &expr);
368
8149987
    }
369

            
370
8150429
    if results.is_empty() {
371
8129859
        return None;
372
20570
    }
373
20570

            
374
20570
    let red = results[0].reduction.clone();
375
20570
    let rule = results[0].rule;
376
20570
    tracing::info!(
377
        new_top=%red.new_top,
378
        "Rule applicable: {} ({:?}), to expression: {}, resulting in: {}",
379
        rule.name,
380
        rule.rule_sets,
381
        initial_expression,
382
        red.new_expression
383
    );
384
    // Return the first result for now
385
20570
    Some(red)
386
8150429
}
387

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

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

            
408
    //iterates over each rule_set and groups by the rule priority
409
1411
    for rule_set in &rule_sets {
410
969
        if let Some((name, priority)) = rule_set.get(0) {
411
969
            rules_by_priorities
412
969
                .entry(*priority)
413
969
                .or_insert(Vec::new())
414
969
                .push(*name);
415
969
        }
416
    }
417

            
418
    //filters the map, retaining only entries where there is more than 1 rule of the same priority
419
442
    let duplicate_rules: HashMap<u16, Vec<&str>> = rules_by_priorities
420
442
        .into_iter()
421
969
        .filter(|(_, group)| group.len() > 1)
422
442
        .collect();
423
442

            
424
442
    if !duplicate_rules.is_empty() {
425
        //accumulates all duplicates into a formatted message
426
        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));
427
        for (priority, rules) in &duplicate_rules {
428
            message.push_str(&format!("Priority {:?} \n Rules: {:?}", priority, rules));
429
        }
430
        bug!("{}", message);
431

            
432
    //no duplicate rules of the same priorities were found in the set of applicable rules
433
    } else {
434
442
        log::warn!("Multiple rules of different priorities are applicable to expression {:?} \n resulting in expression: {:?}
435
        \n Rules{:?}", initial_expr, new_expr, rules)
436
    }
437
442
}