ifc_validate/express/
rules.rs1use std::collections::BTreeSet;
4use std::sync::Arc;
5
6use ifc_schema::Schema;
7
8use super::coverage::{self, Coverage};
9use super::error::ExpressError;
10use super::options::EvalLimits;
11use super::resolve::{self, Globals};
12use super::tables::Tables;
13
14#[derive(Clone)]
36pub struct ExpressRules {
37 pub(crate) tables: Arc<Tables>,
38 pub(crate) limits: EvalLimits,
39 ids: Arc<BTreeSet<String>>,
40}
41
42impl std::fmt::Debug for ExpressRules {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 f.debug_struct("ExpressRules")
45 .field("schema", &self.schema_name())
46 .field("rules", &self.ids.len())
47 .field("limits", &self.limits)
48 .finish()
49 }
50}
51
52impl ExpressRules {
53 pub fn parse(source: &str, schema: &Schema) -> Result<Self, ExpressError> {
60 let mut decl = super::parse::schema(source)?;
61 if !decl.name.eq_ignore_ascii_case(schema.name()) {
62 return Err(ExpressError::SchemaMismatch {
63 source: decl.name.to_string(),
64 tables: schema.name().to_owned(),
65 });
66 }
67 let globals = Globals::new(&decl);
68 resolve::schema(&mut decl, &globals)?;
69 let tables = Tables::new(decl, globals, schema)?;
70 let mut ids = BTreeSet::new();
71 for entity in &tables.schema.entities {
72 for rule in &entity.rules {
73 ids.insert(format!("{}.{}", entity.spelling, rule.label));
74 }
75 }
76 for decl in &tables.schema.types {
77 for rule in &decl.rules {
78 ids.insert(format!("{}.{}", decl.spelling, rule.label));
79 }
80 }
81 for rule in &tables.schema.rules {
82 ids.insert(format!("global.{}", rule.spelling));
83 }
84 Ok(Self {
85 tables: Arc::new(tables),
86 limits: EvalLimits::DEFAULT,
87 ids: Arc::new(ids),
88 })
89 }
90
91 pub fn parse_bytes(bytes: &[u8], schema: &Schema) -> Result<Self, ExpressError> {
101 let text: String = bytes.iter().map(|&byte| char::from(byte)).collect();
102 Self::parse(&text, schema)
103 }
104
105 #[must_use]
107 pub fn with_limits(mut self, limits: EvalLimits) -> Self {
108 self.limits = limits;
109 self
110 }
111
112 #[must_use]
114 pub fn limits(&self) -> EvalLimits {
115 self.limits
116 }
117
118 #[must_use]
120 pub fn schema_name(&self) -> &str {
121 &self.tables.schema.name
122 }
123
124 pub fn rule_ids(&self) -> impl Iterator<Item = &str> {
128 self.ids.iter().map(String::as_str)
129 }
130
131 #[must_use]
134 pub fn covers(&self, id: &str) -> bool {
135 self.ids.contains(id) || self.ids.contains(&format!("global.{id}"))
136 }
137
138 #[must_use]
141 pub fn coverage(&self) -> Coverage {
142 coverage::measure(&self.tables)
143 }
144}
145
146#[cfg(test)]
147mod tests {
148 use super::ExpressRules;
149
150 #[test]
151 fn rules_can_be_shared_between_threads() {
152 fn shared<T: Send + Sync>() {}
153 shared::<ExpressRules>();
154 }
155}