1use crate::graph::Graph;
33use crate::projection::ids::element_id;
34use std::collections::{BTreeMap, BTreeSet};
35
36#[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 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 pub fn is_business_layer(self) -> bool {
63 !matches!(self, ElemKind::Requirement)
64 }
65}
66
67#[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 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
103pub const ALLOWED_RELATIONS: &[(ElemKind, RelKind, ElemKind)] = &[
111 (
113 ElemKind::BusinessRole,
114 RelKind::Assignment,
115 ElemKind::BusinessProcess,
116 ),
117 (
118 ElemKind::BusinessRole,
119 RelKind::Assignment,
120 ElemKind::BusinessService,
121 ),
122 (
124 ElemKind::BusinessProcess,
125 RelKind::Access,
126 ElemKind::BusinessObject,
127 ),
128 (
129 ElemKind::BusinessService,
130 RelKind::Access,
131 ElemKind::BusinessObject,
132 ),
133 (
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 (
151 ElemKind::BusinessProcess,
152 RelKind::Flow,
153 ElemKind::BusinessProcess,
154 ),
155 (
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 (
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 (
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 (
215 ElemKind::Requirement,
216 RelKind::Influence,
217 ElemKind::Requirement,
218 ),
219 (
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 (
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
268pub 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#[derive(Debug, Clone)]
278pub struct Element {
279 pub id: String,
280 pub kind: ElemKind,
281 pub name: String,
282}
283
284#[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 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#[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#[derive(Debug, Clone)]
343pub struct View {
344 pub id: String,
345 pub name: String,
346 pub nodes: Vec<ViewNode>,
347}
348
349#[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
366fn 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 pub fn from_graph(graph: &Graph, model_ref: &str) -> Result<Self, String> {
390 let model_id = id("Model", &["model", model_ref]);
391
392 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 let mut entities: Vec<_> = graph.all_entities();
411 entities.sort_by_key(|e| (e.name().to_string(), e.id().to_string()));
412 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 let mut resources: Vec<_> = graph.all_resources();
428 resources.sort_by_key(|r| (r.name().to_string(), r.id().to_string()));
429 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 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 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 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(); 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.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 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 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 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 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 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 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 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 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}