asbuilt-core 0.3.1

Language-agnostic architecture model, LikeC4 emitter, config and drift check for asbuilt
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! The architecture model every front-end produces and the emitter
//! consumes.
//!
//! Ids are segment lists (`["playwright_rs", "server", "connection"]`),
//! which LikeC4 renders as `playwright_rs.server.connection`. The model
//! keeps real names; mapping them to LikeC4 identifiers happens in the
//! emitter, and [`Model::validate`] is what says two names would
//! collide there.

use std::collections::BTreeMap;

use crate::error::{Error, Result};

/// A fully qualified element id: crate, then module path.
pub type Id = Vec<String>;

/// What a front-end found, plus the externals the config adds.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Model {
    pub elements: Vec<Element>,
    pub relations: Vec<Relation>,
    pub deployment: Deployment,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Element {
    pub id: Id,
    pub kind: ElementKind,
    pub title: String,
    /// The first paragraph of the module's own docs, markdown kept.
    pub description: Option<String>,
    /// `library crate`, `binary crate`, `test crate` and the rest of the
    /// front-end's labels, or whatever the config says for an external.
    pub technology: Option<String>,
    /// Relative to the surveyed root, `/`-separated on every platform.
    /// `None` for an external.
    pub path: Option<String>,
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ElementKind {
    /// A crate or package.
    Container,
    /// A module.
    Component,
    /// A binary's root beside a crate's lib: an entry point, not a module
    /// of the lib. Also tagged `bin`.
    Bin,
    /// A crate's integration tests and benches, as one element. Also
    /// tagged `tests`.
    Tests,
    /// A crate's examples, as one element. Also tagged `examples`.
    Examples,
    /// Something outside the code, from `[[externals]]`; carries the
    /// LikeC4 element kind name (`process`, `browser`, ...).
    External(String),
}

/// The kinds the survey generates. An external may not declare one of
/// their names: it would be themed and read as the thing it is not.
pub const SURVEY_KINDS: [ElementKind; 5] = [
    ElementKind::Container,
    ElementKind::Component,
    ElementKind::Bin,
    ElementKind::Tests,
    ElementKind::Examples,
];

impl ElementKind {
    /// The element kind declared in the LikeC4 specification: a
    /// [`SURVEY_KINDS`] name, or an external's own kind name. `[theme]`
    /// keys are these.
    pub fn keyword(&self) -> &str {
        match self {
            ElementKind::Container => "container",
            ElementKind::Component => "component",
            ElementKind::Bin => "bin",
            ElementKind::Tests => "tests",
            ElementKind::Examples => "examples",
            ElementKind::External(name) => name,
        }
    }
}

/// Evidence for a relation, strongest first. Aggregation keeps the
/// minimum, so the declared order is the precedence and must not be
/// reordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RelationKind {
    Implements,
    Constructs,
    Calls,
    NamesType,
    Uses,
}

