clawgic 0.7.1

Logic engine for making, modifying, and evaluating expressions from sentential (propositional) logic. Support for predicate logic will be added later.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
pub mod operator;
pub mod negation;

use std::{collections::HashMap, mem::swap};

use operator::Operator;
use crate::{expression_tree::{ExpressionTreeError, node::negation::Negation}, operator_notation::OperatorNotation};

/// Nodes for regular logical expression tree.
/// 
/// Can be a binary operator, a variable, or a constant.
/// 
/// Since there is only one unary operator in SL (~ - denial operator), it doesn't
/// get its own enum type and instead is imbedded as a boolean value in operators and variables.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum Node{
    /// Binary operator node.
    Operator{
        /// Whether there is an odd number of tildes preceding the operator.
        neg: Negation,
        /// the type of operator.
        op: Operator,
        /// left operand.
        left: Box<Node>,
        /// right operand.
        right: Box<Node>,
    },
    /// Variable node.
    Variable{
        /// Whether there is an odd number of tildes preceding the variable.
        neg: Negation,
        /// Identifier of the variable. Ex: "A", "G", "B3".
        name: String,
    },
    /// Constant node. True or False.
    Constant(Negation, bool),
}

impl Node{
    /// Whether it is an operator node.
    pub fn is_operator(&self) -> bool{
        match self{
            Self::Operator{..} => true,
            _ => false,
        }
    }

    /// Whether it is a variable node.
    pub fn is_variable(&self) -> bool{
        match self{
            Self::Variable{..} => true,
            _ => false,
        }
    }

    /// Whether it is a constant node.
    pub fn is_constant(&self) -> bool{
        match self{
            Self::Constant(..) => true,
            _ => false,
        }
    }

    /// Attempts to get the boolean value of the node.
    /// 
    /// A constant node will just return it's value
    /// 
    /// If a variable node contains a `Some`, it will return that inner value.
    /// Otherwise it will return an ExpressionTreeError.
    /// 
    /// An operator node will attempt to perform its operation on it's left and right operands. 
    /// Will return an ExpressionTreeError if the evaluation of the left or right results in an `Err` value. 
    pub fn evaluate(&self, vars: &HashMap<String, Option<bool>>) -> Result<bool, ExpressionTreeError>{
        match self{
            Self::Operator{op, neg: denied, left, right} => {
                let left_result = left.evaluate(vars)?;
                let result = match op.short_circuit(left_result){
                    Some(b) => b,
                    None => op.execute(left_result, right.evaluate(vars)?),
                };
                Ok(result != denied.is_denied())
            }
            Self::Variable { neg: denied, name} =>{
                let result = match vars.get(name){
                    Some(b) => {
                        if b.is_none(){
                            return Err(ExpressionTreeError::UninitializedVariable(name.clone()))
                        }
                        b.unwrap()
                    },
                    None => return Err(ExpressionTreeError::UninitializedVariable(name.clone())),
                };
                Ok(denied.is_denied() != result)
            }
            Self::Constant(denied, value) => Ok(denied.is_denied() != *value),
        }
    }

    /// evaluates the tree with a specific set of concrete variables.
    /// 
    /// If some variable is not present in the map, returns `ExpressionTreeError::UninitualizedVariable`
    pub fn evaluate_with_vars(&self, vars: &HashMap<String, bool>) -> Result<bool, ExpressionTreeError>{
        match self{
            Self::Operator{op, neg: denied, left, right} => {
                let left_result = left.evaluate_with_vars(vars)?;
                let result = match op.short_circuit(left_result){
                    Some(b) => b,
                    None => op.execute(left_result, right.evaluate_with_vars(vars)?),
                };
                Ok(result != denied.is_denied())
            }
            Self::Variable { neg: denied, name} =>{
                let result = match vars.get(name){
                    Some(b) => b.clone(),
                    None => return Err(ExpressionTreeError::UninitializedVariable(name.clone())),
                };
                Ok (result != denied.is_denied())
            }
            Self::Constant(denied, value) => Ok(denied.is_denied() != *value),
        }
    }

    /// If the node has at least one tilde, remove one. otherwise, add one. returns a mutable reference.
    pub fn deny(&mut self) -> &mut Self{
        match self{
            Node::Constant(denied, ..) => denied.deny(),
            Node::Variable { neg: denied, ..} => denied.deny(),
            Node::Operator { neg: denied, ..} => denied.deny(),
        };
        self
    }

