Files
core/test/rust/compiler.rs
T
2026-11-27 06:03:56 +00:00

479 lines
18 KiB
Rust

use dever::compiler::check::{rules, types::Types};
use dever::compiler::{
check::calls,
project::{Module, Role},
};
use dever::syntax::{
ast::{Body, Declaration},
diagnostic::Diagnostic,
lex, parse,
source::Source,
};
#[path = "compiler/rule_properties.rs"]
mod rule_properties;
fn conditions(text: &str) -> Result<rules::RuleConditions, Diagnostic> {
let source = Source::new(0, "app.dever", text.into());
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len());
if let Some(error) = diagnostics.into_iter().next() {
return Err(error);
}
let parsed = parse::parse(tokens);
assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics);
let modules = [dever::compiler::project::Module::standalone()];
let types = Types::resolve(&parsed.declarations, &modules)?;
let function = parsed
.declarations
.iter()
.find_map(|declaration| match declaration {
Declaration::Function(function) => Some(function),
_ => None,
})
.unwrap();
let Body::Rule(rule) = &function.body else {
panic!()
};
rules::resolve(function, rule, &types)
}
#[test]
fn rule_name_parameter_and_output_do_not_become_a_row_label() {
for text in [
"rule identity(name: Bool) (out: Bool)\n| name | out |\n| true | true |\n| false | false |",
"rule identity(name: Bool) (out: Bool)\n| name | name | out |\n| yes | true | true |\n| no | false | false |",
"rule identity() (name: Bool)\n| name |\n| true |",
] {
assert!(conditions(text).is_ok(), "{text}");
}
}
#[test]
fn shipping_partitions_exact_decimal_edges() {
let value = conditions("type Region { Local, Remote }\nrule shipping(region: Region, goods: Decimal) (fee: Decimal)\n| region | goods | fee |\n| Local | >= 199 | 0 |\n| Local | < 199 | 8 |\n| Remote | - | 15 |\n").unwrap();
assert_eq!(value.rows.len(), 3);
assert!(value.work < 1000);
let error = conditions("rule precise(value: Decimal) (ok: Bool)\n| value | ok |\n| < 0.1000000000000000000000000000000001 | true |\n| >= 0.1000000000000000000000000000000002 | false |\n").err().unwrap();
assert_eq!(error.code, "C009");
assert!(
error
.message
.contains("0.1000000000000000000000000000000001"),
"{error}"
);
}
#[test]
fn rule_overlap_reports_both_rows_and_missing_reports_a_witness() {
let error = conditions("rule f(x: Bool) (y: Int)\n| x | y |\n| - | 1 |\n| true | 2 |\n")
.err()
.unwrap();
assert!(error.message.contains("overlap: x = true"));
assert_eq!(error.related.len(), 2);
let error = conditions("rule f(x: Bool) (y: Int)\n| x | y |\n| true | 2 |\n")
.err()
.unwrap();
assert!(error.message.contains("does not cover: x = false"));
}
#[test]
fn other_is_a_column_complement_without_row_priority() {
conditions("rule f(x: Text) (y: Int)\n| x | y |\n| \"a\", \"b\" | 1 |\n| other | 2 |\n")
.unwrap();
let error = conditions("rule f(x: Bool, y: Bool) (z: Int)\n| x | y | z |\n| true | true | 1 |\n| false | other | 2 |\n").err().unwrap();
assert!(error.message.contains("does not cover"));
}
#[test]
fn signature_range_limits_coverage_without_hiding_empty_ranges() {
conditions("rule f(x: Int >= 1 and <= 9) (y: Int)\n| x | y |\n| < 5 | 1 |\n| >= 5 | 2 |\n")
.unwrap();
assert_eq!(
conditions("rule f(x: Int > 9223372036854775807) (y: Int)\n| x | y |\n| - | 1 |\n")
.err()
.unwrap()
.code,
"C008"
);
let error = conditions("rule f(x: Int >= 1) (y: Int)\n| x | y |\n| <= 0 | 0 |\n| >= 1 | 1 |\n")
.err()
.unwrap();
assert!(error.message.contains("outside"));
}
#[test]
fn nullable_and_choice_payload_conditions_preserve_their_contracts() {
conditions("rule f(x: Int?) (y: Int)\n| x | y |\n| null | 0 |\n| other | 1 |\n").unwrap();
conditions("type Response { Ready(value: Text), error Rejected(reason: Text) }\nrule f(x: Response) (y: Text)\n| x | y |\n| Ready(value) | value |\n| Rejected(reason) | fail(Response.Rejected(reason)) |\n").unwrap();
let error = conditions("type Response { Ready, error Rejected }\nrule f(x: Response) (y: Int)\n| x | y |\n| Ready | 0 |\n| other | 1 |\n").err().unwrap();
assert_eq!(error.code, "C011");
let error = conditions("type Response { A(first: Text), B(first: Int) }\nrule f(x: Response) (y: Int)\n| x | y |\n| A(value), B(value) | 1 |\n").err().unwrap();
assert!(error.message.contains("same names and types"));
}
#[test]
fn rule_headers_and_failure_outputs_cannot_be_filled_with_defaults() {
for source in [
"rule f(x: Bool) (y: Int)\n| wrong | y |\n| - | 1 |\n",
"rule f(x: Bool) (y: Int)\n| x | y |\n| - | - |\n",
"rule f(x: Bool) (a: Int, b: Int)\n| x | a | b |\n| - | fail(Invalid) | 0 |\n",
] {
assert_eq!(conditions(source).err().unwrap().code, "C009");
}
}
#[test]
fn proof_scales_by_candidate_partitions_and_stops_at_a_real_budget() {
let parameters = (0..10)
.map(|i| format!("b{i}: Bool"))
.collect::<Vec<_>>()
.join(", ");
let header = (0..10)
.map(|i| format!("b{i}"))
.collect::<Vec<_>>()
.join(" | ");
let mut source = format!("rule f({parameters}) (y: Int)\n| {header} | y |\n");
for row in 0..1024 {
let cells = (0..10)
.map(|bit| ((row >> bit) & 1 != 0).to_string())
.collect::<Vec<_>>()
.join(" | ");
source.push_str(&format!("| {cells} | 1 |\n"));
}
assert!(conditions(&source).unwrap().work < rules::PROOF_BUDGET);
let parameters = (0..20)
.map(|i| format!("b{i}: Bool"))
.collect::<Vec<_>>()
.join(", ");
let header = (0..20)
.map(|i| format!("b{i}"))
.collect::<Vec<_>>()
.join(" | ");
let cells = vec!["-"; 20].join(" | ");
assert!(
conditions(&format!(
"rule f({parameters}) (y: Int)\n| {header} | y |\n| {cells} | 1 |\n"
))
.unwrap()
.work
< 1000
);
let mut large = String::from("rule f(x: Int) (y: Int)\n| x | y |\n");
for value in 0..1200 {
large.push_str(&format!("| {value} | 1 |\n"));
}
large.push_str("| other | 2 |\n");
let error = conditions(&large).err().unwrap();
assert_eq!(error.code, "C015");
assert!(error.message.contains("has not been proved"));
}
fn source_declarations(id: usize, text: &str) -> Vec<Declaration> {
let source = Source::new(id, "app.dever", text.into());
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len());
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let result = parse::parse(tokens);
assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
result.declarations
}
fn module(domain: &str, role: Role) -> Module {
Module {
standalone: false,
component: "shop".into(),
domain: domain.into(),
role,
topic: None,
}
}
#[test]
fn every_rule_branch_participates_in_cycle_checking() {
let declarations = source_declarations(
0,
"rule choose(x: Bool) (y: Int)\n| x | y |\n| true | 1 |\n| false | next(x) |\nnext(x: Bool) (y: Int) { y = choose(x) }\n",
);
let error = calls::bind(&declarations, &[Module::standalone()])
.err()
.unwrap();
assert_eq!(error.code, "C010");
assert_eq!(error.related.len(), 2);
}
#[test]
fn domains_cannot_depend_on_each_other_even_without_recursive_functions() {
let mut declarations = source_declarations(
0,
"start() (x: Int) { x = delivery.quote() }\nunit() (x: Int) { x = 1 }\n",
);
declarations.extend(source_declarations(
1,
"quote() (x: Int) { x = order.unit() }\n",
));
let modules = [module("order", Role::App), module("delivery", Role::App)];
let error = dever::compiler::check::program::check(&declarations, &modules)
.err()
.unwrap();
assert!(error.message.contains("domain"));
assert_eq!(error.related.len(), 2);
}
#[test]
fn qualified_names_do_not_bypass_role_access() {
let mut declarations =
source_declarations(0, "start() (x: Int) { x = shop.delivery.domain.quote() }\n");
declarations.extend(source_declarations(1, "quote() (x: Int) { x = 1 }\n"));
let modules = [module("order", Role::App), module("delivery", Role::Domain)];
let error = calls::bind(&declarations, &modules).err().unwrap();
assert_eq!(error.code, "C003");
}
#[test]
fn public_rule_reuse_is_one_bound_call_without_a_wrapper() {
let mut declarations = source_declarations(
0,
"start(x: Bool) (fee: Int) { fee = delivery.shipping(x) }\n",
);
declarations.extend(source_declarations(
1,
"rule shipping(remote: Bool) (fee: Int)\n| remote | fee |\n| true | 15 |\n| false | 8 |\n",
));
let modules = [module("order", Role::App), module("delivery", Role::App)];
let graph = calls::bind(&declarations, &modules).unwrap();
assert_eq!(graph.edges.len(), 1);
assert_eq!(
graph.identities[graph.edges[0].target],
"shop.delivery.app.shipping"
);
assert_eq!(graph.order, vec![1, 0]);
}
#[test]
fn ten_thousand_function_chain_does_not_use_a_recursive_checker_stack() {
let mut source = String::from("step0() (x: Int) { x = 0 }\n");
for index in 1..10_000 {
source.push_str(&format!(
"step{index}() (x: Int) {{ x = step{}() + 1 }}\n",
index - 1
));
}
let declarations = source_declarations(0, &source);
let graph = calls::bind(&declarations, &[Module::standalone()]).unwrap();
assert_eq!(graph.order.len(), 10_000);
assert_eq!(graph.edges.len(), 9_999);
assert_eq!(graph.order[0], 0);
assert_eq!(graph.order[9_999], 9_999);
}
#[test]
fn type_identities_are_scoped_by_domain_and_role() {
let mut declarations = source_declarations(0, "type Item { name: Text }\n");
declarations.extend(source_declarations(1, "type Item { count: Int }\n"));
let modules = [module("order", Role::App), module("stock", Role::App)];
let types = Types::resolve(&declarations, &modules).unwrap();
assert_eq!(types.definitions.len(), 3);
assert_eq!(types.definitions[0].name, "dever.collection.app.Error");
assert_eq!(types.definitions[1].name, "shop.order.app.Item");
assert_eq!(types.definitions[2].name, "shop.stock.app.Item");
}
#[test]
fn project_loads_role_topics_once_and_keeps_local_parse_diagnostics() {
use std::{
fs,
sync::atomic::{AtomicUsize, Ordering},
};
static NEXT: AtomicUsize = AtomicUsize::new(0);
struct Directory(std::path::PathBuf);
impl Drop for Directory {
fn drop(&mut self) {
fs::remove_dir_all(&self.0).unwrap();
}
}
let root = std::env::temp_dir().join(format!(
"dever-next-project-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir(&root).unwrap();
let directory = Directory(root);
let domain = directory.0.join("module/shop/order");
fs::create_dir_all(domain.join("app")).unwrap();
fs::create_dir_all(domain.join("domain")).unwrap();
fs::create_dir_all(directory.0.join("module/shop/front/src/main")).unwrap();
fs::write(
domain.join("app/main.dever"),
"start() (x: Int) { x = app.price() }\n",
)
.unwrap();
fs::write(
domain.join("app/price.dever"),
"price() (x: Int) { x = domain.cost() }\n",
)
.unwrap();
fs::write(
domain.join("domain/cost.dever"),
"broken() (x: Int) { x = }\ncost() (x: Int) { x = 1 }\n",
)
.unwrap();
fs::write(
directory.0.join("module/shop/front/src/main/index.dever"),
"this is not language source",
)
.unwrap();
let project = dever::compiler::project::Project::load(&directory.0).unwrap();
assert_eq!(project.sources.len(), 3);
assert_eq!(project.diagnostics.len(), 1);
let graph = calls::bind(&project.declarations, &project.modules).unwrap();
assert_eq!(graph.edges.len(), 2);
assert!(graph.by_name.contains_key("shop.order.app.price"));
assert!(!graph.by_name.contains_key("shop.order.app.price.price"));
fs::write(domain.join("service.dever"), "ignored() () {}").unwrap();
assert!(dever::compiler::project::Project::load(&directory.0).is_err());
}
#[test]
fn declarations_obey_names_and_cannot_redefine_native_types() {
let declarations = source_declarations(0, "type Int { value: Text }\n");
assert!(Types::resolve(&declarations, &[Module::standalone()]).is_err());
let declarations = source_declarations(0, "type Error { Other }\n");
let mut reserved = module("collection", Role::App);
reserved.component = "dever".into();
assert_eq!(
Types::resolve(&declarations, &[reserved])
.err()
.unwrap()
.code,
"C004"
);
let declarations = source_declarations(
0,
"rule raise(value: dever.collection.Error) ()\n| value | do |\n| DuplicateKey | fail(value) |\n",
);
dever::compiler::check::program::check(&declarations, &[module("value", Role::Domain)])
.unwrap();
let declarations = source_declarations(0, "bad_name() (x: Int) { x = 1 }\n");
assert_eq!(
calls::bind(&declarations, &[Module::standalone()])
.err()
.unwrap()
.code,
"C002"
);
let error = conditions("rule f(x: Bool) (y: Int)\n| name | x | y |\n| BadRow | - | 1 |\n")
.err()
.unwrap();
assert_eq!(error.code, "C002");
}
#[test]
fn private_fields_keep_the_same_boundary_for_reads_writes_and_construction() {
for caller in [
"read(value: vault.Session) (out: Text) { out = value.key }",
"write(value: vault.Session) (out: vault.Session) { out = value\nout.key = \"changed\" }",
"make() (out: vault.Session) { out = vault.Session { key = \"hidden\", label = \"name\" } }",
] {
let mut declarations = source_declarations(0, caller);
declarations.extend(source_declarations(
1,
"type Session { private key: Text, label: Text }",
));
let modules = [module("order", Role::App), module("vault", Role::App)];
let error = dever::compiler::check::program::check(&declarations, &modules)
.err()
.unwrap();
assert_eq!(error.code, "C006", "{error}");
assert!(error.message.contains("field is private"));
}
let mut declarations = source_declarations(
0,
"read(value: shop.vault.domain.Item) (out: Int) { out = value.count }",
);
declarations.extend(source_declarations(1, "type Item { count: Int }"));
let error = dever::compiler::check::program::check(
&declarations,
&[module("order", Role::App), module("vault", Role::Domain)],
)
.err()
.unwrap();
assert_eq!(error.code, "C006");
}
#[test]
fn domain_cycles_include_type_only_and_mixed_dependencies() {
for (left, right) in [
(
"type Item { count: Int }\nf(value: right.Item) (out: right.Item) { out = value }",
"type Item { count: Int }\nf(value: left.Item) (out: left.Item) { out = value }",
),
(
"type Item { count: Int }\nf() (out: Int) { out = right.count() }",
"count() (out: Int) { out = left.Item { count = 1 }.count }",
),
] {
let mut declarations = source_declarations(0, left);
declarations.extend(source_declarations(1, right));
let error = dever::compiler::check::program::check(
&declarations,
&[module("left", Role::App), module("right", Role::App)],
)
.err()
.unwrap();
assert_eq!(error.code, "C010", "{error}");
assert!(error.message.contains("domain"));
}
}
#[test]
fn static_callbacks_do_not_invent_domain_cycles_but_keep_role_checks() {
let mut declarations = source_declarations(
0,
"next(state: Int) (out: Walk<Int, Int>) { out = Done }\nstart(value: Int) (out: Int) { out = domain.total(value, next) }",
);
declarations.extend(source_declarations(1,
"loop total(seed: Int, step: handler(state: Int) (out: Walk<Int, Int>)) (out: Int)\n| each value in walk(seed, step) | result |\n| out | sum value |\n"));
let modules = [module("order", Role::App), module("order", Role::Domain)];
let error = dever::compiler::check::program::check(&declarations, &modules)
.err()
.unwrap();
assert_eq!(error.code, "C003", "{error}");
let modules = [module("order", Role::Domain), module("order", Role::Domain)];
dever::compiler::check::program::check(&declarations, &modules).unwrap();
let mut declarations = source_declarations(
0,
"callback(value: Int) (out: Int) { out = value }\nstart(value: Int) (out: Int) { out = utility.apply(value, callback) }",
);
declarations.extend(source_declarations(1,
"apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = forward(value, transform) }\nforward(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }"));
let modules = [module("order", Role::App), module("utility", Role::App)];
dever::compiler::check::program::check(&declarations, &modules).unwrap();
let mut declarations = source_declarations(
0,
"callback(value: Int) (out: Int) { out = value }\nstart(value: Int) (out: Int) { out = domain.apply(value, callback) }",
);
declarations.extend(source_declarations(1,
"apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }"));
let modules = [module("order", Role::App), module("order", Role::Domain)];
let error = dever::compiler::check::program::check(&declarations, &modules)
.err()
.unwrap();
assert_eq!(error.code, "C003", "{error}");
}
#[test]
fn block_rules_report_overlap_and_uncovered_inputs() {
let overlap = conditions(
"rule pick(x:Bool) (out:Int) x { - => 1
true => 2 }",
)
.err()
.unwrap();
assert!(overlap.message.contains("overlap: x = true"));
let missing = conditions("rule pick(x:Bool) (out:Int) x {true => 2}")
.err()
.unwrap();
assert!(missing.message.contains("does not cover: x = false"));
}