nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Complete thin-lens declarations lower to one typed report owner.
use super::*;

fn goals(input: &str) -> Option<Vec<(String, String)>> {
    let (fields, target) =
        if let Some(c) = re!(r"(?i)^(.+?), then convert both to (.+)$").captures(input) {
            (c[1].to_owned(), Some(c[2].to_owned()))
        } else {
            (input.to_owned(), None)
        };
    let mut fields = lens_fields(&fields)?;
    if let Some(target) = target {
        for (label, unit) in &mut fields {
            // A common distance target cannot be assigned to dimensionless magnification.
            if label == "magnification" || unit != "m" {
                return None;
            }
            *unit = target.clone();
        }
    }
    Some(fields)
}

impl Request<'_> {
    fn declared_lens(
        &self,
        f: &str,
        object: &str,
        height: Option<&str>,
        kind: &str,
        output: &str,
        real_object: bool,
    ) -> Result<String, Error> {
        let fields = goals(output).ok_or_else(invalid)?;
        if real_object {
            self.real_object(object)?;
        }
        self.lens_report(f, object, height, kind, &fields)
    }

    pub(super) fn lens_clauses(&self, input: &str) -> Result<Option<String>, Error> {
        macro_rules! family {
            ($pattern:literal, $c:ident, $answer:expr) => {
                if let Some($c) = re!($pattern).captures(input) {
                    return $answer.map(Some);
                }
            };
        }
        family!(
            r"(?i)^a converging lens has focal length (.+?) and object distance (.+?); calculate image distance and magnification m\s*=\s*-di/do$",
            c,
            self.lens_answer(&c[1], &c[2], None, "converging", "report")
        );
        family!(
            r"(?i)^an object is (.+?) tall and its image is (.+?) tall; calculate signed magnification and state its orientation from the sign$",
            c,
            {
                let object = self.read(&c[1], "m")?;
                let image = self.read(&c[2], "m")?;
                if !object.value.is_positive() {
                    return Err(physical());
                }
                let signed = coordinate(
                    image.value / object.value,
                    image.authored && object.authored,
                )?;
                let orientation = if signed.value.is_negative() {
                    "inverted"
                } else {
                    "upright"
                };
                Ok(report(&[
                    ("magnification", self.emit(&signed, "1")?),
                    ("orientation", orientation.into()),
                ]))
            }
        );
        family!(
            r"(?i)^a (.+?) tall object is (.+?) from a (converging|diverging) lens of focal length (.+?); (?:calculate|find) image distance in metres and signed image height in centimetres$",
            c,
            {
                self.real_object(&c[2])?;
                self.lens_report(
                    &c[4],
                    &c[2],
                    Some(&c[1]),
                    &c[3],
                    &[
                        ("image distance".into(), "m".into()),
                        ("image height".into(), "cm".into()),
                    ],
                )
            }
        );
        family!(
            r"(?i)^a (converging|diverging) lens has focal length (.+?); if an object is (.+?) away, (?:calculate|find) image location and magnification, then scale the image height for an object (.+?) tall$",
            c,
            {
                self.real_object(&c[3])?;
                self.lens_report(
                    &c[2],
                    &c[3],
                    Some(&c[4]),
                    &c[1],
                    &[
                        ("image distance".into(), "cm".into()),
                        ("magnification".into(), "1".into()),
                        ("image height".into(), "cm".into()),
                    ],
                )
            }
        );
        family!(
            r"(?i)^a lens forms an inverted image (.+?) tall from an upright (.+?) object; using m\s*=\s*hi/ho and m\s*=\s*-di/do, find the ratio di/do$",
            c,
            {
                let image_height = self.read(&c[1], "m")?;
                let object_height = self.read(&c[2], "m")?;
                if !image_height.value.is_positive() || !object_height.value.is_positive() {
                    return Err(physical());
                }
                let ratio = coordinate(
                    image_height.value / object_height.value,
                    image_height.authored && object_height.authored,
                )?;
                self.emit(&ratio, "1")
            }
        );
        family!(
            r"(?i)^an object distance of (.+?) and focal length of (.+?) are given for a thin lens; (?:calculate|find) signed image distance$",
            c,
            {
                self.real_object(&c[1])?;
                self.lens_answer(&c[2], &c[1], None, "", "distance")
            }
        );
        family!(
            r"(?i)^a (?:thin )?(converging|diverging) lens has focal length (.+?); an object (.+?) away is (.+?) tall\. (?:find|calculate|report) (.+)$",
            c,
            self.declared_lens(&c[2], &c[3], Some(&c[4]), &c[1], &c[5], true)
        );
        family!(
            r"(?i)^for a (converging|diverging) lens with f\s*=\s*(.+?)(?:,| and) (?:object distance\s+|do\s*=\s*)(.+?)(?:,|;) (?:report|give|find|calculate) (.+?) for (?:an )?object height(?: of)?\s+(.+)$",
            c,
            self.declared_lens(&c[2], &c[3], Some(&c[5]), &c[1], &c[4], false)
        );
        family!(
            r"(?i)^using the thin-lens equation, (?:find|calculate) (.+?) for f\s*=\s*(.+?), do\s*=\s*(.+?), and ho\s*=\s*(.+?); give distances and height in (.+)$",
            c,
            {
                let mut fields = lens_fields(&c[1]).ok_or_else(invalid)?;
                for (label, target) in &mut fields {
                    if label == "magnification" || target != "m" {
                        return Err(invalid());
                    }
                    *target = c[5].to_owned();
                }
                self.lens_report(&c[2], &c[3], Some(&c[4]), "", &fields)
            }
        );
        family!(
            r"(?i)^an object (.+?) tall stands (.+?) before a lens with focal length (.+?); (?:state|find|report) (.+?) using real image distances positive and virtual distances negative$",
            c,
            self.declared_lens(&c[3], &c[2], Some(&c[1]), "", &c[4], true)
        );
        family!(
            r"(?i)^a lens produces a virtual image (.+?) from it for an object (.+?) away; (?:find|calculate) its focal length and (?:signed )?magnification, taking virtual image distance as negative$",
            c,
            {
                self.real_object(&c[2])?;
                let image = self.length(&c[1])?;
                if image.value.is_negative() {
                    return Err(physical());
                }
                let image = coordinate(-image.value, image.authored)?;
                self.lens_inverse_answer(&c[2], &self.emit(&image, "m")?, "focal", "", true)
            }
        );
        family!(
            r"(?i)^for f\s*=\s*(.+?) and do\s*=\s*(.+?), what (.+?) does the thin-lens model give for ho\s*=\s*(.+)$",
            c,
            self.declared_lens(&c[1], &c[2], Some(&c[4]), "", &c[3], false)
        );
        family!(
            r"(?i)^a (.+?) focal-length lens views a (.+?) (?:person|object) from (.+?) away; (?:calculate|find|report) (.+)$",
            c,
            self.declared_lens(&c[1], &c[3], Some(&c[2]), "", &c[4], true)
        );
        family!(
            r"(?i)^a (?:(converging|diverging) )?lens has focal length (.+?) and object distance (.+?); (?:report|find|calculate) (.+?) for a (.+?) tall object$",
            c,
            self.declared_lens(
                &c[2],
                &c[3],
                Some(&c[5]),
                c.get(1).map_or("", |s| s.as_str()),
                &c[4],
                false
            )
        );
        family!(
            r"(?i)^if image distance is (.+?) and object distance is (.+?), calculate focal length and signed magnification from the thin-lens equation$",
            c,
            self.lens_inverse_answer(&c[2], &c[1], "focal", "", true)
        );
        family!(
            r"(?i)^for a (converging|diverging) lens with f\s*=\s*(.+?), do\s*=\s*(.+?), and ho\s*=\s*(.+?), (?:give|report|calculate|find) (.+)$",
            c,
            self.declared_lens(&c[2], &c[3], Some(&c[4]), &c[1], &c[5], false)
        );
        family!(
            r"(?i)^a (.+?) object distance and (.+?) focal length are supplied for a thin lens; (?:calculate|find) (.+)$",
            c,
            self.declared_lens(&c[2], &c[1], None, "", &c[3], false)
        );
        Ok(None)
    }
}