mod supplied_reports;
use super::compositions::Compositions;
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
fn encode_support(name: &str) -> String {
name.as_bytes()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join("")
}
fn decode_support(encoded: &str) -> Result<String, Error> {
if encoded.is_empty() || !encoded.is_ascii() || !encoded.len().is_multiple_of(2) {
return Err(Error("invalid_expression".into()));
}
let bytes = encoded
.as_bytes()
.as_chunks::<2>()
.0
.iter()
.map(|pair| {
let pair = std::str::from_utf8(pair).map_err(|_| Error("invalid_expression".into()))?;
u8::from_str_radix(pair, 16).map_err(|_| Error("invalid_expression".into()))
})
.collect::<Result<Vec<_>, _>>()?;
let name = String::from_utf8(bytes).map_err(|_| Error("invalid_expression".into()))?;
if !re!(r"^[A-Za-z][A-Za-z0-9_]*$").is_match(&name) {
return Err(Error("invalid_expression".into()));
}
Ok(name)
}
fn typed_coordinate(
coordinate: &super::model_coordinates::Coordinate,
unit: &str,
) -> Result<String, Error> {
let scalar = if coordinate.authored {
format!(
"rational({},{})",
coordinate.value.numer(),
coordinate.value.denom()
)
} else {
let value = coordinate
.value
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && !coordinate.value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({value:e})")
};
Ok(if unit == "1" {
scalar
} else {
format!("({scalar} {unit})")
})
}
pub(super) fn supplied_formula_role(
role: &str,
value: &str,
engine: &Compositions,
context: &Context,
) -> Result<String, Error> {
if value.len() > 4096 {
return Err(Error("expression_too_complex".into()));
}
let angular = match role.trim().to_ascii_lowercase().as_str() {
"moment of inertia" => false,
"angular speed" => true,
_ => return Err(Error("invalid_expression".into())),
};
let reference = if angular { "rad/s" } else { "kg*m²" };
let normalized = formula_role_units(value, engine, context);
let magnitude = engine.quantity_value(&normalized, reference, context)?;
if magnitude < 0.0 {
return Err(Error("invalid_physical_quantity".into()));
}
Ok(if angular {
format!("(({normalized}) / (1 rad))")
} else {
format!("({normalized})")
})
}
fn formula_role_units(input: &str, engine: &Compositions, context: &Context) -> String {
for (index, _) in input.char_indices().skip(1) {
let suffix = input[index..].trim();
let units = super::compound_units::explicit_products(suffix, |leaf| {
engine.units.unit(leaf).is_some()
});
if units == suffix
|| super::compound_units::factors(&units, |leaf| engine.units.unit(leaf).is_some())
.is_none()
{
continue;
}
let coefficient = input[..index].trim();
if engine.quantity_value(coefficient, "1", context).is_ok() {
return format!("({coefficient}) {units}");
}
}
input.to_string()
}
#[derive(Default)]
pub struct Mechanics {
compositions: Compositions,
}
impl Plugin for Mechanics {
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
self.lower(input, context).transpose()
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
super::syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = super::syntax::ungroup(input);
if let Some(inner) = input
.strip_prefix("mechanics_support_report(")
.and_then(|value| value.strip_suffix(')'))
{
return Some((|| {
if input.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
let [first, second, load, ratio] = fields.as_slice() else {
return Err(Error("invalid_expression".into()));
};
let first = decode_support(first)?;
let second = decode_support(second)?;
if first.eq_ignore_ascii_case(&second) {
return Err(Error("invalid_expression".into()));
}
let read = |expression: &str, unit: &str| {
super::model_coordinates::read(expression, unit, &self.compositions, context)
};
let load = read(load, "N")?;
let ratio = read(ratio, "1")?;
if load.value.is_negative() || ratio.value.is_negative() {
return Err(Error("invalid_physical_quantity".into()));
}
let bounded = super::model_coordinates::bounded;
let second_value =
bounded(&load.value / (&ratio.value + BigRational::from_integer(1.into())))?;
let first_value = bounded(&ratio.value * &second_value)?;
if bounded(&first_value + &second_value)? != load.value {
return Err(Error("invalid_expression".into()));
}
let display = |value: BigRational| {
let coordinate = super::model_coordinates::Coordinate {
value,
authored: load.authored && ratio.authored,
};
let expression = typed_coordinate(&coordinate, "N")?;
self.compositions
.evaluate(&format!("({expression}) in N"), context)
.ok_or_else(|| Error("invalid_expression".into()))?
};
Ok(format!(
"reaction {first}: {}; reaction {second}: {}; balanced: true",
display(first_value)?,
display(second_value)?
))
})());
}
let inner = input
.strip_prefix("mechanics_summary(")?
.strip_suffix(')')?;
Some((|| {
if input.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
let fields = inner.split(';').collect::<Vec<_>>();
let cart = fields.len() == 4
&& fields.iter().map(|field| field.split('|').next()).eq([
Some("acceleration"),
Some("final speed"),
Some("displacement"),
Some("final kinetic energy"),
]);
if !(2..=3).contains(&fields.len()) && !cart {
return Err(Error("invalid_expression".into()));
}
let mut output = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
if parts.len() != 3 {
return Err(Error("invalid_expression".into()));
}
let (label, target, expression) = (parts[0], parts[1], parts[2]);
self.validate_report_field(label, target, expression, context)?;
let display = self
.compositions
.evaluate(&format!("({expression}) in {target}"), context)
.ok_or_else(|| Error("invalid_expression".into()))??;
output.push(format!("{label}: {display}"));
}
Ok(output.join("; "))
})())
}
}
#[derive(Clone, Copy)]
enum Domain {
Signed,
Nonnegative,
Positive,
}
impl Mechanics {
fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
let trimmed = input.trim().trim_end_matches(['.', '?']);
if let Some(result) = self.supplied_reports(trimmed, context)? {
return Ok(Some(result));
}
if let Some(c) = re!(r"(?i)^add a mass of (.+?) to a duration of (.+?), then express the total in SI base units$").captures(trimmed) {
self.compositions.quantity_value(&c[1], "kg", context)?;
self.compositions.quantity_value(&c[2], "seconds", context)?;
let expression = format!("({}) + ({})", &c[1], &c[2]);
self.compositions.quantity_value(&expression, "kg", context)?;
return Ok(Some(format!("({expression}) in kg")));
}
if !re!(r"(?i)\b(momentum|kinetic|potential|accelera\w*|decelera\w*|brakes|slows|displacement|net force|work|power|u\s*=)\b").is_match(input) {
return Ok(None);
}
let input = input.replace('−', "-");
let input = input.trim().trim_end_matches(['.', '?']);
let (mut shape, quantities) = self.measurements(input);
let mut target = None;
if let Some((sentence, unit)) = shape.rsplit_once(" in ")
&& self.unit(unit)
{
target = Some(unit.to_string());
shape = sentence.into();
}
let shape = shape.as_str();
macro_rules! q {
($c:ident, $index:literal, $unit:literal, $domain:ident) => {
self.role(&$c[$index], &quantities, $unit, Domain::$domain, context)?
};
}
macro_rules! rule {
($pattern:literal, $default:literal, $c:ident, $expression:expr) => {
if let Some($c) = re!($pattern).captures(shape) {
let expression = $expression;
return Ok(Some(format!(
"({expression}) in {}",
target.as_deref().unwrap_or($default)
)));
}
};
}
if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+); (?:find|calculate|determine) the net force and the work done over @(\d+) in the force direction$").captures(shape) {
let m = q!(c, 1, "kg", Positive);
let a = q!(c, 2, "m/s²", Signed);
let distance = q!(c, 3, "m", Nonnegative);
let force = format!("{m} * {a}");
return self.report(&[("net force", "N", force.clone()),
("work", "J", format!("abs({force}) * {distance}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ moving at @(\d+) brakes uniformly to rest over @(\d+); (?:determine|find|calculate) its acceleration and stopping time$").captures(shape) {
let _mass = q!(c, 1, "kg", Positive);
let speed = q!(c, 2, "m/s", Positive);
let distance = q!(c, 3, "m", Positive);
return self.report(&[("acceleration", "m/s²", format!("-square({speed}) / (2 * {distance})")),
("stopping time", "s", format!("2 * {distance} / {speed}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+) for @(\d+) from rest; report force, final speed, and distance (?:traveled|travelled)$").captures(shape) {
let mass = q!(c, 1, "kg", Positive);
let acceleration = q!(c, 2, "m/s²", Signed);
let time = q!(c, 3, "seconds", Nonnegative);
return self.report(&[("force", "N", format!("{mass} * {acceleration}")),
("final speed", "m/s", format!("abs({acceleration} * {time})")),
("distance", "m", format!("abs({acceleration}) * square({time}) / 2"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a @(\d+) [a-z '-]+ slows uniformly from @(\d+) to @(\d+) over @(\d+); (?:calculate|find) acceleration and elapsed time$").captures(shape) {
let _mass = q!(c, 1, "kg", Positive);
let initial = q!(c, 2, "m/s", Positive);
let final_speed = q!(c, 3, "m/s", Nonnegative);
let distance = q!(c, 4, "m", Positive);
let u = super::model_coordinates::read(&initial, "m/s", &self.compositions, context)?;
let v = super::model_coordinates::read(&final_speed, "m/s", &self.compositions, context)?;
let s = super::model_coordinates::read(&distance, "m", &self.compositions, context)?;
let authored = u.authored && v.authored && s.authored;
let (u, v, s) = (u.value, v.value, s.value);
if v >= u {
return Err(Error("invalid_physical_value".into()));
}
let two = BigRational::from_integer(2.into());
let acceleration = super::model_coordinates::bounded((&v - &u) * (&v + &u) / (&two * &s))?;
let time = super::model_coordinates::bounded(two * s / (u + v))?;
let emit = |value: &BigRational, unit: &str| -> Result<String, Error> {
let scalar = if authored {
format!("rational({},{})", value.numer(), value.denom())
} else {
let number = value.to_f64().filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if number == 0.0 && !value.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({number:e})")
};
Ok(format!("(({scalar}) {unit})"))
};
return self.report(&[("acceleration", "m/s²", emit(&acceleration, "m/s²")?),
("elapsed time", "seconds", emit(&time, "seconds")?)], context).map(Some);
}
if let Some(c) = re!(r"(?i)^an? @(\d+) [a-z '-]+ is raised @(\d+) in @(\d+); using g\s*=\s*@(\d+), (?:calculate|find) potential-energy change and average power$").captures(shape) {
let mass = q!(c, 1, "kg", Positive);
let height = q!(c, 2, "m", Nonnegative);
let time = q!(c, 3, "seconds", Positive);
let gravity = q!(c, 4, "m/s²", Positive);
let energy = format!("{mass} * {gravity} * {height}");
return self.report(&[("potential-energy change", "J", energy.clone()),
("average power", "W", format!("({energy}) / {time}"))], context).map(Some);
}
if let Some(c) = re!(r"(?i)^a @(\d+) force acts at @(\d+) to a @(\d+) displacement; (?:calculate|find) work, using the angle measured between force and displacement$").captures(shape) {
let force = q!(c, 1, "N", Nonnegative);
let angle = q!(c, 2, "degrees", Nonnegative);
let displacement = q!(c, 3, "m", Nonnegative);
let coordinate = super::model_coordinates::read(&angle, "degrees", &self.compositions, context)?;
if coordinate.value > BigRational::from_integer(180.into()) {
return Err(Error("invalid_physical_value".into()));
}
let cosine = if coordinate.authored && coordinate.value == BigRational::from_integer(0.into()) {
1.0
} else if coordinate.authored && coordinate.value == BigRational::from_integer(90.into()) {
0.0
} else if coordinate.authored && coordinate.value == BigRational::from_integer(180.into()) {
-1.0
} else {
let radians = self.compositions.quantity_value(&angle, "radians", context)?;
super::arithmetic::eval(&format!("cos({radians:e})"))
.filter(|value| value.is_finite())
.ok_or_else(|| Error("invalid_physical_value".into()))?
};
return Ok(Some(format!("({force} * {displacement} * real({cosine:e})) in J")));
}
rule!(
r"(?i)^a [a-z '-]+ starts from rest and accelerates at @(\d+) for @(\d+); (?:find|calculate) its final (?:speed|velocity)$",
"m/s",
c,
magnitude_if_speed(
format!(
"{} * {}",
q!(c, 1, "m/s²", Signed),
q!(c, 2, "s", Nonnegative)
),
shape
)
);
rule!(
r"(?i)^a [a-z '-]+ (?:travels|moves) at @(\d+) and accelerates at @(\d+) for @(\d+); (?:find|calculate) its (?:displacement|final speed|final velocity)$",
"m",
c,
{
let u = q!(c, 1, "m/s", Signed);
let a = q!(c, 2, "m/s²", Signed);
let t = q!(c, 3, "s", Nonnegative);
if shape.to_ascii_lowercase().ends_with("displacement") {
format!("{u} * {t} + 0.5 * {a} * square({t})")
} else {
return Ok(Some(format!(
"({}) in {}",
magnitude_if_speed(format!("{u} + {a} * {t}"), shape),
target.as_deref().unwrap_or("m/s")
)));
}
}
);
rule!(
r"(?i)^how far does a [a-z '-]+ travel in @(\d+) from an initial (?:speed|velocity) of @(\d+) with acceleration @(\d+)$",
"m",
c,
{
let t = q!(c, 1, "s", Nonnegative);
format!(
"{} * {t} + 0.5 * {} * square({t})",
q!(c, 2, "m/s", Signed),
q!(c, 3, "m/s²", Signed)
)
}
);
rule!(
r"(?i)^for u = @(\d+), a = @(\d+), and t = @(\d+), (?:calculate|find) the displacement$",
"m",
c,
{
let t = q!(c, 3, "s", Nonnegative);
format!(
"{} * {t} + 0.5 * {} * square({t})",
q!(c, 1, "m/s", Signed),
q!(c, 2, "m/s²", Signed)
)
}
);
rule!(
r"(?i)^a [a-z '-]+ has initial velocity @(\d+) and acceleration @(\d+) for @(\d+); (?:what is|find) its final velocity$",
"m/s",
c,
format!(
"{} + {} * {}",
q!(c, 1, "m/s", Signed),
q!(c, 2, "m/s²", Signed),
q!(c, 3, "s", Nonnegative)
)
);
rule!(
r"(?i)^a [a-z '-]+ (?:slows|accelerates uniformly|slows uniformly) from @(\d+) to @(\d+) in @(\d+); (?:find|calculate) its (?:constant )?acceleration$",
"m/s²",
c,
format!(
"({} - {}) / {}",
q!(c, 2, "m/s", Signed),
q!(c, 1, "m/s", Signed),
q!(c, 3, "s", Positive)
)
);
rule!(
r"(?i)^a[n]? [a-z '-]+ (?:accelerates|slows) uniformly from @(\d+) to @(\d+) over @(\d+); (?:find|calculate) (?:its|the) acceleration$",
"m/s²",
c,
format!(
"(square({}) - square({})) / (2 * {})",
q!(c, 2, "m/s", Signed),
q!(c, 1, "m/s", Signed),
q!(c, 3, "m", Positive)
)
);
rule!(
r"(?i)^a [a-z '-]+ moving at @(\d+) brakes uniformly at @(\d+); how long until stopping$",
"s",
c,
format!(
"{} / {}",
q!(c, 1, "m/s", Nonnegative),
q!(c, 2, "m/s²", Positive)
)
);
rule!(
r"(?i)^a[n]? @(\d+) [a-z '-]+ (?:moves|travels|is launched|walks) at @(\d+); (?:find|calculate|determine|express|give|what is) (?:its|their|the [a-z '-]+) (?:signed )?momentum(?: along the chosen axis)?$",
"kg·m/s",
c,
format!(
"{} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^what speed does a @(\d+) [a-z '-]+ need to have momentum @(\d+)$",
"m/s",
c,
format!(
"abs({} / {})",
q!(c, 2, "kg·m/s", Signed),
q!(c, 1, "kg", Positive)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ has momentum @(\d+); (?:find|determine) its (?:speed|velocity)$",
"m/s",
c,
magnitude_if_speed(
format!(
"{} / {}",
q!(c, 2, "kg·m/s", Signed),
q!(c, 1, "kg", Positive)
),
shape
)
);
rule!(
r"(?i)^what is the mass of a[n]? [a-z '-]+ moving at @(\d+) with momentum @(\d+)$",
"kg",
c,
self.mass(
format!(
"{} / {}",
q!(c, 2, "kg·m/s", Signed),
q!(c, 1, "m/s", Signed)
),
context
)?
);
rule!(
r"(?i)^a[n]? [a-z '-]+ of mass @(\d+) changes velocity from @(\d+) to @(\d+); (?:find|calculate) its momentum change$",
"kg·m/s",
c,
format!(
"{} * ({} - {})",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s", Signed),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ moving at @(\d+) is brought to rest; (?:find|determine) the magnitude of its momentum change$",
"kg·m/s",
c,
format!(
"abs({} * (0 m/s - {}))",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^two [a-z '-]+ of masses @(\d+) and @(\d+) move in the same direction at @(\d+) and @(\d+); (?:find|calculate) their total momentum$",
"kg·m/s",
c,
{
let v = q!(c, 3, "m/s", Signed);
let u = q!(c, 4, "m/s", Signed);
let v_value = self.compositions.quantity_value(&v, "m/s", context)?;
let u_value = self.compositions.quantity_value(&u, "m/s", context)?;
if v_value != 0.0 && u_value != 0.0 && v_value.signum() != u_value.signum() {
return Err(Error("invalid_physical_value".into()));
}
format!(
"{} * {v} + {} * {u}",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "kg", Nonnegative)
)
}
);
rule!(
r"(?i)^two [a-z '-]+ have masses @(\d+) and @(\d+) and velocities @(\d+) and @(\d+); (?:find|calculate) their combined signed momentum$",
"kg·m/s",
c,
format!(
"{} * {} + {} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s", Signed),
q!(c, 2, "kg", Nonnegative),
q!(c, 4, "m/s", Signed)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ (?:moves|travels|is launched|walks|has speed) at? ?@(\d+); (?:find|calculate|determine|what is) (?:its|their|the [a-z '-]+) kinetic energy$",
"J",
c,
format!(
"0.5 * {} * square({})",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^calculate the kinetic energy of a @(\d+) [a-z '-]+ moving at @(\d+)$",
"J",
c,
format!(
"0.5 * {} * square({})",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^how much kinetic energy does a @(\d+) [a-z '-]+ have at @(\d+)$",
"J",
c,
format!(
"0.5 * {} * square({})",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^what speed gives a @(\d+) [a-z '-]+ kinetic energy of @(\d+)$",
"m/s",
c,
format!(
"sqrt(2 * {} / {})",
q!(c, 2, "J", Nonnegative),
q!(c, 1, "kg", Positive)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ has kinetic energy @(\d+); (?:find|determine) its (?:speed|velocity magnitude)$",
"m/s",
c,
format!(
"sqrt(2 * {} / {})",
q!(c, 2, "J", Nonnegative),
q!(c, 1, "kg", Positive)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ speeds up from @(\d+) to @(\d+); (?:calculate|find) the change in kinetic energy$",
"J",
c,
format!(
"0.5 * {} * (square({}) - square({}))",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s", Signed),
q!(c, 2, "m/s", Signed)
)
);
rule!(
r"(?i)^a [a-z '-]+ moving at @(\d+) has mass @(\d+); (?:find|calculate) its kinetic energy$",
"J",
c,
format!(
"0.5 * {} * square({})",
q!(c, 2, "kg", Nonnegative),
q!(c, 1, "m/s", Signed)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ is lifted @(\d+); use g = @(\d+) to (?:find|calculate) its gravitational potential energy gain$",
"J",
c,
format!(
"{} * {} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s²", Positive),
q!(c, 2, "m", Nonnegative)
)
);
rule!(
r"(?i)^what height gives a @(\d+) mass gravitational potential energy of @(\d+) if g = @(\d+)$",
"m",
c,
format!(
"{} / ({} * {})",
q!(c, 2, "J", Signed),
q!(c, 1, "kg", Positive),
q!(c, 3, "m/s²", Positive)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ (descends|ascends) @(\d+); (?:calculate|find) the change in gravitational potential energy using g = @(\d+)$",
"J",
c,
{
let direction = if c[2].eq_ignore_ascii_case("descends") {
"-"
} else {
""
};
format!(
"{} * {} * {direction}{}",
q!(c, 1, "kg", Nonnegative),
q!(c, 4, "m/s²", Positive),
q!(c, 3, "m", Nonnegative)
)
}
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ at height @(\d+) has what gravitational potential energy relative to the floor, with g = @(\d+)$",
"J",
c,
format!(
"{} * {} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s²", Positive),
q!(c, 2, "m", Signed)
)
);
rule!(
r"(?i)^(?:find|calculate) the gravitational potential energy of a @(\d+) [a-z '-]+ raised @(\d+) with g = @(\d+)$",
"J",
c,
format!(
"{} * {} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s²", Positive),
q!(c, 2, "m", Nonnegative)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ is raised @(\d+); (?:calculate|find) its gravitational potential energy using g = @(\d+)$",
"J",
c,
format!(
"{} * {} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 3, "m/s²", Positive),
q!(c, 2, "m", Nonnegative)
)
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ accelerates at @(\d+)\. (?:find|calculate) its net force$",
"N",
c,
format!(
"{} * {}",
q!(c, 1, "kg", Nonnegative),
q!(c, 2, "m/s²", Signed)
)
);
rule!(
r"(?i)^a @(\d+) net force acts on a @(\d+) mass\. (?:find|calculate) its acceleration$",
"m/s²",
c,
format!("{} / {}", q!(c, 1, "N", Signed), q!(c, 2, "kg", Positive))
);
rule!(
r"(?i)^a @(\d+) net force produces acceleration @(\d+)\. (?:find|calculate) the mass$",
"kg",
c,
self.mass(
format!("{} / {}", q!(c, 1, "N", Signed), q!(c, 2, "m/s²", Signed)),
context
)?
);
rule!(
r"(?i)^a constant @(\d+) force (acts along|opposes) a @(\d+) displacement\. (?:find|calculate) its (?:signed )?work$",
"J",
c,
{
let sign = if c[2].eq_ignore_ascii_case("opposes") {
"-"
} else {
""
};
format!(
"{sign}{} * {}",
q!(c, 1, "N", Nonnegative),
q!(c, 3, "m", Nonnegative)
)
}
);
rule!(
r"(?i)^@(\d+) of work is done in @(\d+)\. (?:find|calculate) the average power$",
"W",
c,
format!("{} / {}", q!(c, 1, "J", Signed), q!(c, 2, "s", Positive))
);
rule!(
r"(?i)^a @(\d+) [a-z '-]+ operates for @(\d+) at constant power\. (?:find|calculate) the work$",
"J",
c,
format!("{} * {}", q!(c, 1, "W", Signed), q!(c, 2, "s", Nonnegative))
);
Ok(None)
}
fn validate_report_field(
&self,
label: &str,
target: &str,
expression: &str,
context: &Context,
) -> Result<(), Error> {
let reference = match label {
"net force" | "force" | "force magnitude" | "braking force magnitude" => "N",
"work"
| "potential-energy change"
| "kinetic energy"
| "kinetic energy lost"
| "kinetic energy change"
| "final kinetic energy"
| "elastic potential energy" => "J",
"average power" => "W",
"final speed"
| "speed"
| "average speed"
| "shared velocity"
| "common velocity"
| "final signed velocity"
| "impact speed"
| "speed for twice kinetic energy" => "m/s",
"momentum" | "momentum change" | "momentum before impact" => "kg·m/s",
"density" => "kg/m³",
"distance" | "displacement" => "m",
"acceleration" => "m/s²",
"stopping time" | "elapsed time" | "fall time" => "seconds",
_ => return Err(Error("invalid_expression".into())),
};
self.compositions
.quantity_value(&format!("1 {target}"), reference, context)?;
self.compositions
.quantity_value(expression, target, context)?;
Ok(())
}
fn report(&self, fields: &[(&str, &str, String)], context: &Context) -> Result<String, Error> {
for (label, target, expression) in fields {
self.validate_report_field(label, target, expression, context)?;
}
let result = format!(
"mechanics_summary({})",
fields
.iter()
.map(|(label, target, expression)| format!("{label}|{target}|{expression}"))
.collect::<Vec<_>>()
.join(";")
);
if result.len() > 4096 {
return Err(Error("invalid_expression".into()));
}
Ok(result)
}
fn unit(&self, input: &str) -> bool {
super::compound_units::factors(input, |leaf| self.compositions.units.unit(leaf).is_some())
.is_some()
}
fn mass(&self, expression: String, context: &Context) -> Result<String, Error> {
if self
.compositions
.quantity_value(&expression, "kg", context)?
< 0.0
{
return Err(Error("invalid_physical_value".into()));
}
Ok(expression)
}
fn measurements(&self, input: &str) -> (String, Vec<String>) {
let mut shape = String::new();
let mut quantities = Vec::new();
let mut consumed = 0;
let groups = super::syntax::groups(input).unwrap_or_default();
for token in
re!(r"\b[a-z]+\(|[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?").find_iter(input)
{
if token.start() < consumed {
continue;
}
if token.as_str().ends_with('(') {
if super::named_quantities::has_function(token.as_str())
&& let Some(group) = groups.iter().find(|group| group.start == token.end())
{
shape.push_str(&input[consumed..token.start()]);
shape.push_str(&format!("@{}", quantities.len()));
quantities.push(input[token.start()..group.end + 1].to_string());
consumed = group.end + 1;
}
continue;
}
let suffix = &input[token.end()..];
let mut end = None;
for (index, character) in suffix.char_indices() {
if index > 64 || matches!(character, ';' | ',' | '?' | '.') {
break;
}
if character.is_whitespace() && self.unit(suffix[..index].trim()) {
end = Some(index);
}
}
let limit = suffix
.char_indices()
.find(|(i, c)| *i > 64 || matches!(c, ';' | ',' | '?' | '.'))
.map(|(i, _)| i)
.unwrap_or(suffix.len());
if self.unit(suffix[..limit].trim()) {
end = Some(limit);
}
let Some(end) = end else {
continue;
};
let end = token.end() + end;
shape.push_str(&input[consumed..token.start()]);
shape.push_str(&format!("@{}", quantities.len()));
quantities.push(input[token.start()..end].trim().to_string());
consumed = end;
}
shape.push_str(&input[consumed..]);
(
shape.split_whitespace().collect::<Vec<_>>().join(" "),
quantities,
)
}
fn role(
&self,
index: &str,
quantities: &[String],
reference: &str,
domain: Domain,
context: &Context,
) -> Result<String, Error> {
let quantity = index
.parse::<usize>()
.ok()
.and_then(|i| quantities.get(i))
.ok_or_else(|| Error("invalid_expression".into()))?;
let value = self
.compositions
.quantity_value(quantity, reference, context)?;
if (matches!(domain, Domain::Nonnegative | Domain::Positive) && value < 0.0)
|| (matches!(domain, Domain::Positive) && value == 0.0)
{
return Err(Error("invalid_physical_value".into()));
}
Ok(format!("({quantity})"))
}
}
fn magnitude_if_speed(expression: String, sentence: &str) -> String {
if sentence.to_ascii_lowercase().ends_with("speed") {
format!("abs({expression})")
} else {
expression
}
}