mod conversions;
mod recipes;
mod supplied_conversions;
use super::{
compositions::Compositions,
integer_queries::{self, IntegerQueries},
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
#[derive(Default)]
pub struct PracticalQueries {
engine: Compositions,
}
impl Plugin for PracticalQueries {
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
PracticalRequest {
engine: &self.engine,
context,
}
.lower(input.trim().trim_end_matches(['?', '.']))
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
PracticalRequest {
engine: &self.engine,
context,
}
.lower(input.trim().trim_end_matches(['?', '.']))
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
if let Some(result) = recipes::evaluate_positions(&self.engine, input, context) {
return Some(result);
}
if let Some(result) = recipes::evaluate(&self.engine, input, context) {
return Some(result);
}
if let Some(inner) = input
.strip_prefix("practical_pair(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let (width, height) = inner
.split_once(';')
.ok_or_else(|| Error("invalid_expression".into()))?;
self.engine.quantity_value(width, "m", context)?;
self.engine.quantity_value(height, "m", context)?;
Ok(format!(
"{} × {}",
calculate(&self.engine, width, context)?,
calculate(&self.engine, height, context)?
))
})());
}
if let Some(inner) = input
.strip_prefix("practical_label(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let (expression, label) = inner
.split_once(';')
.ok_or_else(|| Error("invalid_expression".into()))?;
let label = label.trim();
if !matches!(label, "fps" | "pixels") {
return Err(Error("invalid_expression".into()));
}
self.engine.quantity_value(expression, "1", context)?;
Ok(format!(
"{} {label}",
calculate(&self.engine, expression, context)?
))
})());
}
if let Some(inner) = input
.strip_prefix("practical_ratio(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let (width, height) = inner
.split_once(';')
.ok_or_else(|| Error("invalid_expression".into()))?;
let request = PracticalRequest {
engine: &self.engine,
context,
};
request.positive_scalar(width)?;
request.positive_scalar(height)?;
IntegerQueries
.evaluate(&format!("reduce {width}/{height} to lowest terms"), context)
.ok_or_else(|| Error("invalid_expression".into()))?
.map(|ratio| ratio.replace('/', ":"))
})());
}
None
}
}
fn calculate(engine: &Compositions, input: &str, context: &Context) -> Result<String, Error> {
engine
.evaluate(input.trim(), context)
.ok_or_else(|| Error("invalid_expression".into()))?
}
struct PracticalRequest<'a> {
engine: &'a Compositions,
context: &'a Context,
}
enum ShareRole {
Accepted,
Rejected,
}
impl PracticalRequest<'_> {
fn quantity(
&self,
input: &str,
reference: &str,
positive: bool,
error: &str,
) -> Result<String, Error> {
let input = re!(r"(?i)(\d)-([a-z]+)").replace_all(input.trim(), "$1 $2");
let value = self
.engine
.quantity_value(&input, reference, self.context)?;
if value < 0.0 || (positive && value == 0.0) {
return Err(Error(error.into()));
}
Ok(format!("({input})"))
}
fn positive_scalar(&self, input: &str) -> Result<String, Error> {
self.quantity(input, "1", true, "invalid_physical_quantity")
}
fn accepted_share(&self, input: &str, role: ShareRole) -> Result<String, Error> {
let input = input.trim();
let (numerator, denominator) =
integer_queries::ratio_value(input.strip_suffix('%').unwrap_or(input).trim())?;
let denominator = if input.ends_with('%') {
denominator * 100
} else {
denominator
};
let fraction = BigRational::new(numerator, denominator);
if fraction < BigRational::from_integer(0.into())
|| fraction > BigRational::from_integer(1.into())
{
return Err(Error("invalid_physical_quantity".into()));
}
let accepted = match role {
ShareRole::Accepted => fraction,
ShareRole::Rejected => BigRational::from_integer(1.into()) - fraction,
};
let expression = format!("rational({},{})", accepted.numer(), accepted.denom());
if expression.len() > 4096 {
return Err(Error("integer_limit".into()));
}
Ok(expression)
}
fn transfer(&self, data: &str, rate: &str) -> Result<String, Error> {
Ok(format!(
"{} / {} in seconds",
self.quantity(data, "GB", false, "invalid_physical_quantity")?,
self.quantity(rate, "GB/s", true, "invalid_rate")?
))
}
fn frames(&self, duration: &str, rate: &str) -> Result<String, Error> {
let duration = self.quantity(duration, "seconds", false, "invalid_duration")?;
self.quantity(rate, "1", true, "invalid_rate")?;
let seconds = self
.engine
.quantity_value(&duration, "seconds", self.context)?;
self.engine.quantity_value(
&format!("{duration} / (1 second) * ({rate})"),
"1",
self.context,
)?;
Ok(format!("{seconds} seconds at {rate} fps in frames"))
}
fn supplied_factor(
&self,
source: &str,
target: &str,
factor: &str,
denominator: &str,
) -> Result<String, Error> {
let source = material_quantity(source);
let c = re!(r"^([+-]?[\d.,]+)\s+(.+)$")
.captures(source)
.ok_or_else(|| Error("invalid_expression".into()))?;
let source_unit = &c[2];
let denominator_unit = self.engine.units.unit(denominator);
let factor_quantity = self
.engine
.units
.quantity(factor)
.ok_or_else(|| Error("invalid_expression".into()))?;
if factor_quantity.unit.offset != 0.0
|| denominator_unit
.as_ref()
.is_some_and(|unit| unit.offset != 0.0)
{
return Err(Error("invalid_expression".into()));
}
self.quantity(
factor,
&factor_quantity.unit.symbol,
true,
"invalid_physical_quantity",
)?;
if let Some(source_quantity) = self.engine.units.quantity(source) {
if source_quantity.unit.offset != 0.0 {
return Err(Error("invalid_expression".into()));
}
self.quantity(
source,
&source_quantity.unit.symbol,
false,
"invalid_physical_quantity",
)?;
if denominator_unit
.as_ref()
.is_some_and(|u| u.symbol == source_quantity.unit.symbol)
{
return Ok(format!(
"({source}) / (1 {denominator}) * ({factor}) in {target}"
));
}
if denominator_unit
.as_ref()
.zip(self.engine.units.unit(target))
.is_some_and(|(a, b)| a.symbol == b.symbol)
{
return Ok(format!(
"({source}) / ({factor}) * (1 {denominator}) in {target}"
));
}
} else if source_unit.to_ascii_lowercase().trim_end_matches('s')
== denominator.to_ascii_lowercase().trim_end_matches('s')
{
self.quantity(&c[1], "1", false, "invalid_physical_quantity")?;
return Ok(format!("({}) * ({factor}) in {target}", &c[1]));
}
Err(Error("incompatible_units".into()))
}
fn lower(&self, s: &str) -> Outcome {
if let Some(c) = re!(r"(?i)^a machine (?:produces|makes) (.+?) for (.+?), with (.+?) rejected(?:\. using expected good parts\s*=\s*output\s*\*\s*\(1\s*-\s*reject_rate\))?[,.;]\s*how many good parts are expected$").captures(s) {
return Some((|| {
let rate = self.quantity(&c[1], "parts/hour", false, "invalid_rate")?;
let duration = self.quantity(&c[2], "hours", false, "invalid_duration")?;
let accepted = self.accepted_share(&c[3], ShareRole::Rejected)?;
let expression = format!("({rate} * {duration} * {accepted}) in parts");
self.engine.quantity_value(&expression, "parts", self.context)?;
Ok(expression)
})());
}
if let Some(c) = re!(r"(?i)^the packaging cell makes (.+?) (?:an|per) (hour|minute) for (.+?); quality reports (.+?) yield\. find expected accepted boxes$").captures(s) {
return Some((|| {
let rate = self.quantity(&format!("{} / (1 {})", &c[1], &c[2]), "boxes/hour", false, "invalid_rate")?;
let duration = self.quantity(&c[3], "hours", false, "invalid_duration")?;
let accepted = self.accepted_share(&c[4], ShareRole::Accepted)?;
let expression = format!("({rate} * {duration} * {accepted}) in boxes");
self.engine.quantity_value(&expression, "boxes", self.context)?;
Ok(expression)
})());
}
if let Some(c) = re!(r"(?i)^a coating head deposits (.+?) for (.+?)\. what volume in (liters?|litres?|L) is deposited if density is (.+)$").captures(s) {
return Some((|| {
let rate = self.quantity(&c[1], "kg/minute", false, "invalid_rate")?;
let duration = self.quantity(&c[2], "minutes", false, "invalid_duration")?;
let density = self.quantity(&c[4], "kg/L", true, "invalid_physical_quantity")?;
let expression = format!("({rate} * {duration} / {density}) in {}", &c[3]);
self.engine.quantity_value(&expression, "L", self.context)?;
Ok(expression)
})());
}
if let Some(c) = re!(r"(?i)^a 3d printer lays down (.+?) of material per (hour|minute|second) for (.+?); at density (.+?), what mass is deposited$").captures(s) {
return Some((|| {
let volume = self.quantity(&c[1], "cm^3", false, "invalid_physical_quantity")?;
let period = self.quantity(&format!("1 {}", &c[2]), "hours", true, "invalid_duration")?;
let duration = self.quantity(&c[3], "hours", false, "invalid_duration")?;
let density = self.quantity(&c[4], "g/cm^3", true, "invalid_physical_quantity")?;
let expression = format!("({volume} / {period} * {duration} * {density}) in g");
self.engine.quantity_value(&expression, "g", self.context)?;
Ok(expression)
})());
}
if let Some(result) = self.conversions(s) {
return Some(result);
}
if let Some(result) = self.recipes(s) {
return Some(result);
}
if let Some(c) = re!(r"(?i)^a tank initially holds (.+?) and drains at (.+?) for (.+?), then receives (.+?); how many liters remain$").captures(s) {
return Some((|| {
let initial = self.quantity(&c[1], "L", false, "invalid_physical_quantity")?;
let rate = self.quantity(&c[2], "L/min", false, "invalid_rate")?;
let duration = self.quantity(&c[3], "minutes", false, "invalid_duration")?;
let received = self.quantity(&c[4], "L", false, "invalid_physical_quantity")?;
Ok(format!("({initial} - {rate} * {duration} + {received}) in L"))
})());
}
if let Some(c) = re!(r"(?i)^a printer produces (.+?) for (.+?), pauses (.+?), then produces (.+?) for (.+?); how many pages does it print in total$").captures(s) {
return Some((|| {
let first_rate = self.quantity(&c[1], "pages/minute", false, "invalid_rate")?;
let first_time = self.quantity(&c[2], "minutes", false, "invalid_duration")?;
self.quantity(&c[3], "seconds", false, "invalid_duration")?;
let second_rate = self.quantity(&c[4], "pages/minute", false, "invalid_rate")?;
let second_time = self.quantity(&c[5], "minutes", false, "invalid_duration")?;
Ok(format!("({first_rate} * {first_time} + {second_rate} * {second_time}) in pages"))
})());
}
if let Some(c) = re!(
r"(?i)^how long (?:does it take to|to) (?:transfer|upload|download|copy) (.+?) at (.+)$"
)
.captures(s)
{
return Some(self.transfer(&c[1], &c[2]));
}
if let Some(c) =
re!(r"(?i)^at (.+?), how long to (?:transfer|upload|download|copy) (.+)$").captures(s)
{
return Some(self.transfer(&c[2], &c[1]));
}
if let Some(c) = re!(
r"(?i)^a (.+?) file takes (.+?) to (?:download|upload|transfer); what was the average speed in (.+)$"
)
.captures(s)
{
return Some((|| {
let data = self.quantity(&c[1], "GB", false, "invalid_physical_quantity")?;
let duration = self.quantity(&c[2], "seconds", true, "invalid_duration")?;
Ok(format!("{data} / {duration} in {}", &c[3]))
})());
}
if let Some(c) = re!(r"(?i)^how much data can i transfer in (.+?) at (.+)$").captures(s) {
return Some((|| {
Ok(format!(
"{} * {} in GB",
self.quantity(&c[1], "seconds", false, "invalid_duration")?,
self.quantity(&c[2], "GB/s", true, "invalid_rate")?
))
})());
}
if let Some(c) = re!(
r"(?i)^at ([+-]?[\d.]+)[×x] playback, how much of a (.+?) movie can i watch in (.+)$"
)
.captures(s)
{
return Some((|| {
let movie = self.quantity(&c[2], "seconds", false, "invalid_duration")?;
let work = self.quantity(&c[3], "seconds", false, "invalid_duration")?;
self.quantity(&c[1], "1", false, "invalid_rate")?;
Ok(format!("min({movie}, {work} * ({})) in minutes", &c[1]))
})());
}
if let Some(c) = re!(
r"(?i)^a (.+?) (?:tutorial|film|clip|episode|video) (?:played|plays) at ([+-]?[\d.]+)[×x], rounded to the nearest second$"
)
.captures(s)
{
return Some((|| {
let duration = self.quantity(&c[1], "seconds", false, "invalid_duration")?;
let speed = self.quantity(&c[2], "1", true, "invalid_rate")?;
Ok(format!("round({duration} / {speed}, 1 second) in seconds"))
})());
}
if let Some(c) =
re!(r"(?i)^how many frames are in a (.+?) video at ([+-]?[\d.]+) fps$").captures(s)
{
return Some(self.frames(&c[1], &c[2]));
}
if let Some(c) = re!(
r"(?i)^a ([+-]?[\d.]+) fps (?:clip|recording) lasts (.+?); (?:estimate its frame count to the nearest whole frame|how many frames)$"
)
.captures(s)
{
return Some(self.frames(&c[2], &c[1]));
}
if let Some(c) =
re!(r"(?i)^how many frames per second is (.+?) frames per (.+)$").captures(s)
{
return Some((|| {
self.quantity(&c[1], "1", false, "invalid_physical_quantity")?;
let period =
self.quantity(&format!("1 {}", &c[2]), "seconds", true, "invalid_duration")?;
Ok(format!(
"practical_label(({}) / {period} * (1 second); fps)",
&c[1]
))
})());
}
if let Some(c) = re!(
r"(?i)^a ([+-]?[\d.]+)[×x]([+-]?[\d.]+) image scaled to ([+-]?[\d.]+) pixels wide becomes how many pixels tall$"
)
.captures(s)
{
return Some((|| {
for value in [&c[1], &c[2], &c[3]] { self.positive_scalar(value)?; }
Ok(format!("practical_label(({}) * ({}) / ({}); pixels)", &c[2], &c[3], &c[1]))
})());
}
if let Some(c) = re!(
r"(?i)^a (.+?) ([+-]?[\d.]+):([+-]?[\d.]+) screen: find its width and height in (.+)$"
)
.captures(s)
{
return Some((|| {
let diagonal = self.quantity(&c[1], "m", true, "invalid_physical_quantity")?;
for value in [&c[2], &c[3]] {
self.positive_scalar(value)?;
}
Ok(format!(
"practical_pair({diagonal} * ({}) / sqrt(square({}) + square({})) in {}; {diagonal} * ({}) / sqrt(square({}) + square({})) in {})",
&c[2], &c[2], &c[3], &c[4], &c[3], &c[2], &c[3], &c[4]
))
})());
}
if let Some(c) = re!(
r"(?i)^convert a ([+-]?[\d.]+)[×x]([+-]?[\d.]+) display's aspect ratio to a simplified ratio$"
)
.captures(s)
{
return Some((|| {
self.positive_scalar(&c[1])?;
self.positive_scalar(&c[2])?;
Ok(format!("practical_ratio({}; {})", &c[1], &c[2]))
})());
}
if let Some(c) = re!(r"(?i)^convert (.+?) to (.+?) using (.+?) = (.+)$").captures(s) {
let definition = self.engine.units.quantity(&c[3])?;
let supplied = self.engine.units.quantity(&c[4])?;
return Some((|| {
if definition.unit.dimension != supplied.unit.dimension {
return Err(Error("incompatible_units".into()));
}
self.quantity(
&c[3],
&definition.unit.symbol,
true,
"invalid_physical_quantity",
)?;
if definition.unit.offset != 0.0 || supplied.unit.offset != 0.0 {
return Err(Error("invalid_expression".into()));
}
self.quantity(
&c[4],
&supplied.unit.symbol,
true,
"invalid_physical_quantity",
)?;
let source = bind_cup(&c[1], &definition.unit.symbol);
let target_name = bind_cup(&c[2], &definition.unit.symbol);
let source_quantity = self
.engine
.units
.quantity(&source)
.ok_or_else(|| Error("invalid_expression".into()))?;
self.quantity(
&source,
&source_quantity.unit.symbol,
false,
"invalid_physical_quantity",
)?;
let target = self
.engine
.units
.unit(&target_name)
.ok_or_else(|| Error("invalid_expression".into()))?;
match (
source_quantity.unit.symbol == definition.unit.symbol,
target.symbol == definition.unit.symbol,
) {
(true, false) => Ok(format!(
"({source}) / ({}) * ({}) in {target_name}",
&c[3], &c[4]
)),
(false, true) => Ok(format!(
"({source}) / ({}) * ({}) in {target_name}",
&c[4], &c[3]
)),
_ => Ok(format!("({source}) in {target_name}")),
}
})());
}
if let Some(c) =
re!(r"(?i)^convert (.+?) to (.+?) (?:using|assuming) (.+?) per (.+)$").captures(s)
{
self.engine.units.quantity(&c[3])?;
return Some(self.supplied_factor(&c[1], &c[2], &c[3], &c[4]));
}
None
}
}
fn material_quantity(input: &str) -> &str {
if let Some(c) = re!(r"(?i)^(.+?) of [a-z]+$").captures(input) {
return c.get(1).unwrap().as_str();
}
if let Some(c) =
re!(r"(?i)^(.+? (?:grams?|g|kilograms?|kg|ounces?|oz|pounds?|lb)) [a-z]+$").captures(input)
{
return c.get(1).unwrap().as_str();
}
input
}
fn bind_cup(value: &str, declared: &str) -> String {
if declared == "US cup" {
re!(r"(?i)^(?:([+-]?[\d.,]+(?:e[+-]?\d+)?|one)\s+)?cups?$")
.replace(value.trim(), "$1 US cup")
.trim()
.to_string()
} else {
value.to_string()
}
}