impl RelationKind {
    /// The relationship kind declared in the LikeC4 specification.
    pub fn keyword(self) -> &'static str {
        match self {
            RelationKind::Implements => "implements",
            RelationKind::Constructs => "constructs",
            RelationKind::Calls => "calls",
            RelationKind::NamesType => "names",
            RelationKind::Uses => "uses",
        }
    }

    /// The line LikeC4 draws it with: solid for the strong evidence (it
    /// implements, constructs or calls), dotted for the weak (it names a
    /// type, or uses). An edge that merges relations of several kinds
    /// keeps their line when they share one and is dashed (LikeC4's
    /// default) when they do not.
    pub(crate) fn line(self) -> &'static str {
        match self {
            RelationKind::Implements | RelationKind::Constructs | RelationKind::Calls => "solid",
            RelationKind::NamesType | RelationKind::Uses => "dotted",
        }
    }

    /// The arrowhead, one per kind, so kinds that share a line still
    /// differ: a hollow triangle for implements (UML's for realizing an
    /// interface), a filled diamond at the constructed end for constructs,
    /// a chevron for calls, a filled dot for names, a hollow dot for uses.
    /// No kind takes the filled triangle (`normal`, LikeC4's default
    /// head): LikeC4 gives it to an edge merging relations of several
    /// kinds, so it marks one whatever the line.
    pub(crate) fn head(self) -> &'static str {
        match self {
            RelationKind::Implements => "onormal",
            RelationKind::Constructs => "diamond",
            RelationKind::Calls => "vee",
            RelationKind::NamesType => "dot",
            RelationKind::Uses => "odot",
        }
    }

    /// Every kind, in precedence order; the emitter declares them all.
    pub const ALL: [RelationKind; 5] = [
        RelationKind::Implements,
        RelationKind::Constructs,
        RelationKind::Calls,
        RelationKind::NamesType,
        RelationKind::Uses,
    ];
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relation {
    pub source: Id,
    pub target: Id,
    pub kind: RelationKind,
    /// The referenced item names, sorted and deduplicated; the label.
    pub items: Vec<String>,
    /// Externals only, from the config.
    pub technology: Option<String>,
}

/// Deployment nodes and instances. Empty until an infrastructure
/// front-end exists; it is here from day one because LikeC4 keeps a
/// separate deployment model and retrofitting it would rework every
/// front-end.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Deployment {
    pub nodes: Vec<DeploymentNode>,
    pub instances: Vec<DeploymentInstance>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeploymentNode {
    pub id: Id,
    pub kind: String,
    pub title: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeploymentInstance {
    pub id: Id,
    /// The model element deployed on the node this instance sits in.
    pub element: Id,
}

/// Whether one id is an ancestor of, a descendant of, or equal to the
/// other. `mod x;` and `pub use x::Y` are structure, not coupling, so a
/// relation between lineal elements is never recorded.
pub fn is_lineal(a: &[String], b: &[String]) -> bool {
    a.starts_with(b) || b.starts_with(a)
}

/// An id as LikeC4 renders it, before sanitizing: segments joined by `.`.
pub fn dotted(id: &[String]) -> String {
    id.join(".")
}

/// The likec4 release whose grammar [`RESERVED`] was derived from. The
/// CLI's tests hold it equal to the release they pin, so a bump fails
/// until the list is re-derived: diff the keyword tokens of
/// `packages/language-server/src/*.langium` between the two tags, probe
/// any new word by validating a model that uses it as a nested element,
/// then move this.
pub const RESERVED_GRAMMAR_VERSION: &str = "1.59.4";

/// Words likec4 refuses as an element id: every keyword token of the
/// grammar at [`RESERVED_GRAMMAR_VERSION`] (extracted from the language
/// server bundle) plus `this`, `it`, `true` and `false`, each confirmed
/// by validating a model with the word as a nested element. `model`, `element`, `deployment` and
/// `relationship` are accepted and so are not here. A module named one
/// of these gets a trailing `_`.
pub const RESERVED: &[&str] = &[
    "BottomTop",
    "LeftRight",
    "RightLeft",
    "TopBottom",
    "and",
    "autoLayout",
    "border",
    "color",
    "deploymentNode",
    "description",
    "dynamic",
    "dynamicPredicateGroup",
    "exclude",
    "extend",
    "extends",
    "false",
    "from",
    "global",
    "head",
    "icon",
    "iconColor",
    "iconPosition",
    "iconSize",
    "icons",
    "import",
    "include",
    "includeAncestors",
    "instanceOf",
    "is",
    "it",
    "kind",
    "likec4lib",
    "line",
    "link",
    "metadata",
    "multiple",
    "navigateTo",
    "not",
    "notation",
    "notes",
    "of",
    "opacity",
    "or",
    "order",
    "padding",
    "predicate",
    "predicateGroup",
    "rank",
    "rgb",
    "rgba",
    "shape",
    "size",
    "specification",
    "style",
    "styleGroup",
    "summary",
    "tag",
    "tail",
    "technology",
    "textSize",
    "this",
    "title",
    "true",
    "variant",
    "view",
    "views",
    "where",
    "with",
];

/// One segment as a LikeC4 identifier: `-` and any other character
/// outside `[A-Za-z0-9_]` become `_`, a leading digit gets a `_` in
/// front of it, and a [`RESERVED`] word gets one after it.
pub fn sanitize_segment(segment: &str) -> String {
    let mut out = String::with_capacity(segment.len() + 1);
    if segment.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        out.push('_');
    }
    for c in segment.chars() {
        out.push(if c.is_ascii_alphanumeric() || c == '_' {
            c
        } else {
            '_'
        });
    }
    if RESERVED.contains(&out.as_str()) {
        out.push('_');
    }
    out
}

