nmbrs-runtime 0.7.0

Workload execution runtime for nmbrs
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! What nmbrs refuses about a scenario comprehension's `where:` filter
//! (SRD-18c, "A filter that keeps nothing is an error").
//!
//! polydat gives a filter that reads an unbound name a defined meaning:
//! the name reads None, the predicate is None, and no tuple is kept.
//! For a scenario that meaning is a loop that silently never runs, so
//! nmbrs holds two rules of its own over polydat's evaluation:
//!
//! - a name a filter reads that nothing binds is an error, reported
//!   from polydat's own name-closure check (`unresolved_names`);
//! - a filter that keeps none of the tuples its source produced is an
//!   error.

use polydat::iteration::comprehension::{
    ClauseYield, Comprehension, ReadSite, Surface, unresolved_names,
};
use polydat::kernel::interp::Lookup;

/// Refuse a filter that reads a name bound nowhere.
///
/// A bare word in a predicate is always such a name: a predicate reads
/// its scope only through `{name}`. Names read by a clause's *source*
/// are not judged here; the evaluation reports those per clause.
pub(crate) fn check_filter_names(comp: &Comprehension, scope: &dyn Lookup) -> Result<(), String> {
    let has = |name: &str| scope.lookup(name).is_some();
    let mut problems: Vec<String> = Vec::new();
    for read in unresolved_names(comp, Surface::Traversal(&has)) {
        let ReadSite::Predicate { predicate } = &read.site else {
            continue;
        };
        let name = &read.name;
        problems.push(if read.bare {
            format!(
                "`where: {predicate}` reads the bare word '{name}', which a filter cannot \
                 resolve: write `{{{name}}}` for the iteration variable or param of that \
                 name, or \"{name}\" for the string"
            )
        } else {
            format!(
                "`where: {predicate}` reads '{{{name}}}', and no iteration variable, \
                 workload param or inherited binding is named '{name}'"
            )
        });
    }
    if problems.is_empty() {
        Ok(())
    } else {
        Err(problems.join("; "))
    }
}

/// The predicates of every filter in `comp`, outermost first.
fn filter_predicates(comp: &Comprehension, out: &mut Vec<String>) {
    match comp {
        Comprehension::Clause { .. } => {}
        Comprehension::Cartesian { children }
        | Comprehension::Zip { children, .. }
        | Comprehension::Union { children } => {
            for child in children {
                filter_predicates(child, out);
            }
        }
        Comprehension::Filter { child, predicate } => {
            out.push(predicate.clone());
            filter_predicates(child, out);
        }
        Comprehension::Order { child, .. } => filter_predicates(child, out),
    }
}

