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::Component);
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 " tag external",
403 " tag tests",
404 " relationship implements",
405 " relationship constructs",
406 " relationship calls",
407 " relationship names",
408 " relationship uses",
409 ] {
410 assert!(
411 spec.contains(&format!("{line}\n")),
412 "missing {line:?} in:\n{spec}"
413 );
414 }
415 }
416
417 #[test]
418 fn a_themed_kind_declares_its_color_and_styles_the_element_with_it() {
419 let opts = options().with_theme(BTreeMap::from([
420 ("container".to_string(), "#f0a884".to_string()),
421 ("process".to_string(), "#c9c9c9".to_string()),
422 ]));
423 let text = emit(&sample(), &opts);
424 let spec = text.split("model {").next().unwrap();
425 assert!(
426 spec.starts_with(&format!(
427 "{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 tag external\n"
428 )),
429 "{spec}"
430 );
431 }
432
433 #[test]
434 fn a_theme_for_a_kind_the_model_lacks_emits_nothing_for_it() {
435 let opts = options().with_theme(BTreeMap::from([(
436 "browser".to_string(),
437 "#000000".to_string(),
438 )]));
439 let text = emit(&sample(), &opts);
440 assert!(!text.contains("browser"), "{text}");
441 assert_eq!(text, emit(&sample(), &options()));
442 }
443
444 #[test]
445 fn a_child_is_nested_inside_its_parent_under_its_last_segment() {
446 let text = emit(&sample(), &options());
447 let app_block = text.split(" app = container 'app' {").nth(1).unwrap();
448 assert!(
449 app_block.contains("\n server = component 'server' {"),
450 "{text}"
451 );
452 assert!(!text.contains("app.server = component"), "{text}");
453 }
454
455 #[test]
456 fn tags_come_first_in_a_body() {
457 let text = emit(&sample(), &options());
458 assert!(
459 text.contains("tests = component 'tests' {\n #tests\n }"),
460 "{text}"
461 );
462 }
463
464 #[test]
465 fn a_quote_in_a_description_is_escaped_and_markdown_kept() {
466 let text = emit(&sample(), &options());
467 assert!(
468 text.contains("description 'Where it\\'s sent.\n\n- one\n- two'"),
469 "{text}"
470 );
471 }
472
473 #[test]
474 fn a_path_becomes_metadata_and_a_link_relative_to_the_output_directory() {
475 let text = emit(&sample(), &options());
476 assert!(text.contains("metadata {\n path 'crates/app/src/server.rs'\n }\n link ../../crates/app/src/server.rs\n"), "{text}");
477 }
478
479 #[test]
480 fn an_output_file_at_the_root_links_with_a_dot_prefix() {
481 let text = emit(&sample(), &EmitOptions::for_output_path("model.c4"));
482 assert!(text.contains("link ./crates/app\n"), "{text}");
483 assert_eq!(EmitOptions::for_output_path("./model.c4").link_prefix, "./");
484 }
485
486 #[test]
487 fn a_relation_line_carries_kind_label_and_technology() {
488 let text = emit(&sample(), &options());
489 assert!(
490 text.contains(" app.tests -[calls]-> app.server 'Server, connect'\n"),
491 "{text}"
492 );
493 assert!(
494 text.contains(
495 " app.server -[uses]-> node_driver 'spawns' {\n technology 'stdio'\n }\n"
496 ),
497 "{text}"
498 );
499 }
500
501 #[test]
502 fn a_relation_without_items_has_no_label() {
503 let mut model = sample();
504 model.relations[0].items.clear();
505 let text = emit(&model, &options());
506 assert!(
507 text.contains(" app.tests -[calls]-> app.server\n"),
508 "{text}"
509 );
510 }
511
512 #[test]
513 fn the_index_view_includes_every_top_level_element() {
514 let text = emit(&sample(), &options());
515 assert!(text.contains(" view index {\n title 'Overview'\n include app, node_driver\n autoLayout LeftRight\n }"), "{text}");
516 }
517
518 #[test]
519 fn an_element_with_children_gets_a_scoped_view_and_a_leaf_does_not() {
520 let text = emit(&sample(), &options());
521 assert!(text.contains(" view view_app of app {\n title 'app'\n include *\n autoLayout TopBottom\n }"), "{text}");
522 assert!(!text.contains("of app.server {"), "{text}");
523 assert!(!text.contains("of node_driver {"), "{text}");
524 }
525
526 #[test]
527 fn a_hyphen_in_an_id_is_an_underscore_everywhere_it_appears() {
528 let mut model = sample();
529 for e in &mut model.elements {
530 if e.id[0] == "app" {
531 e.id[0] = "my-app".into();
532 }
533 }
534 for r in &mut model.relations {
535 if r.source[0] == "app" {
536 r.source[0] = "my-app".into();
537 }
538 if r.target[0] == "app" {
539 r.target[0] = "my-app".into();
540 }
541 }
542 let text = emit(&model, &options());
543 assert!(text.contains(" my_app = container"), "{text}");
544 assert!(
545 text.contains("my_app.tests -[calls]-> my_app.server"),
546 "{text}"
547 );
548 assert!(text.contains("view view_my_app of my_app"), "{text}");
549 for line in text.lines().filter(|l| l.contains("my-app")) {
551 assert!(line.trim_start().starts_with("title "), "{line}");
552 }
553 }
554
555 #[test]
556 fn an_element_whose_parent_is_absent_is_emitted_at_the_top_level() {
557 let model = Model {
558 elements: vec![element("gone.child", ElementKind::Component)],
559 ..Default::default()
560 };
561 let text = emit(&model, &options());
562 assert!(
563 text.contains("model {\n child = component 'child'\n"),
564 "{text}"
565 );
566 }
567
568 #[test]
569 fn each_body_field_alone_earns_a_block() {
570 fn only(f: impl FnOnce(&mut Element)) -> Model {
571 let mut e = element("x", ElementKind::Container);
572 f(&mut e);
573 Model {
574 elements: vec![e],
575 ..Default::default()
576 }
577 }
578 let mut with_child = only(|_| {});
579 with_child
580 .elements
581 .push(element("x.y", ElementKind::Component));
582 let cases = [
583 ("tags", only(|e| e.tags = vec!["tests".into()])),
584 ("description", only(|e| e.description = Some("d".into()))),
585 ("technology", only(|e| e.technology = Some("t".into()))),
586 ("path", only(|e| e.path = Some("p".into()))),
587 ("child", with_child),
588 ];
589 for (field, model) in cases {
590 let text = emit(&model, &options());
591 assert!(
592 text.contains(" x = container 'x' {\n"),
593 "{field} alone should open a block:\n{text}"
594 );
595 }
596 }
597
598 #[test]
599 fn an_element_with_nothing_to_say_has_no_block() {
600 let model = Model {
601 elements: vec![element("leaf", ElementKind::Container)],
602 ..Default::default()
603 };
604 let text = emit(&model, &options());
605 assert!(text.contains(" leaf = container 'leaf'\n}"), "{text}");
606 }
607
608 #[test]
609 fn output_does_not_depend_on_input_order() {
610 let a = emit(&sample(), &options());
611 let mut shuffled = sample();
612 shuffled.elements.reverse();
613 shuffled.relations.reverse();
614 let b = emit(&shuffled, &options());
615 assert_eq!(a, b);
616 }
617
618 #[test]
619 fn output_has_no_carriage_returns_or_backslashes_in_paths() {
620 let mut model = sample();
621 model.elements[2].description = Some("line\r\nnext".into());
622 let text = emit(&model, &options());
623 assert!(!text.contains('\r'), "{text:?}");
624 assert!(text.contains("description 'line\nnext'"), "{text}");
625 }
626
627 #[test]
628 fn the_root_path_keeps_its_metadata_but_has_no_link() {
629 let mut model = sample();
630 model
631 .elements
632 .iter_mut()
633 .find(|e| e.id == ["app"])
634 .unwrap()
635 .path = Some(".".into());
636 let text = emit(&model, &options());
637 let app_block = text.split(" app = container 'app' {").nth(1).unwrap();
638 let head: String = app_block.lines().take(4).collect::<Vec<_>>().join("\n");
639 assert!(head.contains("path '.'"), "{head}");
640 assert!(!head.contains("link"), "{head}");
641 }
642
643 #[test]
644 fn a_space_or_quote_in_a_path_is_percent_encoded_in_the_link_only() {
645 let mut model = sample();
646 model
647 .elements
648 .iter_mut()
649 .find(|e| e.id == ["app", "server"])
650 .unwrap()
651 .path = Some("crates/my tool/it's.rs".into());
652 let text = emit(&model, &options());
653 assert!(text.contains("path 'crates/my tool/it\\'s.rs'"), "{text}");
654 assert!(
655 text.contains("link ../../crates/my%20tool/it%27s.rs\n"),
656 "{text}"
657 );
658 }
659
660 #[test]
661 fn link_encoding_keeps_unreserved_characters_and_slashes() {
662 assert_eq!(link_encode("a-b_c.d~/e"), "a-b_c.d~/e");
663 assert_eq!(link_encode("é"), "%C3%A9");
664 }
665
666 #[test]
667 fn two_ids_that_collapse_to_one_view_id_get_distinct_views() {
668 let model = Model {
669 elements: vec![
670 element("a.b_c", ElementKind::Container),
671 element("a.b_c.x", ElementKind::Component),
672 element("a_b.c", ElementKind::Container),
673 element("a_b.c.y", ElementKind::Component),
674 element("a_b_c", ElementKind::Container),
675 element("a_b_c.z", ElementKind::Component),
676 ],
677 ..Default::default()
678 };
679 let text = emit(&model, &options());
680 assert!(text.contains("view view_a_b_c of a.b_c {"), "{text}");
681 assert!(text.contains("view view_a_b_c_2 of a_b.c {"), "{text}");
682 assert!(text.contains("view view_a_b_c_3 of a_b_c {"), "{text}");
683 let mut normalized = model.clone();
684 normalized.normalize();
685 let names: Vec<String> = view_ids(&normalized).into_values().collect();
686 assert_eq!(names, ["view_a_b_c", "view_a_b_c_2", "view_a_b_c_3"]);
687 }
688
689 #[test]
690 fn view_ids_names_every_element_with_children_and_only_those() {
691 let mut model = sample();
692 model.normalize();
693 let names = view_ids(&model);
694 let keyed: Vec<(String, String)> = names
695 .iter()
696 .map(|(id, name)| (id.join("."), name.clone()))
697 .collect();
698 assert_eq!(keyed, [("app".to_string(), "view_app".to_string())]);
699 assert!(!names.contains_key(&id("app.server")));
700 assert!(!names.contains_key(&id("node_driver")));
701 }
702
703 #[test]
704 fn a_backslash_in_a_string_is_escaped() {
705 assert_eq!(quote("a\\b"), "'a\\\\b'");
706 }
707
708 #[test]
709 fn link_prefix_counts_directories_not_the_file() {
710 assert_eq!(
711 EmitOptions::for_output_path("a/b/c/m.c4").link_prefix,
712 "../../../"
713 );
714 assert_eq!(EmitOptions::for_output_path("a/m.c4").link_prefix, "../");
715 }
716}