/// The whole id as a LikeC4 identifier path.
pub fn sanitize_id(id: &[String]) -> String {
    id.iter()
        .map(|s| sanitize_segment(s))
        .collect::<Vec<_>>()
        .join(".")
}

impl Model {
    /// Sort elements by id, merge relations on `(source, target)`
    /// (strongest kind, union of items, first technology), and sort
    /// them. Every path to the emitter goes through here, so output
    /// order never depends on discovery order.
    pub fn normalize(&mut self) {
        self.elements.sort_by(|a, b| a.id.cmp(&b.id));

        let mut merged: BTreeMap<(Id, Id), Relation> = BTreeMap::new();
        for rel in self.relations.drain(..) {
            let key = (rel.source.clone(), rel.target.clone());
            match merged.get_mut(&key) {
                None => {
                    merged.insert(key, rel);
                }
                Some(existing) => {
                    existing.kind = existing.kind.min(rel.kind);
                    existing.items.extend(rel.items);
                    if existing.technology.is_none() {
                        existing.technology = rel.technology;
                    }
                }
            }
        }
        self.relations = merged
            .into_values()
            .map(|mut rel| {
                rel.items.sort();
                rel.items.dedup();
                rel
            })
            .collect();
    }

    /// Append another front-end's model and normalize.
    pub fn merge(&mut self, other: Model) {
        self.elements.extend(other.elements);
        self.relations.extend(other.relations);
        self.deployment.nodes.extend(other.deployment.nodes);
        self.deployment.instances.extend(other.deployment.instances);
        self.normalize();
    }

    /// Fail if two elements have the same id, or two ids that become the
    /// same LikeC4 identifier.
    pub fn validate(&self) -> Result<()> {
        let mut seen: BTreeMap<String, &Id> = BTreeMap::new();
        for element in &self.elements {
            let key = sanitize_id(&element.id);
            if let Some(first) = seen.insert(key.clone(), &element.id) {
                return Err(Error::DuplicateId {
                    id: key,
                    first: dotted(first),
                    second: dotted(&element.id),
                });
            }
        }
        Ok(())
    }

