salsa/tests/tracked-struct-value-field-bad-eq.rs
Niko Matsakis daaa78056a switch to new database design
Under this design, *all* databases are a
`DatabaseImpl<U>`, where the `U` implements
`UserData` (you can use `()` if there is none).

Code would default to `&dyn salsa::Database` but
if you want to give access to the userdata, you
can define a custom database trait
`MyDatabase: salsa::Databse` so long as you

* annotate `MyDatabase` trait definition of
  impls of `MyDatabase` with `#[salsa::db]`
* implement `MyDatabase` for `DatabaseImpl<U>`
  where `U` is your userdata (this could be a
  blanket impl, if you don't know the precise
  userdata type).

The `tests/common/mod.rs` shows the pattern.
2024-07-28 12:47:50 +00:00

86 lines
2.2 KiB
Rust

//! Test a field whose `PartialEq` impl is always true.
//! This can result in us getting different results than
//! if we were to execute from scratch.
use expect_test::expect;
use salsa::{Database, Setter};
mod common;
use common::LogDatabase;
use test_log::test;
#[salsa::input]
struct MyInput {
field: bool,
}
#[allow(clippy::derived_hash_with_manual_eq)]
#[derive(Eq, Hash, Debug, Clone)]
struct BadEq {
field: bool,
}
impl PartialEq for BadEq {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl From<bool> for BadEq {
fn from(value: bool) -> Self {
Self { field: value }
}
}
#[salsa::tracked]
struct MyTracked<'db> {
field: BadEq,
}
#[salsa::tracked]
fn the_fn(db: &dyn Database, input: MyInput) -> bool {
let tracked = make_tracked_struct(db, input);
read_tracked_struct(db, tracked)
}
#[salsa::tracked]
fn make_tracked_struct(db: &dyn Database, input: MyInput) -> MyTracked<'_> {
MyTracked::new(db, BadEq::from(input.field(db)))
}
#[salsa::tracked]
fn read_tracked_struct<'db>(db: &'db dyn Database, tracked: MyTracked<'db>) -> bool {
tracked.field(db).field
}
#[test]
fn execute() {
let mut db: salsa::DatabaseImpl<common::ExecuteValidateLogger> = Default::default();
let input = MyInput::new(&db, true);
let result = the_fn(&db, input);
assert!(result);
db.assert_logs(expect![[r#"
[
"salsa_event(WillExecute { database_key: the_fn(0) })",
"salsa_event(WillExecute { database_key: make_tracked_struct(0) })",
"salsa_event(WillExecute { database_key: read_tracked_struct(0) })",
]"#]]);
// Update the input to `false` and re-execute.
input.set_field(&mut db).to(false);
let result = the_fn(&db, input);
// If the `Eq` impl were working properly, we would
// now return `false`. But because the `Eq` is considered
// equal we re-use memoized results and so we get true.
assert!(result);
db.assert_logs(expect![[r#"
[
"salsa_event(WillExecute { database_key: make_tracked_struct(0) })",
"salsa_event(DidValidateMemoizedValue { database_key: read_tracked_struct(0) })",
"salsa_event(DidValidateMemoizedValue { database_key: the_fn(0) })",
]"#]]);
}