1
use std::fmt::{self, Display, Formatter};
2
use std::hash::Hash;
3

            
4
use thiserror::Error;
5

            
6
use crate::ast::{Expression, SymbolTable};
7
use crate::metadata::Metadata;
8
use crate::model::Model;
9

            
10
#[derive(Debug, Error)]
11
pub enum ApplicationError {
12
    #[error("Rule is not applicable")]
13
    RuleNotApplicable,
14

            
15
    #[error("Could not calculate the expression domain")]
16
    DomainError,
17
}
18

            
19
/// Represents the result of applying a rule to an expression within a model.
20
///
21
/// A `Reduction` encapsulates the changes made to a model during a rule application.
22
/// It includes a new expression to replace the original one, an optional top-level constraint
23
/// to be added to the model, and any updates to the model's symbol table.
24
///
25
/// This struct allows for representing side-effects of rule applications, ensuring that
26
/// all modifications, including symbol table expansions and additional constraints, are
27
/// accounted for and can be applied to the model consistently.
28
///
29
/// # Fields
30
/// - `new_expression`: The updated [`Expression`] that replaces the original one after applying the rule.
31
/// - `new_top`: An additional top-level [`Expression`] constraint that should be added to the model. If no top-level
32
///   constraint is needed, this field can be set to `Expression::Nothing`.
33
/// - `symbols`: A [`SymbolTable`] containing any new symbol definitions or modifications to be added to the model's
34
///   symbol table. If no symbols are modified, this field can be set to an empty symbol table.
35
///
36
/// # Usage
37
/// A `Reduction` can be created using one of the provided constructors:
38
/// - [`Reduction::new`]: Creates a reduction with a new expression, top-level constraint, and symbol modifications.
39
/// - [`Reduction::pure`]: Creates a reduction with only a new expression and no side-effects on the symbol table or constraints.
40
/// - [`Reduction::with_symbols`]: Creates a reduction with a new expression and symbol table modifications, but no top-level constraint.
41
/// - [`Reduction::with_top`]: Creates a reduction with a new expression and a top-level constraint, but no symbol table modifications.
42
///
43
/// The `apply` method allows for applying the changes represented by the `Reduction` to a [`Model`].
44
///
45
/// # Example
46
/// ```
47
1
/// // Need to add an example
48
1
/// ```
49
1
///
50
/// # See Also
51
/// - [`ApplicationResult`]: Represents the result of applying a rule, which may either be a `Reduction` or an `ApplicationError`.
52
/// - [`Model`]: The structure to which the `Reduction` changes are applied.
53
#[non_exhaustive]
54
#[derive(Clone, Debug)]
55
pub struct Reduction {
56
    pub new_expression: Expression,
57
    pub new_top: Expression,
58
    pub symbols: SymbolTable,
59
}
60

            
61
/// The result of applying a rule to an expression.
62
/// Contains either a set of reduction instructions or an error.
63
pub type ApplicationResult = Result<Reduction, ApplicationError>;
64

            
65
impl Reduction {
66
26962
    pub fn new(new_expression: Expression, new_top: Expression, symbols: SymbolTable) -> Self {
67
26962
        Self {
68
26962
            new_expression,
69
26962
            new_top,
70
26962
            symbols,
71
26962
        }
72
26962
    }
73

            
74
    /// Represents a reduction with no side effects on the model.
75
22576
    pub fn pure(new_expression: Expression) -> Self {
76
22576
        Self {
77
22576
            new_expression,
78
22576
            new_top: Expression::And(Metadata::new(), Vec::new()),
79
22576
            symbols: SymbolTable::new(),
80
22576
        }
81
22576
    }
82

            
83
    /// Represents a reduction that also modifies the symbol table.
84
    pub fn with_symbols(new_expression: Expression, symbols: SymbolTable) -> Self {
85
        Self {
86
            new_expression,
87
            new_top: Expression::And(Metadata::new(), Vec::new()),
88
            symbols,
89
        }
90
    }
91

            
92
    /// Represents a reduction that also adds a top-level constraint to the model.
93
    pub fn with_top(new_expression: Expression, new_top: Expression) -> Self {
94
        Self {
95
            new_expression,
96
            new_top,
97
            symbols: SymbolTable::new(),
98
        }
99
    }
100

            
101
    // Apply side-effects (e.g. symbol table updates
102
22270
    pub fn apply(self, model: &mut Model) {
103
22270
        model.extend_sym_table(self.symbols);
104

            
105
        // TODO: (yb33) Remove it when we change constraints to a vector
106
22270
        if let Expression::And(_, exprs) = &self.new_top {
107
21930
            if exprs.is_empty() {
108
21760
                model.constraints = self.new_expression.clone();
109
21760
                return;
110
170
            }
111
340
        }
112

            
113
510
        model.constraints = match self.new_expression {
114
289
            Expression::And(metadata, mut exprs) => {
115
289
                // Avoid creating a nested conjunction
116
289
                exprs.push(self.new_top.clone());
117
289
                Expression::And(metadata.clone_dirty(), exprs)
118
            }
119
221
            _ => Expression::And(
120
221
                Metadata::new(),
121
221
                vec![self.new_expression.clone(), self.new_top],
122
221
            ),
123
        };
124
22270
    }
125
}
126

            
127
/**
128
 * A rule with a name, application function, and rule sets.
129
 *
130
 * # Fields
131
 * - `name` The name of the rule.
132
 * - `application` The function to apply the rule.
133
 * - `rule_sets` A list of rule set names and priorities that this rule is a part of. This is used to populate rulesets at runtime.
134
 */
135
#[derive(Clone, Debug)]
136
pub struct Rule<'a> {
137
    pub name: &'a str,
138
    pub application: fn(&Expression, &Model) -> ApplicationResult,
139
    pub rule_sets: &'a [(&'a str, u16)], // (name, priority). At runtime, we add the rule to rulesets
140
}
141

            
142
impl<'a> Rule<'a> {
143
    pub const fn new(
144
        name: &'a str,
145
        application: fn(&Expression, &Model) -> ApplicationResult,
146
        rule_sets: &'a [(&'static str, u16)],
147
    ) -> Self {
148
        Self {
149
            name,
150
            application,
151
            rule_sets,
152
        }
153
    }
154

            
155
296658143
    pub fn apply(&self, expr: &Expression, mdl: &Model) -> ApplicationResult {
156
296658143
        (self.application)(expr, mdl)
157
296658143
    }
158
}
159

            
160
impl Display for Rule<'_> {
161
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
162
        write!(f, "{}", self.name)
163
    }
164
}
165

            
166
impl PartialEq for Rule<'_> {
167
475558
    fn eq(&self, other: &Self) -> bool {
168
475558
        self.name == other.name
169
475558
    }
170
}
171

            
172
impl Eq for Rule<'_> {}
173

            
174
impl Hash for Rule<'_> {
175
693855
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
176
693855
        self.name.hash(state);
177
693855
    }
178
}