Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 89 additions & 12 deletions core/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::error::{FendError, Interrupt};
use crate::eval::evaluate_to_value;
use crate::ident::Ident;
use crate::interrupt::test_int;
use crate::lexer::Symbol;
use crate::num::{Base, FormattingStyle, Number, Range, RangeBound};
use crate::result::FResult;
use crate::scope::Scope;
Expand Down Expand Up @@ -104,6 +105,59 @@ impl fmt::Display for Bop {
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Comparison {
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
}

impl Serialize for Comparison {
fn serialize(&self, write: &mut impl io::Write) -> FResult<()> {
let value: u8 = match self {
Self::Ne => 0,
Self::Eq => 1,
Self::Lt => 2,
Self::Le => 3,
Self::Gt => 4,
Self::Ge => 5,
};
value.serialize(write)
}
}

impl Deserialize for Comparison {
fn deserialize(read: &mut impl io::Read) -> FResult<Self> {
let value = u8::deserialize(read)?;

Ok(match value {
0 => Self::Ne,
1 => Self::Eq,
2 => Self::Lt,
3 => Self::Le,
4 => Self::Gt,
5 => Self::Ge,
_ => return Err(FendError::DeserializationError("Invalid comparison")),
})
}
}

impl From<Comparison> for Symbol {
fn from(value: Comparison) -> Self {
match value {
Comparison::Eq => Self::DoubleEquals,
Comparison::Ne => Self::NotEquals,
Comparison::Lt => Self::LessThan,
Comparison::Le => Self::LessThanOrEquals,
Comparison::Gt => Self::GreaterThan,
Comparison::Ge => Self::GreaterThanOrEquals,
}
}
}

#[derive(Clone, Debug)]
pub(crate) enum Expr {
Literal(Value),
Expand All @@ -127,7 +181,7 @@ pub(crate) enum Expr {
Of(Ident, Box<Self>),

Assign(Ident, Box<Self>),
Equality(bool, Box<Self>, Box<Self>),
Comparison(Comparison, Box<Self>, Box<Self>),
Statements(Box<Self>, Box<Self>),
}

Expand Down Expand Up @@ -161,7 +215,7 @@ impl Expr {
(Self::Fn(a1, a2), Self::Fn(b1, b2))
| (Self::Of(a1, a2), Self::Of(b1, b2))
| (Self::Assign(a1, a2), Self::Assign(b1, b2)) => a1 == b1 && a2.compare(b2, ctx, int)?,
(Self::Equality(a1, a2, a3), Self::Equality(b1, b2, b3)) => {
(Self::Comparison(a1, a2, a3), Self::Comparison(b1, b2, b3)) => {
a1 == b1 && a2.compare(b2, ctx, int)? && a3.compare(b3, ctx, int)?
}
_ => false,
Expand Down Expand Up @@ -244,7 +298,7 @@ impl Expr {
a.serialize(write)?;
b.serialize(write)?;
}
Self::Equality(is_equals, a, b) => {
Self::Comparison(is_equals, a, b) => {
16u8.serialize(write)?;
is_equals.serialize(write)?;
a.serialize(write)?;
Expand Down Expand Up @@ -300,8 +354,8 @@ impl Expr {
Box::new(Self::deserialize(read)?),
Box::new(Self::deserialize(read)?),
),
16 => Self::Equality(
bool::deserialize(read)?,
16 => Self::Comparison(
Comparison::deserialize(read)?,
Box::new(Self::deserialize(read)?),
Box::new(Self::deserialize(read)?),
),
Expand Down Expand Up @@ -362,10 +416,10 @@ impl Expr {
a.format(attrs, ctx, int)?,
b.format(attrs, ctx, int)?
),
Self::Equality(is_equals, a, b) => format!(
Self::Comparison(comp, a, b) => format!(
"{} {} {}",
a.format(attrs, ctx, int)?,
if *is_equals { "==" } else { "!=" },
Symbol::from(*comp),
b.format(attrs, ctx, int)?
),
})
Expand Down Expand Up @@ -539,13 +593,36 @@ pub(crate) fn evaluate<I: Interrupt>(
let _lhs = evaluate(*a, scope.clone(), attrs, spans, context, int)?;
evaluate(*b, scope, attrs, spans, context, int)?
}
Expr::Equality(is_equals, a, b) => {
Expr::Comparison(comp, a, b) => {
let lhs = evaluate(*a, scope.clone(), attrs, spans, context, int)?;
let rhs = evaluate(*b, scope, attrs, spans, context, int)?;
Value::Bool(match lhs.compare(&rhs, context, int)? {
Some(cmp::Ordering::Equal) => is_equals,
Some(cmp::Ordering::Greater | cmp::Ordering::Less) | None => !is_equals,
})

let ordering = lhs.compare(&rhs, context, int)?;

let value: bool = match ordering {
Option::None => match comp {
Comparison::Eq => false,
Comparison::Ne => true,
_ => {
return Err(FendError::CannotCompare(
comp,
lhs.format_to_plain_string(0, attrs, true, context, int)?,
rhs.format_to_plain_string(0, attrs, true, context, int)?,
));
}
},
Some(cmp::Ordering::Equal) => {
matches!(comp, Comparison::Eq | Comparison::Le | Comparison::Ge)
}
Some(cmp::Ordering::Greater) => {
matches!(comp, Comparison::Ne | Comparison::Ge | Comparison::Gt)
}
Some(cmp::Ordering::Less) => {
matches!(comp, Comparison::Ne | Comparison::Le | Comparison::Lt)
}
};

Value::Bool(value)
}
})
}
Expand Down
2 changes: 1 addition & 1 deletion core/src/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use year::Year;

use crate::{Interrupt, error::FendError, ident::Ident, result::FResult, value::Value};

#[derive(Copy, Clone, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub(crate) struct Date {
year: Year,
month: Month,
Expand Down
2 changes: 1 addition & 1 deletion core/src/date/day.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{Deserialize, Serialize};
use std::fmt;
use std::io;

#[derive(Copy, Clone, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub(crate) struct Day(u8);

impl Day {
Expand Down
2 changes: 1 addition & 1 deletion core/src/date/month.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
};
use std::{convert, fmt, io};

#[derive(Copy, Clone, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub(crate) enum Month {
January = 1,
February = 2,
Expand Down
2 changes: 1 addition & 1 deletion core/src/date/year.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
serialize::{Deserialize, Serialize},
};

#[derive(Copy, Clone, Eq, PartialEq)]
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd)]
pub(crate) struct Year(i32);

impl Year {
Expand Down
6 changes: 6 additions & 0 deletions core/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::{error, fmt, io};

use crate::ast::Comparison;
use crate::lexer::Symbol;
use crate::{date, num::Range};

#[derive(Debug)]
Expand Down Expand Up @@ -92,6 +94,7 @@ pub(crate) enum FendError {
after: date::Date,
},
RomanNumeralZero,
CannotCompare(Comparison, String, String),
}

impl fmt::Display for FendError {
Expand Down Expand Up @@ -242,6 +245,9 @@ impl fmt::Display for FendError {
)
}
Self::RomanNumeralZero => write!(f, "zero cannot be represented as a roman numeral"),
Self::CannotCompare(c, a, b) => {
write!(f, "invalid comparison: {a} {} {b}", Symbol::from(*c))
}
}
}
}
Expand Down
16 changes: 14 additions & 2 deletions core/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ pub(crate) enum Symbol {
Equals, // used for assignment
DoubleEquals, // used for equality
NotEquals,
GreaterThan,
GreaterThanOrEquals,
LessThan,
LessThanOrEquals,
Combination,
Permutation,
}
Expand Down Expand Up @@ -70,6 +74,10 @@ impl fmt::Display for Symbol {
Self::Equals => "=",
Self::DoubleEquals => "==",
Self::NotEquals => "!=",
Self::GreaterThan => ">",
Self::GreaterThanOrEquals => ">=",
Self::LessThan => "<",
Self::LessThanOrEquals => "<=",
Self::Combination => "nCr",
Self::Permutation => "nPr",
};
Expand Down Expand Up @@ -607,15 +615,19 @@ fn parse_symbol(ch: char, input: &mut &str) -> FResult<Token> {
Symbol::ShiftLeft
} else if test_next('>') {
Symbol::NotEquals
} else if test_next('=') {
Symbol::LessThanOrEquals
} else {
return Err(FendError::UnexpectedChar(ch));
Symbol::LessThan
}
}
'>' => {
if test_next('>') {
Symbol::ShiftRight
} else if test_next('=') {
Symbol::GreaterThanOrEquals
} else {
return Err(FendError::UnexpectedChar(ch));
Symbol::GreaterThan
}
}
';' => Symbol::Semicolon,
Expand Down
38 changes: 23 additions & 15 deletions core/src/parser.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::ast::{Bop, Expr};
use crate::ast::{Bop, Comparison, Expr};
use crate::lexer::{Symbol, Token};
use crate::value::Value;
use std::fmt;
Expand Down Expand Up @@ -494,22 +494,30 @@ fn parse_function(input: &[Token]) -> ParseResult<'_> {
}