/// The error for a comprehension whose filter kept nothing, or `None`
/// when that is not what happened.
///
/// The comprehension is judged as a whole: a filter that empties some
/// sub-spaces of a union is how part of a matrix is selected, so only
/// an empty result is the error. A clause that produced no values is a
/// different condition (an empty source), reported where the clauses
/// are, and is not blamed on the filter.
pub(crate) fn empty_filter_error(
    comp: &Comprehension,
    tuples: usize,
    clauses: &[ClauseYield],
) -> Option<String> {
    if tuples > 0 {
        return None;
    }
    let mut predicates = Vec::new();
    filter_predicates(comp, &mut predicates);
    if predicates.is_empty() {
        return None;
    }
    if clauses.is_empty() || clauses.iter().any(|c| c.evaluations == 0 || c.values == 0) {
        return None;
    }
    let filters = predicates
        .iter()
        .map(|p| format!("`where: {p}`"))
        .collect::<Vec<_>>()
        .join(" and ");
    let produced = clauses
        .iter()
        .map(|c| format!("{} value(s) of '{}'", c.values, c.var))
        .collect::<Vec<_>>()
        .join(", ");
    Some(format!(
        "{filters} kept none of the tuples its source produced ({produced}), so nothing \
         beneath it would run. In a filter, an iteration variable or param is written \
         `{{name}}` and is compared with its declared type"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use polydat::iteration::comprehension::evaluate_for_iteration_with_none_reads;
    use polydat::iteration::comprehension::spec::parse_comprehension_algebra;

    fn kernel() -> polydat::kernel::PolydatKernel {
        polydat::dsl::compile::compile_polydat_interpreter(
            r#"
            extern select_sizes: str = "^(1m)$"
            const sel := select_sizes
        "#,
        )
        .expect("compile")
    }

    /// The filter error for `text`, evaluated against the test scope.
    fn outcome(text: &str) -> (Result<(), String>, Option<String>) {
        let comp = parse_comprehension_algebra(text).expect("parse");
        let scope = kernel();
        let names = check_filter_names(&comp, &scope);
        let (evaluated, _) =
            evaluate_for_iteration_with_none_reads(&comp, &scope).expect("evaluate");
        let empty = empty_filter_error(&comp, evaluated.tuples.len(), &evaluated.clauses);
        (names, empty)
    }

    #[test]
    fn a_bare_word_in_a_filter_is_refused_with_both_spellings() {
        let (names, _) = outcome(r#"size in ["1m","10m"] where str_eq(size, "1m")"#);
        let err = names.unwrap_err();
        assert!(err.contains("bare word 'size'"), "{err}");
        assert!(err.contains("{size}") && err.contains("\"size\""), "{err}");
    }

    #[test]
    fn an_unbound_placeholder_in_a_filter_is_refused() {
        let (names, _) = outcome(r#"size in ["1m"] where {sise} == "1m""#);
        let err = names.unwrap_err();
        assert!(err.contains("'{sise}'"), "{err}");
    }

    #[test]
    fn a_filter_reading_its_tuple_and_its_scope_is_accepted() {
        let (names, empty) =
            outcome(r#"size in ["1m","10m"] where regex_match("{size}", "{select_sizes}")"#);
        assert!(names.is_ok(), "{names:?}");
        assert!(empty.is_none(), "{empty:?}");
    }

    /// A filter no tuple satisfies; polydat evaluates it without
    /// complaint, and nmbrs refuses the result.
    #[test]
    fn a_filter_that_keeps_nothing_is_refused() {
        let (names, empty) = outcome(r#"size in ["1m","10m"] where regex_match({size}, "^(6m)$")"#);
        assert!(names.is_ok(), "{names:?}");
        let err = empty.expect("an empty-filter error");
        assert!(err.contains("regex_match({size}"), "{err}");
        assert!(err.contains("2 value(s) of 'size'"), "{err}");
    }

    /// A placeholder that is a whole argument of a call is the string
    /// it names (polydat spec ยง3.1.5), so the unquoted form selects as
    /// the quoted one does.
    #[test]
    fn an_unquoted_call_argument_reads_the_string() {
        let (names, empty) =
            outcome(r#"size in ["1m","10m"] where regex_match({size}, {select_sizes})"#);
        assert!(names.is_ok(), "{names:?}");
        assert!(empty.is_none(), "{empty:?}");
    }

    #[test]
    fn a_filter_that_keeps_something_is_not_an_error() {
        let (_, empty) = outcome(r#"size in ["1m","10m"] where {size} == "1m""#);
        assert!(empty.is_none(), "{empty:?}");
    }

    /// No filter, no filter error: an empty source is another rule's.
    #[test]
    fn an_unfiltered_comprehension_is_never_this_error() {
        let comp = parse_comprehension_algebra(r#"size in ["1m"]"#).expect("parse");
        let none = empty_filter_error(
            &comp,
            0,
            &[ClauseYield {
                var: "size".into(),
                source: None,
                evaluations: 1,
                values: 1,
            }],
        );
        assert!(none.is_none());
    }

    /// A clause that produced nothing is an empty source, not a filter
    /// that kept nothing.
    #[test]
    fn an_empty_source_is_not_blamed_on_the_filter() {
        let comp =
            parse_comprehension_algebra(r#"size in ["1m"] where {size} == "1m""#).expect("parse");
        let none = empty_filter_error(
            &comp,
            0,
            &[ClauseYield {
                var: "size".into(),
                source: None,
                evaluations: 1,
                values: 0,
            }],
        );
        assert!(none.is_none());
    }
}