Skip to content

Commit 9a11ae4

Browse files
feat: policy table output type (#481)
1 parent 68708fa commit 9a11ae4

11 files changed

Lines changed: 539 additions & 42 deletions

File tree

‎core/engine/src/policy/blocks/context.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ pub struct ExecutionError {
5656
pub source: IsolateError,
5757
}
5858

59+
pub type SharedDictionaryTypes = Rc<ahash::HashMap<Arc<str>, VariableType>>;
60+
5961
pub struct AnalysisContext {
6062
scope: VariableType,
6163
policy_path: Arc<str>,
@@ -65,6 +67,7 @@ pub struct AnalysisContext {
6567
diagnostics: Vec<Diagnostic>,
6668
pass: AnalysisPass,
6769
intellisense: SharedIntelliSense,
70+
dictionary_types: SharedDictionaryTypes,
6871
}
6972

7073
impl AnalysisContext {
@@ -74,6 +77,7 @@ impl AnalysisContext {
7477
block_id: Arc<str>,
7578
intellisense: SharedIntelliSense,
7679
pass: AnalysisPass,
80+
dictionary_types: SharedDictionaryTypes,
7781
) -> Self {
7882
Self {
7983
scope,
@@ -84,13 +88,18 @@ impl AnalysisContext {
8488
diagnostics: Vec::new(),
8589
pass,
8690
intellisense,
91+
dictionary_types,
8792
}
8893
}
8994

9095
pub(super) fn scope(&self) -> &VariableType {
9196
&self.scope
9297
}
9398

99+
pub(super) fn dictionary_types(&self) -> &ahash::HashMap<Arc<str>, VariableType> {
100+
&self.dictionary_types
101+
}
102+
94103
pub fn analyze_standard(
95104
&mut self,
96105
source: &Arc<str>,

‎core/engine/src/policy/blocks/decision_table.rs‎

Lines changed: 187 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,80 @@ pub struct OutputColumn {
228228
pub field: Arc<str>,
229229
pub raw_field: Arc<str>,
230230
pub collect: bool,
231+
pub declared: Option<DeclaredType>,
232+
}
233+
234+
#[derive(Debug, Clone, PartialEq, Eq)]
235+
pub enum DeclaredBase {
236+
String,
237+
Number,
238+
Bool,
239+
Date,
240+
Dictionary(Arc<str>),
241+
}
242+
243+
#[derive(Debug, Clone, PartialEq, Eq)]
244+
pub struct DeclaredType {
245+
pub base: DeclaredBase,
246+
pub array: bool,
247+
}
248+
249+
impl DeclaredType {
250+
pub(crate) fn parse(raw: &str) -> Result<Option<DeclaredType>, String> {
251+
let raw = raw.trim();
252+
if raw.is_empty() {
253+
return Ok(None);
254+
}
255+
let (base_raw, array) = match raw.strip_suffix("[]") {
256+
Some(base) => (base.trim_end(), true),
257+
None => (raw, false),
258+
};
259+
let base = match base_raw {
260+
"string" => DeclaredBase::String,
261+
"number" => DeclaredBase::Number,
262+
"boolean" => DeclaredBase::Bool,
263+
"date" => DeclaredBase::Date,
264+
other => {
265+
if crate::policy::ir::DataModelIr::validate_identifier(other).is_err() {
266+
return Err(format!(
267+
"invalid output type '{raw}': expected string, number, boolean, date or a dictionary name, optionally suffixed with []"
268+
));
269+
}
270+
DeclaredBase::Dictionary(Arc::from(other))
271+
}
272+
};
273+
Ok(Some(DeclaredType { base, array }))
274+
}
275+
276+
pub(crate) fn resolve(
277+
&self,
278+
dictionaries: &HashMap<Arc<str>, VariableType>,
279+
) -> Option<VariableType> {
280+
let base = match &self.base {
281+
DeclaredBase::String => VariableType::String,
282+
DeclaredBase::Number => VariableType::Number,
283+
DeclaredBase::Bool => VariableType::Bool,
284+
DeclaredBase::Date => VariableType::Date,
285+
DeclaredBase::Dictionary(name) => dictionaries.get(name)?.shallow_clone(),
286+
};
287+
Some(if self.array { base.array() } else { base })
288+
}
289+
}
290+
291+
impl std::fmt::Display for DeclaredType {
292+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
293+
match &self.base {
294+
DeclaredBase::String => write!(f, "string")?,
295+
DeclaredBase::Number => write!(f, "number")?,
296+
DeclaredBase::Bool => write!(f, "boolean")?,
297+
DeclaredBase::Date => write!(f, "date")?,
298+
DeclaredBase::Dictionary(name) => write!(f, "{name}")?,
299+
}
300+
if self.array {
301+
write!(f, "[]")?;
302+
}
303+
Ok(())
304+
}
231305
}
232306

233307
impl DecisionTableIr {
@@ -315,11 +389,28 @@ impl DecisionTableIr {
315389
Arc::from(path)
316390
};
317391

392+
let declared = match DeclaredType::parse(col.column_type.as_deref().unwrap_or("")) {
393+
Ok(declared) => declared,
394+
Err(message) => {
395+
cx.target_error(
396+
&col.id,
397+
CursorTarget::DecisionTableHead {
398+
col: col.id.clone(),
399+
},
400+
None,
401+
DiagnosticCode::TypeMismatch,
402+
message,
403+
);
404+
None
405+
}
406+
};
407+
318408
OutputColumn {
319409
id: col.id.clone(),
320410
field,
321411
raw_field,
322412
collect,
413+
declared,
323414
}
324415
}
325416

@@ -424,29 +515,66 @@ impl DecisionTableIr {
424515
continue;
425516
}
426517

518+
let declared = (cx.is_enriched())
519+
.then(|| self.resolve_declared(col, cx))
520+
.flatten();
521+
427522
let mut cell_types: Vec<VariableType> = Vec::new();
428523
for rule in &self.rules {
429524
let Some(cell) = rule.get(&col.id).filter(|c| !c.is_empty()) else {
430525
continue;
431526
};
432527
let analysis = cx.analyze_standard(cell, Some(col.id.clone()));
433-
cell_types.push(analysis.return_type.clone());
434-
}
435-
436-
if !col.collect && cx.is_enriched() && !self.column_covered(col, cx, &input_field_types)
437-
{
438-
cell_types.push(VariableType::Null);
528+
match &declared {
529+
Some(expected) => {
530+
let actual = &analysis.return_type;
531+
if !actual.is_null() && !actual.satisfies(expected) {
532+
let target =
533+
rule.get(ROW_ID_KEY)
534+
.map(|row| CursorTarget::DecisionTableCell {
535+
row: row.clone(),
536+
col: col.id.clone(),
537+
});
538+
cx.error_with_target(
539+
DiagnosticCode::TypeMismatch,
540+
Some(col.id.clone()),
541+
None,
542+
target,
543+
format!("output cell must be `{expected}`, got `{actual}`"),
544+
);
545+
}
546+
}
547+
None => cell_types.push(analysis.return_type.clone()),
548+
}
439549
}
440550

551+
let covered = col.collect
552+
|| !cx.is_enriched()
553+
|| self.column_covered(col, cx, &input_field_types);
441554
let target = Some(CursorTarget::DecisionTableHead {
442555
col: col.id.clone(),
443556
});
444-
let mut resolved = cx.merge_types(
445-
&cell_types,
446-
&col.field,
447-
Some(col.id.clone()),
448-
target.clone(),
449-
);
557+
558+
let mut resolved = match declared {
559+
Some(expected) => {
560+
if covered {
561+
expected
562+
} else {
563+
VariableType::Nullable(std::rc::Rc::new(expected))
564+
}
565+
}
566+
None => {
567+
if !covered {
568+
cell_types.push(VariableType::Null);
569+
}
570+
cx.merge_types(
571+
&cell_types,
572+
&col.field,
573+
Some(col.id.clone()),
574+
target.clone(),
575+
)
576+
}
577+
};
450578

451579
if col.collect {
452580
resolved = resolved.array();
@@ -456,6 +584,29 @@ impl DecisionTableIr {
456584
}
457585
}
458586

587+
fn resolve_declared(
588+
&self,
589+
col: &OutputColumn,
590+
cx: &mut AnalysisContext,
591+
) -> Option<VariableType> {
592+
let declared = col.declared.as_ref()?;
593+
let resolved = declared.resolve(cx.dictionary_types());
594+
if resolved.is_none() {
595+
cx.error_with_target(
596+
DiagnosticCode::TypeMismatch,
597+
Some(col.id.clone()),
598+
None,
599+
Some(CursorTarget::DecisionTableHead {
600+
col: col.id.clone(),
601+
}),
602+
format!(
603+
"unknown output type '{declared}': no dictionary with that name is in scope"
604+
),
605+
);
606+
}
607+
resolved
608+
}
609+
459610
fn column_covered(
460611
&self,
461612
col: &OutputColumn,
@@ -778,6 +929,7 @@ impl DecisionTableIr {
778929
block_id: &Arc<str>,
779930
scope: &VariableType,
780931
is: &mut IntelliSense,
932+
dictionaries: &HashMap<Arc<str>, VariableType>,
781933
) -> Vec<NlExpression> {
782934
let mut out = Vec::new();
783935
let mut input_scopes: HashMap<Arc<str>, (ExpressionKind, VariableType)> =
@@ -836,7 +988,8 @@ impl DecisionTableIr {
836988
}
837989
for col in &self.outputs {
838990
let cell: &str = rule.get(&col.id).map(|c| c.as_ref()).unwrap_or("");
839-
out.push(NlExpression::project(
991+
let expected = col.declared.as_ref().and_then(|d| d.resolve(dictionaries));
992+
out.push(NlExpression::project_expected(
840993
is,
841994
policy_path,
842995
block_id,
@@ -847,6 +1000,7 @@ impl DecisionTableIr {
8471000
ExpressionKind::Standard,
8481001
cell,
8491002
scope,
1003+
expected.as_ref(),
8501004
));
8511005
}
8521006
}
@@ -859,19 +1013,29 @@ impl DecisionTableIr {
8591013
cursor: &Cursor,
8601014
scope: VariableType,
8611015
is: &mut IntelliSense,
862-
) -> (ExpressionKind, VariableType) {
1016+
dictionaries: &HashMap<Arc<str>, VariableType>,
1017+
) -> (ExpressionKind, VariableType, Option<VariableType>) {
8631018
let CursorTarget::DecisionTableCell { col, .. } = &cursor.target else {
864-
return (ExpressionKind::Standard, scope);
1019+
return (ExpressionKind::Standard, scope, None);
8651020
};
866-
let Some(ColumnRef::Input(column)) = self.column_by_id(col) else {
867-
return (ExpressionKind::Standard, scope);
868-
};
869-
match column.field.as_ref().filter(|f| !f.is_empty()) {
870-
Some(field) => {
871-
let field_type = is.analyze(field.as_ref(), &scope).return_type.clone();
872-
(ExpressionKind::Unary, scope.with_dollar(&field_type))
1021+
match self.column_by_id(col) {
1022+
Some(ColumnRef::Input(column)) => {
1023+
match column.field.as_ref().filter(|f| !f.is_empty()) {
1024+
Some(field) => {
1025+
let field_type = is.analyze(field.as_ref(), &scope).return_type.clone();
1026+
(ExpressionKind::Unary, scope.with_dollar(&field_type), None)
1027+
}
1028+
None => (ExpressionKind::Standard, scope, None),
1029+
}
1030+
}
1031+
Some(ColumnRef::Output(column)) => {
1032+
let expected = column
1033+
.declared
1034+
.as_ref()
1035+
.and_then(|d| d.resolve(dictionaries));
1036+
(ExpressionKind::Standard, scope, expected)
8731037
}
874-
None => (ExpressionKind::Standard, scope),
1038+
None => (ExpressionKind::Standard, scope, None),
8751039
}
8761040
}
8771041

‎core/engine/src/policy/blocks/mod.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub use assertion::{AssertionDoc, AssertionIr};
2929
pub(crate) use context::IntelliSenseSource;
3030
pub use context::{
3131
AnalysisContext, AnalysisSummary, ExecutionContext, ExecutionError, ExpressionLocation,
32-
InstanceSource, PropertyRead, SharedIntelliSense, WriteTarget,
32+
InstanceSource, PropertyRead, SharedDictionaryTypes, SharedIntelliSense, WriteTarget,
3333
};
3434
pub(crate) use decision_table::TableSelection;
3535
pub use decision_table::{DecisionTableDoc, DecisionTableIr};
@@ -237,19 +237,21 @@ impl Block {
237237
policy_path: &Arc<str>,
238238
scope: &VariableType,
239239
is: &mut IntelliSense,
240+
dictionaries: &HashMap<Arc<str>, VariableType>,
240241
) -> Vec<NlExpression> {
241-
self.kind.nl(policy_path, &self.id, scope, is)
242+
self.kind.nl(policy_path, &self.id, scope, is, dictionaries)
242243
}
243244

244245
pub fn nl_scope(
245246
&self,
246247
cursor: &Cursor,
247248
scope: VariableType,
248249
is: &mut IntelliSense,
249-
) -> (ExpressionKind, VariableType) {
250+
dictionaries: &HashMap<Arc<str>, VariableType>,
251+
) -> (ExpressionKind, VariableType, Option<VariableType>) {
250252
match &self.kind {
251-
BlockKind::DecisionTable(d) => d.nl_scope(cursor, scope, is),
252-
_ => (ExpressionKind::Standard, scope),
253+
BlockKind::DecisionTable(d) => d.nl_scope(cursor, scope, is, dictionaries),
254+
_ => (ExpressionKind::Standard, scope, None),
253255
}
254256
}
255257
}
@@ -347,10 +349,11 @@ impl BlockKind {
347349
block_id: &Arc<str>,
348350
scope: &VariableType,
349351
is: &mut IntelliSense,
352+
dictionaries: &HashMap<Arc<str>, VariableType>,
350353
) -> Vec<NlExpression> {
351354
match self {
352355
BlockKind::Assertion(a) => a.nl(policy_path, block_id, scope, is),
353-
BlockKind::DecisionTable(d) => d.nl(policy_path, block_id, scope, is),
356+
BlockKind::DecisionTable(d) => d.nl(policy_path, block_id, scope, is, dictionaries),
354357
BlockKind::Expression(e) => e.nl(policy_path, block_id, scope, is),
355358
BlockKind::Match(m) => m.nl(policy_path, block_id, scope, is),
356359
}

0 commit comments

Comments
 (0)