303 lines
9.5 KiB
Rust
303 lines
9.5 KiB
Rust
//! 规则条件解析后执行有界互斥穷尽证明;结果表达式另由共享表达式检查器处理。
|
|
|
|
mod partition;
|
|
mod proof;
|
|
|
|
use super::types::{self, Types};
|
|
use crate::compiler::model::{self, Condition, Pattern, Shape, Type, numeric::Number};
|
|
use crate::syntax::names::{self, Style};
|
|
use crate::syntax::{ast, diagnostic::Diagnostic, source::Span};
|
|
use model::InputFact as Fact;
|
|
use std::collections::HashSet;
|
|
|
|
pub const PROOF_BUDGET: usize = 1_000_000;
|
|
|
|
/// loop 只需本格匹配后的事实,不要求各输出行互斥或穷尽。
|
|
pub(super) fn filter_fact(
|
|
input: &model::Field,
|
|
condition: &Condition,
|
|
types: &Types,
|
|
) -> Result<Fact, Diagnostic> {
|
|
let cells = partition::cells(input, &[condition], types);
|
|
if cells.len().saturating_mul(condition.alternatives.len()) > PROOF_BUDGET {
|
|
return Err(Diagnostic::new(
|
|
"C009",
|
|
"loop filter proof budget exceeded",
|
|
condition.span,
|
|
));
|
|
}
|
|
cells
|
|
.iter()
|
|
.filter(|cell| {
|
|
condition
|
|
.alternatives
|
|
.iter()
|
|
.any(|pattern| partition::matches(pattern, cell))
|
|
})
|
|
.map(|cell| partition::fact(cell, input))
|
|
.reduce(partition::union)
|
|
.ok_or_else(|| {
|
|
Diagnostic::new(
|
|
"C009",
|
|
"loop filter is outside its input domain",
|
|
condition.span,
|
|
)
|
|
})
|
|
}
|
|
|
|
pub struct RuleConditions {
|
|
pub inputs: Vec<model::Field>,
|
|
pub rows: Vec<Vec<Condition>>,
|
|
pub work: usize,
|
|
pub facts: Vec<Vec<Fact>>,
|
|
}
|
|
|
|
pub fn resolve(
|
|
function: &ast::Function,
|
|
rule: &ast::Rule,
|
|
types: &Types,
|
|
) -> Result<RuleConditions, Diagnostic> {
|
|
let inputs = types.inputs(&function.inputs)?;
|
|
let outputs = types.fields(&function.outputs)?;
|
|
let named = rule.rows[0].name.is_some();
|
|
let mut expected = inputs
|
|
.iter()
|
|
.chain(&outputs)
|
|
.map(|field| field.name.as_str())
|
|
.collect::<Vec<_>>();
|
|
if outputs.is_empty() {
|
|
expected.push("do");
|
|
}
|
|
if named {
|
|
expected.insert(0, "name");
|
|
}
|
|
if rule.header.iter().map(|cell| cell.0.as_str()).ne(expected) {
|
|
return Err(Diagnostic::new(
|
|
"C009",
|
|
"rule header must name inputs and outputs in signature order",
|
|
function.span,
|
|
));
|
|
}
|
|
resolve_rows(inputs, rule, outputs.is_empty(), types, function.span)
|
|
}
|
|
|
|
pub(super) fn resolve_rows(
|
|
inputs: Vec<model::Field>,
|
|
rule: &ast::Rule,
|
|
action: bool,
|
|
types: &Types,
|
|
span: Span,
|
|
) -> Result<RuleConditions, Diagnostic> {
|
|
let mut row_names = HashSet::new();
|
|
let mut rows = Vec::new();
|
|
for row in &rule.rows {
|
|
if let Some((name, span)) = &row.name {
|
|
names::validate(name, Style::Value, *span)?;
|
|
}
|
|
if let Some((name, span)) = &row.name
|
|
&& !row_names.insert(name)
|
|
{
|
|
return Err(Diagnostic::new("C009", "duplicate rule row name", *span));
|
|
}
|
|
let mut bindings = inputs
|
|
.iter()
|
|
.map(|field| field.name.clone())
|
|
.collect::<HashSet<_>>();
|
|
let conditions = row
|
|
.conditions
|
|
.iter()
|
|
.zip(&inputs)
|
|
.map(|(condition, input)| {
|
|
resolve_condition(condition, &input.kind, types, &mut bindings)
|
|
})
|
|
.collect::<Result<Vec<_>, Diagnostic>>()?;
|
|
let failed = row.results[0].as_ref().is_some_and(|expression| matches!(&expression.kind, ast::ExpressionKind::Call(target, _) if target.path().as_deref() == Some("fail")));
|
|
if failed {
|
|
if row.results.iter().skip(1).any(Option::is_some) {
|
|
return Err(Diagnostic::new(
|
|
"C009",
|
|
"a failed row must discard all later outputs",
|
|
row.span,
|
|
));
|
|
}
|
|
} else if row.results.iter().any(Option::is_none) {
|
|
return Err(Diagnostic::new(
|
|
"C009",
|
|
"a successful row must provide every output",
|
|
row.span,
|
|
));
|
|
}
|
|
if action
|
|
&& !matches!(
|
|
&row.results[0].as_ref().unwrap().kind,
|
|
ast::ExpressionKind::Call(..)
|
|
)
|
|
{
|
|
return Err(Diagnostic::new(
|
|
"C009",
|
|
"a rule action must be one call",
|
|
row.span,
|
|
));
|
|
}
|
|
rows.push(conditions);
|
|
}
|
|
let (work, facts) = proof::prove(&inputs, &rows, types, span)?;
|
|
Ok(RuleConditions {
|
|
inputs,
|
|
rows,
|
|
work,
|
|
facts,
|
|
})
|
|
}
|
|
|
|
pub(super) fn resolve_condition(
|
|
condition: &ast::Condition,
|
|
kind: &Type,
|
|
types: &Types,
|
|
bindings: &mut HashSet<String>,
|
|
) -> Result<Condition, Diagnostic> {
|
|
let alternatives = condition
|
|
.alternatives
|
|
.iter()
|
|
.map(|pattern| resolve_pattern(pattern, kind, types, condition.span))
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
let mut payload = None;
|
|
for pattern in &alternatives {
|
|
let names = match pattern {
|
|
Pattern::Variant(index, names) => {
|
|
let Type::Named(kind) = present(kind) else {
|
|
unreachable!()
|
|
};
|
|
let Shape::Choice(variants) = &types.definitions[*kind].shape else {
|
|
unreachable!()
|
|
};
|
|
names
|
|
.iter()
|
|
.zip(&variants[*index].fields)
|
|
.map(|(name, field)| (name.clone(), field.kind.clone()))
|
|
.collect::<Vec<_>>()
|
|
}
|
|
_ => Vec::new(),
|
|
};
|
|
if payload.as_ref().is_some_and(|previous| *previous != names) {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"alternatives must bind the same names and types",
|
|
condition.span,
|
|
));
|
|
}
|
|
payload = Some(names);
|
|
}
|
|
for (name, _) in payload.expect("parsed condition has alternatives") {
|
|
names::validate(&name, Style::Value, condition.span)?;
|
|
if !bindings.insert(name) {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"rule payload binding shadows an existing name",
|
|
condition.span,
|
|
));
|
|
}
|
|
}
|
|
Ok(Condition {
|
|
alternatives,
|
|
span: condition.span,
|
|
})
|
|
}
|
|
|
|
fn present(kind: &Type) -> &Type {
|
|
if let Type::Optional(inner) = kind {
|
|
inner
|
|
} else {
|
|
kind
|
|
}
|
|
}
|
|
|
|
pub(super) fn resolve_pattern(
|
|
pattern: &ast::Pattern,
|
|
kind: &Type,
|
|
types: &Types,
|
|
span: Span,
|
|
) -> Result<Pattern, Diagnostic> {
|
|
let scalar = present(kind);
|
|
let pattern = match pattern {
|
|
ast::Pattern::Any => Pattern::Any,
|
|
ast::Pattern::Other => Pattern::Other,
|
|
ast::Pattern::Literal(ast::Literal::Null) if matches!(kind, Type::Optional(_)) => {
|
|
Pattern::Null
|
|
}
|
|
ast::Pattern::Literal(ast::Literal::Bool(value)) if *scalar == Type::Bool => {
|
|
Pattern::Bool(*value)
|
|
}
|
|
ast::Pattern::Literal(ast::Literal::Text(value)) if *scalar == Type::Text => {
|
|
Pattern::Text(value.clone())
|
|
}
|
|
ast::Pattern::Literal(ast::Literal::Number(value))
|
|
if matches!(scalar, Type::Int | Type::Decimal) =>
|
|
{
|
|
Pattern::Number(
|
|
Number::parse(value, scalar)
|
|
.map_err(|message| Diagnostic::new("C008", message, span))?,
|
|
)
|
|
}
|
|
ast::Pattern::Range(bounds) => Pattern::Range(types::range(scalar, bounds, span)?),
|
|
ast::Pattern::Variant(name, bindings) => {
|
|
let Type::Named(index) = scalar else {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"variant condition requires a choice",
|
|
span,
|
|
));
|
|
};
|
|
let definition = &types.definitions[*index];
|
|
let Shape::Choice(variants) = &definition.shape else {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"records cannot be variant conditions",
|
|
span,
|
|
));
|
|
};
|
|
let index = variants
|
|
.iter()
|
|
.position(|variant| {
|
|
*name == variant.name
|
|
|| *name
|
|
== format!(
|
|
"{}.{}",
|
|
definition.name.rsplit('.').next().unwrap(),
|
|
variant.name
|
|
)
|
|
})
|
|
.ok_or_else(|| Diagnostic::new("C004", "unknown choice variant", span))?;
|
|
if bindings.len() != variants[index].fields.len() {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"variant payload binding count differs",
|
|
span,
|
|
));
|
|
}
|
|
Pattern::Variant(index, bindings.clone())
|
|
}
|
|
_ => {
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"condition does not match its input type",
|
|
span,
|
|
));
|
|
}
|
|
};
|
|
if matches!(pattern, Pattern::Other)
|
|
&& !matches!(kind, Type::Optional(_))
|
|
&& !matches!(
|
|
scalar,
|
|
Type::Bool | Type::Int | Type::Decimal | Type::Text | Type::Named(_)
|
|
)
|
|
{
|
|
return Err(Diagnostic::new(
|
|
"C005",
|
|
"this input only supports an unconstrained condition",
|
|
span,
|
|
));
|
|
}
|
|
Ok(pattern)
|
|
}
|