Add elvis operator

This commit is contained in:
elkowar 2021-03-02 14:52:51 +01:00
parent f2c0e06997
commit c37c5b3cf3
5 changed files with 9 additions and 3 deletions

View file

@ -1,7 +1,7 @@
+++
title = "Examples"
slug = "Sample configs"
weight = 5
weight = 6
+++
## Example Configurations

View file

@ -1,7 +1,7 @@
+++
title = "Eww expressions"
slug = "Embedded eww expression language"
weight = 6
weight = 5
+++
# The embedded Eww expression-language
@ -27,6 +27,8 @@ The expression language supports:
- simple mathematical operations (`+`, `-`, `*`, `/`, `%`)
- comparisons (`==`, `!=`, `>`, `<`)
- boolean operations (`||`, `&&`, `!`)
- elvis operator (`?:`)
- if the left side is `""`, then returns the right side, otherwise evaluates to the left side.
- conditionals (`if condition then 'value' else 'other value'`)
- numbers, strings, booleans and variable references (`12`, `'hi'`, `true`, `some_variable`)
- strings can contain other expressions again: `'foo {{some_variable}} bar'`

View file

@ -16,6 +16,7 @@ pub enum BinOp {
Or,
GT,
LT,
Elvis,
}
impl std::fmt::Display for BinOp {
@ -32,6 +33,7 @@ impl std::fmt::Display for BinOp {
BinOp::Or => write!(f, "||"),
BinOp::GT => write!(f, ">"),
BinOp::LT => write!(f, "<"),
BinOp::Elvis => write!(f, "?:"),
}
}
}
@ -150,6 +152,7 @@ impl AttrValueExpr {
BinOp::Mod => PrimitiveValue::from(a.as_f64()? % b.as_f64()?),
BinOp::GT => PrimitiveValue::from(a.as_f64()? > b.as_f64()?),
BinOp::LT => PrimitiveValue::from(a.as_f64()? < b.as_f64()?),
BinOp::Elvis => PrimitiveValue::from(if a.0.is_empty() { b } else { a }),
})
}
AttrValueExpr::UnaryOp(op, a) => {

View file

@ -131,6 +131,7 @@ pub fn parse_expr(i: &str) -> IResult<&str, AttrValueExpr, VerboseError<&str>> {
let (i, remainder) = many0(alt((
map(preceded(tag("&&"), parse_term1), |x| (BinOp::And, x)),
map(preceded(tag("||"), parse_term1), |x| (BinOp::Or, x)),
map(preceded(tag("?:"), parse_term1), |x| (BinOp::Elvis, x)),
)))(i)?;
let exprs = remainder

View file

@ -6,7 +6,7 @@ use std::{convert::TryFrom, fmt, iter::FromIterator};
use crate::impl_try_from;
#[derive(Clone, Deserialize, Serialize, derive_more::From, Default)]
pub struct PrimitiveValue(String);
pub struct PrimitiveValue(pub String);
impl fmt::Display for PrimitiveValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {