1use cimmodel::base::{FastMap, FastSet, FieldMap, FieldValue};
13use cimmodel::{CimDataset, Element};
14
15use crate::helpers;
16use crate::par::{par_concat, par_map, runs, threads_for};
17use crate::shapes::{
18 AltBranch, Branch, Check, ClosedShape, Constraint, Logic, LogicOp, NodeKind, Path, PropShape,
19 ShapeDef, Step, Target,
20};
21use crate::{Config, Violation};
22
23#[derive(Default)]
34struct ReverseIndex<'a> {
35 counts: FastMap<(&'a str, &'static str), u32>,
37 sources: FastMap<(&'a str, &'static str), Vec<&'a str>>,
39}
40
41impl<'a> ReverseIndex<'a> {
42 fn count(&self, mrid: &str, field: &'static str) -> u32 {
43 self.counts.get(&(mrid, field)).copied().unwrap_or(0)
44 }
45
46 fn sources<'s>(&'s self, mrid: &'a str, field: &'static str) -> &'s [&'a str] {
47 self.sources.get(&(mrid, field)).map_or(&[], Vec::as_slice)
48 }
49}
50
51struct Ctx<'a> {
53 ds: &'a CimDataset,
54 set: &'a [CimDataset],
57 source: Source,
58 reverse: ReverseIndex<'a>,
59}
60
61#[derive(Clone, Copy, PartialEq, Eq)]
63enum Kind {
64 Text,
65 Refs,
66}
67
68enum Values<'a> {
70 Text(&'a [String]),
73 Refs(&'a [String]),
75 Count(u32),
77 Absent,
78 Chain(Kind, Vec<&'a str>),
81 Unknown,
84}
85
86impl<'a> Values<'a> {
87 fn count(&self) -> Option<u32> {
89 Some(match self {
90 Values::Text(v) | Values::Refs(v) => v.len() as u32,
91 Values::Count(n) => *n,
92 Values::Absent => 0,
93 Values::Chain(_, v) => v.len() as u32,
94 Values::Unknown => return None,
95 })
96 }
97
98 fn any_text(&self, mut f: impl FnMut(&str) -> bool) -> bool {
100 match self {
101 Values::Text(vs) => vs.iter().any(|v| f(v)),
102 Values::Chain(Kind::Text, vs) => vs.iter().any(|v| f(v)),
103 _ => false,
104 }
105 }
106
107 fn any_ref(&self, mut f: impl FnMut(&str) -> bool) -> bool {
109 match self {
110 Values::Refs(vs) => vs.iter().any(|v| f(v)),
111 Values::Chain(Kind::Refs, vs) => vs.iter().any(|v| f(v)),
112 _ => false,
113 }
114 }
115
116 fn is_text(&self) -> bool {
117 matches!(self, Values::Text(_) | Values::Chain(Kind::Text, _))
118 }
119
120 fn is_refs(&self) -> bool {
121 matches!(self, Values::Refs(_) | Values::Chain(Kind::Refs, _))
122 }
123}
124
125type Fields = FieldMap;
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub enum Source {
136 Nc,
138 Cgmes,
140}
141
142impl Source {
143 fn fields(self, entry: &Element) -> Option<&Fields> {
145 self.owns(entry).then(|| entry.fields())
146 }
147
148 fn owns(self, entry: &Element) -> bool {
151 entry.type_name().starts_with("nc:") == (self == Source::Nc)
152 }
153}
154
155fn refs_of<'a>(f: &'a Fields, field: &str) -> &'a [String] {
156 match f.get(field) {
157 Some(FieldValue::Resource(s)) => std::slice::from_ref(s),
158 Some(FieldValue::ResourceList(v)) => v.as_slice(),
159 _ => &[],
160 }
161}
162
163fn field_values<'a>(f: &'a Fields, field: &str) -> Values<'a> {
164 match f.get(field) {
165 Some(FieldValue::Text(s)) => Values::Text(std::slice::from_ref(s)),
166 Some(FieldValue::TextList(v)) => Values::Text(v.as_slice()),
167 Some(FieldValue::Resource(_)) | Some(FieldValue::ResourceList(_)) => {
168 Values::Refs(refs_of(f, field))
169 }
170 None => Values::Absent,
171 }
172}
173
174fn number(v: &str) -> Option<f64> {
177 v.trim().parse::<f64>().ok()
178}
179
180fn resolve<'a>(ctx: &Ctx<'a>, el: &'a Fields, mrid: &'a str, path: &Path) -> Values<'a> {
181 match path {
182 Path::Forward(field) => field_values(el, field),
183 Path::Chain([Step::Forward(field), Step::Type]) => field_values(el, field),
186 Path::Inverse(field) => Values::Count(ctx.reverse.count(mrid, field)),
187 Path::Alternative(branches) => {
188 let mut total = 0;
192 for b in *branches {
193 total += match b {
194 AltBranch::Forward(field) => field_values(el, field).count().unwrap_or(0),
195 AltBranch::Inverse(field) => ctx.reverse.count(mrid, field),
196 };
197 }
198 Values::Count(total)
199 }
200 Path::Chain(steps) => chain(ctx, el, mrid, steps),
201 }
202}
203
204fn chain<'a>(ctx: &Ctx<'a>, focus: &'a Fields, mrid: &'a str, steps: &[Step]) -> Values<'a> {
213 let mut nodes: Vec<&'a str> = vec![mrid];
214 for (i, step) in steps.iter().enumerate() {
215 let last = i + 1 == steps.len();
216 match step {
217 Step::Forward(field) => {
218 let mut next: Vec<&'a str> = Vec::new();
219 let mut texts: Vec<&'a str> = Vec::new();
220 for &node in &nodes {
221 let fields = if node == mrid {
222 focus
223 } else {
224 match ctx.ds.entries.get(node).and_then(|e| ctx.source.fields(e)) {
225 Some(f) => f,
226 None => return Values::Unknown,
227 }
228 };
229 match fields.get(*field) {
230 Some(FieldValue::Text(s)) => texts.push(s),
231 Some(FieldValue::TextList(v)) => texts.extend(v.iter().map(String::as_str)),
232 Some(FieldValue::Resource(r)) => next.push(r),
233 Some(FieldValue::ResourceList(v)) => {
234 next.extend(v.iter().map(String::as_str))
235 }
236 None => {}
237 }
238 }
239 let before_type = matches!(steps.get(i + 1), Some(Step::Type));
242 if (last || before_type) && !texts.is_empty() {
243 return Values::Chain(Kind::Text, texts);
244 }
245 if last {
246 return Values::Chain(Kind::Refs, next);
247 }
248 nodes = next;
249 }
250 Step::Inverse(field) => {
251 let next: Vec<&'a str> = nodes
252 .iter()
253 .flat_map(|n| ctx.reverse.sources(n, field).iter().copied())
254 .collect();
255 if last {
256 return Values::Chain(Kind::Refs, next);
257 }
258 nodes = next;
259 }
260 Step::Type => return Values::Chain(Kind::Refs, nodes),
264 }
265 }
266 Values::Chain(Kind::Refs, nodes)
267}
268
269fn datatype_ok(s: &str, xsd: &str) -> bool {
274 let t = s.trim();
275 match xsd {
276 "string" | "normalizedString" | "token" | "Name" | "NCName" | "language" => true,
277 "boolean" => matches!(t, "true" | "false" | "1" | "0"),
278 "integer" | "int" | "long" | "short" | "byte" | "nonPositiveInteger"
279 | "negativeInteger" => t.parse::<i64>().is_ok(),
280 "nonNegativeInteger" | "positiveInteger" | "unsignedInt" | "unsignedLong"
281 | "unsignedShort" | "unsignedByte" => t.parse::<u64>().is_ok(),
282 "decimal" | "float" | "double" => t.parse::<f64>().is_ok(),
283 "dateTime" | "dateTimeStamp" => helpers::is_xsd_datetime(t),
284 "date" => helpers::is_xsd_date(t),
285 "gMonthDay" => helpers::is_xsd_gmonthday(t),
286 "anyURI" => helpers::is_xsd_anyuri(t),
287 _ => true,
289 }
290}
291
292fn violation(mrid: &str, class: &str, property: &str, c: &Check) -> Violation {
293 Violation {
294 object_id: mrid.to_string(),
295 rule_id: c.rule_id.to_string(),
296 class: class.to_string(),
297 property: property.to_string(),
298 message: c.message.to_string(),
299 severity: c.severity.to_string(),
300 name: c.name.to_string(),
301 description: c.description.to_string(),
302 }
303}
304
305fn path_label(path: &Path) -> std::borrow::Cow<'static, str> {
308 use std::borrow::Cow;
309 let inverse = |f: &str| Cow::Owned(format!("^{f}"));
312 match path {
313 Path::Forward(f) => Cow::Borrowed(f),
314 Path::Inverse(f) => inverse(f),
315 Path::Alternative(branches) => match branches.first() {
316 Some(AltBranch::Forward(f)) => Cow::Borrowed(f),
317 Some(AltBranch::Inverse(f)) => inverse(f),
318 None => Cow::Borrowed(""),
319 },
320 Path::Chain(steps) => match steps.first() {
321 Some(Step::Forward(f)) => Cow::Borrowed(f),
322 Some(Step::Inverse(f)) => inverse(f),
323 _ => Cow::Borrowed(""),
324 },
325 }
326}
327
328fn any_type(
349 ctx: &Ctx<'_>,
350 mrid: &str,
351 test: impl Fn(&cimmodel::base::ClassDef) -> bool,
352) -> Option<bool> {
353 if let Some(e) = ctx.ds.entries.get(mrid) {
354 return Some(e.types().any(test));
355 }
356 if ctx.source != Source::Nc {
357 return None;
358 }
359 let mut held = false;
360 for e in ctx.set.iter().filter_map(|d| d.entries.get(mrid)) {
361 held = true;
362 if e.types().any(&test) {
363 return Some(true);
364 }
365 }
366 held.then_some(false)
367}
368
369fn fails(ctx: &Ctx<'_>, el: &Fields, values: &Values<'_>, constraint: &Constraint) -> bool {
371 if matches!(values, Values::Unknown) {
372 return false;
373 }
374 match constraint {
375 Constraint::MinCount(n) => values.count().is_some_and(|c| c < *n),
376 Constraint::MaxCount(n) => values.count().is_some_and(|c| c > *n),
377
378 Constraint::Datatype(xsd) => values.any_text(|v| !datatype_ok(v, xsd)),
382
383 Constraint::NodeKind(kind) => match kind {
386 NodeKind::Literal => values.is_refs() && values.count() != Some(0),
387 NodeKind::Iri => values.is_text() && values.count() != Some(0),
388 NodeKind::BlankNode => values.is_text() && values.count() != Some(0),
391 },
392
393 Constraint::In(allowed) => {
394 values.any_text(|v| !allowed.contains(&v.trim()))
395 || values.any_ref(|r| !allowed.contains(&r))
396 }
397 Constraint::HasValue(want) => match values {
398 v if v.is_text() => !v.any_text(|t| t.trim() == *want),
399 v if v.is_refs() => !v.any_ref(|r| r == *want),
400 _ => false,
401 },
402
403 Constraint::MaxLength(n) => values.any_text(|v| v.chars().count() as u32 > *n),
404 Constraint::MinLength(n) => values.any_text(|v| (v.chars().count() as u32) < *n),
405 Constraint::Length(n) => values.any_text(|v| v.chars().count() as u32 != *n),
406
407 Constraint::Class(allowed) => {
412 values.any_ref(|r| any_type(ctx, r, |t| allowed.contains(&t.qualified)) == Some(false))
413 }
414 Constraint::RefClass(allowed) => {
415 values.any_ref(|r| any_type(ctx, r, |t| !allowed.contains(&t.qualified)) == Some(true))
416 }
417 Constraint::NotClass(forbidden) => {
418 values.any_ref(|r| any_type(ctx, r, |t| forbidden.contains(&t.qualified)) == Some(true))
419 }
420 Constraint::QualifiedIn { allowed, min } => {
421 let mut n = 0u32;
422 values.any_text(|v| {
423 n += u32::from(allowed.contains(&v.trim()));
424 false
425 });
426 values.any_ref(|r| {
427 n += u32::from(allowed.contains(&r));
428 false
429 });
430 n < *min
431 }
432
433 Constraint::MinInclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x < *b)),
434 Constraint::MaxInclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x > *b)),
435 Constraint::MinExclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x <= *b)),
436 Constraint::MaxExclusive(b) => values.any_text(|v| number(v).is_some_and(|x| x >= *b)),
437
438 Constraint::LessThan(other) => pair(values, el, other, |a, b| a < b),
441 Constraint::LessThanOrEquals(other) => pair(values, el, other, |a, b| a <= b),
442 }
443}
444
445const MRID: &str = "IdentifiedObject.mRID";
447
448fn mrid_exempt(t: &Resolved<'_>, prop: &PropShape) -> bool {
458 t.described && prop.path == Path::Forward(MRID)
459}
460
461fn check_prop<'a>(
462 ctx: &Ctx<'a>,
463 el: &'a Fields,
464 class: &str,
465 mrid: &'a str,
466 prop: &PropShape,
467 no_min: bool,
468 out: &mut Vec<Violation>,
469) {
470 let values = resolve(ctx, el, mrid, &prop.path);
471 for c in prop.checks {
472 if no_min && matches!(c.constraint, Constraint::MinCount(_)) {
473 continue;
474 }
475 if fails(ctx, el, &values, &c.constraint) {
476 out.push(violation(mrid, class, &path_label(&prop.path), c));
477 }
478 }
479}
480
481fn branch_conforms<'a>(
484 ctx: &Ctx<'a>,
485 el: &'a Fields,
486 mrid: &'a str,
487 branch: &Branch,
488) -> Option<bool> {
489 let mut holds = true;
490 for prop in branch.props {
491 let values = resolve(ctx, el, mrid, &prop.path);
492 if matches!(values, Values::Unknown) {
493 return None;
494 }
495 if prop
496 .checks
497 .iter()
498 .any(|c| fails(ctx, el, &values, &c.constraint))
499 {
500 holds = false;
501 break;
502 }
503 }
504 Some(holds != branch.negate)
505}
506
507fn check_logic<'a>(
510 ctx: &Ctx<'a>,
511 el: &'a Fields,
512 class: &str,
513 mrid: &'a str,
514 logic: &Logic,
515 out: &mut Vec<Violation>,
516) {
517 let mut conforming = 0usize;
518 for branch in logic.branches {
519 match branch_conforms(ctx, el, mrid, branch) {
520 Some(true) => conforming += 1,
521 Some(false) => {}
522 None => return,
524 }
525 }
526 let holds = match logic.op {
527 LogicOp::And => conforming == logic.branches.len(),
528 LogicOp::Or => conforming >= 1,
529 LogicOp::Xone => conforming == 1,
530 };
531 if !holds {
532 out.push(Violation {
533 object_id: mrid.to_string(),
534 rule_id: logic.rule_id.to_string(),
535 class: class.to_string(),
536 property: logic.name.to_string(),
537 message: logic.message.to_string(),
538 severity: logic.severity.to_string(),
539 name: logic.name.to_string(),
540 description: logic.description.to_string(),
541 });
542 }
543}
544
545fn pair(values: &Values, el: &Fields, other: &str, holds: impl Fn(f64, f64) -> bool) -> bool {
547 let others = field_values(el, other);
548 values.any_text(|a| {
549 number(a).is_some_and(|a| others.any_text(|b| number(b).is_some_and(|b| !holds(a, b))))
550 })
551}
552
553fn check_closed(
555 el: &Fields,
556 class: &str,
557 mrid: &str,
558 closed: &ClosedShape,
559 out: &mut Vec<Violation>,
560) {
561 let mut extra: Vec<&str> = el
562 .keys()
563 .copied()
564 .filter(|k| !closed.allowed.contains(k))
565 .collect();
566 extra.sort_unstable();
569
570 for field in extra {
571 out.push(Violation {
572 object_id: mrid.to_string(),
573 rule_id: closed.rule_id.to_string(),
574 class: class.to_string(),
575 property: field.to_string(),
576 message: closed.message.to_string(),
577 severity: closed.severity.to_string(),
578 name: closed.name.to_string(),
579 description: closed.description.to_string(),
580 });
581 }
582}
583
584#[derive(Clone, Copy)]
588struct Resolved<'a> {
589 mrid: &'a String,
590 class: &'static str,
591 fields: &'a Fields,
592 described: bool,
593}
594
595impl<'a> Resolved<'a> {
596 fn new(source: Source, mrid: &'a String, entry: &'a Element, fields: &'a Fields) -> Self {
597 let described = source == Source::Cgmes && !entry.defined();
598 Resolved {
599 mrid,
600 class: entry.type_name(),
601 fields,
602 described,
603 }
604 }
605}
606
607fn resolve_target<'a>(
611 ds: &'a CimDataset,
612 source: Source,
613 mrid: &'a String,
614) -> Option<Resolved<'a>> {
615 let entry = ds.entries.get(mrid)?;
616 let fields = source.fields(entry)?;
617 Some(Resolved::new(source, mrid, entry, fields))
618}
619
620fn build_indexes<'a>(
631 ds: &'a CimDataset,
632 source: Source,
633 count_fields: &[&'static str],
634 list_fields: &[&'static str],
635 subject_fields: &[&'static str],
636) -> (ReverseIndex<'a>, FastMap<&'static str, Vec<Resolved<'a>>>) {
637 if count_fields.is_empty() && list_fields.is_empty() && subject_fields.is_empty() {
638 return (ReverseIndex::default(), FastMap::default());
639 }
640 type Partial<'a> = (ReverseIndex<'a>, FastMap<&'static str, Vec<Resolved<'a>>>);
641 let index = |entries: &mut dyn Iterator<Item = (&'a String, &'a Element)>| -> Partial<'a> {
642 let mut reverse = ReverseIndex::default();
643 let mut subjects: FastMap<&'static str, Vec<Resolved<'a>>> =
644 subject_fields.iter().map(|f| (*f, Vec::new())).collect();
645 for (mrid, entry) in entries {
646 let Some(f) = source.fields(entry) else {
647 continue;
648 };
649 for field in count_fields {
650 for target in refs_of(f, field) {
651 *reverse.counts.entry((target.as_str(), *field)).or_insert(0) += 1;
652 }
653 }
654 for field in list_fields {
655 for target in refs_of(f, field) {
656 reverse
657 .sources
658 .entry((target.as_str(), *field))
659 .or_default()
660 .push(mrid);
661 }
662 }
663 for field in subject_fields {
664 if f.contains_key(*field) {
665 let r = Resolved::new(source, mrid, entry, f);
666 subjects.get_mut(field).expect("seeded above").push(r);
667 }
668 }
669 }
670 (reverse, subjects)
671 };
672
673 let threads = threads_for(ds.entries.len());
674 if threads == 1 {
675 return index(&mut ds.entries.iter());
676 }
677 let all: Vec<(&'a String, &'a Element)> = ds.entries.iter().collect();
681 let parts: Vec<Partial<'a>> = par_map(&runs(&all, threads, |_| 1), |run| {
682 index(&mut run.iter().copied())
683 });
684 let mut parts = parts.into_iter();
685 let (mut reverse, mut subjects) = parts.next().expect("at least one run");
686 for (r, subj) in parts {
687 for (k, n) in r.counts {
688 *reverse.counts.entry(k).or_insert(0) += n;
689 }
690 for (k, list) in r.sources {
691 reverse.sources.entry(k).or_default().extend(list);
692 }
693 for (field, list) in subj {
694 subjects.get_mut(field).expect("seeded above").extend(list);
695 }
696 }
697 (reverse, subjects)
698}
699
700fn targets_of<'a>(
708 ds: &'a CimDataset,
709 source: Source,
710 shape: &ShapeDef,
711 subjects: &FastMap<&'static str, Vec<Resolved<'a>>>,
712 by_class: &mut FastMap<&'static str, Vec<Resolved<'a>>>,
713) -> Vec<Resolved<'a>> {
714 let mut out: Vec<Resolved<'a>> = Vec::new();
715 for target in shape.targets {
716 match target {
717 Target::Class(classes) => {
718 for class in *classes {
719 let list = by_class.entry(class).or_insert_with(|| {
720 ds.by_type
721 .get(*class)
722 .into_iter()
723 .flatten()
724 .filter_map(|mrid| resolve_target(ds, source, mrid))
725 .collect()
726 });
727 out.extend_from_slice(list);
728 }
729 }
730 Target::SubjectsOf(field) => {
731 out.extend_from_slice(subjects.get(field).map_or(&[], Vec::as_slice));
732 }
733 }
734 }
735 let mut seen = FastSet::default();
739 out.retain(|t| seen.insert(t.mrid));
740 out
741}
742
743fn run_shape<'a>(ctx: &Ctx<'a>, shape: &ShapeDef, t: &Resolved<'a>, out: &mut Vec<Violation>) {
745 for prop in shape.props {
746 check_prop(
747 ctx,
748 t.fields,
749 t.class,
750 t.mrid,
751 prop,
752 mrid_exempt(t, prop),
753 out,
754 );
755 }
756 for logic in shape.logic {
757 check_logic(ctx, t.fields, t.class, t.mrid, logic, out);
758 }
759 if let Some(closed) = shape.closed {
760 check_closed(t.fields, t.class, t.mrid, closed, out);
761 }
762}
763
764pub fn validate_profile(
770 ds: &CimDataset,
771 profile: &str,
772 shapes: &'static [ShapeDef],
773 cfg: &Config,
774) -> Vec<Violation> {
775 validate_profile_in(ds, &[], profile, shapes, cfg)
776}
777
778pub fn validate_profile_in(
781 ds: &CimDataset,
782 set: &[CimDataset],
783 profile: &str,
784 shapes: &'static [ShapeDef],
785 _cfg: &Config,
786) -> Vec<Violation> {
787 let active: Vec<&ShapeDef> = shapes
788 .iter()
789 .filter(|s| s.profiles.contains(&profile))
790 .collect();
791 validate_shapes_in(ds, set, Source::Nc, &active)
792}
793
794const SLICE: usize = 2048;
796
797pub fn validate_shapes(ds: &CimDataset, source: Source, active: &[&ShapeDef]) -> Vec<Violation> {
806 validate_shapes_in(ds, &[], source, active)
807}
808
809pub fn validate_shapes_in(
814 ds: &CimDataset,
815 set: &[CimDataset],
816 source: Source,
817 active: &[&ShapeDef],
818) -> Vec<Violation> {
819 if active.is_empty() {
820 return Vec::new();
821 }
822
823 let mut count_fields: Vec<&'static str> = Vec::new();
826 let mut list_fields: Vec<&'static str> = Vec::new();
827 let paths = active.iter().flat_map(|s| {
828 s.props
829 .iter()
830 .map(|p| &p.path)
831 .chain(s.logic.iter().flat_map(|l| {
832 l.branches
833 .iter()
834 .flat_map(|b| b.props.iter().map(|p| &p.path))
835 }))
836 });
837 for path in paths {
838 match path {
839 Path::Inverse(f) => count_fields.push(f),
840 Path::Alternative(branches) => {
841 count_fields.extend(branches.iter().filter_map(|b| match b {
842 AltBranch::Inverse(f) => Some(*f),
843 AltBranch::Forward(_) => None,
844 }))
845 }
846 Path::Chain(steps) => list_fields.extend(steps.iter().filter_map(|s| match s {
847 Step::Inverse(f) => Some(*f),
848 _ => None,
849 })),
850 Path::Forward(_) => {}
851 }
852 }
853 count_fields.sort_unstable();
854 count_fields.dedup();
855 list_fields.sort_unstable();
856 list_fields.dedup();
857
858 let mut subject_fields: Vec<&'static str> = active
859 .iter()
860 .flat_map(|s| s.targets.iter())
861 .filter_map(|t| match t {
862 Target::SubjectsOf(f) => Some(*f),
863 Target::Class(_) => None,
864 })
865 .collect();
866 subject_fields.sort_unstable();
867 subject_fields.dedup();
868
869 let (reverse, subjects) =
870 build_indexes(ds, source, &count_fields, &list_fields, &subject_fields);
871 let ctx = Ctx {
872 ds,
873 set,
874 source,
875 reverse,
876 };
877
878 let mut by_class_shapes: FastMap<&'static str, Vec<&ShapeDef>> = FastMap::default();
889 let mut by_subject_shapes: FastMap<&'static str, Vec<&ShapeDef>> = FastMap::default();
890 let mut mixed: Vec<&ShapeDef> = Vec::new();
891 for shape in active {
892 let all_class = shape.targets.iter().all(|t| matches!(t, Target::Class(_)));
893 match shape.targets {
894 _ if all_class => {
895 let mut classes: Vec<&'static str> = shape
896 .targets
897 .iter()
898 .flat_map(|t| match t {
899 Target::Class(cs) => cs.iter().copied(),
900 Target::SubjectsOf(_) => [].iter().copied(),
901 })
902 .collect();
903 classes.sort_unstable();
904 classes.dedup();
905 for class in classes {
906 by_class_shapes.entry(class).or_default().push(shape);
907 }
908 }
909 [Target::SubjectsOf(field)] => by_subject_shapes.entry(field).or_default().push(shape),
910 _ => mixed.push(shape),
911 }
912 }
913
914 let work: Vec<(&[&ShapeDef], &[String])> = by_class_shapes
921 .iter()
922 .flat_map(|(class, shapes)| {
923 ds.by_type
924 .get(*class)
925 .map_or(&[][..], Vec::as_slice)
926 .chunks(SLICE)
927 .map(move |mrids| (shapes.as_slice(), mrids))
928 })
929 .collect();
930 let total: usize = work.iter().map(|(_, m)| m.len()).sum();
931 let mut out = par_concat(
932 &runs(&work, threads_for(total), |(_, m)| m.len()),
933 |items| {
934 let mut out = Vec::new();
935 for (shapes, mrids) in items {
936 for t in mrids
937 .iter()
938 .filter_map(|mrid| resolve_target(ds, source, mrid))
939 {
940 for shape in *shapes {
941 run_shape(&ctx, shape, &t, &mut out);
942 }
943 }
944 }
945 out
946 },
947 );
948
949 let work: Vec<(&[&ShapeDef], &[Resolved])> = by_subject_shapes
951 .iter()
952 .flat_map(|(field, shapes)| {
953 subjects
954 .get(field)
955 .map_or(&[][..], Vec::as_slice)
956 .chunks(SLICE)
957 .map(move |targets| (shapes.as_slice(), targets))
958 })
959 .collect();
960 let total: usize = work.iter().map(|(_, t)| t.len()).sum();
961 out.extend(par_concat(
962 &runs(&work, threads_for(total), |(_, t)| t.len()),
963 |items| {
964 let mut out = Vec::new();
965 for (shapes, targets) in items {
966 for t in *targets {
967 for shape in *shapes {
968 run_shape(&ctx, shape, t, &mut out);
969 }
970 }
971 }
972 out
973 },
974 ));
975 let mut by_class: FastMap<&'static str, Vec<Resolved>> = FastMap::default();
976 for shape in mixed {
977 for t in targets_of(ds, source, shape, &subjects, &mut by_class) {
978 run_shape(&ctx, shape, &t, &mut out);
979 }
980 }
981
982 let mut seen = FastSet::default();
987 let keep: Vec<bool> = out
988 .iter()
989 .map(|v| {
990 seen.insert((
991 v.object_id.as_str(),
992 v.rule_id.as_str(),
993 v.property.as_str(),
994 v.message.as_str(),
995 ))
996 })
997 .collect();
998 drop(seen);
999 let mut keep = keep.into_iter();
1000 out.retain(|_| keep.next().unwrap_or(true));
1001 out
1002}