    /// If the node has more than 1 tilde, remove two. otherwise add two. returns a mutable reference.
    pub fn double_deny(&mut self) -> &mut Self{
        match self{
            Node::Constant(denied, ..) => denied.double_deny(),
            Node::Variable { neg: denied, ..} => denied.double_deny(),
            Node::Operator { neg: denied, ..} => denied.double_deny(),
        };
        self
    }

    /// Adds a tilde to the node; returns a mutable reference
    pub fn negate(&mut self) -> &mut Self{
        match self{
            Node::Constant(denied, ..) => denied.negate(),
            Node::Variable { neg: denied, ..} => denied.negate(),
            Node::Operator { neg: denied, ..} => denied.negate(),
        };
        self
    }

    // Adds two tildes to the node; returns a mutable reference
    pub fn double_negate(&mut self) -> &mut Self{
        match self{
            Node::Constant(denied, ..) => denied.double_negate(),
            Node::Variable { neg: denied, ..} => denied.double_negate(),
            Node::Operator { neg: denied, ..} => denied.double_negate(),
        };
        self
    }

    /// Reduces the number of tildes to 0 or 1, retaining the truth value of the node; returns a mutable reference.
    pub fn reduce_negation(&mut self) -> &mut Self{
        match self{
            Node::Constant(denied, ..) => denied.reduce(),
            Node::Variable { neg: denied, ..} => denied.reduce(),
            Node::Operator { neg: denied, ..} => denied.reduce(),
        };
        self
    }

