clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Halt flags, change flags, writing to logical names, message previewing, and
//! the class defaults mode.

use std::cell::RefCell;
use std::rc::Rc;

use clips_bindings::*;

/// Collects everything written to one logical name.
struct Capture {
    logical_name: &'static str,
    output: Rc<RefCell<String>>,
}

impl Router for Capture {
    fn query(&mut self, logical_name: &str) -> bool {
        logical_name == self.logical_name
    }

    fn write(&mut self, _logical_name: &str, text: &str) {
        self.output.borrow_mut().push_str(text);
    }
}

fn capturing(environment: &mut Environment, logical_name: &'static str) -> Rc<RefCell<String>> {
    let output = Rc::new(RefCell::new(String::new()));
    environment
        .register_router(
            "test-capture",
            40,
            Capture {
                logical_name,
                output: output.clone(),
            },
        )
        .expect("router name is unused");
    output
}

/// `(halt)` stops the run, but neither halt flag survives it: `Run` clears the
/// rule-halt flag on entry and return, and clears the evaluation-halt flag on
/// entry. The flags are therefore not a way to learn why a run stopped.
#[test]
fn halt_stops_a_run_without_leaving_either_flag_set() {
    let mut environment = Environment::new().unwrap();
    environment.build("(deftemplate tick (slot n))").unwrap();
    environment
        .build("(defrule stop (tick) => (halt))")
        .unwrap();
    environment
        .build("(defrule also-eligible (tick) =>)")
        .unwrap();
    environment.assert_string("(tick (n 1))").unwrap();

    let fired = environment.run(None);
    assert_eq!(fired, 1, "`(halt)` stopped the run before the second rule");
    assert!(!environment.halt_rules());
    assert!(!environment.halt_execution());
}

/// Neither halt flag can stop a run from outside it: `Run` clears both on
/// entry. This is why CLIPS's `Halt` is not bound at all — it does exactly
/// `set_halt_rules(true)`, which this shows to be inert.
#[test]
fn setting_a_halt_flag_before_a_run_does_not_stop_it() {
    let build = |environment: &mut Environment| {
        environment.build("(deftemplate tick (slot n))").unwrap();
        environment.build("(defrule a (tick) =>)").unwrap();
        environment.build("(defrule b (tick) =>)").unwrap();
        environment.assert_string("(tick (n 1))").unwrap();
    };

    let mut environment = Environment::new().unwrap();
    build(&mut environment);
    environment.set_halt_rules(true);
    assert_eq!(
        environment.run(None),
        2,
        "the rule-halt flag is cleared on entry to Run"
    );

    let mut environment = Environment::new().unwrap();
    build(&mut environment);
    environment.set_halt_execution(true);
    assert_eq!(
        environment.run(None),
        2,
        "the evaluation-halt flag is cleared on entry to Run"
    );
}

/// The evaluation-halt flag's real meaning: a failed `eval` leaves it set until
/// the next evaluation clears it.
#[test]
fn a_failed_evaluation_sets_the_halt_flag_until_the_next_one() {
    let mut environment = Environment::new().unwrap();

    assert!(!environment.halt_execution());
    assert!(environment.eval("(/ 1 0)").is_err());
    assert!(environment.halt_execution());

    let recovered = environment.eval("(+ 1 1)").unwrap().as_i64();
    assert_eq!(recovered, Some(2));
    assert!(
        !environment.halt_execution(),
        "CLIPS clears the flag itself when evaluation resumes"
    );
}

#[test]
fn change_flags_track_facts_instances_globals_and_focus() {
    let mut environment = Environment::new().unwrap();
    environment.build("(deftemplate item (slot id))").unwrap();
    environment
        .build("(defclass THING (is-a USER) (slot id))")
        .unwrap();
    environment.build("(defglobal ?*count* = 0)").unwrap();
    // Defining a module makes it current, which would hide MAIN's constructs
    // from the assertions below.
    environment.build("(defmodule OTHER)").unwrap();
    environment.set_current_module("MAIN").unwrap();

    environment.set_fact_list_changed(false);
    environment.set_instances_changed(false);
    environment.set_globals_changed(false);
    environment.set_focus_changed(false);

    environment.assert_string("(item (id 1))").unwrap();
    assert!(environment.fact_list_changed());

    environment
        .make_instance("([one] of THING (id 1))")
        .unwrap();
    assert!(environment.instances_changed());

    environment.set_defglobal_integer("count", 7).unwrap();
    assert!(environment.globals_changed());

    environment.focus("OTHER").unwrap();
    assert!(environment.focus_changed());
}

