1use std::collections::{BTreeMap, BTreeSet};
10use std::fmt::Write;
11
12use crate::model::{Element, Id, Model, RelationKind, sanitize_id, sanitize_segment};
13
14pub const HEADER: &str = "// GENERATED by asbuilt. Do not edit; run asbuilt survey.";
17
18#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct EmitOptions {
21 pub link_prefix: String,
25 pub theme: BTreeMap<String, String>,
29}
30
31impl EmitOptions {
32 pub fn for_output_path(output_path: &str) -> Self {
35 let depth = output_path
36 .split('/')
37 .filter(|s| !s.is_empty() && *s != ".")
38 .count()
39 .saturating_sub(1);
40 let link_prefix = if depth == 0 {
41 "./".to_string()
42 } else {
43 "../".repeat(depth)
44 };
45 Self {
46 link_prefix,
47 theme: BTreeMap::new(),
48 }
49 }
50
51 pub fn with_theme(mut self, theme: BTreeMap<String, String>) -> Self {
53 self.theme = theme;
54 self
55 }
56}
57
58fn quote(text: &str) -> String {
61 let mut out = String::with_capacity(text.len() + 2);
62 out.push('\'');
63 for c in text.chars() {
64 match c {
65 '\\' => out.push_str("\\\\"),
66 '\'' => out.push_str("\\'"),
67 '\r' => {}
68 c => out.push(c),
69 }
70 }
71 out.push('\'');
72 out
73}
74
75pub fn link_encode(path: &str) -> String {
79 let mut out = String::with_capacity(path.len());
80 for byte in path.bytes() {
81 let keep = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/');
82 if keep {
83 out.push(byte as char);
84 } else {
85 out.push_str(&format!("%{byte:02X}"));
86 }
87 }
88 out
89}
90
91pub fn emit(model: &Model, options: &EmitOptions) -> String {
94 let mut model = model.clone();
95 model.normalize();
96
97 let mut out = String::new();
98 out.push_str(HEADER);
99 out.push('\n');
100 out.push('\n');
101 emit_specification(&mut out, &model, &options.theme);
102 out.push('\n');
103 emit_model(&mut out, &model, options);
104 out.push('\n');
105 emit_views(&mut out, &model);
106 out
107}
108
109pub fn theme_color_name(kind: &str) -> String {
111 format!("theme_{kind}")
112}
113
114fn emit_specification(out: &mut String, model: &Model, theme: &BTreeMap<String, String>) {
115 let mut kinds: BTreeSet<&str> = BTreeSet::new();
116 let mut tags: BTreeSet<&str> = BTreeSet::new();
117 for element in &model.elements {
118 kinds.insert(element.kind.keyword());
119 tags.extend(element.tags.iter().map(String::as_str));
120 }
121 out.push_str("specification {\n");
122 for kind in &kinds {
123 if let Some(color) = theme.get(*kind) {
124 writeln!(out, " color {} {color}", theme_color_name(kind)).unwrap();
125 }
126 }
127 for kind in &kinds {
128 if theme.contains_key(*kind) {
129 writeln!(
130 out,
131 " element {kind} {{\n style {{\n color {}\n }}\n }}",
132 theme_color_name(kind)
133 )
134 .unwrap();
135 } else {
136 writeln!(out, " element {kind}").unwrap();
137 }
138 }
139 for tag in tags {
140 writeln!(out, " tag {tag}").unwrap();
141 }
142 for kind in RelationKind::ALL {
143 writeln!(out, " relationship {}", kind.keyword()).unwrap();
144 }
145 out.push_str("}\n");
146}
147
148pub(crate) fn children_of<'a>(model: &'a Model, parent: &[String]) -> Vec<&'a Element> {
152 model
153 .elements
154 .iter()
155 .filter(|e| {
156 if parent.is_empty() {
157 e.id.len() == 1 || model.element(&e.id[..e.id.len() - 1]).is_none()
158 } else {
159 e.id.len() == parent.len() + 1 && e.id.starts_with(parent)
160 }
161 })
162 .collect()
163}
164
165fn emit_model(out: &mut String, model: &Model, options: &EmitOptions) {
166 out.push_str("model {\n");
167 for element in children_of(model, &[]) {
168 emit_element(out, model, element, options, 1);
169 }
170 if !model.relations.is_empty() {
171 out.push('\n');
172 }
173 for rel in &model.relations {
174 let indent = " ";
175 write!(
176 out,
177 "{indent}{} -[{}]-> {}",
178 sanitize_id(&rel.source),
179 rel.kind.keyword(),
180 sanitize_id(&rel.target)
181 )
182 .unwrap();
183 if !rel.items.is_empty() {
184 write!(out, " {}", quote(&rel.items.join(", "))).unwrap();
185 }
186 match &rel.technology {
187 Some(technology) => {
188 writeln!(
189 out,
190 " {{\n{indent} technology {}\n{indent}}}",
191 quote(technology)
192 )
193 .unwrap();
194 }
195 None => out.push('\n'),
196 }
197 }
198 out.push_str("}\n");
199}
200
201fn emit_element(
202 out: &mut String,
203 model: &Model,
204 element: &Element,
205 options: &EmitOptions,
206 depth: usize,
207) {
208 let indent = " ".repeat(depth);
209 let inner = " ".repeat(depth + 1);
210 let name = sanitize_segment(element.id.last().map(String::as_str).unwrap_or_default());
216 let children = children_of(model, &element.id);
217 let has_body = !element.tags.is_empty()
218 || element.description.is_some()
219 || element.technology.is_some()
220 || element.path.is_some()
221 || !children.is_empty();
222
223 write!(
224 out,
225 "{indent}{name} = {} {}",
226 element.kind.keyword(),
227 quote(&element.title)
228 )
229 .unwrap();
230 if !has_body {
231 out.push('\n');
232 return;
233 }
234 out.push_str(" {\n");
235 if !element.tags.is_empty() {
237 let tags: Vec<String> = element.tags.iter().map(|t| format!("#{t}")).collect();
238 writeln!(out, "{inner}{}", tags.join(" ")).unwrap();
239 }
240 if let Some(description) = &element.description {
241 writeln!(out, "{inner}description {}", quote(description)).unwrap();
242 }
243 if let Some(technology) = &element.technology {
244 writeln!(out, "{inner}technology {}", quote(technology)).unwrap();
245 }
246 if let Some(path) = &element.path {
247 writeln!(
248 out,
249 "{inner}metadata {{\n{inner} path {}\n{inner}}}",
250 quote(path)
251 )
252 .unwrap();
253 if path != "." {
257 writeln!(
258 out,
259 "{inner}link {}{}",
260 options.link_prefix,
261 link_encode(path)
262 )
263 .unwrap();
264 }
265 }
266 for child in children {
267 emit_element(out, model, child, options, depth + 1);
268 }
269 writeln!(out, "{indent}}}").unwrap();
270}
271
272pub fn view_id(id: &Id) -> String {
276 format!("view_{}", sanitize_id(id).replace('.', "_"))
277}
278
279pub fn view_ids(model: &Model) -> BTreeMap<Id, String> {
286 let mut used: BTreeSet<String> = BTreeSet::from(["index".to_string()]);
287 let mut names = BTreeMap::new();
288 for element in &model.elements {
289 if children_of(model, &element.id).is_empty() {
290 continue;
291 }
292 let base = view_id(&element.id);
293 let id = std::iter::once(base.clone())
294 .chain((2..).map(|n| format!("{base}_{n}")))
295 .find(|candidate| used.insert(candidate.clone()))
296 .expect("an unbounded sequence of candidates always has a free one");
297 names.insert(element.id.clone(), id);
298 }
299 names
300}
301
302fn emit_views(out: &mut String, model: &Model) {
303 out.push_str("views {\n");
304 let top: Vec<String> = children_of(model, &[])
305 .iter()
306 .map(|e| sanitize_id(&e.id))
307 .collect();
308 out.push_str(" view index {\n title 'Overview'\n");
309 if !top.is_empty() {
310 writeln!(out, " include {}", top.join(", ")).unwrap();
311 }
312 out.push_str(" autoLayout LeftRight\n }\n");
313 let names = view_ids(model);
314 for element in &model.elements {
315 let Some(id) = names.get(&element.id) else {
316 continue;
317 };
318 let fqn = sanitize_id(&element.id);
319 writeln!(
320 out,
321 "\n view {id} of {fqn} {{\n title {}\n include *\n autoLayout TopBottom\n }}",
322 quote(&element.id.join("."))
323 )
324 .unwrap();
325 }
326 out.push_str("}\n");
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332 use crate::model::{ElementKind, Relation};
333
334 fn id(s: &str) -> Id {
335 s.split('.').map(str::to_string).collect()
336 }
337
338 fn element(s: &str, kind: ElementKind) -> Element {
339 Element {
340 id: id(s),
341 kind,
342 title: s.rsplit('.').next().unwrap().to_string(),
343 description: None,
344 technology: None,
345 path: None,
346 tags: vec![],
347 }
348 }
349
350 fn sample() -> Model {
351 let mut app = element("app", ElementKind::Container);
352 app.technology = Some("library crate".into());
353 app.path = Some("crates/app".into());
354 let mut server = element("app.server", ElementKind::Component);
355 server.description = Some("Where it's sent.\n\n- one\n- two".into());
356 server.path = Some("crates/app/src/server.rs".into());
357 let mut tests = element("app.tests", ElementKind::Tests);
358 tests.tags = vec!["tests".into()];
359 let mut driver = element("node_driver", ElementKind::External("process".into()));
360 driver.tags = vec!["external".into()];
361 driver.technology = Some("Node.js process".into());
362 Model {
363 elements: vec![tests, driver, server, app],
364 relations: vec![
365 Relation {
366 source: id("app.tests"),
367 target: id("app.server"),
368 kind: RelationKind::Calls,
369 items: vec!["Server".into(), "connect".into()],
370 technology: None,
371 },
372 Relation {
373 source: id("app.server"),
374 target: id("node_driver"),
375 kind: RelationKind::Uses,
376 items: vec!["spawns".into()],
377 technology: Some("stdio".into()),
378 },
379 ],
380 ..Default::default()
381 }
382 }
383
384 fn options() -> EmitOptions {
385 EmitOptions::for_output_path("docs/architecture/model.c4")
386 }
387
388 #[test]
389 fn the_header_is_the_first_line() {
390 let text = emit(&sample(), &options());
391 assert_eq!(text.lines().next(), Some(HEADER));
392 }
393
394 #[test]
395 fn the_specification_declares_every_element_kind_tag_and_relationship_kind() {
396 let text = emit(&sample(), &options());
397 let spec = text.split("model {").next().unwrap();
398 for line in [
399 " element component",
400 " element container",
401 " element process",
402 " element tests",
403 " tag external",
404 " tag tests",
405 " relationship implements",
406 " relationship constructs",
407 " relationship calls",
408 " relationship names",
409 " relationship uses",
410 ] {
411 assert!(
412 spec.contains(&format!("{line}\n")),
413 "missing {line:?} in:\n{spec}"
414 );
415 }
416 }
417
418 #[test]
419 fn a_themed_kind_declares_its_color_and_styles_the_element_with_it() {
420 let opts = options().with_theme(BTreeMap::from([
421 ("container".to_string(), "#f0a884".to_string()),
422 ("process".to_string(), "#c9c9c9".to_string()),
423 ]));
424 let text = emit(&sample(), &opts);
425 let spec = text.split("model {").next().unwrap();
426 assert!(
427 spec.starts_with(&format!(
428 "{HEADER}\n\nspecification {{\n color theme_container #f0a884\n color theme_process #c9c9c9\n element component\n element container {{\n style {{\n color theme_container\n }}\n }}\n element process {{\n style {{\n color theme_process\n }}\n }}\n element tests\n tag external\n"
429 )),
430 "{spec}"
431 );
432 }
433
434 #[test]
435 fn a_theme_for_a_kind_the_model_lacks_emits_nothing_for_it() {
436 let opts = options().with_theme(BTreeMap::from([(
437 "browser".to_string(),
438 "#000000".to_string(),
439 )]));
440 let text = emit(&sample(), &opts);
441 assert!(!text.contains("browser"), "{text}");
442 assert_eq!(text, emit(&sample(), &options()));
443 }
444
445 #[test]
446 fn a_child_is_nested_inside_its_parent_under_its_last_segment() {
447 let text = emit(&sample(), &options());
448 let app_block = text.split(" app = container 'app' {").nth(1).unwrap();
449 assert!(
450 app_block.contains("\n server = component 'server' {"),
451 "{text}"
452 );
453 assert!(!text.contains("app.server = component"), "{text}");
454 }
455
456 #[test]
457 fn tags_come_first_in_a_body() {
458 let text = emit(&sample(), &options());
459 assert!(
460 text.contains("tests = tests 'tests' {\n #tests\n }"),
461 "{text}"
462 );
463 }
464
465 #[test]
466 fn a_quote_in_a_description_is_escaped_and_markdown_kept() {
467 let text = emit(&sample(), &options());
468 assert!(
469 text.contains("description 'Where it\\'s sent.\n\n- one\n- two'"),
470 "{text}"
471 );
472 }
473
474 #[test]
475 fn a_path_becomes_metadata_and_a_link_relative_to_the_output_directory() {
476 let text = emit(&sample(), &options());
477 assert!(text.contains("metadata {\n path 'crates/app/src/server.rs'\n }\n link ../../crates/app/src/server.rs\n"), "{text}");
478 }
479
480 #[test]
481 fn an_output_file_at_the_root_links_with_a_dot_prefix() {
482 let text = emit(&sample(), &EmitOptions::for_output_path("model.c4"));
483 assert!(text.contains("link ./crates/app\n"), "{text}");
484 assert_eq!(EmitOptions::for_output_path("./model.c4").link_prefix, "./");
485 }
486
487 #[test]
488 fn a_relation_line_carries_kind_label_and_technology() {
489 let text = emit(&sample(), &options());
490 assert!(
491 text.contains(" app.tests -[calls]-> app.server 'Server, connect'\n"),
492 "{text}"
493 );
494 assert!(
495 text.contains(
496 " app.server -[uses]-> node_driver 'spawns' {\n technology 'stdio'\n }\n"
497 ),
498 "{text}"
499 );
500 }
501
502 #[test]
503 fn a_relation_without_items_has_no_label() {
504 let mut model = sample();
505 model.relations[0].items.clear();
506 let text = emit(&model, &options());
507 assert!(
508 text.contains(" app.tests -[calls]-> app.server\n"),
509 "{text}"
510 );
511 }
512
513 #[test]
514 fn the_index_view_includes_every_top_level_element() {
515 let text = emit(&sample(), &options());
516 assert!(text.contains(" view index {\n title 'Overview'\n include app, node_driver\n autoLayout LeftRight\n }"), "{text}");
517 }
518
519 #[test]
520 fn an_element_with_children_gets_a_scoped_view_and_a_leaf_does_not() {
521 let text = emit(&sample(), &options());
522 assert!(text.contains(" view view_app of app {\n title 'app'\n include *\n autoLayout TopBottom\n }"), "{text}");
523 assert!(!text.contains("of app.server {"), "{text}");
524 assert!(!text.contains("of node_driver {"), "{text}");
525 }
526
527 #[test]
528 fn a_hyphen_in_an_id_is_an_underscore_everywhere_it_appears() {
529 let mut model = sample();
530 for e in &mut model.elements {
531 if e.id[0] == "app" {
532 e.id[0] = "my-app".into();
533 }
534 }
535 for r in &mut model.relations {
536 if r.source[0] == "app" {
537 r.source[0] = "my-app".into();
538 }
539 if r.target[0] == "app" {
540 r.target[0] = "my-app".into();
541 }
542 }
543 let text = emit(&model, &options());
544 assert!(text.contains(" my_app = container"), "{text}");
545 assert!(
546 text.contains("my_app.tests -[calls]-> my_app.server"),
547 "{text}"
548 );
549 assert!(text.contains("view view_my_app of my_app"), "{text}");
550 for line in text.lines().filter(|l| l.contains("my-app")) {
552 assert!(line.trim_start().starts_with("title "), "{line}");
553 }
554 }
555
556 #[test]
557 fn an_element_whose_parent_is_absent_is_emitted_at_the_top_level() {
558 let model = Model {
559 elements: vec![element("gone.child", ElementKind::Component)],
560 ..Default::default()
561 };
562 let text = emit(&model, &options());
563 assert!(
564 text.contains("model {\n child = component 'child'\n"),
565 "{text}"
566 );
567 }
568
569 #[test]
570 fn each_body_field_alone_earns_a_block() {
571 fn only(f: impl FnOnce(&mut Element)) -> Model {
572 let mut e = element("x", ElementKind::Container);
573 f(&mut e);
574 Model {
575 elements: vec![e],
576 ..Default::default()
577 }
578 }
579 let mut with_child = only(|_| {});
580 with_child
581 .elements
582 .push(element("x.y", ElementKind::Component));
583 let cases = [
584 ("tags", only(|e| e.tags = vec!["tests".into()])),
585 ("description", only(|e| e.description = Some("d".into()))),
586 ("technology", only(|e| e.technology = Some("t".into()))),
587 ("path", only(|e| e.path = Some("p".into()))),
588 ("child", with_child),
589 ];
590 for (field, model) in cases {
591 let text = emit(&model, &options());
592 assert!(
593 text.contains(" x = container 'x' {\n"),
594 "{field} alone should open a block:\n{text}"
595 );
596 }
597 }
598
599 #[test]
600 fn an_element_with_nothing_to_say_has_no_block() {
601 let model = Model {
602 elements: vec![element("leaf", ElementKind::Container)],
603 ..Default::default()
604 };
605 let text = emit(&model, &options());
606 assert!(text.contains(" leaf = container 'leaf'\n}"), "{text}");
607 }
608
609 #[test]
610 fn output_does_not_depend_on_input_order() {
611 let a = emit(&sample(), &options());
612 let mut shuffled = sample();
613 shuffled.elements.reverse();
614 shuffled.relations.reverse();
615 let b = emit(&shuffled, &options());
616 assert_eq!(a, b);
617 }
618
619 #[test]
620 fn output_has_no_carriage_returns_or_backslashes_in_paths() {
621 let mut model = sample();
622 model.elements[2].description = Some("line\r\nnext".into());
623 let text = emit(&model, &options());
624 assert!(!text.contains('\r'), "{text:?}");
625 assert!(text.contains("description 'line\nnext'"), "{text}");
626 }
627
628 #[test]
629 fn the_root_path_keeps_its_metadata_but_has_no_link() {
630 let mut model = sample();
631 model
632 .elements
633 .iter_mut()
634 .find(|e| e.id == ["app"])
635 .unwrap()
636 .path = Some(".".into());
637 let text = emit(&model, &options());
638 let app_block = text.split(" app = container 'app' {").nth(1).unwrap();
639 let head: String = app_block.lines().take(4).collect::<Vec<_>>().join("\n");
640 assert!(head.contains("path '.'"), "{head}");
641 assert!(!head.contains("link"), "{head}");
642 }
643
644 #[test]
645 fn a_space_or_quote_in_a_path_is_percent_encoded_in_the_link_only() {
646 let mut model = sample();
647 model
648 .elements
649 .iter_mut()
650 .find(|e| e.id == ["app", "server"])
651 .unwrap()
652 .path = Some("crates/my tool/it's.rs".into());
653 let text = emit(&model, &options());
654 assert!(text.contains("path 'crates/my tool/it\\'s.rs'"), "{text}");
655 assert!(
656 text.contains("link ../../crates/my%20tool/it%27s.rs\n"),
657 "{text}"
658 );
659 }
660
661 #[test]
662 fn link_encoding_keeps_unreserved_characters_and_slashes() {
663 assert_eq!(link_encode("a-b_c.d~/e"), "a-b_c.d~/e");
664 assert_eq!(link_encode("é"), "%C3%A9");
665 }
666
667 #[test]
668 fn two_ids_that_collapse_to_one_view_id_get_distinct_views() {
669 let model = Model {
670 elements: vec![
671 element("a.b_c", ElementKind::Container),
672 element("a.b_c.x", ElementKind::Component),
673 element("a_b.c", ElementKind::Container),
674 element("a_b.c.y", ElementKind::Component),
675 element("a_b_c", ElementKind::Container),
676 element("a_b_c.z", ElementKind::Component),
677 ],
678 ..Default::default()
679 };
680 let text = emit(&model, &options());
681 assert!(text.contains("view view_a_b_c of a.b_c {"), "{text}");
682 assert!(text.contains("view view_a_b_c_2 of a_b.c {"), "{text}");
683 assert!(text.contains("view view_a_b_c_3 of a_b_c {"), "{text}");
684 let mut normalized = model.clone();
685 normalized.normalize();
686 let names: Vec<String> = view_ids(&normalized).into_values().collect();
687 assert_eq!(names, ["view_a_b_c", "view_a_b_c_2", "view_a_b_c_3"]);
688 }
689
690 #[test]
691 fn view_ids_names_every_element_with_children_and_only_those() {
692 let mut model = sample();
693 model.normalize();
694 let names = view_ids(&model);
695 let keyed: Vec<(String, String)> = names
696 .iter()
697 .map(|(id, name)| (id.join("."), name.clone()))
698 .collect();
699 assert_eq!(keyed, [("app".to_string(), "view_app".to_string())]);
700 assert!(!names.contains_key(&id("app.server")));
701 assert!(!names.contains_key(&id("node_driver")));
702 }
703
704 #[test]
705 fn a_backslash_in_a_string_is_escaped() {
706 assert_eq!(quote("a\\b"), "'a\\\\b'");
707 }
708
709 #[test]
710 fn link_prefix_counts_directories_not_the_file() {
711 assert_eq!(
712 EmitOptions::for_output_path("a/b/c/m.c4").link_prefix,
713 "../../../"
714 );
715 assert_eq!(EmitOptions::for_output_path("a/m.c4").link_prefix, "../");
716 }
717}