1use std::path::{Path, PathBuf};
35
36use bynk_syntax::ast::*;
37use bynk_syntax::lexer::tokenize;
38use bynk_syntax::parser::parse_unit_with_recovery;
39use bynk_syntax::span::Span;
40
41use crate::symbols;
42
43#[derive(Debug, Clone, PartialEq)]
45pub struct DocModel {
46 pub unit_name: String,
49 pub unit_kind: &'static str,
52 pub unit_doc: Option<String>,
55 pub unit_span: Span,
57 pub entries: Vec<DocEntry>,
59}
60
61#[derive(Debug, Clone, PartialEq)]
64pub struct DocEntry {
65 pub name: String,
68 pub kind: &'static str,
70 pub depth: u32,
73 pub markdown: String,
77 pub documented: bool,
81 pub span: Span,
83 pub file: Option<PathBuf>,
87}
88
89type PageParts<'u> = (
92 &'static str,
93 String,
94 Span,
95 &'u Option<Doc>,
96 &'u [CommonsItem],
97);
98
99fn page_parts(unit: &SourceUnit) -> Option<PageParts<'_>> {
101 match unit {
102 SourceUnit::Commons(c) => Some((
103 "commons",
104 c.name.joined(),
105 c.name.span,
106 &c.documentation,
107 &c.items,
108 )),
109 SourceUnit::Context(c) => Some((
110 "context",
111 c.name.joined(),
112 c.name.span,
113 &c.documentation,
114 &c.items,
115 )),
116 SourceUnit::Adapter(a) => Some((
117 "adapter",
118 a.name.joined(),
119 a.name.span,
120 &a.documentation,
121 &a.items,
122 )),
123 SourceUnit::Suite(_) => None,
124 }
125}
126
127fn parse(text: &str) -> Option<SourceUnit> {
128 let tokens = tokenize(text).ok()?;
129 parse_unit_with_recovery(&tokens, text).0
130}
131
132pub fn documentation_model(text: &str) -> Option<DocModel> {
143 let unit = parse(text)?;
144 let (unit_kind, unit_name, unit_span, unit_doc, items) = page_parts(&unit)?;
145 let mut entries = Vec::new();
146 for item in items {
147 push_item(&mut entries, item);
148 }
149 Some(DocModel {
150 unit_name,
151 unit_kind,
152 unit_doc: unit_doc.as_deref().map(str::to_owned),
153 unit_span,
154 entries,
155 })
156}
157
158pub fn documentation_model_merged<'a>(
172 primary: (&'a Path, &'a str),
173 files: impl IntoIterator<Item = (&'a Path, &'a str)>,
174) -> Option<DocModel> {
175 let unit = parse(primary.1)?;
176 let (unit_kind, unit_name, unit_span, _, _) = page_parts(&unit)?;
177 let mut all: Vec<(&Path, &str)> = files.into_iter().collect();
178 if !all.iter().any(|(p, _)| *p == primary.0) {
179 all.push(primary);
180 }
181 all.sort_by(|a, b| a.0.cmp(b.0));
182 all.dedup_by(|a, b| a.0 == b.0);
183 let mut unit_doc: Option<String> = None;
184 let mut entries = Vec::new();
185 for (path, text) in all {
186 let Some(unit) = parse(text) else {
187 continue;
188 };
189 let Some((kind, name, _, _, items)) = page_parts(&unit) else {
190 continue;
191 };
192 if kind != unit_kind || name != unit_name {
193 continue;
194 }
195 if unit_doc.is_none() {
196 unit_doc = unit.module_doc().map(str::to_string);
197 }
198 let start = entries.len();
199 for item in items {
200 push_item(&mut entries, item);
201 }
202 for e in &mut entries[start..] {
203 e.file = Some(path.to_path_buf());
204 }
205 }
206 Some(DocModel {
207 unit_name,
208 unit_kind,
209 unit_doc,
210 unit_span,
211 entries,
212 })
213}
214
215fn push_item(out: &mut Vec<DocEntry>, item: &CommonsItem) {
223 match item {
224 CommonsItem::Type(t) => {
225 out.push(DocEntry {
226 name: t.name.name.clone(),
227 kind: "type",
228 depth: 0,
229 markdown: symbols::describe_type(t),
230 documented: t.documentation.is_some(),
231 span: t.name.span,
232 file: None,
233 });
234 push_member_docs(out, t);
235 }
236 CommonsItem::Fn(f) => out.push(DocEntry {
237 name: f.name.display(),
238 kind: match f.name {
239 FnName::Free(_) => "function",
240 FnName::Method { .. } => "method",
241 },
242 depth: 0,
243 markdown: symbols::describe_fn(f),
244 documented: f.documentation.is_some(),
245 span: f.name.ident().span,
246 file: None,
247 }),
248 CommonsItem::Capability(c) => {
249 out.push(DocEntry {
250 name: c.name.name.clone(),
251 kind: "capability",
252 depth: 0,
253 markdown: symbols::describe_capability(c),
254 documented: c.documentation.is_some(),
255 span: c.name.span,
256 file: None,
257 });
258 for op in &c.ops {
259 out.push(DocEntry {
260 name: format!("{}.{}", c.name.name, op.name.name),
261 kind: "operation",
262 depth: 1,
263 markdown: symbols::describe_capability_op(c, op),
264 documented: op.documentation.is_some(),
265 span: op.name.span,
266 file: None,
267 });
268 }
269 }
270 CommonsItem::Provider(p) => out.push(DocEntry {
271 name: format!("{} = {}", p.capability.name, p.provider_name.name),
272 kind: "provider",
273 depth: 0,
274 markdown: symbols::describe_provider(p),
275 documented: p.documentation.is_some(),
276 span: p.provider_name.span,
277 file: None,
278 }),
279 CommonsItem::Service(s) => {
280 out.push(DocEntry {
281 name: s.name.name.clone(),
282 kind: "service",
283 depth: 0,
284 markdown: symbols::describe_service(s),
285 documented: s.documentation.is_some(),
286 span: s.name.span,
287 file: None,
288 });
289 for h in &s.handlers {
290 out.push(DocEntry {
291 name: symbols::handler_line(h),
295 kind: "handler",
296 depth: 1,
297 markdown: symbols::describe_service_handler(s, h),
298 documented: h.documentation.is_some(),
299 span: h.span,
300 file: None,
301 });
302 }
303 }
304 CommonsItem::Agent(a) => {
305 out.push(DocEntry {
306 name: a.name.name.clone(),
307 kind: "agent",
308 depth: 0,
309 markdown: symbols::describe_agent(a),
310 documented: a.documentation.is_some(),
311 span: a.name.span,
312 file: None,
313 });
314 for h in &a.handlers {
315 let handler = h
316 .method_name
317 .as_ref()
318 .map(|m| m.name.clone())
319 .unwrap_or_else(|| "call".to_string());
320 out.push(DocEntry {
321 name: format!("{}.{}", a.name.name, handler),
322 kind: "handler",
323 depth: 1,
324 markdown: symbols::describe_agent_handler(a, h, &handler),
325 documented: h.documentation.is_some(),
326 span: h.method_name.as_ref().map(|m| m.span).unwrap_or(h.span),
327 file: None,
328 });
329 }
330 }
331 CommonsItem::Actor(a) => out.push(DocEntry {
332 name: a.name.name.clone(),
333 kind: "actor",
334 depth: 0,
335 markdown: symbols::describe_actor(a),
336 documented: a.documentation.is_some(),
337 span: a.name.span,
338 file: None,
339 }),
340 CommonsItem::Messages(m) => {
342 out.push(DocEntry {
343 name: m.tag.clone(),
344 kind: "messages",
345 depth: 0,
346 markdown: symbols::describe_messages(m),
347 documented: m.documentation.is_some(),
348 span: m.tag_span,
349 file: None,
350 });
351 for e in &m.entries {
353 if let Some(doc) = &e.documentation {
354 out.push(DocEntry {
355 name: format!("{}.{}", m.tag, e.code),
356 kind: "message",
357 depth: 1,
358 markdown: format!(
359 "```bynk\n\"{}\" => …\n```\n\n{}",
360 e.code,
361 doc.trim_end()
362 ),
363 documented: true,
364 span: e.code_span,
365 file: None,
366 });
367 }
368 }
369 }
370 CommonsItem::Event(e) => {
374 out.push(DocEntry {
375 name: e.name.name.clone(),
376 kind: "event",
377 depth: 0,
378 markdown: symbols::describe_type(&e.as_type_decl()),
379 documented: e.documentation.is_some(),
380 span: e.name.span,
381 file: None,
382 });
383 push_member_docs(out, &e.as_type_decl());
384 }
385 CommonsItem::Asset(a) => out.push(DocEntry {
387 name: a.name.name.clone(),
388 kind: "asset",
389 depth: 0,
390 markdown: symbols::describe_asset(a),
391 documented: a.documentation.is_some(),
392 span: a.name.span,
393 file: None,
394 }),
395 CommonsItem::Embed(e) => out.push(DocEntry {
397 name: e.name.name.clone(),
398 kind: "embed",
399 depth: 0,
400 markdown: symbols::describe_embed(e),
401 documented: e.documentation.is_some(),
402 span: e.name.span,
403 file: None,
404 }),
405 CommonsItem::Const(c) => out.push(DocEntry {
407 name: c.name.name.clone(),
408 kind: "constant",
409 depth: 0,
410 markdown: symbols::describe_const(c),
411 documented: c.documentation.is_some(),
412 span: c.name.span,
413 file: None,
414 }),
415 }
416}
417
418fn push_member_docs(out: &mut Vec<DocEntry>, t: &TypeDecl) {
424 match &t.body {
425 TypeBody::Record(r) => {
426 for f in r.fields.iter().filter(|f| f.documentation.is_some()) {
427 out.push(DocEntry {
428 name: format!("{}.{}", t.name.name, f.name.name),
429 kind: "field",
430 depth: 1,
431 markdown: symbols::describe_record_field(t, f),
432 documented: true,
433 span: f.name.span,
434 file: None,
435 });
436 }
437 }
438 TypeBody::Sum(s) => {
439 for v in &s.variants {
440 if v.documentation.is_some() {
441 out.push(DocEntry {
442 name: format!("{}.{}", t.name.name, v.name.name),
443 kind: "variant",
444 depth: 1,
445 markdown: symbols::describe_variant(t, v),
446 documented: true,
447 span: v.name.span,
448 file: None,
449 });
450 }
451 for p in v.payload.iter().filter(|p| p.documentation.is_some()) {
452 out.push(DocEntry {
453 name: format!("{}.{}.{}", t.name.name, v.name.name, p.name.name),
454 kind: "field",
455 depth: 2,
456 markdown: symbols::describe_variant_field(t, v, p),
457 documented: true,
458 span: p.name.span,
459 file: None,
460 });
461 }
462 }
463 }
464 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
465 }
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471
472 const DOCUMENTED_CTX: &str = r#"---
477The demo application context.
478---
479context demo.app
480
481---
482Reads the wall clock.
483---
484capability Clock {
485 ---
486 Milliseconds since the Unix epoch.
487 ---
488 fn now() -> Int
489}
490
491---
492An amount in the smallest currency unit.
493---
494type Money = Int where NonNegative
495
496---
497The public HTTP surface.
498---
499service Api from http {
500 ---
501 Returns the current instant.
502 ---
503 on GET("/now") () -> Effect[Int] given Clock {
504 Clock.now()
505 }
506}
507
508---
509A per-key running total.
510---
511agent Counter {
512 key id: Int
513 store value: Cell[Int]
514 ---
515 Adds `amount` to the total and returns the new value.
516 ---
517 on call bump(amount: Int) -> Effect[Int] {
518 let _ <- value.update((v) => v + amount)
519 value
520 }
521}
522"#;
523
524 #[test]
525 fn documented_context_aggregates_every_declaration_in_order_and_hierarchy() {
526 let model = documentation_model(DOCUMENTED_CTX).expect("a context model");
527 assert_eq!(model.unit_name, "demo.app");
528 assert_eq!(model.unit_kind, "context");
529 assert_eq!(
530 model.unit_doc.as_deref(),
531 Some("The demo application context.")
532 );
533
534 let names: Vec<(&str, u32, &str)> = model
537 .entries
538 .iter()
539 .map(|e| (e.name.as_str(), e.depth, e.kind))
540 .collect();
541 assert_eq!(
542 names,
543 vec![
544 ("Clock", 0, "capability"),
545 ("Clock.now", 1, "operation"),
546 ("Money", 0, "type"),
547 ("Api", 0, "service"),
548 ("on GET(\"/now\")", 1, "handler"),
549 ("Counter", 0, "agent"),
550 ("Counter.bump", 1, "handler"),
551 ]
552 );
553
554 assert!(model.entries.iter().all(|e| e.documented));
557 let money = model.entries.iter().find(|e| e.name == "Money").unwrap();
558 assert!(
559 money
560 .markdown
561 .contains("An amount in the smallest currency unit.")
562 );
563 assert!(money.markdown.contains("```bynk"));
564 let bump = model
565 .entries
566 .iter()
567 .find(|e| e.name == "Counter.bump")
568 .unwrap();
569 assert!(bump.markdown.contains("Adds `amount` to the total"));
570 }
571
572 #[test]
573 fn undocumented_declarations_are_flagged_for_the_coverage_placeholder() {
574 let src = "commons demo.x {\n\
575 ---\n\
576 Has docs.\n\
577 ---\n\
578 type Documented = Int\n\
579 type Undocumented = Int\n\
580 fn helper(n: Int) -> Int { n }\n\
581 }";
582 let model = documentation_model(src).expect("a commons model");
583 assert_eq!(model.unit_kind, "commons");
584 let documented = model
585 .entries
586 .iter()
587 .find(|e| e.name == "Documented")
588 .unwrap();
589 assert!(documented.documented);
590 let undoc = model
591 .entries
592 .iter()
593 .find(|e| e.name == "Undocumented")
594 .unwrap();
595 assert!(!undoc.documented);
596 assert!(undoc.markdown.contains("```bynk"));
599 let helper = model.entries.iter().find(|e| e.name == "helper").unwrap();
600 assert!(!helper.documented);
601 }
602
603 #[test]
604 fn suite_units_have_no_documentation_page() {
605 let src = "suite for demo.app {\n\
606 case works {\n\
607 expect true\n\
608 }\n\
609 }";
610 assert!(documentation_model(src).is_none());
612 }
613
614 #[test]
615 fn empty_input_yields_no_model() {
616 assert!(documentation_model("").is_none());
617 }
618
619 #[test]
623 fn documented_members_are_listed_under_their_type() {
624 let src = "commons m\n\nuses bynk.locale\nuses bynk.locale.types\n\n--- A run.\ntype Run = {\n --- The repo.\n repo: String,\n n: Int,\n}\n\ntype Shape =\n ---\n Round.\n ---\n | Circle(\n --- The radius.\n r: Int,\n )\n | Dot\n\nmessages \"en\" @reference {\n --- Greets.\n \"hi\" => \"Hello\"\n \"bye\" => \"Bye\"\n}\n";
625 let model = documentation_model(src).expect("a model");
626 let rows: Vec<(&str, &str, u32)> = model
627 .entries
628 .iter()
629 .map(|e| (e.name.as_str(), e.kind, e.depth))
630 .collect();
631 assert_eq!(
632 rows,
633 [
634 ("Run", "type", 0),
635 ("Run.repo", "field", 1),
636 ("Shape", "type", 0),
637 ("Shape.Circle", "variant", 1),
638 ("Shape.Circle.r", "field", 2),
639 ("en", "messages", 0),
640 ("en.hi", "message", 1),
641 ]
642 );
643 let repo = &model.entries[1];
644 assert!(repo.documented && repo.markdown.contains("The repo."));
645 assert!(model.entries[3].markdown.contains("Round."));
646 assert!(model.entries[4].markdown.contains("The radius."));
647 assert!(model.entries[6].markdown.contains("Greets."));
648 }
649
650 #[test]
654 fn the_merged_page_lists_member_docs_with_their_file() {
655 use std::path::Path;
656 let a = "--- The model.\ncommons m\n\ntype Run = {\n --- The repo.\n repo: String,\n}\n";
657 let b = "commons m\n\ntype Outcome = enum {\n --- Passed.\n Pass,\n Fail,\n}\n";
658 let (pa, pb) = (Path::new("a.bynk"), Path::new("b.bynk"));
659 let model = documentation_model_merged((pa, a), [(pb, b)]).expect("a model");
660 assert_eq!(model.unit_doc.as_deref(), Some("The model."));
661 let rows: Vec<(&str, u32, Option<&Path>)> = model
662 .entries
663 .iter()
664 .map(|e| (e.name.as_str(), e.depth, e.file.as_deref()))
665 .collect();
666 assert_eq!(
667 rows,
668 [
669 ("Run", 0, Some(pa)),
670 ("Run.repo", 1, Some(pa)),
671 ("Outcome", 0, Some(pb)),
672 ("Outcome.Pass", 1, Some(pb)),
673 ]
674 );
675 }
676
677 #[test]
678 fn adapter_unit_documents_its_items() {
679 let src = "adapter tokens {\n\
680 binding \"./tokens.binding.ts\"\n\
681 exports capability { Jwt }\n\
682 capability Jwt {\n\
683 fn sign(secret: String) -> Effect[String]\n\
684 }\n\
685 provides Jwt = JoseJwt\n\
686 }";
687 let model = documentation_model(src).expect("an adapter model");
688 assert_eq!(model.unit_name, "tokens");
689 assert_eq!(model.unit_kind, "adapter");
690 assert!(
691 model
692 .entries
693 .iter()
694 .any(|e| e.name == "Jwt" && e.kind == "capability")
695 );
696 assert!(
697 model
698 .entries
699 .iter()
700 .any(|e| e.name == "Jwt.sign" && e.kind == "operation")
701 );
702 assert!(
703 model
704 .entries
705 .iter()
706 .any(|e| e.name == "Jwt = JoseJwt" && e.kind == "provider")
707 );
708 }
709}