use crate::ast::{var_prop, BinaryOp};
use crate::Expr;
use relate_names::SmallName;
fn side_core<'a, K, R>(
recognizer: R,
left: &'a Expr,
right: &'a Expr,
) -> Option<(K, &'a Expr, bool)>
where
R: Fn(&'a Expr) -> Option<K>,
{
if let Some(k) = recognizer(left) {
return Some((k, right, true));
}
recognizer(right).map(|k| (k, left, false))
}
pub fn orient_side<'a, K, R>(
recognizer: R,
left: &'a Expr,
right: &'a Expr,
) -> Option<(K, &'a Expr)>
where
R: Fn(&'a Expr) -> Option<K>,
{
side_core(recognizer, left, right).map(|(k, other, _)| (k, other))
}
pub fn var_key_side<'a>(
var: &SmallName,
left: &'a Expr,
right: &'a Expr,
) -> Option<(&'a SmallName, &'a Expr)> {
orient_side(|e| key_of(e, var), left, right)
}
pub fn key_of<'e>(expr: &'e Expr, var: &SmallName) -> Option<&'e SmallName> {
var_prop(expr)
.filter(|(name, _)| name == &var)
.map(|(_, key)| key)
}
pub(crate) fn flip_cmp(op: BinaryOp) -> Option<BinaryOp> {
Some(match op {
BinaryOp::Lt => BinaryOp::Gt,
BinaryOp::Gt => BinaryOp::Lt,
BinaryOp::Lte => BinaryOp::Gte,
BinaryOp::Gte => BinaryOp::Lte,
BinaryOp::Eq | BinaryOp::Neq => op,
_ => return None,
})
}
pub fn orient<'a, K, R>(
recognizer: R,
left: &'a Expr,
right: &'a Expr,
op: BinaryOp,
) -> Option<(K, &'a Expr, BinaryOp)>
where
R: Fn(&'a Expr) -> Option<K>,
{
let (k, other, from_left) = side_core(recognizer, left, right)?;
let op = if from_left { op } else { flip_cmp(op)? };
Some((k, other, op))
}