    pub fn element(&self, id: &[String]) -> Option<&Element> {
        self.elements.iter().find(|e| e.id == id)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn id(s: &str) -> Id {
        s.split('.').map(str::to_string).collect()
    }

    fn element(s: &str) -> Element {
        Element {
            id: id(s),
            kind: ElementKind::Component,
            title: s.rsplit('.').next().unwrap().to_string(),
            description: None,
            technology: None,
            path: None,
            tags: vec![],
        }
    }

    fn relation(source: &str, target: &str, kind: RelationKind, items: &[&str]) -> Relation {
        Relation {
            source: id(source),
            target: id(target),
            kind,
            items: items.iter().map(|s| s.to_string()).collect(),
            technology: None,
        }
    }

    #[test]
    fn precedence_is_the_declared_order_strongest_first() {
        assert!(RelationKind::Implements < RelationKind::Constructs);
        assert!(RelationKind::Constructs < RelationKind::Calls);
        assert!(RelationKind::Calls < RelationKind::NamesType);
        assert!(RelationKind::NamesType < RelationKind::Uses);
    }

    #[test]
    fn the_surveyed_kinds_are_every_kind_but_external_in_specification_order() {
        assert_eq!(
            SURVEY_KINDS.map(|kind| kind.keyword().to_string()),
            ["container", "component", "bin", "tests", "examples"]
        );
    }

    #[test]
    fn every_kind_has_a_distinct_keyword() {
        let mut keywords: Vec<_> = RelationKind::ALL.iter().map(|k| k.keyword()).collect();
        keywords.sort();
        keywords.dedup();
        assert_eq!(
            keywords,
            ["calls", "constructs", "implements", "names", "uses"]
        );
    }

    #[test]
    fn an_ancestor_and_its_descendant_are_lineal_in_both_directions() {
        assert!(is_lineal(&id("a"), &id("a.b.c")));
        assert!(is_lineal(&id("a.b.c"), &id("a")));
    }

    #[test]
    fn an_element_is_lineal_with_itself() {
        assert!(is_lineal(&id("a.b"), &id("a.b")));
    }

    #[test]
    fn siblings_are_not_lineal() {
        assert!(!is_lineal(&id("a.b"), &id("a.c")));
    }

    #[test]
    fn a_shared_prefix_string_is_not_lineage() {
        // `a.bc` is not under `a.b`; segments compare whole.
        assert!(!is_lineal(&id("a.b"), &id("a.bc")));
    }

    #[test]
    fn a_hyphen_becomes_an_underscore() {
        assert_eq!(sanitize_segment("playwright-rs"), "playwright_rs");
    }

    #[test]
    fn a_leading_digit_is_prefixed() {
        assert_eq!(sanitize_segment("3d"), "_3d");
    }

    #[test]
    fn a_reserved_word_gets_a_trailing_underscore() {
        assert_eq!(sanitize_segment("view"), "view_");
        assert_eq!(sanitize_segment("link"), "link_");
        // `icons` was found the hard way: a playwright-rust module.
        assert_eq!(sanitize_segment("icons"), "icons_");
        assert_eq!(sanitize_segment("summary"), "summary_");
    }

    #[test]
    fn model_and_element_are_not_reserved() {
        // likec4 accepts both as ids (at `RESERVED_GRAMMAR_VERSION`); asbuilt-core's own `model`
        // module keeps its name.
        assert_eq!(sanitize_segment("model"), "model");
        assert_eq!(sanitize_segment("element"), "element");
    }

    #[test]
    fn the_reserved_list_is_sorted_and_unique() {
        let mut sorted = RESERVED.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted, RESERVED);
    }

    #[test]
    fn a_plain_identifier_is_unchanged() {
        assert_eq!(sanitize_segment("server_v2"), "server_v2");
    }

    #[test]
    fn sanitizing_an_id_keeps_the_dots() {
        assert_eq!(sanitize_id(&id("play-wright.a.1x")), "play_wright.a._1x");
    }

    #[test]
    fn normalize_sorts_elements_by_id() {
        let mut model = Model {
            elements: vec![element("b"), element("a.z"), element("a")],
            ..Default::default()
        };
        model.normalize();
        let ids: Vec<_> = model.elements.iter().map(|e| dotted(&e.id)).collect();
        assert_eq!(ids, ["a", "a.z", "b"]);
    }

    #[test]
    fn normalize_merges_relations_on_the_pair_keeping_the_strongest_kind() {
        let mut model = Model {
            relations: vec![
                relation("a", "b", RelationKind::Uses, &["Y"]),
                relation("a", "b", RelationKind::Calls, &["X"]),
            ],
            ..Default::default()
        };
        model.normalize();
        assert_eq!(
            model.relations,
            vec![relation("a", "b", RelationKind::Calls, &["X", "Y"])]
        );
    }

