Skip to main content

logicaffeine_lsp/
stdlib_docs.rs

1//! The stdlib teaching registry: every prelude definition's literate
2//! documentation, read once from the RAW embedded module sources
3//! (`loader::prelude_module_sources` — Notes included) through
4//! `teach::extract_literate_docs`. Hover, completion, and signature help
5//! fall back here when a name has no local definition, so `md5` teaches in
6//! the editor exactly what its `## Note` says in the source.
7
8use std::collections::HashMap;
9use std::sync::OnceLock;
10
11use logicaffeine_language::teach::extract_literate_docs;
12
13/// One stdlib definition's teaching surface.
14pub struct StdlibDoc {
15    /// The full `##` header (or `## Definition` body type line), verbatim.
16    pub signature: String,
17    /// The SUMMARY of the `## Note` directly above the definition: its first paragraph — one or
18    /// two short sentences, the line hover and completion lead with (the rustdoc convention).
19    /// `stdlib_teach_lock` holds every summary to ≤ 200 chars of plain prose.
20    pub doc: Option<String>,
21    /// The rest of the `## Note` (every paragraph after the first), rendered under the summary in
22    /// hover — the protocol tables, edge cases, and citations that make a note long.
23    pub details: Option<String>,
24    /// True for type definitions (`## A … has/is`), false for functions.
25    pub is_type: bool,
26}
27
28/// Split a `## Note` body into its summary paragraph and the remaining paragraphs.
29fn split_summary(note: Option<String>) -> (Option<String>, Option<String>) {
30    let Some(note) = note else {
31        return (None, None);
32    };
33    let note = note.trim();
34    match note.find("\n\n") {
35        Some(cut) => {
36            let details = note[cut..].trim();
37            (
38                Some(note[..cut].trim().to_string()),
39                (!details.is_empty()).then(|| details.to_string()),
40            )
41        }
42        None => (Some(note.to_string()), None),
43    }
44}
45
46fn registry() -> &'static HashMap<String, StdlibDoc> {
47    static DOCS: OnceLock<HashMap<String, StdlibDoc>> = OnceLock::new();
48    DOCS.get_or_init(|| {
49        let mut map = HashMap::new();
50        for src in logicaffeine_compile::loader::prelude_module_sources() {
51            for lit in extract_literate_docs(src) {
52                let is_type = !lit.signature.contains("## To");
53                let (doc, details) = split_summary(lit.doc);
54                map.entry(lit.name).or_insert(StdlibDoc {
55                    signature: lit.signature,
56                    doc,
57                    details,
58                    is_type,
59                });
60            }
61        }
62        // Enum VARIANTS teach through their enum: hovering `Ok` shows the
63        // variant's own line as the signature and Result's note as the prose.
64        let mut variants: Vec<(String, StdlibDoc)> = Vec::new();
65        for src in logicaffeine_compile::loader::prelude_module_sources() {
66            let mut current_enum: Option<String> = None;
67            for line in src.lines() {
68                let t = line.trim();
69                let article = t.strip_prefix("A ").or_else(|| t.strip_prefix("An "));
70                if !line.starts_with(' ') {
71                    // An enum header may carry a markdown `## ` prefix (`## A Json is either:`) or be
72                    // bare (`A Result … is either:`); both name the enum whose indented variants follow.
73                    let header = t.trim_start_matches('#').trim_start();
74                    let header_article = header
75                        .strip_prefix("A ")
76                        .or_else(|| header.strip_prefix("An "));
77                    current_enum = match header_article {
78                        Some(rest) if header.ends_with("is either:") => {
79                            rest.split_whitespace().next().map(|w| w.to_string())
80                        }
81                        _ => None,
82                    };
83                    continue;
84                }
85                if let (Some(enum_name), Some(rest)) = (&current_enum, article) {
86                    if let Some(name) = rest
87                        .split(|c: char| c == '(' || c == '.' || c.is_whitespace())
88                        .next()
89                        .filter(|w| w.chars().next().is_some_and(|c| c.is_ascii_uppercase()))
90                    {
91                        let (doc, details) = map
92                            .get(enum_name.as_str())
93                            .map(|d: &StdlibDoc| (d.doc.clone(), d.details.clone()))
94                            .unwrap_or((None, None));
95                        variants.push((
96                            name.to_string(),
97                            StdlibDoc {
98                                signature: t.to_string(),
99                                doc,
100                                details,
101                                is_type: true,
102                            },
103                        ));
104                    }
105                }
106            }
107        }
108        for (name, doc) in variants {
109            map.entry(name).or_insert(doc);
110        }
111        map
112    })
113}
114
115/// The teaching surface for a stdlib prelude name, if it is one.
116pub fn stdlib_doc(name: &str) -> Option<&'static StdlibDoc> {
117    registry().get(name)
118}
119
120/// Every stdlib name with its doc, name-sorted (completion feed).
121pub fn all() -> Vec<(&'static str, &'static StdlibDoc)> {
122    let mut entries: Vec<(&'static str, &'static StdlibDoc)> = registry()
123        .iter()
124        .map(|(name, doc)| (name.as_str(), doc))
125        .collect();
126    entries.sort_by_key(|(name, _)| *name);
127    entries
128}
129
130/// Hover markdown for a stdlib name: the signature as code, then the prose.
131pub fn hover_md(name: &str, entry: &StdlibDoc) -> String {
132    let mut md = format!(
133        "**{name}** — standard library\n\n```\n{}\n```",
134        entry.signature
135    );
136    if let Some(doc) = &entry.doc {
137        md.push_str("\n\n");
138        md.push_str(doc);
139    }
140    if let Some(details) = &entry.details {
141        md.push_str("\n\n");
142        md.push_str(details);
143    }
144    md
145}
146
147#[cfg(test)]
148#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/stdlib_docs/tests.rs"]
149mod tests;