microcad_lang/syntax/
doc_block.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Documentation block syntax element
5
6use crate::{src_ref::*, syntax::*};
7
8/// Retrieve doc from symbol definition.
9pub trait Doc {
10    /// Return documentation
11    fn doc(&self) -> Option<DocBlock>;
12}
13
14/// Static variant of trait Doc for builtins.
15pub type BuiltinDocFn = dyn Fn() -> Option<DocBlock>;
16
17/// Block of documentation comments, starting with `/// `.
18#[derive(Clone, Default)]
19pub struct DocBlock {
20    /// Doc summary.
21    pub summary: String,
22    /// Doc details.
23    pub details: Option<String>,
24    /// Source reference.
25    pub src_ref: SrcRef,
26}
27
28impl DocBlock {
29    /// Create new doc block for builtin.
30    pub fn new_builtin(comment: &str) -> Self {
31        let lines: Vec<_> = comment.lines().collect();
32        let (summary, details) =
33            if let Some(pos) = lines.iter().position(|line| line.trim().is_empty()) {
34                (lines[0..pos].join("\n"), Some(lines[pos..].join("\n")))
35            } else {
36                (lines.join("\n"), None)
37            };
38
39        Self {
40            summary,
41            details,
42            src_ref: SrcRef(None),
43        }
44    }
45}
46
47impl SrcReferrer for DocBlock {
48    fn src_ref(&self) -> SrcRef {
49        self.src_ref.clone()
50    }
51}
52
53impl std::fmt::Display for DocBlock {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        let summary = &self.summary;
56        match &self.details {
57            None => write!(f, "{summary}"),
58            Some(details) => write!(f, "{summary}\n\n{details}"),
59        }
60    }
61}
62
63impl TreeDisplay for DocBlock {
64    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
65        writeln!(
66            f,
67            "{:depth$}DocBlock: '{}'",
68            "",
69            crate::shorten!(self.summary)
70        )
71    }
72}