#[test]
fn bulk_removal_clears_facts_and_instances() {
    let mut environment = Environment::new().unwrap();
    environment.build("(deftemplate item (slot id))").unwrap();
    environment
        .build("(defclass THING (is-a USER) (slot id))")
        .unwrap();
    for id in 1..=3 {
        environment
            .assert_string(&format!("(item (id {id}))"))
            .unwrap();
        environment
            .make_instance(&format!("([thing-{id}] of THING (id {id}))"))
            .unwrap();
    }
    assert_eq!(environment.fact_count(), 3);
    assert_eq!(environment.instance_count(), 3);

    environment.retract_all_facts().unwrap();
    environment.unmake_all_instances().unwrap();

    assert_eq!(environment.fact_count(), 0);
    assert_eq!(environment.instance_count(), 0);
}

#[test]
fn writing_reaches_the_router_that_claims_the_logical_name() {
    let mut environment = Environment::new().unwrap();
    let output = capturing(&mut environment, "report");

    environment.write_to("report", "first").unwrap();
    environment.write_to("report", " second").unwrap();
    assert_eq!(output.borrow().as_str(), "first second");

    // A name no router claims does not reach this router. CLIPS reports it on
    // stderr as [ROUTER1] rather than failing the call.
    environment.write_to("unclaimed", "ignored").unwrap();
    assert_eq!(output.borrow().as_str(), "first second");

    environment.remove_router("test-capture").unwrap();
}

#[test]
fn stdout_writes_are_capturable_and_writeln_adds_a_newline() {
    let mut environment = Environment::new().unwrap();
    let output = capturing(&mut environment, "stdout");

    environment.write("no newline").unwrap();
    environment.writeln(" then one").unwrap();

    assert_eq!(output.borrow().as_str(), "no newline then one\n");
    environment.remove_router("test-capture").unwrap();
}

#[test]
fn previewing_a_send_reports_the_handlers_that_would_run() {
    let mut environment = Environment::new().unwrap();
    environment
        .build("(defclass BASE (is-a USER) (slot id))")
        .unwrap();
    environment.build("(defclass DERIVED (is-a BASE))").unwrap();
    environment
        .build("(defmessage-handler BASE describe () (printout t \"base\"))")
        .unwrap();
    environment
        .build("(defmessage-handler DERIVED describe () (printout t \"derived\"))")
        .unwrap();

    let output = capturing(&mut environment, "preview");
    {
        let class = environment
            .find_defclass("DERIVED")
            .unwrap()
            .expect("the class exists");
        class.preview_send("preview", "describe").unwrap();
    }

    let preview = output.borrow().clone();
    assert!(
        preview.contains("DERIVED") && preview.contains("BASE"),
        "the preview should list both handlers in precedence order, got: {preview:?}"
    );

    output.borrow_mut().clear();
    {
        let class = environment
            .find_defclass("DERIVED")
            .unwrap()
            .expect("the class exists");
        class.preview_send("preview", "absent-message").unwrap();
    }
    assert!(
        !output.borrow().contains("DERIVED"),
        "no handler applies, so no handler should be listed"
    );

    environment.remove_router("test-capture").unwrap();
}

/// Despite its name, the mode controls accessor-handler creation, not slot
/// default values: both classes below get the same `Static` slot default.
#[test]
fn the_class_defaults_mode_controls_accessor_creation_not_slot_defaults() {
    let mut environment = Environment::new().unwrap();
    assert_eq!(
        environment.class_defaults_mode(),
        ClassDefaultsMode::Convenience
    );

    let previous = environment.set_class_defaults_mode(ClassDefaultsMode::Conservation);
    assert_eq!(previous, ClassDefaultsMode::Convenience);
    assert_eq!(
        environment.class_defaults_mode(),
        ClassDefaultsMode::Conservation
    );

    environment
        .build("(defclass SPARSE (is-a USER) (slot value))")
        .unwrap();
    environment.set_class_defaults_mode(ClassDefaultsMode::Convenience);
    environment
        .build("(defclass FILLED (is-a USER) (slot value))")
        .unwrap();

    let handler_names = |class: &str| -> Vec<String> {
        let class = environment.find_defclass(class).unwrap().unwrap();
        class
            .message_handlers()
            .map(|handler| handler.name().to_string())
            .collect()
    };

    assert_eq!(
        handler_names("SPARSE"),
        Vec::<String>::new(),
        "conservation mode creates no accessors"
    );
    assert_eq!(
        handler_names("FILLED"),
        ["get-value", "put-value"],
        "convenience mode creates both accessors"
    );

    // The slot default is unaffected by the mode, contrary to what the CLIPS
    // name suggests.
    for class in ["SPARSE", "FILLED"] {
        let class = environment.find_defclass(class).unwrap().unwrap();
        let slot = class.slot("value").unwrap().expect("the slot exists");
        assert_eq!(slot.default_type(&environment), SlotDefaultType::Static);
    }
}

#[test]
fn beta_memory_resizing_round_trips() {
    let mut environment = Environment::new().unwrap();
    let original = environment.beta_memory_resizing();

    let previous = environment.set_beta_memory_resizing(!original);
    assert_eq!(previous, original);
    assert_eq!(environment.beta_memory_resizing(), !original);

    environment.set_beta_memory_resizing(original);
    assert_eq!(environment.beta_memory_resizing(), original);
}