Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arbitrary precision #75

Merged
merged 4 commits into from
Sep 19, 2020
Merged
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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ spectest = ["yaml-rust", "deunicode", "hrx-get", "regex"]
bytecount = "0.6.0"
lazy_static = "1.0"
nom = "5.0.0"
num-bigint = { version = "0.3.0", default-features = false, features = ["std"] }
num-integer = "0.1.42"
num-rational = { version = "0.3.0", default-features = false }
num-traits = "^0.2.0"
rand = "0.7.0"
Expand Down
8 changes: 6 additions & 2 deletions src/css/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::functions::SassFunction;
use crate::ordermap::OrderMap;
use crate::output::{Format, Formatted};
use crate::value::{ListSeparator, Number, Operator, Quotes, Rgba, Unit};
use num_bigint::BigInt;
use num_rational::Rational;
use std::convert::TryFrom;

Expand All @@ -24,7 +25,10 @@ pub enum Value {
///
/// The boolean flag is true for calculated values and false for
/// literal values.
Numeric(Number, Unit, bool),
Numeric(Number<isize>, Unit, bool),
/// A rational value with a Unit and flags, similar to Numeric, but with
/// support for arbitrarily large numbers.
NumericBig(Number<BigInt>, Unit, bool),
Color(Rgba, Option<String>),
Null,
True,
Expand All @@ -41,7 +45,7 @@ pub enum Value {
}

impl Value {
pub fn scalar<T: Into<Number>>(v: T) -> Self {
pub fn scalar<T: Into<Number<isize>>>(v: T) -> Self {
Value::Numeric(v.into(), Unit::None, false)
}
pub fn bool(v: bool) -> Self {
Expand Down
3 changes: 3 additions & 0 deletions src/css/valueformat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ impl<'a> Display for Formatted<'a, Value> {
Value::Numeric(ref num, ref unit, _) => {
write!(out, "{}{}", num.format(self.format), unit)
}
Value::NumericBig(ref num, ref unit, _) => {
write!(out, "{}{}", num.format(self.format), unit)
}
Value::Color(ref rgba, ref name) => {
if let Some(ref name) = *name {
name.fmt(out)
Expand Down
124 changes: 96 additions & 28 deletions src/parser/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ use nom::bytes::complete::{tag, tag_no_case};
use nom::character::complete::{
alphanumeric1, multispace0, multispace1, one_of,
};
use nom::combinator::{map, map_res, not, opt, peek, recognize, value};
use nom::combinator::{
map, map_opt, map_res, not, opt, peek, recognize, value,
};
use nom::multi::{
fold_many0, fold_many1, many0, many_m_n, separated_nonempty_list,
};
use nom::sequence::{delimited, pair, preceded, terminated, tuple};
use nom::IResult;
use num_rational::Rational;
use num_bigint::BigInt;
use num_rational::{Ratio, Rational};
use num_traits::{One, Zero};
use std::str::from_utf8;

pub fn value_expression(input: &[u8]) -> IResult<&[u8], Value> {
Expand Down Expand Up @@ -294,51 +298,115 @@ fn bracket_list(input: &[u8]) -> IResult<&[u8], Value> {
))
}

fn sign_prefix(input: &[u8]) -> IResult<&[u8], Option<&[u8]>> {
opt(alt((tag("-"), tag("+"))))(input)
}

enum AnyRatio {
Machine(Ratio<isize>),
Big(Ratio<BigInt>),
}

fn number(input: &[u8]) -> IResult<&[u8], Value> {
let (input, (sign, (lead_zero, num), unit)) = tuple((
opt(alt((tag("-"), tag("+")))),
alt((
map(pair(decimal_integer, opt(decimal_decimals)), |(n, d)| {
(true, if let Some(d) = d { n + d } else { n })
}),
map(decimal_decimals, |dec| (false, dec)),
map(
tuple((
sign_prefix,
alt((
map(pair(decimal_integer, decimal_decimals), |(n, d)| {
(true, AnyRatio::Machine(n + d))
}),
map(
pair(decimal_integer_big, decimal_decimals_big),
|(n, d)| (true, AnyRatio::Big(n + d)),
),
map(decimal_decimals, |dec| (false, AnyRatio::Machine(dec))),
map(decimal_decimals_big, |dec| (false, AnyRatio::Big(dec))),
map(decimal_integer, |int| (true, AnyRatio::Machine(int))),
map(decimal_integer_big, |int| (true, AnyRatio::Big(int))),
)),
unit,
)),
unit,
))(input)?;
Ok((
input,
Value::Numeric(
Number {
value: if sign == Some(b"-") { -num } else { num },
plus_sign: sign == Some(b"+"),
lead_zero,
|(sign, (lead_zero, num), unit)| match num {
AnyRatio::Machine(num) => Value::Numeric(
Number {
value: if sign == Some(b"-") { -num } else { num },
plus_sign: sign == Some(b"+"),
lead_zero,
},
unit,
),
AnyRatio::Big(num) => Value::NumericBig(
Number {
value: if sign == Some(b"-") { -num } else { num },
plus_sign: sign == Some(b"+"),
lead_zero,
},
unit,
),
},
)(input)
}

pub fn decimal_integer(input: &[u8]) -> IResult<&[u8], Rational> {
map_opt(
fold_many1(
// Note: We should use bytes directly, one_of returns a char.
one_of("0123456789"),
Some(0isize),
|r, d| {
r?.checked_mul(10)?.checked_add(isize::from(d as u8 - b'0'))
},
unit,
),
))
|opt_int| opt_int.map(Rational::from_integer),
)(input)
}

pub fn decimal_integer(input: &[u8]) -> IResult<&[u8], Rational> {
pub fn decimal_integer_big(input: &[u8]) -> IResult<&[u8], Ratio<BigInt>> {
map(
fold_many1(
// Note: We should use bytes directly, one_of returns a char.
one_of("0123456789"),
0,
|r, d| r * 10 + isize::from(d as u8 - b'0'),
BigInt::zero(),
|r, d| r * 10 + BigInt::from(d as u8 - b'0'),
),
Rational::from_integer,
Ratio::from_integer,
)(input)
}

pub fn decimal_decimals(input: &[u8]) -> IResult<&[u8], Rational> {
map_opt(
preceded(
tag("."),
fold_many1(
one_of("0123456789"),
Some((0isize, 1isize)),
|opt_pair, d| {
let (r, n) = opt_pair?;
Some((
r.checked_mul(10)?
.checked_add(isize::from(d as i8 - b'0' as i8))?,
n.checked_mul(10)?,
))
},
),
),
|opt_pair| opt_pair.map(|(r, d)| Rational::new(r, d)),
)(input)
}

pub fn decimal_decimals_big(input: &[u8]) -> IResult<&[u8], Ratio<BigInt>> {
map(
preceded(
tag("."),
fold_many1(one_of("0123456789"), (0, 1), |(r, n), d| {
(r * 10 + isize::from(d as i8 - b'0' as i8), n * 10)
}),
fold_many1(
one_of("0123456789"),
(BigInt::zero(), BigInt::one()),
|(r, n), d| {
(r * 10 + BigInt::from(d as i8 - b'0' as i8), n * 10)
},
),
),
|(r, d)| Rational::new(r, d),
|(r, d)| Ratio::new(r, d),
)(input)
}

Expand Down
15 changes: 14 additions & 1 deletion src/sass/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::ordermap::OrderMap;
use crate::sass::{CallArgs, SassString};
use crate::value::{ListSeparator, Number, Operator, Quotes, Rgba, Unit};
use crate::variablescope::Scope;
use num_bigint::BigInt;
use num_rational::Rational;
use num_traits::Zero;

Expand All @@ -20,7 +21,11 @@ pub enum Value {
List(Vec<Value>, ListSeparator, bool, bool),
/// A Numeric value is a rational value with a Unit (which may be
/// Unit::None) and flags.
Numeric(Number, Unit),
Numeric(Number<isize>, Unit),
/// A NumericBig value is a rational value with a Unit (which may be
/// Unit::None) and flags. The numerator and denominator of the value
/// may be arbitrarily large.
NumericBig(Number<BigInt>, Unit),
/// "(a/b) and a/b differs semantically. Parens means the value
/// should be evaluated numerically if possible, without parens /
/// is not allways division.
Expand Down Expand Up @@ -96,6 +101,7 @@ impl Value {
pub fn evaluate(&self, scope: &dyn Scope) -> Result<css::Value, Error> {
self.do_evaluate(scope, false)
}

pub fn do_evaluate(
&self,
scope: &dyn Scope,
Expand Down Expand Up @@ -162,6 +168,13 @@ impl Value {
}
Ok(css::Value::Numeric(num, unit.clone(), arithmetic))
}
Value::NumericBig(ref num, ref unit) => {
let mut num = num.clone();
if arithmetic {
num.lead_zero = true;
}
Ok(css::Value::NumericBig(num, unit.clone(), arithmetic))
}
Value::Map(ref m) => {
let items = m.iter()
.map(|&(ref k, ref v)| -> Result<(css::Value, css::Value), Error> {
Expand Down
Loading