79 lines
1.8 KiB
Rust
79 lines
1.8 KiB
Rust
mod tests;
|
|
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum Token {
|
|
Negation,
|
|
Conjunction,
|
|
Disjunction,
|
|
ExclusiveDisjunction,
|
|
MaterialCondition,
|
|
LogicalEquivalence
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub enum Node<T> {
|
|
Leaf(T),
|
|
Unary {
|
|
operator: Token,
|
|
operand: Box<Node<T>>
|
|
},
|
|
Binary {
|
|
operator: Token,
|
|
lhs: Box<Node<T>>,
|
|
rhs: Box<Node<T>>,
|
|
},
|
|
}
|
|
|
|
pub fn add_unary_node<T>(stack: &mut Vec<Node<T>>, token: Token) {
|
|
let operand = Box::new(stack.pop().unwrap());
|
|
stack.push(Node::Unary {
|
|
operator: token,
|
|
operand,
|
|
});
|
|
}
|
|
|
|
pub fn add_binary_node<T>(stack: &mut Vec<Node<T>>, token: Token) {
|
|
let rhs = Box::new(stack.pop().unwrap());
|
|
let lhs = Box::new(stack.pop().unwrap());
|
|
stack.push(Node::Binary {
|
|
operator: token,
|
|
lhs,
|
|
rhs
|
|
});
|
|
}
|
|
|
|
fn bool_to_char(b: bool) -> char {
|
|
match b {
|
|
false => '0',
|
|
true => '1'
|
|
}
|
|
}
|
|
|
|
fn token_to_char(token: Token) -> char {
|
|
match token {
|
|
Token::Negation => '!',
|
|
Token::Conjunction =>'&',
|
|
Token::Disjunction => '|',
|
|
Token::ExclusiveDisjunction => '^',
|
|
Token::MaterialCondition => '>',
|
|
Token::LogicalEquivalence => '=',
|
|
}
|
|
}
|
|
|
|
fn ast_to_formula(ast: Node<bool>) -> String {
|
|
let mut str = String::from("");
|
|
match ast {
|
|
Node::Unary { operator, operand } => {
|
|
str.push_str(ast_to_formula(*operand).as_str());
|
|
str.push(token_to_char(operator));
|
|
},
|
|
Node::Binary { operator, lhs, rhs } => {
|
|
str.push_str(ast_to_formula(*rhs).as_str());
|
|
str.push_str(ast_to_formula(*lhs).as_str());
|
|
str.push(token_to_char(operator));
|
|
},
|
|
Node::Leaf(b) => str.push(bool_to_char(b)),
|
|
};
|
|
str
|
|
} |