1
use std::collections::HashMap;
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 tracing::trace;
10
use uniplate::Uniplate;
11

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

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

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

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

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

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

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

            
132
27
    // Check if optimizations are enabled
133
27
    let apply_optimizations = optimizations_enabled();
134
27

            
135
27
    let start = std::time::Instant::now();
136

            
137
    //the while loop is exited when None is returned implying the sub-expression is clean
138
27
    for i in 0..new_model.constraints.len() {
139
18
        while let Some(step) = rewrite_iteration(
140
18
            &new_model.constraints[i],
141
18
            &new_model,
142
18
            &rules,
143
18
            apply_optimizations,
144
18
            &mut stats,
145
18
        ) {
146
9
            step.apply(&mut new_model, i); // Apply side-effects (e.g. symbol table updates)
147
9
        }
148
    }
149
27
    stats.rewriter_run_time = Some(start.elapsed());
150
27
    model.context.write().unwrap().stats.add_rewriter_run(stats);
151
27
    Ok(new_model)
152
27
}
153

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

            
225
18
    // Mark the expression as clean - will be marked dirty if any rule is applied
226
18
    let mut expression = expression.clone();
227
18

            
228
18
    let rule_results = apply_all_rules(&expression, model, rules, stats);
229
18
    trace_rules(&rule_results, expression.clone());
230
18
    if let Some(new) = choose_rewrite(&rule_results, &expression) {
231
        // If a rule is applied, mark the expression as dirty
232
9
        return Some(new);
233
9
    }
234
9

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

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

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

            
368
9
        check_priority(rules.clone(), initial_expression, &expr);
369
9
    }
370

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

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

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

            
409
    //iterates over each rule_set and groups by the rule priority
410
27
    for rule_set in &rule_sets {
411
18
        if let Some((name, priority)) = rule_set.first() {
412
18
            rules_by_priorities
413
18
                .entry(*priority)
414
18
                .or_default()
415
18
                .push(*name);
416
18
        }
417
    }
418

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

            
425
9
    if !duplicate_rules.is_empty() {
426
        //accumulates all duplicates into a formatted message
427
        let mut message = format!("Found multiple rules of the same priority applicable to to expression: {:?} \n resulting in expression: {:?}", initial_expr, new_expr);
428
        for (priority, rules) in &duplicate_rules {
429
            message.push_str(&format!("Priority {:?} \n Rules: {:?}", priority, rules));
430
        }
431
        bug!("{}", message);
432

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

            
440
18
fn trace_rules(results: &[RuleResult], expression: Expression) {
441
18
    if !results.is_empty() {
442
9
        let rule = results[0].rule;
443
9
        let new_expression = results[0].reduction.new_expression.clone();
444
9

            
445
9
        trace!(
446
            target: "rule_engine",
447
9
            "Rule applicable: {} ({:?}), to expression: {}, resulting in: {}",
448
            rule.name,
449
            rule.rule_sets,
450
            expression,
451
            new_expression,
452
        );
453
9
    }
454
18
}