nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use super::*;

impl ThermalRequest<'_> {
    pub(super) fn wording(&self, input: &str) -> Outcome {
        let s = input.trim().trim_end_matches(['.', '?']).replace('−', "-");
        if let Some(result) = self.supplied_wording(&s) {
            return Some(result);
        }
        if let Some(result) = self.expanded_wording(&s) {
            return Some(result);
        }
        if let Some(c) = re!(r"(?i)^a [a-z]+ sample absorbs (.+?) while its temperature rises (.+?); with mass (.+?) calculate specific heat in J/\(kg K\)$").captures(&s) {
            return Some((|| {
                let heat = self.role(&c[1], "J", false)?;
                let rise = self.role(&c[2], "K", true)?;
                let mass = self.role(&c[3], "kg", true)?;
                Ok(format!("thermal_specific_heat(({heat})/({mass})/({rise}))"))
            })());
        }
        if let Some(c) = re!(r"(?i)^(heat|warm|cool) (.+?) (?:of )?[a-z]+ from (.+?) to (.+?)(?: using|; use) (?:c\s*=\s*|a specific heat of )(.+?)(?:(?:; | and )(?:find the energy|report heat (?:removed|released)) in (.+))?$")
                .captures(&s)
            {
            return Some(self.directed_heat(&c[2], &c[5], &c[3], &c[4], c[1].eq_ignore_ascii_case("cool"), c.get(6).map_or("J", |m| m.as_str())));
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ (?:part|sample|block) warms from (.+?) to (.+?)\. with c\s*=\s*(.+?), how much heat does it absorb$")
                .captures(&s)
            {
            return Some(self.directed_heat(&c[1], &c[4], &c[2], &c[3], false, "J"));
        }
        if let Some(c) = re!(r"(?i)^how many (.+?) are needed to raise (.+?) (?:of )?[a-z]+ by (.+?) if its specific heat is (.+)$")
                .captures(&s)
            {
            return Some((|| {
                let mass = self.role(&c[2], "kg", false)?;
                let rise = self.rise(&c[3])?;
                let rise = format!("({rise})*(1 K)");
                let capacity = self.capacity(&c[4], "J/(kg*K)")?;
                Ok(format!("{mass}*{capacity}*{rise} in {}", &c[1]))
            })());
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ (?:sample|block|body) (?:gains|absorbs) (.+?)\. its specific heat is (.+?) and its initial temperature is (.+?); what is its final temperature$")
                .captures(&s)
            {
            return Some((|| {
                let heat = self.role(&c[2], "J", false)?;
                self.final_temperature(&c[1], &c[3], &c[4], &heat).map(|t| format!("{t} in °C"))
            })());
        }
        if let Some(c) = re!(r"(?i)^(?:how much energy )?(melts|freeze|vaporize|condense) (.+?) (?:of )?[a-z]+ at (.+?)(?: if the|\. using| using) latent heat of (?:fusion|vaporization)(?: is)?\s+(.+?)(?:; report the energy in (.+?)|, how much heat is released)?$")
                .captures(&s)
            {
            return Some((|| {
                self.temperature(&c[3])?;
                let heat = self.latent(&c[2], &c[4])?;
                Ok(format!("{heat} in {}", c.get(5).map_or("J", |m| m.as_str())))
            })());
        }
        if let Some(c) = re!(r"(?i)^a (.+?) substance melts using (.+?)\. what latent heat of fusion does that imply, in (.+)$")
                .captures(&s)
            {
            return Some((|| {
                let heat = self.role(&c[2], "J", false)?;
                let mass = self.role(&c[1], "kg", true)?;
                Ok(format!("{heat}/{mass} in {}", &c[3]))
            })());
        }
        if let Some(c) = re!(r"(?i)^a (.+?) heater runs for (.+?) with 100% conversion to heat\. how many (.+?) are supplied$")
                .captures(&s)
            {
            return Some((|| {
                let power = self.role(&c[1], "W", true)?;
                let time = self.role(&c[2], "s", false)?;
                Ok(format!("{power}*{time} in {}", &c[3]))
            })());
        }
        if let Some(c) = re!(r"(?i)^a (.+?) heater supplies (.+?) to a body\. how long does it run, in (.+?), at 100% efficiency$")
                .captures(&s)
            {
            return Some((|| {
                let power = self.role(&c[1], "W", true)?;
                let heat = self.role(&c[2], "J", false)?;
                Ok(format!("{heat}/{power} in {}", &c[3]))
            })());
        }
        if re!(r"(?i)^(?:heat|warm|cool|calculate heat released by cooling) .+\b(?:from|by)\b")
            .is_match(&s)
        {
            return Some(Err(Error("invalid_expression".into())));
        }
        None
    }
}

impl ThermalRequest<'_> {
    // Recognize quantity boundaries with the shared unit grammar, retaining prose.
    fn quantities(&self, input: &str) -> (String, Vec<String>) {
        let numbers: Vec<_> = re!(r"[+-]?(?:\d[\d,]*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?")
            .find_iter(input)
            .collect();
        let mut shape = String::new();
        let mut quantities = Vec::new();
        let mut cursor = 0;
        for (i, number) in numbers.iter().enumerate() {
            if number.start() < cursor {
                continue;
            }
            let limit = numbers.get(i + 1).map_or(input.len(), |n| n.start());
            let end = input[number.end()..limit]
                .char_indices()
                .map(|(i, _)| number.end() + i)
                .chain(std::iter::once(limit))
                .rfind(|end| {
                    let unit = input[number.end()..*end].trim();
                    !unit.is_empty()
                        && compound_units::factors(unit, |leaf| {
                            !leaf.contains(['/', '*', '·', '(', ')'])
                                && self.engine.units.unit(leaf).is_some()
                        })
                        .is_some()
                });
            let Some(end) = end else { continue };
            let end = number.start() + input[number.start()..end].trim_end().len();
            shape.push_str(&input[cursor..number.start()]);
            shape.push_str(&format!("@{}", quantities.len()));
            quantities.push(input[number.start()..end].trim().into());
            cursor = end;
        }
        shape.push_str(&input[cursor..]);
        (
            shape.split_whitespace().collect::<Vec<_>>().join(" "),
            quantities,
        )
    }
    fn converted(&self, input: &str, target: &str) -> Result<String, Error> {
        Ok(format!("({})*(1 K) in {target}", self.temperature(input)?))
    }
    fn signed_heat(
        &self,
        quantities: &[String],
        target: &str,
        wording: &str,
    ) -> Result<String, Error> {
        let cooling = re!(r"(?i)\bcools? from\b|\bto cool (?:@0|from)\b|\bheat (?:is|must be) removed\b|\bdown to @3\b").is_match(wording);
        let warming =
            re!(r"(?i)\b(?:warms?|warming|is heated) from\b|\braises it from\b|\bto raise @0\b")
                .is_match(wording);
        let direction = if cooling {
            Some(true)
        } else if warming {
            Some(false)
        } else {
            None
        };
        self.direction(&quantities[2], &quantities[3], direction)?;
        Ok(format!(
            "{} in {target}",
            self.sensible(
                &quantities[0],
                &quantities[1],
                &quantities[2],
                &quantities[3]
            )?
        ))
    }
    fn expanded_wording(&self, input: &str) -> Outcome {
        if !re!(r"(?i)temperature|thermometer|sensible heat|specific heat|heat capacity|latent heat|\bc\s*=|cools|warms|melts|vaporizes|condenses|freezes|°[cf]").is_match(input) { return None; }
        let (s, q) = self.quantities(input);
        // Absolute readings and intervals have deliberately separate output paths.
        if q.len() == 1 {
            if re!(r"(?i)^convert @0 to celsius, rounded to two decimal places$").is_match(&s) {
                return Some(
                    self.converted(&q[0], "°C")
                        .map(|t| format!("round(({t}),2)")),
                );
            }
            if let Some(c) = re!(
                r"(?i)^(?:convert @0 to (.+?)|what is @0 in (.+?))(?:, using k = °c \+ 273\.15)?$"
            )
            .captures(&s)
            {
                return Some(
                    self.converted(&q[0], c.get(1).or_else(|| c.get(2)).unwrap().as_str()),
                );
            }
            if re!(r"(?i)^(?:at what celsius temperature is [a-z]+ at @0|what celsius temperature corresponds to @0)$").is_match(&s) {
                return Some(self.converted(&q[0], "°C"));
            }
            if re!(r"(?i)^a room is at @0; report its temperature in °f, using k = °c \+ 273\.15$")
                .is_match(&s)
            {
                return Some(self.converted(&q[0], "°F"));
            }
            if let Some(c) = re!(r"(?i)^(?:a thermometer rises by @0\. express the temperature change in (.+)|convert a temperature difference of @0 to (.+))$")
                .captures(&s)
            {
                let interval = if s.to_ascii_lowercase().starts_with("a thermometer") { self.rise(&q[0]) } else { self.temperature_coordinate(&q[0], false) };
                return Some(interval.map(|v|self.interval(&v,c.get(1).or_else(||c.get(2)).unwrap().as_str())));
            }
            if re!(r"(?i)^a reading of @0 is how many celsius degrees above absolute zero\? use k = °c \+ 273\.15$").is_match(&s) {
                return Some(self.temperature(&q[0]).map(|v|self.interval(&v,"°C")));
            }
        }
        if q.len() == 2 {
            if re!(r"(?i)^how many degrees fahrenheit warmer is @0 than @1$").is_match(&s) {
                return Some(
                    self.difference(&q[1], &q[0])
                        .map(|v| self.interval(&v, "°F")),
                );
            }
            if re!(r"(?i)^(?:a sample starts at @0 and cools by @1; give its final temperature in °f|what is @0 below @1)$").is_match(&s) {
                return Some((|| {
                    let (start, change, target) = if s.to_ascii_lowercase().starts_with("what") { (&q[1],&q[0],"°C") } else { (&q[0],&q[1],"°F") };
                    let expression = format!("({})-({})",self.temperature(start)?,self.rise(change)?);
                    let expression = self.exact(&expression)?.unwrap_or(expression);
                    let expression = format!("({expression})*(1 K)");
                    self.role(&expression,"K",false)?;
                    Ok(format!("{expression} in {target}"))
                })());
            }
            let phase = re!(r"(?i)^(?:the latent heat of (?:fusion|vaporization) is @0\. how much heat melts @1 of [a-z]+ at its melting point|using latent heat @0, how much heat is needed to (?:vaporize|melt) @1)$").is_match(&s);
            let forward = re!(r"(?i)^(?:a @0 substance (?:vaporizes|melts) with latent heat @1\. calculate heat absorbed in (.+)|a @0 sample condenses and releases heat; latent heat of vaporization is @1\. report signed heat in (.+)|how much heat does @0 of [a-z]+ release when it freezes\? use latent heat of fusion @1 and a negative sign for released heat)$").captures(&s);
            if phase || forward.is_some() {
                return Some((|| {
                    let (mass, heat) = if phase {
                        (&q[1], &q[0])
                    } else {
                        (&q[0], &q[1])
                    };
                    let expression = self.latent(mass, heat)?;
                    let negative = s.to_ascii_lowercase().contains("condenses")
                        || s.to_ascii_lowercase().contains("negative sign");
                    let supplied_unit = phase
                        .then(|| self.engine.units.quantity(heat))
                        .flatten()
                        .and_then(|q| {
                            q.unit
                                .symbol
                                .split_once('/')
                                .map(|(unit, _)| unit.to_string())
                        });
                    let target = forward
                        .as_ref()
                        .and_then(|c| c.get(1).or_else(|| c.get(2)))
                        .map_or(supplied_unit.as_deref().unwrap_or("J"), |m| m.as_str());
                    Ok(format!(
                        "{} in {target}",
                        if negative {
                            format!("-({expression})")
                        } else {
                            expression
                        }
                    ))
                })());
            }
        }
        if q.len() == 3 {
            if re!(r"(?i)^an object has heat capacity @0 and warms from @1 to @2\. calculate signed heat in joules$").is_match(&s) {
                return Some((|| {
                    self.direction(&q[1], &q[2], Some(false))?;
                    self.capacity_energy(&q[0], &q[1], &q[2]).map(|v| format!("{v} in J"))
                })());
            }
            if re!(r"(?i)^a @0 sample, c=@1, releases @2\. what is its temperature change in °c$")
                .is_match(&s)
            {
                return Some((|| {
                    let mass = self.role(&q[0], "kg", true)?;
                    let capacity = self.capacity(&q[1], "J/(kg*K)")?;
                    let heat = self.role(&q[2], "J", false)?;
                    Ok(format!(
                        "thermal_interval(-({heat})/({mass}*{capacity});°C)"
                    ))
                })());
            }
            if let Some(c) =
                re!(r"(?i)^(?:a @0 [a-z]+ with specific heat @1 warms by @2\. calculate signed sensible heat in (.+)|an? @0 [a-z]+ has c=@1\. what signed heat accompanies cooling it by @2|what sensible heat in (.+?) raises @0, c=@1, by @2|a @0 [a-z]+ with c=@1 cools by @2\. return signed heat in (.+))$")
                .captures(&s)
            {
                return Some((|| {
                    let mass=self.role(&q[0],"kg",false)?;
                    let capacity=self.capacity(&q[1],"J/(kg*K)")?;
                    let change=self.rise(&q[2])?;
                    let target=c.get(1).or_else(||c.get(2)).or_else(||c.get(3)).map_or("kJ",|m|m.as_str());
                    let cooling = re!(r"(?i)\bcools by @2\b|\bcooling it by @2\b").is_match(&s);
                    let sign = if cooling { "-" } else { "" };
                    Ok(format!("{sign}({mass}*{capacity}*({change})*(1 K)) in {target}"))
                })());
            }
        }
        if q.len() == 4 {
            if let Some(c) =
                re!(r"(?i)^(?:a @0 body with c=@1 loses @2\. starting at @3, what is its final temperature in (.+)|a @0 object, c=@1, starts at @2 and absorbs @3\. find the final (.+?) temperature|a @0 [a-z]+ (?:part|sample|block) with c=@1 absorbs @2 from @3\. what is its final temperature in (.+)|a @0 block at @1 loses @2; its specific heat is @3\. find final temperature in (.+))$")
                .captures(&s)
            {
                return Some((|| {
                    let (capacity,start,heat)=if c.get(4).is_some() { (&q[3],&q[1],format!("-({})",self.role(&q[2],"J",false)?)) }
                        else if c.get(2).is_some() {(&q[1],&q[2],self.role(&q[3],"J",false)?)}
                        else {(&q[1],&q[3],if c.get(1).is_some(){format!("-({})",self.role(&q[2],"J",false)?)}else{self.role(&q[2],"J",false)?})};
                    let target=c.iter().skip(1).flatten().next().unwrap().as_str();
                    let target=if target.eq_ignore_ascii_case("°f") {"°F"}else{target};
                    Ok(format!("{} in {target}",self.final_temperature(&q[0],capacity,start,&heat)?))
                })());
            }
            let between=re!(r"(?i)^(?:a [a-z]+ block of mass @0 has specific heat @1\. how much sensible heat raises it from @2 to @3|find the sensible heat to cool @0 of [a-z]+, specific heat @1, from @2 to @3|how much heat is removed when @0 with specific heat @1 cools from @2 to @3\? report signed heat|how much signed heat for @0 of [a-z]+ with c=@1, from @2 down to @3|find the heat to raise @0 with c=@1 from @2 to @3|compute q = mcΔt for m=@0, c=@1, t₁=@2, t₂=@3)$").is_match(&s);
            let targeted=re!(r"(?i)^(?:calculate sensible heat for @0(?: at @1, warming|, c=@1,) from @2 to @3; (?:give|report) (.+)|a @0 object has c = @1 and goes from @2 to @3\. find signed heat in (.+)|for a @0 block with specific heat @1, find heat for a change from @2 to @3 and express it in (.+)|for a @0 sample with c=@1, calculate heat to go from @2 to @3; answer in (.+)|a @0 object with c=@1 is heated from @2 to @3\. give q in (.+)|how much heat must be removed from @0 with c=@1 to cool from @2 to @3\? give a negative signed result in (.+))$").captures(&s);
            if between || targeted.is_some() {
                let target = targeted
                    .as_ref()
                    .and_then(|c| c.iter().skip(1).flatten().next())
                    .map_or("J", |m| m.as_str());
                return Some(self.signed_heat(&q, target, &s));
            }
        }
        None
    }
}