use super::arithmetic::eval;
use crate::{Context, Outcome, Plugin, number, re};
#[derive(Clone, Debug)]
pub struct Unit {
pub aliases: &'static str,
pub symbol: String,
pub dimension: [i8; 8],
pub scale: f64,
pub offset: f64,
}
#[derive(Clone, Debug)]
pub struct Units {
pub units: Vec<Unit>,
}
#[derive(Clone, Debug)]
pub(crate) struct Quantity {
pub base: f64,
pub unit: Unit,
}
impl Default for Units {
fn default() -> Self {
let mut units = vec![];
macro_rules! add {
($dim:expr,$scale:expr,$symbol:literal,$aliases:literal) => {
units.push(Unit {
aliases: $aliases,
symbol: $symbol.into(),
dimension: $dim,
scale: $scale,
offset: 0.0,
});
};
}
let l = [1, 0, 0, 0, 0, 0, 0, 0];
let m = [0, 1, 0, 0, 0, 0, 0, 0];
let t = [0, 0, 1, 0, 0, 0, 0, 0];
let data = [0, 0, 0, 0, 1, 0, 0, 0];
add!(l, 1.0, "m", "m|meter|meters|metre|metres");
add!(
l,
1000.0,
"km",
"km|kilometer|kilometers|kilometre|kilometres"
);
add!(
l,
0.01,
"cm",
"cm|centimeter|centimeters|centimetre|centimetres"
);
add!(
l,
0.001,
"mm",
"mm|millimeter|millimeters|millimetre|millimetres"
);
add!(
l,
1e-6,
"μm",
"µm|μm|micrometer|micrometers|micrometre|micrometres"
);
add!(l, 1e-9, "nm", "nm|nanometer|nanometers");
add!(l, 0.0254, "inches", "in|inch|inches");
add!(l, 0.3048, "feet", "ft|foot|feet");
add!(l, 0.9144, "yd", "yd|yard|yards");
add!(l, 1609.344, "mi", "mi|mile|miles");
add!(l, 1852.0, "NM", "nmile|nautical mile|nautical miles");
add!(l, 201.168, "fur", "furlong|furlongs");
add!(l, 3.085677581491367e16, "pc", "pc|parsec|parsecs");
add!(l, 9.4607304725808e15, "ly", "ly|light year|light years");
add!(m, 1.0, "kg", "kg|kilogram|kilograms");
add!(m, 0.001, "g", "g|gram|grams");
add!(m, 1e-6, "mg", "mg|milligram|milligrams");
add!(m, 1e-9, "μg", "ug|µg|μg|microgram|micrograms");
add!(m, 1e-12, "ng", "ng|nanogram|nanograms");
add!(m, 1000.0, "t", "tonne|tonnes|metric ton|metric tons");
add!(m, 0.45359237, "lb", "lb|lbs|pound|pounds");
add!(m, 0.028349523125, "oz", "oz|ounce|ounces");
add!(m, 6.35029318, "st", "st|stone|stones");
add!(t, 1.0, "s", "s|sec|secs|second|seconds");
add!(t, 1e-6, "µs", "microsecond|microseconds|us|µs");
add!(t, 0.001, "ms", "ms|millisecond|milliseconds");
add!(t, 60.0, "min", "min|mins|minute|minutes");
add!(t, 3600.0, "hours", "h|hr|hrs|hour|hours");
add!(t, 86400.0, "days", "d|day|days");
add!(t, 604800.0, "weeks", "w|wk|wks|week|weeks");
add!(t, 2629746.0, "months", "month|months");
add!(t, 31556952.0, "years", "yr|yrs|year|years");
add!(
[2, 0, 0, 0, 0, 0, 0, 0],
10000.0,
"ha",
"ha|hectare|hectares"
);
add!(
[2, 0, 0, 0, 0, 0, 0, 0],
4046.8564224,
"ac",
"ac|acre|acres"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.001,
"L",
"l|liter|liters|litre|litres"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
1e-6,
"mL",
"ml|milliliter|milliliters|millilitre|millilitres"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
1e-9,
"µL",
"ul|µl|microliter|microliters"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
1e-12,
"nL",
"nl|nanoliter|nanoliters"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.00025,
"metric cup",
"cup|cups|metric cup|metric cups"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.000015,
"tbsp",
"tbsp|tablespoon|tablespoons"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.000005,
"tsp",
"tsp|teaspoon|teaspoons"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.003785411784,
"gal",
"gal|gallon|gallons"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.00454609,
"imp gal",
"imperial gallon|imperial gallons"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.000473176473,
"pt",
"pt|pint|pints"
);
add!(
[3, 0, 0, 0, 0, 0, 0, 0],
0.000946352946,
"qt",
"qt|quart|quarts"
);
add!([3, 0, 0, 0, 0, 0, 0, 0], 0.0352391, "bu", "bushel|bushels");
let energy = [2, 1, -2, 0, 0, 0, 0, 0];
add!(energy, 1.0, "J", "j|joule|joules");
add!(energy, 1000.0, "kJ", "kj|kilojoule|kilojoules");
add!(energy, 1e6, "MJ", "mj|megajoule|megajoules");
add!(energy, 1e9, "GJ", "gj|gigajoule|gigajoules");
add!(energy, 4.184, "cal", "cal|calorie|calories");
add!(energy, 4184.0, "kCal", "kcal|kilocalorie|kilocalories");
add!(energy, 3600.0, "Wh", "wh|watt hour|watt hours");
add!(energy, 3.6e6, "kWh", "kwh|kilowatt hour|kilowatt hours");
add!(energy, 3.6e9, "MWh", "mwh|megawatt hour|megawatt hours");
add!(energy, 3.6e12, "GWh", "gwh|gigawatt hour|gigawatt hours");
add!(energy, 1.35582, "lbf⋅ft", "foot-pound|foot-pounds");
let power = [2, 1, -3, 0, 0, 0, 0, 0];
add!(power, 1.0, "W", "w|watt|watts");
add!(power, 1000.0, "kW", "kw|kilowatt|kilowatts");
add!(power, 745.7, "hp", "horsepower|hp");
let pressure = [-1, 1, -2, 0, 0, 0, 0, 0];
add!(pressure, 1.0, "Pa", "pa|pascal|pascals");
add!(pressure, 1000.0, "kPa", "kpa|kilopascal|kilopascals");
add!(pressure, 100.0, "hPa", "hpa|hectopascal|hectopascals");
add!(pressure, 1e6, "MPa", "mpa|megapascal|megapascals");
add!(pressure, 1e9, "GPa", "gpa|gigapascal|gigapascals");
add!(pressure, 100000.0, "bar", "bar|bars");
add!(pressure, 100.0, "mbar", "mbar|millibar|millibars");
add!(pressure, 101325.0, "atm", "atm|atmosphere|atmospheres");
add!(pressure, 6894.76, "psi", "psi");
add!(pressure, 6894760.0, "ksi", "ksi");
let angle = [0, 0, 0, 0, 0, 0, 0, 1];
add!(angle, 1.0, "rad", "rad|radian|radians");
add!(
angle,
std::f64::consts::PI / 180.0,
"°",
"°|deg|degree|degrees"
);
add!(
angle,
std::f64::consts::PI / 10800.0,
"′",
"arcminute|arcminutes"
);
add!(
angle,
std::f64::consts::TAU,
"rev",
"rev|revolution|revolutions"
);
add!([1, 0, -1, 0, 0, 0, 0, 0], 1609.344 / 3600.0, "mph", "mph");
add!(
[1, 0, -1, 0, 0, 0, 0, 0],
1852.0 / 3600.0,
"kn",
"knot|knots|kn"
);
add!(data, 1.0, "B", "b|byte|bytes");
add!(data, 0.125, "bit", "bit|bits");
add!(data, 1000.0, "kB", "kb|kilobyte|kilobytes");
add!(data, 1e6, "MB", "mb|megabyte|megabytes");
add!(data, 1e9, "GB", "gb|gigabyte|gigabytes");
add!(data, 1e12, "TB", "tb|terabyte|terabytes");
add!(data, 1024.0, "KiB", "kib|kibibyte|kibibytes");
add!(data, 1048576.0, "MiB", "mib|mebibyte|mebibytes");
add!(data, 1073741824.0, "GiB", "gib|gibibyte|gibibytes");
add!(data, 1099511627776.0, "TiB", "tib|tebibyte|tebibytes");
add!(data, 125.0, "kbit", "kbit|kilobit|kilobits");
add!(data, 125000000.0, "Gbit", "gbit|gigabit|gigabits");
add!(data, 125000.0, "Mbit", "mbit|megabit|megabits");
for (aliases, symbol, scale, offset) in [
("c|°c|celsius|degrees celsius", "°C", 1.0, 273.15),
(
"f|°f|fahrenheit|degrees fahrenheit",
"°F",
5.0 / 9.0,
255.3722222222222,
),
("k|kelvin", "K", 1.0, 0.0),
] {
units.push(Unit {
aliases,
symbol: symbol.into(),
dimension: [0, 0, 0, 1, 0, 0, 0, 0],
scale,
offset,
});
}
let force = [1, 1, -2, 0, 0, 0, 0, 0];
add!(force, 1.0, "N", "newton|newtons");
add!(
force,
4.4482216152605,
"lbf",
"lbf|pounds of force|pound of force|pound-force|pounds force|pound force"
);
add!(force, 0.138254954376, "pdl", "pdl|poundal|poundals");
add!(
[0, 0, 0, 0, 0, 1, 0, 0],
1.0,
"amps",
"amp|amps|ampere|amperes"
);
add!([2, 1, -3, 0, 0, -1, 0, 0], 1.0, "V", "v|volt|volts");
add!([2, 1, -3, 0, 0, -2, 0, 0], 1.0, "Ω", "ω|ohm|ohms");
add!([-2, -1, 4, 0, 0, 2, 0, 0], 1.0, "farads", "farad|farads");
add!([2, 1, -2, 0, 0, -2, 0, 0], 1.0, "henrys", "henry|henrys");
add!(
[-2, -1, 3, 0, 0, 2, 0, 0],
1.0,
"siemens",
"siemen|siemens|℧"
);
add!(
[0, 0, 1, 0, 0, 1, 0, 0],
1.0,
"coulombs",
"coulomb|coulombs"
);
add!(
[0, 0, 1, 0, 0, 1, 0, 0],
3600.0,
"Ah",
"ah|amp hour|amp hours|ampere hour|ampere hours"
);
add!([2, 1, -2, 0, 0, -1, 0, 0], 1.0, "Wb", "wb|weber|webers");
add!([0, 1, -2, 0, 0, -1, 0, 0], 1.0, "teslas", "tesla|teslas");
add!([0, 0, 0, 0, 0, 0, 1, 0], 1.0, "mol", "mol|mols|mole|moles");
add!([-3, 0, 0, 0, 0, 0, 1, 0], 1000.0, "ᴍ", "molar|molars");
add!([0, 0, -1, 0, 0, 0, 0, 0], 1.0, "Hz", "hertz|hz");
add!(
[0, 0, -1, 0, 0, 0, 0, 1],
std::f64::consts::TAU / 60.0,
"rpm",
"rpm|rev/min|r/min|revolutions per minute"
);
add!(
[0, 0, -1, 0, 0, 0, 0, 1],
std::f64::consts::TAU,
"rps",
"rps|rev/s|r/s|revolutions per second"
);
add!(
[2, 1, -2, 0, 0, 0, 0, 0],
1.0,
"N⋅m",
"nm|n m|n⋅m|newton meter|newton meters|newton metre|newton metres"
);
add!(
[2, 1, -2, 0, 0, 0, 0, 0],
1.35582,
"lbf⋅ft",
"ft-lb|lbf-ft|lbf ft|pound feet|pound foot|foot pound|foot pounds"
);
add!(
[2, 1, -2, 0, 0, 0, 0, 0],
0.1129848,
"lbf⋅in",
"inch-pound|pound inch|pound inches|inch pound|inch pounds|lbf-in"
);
add!(
[1, 0, -2, 0, 0, 0, 0, 0],
1.0,
"m/s²",
"m/s²|m/s^2|m / s^2|m/sec^2|m / sec^2|meters per second squared|metres per second squared|meters per second^2"
);
add!(
[1, 0, -2, 0, 0, 0, 0, 0],
0.3048,
"ft/s²",
"ft/s²|ft/s^2|ft / s^2|ft/sec^2|feet per second squared|feet per second^2"
);
add!(
[-2, 0, 0, 0, 0, 0, 0, 0],
1e8 / 235.2145835714,
"MPG",
"mpg"
);
add!(
[2, 0, 0, 0, 0, 0, 0, 0],
1e-8,
"L/100km",
"l/100km|l/100 km|l / 100 km|l /100 km|l / 100 kilometers|l per 100 km|l per 100km|liters per 100 km|liters per 100 kilometers|litres per 100 kilometers"
);
Self { units }
}
}
impl Units {
fn grouped_unit<'a>(&self, input: &'a str) -> Option<(&'a str, Unit)> {
if !input.starts_with('(') {
return None;
}
let groups = super::syntax::groups(input)?;
let group = groups.first()?;
let unit = self.unit(input[group.end + 1..].trim())?;
Some((&input[..group.end + 1], unit))
}
pub(crate) fn expression(&self, input: &str, depth: usize) -> Result<Quantity, crate::Error> {
self.expression_inner(input, depth, false, false)
}
fn expression_inner(
&self,
input: &str,
depth: usize,
intermediate: bool,
standard: bool,
) -> Result<Quantity, crate::Error> {
let invalid = || crate::Error("invalid_expression".into());
let domain = || crate::Error("internal_error".into());
if depth > 64 {
return Err(invalid());
}
let normalized = input
.replace(" plus ", " + ")
.replace(" minus ", " - ")
.replace(" divided by ", " / ")
.replace(" multiplied by ", " * ")
.replace('×', "*")
.replace('÷', "/");
let s = normalized.trim();
if let Some(product) = super::syntax::group_products(s, |group| {
self.expression_inner(group, depth + 1, intermediate, standard)
.is_ok_and(|quantity| quantity.unit.dimension != [0; 8])
})? {
return self.expression_inner(&product, depth + 1, intermediate, standard);
}
if standard && let Some((coefficient, unit)) = self.grouped_unit(s) {
let mut quantity =
self.expression_inner(coefficient, depth + 1, intermediate, standard)?;
if quantity.unit.dimension == [0; 8] {
quantity.base = quantity.base * unit.scale + unit.offset;
} else if quantity.unit.dimension != unit.dimension {
return Err(domain());
}
quantity.unit = unit;
return Ok(quantity);
}
if let Some((left, right)) = s.rsplit_once(" times ") {
let a = self.expression_inner(left, depth + 1, intermediate, standard)?;
let b = self.expression_inner(right, depth + 1, intermediate, standard)?;
return Ok(Quantity {
base: ((a.base - a.unit.offset) / a.unit.scale)
* ((b.base - b.unit.offset) / b.unit.scale),
unit: self.canonical([0; 8]).ok_or_else(domain)?,
});
}
let operators = super::arithmetic::operators(s).ok_or_else(invalid)?;
for level in ["+-", "*/", "^"] {
for &(i, op) in operators.iter().rev().filter(|(i, op)| {
level.contains(*op)
&& !(*op == '-'
&& s[..*i].chars().last().is_some_and(char::is_alphabetic)
&& s[*i + 1..].starts_with(char::is_alphabetic))
}) {
let (mut a, b) = match (
self.expression_inner(&s[..i], depth + 1, intermediate, standard),
self.expression_inner(&s[i + 1..], depth + 1, intermediate, standard),
) {
(Ok(a), Ok(b)) => (a, b),
(Err(a), Err(b))
if a.0 == "invalid_expression" || b.0 == "invalid_expression" =>
{
return Err(invalid());
}
(Err(e), _) | (_, Err(e)) if e.0 == "internal_error" => return Err(e),
_ => continue,
};
match op {
'+' | '-' => {
if standard
&& a.unit.dimension != b.unit.dimension
&& !s[i + 1..].trim().ends_with('%')
{
if a.unit.dimension == [0; 8] {
a.base = a.base * b.unit.scale + b.unit.offset;
a.unit = b.unit.clone();
} else if b.unit.dimension == [0; 8] {
let value = b.base * a.unit.scale;
a.base += if op == '+' { value } else { -value };
return Ok(a);
}
}
if s[i + 1..].trim().ends_with('%') && b.unit.dimension == [0; 8] {
a.base = (a.base - a.unit.offset)
* (1.0 + if op == '+' { b.base } else { -b.base })
+ a.unit.offset;
return Ok(a);
}
if a.unit.dimension != b.unit.dimension {
return Err(domain());
}
let offset = if a.unit.symbol == b.unit.symbol {
b.unit.offset
} else {
0.0
};
a.base += if op == '+' {
b.base - offset
} else {
-(b.base - offset)
};
if b.unit.scale > a.unit.scale {
a.unit = b.unit;
}
}
'*' | '/' => {
if standard
&& op == '*'
&& ((a.unit.dimension == [0; 8] && b.unit.offset != 0.0)
|| (b.unit.dimension == [0; 8] && a.unit.offset != 0.0))
{
let (scalar, mut quantity) = if a.unit.dimension == [0; 8] {
(a.base, b)
} else {
(b.base, a)
};
quantity.base = (quantity.base - quantity.unit.offset) * scalar
+ quantity.unit.offset;
return Ok(quantity);
}
if op == '/' && a.unit.dimension == [0; 8] && b.unit.dimension != [0; 8] {
let grouped = s[i + 1..].trim().starts_with('(');
a.base = if grouped {
b.base / a.base
} else {
a.base / ((b.base - b.unit.offset) / b.unit.scale) * b.unit.scale
};
a.unit = b.unit;
return Ok(a);
}
let torque = if op == '*'
&& a.unit.dimension == [1, 1, -2, 0, 0, 0, 0, 0]
&& b.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]
{
Some(
self.unit(if a.unit.symbol == "lbf" && b.unit.symbol == "feet" {
"foot pounds"
} else {
"newton meters"
})
.ok_or_else(domain)?,
)
} else {
None
};
let torque_rate = if op == '/'
&& a.unit.symbol.contains('⋅')
&& b.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0]
{
self.unit(&format!("{}/{}", a.unit.symbol, b.unit.symbol))
} else {
None
};
let rate_unit = if op == '/'
&& b.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0]
&& a.unit.dimension != b.unit.dimension
{
self.unit(&format!("{}/{}", a.unit.symbol, b.unit.symbol))
} else if op == '*' && b.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0] {
a.unit
.symbol
.split_once('/')
.and_then(|(numerator, _)| self.unit(numerator))
} else if op == '*' && a.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0] {
b.unit
.symbol
.split_once('/')
.and_then(|(n, _)| self.unit(n))
} else {
None
};
let torque_value = torque.as_ref().map(|u| {
if u.symbol == "lbf⋅ft" {
a.base / a.unit.scale * b.base / b.unit.scale * u.scale
} else {
a.base * b.base
}
});
a.base = if op == '*' {
a.base * b.base
} else {
a.base / b.base
};
if b.unit.dimension != [0; 8] {
for (d, other) in a.unit.dimension.iter_mut().zip(b.unit.dimension) {
*d = if op == '*' {
d.checked_add(other)
} else {
d.checked_sub(other)
}
.ok_or_else(domain)?;
}
a.unit = torque
.or(torque_rate)
.or(rate_unit.filter(|u| {
u.dimension == a.unit.dimension
&& u.symbol.matches('/').count() < 2
}))
.or_else(|| self.canonical(a.unit.dimension))
.or_else(|| {
(intermediate
&& (a.unit.dimension[1] != 0 || a.unit.dimension[5] != 0))
.then(|| Unit {
aliases: "",
symbol: format!(
"{}{}{}",
a.unit.symbol, op, b.unit.symbol
),
dimension: a.unit.dimension,
scale: 1.0,
offset: 0.0,
})
})
.ok_or_else(domain)?;
if let Some(value) = torque_value {
a.base = value;
}
}
}
'^' => {
if b.unit.dimension != [0; 8]
|| b.base.fract() != 0.0
|| b.base.abs() > 16.0
{
return Err(domain());
}
a.base = a.base.powf(b.base);
for d in &mut a.unit.dimension {
*d = d.checked_mul(b.base as i8).ok_or_else(domain)?;
}
a.unit = self.canonical(a.unit.dimension).ok_or_else(domain)?;
}
_ => unreachable!(),
}
return Ok(a);
}
}
if let Some(inner) = s.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
if let Some(c) = re!(r"^([+-]?[\d.]+) [a-zA-Z]+$").captures(inner.trim())
&& self.quantity(inner).is_none()
{
return Ok(Quantity {
base: c[1].parse().map_err(|_| invalid())?,
unit: self.canonical([0; 8]).ok_or_else(domain)?,
});
}
return self.expression_inner(inner, depth + 1, intermediate, standard);
}
if let Some(inner) = s.strip_prefix("abs(").and_then(|s| s.strip_suffix(')')) {
let q = self.expression_inner(inner, depth + 1, intermediate, standard)?;
return Ok(Quantity {
base: ((q.base - q.unit.offset) / q.unit.scale).abs(),
unit: self.canonical([0; 8]).ok_or_else(domain)?,
});
}
if let Some(inner) = s.strip_prefix("sqrt(").and_then(|s| s.strip_suffix(')')) {
let mut q = self.expression_inner(inner, depth + 1, true, standard)?;
if q.unit.dimension.iter().any(|d| d % 2 != 0) {
return Err(domain());
}
for d in &mut q.unit.dimension {
*d /= 2;
}
q.base = q.base.sqrt();
q.unit = q
.unit
.symbol
.strip_suffix('²')
.and_then(|base| self.unit(base))
.filter(|u| u.dimension == q.unit.dimension)
.or_else(|| self.canonical(q.unit.dimension))
.ok_or_else(domain)?;
return Ok(q);
}
if let Some(c) = re!(r"^([+-]?[\d.]+)% (of|on|off) (.+)$").captures(s) {
let mut q = self.expression_inner(&c[3], depth + 1, intermediate, standard)?;
let p = c[1].parse::<f64>().map_err(|_| invalid())? / 100.0;
q.base *= match &c[2] {
"on" => 1.0 + p,
"off" => 1.0 - p,
_ => p,
};
return Ok(q);
}
self.quantity(s)
.or_else(|| {
(depth > 0 && !s.contains(' '))
.then(|| self.unit(s))
.flatten()
.filter(|unit| standard || unit.symbol == s)
.map(|unit| Quantity {
base: unit.scale + unit.offset,
unit,
})
})
.or_else(|| {
s.strip_suffix(" squared")
.filter(|_| depth > 0)
.and_then(|s| self.quantity(s))
})
.or_else(|| {
let c = (depth > 0)
.then(|| re!(r"^([+-]?[\d.]+) [a-z]+$").captures(s))
.flatten()?;
Some(Quantity {
base: c[1].parse().ok()?,
unit: self.canonical([0; 8])?,
})
})
.or_else(|| {
Some(Quantity {
base: s.strip_suffix('%')?.trim().parse::<f64>().ok()? / 100.0,
unit: self.canonical([0; 8])?,
})
})
.or_else(|| {
Some(Quantity {
base: eval(s)?,
unit: self.canonical([0; 8])?,
})
})
.ok_or_else(invalid)
}
fn canonical(&self, dimension: [i8; 8]) -> Option<Unit> {
if dimension == [0; 8] {
return Some(Unit {
aliases: "",
symbol: String::new(),
dimension,
scale: 1.0,
offset: 0.0,
});
}
if let Some(u) = self
.units
.iter()
.find(|u| u.dimension == dimension && u.scale == 1.0 && u.offset == 0.0)
{
return Some(u.clone());
}
if dimension[2] == -1 && dimension[1] == 0 && dimension[3..] == [0; 5] {
return self.unit(match dimension[0] {
1 => "m/s",
3 => "L/min",
_ => return None,
});
}
if dimension[1..] == [0; 7] && matches!(dimension[0], 2 | 3) {
return self.unit(if dimension[0] == 2 { "m²" } else { "m³" });
}
None
}
pub fn with_unit(mut self, unit: Unit) -> Self {
self.units.push(unit);
self
}
pub(crate) fn unit(&self, s: &str) -> Option<Unit> {
self.unit_at(s, 0)
}
fn unit_at(&self, s: &str, depth: usize) -> Option<Unit> {
if depth > 64 {
return None;
}
let micro = s.replace('μ', "µ");
let s = micro.trim();
if let Some(unit) = self.units.iter().find(|unit| unit.symbol == s) {
return Some(unit.clone());
}
if let Some(prefix) = s.strip_suffix('Ω')
&& let Some((factor, symbol)) = match prefix {
"k" => Some((1e3, "k")),
"M" => Some((1e6, "M")),
"G" => Some((1e9, "G")),
"m" => Some((1e-3, "m")),
"u" | "µ" | "μ" => Some((1e-6, "µ")),
_ => None,
}
{
let mut unit = self.unit_at("ohms", depth + 1)?;
unit.scale *= factor;
unit.symbol = format!("{symbol}Ω");
unit.aliases = "";
return Some(unit);
}
if matches!(s, "millimoles" | "micromoles" | "nanomoles" | "microwatts") {
return None;
}
if let Some((base, symbol)) = match s {
"MBps" | "megabytes per second" => Some(("MB/s", "MBps")),
"GBps" | "gigabytes per second" => Some(("GB/s", "GBps")),
"megabits per second" => Some(("mbit/s", "Mbps")),
_ => None,
} {
let mut u = self.unit_at(base, depth + 1)?;
u.symbol = symbol.into();
return Some(u);
}
let s = match s {
"Nm" => "newton meters",
"Mb" => "mbit",
"Gb" => "gbit",
"kbps" => "kbit/s",
"Mbps" => "mbit/s",
"Gbps" => "gbit/s",
s => s,
};
if let Some(u) = self
.units
.iter()
.find(|u| u.aliases.split('|').any(|a| a.eq_ignore_ascii_case(s)))
{
return Some(u.clone());
}
let s = s.to_lowercase().replace(" per ", "/").replace("//", "/");
let s = s.strip_prefix("decimal ").unwrap_or(&s);
if let Some(u) = self
.units
.iter()
.find(|u| u.aliases.split('|').any(|a| a == s))
{
return Some(u.clone());
}
for (prefix, factor, symbol) in [
("pico", 1e-12, "p"),
("nano", 1e-9, "n"),
("micro", 1e-6, "µ"),
("milli", 1e-3, "m"),
("kilo", 1e3, "k"),
("mega", 1e6, "M"),
("giga", 1e9, "G"),
("tera", 1e12, "T"),
] {
if let Some(base) = s.strip_prefix(prefix) {
let Some(mut u) = self.unit_at(base, depth + 1) else {
continue;
};
if !matches!(
u.symbol.as_str(),
"N" | "amps"
| "V"
| "Ω"
| "farads"
| "henrys"
| "siemens"
| "coulombs"
| "Ah"
| "Wb"
| "teslas"
| "mol"
| "Hz"
| "W"
) {
continue;
}
u.scale *= factor;
if !u.scale.is_finite() {
return None;
}
u.symbol = format!(
"{}{}",
if matches!(
u.symbol.as_str(),
"amps" | "farads" | "henrys" | "siemens" | "teslas" | "coulombs"
) {
prefix
} else if u.symbol == "V" && prefix == "kilo" {
"K"
} else {
symbol
},
u.symbol
);
u.aliases = "";
return Some(u);
}
}
if let Some((a, b)) = s.rsplit_once('/') {
let (a, b) = (self.unit_at(a, depth + 1)?, self.unit_at(b, depth + 1)?);
let mut dimension = a.dimension;
for (i, d) in dimension.iter_mut().enumerate() {
*d = d.checked_sub(b.dimension[i])?;
}
let symbol = if a.symbol == "km" && b.symbol == "hours" {
"km/h".to_string()
} else if a.symbol == "mi" && b.symbol == "hours" {
"mph".to_string()
} else {
format!("{}/{}", rate_symbol(&a.symbol), rate_symbol(&b.symbol))
};
let scale = a.scale / b.scale;
if !scale.is_finite() {
return None;
}
return Some(Unit {
aliases: "",
symbol,
dimension,
scale,
offset: 0.0,
});
}
let (power, base) = if let Some(s) = s.strip_prefix("square ") {
(2, s)
} else if let Some(s) = s.strip_prefix("cubic ") {
(3, s)
} else if let Some(s) = s.strip_suffix('²').or_else(|| s.strip_suffix('2')) {
(2, s)
} else {
let s = s.strip_suffix('³').or_else(|| s.strip_suffix('3'))?;
(3, s)
};
let mut u = self.unit_at(base, depth + 1)?;
for d in &mut u.dimension {
*d = d.checked_mul(power)?;
}
u.scale = u.scale.powi(power as i32);
if !u.scale.is_finite() {
return None;
}
u.symbol = format!(
"{}{}",
match u.symbol.as_str() {
"feet" => "ft",
"inches" => "in",
s => s,
},
if power == 2 { "²" } else { "³" }
);
Some(u)
}
pub(crate) fn quantity(&self, s: &str) -> Option<Quantity> {
let s = s
.trim()
.replace(',', "")
.replace(" + ", " ")
.replace(" plus ", " ")
.replace('−', "-")
.replace('π', "pi")
.replace('\'', " feet ")
.replace('"', " inches ");
if let Some(c) =
re!(r"^([+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$").captures(&s)
&& let Some(unit) = self.unit(&c[2])
{
return Some(Quantity {
base: c[1].parse::<f64>().ok()? * unit.scale + unit.offset,
unit,
});
}
let matches: Vec<_> =
re!(r"(?i)[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?|[+-]?pi\b(?:/\d+)?|\bone\b")
.find_iter(&s)
.filter(|m| {
!(m.start() > 0
&& s[..m.start()]
.chars()
.last()
.is_some_and(char::is_alphabetic)
&& (m.end() == s.len() || s[m.end()..].starts_with(char::is_whitespace)))
})
.collect();
if matches.is_empty() || matches[0].start() != 0 {
return None;
}
let mut result: Option<Quantity> = None;
for (i, m) in matches.iter().enumerate() {
let end = matches.get(i + 1).map(|m| m.start()).unwrap_or(s.len());
let unit_text = s[m.end()..end].trim();
let u = self.unit(unit_text)?;
let n = if m.as_str().eq_ignore_ascii_case("one") {
1.0
} else {
m.as_str().parse().ok().or_else(|| eval(m.as_str()))?
};
let base = n * u.scale + u.offset;
if let Some(q) = &mut result {
if q.unit.dimension != u.dimension {
return None;
}
q.base += base;
} else {
result = Some(Quantity { base, unit: u });
}
}
result
}
}
fn rate_symbol(s: &str) -> &str {
match s {
"hours" => "hour",
"days" => "day",
"weeks" => "week",
"months" => "month",
"years" => "year",
"feet" => "ft",
s => s,
}
}
pub(crate) fn format_quantity(n: f64, u: &Unit) -> String {
if !n.is_finite() {
return "Error: ∞".into();
}
let n = if matches!(u.symbol.as_str(), "gal" | "pt" | "qt") {
(n * 1e6).round() / 1e6
} else {
n
};
let symbol = if n.abs() == 1.0 {
match u.symbol.as_str() {
"hours" => "hour",
"days" => "day",
"weeks" => "week",
"months" => "month",
"years" => "year",
s => s,
}
} else {
u.symbol.as_str()
};
format!(
"{}{}{symbol}",
number(n),
if symbol == "°" || symbol == "′" {
""
} else {
" "
}
)
}
fn standard_comments(input: &str, units: &Units) -> Result<String, crate::Error> {
let mut output = String::new();
let mut groups = vec![(false, false)]; let mut cursor = 0;
for word in re!(r"[\p{L}]+|[()]").find_iter(input) {
let (feet, ignored) = *groups.last().unwrap();
if !ignored {
output.push_str(&input[cursor..word.start()]);
}
let text = word.as_str();
match text {
"(" => {
output.push('(');
groups.push((false, false));
}
")" => {
output.push(')');
if groups.len() > 1 {
groups.pop();
}
}
_ if ignored => {}
"into" if !input.trim_start().to_lowercase().starts_with("convert ") => {
if groups.len() == 1 {
return Err(crate::Error("invalid_expression".into()));
}
groups.last_mut().unwrap().1 = true;
}
"in" => {
let before = input[..word.start()].trim_end();
let after = input[word.end()..].trim_start();
let attached = before.ends_with(|c: char| c.is_ascii_digit() || c == '.');
let followed_by_converter = re!(r"^(?:to|in)\b").is_match(after);
let has_target = re!(r"^[\p{L}]+(?:\s+[\p{L}\d]+)*")
.find(after)
.is_some_and(|m| {
let target = m.as_str();
units.unit(target).is_some()
|| re!(r"^(?:binary|bin|hexadecimal|hex|octal|oct|decimal|dec|base)\b")
.is_match(target)
});
if attached && !feet && !followed_by_converter && !has_target {
if groups.len() == 1 {
return Err(crate::Error("invalid_expression".into()));
}
} else {
output.push_str(text);
}
}
_ => {
output.push_str(text);
if matches!(text, "ft" | "foot" | "feet") {
groups.last_mut().unwrap().0 = true;
}
}
}
cursor = word.end();
}
if !groups.last().unwrap().1 {
output.push_str(&input[cursor..]);
}
Ok(output)
}
impl Plugin for Units {
fn evaluate(&self, input: &str, _context: &Context) -> Outcome {
if input.to_lowercase().starts_with("convert ")
&& super::syntax::word_operators(input).contains(['+', '-', '*', '/'])
{
return Some(Err(crate::Error("invalid_expression".into())));
}
let lexical = match standard_comments(input, self) {
Ok(s) => s,
Err(e) => return Some(Err(e)),
};
let comments = lexical != input;
let normalized = lexical.trim().replace(" is what in ", " in ");
let s = normalized.as_str();
if let Some(c) = re!(r"^([\d.()+*/^ -]+)\^([\d.]+)\s*/\s*([\p{L}]+)$").captures(s)
&& eval(&c[1]).is_some()
&& let Some(per) = self.unit(&c[3])
&& per.dimension == [0, 0, 1, 0, 0, 0, 0, 0]
{
return Some(Ok(format!("{}/{}", &c[2], rate_symbol(&per.symbol))));
}
if re!(r"(?i)(?:feet|foot|ft)\b").is_match(s)
&& re!(r"(?i)(?:inches|inch|in)\b").is_match(s)
&& !re!(r" (?:to|in|as) ").is_match(s)
&& let Some(q) = self
.expression_inner(s, 0, false, true)
.ok()
.or_else(|| self.quantity(s))
&& q.unit.symbol == "feet"
{
let feet = q.base / 0.3048;
let whole = feet.trunc();
let inches = (feet - whole) * 12.0;
return Some(Ok(format!(
"{} {} {} inches",
number(whole),
if whole.abs() == 1.0 { "foot" } else { "feet" },
number(inches)
)));
}
let inner = super::syntax::ungroup(s);
if inner != s && re!(r" (?:to|in|as) ").is_match(inner) {
return self.evaluate(inner, _context);
}
if let Some((duration, rate)) = s.split_once(" of ")
&& rate.contains('/')
&& self
.quantity(duration)
.is_some_and(|q| q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
{
return Some(Err(crate::Error("null_result".into())));
}
if let Some(c) = re!(r"^(.+) in (?:a|an) (.+)$").captures(s) {
let target = self.unit(&c[1])?;
let from = self.unit(&c[2])?;
if target.dimension != from.dimension {
return None;
}
return Some(Ok(format_quantity(from.scale / target.scale, &target)));
}
if let Some(c) = re!(r"^(.+) in pounds and ounces$").captures(s) {
let q = self.quantity(&c[1])?;
if q.unit.dimension != [0, 1, 0, 0, 0, 0, 0, 0] {
return None;
}
let pounds = q.base / 0.45359237;
return Some(Ok(format!(
"{} lb {} oz",
number(pounds.trunc()),
number(pounds.fract() * 16.0)
)));
}
if let Some(c) = re!(r"^(.+) in (.+) in (.+)$").captures(s)
&& let Some(a) = self.quantity(&c[1])
&& let Some(b) = self.quantity(&c[2])
&& let Some(target) = self.unit(&c[3])
{
let mut dims = a.unit.dimension;
for (i, d) in dims.iter_mut().enumerate() {
*d -= b.unit.dimension[i];
}
if dims == target.dimension {
return Some(Ok(format_quantity(
if a.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]
&& b.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0]
{
a.unit.scale / (b.base / (a.base / a.unit.scale)).round() / target.scale
} else {
a.base / b.base / target.scale
},
&target,
)));
}
}
if let Some(c) = re!(r"^([+-]?[\d.]+)'([\d.]+)$").captures(s) {
let m = c[1].parse::<f64>().ok()? * 0.3048 + c[2].parse::<f64>().ok()? * 0.0254;
return Some(Ok(format!("{} m", number(m))));
}
if s.contains(" per ") && !re!(r" (?:to|in|into|as) ").is_match(s) {
let quantity = self.quantity(s);
if quantity.is_none() && !s.contains("abs(") {
return None;
}
if let Some(q) = quantity
&& q.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]
{
let n = q.base / 0.0254;
return Some(Ok(format!(
"{} inches",
format!("{n:.10}")
.trim_end_matches('0')
.trim_end_matches('.')
)));
}
}
let s = if s.to_lowercase().starts_with("convert ") && s.contains(" into ") {
&s[8..]
} else {
s
};
if !re!(r" (?i:to|in|into|as) ").is_match(s) && s.contains(['+', '-', '*', '/', '('])
|| s.contains(" plus ")
|| re!(r"[\d.]% (?:of|on|off) ").is_match(s)
{
let normalized = s.replace(" plus ", " + ").replace(" minus ", " - ");
let result = self.expression_inner(&normalized, 0, false, true);
let quantity_power = s.contains('^')
&& !s.contains(" for ")
&& re!(r"[a-zA-Z]+").find_iter(s).any(|word| {
self.unit(word.as_str())
.is_some_and(|unit| unit.dimension != [0; 8])
});
if (s.contains("abs(")
|| s.contains("sqrt(")
|| quantity_power
|| self.grouped_unit(&normalized).is_some())
&& let Err(error) = &result
&& error.0 == "internal_error"
{
return Some(Err(error.clone()));
}
if let Ok(q) = result
&& (q.unit.dimension != [0; 8] || s.contains("abs(") || comments)
{
let grouped_duration = re!(r"^[+-]?[\d.]+% (?:of|on|off) \(").is_match(s)
&& re!(r"[a-zA-Z]+")
.find_iter(s)
.filter_map(|m| self.unit(m.as_str()))
.filter(|u| u.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
.all(|u| u.scale == q.unit.scale);
return Some(Ok(if q.unit.dimension == [0; 8] {
number(q.base)
} else if q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0] && !grouped_duration {
super::time::span(q.base, if s.contains('%') { 604800.0 } else { 86400.0 })
} else {
format_quantity((q.base - q.unit.offset) / q.unit.scale, &q.unit)
}));
}
}
let c = re!(r"(?i)^(.+) (?:to|in|into|as) (.+)$").captures(s)?;
let target_text = if c[2].contains('^') {
super::compositions::normalize_unit_powers(&c[2], self)
} else {
c[2].to_owned()
};
let mut target = self.unit(&target_text)?;
if target.symbol == "L/100km"
&& let Some(rate) = re!(r"^(.+) per ([\d.]+ .+)$").captures(&c[1])
&& self
.quantity(&rate[1])
.is_some_and(|q| q.unit.dimension == [3, 0, 0, 0, 0, 0, 0, 0])
&& self
.quantity(&rate[2])
.is_some_and(|q| q.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0])
{
return Some(Err(crate::Error("internal_error".into())));
}
if let Some(rate) = re!(r"^([+-]?[\d.]+) ([\p{L}]+)(?:/| per )(.+)$").captures(&c[1])
&& self.unit(&rate[2]).is_none()
&& self.quantity(&c[1]).is_none()
{
let per = self.unit(&rate[3])?;
let n = rate[1].parse::<f64>().ok()?;
if let Some((_, denominator)) = c[2].rsplit_once('/')
&& let Some(denominator) = self.unit(denominator)
&& denominator.dimension == per.dimension
{
return Some(Ok(format!(
"{}/{}",
number(n * denominator.scale / per.scale),
denominator.symbol
)));
}
return Some(Ok(format!(
"{}/{}",
format_quantity(n, &target),
per.symbol
)));
}
if let Some(square) = re!(r"^([+-]?[\d.]+) square (.+)$").captures(&c[1])
&& square[2].contains(' ')
&& self.unit(&square[2]).is_some()
&& target.dimension == [2, 0, 0, 0, 0, 0, 0, 0]
{
let n = square[1].parse::<f64>().ok()?;
return Some(Ok(format!("{} m²", number(n * n * target.scale))));
}
let source = c[1].replace(" for ", " * ");
if source.trim_end().ends_with(',') {
return None;
}
let q = match self
.quantity(&source)
.map(Ok)
.unwrap_or_else(|| self.expression_inner(&source, 0, true, true))
{
Ok(q) => q,
Err(e) if e.0 == "internal_error" => return Some(Err(e)),
_ => return None,
};
if input.contains(" is what in ") && q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0] {
return None;
}
if q.unit.dimension[0] == 3 && target.dimension == [1, 0, 0, 0, 0, 0, 0, 0] {
target = self.unit(&format!("{}³", c[2].trim()))?;
}
if q.unit.dimension[0].abs() == 2
&& q.unit.dimension[1..] == [0; 7]
&& target.dimension[1..] == [0; 7]
&& q.unit.dimension[0] == -target.dimension[0]
{
return Some(Ok(format_quantity(
if target.symbol == "L/100km" {
let n = q.base / q.unit.scale;
235.2145835714 / n
} else {
1.0 / q.base / target.scale
},
&target,
)));
}
if !q.base.is_finite()
&& (q.unit.dimension == target.dimension || q.unit.dimension == [0; 8])
{
return Some(Ok(if q.unit.dimension == [3, 0, -1, 0, 0, 0, 0, 0] {
format!("Error: ∞/{}", target.symbol.split('/').next_back()?)
} else {
"Error: ∞".into()
}));
}
if q.unit.symbol.contains("⋅")
&& q.unit.symbol.contains('/')
&& target.dimension == [2, 1, -3, 0, 0, 0, 0, 0]
{
return Some(Err(crate::Error("internal_error".into())));
}
if q.unit.dimension != target.dimension
&& q.unit.dimension[2] == -1
&& q.unit.symbol.contains('/')
{
let mut numerator = q.unit.dimension;
numerator[2] = 0;
if target.dimension == numerator {
target = self.unit(&format!(
"{}/{}",
target.symbol,
q.unit.symbol.split('/').next_back()?
))?;
} else if target.dimension == [0, 0, 1, 0, 0, 0, 0, 0] {
target = self.unit(&format!(
"{}/{}",
q.unit.symbol.split('/').next()?,
target.symbol
))?;
}
}
if q.unit.dimension == [0; 8] {
return Some(Ok(format_quantity(q.base, &target)));
}
if q.unit.dimension != target.dimension {
let classified = crate::diagnostics::classify(input);
return Some(Err(
if input.trim_start().starts_with("convert ") && s.contains(" into ") {
crate::Error("null_result".into())
} else if classified.0 == "null_result" || s.contains(" into ") {
classified
} else {
crate::Error("internal_error".into())
},
));
}
let n = (q.base - target.offset) / target.scale;
Some(Ok(format_quantity(n, &target)))
}
}