    /// Applies demorgan's law to the node if it is
    /// a conjunction or a disjunction; returns a mutable reference. 
    /// 
    /// Otherwise, does nothing and returns `None`.
    pub fn demorgans(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: denied, op, left, right } => {
                if op.is_and() || op.is_or(){
                    *op = if op.is_and() {Operator::OR} else {Operator::AND};
                    denied.deny();
                    left.deny();
                    right.deny();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Applies demorgan's law to the node if it is
    /// a conjunction or a disjunction; returns a mutable reference.
    /// 
    /// Otherwise, does nothing and returns `None`.
    /// 
    /// Opts for negating instead of denying
    pub fn demorgans_neg(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: denied, op, left, right } => {
                if op.is_and() || op.is_or(){
                    *op = if op.is_and() {Operator::OR} else {Operator::AND};
                    denied.negate();
                    left.negate();
                    right.negate();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Applies transposition if the main connective (barring tildes)
    /// is a conditional and then returns a mutable reference.
    /// 
    /// otherwise, does nothing and returns `None`.
    pub fn transposition(&mut self) -> Option<&mut Self>{
        let Node::Operator { neg: _, op, left, right } = self
            else {return None};
        if op.is_con(){
            left.deny();
            right.deny();
            swap(left, right);
            return Some(self);
        }
        None
    }

    /// Applies transposition if the main connective (barring tildes)
    /// is a conditional and then returns a mutable reference.
    /// 
    /// otherwise, does nothing and returns `None`.
    /// 
    /// Opts for negating instead of denying
    pub fn transposition_neg(&mut self) -> Option<&mut Self>{
        let Node::Operator { neg: _, op, left, right } = self
            else {return None};
        if op.is_con(){
            left.negate();
            right.negate();
            swap(left, right);
            return Some(self);
        }
        None
    }

    /// Performs the logical rule of implication on a node if it is a conditional operator or a disjunction operator; returns a mut reference.
    /// 
    /// Otherwise, does nothing and returns None.. 
    pub fn implication(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: _, op, left, right: _ } => {
                if op.is_con() || op.is_or(){
                    *op =  if op.is_con() {Operator::OR} else {Operator::CON};
                    left.deny();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Performs the logical rule of implication on a node if it is a conditional operator or a disjunction operator; returns a mut reference.
    /// 
    /// Otherwise, does nothing and returns None.. 
    /// 
    /// Opts for negating instead of denying
    pub fn implication_neg(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: _, op, left, right: _ } => {
                if op.is_con() || op.is_or(){
                    *op =  if op.is_con() {Operator::OR} else {Operator::CON};
                    left.negate();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Performs the logical rule of Negated Conditional on a node if it is
    /// a conditional or a conjuction; returns a mut reference. 
    /// 
    /// Otherwise does nothing and returns `None`.
    pub fn ncon(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: denied, op, left: _, right } => {
                if op.is_con() || op.is_and(){
                    *op = if op.is_con() {Operator::AND} else {Operator::CON};
                    denied.deny();
                    right.deny();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Performs the logical rule of Negated Conditional on a node if it is
    /// a conditional or a conjuction; returns a mut reference. 
    /// 
    /// Otherwise does nothing and returns `None`.
    /// 
    /// Opts for negating instead of denying
    pub fn ncon_neg(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: denied, op, left: _, right } => {
                if op.is_con() || op.is_and(){
                    *op = if op.is_con() {Operator::AND} else {Operator::CON};
                    denied.negate();
                    right.negate();
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Performs the logical rule of Material Equivalence on a node
    /// if it is a biconditional or a conjunction of conditionals; returns a mut reference. 
    /// Otherwise, does nothing and returns `None`.
    pub fn mat_eq(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: _, op, left, right } => {
                if op.is_bicon(){
                    *op = Operator::AND;
                    let old_left = left.clone();
                    let old_right = right.clone();
                    *left = Box::new(Node::Operator { neg: Negation::default(), op: Operator::CON, left: old_left.clone(), right: old_right.clone() });
                    *right = Box::new(Node::Operator { neg: Negation::default(), op: Operator::CON, left: old_right, right: old_left });

                    return Some(self);
                }else if op.is_and(){
                    if let Node::Operator{neg: ld, op: l_op, left: ll, right: lr} = *left.clone(){
                        if let Node::Operator { neg: rd, op: r_op, left: rl, right: rr } = *right.clone(){
                            if l_op.is_con() && r_op.is_con() && !ld.is_denied() && !rd.is_denied() && ll == rr && lr == rl{
                                *op = Operator::BICON;
                                *left = ll;
                                *right = lr;
                            }
                        }
                    }
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    /// Performs the logical rule of Material Equivalence on a node
    /// and turns it monotonous if it is a biconditional; returns a mut reference. 
    /// Otherwise, does nothing and returns `None`.
    /// 
    /// Also if operator is denied, consumes the denial
    /// and handles it accordingly.
    pub fn mat_eq_mono(&mut self) -> Option<&mut Self>{
        match self{
            Node::Operator { neg: denied, op, left, right } => {
                if op.is_bicon(){
                    *op = Operator::OR;
                    let mut old_left = left.clone();
                    let mut old_right = right.clone();
                    if denied.is_denied(){
                        denied.deny();
                        if old_left < old_right{
                            old_left.deny();
                        }
                        else{
                            old_right.deny();
                        }
                    }
                    *left = Box::new(Node::Operator { neg: Negation::default(), op: Operator::AND, left: old_left.clone(), right: old_right.clone() });
                    old_left.deny();
                    old_right.deny();
                    *right = Box::new(Node::Operator { neg: Negation::default(), op: Operator::AND, left: old_left, right: old_right });
                    return Some(self);
                }
            },
            _ => (),
        }
        None
    }

    ///Returns a string representation of the current node based on the given notation.
    pub fn print(&self, notation: &OperatorNotation) -> String{
        match self{
            Self::Operator { neg: denied, op, .. } => {
                let mut s = String::new();
                if denied.is_denied(){
                    s.push_str(notation.get_notation(Operator::NOT));
                }
                s.push_str(notation.get_notation(*op));

                s
            }
            Self::Variable { neg: denied, name, .. } => {
                let mut s = String::new();
                if denied.is_denied(){
                    s.push_str(notation.get_notation(Operator::NOT));
                }
                s.push_str(name);
                s
            }
            Self::Constant(denied, b) => {
                let mut s = String::new();
                for _ in 0..denied.count(){
                    s.push_str(notation.get_notation(Operator::NOT))
                }
                s + 
                if *b{
                    "TRUE"
                }else{
                    "FALSE"
                }
            }
        }
    }

    ///Returns a string representation of the current node based on `OperationNotation::ascii()`.
    pub fn to_ascii(&self) -> String{
        self.print(&OperatorNotation::ascii())
    }
}

///Returns a string representation of the current node based on `OperationNotation::default()`.
impl ToString for Node{
    fn to_string(&self) -> String {
        self.print(&OperatorNotation::default())
    }
}

impl std::ops::Not for Node{
    type Output = Self;
    fn not(mut self) -> Self::Output {
        self.deny();
        self
    }
}