use crate::plugins::{
compositions::Compositions,
compound_units, integer_queries, syntax,
units::{Unit, Units},
};
use crate::{Context, Error};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Zero};
pub(super) struct Coordinate {
pub value: BigRational,
pub authored: bool,
}
fn authored(value: BigRational) -> Result<Coordinate, Error> {
Ok(Coordinate {
value: bounded(value)?,
authored: true,
})
}
fn quantity_value(
input: &str,
reference: &str,
engine: &Compositions,
context: &Context,
) -> Result<f64, Error> {
let error = match engine.quantity_value(input, reference, context) {
Ok(value) => return Ok(value),
Err(error) if error.0 == "invalid_expression" => error,
Err(error) => return Err(error),
};
for (at, _) in input.char_indices().skip(1) {
let coefficient = input[..at].trim();
let unit = input[at..].trim();
if let Some(factors) = compound_units::factors(&unit.replace(" per ", "/"), |leaf| {
engine.units.unit(leaf).is_some()
}) && !factors.is_empty()
&& engine.quantity_value(coefficient, "1", context).is_ok()
{
return engine.quantity_value(&format!("({coefficient}) {unit}"), reference, context);
}
}
Err(error)
}
pub(super) fn read(
input: &str,
reference: &str,
engine: &Compositions,
context: &Context,
) -> Result<Coordinate, Error> {
let computed = quantity_value(input, reference, engine, context)?;
let input = syntax::ungroup(input);
if reference == "1"
&& let Ok((n, d)) = integer_queries::ratio_value(input)
{
return authored(BigRational::new(n, d));
}
let units = &engine.units;
let (reference_dimensions, reference_scale) =
unit_scale(reference, units).ok_or_else(|| Error("incompatible_units".into()))?;
for (at, _) in input.char_indices().skip(1) {
let Some((dimensions, scale)) = unit_scale(input[at..].trim(), units) else {
continue;
};
if !scale.has_unit || dimensions != reference_dimensions {
continue;
}
let Ok((n, d)) = integer_queries::ratio_value(input[..at].trim()) else {
continue;
};
if scale.pi_power == reference_scale.pi_power {
return authored(
BigRational::new(n, d) * scale.coefficient / &reference_scale.coefficient,
);
}
}
Ok(Coordinate {
value: bounded(
BigRational::from_float(computed).ok_or_else(|| Error("numeric_overflow".into()))?,
)?,
authored: false,
})
}
fn leaf(name: &str, units: &Units) -> Option<Unit> {
let name = name.trim();
units
.units
.iter()
.find(|unit| unit.symbol == name)
.or_else(|| {
units.units.iter().find(|unit| {
unit.aliases
.split('|')
.any(|alias| alias.eq_ignore_ascii_case(name))
})
})
.cloned()
.or_else(|| {
(!name.contains(['/', '*', '·', '⋅', '^', '²', '³', '(', ')'])
&& !name.ends_with(['2', '3'])
&& !name.starts_with("square ")
&& !name.starts_with("cubic "))
.then(|| units.unit(name))
.flatten()
})
.filter(|unit| unit.offset == 0.0 && unit.scale.is_finite() && unit.scale > 0.0)
}
struct Scale {
coefficient: BigRational,
pi_power: i32,
has_unit: bool,
}
fn unit_scale(input: &str, units: &Units) -> Option<([i8; 8], Scale)> {
let input = input.replace(" per ", "/");
let factors = compound_units::factors(&input, |name| leaf(name, units).is_some())?;
let has_unit = !factors.is_empty();
let mut dimensions = [0i8; 8];
let mut scale = BigRational::one();
let mut pi_power = 0;
for (name, exponent) in factors {
let unit = leaf(&name, units)?;
let (coefficient, pi) = match unit.symbol.as_str() {
"°" => (BigRational::new(1.into(), 180.into()), 1),
"′" => (BigRational::new(1.into(), 10_800.into()), 1),
"rev" => (BigRational::from_integer(2.into()), 1),
_ => {
let (n, d) = integer_queries::ratio_value(&unit.scale.to_string()).ok()?;
(BigRational::new(n, d), 0)
}
};
scale *= coefficient.pow(i32::from(exponent));
pi_power += pi * i32::from(exponent);
for (dimension, power) in dimensions.iter_mut().zip(unit.dimension) {
*dimension = dimension.checked_add(power.checked_mul(exponent)?)?;
}
}
(!scale.is_zero()).then_some((
dimensions,
Scale {
coefficient: scale,
pi_power,
has_unit,
},
))
}
pub(super) fn computed_root(
squared: BigRational,
evaluate: impl FnOnce(&str) -> Result<f64, Error>,
) -> Result<BigRational, Error> {
let squared = bounded(squared)?;
if squared.is_zero() {
return Ok(BigRational::zero());
}
let exponent = (squared.numer().bits() as i64 - squared.denom().bits() as i64).div_euclid(2);
let power = BigInt::one() << exponent.unsigned_abs() as usize;
let scale = if exponent >= 0 {
BigRational::from_integer(power)
} else {
BigRational::new(BigInt::one(), power)
};
let coefficient = bounded(squared / scale.pow(2))?;
let root = evaluate(&format!(
"sqrt(rational({},{}))",
coefficient.numer(),
coefficient.denom()
))?;
bounded(BigRational::from_float(root).ok_or_else(|| Error("numeric_overflow".into()))? * scale)
}
pub(super) fn bounded(value: BigRational) -> Result<BigRational, Error> {
if value.numer().bits().max(value.denom().bits()) > 65_536 {
Err(Error("integer_limit".into()))
} else {
Ok(value)
}
}