fn parse_equality(input: &[Token]) -> ParseResult<'_> {
const COMPARISONS: [Comparison; 6] = [
Comparison::Eq, // "=="
Comparison::Ne, // "!=" | "<>"
Comparison::Le, // "<="
Comparison::Lt, // "<"
Comparison::Ge, // ">="
Comparison::Gt, // ">"
];

let (lhs, input) = parse_function(input)?;
if let Ok(((), remaining)) = parse_fixed_symbol(input, Symbol::DoubleEquals) {
let (rhs, remaining) = parse_function(remaining)?;
Ok((
Expr::Equality(true, Box::new(lhs), Box::new(rhs)),
remaining,
))
} else if let Ok(((), remaining)) = parse_fixed_symbol(input, Symbol::NotEquals) {
let (rhs, remaining) = parse_function(remaining)?;
Ok((
Expr::Equality(false, Box::new(lhs), Box::new(rhs)),
remaining,
))
} else {
Ok((lhs, input))

if let Ok((Token::Symbol(symbol), remaining)) = parse_token(input) {
for comp in COMPARISONS {
if Symbol::from(comp) == symbol {
let (rhs, remaining) = parse_function(remaining)?;
return Ok((
Expr::Comparison(comp, Box::new(lhs), Box::new(rhs)),
remaining,
));
}
}
}

Ok((lhs, input))
}