    #[test]
    fn normalize_dedups_items_within_a_relation() {
        let mut model = Model {
            relations: vec![relation("a", "b", RelationKind::Uses, &["Y", "X", "Y"])],
            ..Default::default()
        };
        model.normalize();
        assert_eq!(model.relations[0].items, ["X", "Y"]);
    }

    #[test]
    fn normalize_sorts_relations_by_source_then_target() {
        let mut model = Model {
            relations: vec![
                relation("b", "a", RelationKind::Uses, &[]),
                relation("a", "c", RelationKind::Uses, &[]),
                relation("a", "b", RelationKind::Uses, &[]),
            ],
            ..Default::default()
        };
        model.normalize();
        let pairs: Vec<_> = model
            .relations
            .iter()
            .map(|r| (dotted(&r.source), dotted(&r.target)))
            .collect();
        assert_eq!(
            pairs,
            [
                ("a".into(), "b".into()),
                ("a".into(), "c".into()),
                ("b".into(), "a".into())
            ]
        );
    }

    #[test]
    fn normalize_keeps_the_first_technology_seen() {
        let mut first = relation("a", "b", RelationKind::Uses, &[]);
        first.technology = Some("stdio".into());
        let mut model = Model {
            relations: vec![
                relation("a", "b", RelationKind::Uses, &[]),
                first,
                relation("a", "b", RelationKind::Uses, &[]),
            ],
            ..Default::default()
        };
        model.normalize();
        assert_eq!(model.relations[0].technology.as_deref(), Some("stdio"));
    }

    #[test]
    fn merge_appends_and_normalizes() {
        let mut model = Model {
            elements: vec![element("b")],
            ..Default::default()
        };
        model.merge(Model {
            elements: vec![element("a")],
            relations: vec![relation("a", "b", RelationKind::Uses, &["X"])],
            ..Default::default()
        });
        let ids: Vec<_> = model.elements.iter().map(|e| dotted(&e.id)).collect();
        assert_eq!(ids, ["a", "b"]);
        assert_eq!(model.relations.len(), 1);
    }

    #[test]
    fn two_ids_that_sanitize_alike_are_a_duplicate_naming_both() {
        let model = Model {
            elements: vec![element("foo-bar"), element("foo_bar")],
            ..Default::default()
        };
        match model.validate() {
            Err(Error::DuplicateId { id, first, second }) => {
                assert_eq!(id, "foo_bar");
                assert_eq!(first, "foo-bar");
                assert_eq!(second, "foo_bar");
            }
            other => panic!("expected DuplicateId, got {other:?}"),
        }
    }

    #[test]
    fn an_id_that_appears_twice_is_a_duplicate() {
        let model = Model {
            elements: vec![element("app"), element("app")],
            ..Default::default()
        };
        match model.validate() {
            Err(Error::DuplicateId { id, first, second }) => {
                assert_eq!(
                    (id.as_str(), first.as_str(), second.as_str()),
                    ("app", "app", "app")
                );
            }
            other => panic!("expected DuplicateId, got {other:?}"),
        }
    }

    #[test]
    fn distinct_ids_validate() {
        let model = Model {
            elements: vec![element("a"), element("a.b"), element("b")],
            ..Default::default()
        };
        assert!(model.validate().is_ok());
    }

    #[test]
    fn element_finds_by_exact_id() {
        let model = Model {
            elements: vec![element("a"), element("a.b")],
            ..Default::default()
        };
        assert_eq!(
            model.element(&id("a.b")).map(|e| e.title.as_str()),
            Some("b")
        );
        assert_eq!(model.element(&id("a.b.c")), None);
    }

    #[test]
    fn each_relation_kind_is_drawn_with_its_line_and_head() {
        assert_eq!(
            RelationKind::ALL.map(|kind| (kind.keyword(), kind.line(), kind.head())),
            [
                ("implements", "solid", "onormal"),
                ("constructs", "solid", "diamond"),
                ("calls", "solid", "vee"),
                ("names", "dotted", "dot"),
                ("uses", "dotted", "odot"),
            ]
        );
    }
}