Skip to main content

domainforge_core/projection/archimate/
ir.rs

1//! ArchiMate 3.0 architecture IR: a graph-derived, renderer-agnostic model of a
2//! single business-layer architecture, plus its motivation drivers.
3//!
4//! Mapping (declared v1 subset — see `docs/archimate-projections.md`):
5//! - **BusinessRole**    — one per declared role.
6//! - **BusinessObject**  — one per declared entity *and* one per declared
7//!   resource (both are passive business-layer objects).
8//! - **BusinessProcess** — one per declared flow (the activity that moves a
9//!   resource from one entity to another).
10//! - **Requirement**     — one per authority policy (a motivation-layer driver
11//!   the architecture must satisfy).
12//!
13//! Relations are emitted **only** where the static [`ALLOWED_RELATIONS`] table
14//! says the `(source-kind, relation-kind, target-kind)` triple is legal ArchiMate.
15//! [`Relation::build`] consults that table and returns `Err` on any illegal
16//! triple, so the IR *cannot* hold an out-of-spec relation — validation by
17//! construction, the property this projection exists to prove. Emitted relations:
18//! - **Assignment**  BusinessRole → BusinessProcess (a role performs a flow's
19//!   process) when the graph binds the role to the flow's source entity.
20//! - **Access**      BusinessProcess → BusinessObject (a flow's process accesses
21//!   the objects for its source and target entities).
22//! - **Triggering**  BusinessProcess → BusinessProcess (a flow whose target
23//!   entity is another flow's source entity triggers that next flow).
24//! - **Association** Requirement → BusinessObject (a policy is associated with
25//!   every object whose name its condition expression references).
26//!
27//! Every id is minted through [`crate::projection::ids::element_id`] under the
28//! `archimate` family and prefixed with an alpha tag so it is a legal XML
29//! `NCName` / `xsd:ID`. All collections are built and emitted in sorted
30//! (`BTreeMap`/`Vec::sort`) order, so output is byte-identical run-to-run.
31
32use crate::graph::Graph;
33use crate::projection::ids::element_id;
34use std::collections::{BTreeMap, BTreeSet};
35
36/// An ArchiMate element type. The [`ElemKind::archimate_type`] string is the
37/// exact `xsi:type` value the renderer stamps on the `<element>`.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
39pub enum ElemKind {
40    BusinessRole,
41    BusinessObject,
42    BusinessProcess,
43    BusinessService,
44    Requirement,
45}
46
47impl ElemKind {
48    /// The `xsi:type` value (an ArchiMate element type name).
49    pub fn archimate_type(self) -> &'static str {
50        match self {
51            ElemKind::BusinessRole => "BusinessRole",
52            ElemKind::BusinessObject => "BusinessObject",
53            ElemKind::BusinessProcess => "BusinessProcess",
54            ElemKind::BusinessService => "BusinessService",
55            ElemKind::Requirement => "Requirement",
56        }
57    }
58
59    /// Whether this kind belongs to the business layer (motivation elements such
60    /// as [`ElemKind::Requirement`] do not; they are excluded from the
61    /// business-layer view).
62    pub fn is_business_layer(self) -> bool {
63        !matches!(self, ElemKind::Requirement)
64    }
65}
66
67/// An ArchiMate relationship type. The [`RelKind::archimate_type`] string is the
68/// exact `xsi:type` value the renderer stamps on the `<relationship>`.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
70pub enum RelKind {
71    Composition,
72    Aggregation,
73    Assignment,
74    Realization,
75    Serving,
76    Access,
77    Triggering,
78    Flow,
79    Specialization,
80    Association,
81    Influence,
82}
83
84impl RelKind {
85    /// The `xsi:type` value (an ArchiMate relationship type name).
86    pub fn archimate_type(self) -> &'static str {
87        match self {
88            RelKind::Composition => "Composition",
89            RelKind::Aggregation => "Aggregation",
90            RelKind::Assignment => "Assignment",
91            RelKind::Realization => "Realization",
92            RelKind::Serving => "Serving",
93            RelKind::Access => "Access",
94            RelKind::Triggering => "Triggering",
95            RelKind::Flow => "Flow",
96            RelKind::Specialization => "Specialization",
97            RelKind::Association => "Association",
98            RelKind::Influence => "Influence",
99        }
100    }
101}
102
103/// The curated legal `(source-kind, relation-kind, target-kind)` triples for the
104/// element and relation kinds this projection uses. It is a **subset** of the
105/// full ArchiMate 3.1 relationship matrix — only the kinds we mint elements for
106/// appear — but every entry is genuinely spec-legal, and no triple absent from
107/// this table can ever be built (see [`Relation::build`]). Sorted at rest is not
108/// required (lookup is a linear scan), but the table is grouped by relation for
109/// readability.
110pub const ALLOWED_RELATIONS: &[(ElemKind, RelKind, ElemKind)] = &[
111    // Assignment: an active-structure element performs a behavior element.
112    (
113        ElemKind::BusinessRole,
114        RelKind::Assignment,
115        ElemKind::BusinessProcess,
116    ),
117    (
118        ElemKind::BusinessRole,
119        RelKind::Assignment,
120        ElemKind::BusinessService,
121    ),
122    // Access: a behavior element accesses a passive-structure element.
123    (
124        ElemKind::BusinessProcess,
125        RelKind::Access,
126        ElemKind::BusinessObject,
127    ),
128    (
129        ElemKind::BusinessService,
130        RelKind::Access,
131        ElemKind::BusinessObject,
132    ),
133    // Triggering: temporal/causal ordering between behavior elements.
134    (
135        ElemKind::BusinessProcess,
136        RelKind::Triggering,
137        ElemKind::BusinessProcess,
138    ),
139    (
140        ElemKind::BusinessProcess,
141        RelKind::Triggering,
142        ElemKind::BusinessService,
143    ),
144    (
145        ElemKind::BusinessService,
146        RelKind::Triggering,
147        ElemKind::BusinessProcess,
148    ),
149    // Flow: transfer between behavior elements.
150    (
151        ElemKind::BusinessProcess,
152        RelKind::Flow,
153        ElemKind::BusinessProcess,
154    ),
155    // Serving: a behavior element serves an active-structure or behavior element.
156    (
157        ElemKind::BusinessService,
158        RelKind::Serving,
159        ElemKind::BusinessRole,
160    ),
161    (
162        ElemKind::BusinessService,
163        RelKind::Serving,
164        ElemKind::BusinessProcess,
165    ),
166    (
167        ElemKind::BusinessProcess,
168        RelKind::Serving,
169        ElemKind::BusinessRole,
170    ),
171    // Realization: a more concrete element realizes a more abstract one.
172    (
173        ElemKind::BusinessProcess,
174        RelKind::Realization,
175        ElemKind::BusinessService,
176    ),
177    (
178        ElemKind::BusinessProcess,
179        RelKind::Realization,
180        ElemKind::Requirement,
181    ),
182    (
183        ElemKind::BusinessService,
184        RelKind::Realization,
185        ElemKind::Requirement,
186    ),
187    (
188        ElemKind::BusinessObject,
189        RelKind::Realization,
190        ElemKind::Requirement,
191    ),
192    // Association: the universal, weakly-typed relationship.
193    (
194        ElemKind::Requirement,
195        RelKind::Association,
196        ElemKind::BusinessObject,
197    ),
198    (
199        ElemKind::Requirement,
200        RelKind::Association,
201        ElemKind::BusinessProcess,
202    ),
203    (
204        ElemKind::Requirement,
205        RelKind::Association,
206        ElemKind::BusinessRole,
207    ),
208    (
209        ElemKind::BusinessObject,
210        RelKind::Association,
211        ElemKind::BusinessObject,
212    ),
213    // Influence: one motivation element influences another.
214    (
215        ElemKind::Requirement,
216        RelKind::Influence,
217        ElemKind::Requirement,
218    ),
219    // Specialization: same-type generalization.
220    (
221        ElemKind::BusinessRole,
222        RelKind::Specialization,
223        ElemKind::BusinessRole,
224    ),
225    (
226        ElemKind::BusinessObject,
227        RelKind::Specialization,
228        ElemKind::BusinessObject,
229    ),
230    (
231        ElemKind::BusinessProcess,
232        RelKind::Specialization,
233        ElemKind::BusinessProcess,
234    ),
235    (
236        ElemKind::BusinessService,
237        RelKind::Specialization,
238        ElemKind::BusinessService,
239    ),
240    (
241        ElemKind::Requirement,
242        RelKind::Specialization,
243        ElemKind::Requirement,
244    ),
245    // Composition / Aggregation: whole-part between compatible elements.
246    (
247        ElemKind::BusinessObject,
248        RelKind::Composition,
249        ElemKind::BusinessObject,
250    ),
251    (
252        ElemKind::BusinessObject,
253        RelKind::Aggregation,
254        ElemKind::BusinessObject,
255    ),
256    (
257        ElemKind::BusinessProcess,
258        RelKind::Composition,
259        ElemKind::BusinessProcess,
260    ),
261    (
262        ElemKind::Requirement,
263        RelKind::Aggregation,
264        ElemKind::Requirement,
265    ),
266];
267
268/// Whether `(source, rel, target)` is a legal ArchiMate triple per
269/// [`ALLOWED_RELATIONS`].
270pub fn relation_allowed(source: ElemKind, rel: RelKind, target: ElemKind) -> bool {
271    ALLOWED_RELATIONS
272        .iter()
273        .any(|&(s, r, t)| s == source && r == rel && t == target)
274}
275
276/// An ArchiMate element (a node in the model).
277#[derive(Debug, Clone)]
278pub struct Element {
279    pub id: String,
280    pub kind: ElemKind,
281    pub name: String,
282}
283
284/// An ArchiMate relationship (a typed, directed edge). Constructed only through
285/// [`Relation::build`], which rejects any triple absent from [`ALLOWED_RELATIONS`].
286#[derive(Debug, Clone)]
287pub struct Relation {
288    pub id: String,
289    pub source: String,
290    pub target: String,
291    pub kind: RelKind,
292    pub source_kind: ElemKind,
293    pub target_kind: ElemKind,
294}
295
296impl Relation {
297    /// Build a relation, enforcing the ArchiMate relation matrix by construction.
298    /// Returns `Err` (naming the offending triple) when the
299    /// `(source-kind, relation-kind, target-kind)` triple is not in
300    /// [`ALLOWED_RELATIONS`] — the teeth-check the whole projection turns on.
301    pub fn build(
302        id: String,
303        source: String,
304        source_kind: ElemKind,
305        kind: RelKind,
306        target: String,
307        target_kind: ElemKind,
308    ) -> Result<Self, String> {
309        if !relation_allowed(source_kind, kind, target_kind) {
310            return Err(format!(
311                "illegal ArchiMate relation: {} --{}--> {} is not in the allowed-relations matrix",
312                source_kind.archimate_type(),
313                kind.archimate_type(),
314                target_kind.archimate_type()
315            ));
316        }
317        Ok(Relation {
318            id,
319            source,
320            target,
321            kind,
322            source_kind,
323            target_kind,
324        })
325    }
326}
327
328/// A node inside the auto-generated view: it references an [`Element`] and
329/// carries a deterministic grid position (visual layout is index-derived, never
330/// authored, so output stays byte-identical).
331#[derive(Debug, Clone)]
332pub struct ViewNode {
333    pub id: String,
334    pub element_ref: String,
335    pub x: i32,
336    pub y: i32,
337    pub w: i32,
338    pub h: i32,
339}
340
341/// A single ArchiMate view (`xsi:type="Diagram"`) listing element references.
342#[derive(Debug, Clone)]
343pub struct View {
344    pub id: String,
345    pub name: String,
346    pub nodes: Vec<ViewNode>,
347}
348
349/// The complete architecture, ready to render. Every collection is sorted so
350/// output is byte-identical run-to-run.
351#[derive(Debug, Clone)]
352pub struct ArchitectureIR {
353    pub model_id: String,
354    pub model_name: String,
355    pub elements: Vec<Element>,
356    pub relations: Vec<Relation>,
357    pub views: Vec<View>,
358}
359
360const FAMILY: &str = "archimate";
361
362fn id(prefix: &str, parts: &[&str]) -> String {
363    format!("{prefix}_{}", element_id(FAMILY, parts))
364}
365
366/// Split `expr` into identifier tokens (`[A-Za-z0-9_]+` runs) for policy→object
367/// association discovery.
368fn identifier_tokens(expr: &str) -> BTreeSet<String> {
369    let mut out = BTreeSet::new();
370    let mut cur = String::new();
371    for ch in expr.chars() {
372        if ch.is_ascii_alphanumeric() || ch == '_' {
373            cur.push(ch);
374        } else if !cur.is_empty() {
375            out.insert(std::mem::take(&mut cur));
376        }
377    }
378    if !cur.is_empty() {
379        out.insert(cur);
380    }
381    out
382}
383
384impl ArchitectureIR {
385    /// Build the architecture IR from `graph`. `model_ref` is a provenance label
386    /// used for the model display name and its id. Returns `Err` only if a
387    /// relation would violate the ArchiMate matrix — which, by construction of
388    /// this builder, it never does; the fallibility is the guarantee.
389    pub fn from_graph(graph: &Graph, model_ref: &str) -> Result<Self, String> {
390        let model_id = id("Model", &["model", model_ref]);
391
392        // --- Elements -------------------------------------------------------
393        // Roles → BusinessRole.
394        let mut roles: Vec<_> = graph.all_roles();
395        roles.sort_by_key(|r| (r.name().to_string(), r.id().to_string()));
396        let mut role_elem_by_name: BTreeMap<String, String> = BTreeMap::new();
397        let mut elements: Vec<Element> = Vec::new();
398        for r in &roles {
399            let eid = id("Element", &["role", r.namespace(), r.name()]);
400            role_elem_by_name.insert(r.name().to_string(), eid.clone());
401            elements.push(Element {
402                id: eid,
403                kind: ElemKind::BusinessRole,
404                name: r.name().to_string(),
405            });
406        }
407
408        // Entities → BusinessObject. Track element id + ConceptId string so
409        // flows can look up their endpoints.
410        let mut entities: Vec<_> = graph.all_entities();
411        entities.sort_by_key(|e| (e.name().to_string(), e.id().to_string()));
412        // ConceptId string → (element id, entity ConceptId for role lookup).
413        let mut object_by_entity: BTreeMap<String, String> = BTreeMap::new();
414        let mut entity_cid: BTreeMap<String, crate::ConceptId> = BTreeMap::new();
415        for e in &entities {
416            let eid = id("Element", &["entity", e.namespace(), e.name()]);
417            object_by_entity.insert(e.id().to_string(), eid.clone());
418            entity_cid.insert(e.id().to_string(), e.id().clone());
419            elements.push(Element {
420                id: eid,
421                kind: ElemKind::BusinessObject,
422                name: e.name().to_string(),
423            });
424        }
425
426        // Resources → BusinessObject. Named objects for policy association.
427        let mut resources: Vec<_> = graph.all_resources();
428        resources.sort_by_key(|r| (r.name().to_string(), r.id().to_string()));
429        // Object name → element id (entities and resources), for policy tokens.
430        let mut object_by_name: BTreeMap<String, String> = BTreeMap::new();
431        for e in &entities {
432            object_by_name
433                .entry(e.name().to_string())
434                .or_insert_with(|| object_by_entity[&e.id().to_string()].clone());
435        }
436        for r in &resources {
437            let eid = id("Element", &["resource", r.namespace(), r.name()]);
438            object_by_name
439                .entry(r.name().to_string())
440                .or_insert_with(|| eid.clone());
441            elements.push(Element {
442                id: eid,
443                kind: ElemKind::BusinessObject,
444                name: r.name().to_string(),
445            });
446        }
447
448        // Flows → BusinessProcess. Flow ids are random UUIDs, so the process id
449        // is derived from the (deterministic) resource/from/to ConceptIds.
450        // Only flows whose endpoints resolve to known entities are projected.
451        let mut flow_keys: Vec<(String, String, String)> = Vec::new();
452        for f in graph.all_flows() {
453            let from = f.from_id().to_string();
454            let to = f.to_id().to_string();
455            if !object_by_entity.contains_key(&from) || !object_by_entity.contains_key(&to) {
456                continue;
457            }
458            flow_keys.push((from, to, f.resource_id().to_string()));
459        }
460        flow_keys.sort();
461        flow_keys.dedup();
462        // (from, to) → process element id, for triggering chains.
463        let mut process_by_key: BTreeMap<(String, String, String), String> = BTreeMap::new();
464        let mut processes_from_entity: BTreeMap<String, Vec<String>> = BTreeMap::new();
465        for (from, to, res) in &flow_keys {
466            let pid = id("Element", &["process", from, to, res]);
467            let from_name = entities
468                .iter()
469                .find(|e| e.id().to_string() == *from)
470                .map(|e| e.name().to_string())
471                .unwrap_or_default();
472            let to_name = entities
473                .iter()
474                .find(|e| e.id().to_string() == *to)
475                .map(|e| e.name().to_string())
476                .unwrap_or_default();
477            elements.push(Element {
478                id: pid.clone(),
479                kind: ElemKind::BusinessProcess,
480                name: format!("{from_name} to {to_name}"),
481            });
482            process_by_key.insert((from.clone(), to.clone(), res.clone()), pid.clone());
483            processes_from_entity
484                .entry(from.clone())
485                .or_default()
486                .push(pid);
487        }
488
489        // Policies → Requirement.
490        let mut policies: Vec<_> = graph.all_policies();
491        policies.sort_by_key(|p| (p.name.clone(), p.id.to_string()));
492        let mut requirement_of_policy: Vec<(String, String)> = Vec::new(); // (req id, expr)
493        for p in &policies {
494            let rid = id("Element", &["requirement", &p.namespace, &p.name]);
495            elements.push(Element {
496                id: rid.clone(),
497                kind: ElemKind::Requirement,
498                name: p.name.clone(),
499            });
500            requirement_of_policy.push((rid, p.expression().to_string()));
501        }
502
503        // Elements sorted for byte-determinism (kind, then name, then id).
504        elements.sort_by(|a, b| {
505            a.kind
506                .cmp(&b.kind)
507                .then_with(|| a.name.cmp(&b.name))
508                .then_with(|| a.id.cmp(&b.id))
509        });
510
511        // --- Relations (validation by construction) ------------------------
512        // Collected into a map keyed by relation id so duplicates collapse and
513        // ordering is deterministic.
514        let mut relations: BTreeMap<String, Relation> = BTreeMap::new();
515        let mut add = |rid: String,
516                       src: String,
517                       sk: ElemKind,
518                       rk: RelKind,
519                       tgt: String,
520                       tk: ElemKind|
521         -> Result<(), String> {
522            let rel = Relation::build(rid.clone(), src, sk, rk, tgt, tk)?;
523            relations.entry(rid).or_insert(rel);
524            Ok(())
525        };
526
527        for (from, to, res) in &flow_keys {
528            let pid = &process_by_key[&(from.clone(), to.clone(), res.clone())];
529            let from_obj = &object_by_entity[from];
530            let to_obj = &object_by_entity[to];
531            // Access: the process reads/writes the two endpoint objects.
532            add(
533                id("Relation", &["access", pid, from_obj]),
534                pid.clone(),
535                ElemKind::BusinessProcess,
536                RelKind::Access,
537                from_obj.clone(),
538                ElemKind::BusinessObject,
539            )?;
540            add(
541                id("Relation", &["access", pid, to_obj]),
542                pid.clone(),
543                ElemKind::BusinessProcess,
544                RelKind::Access,
545                to_obj.clone(),
546                ElemKind::BusinessObject,
547            )?;
548            // Assignment: roles bound to the source entity perform the process.
549            if let Some(cid) = entity_cid.get(from) {
550                let mut role_names = graph.role_names_for_entity(cid);
551                role_names.sort();
552                for rn in &role_names {
553                    if let Some(role_elem) = role_elem_by_name.get(rn) {
554                        add(
555                            id("Relation", &["assign", role_elem, pid]),
556                            role_elem.clone(),
557                            ElemKind::BusinessRole,
558                            RelKind::Assignment,
559                            pid.clone(),
560                            ElemKind::BusinessProcess,
561                        )?;
562                    }
563                }
564            }
565        }
566
567        // Triggering: a flow whose target entity is another flow's source entity
568        // triggers that next flow's process.
569        for (from, to, res) in &flow_keys {
570            let pid = &process_by_key[&(from.clone(), to.clone(), res.clone())];
571            if let Some(next_processes) = processes_from_entity.get(to) {
572                for next_pid in next_processes {
573                    if next_pid == pid {
574                        continue;
575                    }
576                    add(
577                        id("Relation", &["trigger", pid, next_pid]),
578                        pid.clone(),
579                        ElemKind::BusinessProcess,
580                        RelKind::Triggering,
581                        next_pid.clone(),
582                        ElemKind::BusinessProcess,
583                    )?;
584                }
585            }
586        }
587
588        // Association: a requirement is associated with every object whose name
589        // its condition expression references (token match).
590        for (rid, expr) in &requirement_of_policy {
591            let tokens = identifier_tokens(expr);
592            for (obj_name, obj_id) in &object_by_name {
593                let referenced = tokens.contains(obj_name)
594                    || (obj_name.contains(' ') && expr.contains(obj_name.as_str()));
595                if referenced {
596                    add(
597                        id("Relation", &["assoc", rid, obj_id]),
598                        rid.clone(),
599                        ElemKind::Requirement,
600                        RelKind::Association,
601                        obj_id.clone(),
602                        ElemKind::BusinessObject,
603                    )?;
604                }
605            }
606        }
607
608        let relations: Vec<Relation> = relations.into_values().collect();
609
610        // --- View: one auto-generated business-layer view -------------------
611        // Lists every business-layer element (roles, objects, processes) via a
612        // node with a deterministic grid position. Motivation requirements are a
613        // different layer and are excluded (per-stakeholder views are v2).
614        let business: Vec<&Element> = elements
615            .iter()
616            .filter(|e| e.kind.is_business_layer())
617            .collect();
618        let cols = 5;
619        let (cell_w, cell_h, node_w, node_h) = (185, 100, 160, 80);
620        let nodes: Vec<ViewNode> = business
621            .iter()
622            .enumerate()
623            .map(|(i, e)| {
624                let col = (i % cols) as i32;
625                let row = (i / cols) as i32;
626                ViewNode {
627                    id: id("Node", &["node", &e.id]),
628                    element_ref: e.id.clone(),
629                    x: 12 + col * cell_w,
630                    y: 12 + row * cell_h,
631                    w: node_w,
632                    h: node_h,
633                }
634            })
635            .collect();
636        let views = vec![View {
637            id: id("View", &["view", "business", model_ref]),
638            name: "Business Layer".to_string(),
639            nodes,
640        }];
641
642        Ok(ArchitectureIR {
643            model_id,
644            model_name: model_ref.to_string(),
645            elements,
646            relations,
647            views,
648        })
649    }
650
651    /// Structural reference-integrity check — the teeth-check XSD `xsd:IDREF`
652    /// validation cannot fully perform against minted ids. Verifies every
653    /// relationship endpoint, every view `elementRef`, and asserts every held
654    /// relation is still spec-legal (defence in depth against a hand-mutated IR).
655    /// Returns the first problem found.
656    pub fn validate_references(&self) -> Result<(), String> {
657        let elem_ids: BTreeSet<&str> = self.elements.iter().map(|e| e.id.as_str()).collect();
658        let elem_kind: BTreeMap<&str, ElemKind> = self
659            .elements
660            .iter()
661            .map(|e| (e.id.as_str(), e.kind))
662            .collect();
663
664        for r in &self.relations {
665            if !elem_ids.contains(r.source.as_str()) {
666                return Err(format!(
667                    "relationship {} has source {} with no matching element",
668                    r.id, r.source
669                ));
670            }
671            if !elem_ids.contains(r.target.as_str()) {
672                return Err(format!(
673                    "relationship {} has target {} with no matching element",
674                    r.id, r.target
675                ));
676            }
677            if !relation_allowed(r.source_kind, r.kind, r.target_kind) {
678                return Err(format!(
679                    "relationship {} is an illegal ArchiMate triple: {} --{}--> {}",
680                    r.id,
681                    r.source_kind.archimate_type(),
682                    r.kind.archimate_type(),
683                    r.target_kind.archimate_type()
684                ));
685            }
686            // Endpoint kinds must match the declared source/target kinds.
687            if elem_kind.get(r.source.as_str()) != Some(&r.source_kind) {
688                return Err(format!(
689                    "relationship {} source-kind disagrees with element {}",
690                    r.id, r.source
691                ));
692            }
693            if elem_kind.get(r.target.as_str()) != Some(&r.target_kind) {
694                return Err(format!(
695                    "relationship {} target-kind disagrees with element {}",
696                    r.id, r.target
697                ));
698            }
699        }
700        for v in &self.views {
701            for n in &v.nodes {
702                if !elem_ids.contains(n.element_ref.as_str()) {
703                    return Err(format!(
704                        "view {} node {} references element {} which does not exist",
705                        v.id, n.id, n.element_ref
706                    ));
707                }
708            }
709        }
710        Ok(())
711    }
712}