fn parse_assignment(input: &[Token]) -> ParseResult<'_> {
Expand Down
8 changes: 4 additions & 4 deletions core/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,11 @@ impl Value {
}
return Ok(Some(cmp::Ordering::Equal));
}
(Self::String(a), Self::String(b)) => c(a == b),
(Self::Bool(a), Self::Bool(b)) => c(a == b),
(Self::Month(a), Self::Month(b)) => c(a == b),
(Self::String(a), Self::String(b)) => a.partial_cmp(b),
(Self::Bool(a), Self::Bool(b)) => a.partial_cmp(b),
(Self::Month(a), Self::Month(b)) => a.partial_cmp(b),
(Self::DayOfWeek(a), Self::DayOfWeek(b)) => c(a == b),
(Self::Date(a), Self::Date(b)) => c(a == b),
(Self::Date(a), Self::Date(b)) => a.partial_cmp(b),
_ => None,
})
}
Expand Down
42 changes: 42 additions & 0 deletions core/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5929,6 +5929,48 @@ fn test_equality() {
test_eval("2.000m == approx. 200cm", "true");
}

#[test]
fn test_number_comparisons() {
test_eval("1 + 2 >= 3", "true");
test_eval("1 + 2 < 4", "true");
test_eval("1 + 2 <= 4", "true");
test_eval("1 <= 0", "false");
test_eval("1 >= 0", "true");
test_eval("1 > 0", "true");
test_eval("2m >= 200cm", "true");
test_eval("2.010m > 200cm", "true");
test_eval("2.010m <= 200cm", "false");
test_eval("2.000m >= approx. 200cm", "true");
test_eval("2.000m <= approx. 200cm", "true");
test_eval("-1 < 1", "true");
test_eval("-1 <= 1", "true");
test_eval("-1 > 1", "false");
test_eval("-1 >= 1", "false");
test_eval("-2^64 >= 1", "false");
test_eval("2^100 > 2^100 - 1", "true");
test_eval("2^100 > 2^100 + 1", "false");
test_eval("2^100 > 2^100", "false");
test_eval("2^-99 > 2^-100", "true");
test_eval("2^-99 < 2^-100", "false");
test_eval("2^-100 < 2^-99", "true");
test_eval("2^-100 > 2^-99", "false");
}

#[test]
fn test_other_comparisons() {
test_eval("\"a\" < \"b\"", "true");
test_eval("@1970-01-01 > @1970-01-02", "false");
test_eval("@2003-12-12 < @2004-02-29", "true");
test_eval("true > false", "true");
test_eval("true < false", "false");
test_eval("true >= false", "true");
test_eval("true <= false", "false");
test_eval("true >= true", "true");
test_eval("true <= true", "true");
test_eval("false >= false", "true");
test_eval("false <= false", "true");
}

#[test]
fn test_roman() {
expect_error(
Expand Down
Loading