Skip to main content

reflex/pulse/build/
reference.rs

1//! The API reference: one page per public module, one per public type.
2//!
3//! ```text
4//! Reference
5//! └─ my_lib                 module page: docs, submodules, types, functions, constants
6//!    ├─ Engine              type page: definition, fields/variants, methods, trait impls
7//!    └─ api                 module page
8//!       └─ Thing            type page
9//! ```
10//! Doc comments keep their markdown. Rustdoc's hidden example lines are removed and
11//! intra-doc links (`` [`Foo`] ``, `[Self::new]`, `[x](crate::a::B)`) become links to
12//! the symbol's page, resolved from the item's scope like rustdoc does.
13
14use super::{PageSpec, SiteBuilder};
15use crate::parsers::api::{ApiItem, ApiKind, DocComment, Visibility};
16use crate::pulse::extract::surface::{Package, Surface, SurfaceItem};
17use crate::pulse::model::ids::slugify;
18use crate::pulse::model::{
19    AnchorId, Block, Inline, MarkdownOrigin, MarkdownText, NavNode, PageId, PageKind, ParamRow,
20    SourceLoc, SymbolBlock, SymbolEntry, SymbolId, TabId, Target,
21};
22use std::collections::{BTreeMap, HashMap};
23use std::sync::LazyLock;
24
25use super::links::SYMBOL_SCHEME;
26
27/// Longest signature kept on one line.
28const SIGNATURE_WIDTH: usize = 90;
29
30/// Tidy a whitespace-collapsed signature, and wrap a long `fn` (or Python `def`) one
31/// like rustfmt: one parameter per line, `where` on its own line.
32pub fn pretty_signature(sig: &str) -> String {
33    let mut s = sig
34        .replace("( ", "(")
35        .replace(" )", ")")
36        .replace(",)", ")")
37        .replace("< ", "<")
38        .replace(" >", ">");
39    while s.contains(", )") {
40        s = s.replace(", )", ")");
41    }
42    if s.chars().count() <= SIGNATURE_WIDTH {
43        return s;
44    }
45    let Some(fn_at) = s.find("fn ").or_else(|| s.find("def ")) else {
46        return s;
47    };
48    // The parameter list opens at the first `(` outside the generics after the name.
49    let bytes = s.as_bytes();
50    let mut depth = 0i32;
51    let mut open = None;
52    for (i, &b) in bytes.iter().enumerate().skip(fn_at) {
53        match b {
54            b'<' => depth += 1,
55            b'>' if i > 0 && bytes[i - 1] != b'-' => depth -= 1,
56            b'(' if depth == 0 => {
57                open = Some(i);
58                break;
59            }
60            _ => {}
61        }
62    }
63    let Some(open) = open else {
64        return s;
65    };
66    let mut depth = 0i32;
67    let mut close = None;
68    let mut parts = Vec::new();
69    let mut last = open + 1;
70    for (i, &b) in bytes.iter().enumerate().skip(open + 1) {
71        match b {
72            b'(' | b'[' | b'{' | b'<' => depth += 1,
73            b'>' if bytes[i - 1] == b'-' => {}
74            b')' if depth == 0 => {
75                close = Some(i);
76                break;
77            }
78            b')' | b']' | b'}' | b'>' => depth -= 1,
79            b',' if depth == 0 => {
80                parts.push(s[last..i].trim().to_string());
81                last = i + 1;
82            }
83            _ => {}
84        }
85    }
86    let Some(close) = close else {
87        return s;
88    };
89    let tail = s[last..close].trim();
90    if !tail.is_empty() {
91        parts.push(tail.to_string());
92    }
93    let mut out = s[..=open].to_string();
94    for p in &parts {
95        out.push_str(&format!("\n    {p},"));
96    }
97    if !parts.is_empty() {
98        out.push('\n');
99    }
100    let rest = &s[close..];
101    match rest.split_once(" where ") {
102        Some((before, clauses)) => {
103            out.push_str(before);
104            out.push_str("\nwhere\n");
105            for c in clauses.split(", ").filter(|c| !c.is_empty()) {
106                out.push_str(&format!("    {},\n", c.trim_end_matches(',')));
107            }
108            out.truncate(out.trim_end().len());
109        }
110        None => out.push_str(rest),
111    }
112    out
113}
114
115/// Which parts of the library surface to document.
116#[derive(Debug, Clone, Default)]
117pub struct ReferenceOptions {
118    /// Leave the library reference out (a CLI-first project).
119    pub skip_library: bool,
120    /// Only modules whose path starts with one of these (`reflex::query`). Empty = all.
121    pub include: Vec<String>,
122}
123
124fn sym_id(lang: &str, path: &str, kind: ApiKind) -> SymbolId {
125    SymbolId(format!("{lang}:{path}#{}", kind.label().replace(' ', "-")))
126}
127
128fn anchor(kind: ApiKind, name: &str) -> AnchorId {
129    AnchorId(format!(
130        "{}.{}",
131        slugify(kind.label()),
132        name.to_ascii_lowercase()
133            .chars()
134            .filter(|c| c.is_ascii_alphanumeric() || *c == '_')
135            .collect::<String>()
136    ))
137}
138
139fn module_page(path: &str) -> PageId {
140    PageId(format!("docs/ref/mod/{path}"))
141}
142
143fn type_page(path: &str) -> PageId {
144    PageId(format!("docs/ref/type/{path}"))
145}
146
147fn path_slug(path: &str, sep: &str) -> String {
148    // Go package paths (`kv/sub`) keep their directories as URL segments.
149    path.split(sep)
150        .flat_map(|s| s.split('/'))
151        .map(slugify)
152        .collect::<Vec<_>>()
153        .join("/")
154}
155
156/// Whether an item gets its own page: types, and named types that have methods
157/// (a Go `type Kind int` with `String()`).
158fn has_page(item: &ApiItem) -> bool {
159    item.kind.is_type() || (item.kind == ApiKind::TypeAlias && !item.members.is_empty())
160}
161
162/// Build the library reference and return its nav nodes (one group per crate).
163pub fn build(b: &mut SiteBuilder, api: &Surface, opts: &ReferenceOptions) -> Vec<NavNode> {
164    if opts.skip_library {
165        return Vec::new();
166    }
167    let mut nav = Vec::new();
168    for k in api.libraries() {
169        let included = |path: &str| {
170            let nested = |a: &str, b: &str| {
171                a.starts_with(&format!("{b}{}", k.sep)) || a.starts_with(&format!("{b}/"))
172            };
173            opts.include.is_empty()
174                || opts
175                    .include
176                    .iter()
177                    .any(|p| path == p || nested(path, p) || nested(p, path))
178        };
179        let modules: Vec<usize> = (0..k.modules.len())
180            .filter(|&i| k.modules[i].public && included(&k.modules[i].path))
181            .collect();
182        if modules.is_empty() {
183            continue;
184        }
185        let index = SymbolIndex::build(k, &modules, b);
186        let mut crate_nav = Vec::new();
187        for &mi in &modules {
188            let m = &k.modules[mi];
189            let types: Vec<&SurfaceItem> = public_items(k, mi)
190                .filter(|it| has_page(&it.item))
191                .collect();
192            let mut group = vec![NavNode::page(&module_page(&m.path))];
193            for t in &types {
194                let blocks = type_blocks(k, t, &index);
195                let summary = t.item.doc.as_ref().map(|d| plain(&d.summary));
196                b.add_page(PageSpec {
197                    id: type_page(&t.path),
198                    tab: TabId::Docs,
199                    kind: PageKind::ReferenceType {
200                        path: t.path.clone(),
201                    },
202                    title: t.item.name.clone(),
203                    description: summary.filter(|s| !s.is_empty()),
204                    slug: Some(format!("reference/{}", path_slug(&t.path, k.sep))),
205                    badges: badges_for(&t.item),
206                    blocks,
207                });
208                group.push(NavNode::page(&type_page(&t.path)));
209            }
210            let blocks = module_blocks(k, mi, &modules, &index);
211            b.add_page(PageSpec {
212                id: module_page(&m.path),
213                tab: TabId::Docs,
214                kind: PageKind::ReferenceModule {
215                    path: m.path.clone(),
216                },
217                title: m.path.clone(),
218                description: m
219                    .doc
220                    .as_ref()
221                    .map(|d| plain(&d.summary))
222                    .filter(|s| !s.is_empty()),
223                slug: Some(format!("reference/{}", path_slug(&m.path, k.sep))),
224                badges: vec!["module".into()],
225                blocks,
226            });
227            if mi == 0 {
228                crate_nav.extend(group);
229            } else {
230                crate_nav.push(NavNode::Group {
231                    label: m
232                        .path
233                        .strip_prefix(&format!("{}{}", k.name, k.sep))
234                        .or_else(|| m.path.strip_prefix(&format!("{}/", k.name)))
235                        .unwrap_or(&m.path)
236                        .to_string(),
237                    collapsed: true,
238                    children: group,
239                });
240            }
241        }
242        b.symbols.extend(index.entries);
243        nav.push(NavNode::Group {
244            label: k.name.clone(),
245            collapsed: false,
246            children: crate_nav,
247        });
248    }
249    nav
250}
251
252fn public_items(k: &Package, mi: usize) -> impl Iterator<Item = &SurfaceItem> {
253    k.modules[mi].items.iter().filter(|it| it.public)
254}
255
256/// Documented symbols of one crate, for the registry and for intra-doc links.
257struct SymbolIndex {
258    entries: BTreeMap<SymbolId, SymbolEntry>,
259    by_path: HashMap<String, SymbolId>,
260    by_name: HashMap<String, Vec<SymbolId>>,
261    crate_name: String,
262    lang: String,
263    sep: &'static str,
264}
265
266impl SymbolIndex {
267    fn build(k: &Package, modules: &[usize], _b: &SiteBuilder) -> Self {
268        let mut idx = Self {
269            entries: BTreeMap::new(),
270            by_path: HashMap::new(),
271            by_name: HashMap::new(),
272            crate_name: k.name.clone(),
273            lang: k.lang_id(),
274            sep: k.sep,
275        };
276        for &mi in modules {
277            let m = &k.modules[mi];
278            idx.add(
279                &m.path,
280                &m.name,
281                ApiKind::Module,
282                module_page(&m.path),
283                None,
284            );
285            for it in public_items(k, mi) {
286                if has_page(&it.item) {
287                    let page = type_page(&it.path);
288                    idx.add(&it.path, &it.item.name, it.item.kind, page.clone(), None);
289                    for mem in documented_members(&it.item) {
290                        idx.add(
291                            &k.join(&it.path, &mem.name),
292                            &mem.name,
293                            mem.kind,
294                            page.clone(),
295                            Some(anchor(mem.kind, &mem.name)),
296                        );
297                    }
298                } else {
299                    idx.add(
300                        &it.path,
301                        &it.item.name,
302                        it.item.kind,
303                        module_page(&m.path),
304                        Some(anchor(it.item.kind, &it.item.name)),
305                    );
306                }
307            }
308        }
309        idx
310    }
311
312    fn add(
313        &mut self,
314        path: &str,
315        name: &str,
316        kind: ApiKind,
317        page: PageId,
318        anchor: Option<AnchorId>,
319    ) {
320        let id = sym_id(&self.lang, path, kind);
321        self.by_path
322            .entry(path.to_string())
323            .or_insert_with(|| id.clone());
324        self.by_name
325            .entry(name.to_string())
326            .or_default()
327            .push(id.clone());
328        self.entries.insert(
329            id,
330            SymbolEntry {
331                name: name.to_string(),
332                path: path.to_string(),
333                kind: kind.label().to_string(),
334                page,
335                anchor,
336            },
337        );
338    }
339
340    /// Resolve an intra-doc link written in `module` (and inside `self_type`, if any),
341    /// the way rustdoc does for Rust; other languages use the same scopes.
342    fn resolve(&self, link: &str, module: &str, self_type: Option<&str>) -> Option<&SymbolId> {
343        let sep = self.sep;
344        let link = link.trim_end_matches("()").trim_end_matches('!');
345        let j = |a: &str, b: &str| format!("{a}{sep}{b}");
346        let try_path = |p: &str| self.by_path.get(p);
347        if sep == "::" {
348            if let Some(rest) = link.strip_prefix("Self::") {
349                return self_type.and_then(|t| try_path(&j(t, rest)));
350            }
351            if let Some(rest) = link.strip_prefix("crate::") {
352                return try_path(&j(&self.crate_name, rest));
353            }
354            if let Some(rest) = link.strip_prefix("self::") {
355                return try_path(&j(module, rest));
356            }
357            if let Some(rest) = link.strip_prefix("super::") {
358                let parent = module.rsplit_once(sep).map(|(p, _)| p)?;
359                return try_path(&j(parent, rest));
360            }
361        }
362        if let Some(t) = self_type
363            && let Some(id) = try_path(&j(t, link))
364        {
365            return Some(id);
366        }
367        try_path(&j(module, link))
368            .or_else(|| try_path(link))
369            .or_else(|| try_path(&j(&self.crate_name, link)))
370            .or_else(|| {
371                // A bare name that is unique in the package.
372                let name = link.rsplit(sep).next().unwrap_or(link);
373                match self.by_name.get(name).map(Vec::as_slice) {
374                    Some([only]) => Some(only),
375                    _ => None,
376                }
377            })
378    }
379}
380
381/// Members documented on a type page: fields, variants, public methods, associated items.
382fn documented_members(item: &ApiItem) -> impl Iterator<Item = &ApiItem> {
383    documented_members_indexed(item).map(|(_, m)| m)
384}
385
386fn documented_members_indexed(item: &ApiItem) -> impl Iterator<Item = (usize, &ApiItem)> {
387    item.members.iter().enumerate().filter(|(_, m)| {
388        !m.test_only
389            && !m.hidden
390            && match m.kind {
391                ApiKind::Field => {
392                    m.visibility == Visibility::Public || m.visibility == Visibility::Inherited
393                }
394                ApiKind::Variant => true,
395                _ => m.trait_impl.is_none() && m.visibility.is_public(),
396            }
397    })
398}
399
400fn plain(md: &str) -> String {
401    md.replace(['`', '*'], "").replace("[", "").replace("]", "")
402}
403
404fn badges_for(item: &ApiItem) -> Vec<String> {
405    let mut v = vec![item.kind.label().to_string()];
406    v.extend(attr_badges(item));
407    if item.deprecated.is_some() {
408        v.push("deprecated".into());
409    }
410    v
411}
412
413/// Badges a Python decorator or dunder earns (`@classmethod` → `classmethod`).
414fn attr_badges(item: &ApiItem) -> Vec<String> {
415    let mut v: Vec<String> = Vec::new();
416    for a in &item.attrs {
417        let callee = a.split('(').next().unwrap_or(a).trim();
418        let badge = match callee.rsplit('.').next().unwrap_or(callee) {
419            "classmethod" => "classmethod",
420            "staticmethod" => "staticmethod",
421            "property" | "cached_property" => "property",
422            "abstractmethod" | "abstractproperty" => "abstract",
423            "dataclass" => "dataclass",
424            _ => continue,
425        };
426        if !v.iter().any(|b| b == badge) {
427            v.push(badge.to_string());
428        }
429    }
430    if item.kind == ApiKind::Method && item.name == "__init__" {
431        v.push("constructor".into());
432    }
433    v
434}
435
436static INTRA_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
437    regex::Regex::new(
438        r"\[(`?)([A-Za-z_][\w:.]*(?:\(\)|!)?)(`?)\](\(([A-Za-z_][\w]*(?:::[\w]+)*(?:\(\)|!)?)\))?",
439    )
440    .expect("valid regex")
441});
442
443/// [`INTRA_RE`] for dot-separated packages (Python): `` [`pkg.mod.Foo`] ``, `[x](pkg.Foo)`.
444static INTRA_DOT_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
445    regex::Regex::new(
446        r"\[(`?)([A-Za-z_][\w.]*(?:\(\))?)(`?)\](\(([A-Za-z_][\w]*(?:\.[\w]+)*(?:\(\))?)\))?",
447    )
448    .expect("valid regex")
449});
450
451/// Remove rustdoc hidden lines from rust fences, tag bare fences as `rust`, and turn
452/// intra-doc links into `pulse-symbol:` links.
453fn render_doc(
454    doc: &DocComment,
455    index: &SymbolIndex,
456    module: &str,
457    self_type: Option<&str>,
458    file: &str,
459) -> MarkdownText {
460    let mut out = Vec::new();
461    let mut fence: Option<bool> = None; // Some(is_rust)
462    for line in doc.markdown.lines() {
463        let t = line.trim_start();
464        let is_fence = t.starts_with("```") || t.starts_with("~~~");
465        match (&fence, is_fence) {
466            (None, true) => {
467                let info = t.trim_start_matches(['`', '~']).trim();
468                // Rustdoc fences (bare, `rust`, `no_run`, …) hide `# ` lines; in other
469                // languages a bare fence is code in the package's own language.
470                let is_rust = index.lang == "rust";
471                let rusty = is_rust
472                    && (info.is_empty()
473                        || info.split(',').all(|a| {
474                            a.trim().starts_with("rust")
475                                || matches!(
476                                    a.trim(),
477                                    "ignore" | "no_run" | "should_panic" | "compile_fail"
478                                )
479                                || a.trim().starts_with("edition")
480                        }));
481                fence = Some(rusty);
482                out.push(if rusty {
483                    "```rust".to_string()
484                } else if info.is_empty() {
485                    format!("```{}", index.lang)
486                } else {
487                    line.to_string()
488                });
489            }
490            (Some(_), true) => {
491                fence = None;
492                out.push("```".to_string());
493            }
494            (Some(true), false) => {
495                if t == "#" || t.starts_with("# ") {
496                    continue;
497                }
498                out.push(if t.starts_with("##") {
499                    line.replacen("##", "#", 1)
500                } else {
501                    line.to_string()
502                });
503            }
504            (Some(false), false) => out.push(line.to_string()),
505            (None, false) => {
506                let re = if index.sep == "." {
507                    &*INTRA_DOT_RE
508                } else {
509                    &*INTRA_RE
510                };
511                let rewritten = re.replace_all(line, |c: &regex::Captures| {
512                    let whole = c.get(0).unwrap().as_str();
513                    let (tick, text, dest) = (&c[1], &c[2], c.get(5).map(|m| m.as_str()));
514                    // `[text](https://…)` never matches; a bare `[word]` needs a path shape.
515                    let target = dest.unwrap_or(text);
516                    if dest.is_none() && tick.is_empty() && !text.contains(index.sep) {
517                        return whole.to_string();
518                    }
519                    // `.` separates paths only where it is the package separator (Go).
520                    if index.sep != "." && text.contains('.') {
521                        return whole.to_string();
522                    }
523                    match index.resolve(target, module, self_type) {
524                        Some(id) => format!("[{tick}{text}{tick}]({SYMBOL_SCHEME}{})", id.0),
525                        None if !tick.is_empty() => format!("`{text}`"),
526                        None => whole.to_string(),
527                    }
528                });
529                out.push(rewritten.into_owned());
530            }
531        }
532    }
533    MarkdownText {
534        source: out.join("\n"),
535        origin: MarkdownOrigin::Comment,
536        from: Some(SourceLoc::lines(file, doc.start_line, doc.end_line)),
537    }
538}
539
540fn symbol_block(
541    item: &ApiItem,
542    path: &str,
543    file: &str,
544    index: &SymbolIndex,
545    module: &str,
546    self_type: Option<&str>,
547) -> Block {
548    let sig = item.sig.as_ref();
549    let mut badges = Vec::new();
550    if let Some(s) = sig {
551        for (on, label) in [
552            (s.is_const, "const"),
553            (s.is_async, "async"),
554            (s.is_unsafe, "unsafe"),
555        ] {
556            if on {
557                badges.push(label.to_string());
558            }
559        }
560    }
561    badges.extend(attr_badges(item));
562    let deprecated = item.deprecated.as_ref().map(|d| {
563        let mut s = String::from("Deprecated");
564        if let Some(v) = &d.since {
565            s.push_str(&format!(" since {v}"));
566        }
567        if let Some(n) = &d.note {
568            s.push_str(&format!(": {n}"));
569        }
570        s
571    });
572    Block::Symbol {
573        symbol: Box::new(SymbolBlock {
574            id: sym_id(&index.lang, path, item.kind),
575            anchor: anchor(item.kind, &item.name),
576            kind: item.kind.label().to_string(),
577            name: item.name.clone(),
578            lang: index.lang.clone(),
579            signature: pretty_signature(&item.signature),
580            doc: item
581                .doc
582                .as_ref()
583                .map(|d| render_doc(d, index, module, self_type, file)),
584            params: sig
585                .map(|s| {
586                    s.params
587                        .iter()
588                        .map(|p| ParamRow {
589                            name: p.name.clone(),
590                            ty: p.ty.clone(),
591                        })
592                        .collect()
593                })
594                .unwrap_or_default(),
595            returns: sig.and_then(|s| s.returns.clone()),
596            deprecated,
597            badges,
598            source: SourceLoc::lines(file, item.start_line, item.end_line),
599        }),
600    }
601}
602
603fn summary_cell(
604    doc: Option<&DocComment>,
605    index: &SymbolIndex,
606    module: &str,
607    file: &str,
608) -> Vec<Inline> {
609    match doc {
610        Some(d) if !d.summary.is_empty() => {
611            let one = DocComment {
612                markdown: d.summary.clone(),
613                ..d.clone()
614            };
615            let md = render_doc(&one, index, module, None, file).source;
616            vec![Inline::text(plain(&md))]
617        }
618        _ => vec![],
619    }
620}
621
622fn module_blocks(k: &Package, mi: usize, included: &[usize], index: &SymbolIndex) -> Vec<Block> {
623    let m = &k.modules[mi];
624    let mut blocks = Vec::new();
625    if let Some(d) = &m.doc {
626        blocks.push(Block::Markdown {
627            markdown: render_doc(d, index, &m.path, None, &m.file),
628        });
629    }
630    let children: Vec<usize> = m
631        .children
632        .iter()
633        .copied()
634        .filter(|c| included.contains(c))
635        .collect();
636    if !children.is_empty() {
637        blocks.push(Block::heading(2, "Modules"));
638        blocks.push(Block::Table {
639            columns: vec!["Module".into(), "Summary".into()],
640            rows: children
641                .iter()
642                .map(|&c| {
643                    let cm = &k.modules[c];
644                    vec![
645                        vec![Inline::code_link(
646                            Target::page(module_page(&cm.path)),
647                            &cm.name,
648                        )],
649                        summary_cell(cm.doc.as_ref(), index, &cm.path, &cm.file),
650                    ]
651                })
652                .collect(),
653        });
654    }
655
656    let items: Vec<&SurfaceItem> = public_items(k, mi).collect();
657    let types: Vec<&&SurfaceItem> = items.iter().filter(|it| has_page(&it.item)).collect();
658    if !types.is_empty() {
659        blocks.push(Block::heading(2, "Types"));
660        blocks.push(Block::Table {
661            columns: vec!["Name".into(), "Kind".into(), "Summary".into()],
662            rows: types
663                .iter()
664                .map(|it| {
665                    vec![
666                        vec![Inline::code_link(
667                            Target::page(type_page(&it.path)),
668                            &it.item.name,
669                        )],
670                        vec![Inline::text(it.item.kind.label())],
671                        summary_cell(it.item.doc.as_ref(), index, &m.path, &it.file),
672                    ]
673                })
674                .collect(),
675        });
676    }
677    for (kind, title) in [
678        (ApiKind::Function, "Functions"),
679        (ApiKind::Macro, "Macros"),
680        (ApiKind::Const, "Constants"),
681        (ApiKind::Static, "Statics"),
682        (ApiKind::TypeAlias, type_alias_title(k)),
683    ] {
684        let group: Vec<&&SurfaceItem> = items
685            .iter()
686            .filter(|it| it.item.kind == kind && !has_page(&it.item))
687            .collect();
688        if group.is_empty() {
689            continue;
690        }
691        blocks.push(Block::heading(2, title));
692        for it in group {
693            blocks.push(symbol_block(
694                &it.item, &it.path, &it.file, index, &m.path, None,
695            ));
696        }
697    }
698    if blocks.is_empty() {
699        blocks.push(Block::text("This module has no public items."));
700    }
701    blocks
702}
703
704/// Go has no aliases in the Rust sense: `type Kind int` is a new type.
705fn type_alias_title(k: &Package) -> &'static str {
706    if k.lang == crate::models::Language::Go {
707        "Other types"
708    } else {
709        "Type aliases"
710    }
711}
712
713fn type_blocks(k: &Package, t: &SurfaceItem, index: &SymbolIndex) -> Vec<Block> {
714    let module = t.path.rsplit_once(k.sep).map(|(m, _)| m).unwrap_or(&k.name);
715    // The page is the type: its definition renders flat, not as a card under its own title.
716    let mut blocks = vec![Block::Code {
717        lang: k.lang_id(),
718        code: pretty_signature(&t.item.signature),
719        title: None,
720    }];
721    if let Some(d) = &t.item.deprecated {
722        let mut msg = String::from("Deprecated");
723        if let Some(v) = &d.since {
724            msg.push_str(&format!(" since {v}"));
725        }
726        if let Some(n) = &d.note {
727            msg.push_str(&format!(": {n}"));
728        }
729        blocks.push(Block::Callout {
730            kind: crate::pulse::model::content::CalloutKind::Caution,
731            title: Some("Deprecated".into()),
732            body: vec![Block::text(msg)],
733        });
734    }
735    if let Some(doc) = &t.item.doc {
736        blocks.push(Block::Markdown {
737            markdown: render_doc(doc, index, module, Some(&t.path), &t.file),
738        });
739    }
740    let def = SourceLoc::lines(&t.file, t.item.start_line, t.item.end_line);
741    blocks.push(Block::para(vec![
742        Inline::text("Defined in "),
743        Inline::code_link(Target::Source { loc: def.clone() }, def.label()),
744        Inline::text("."),
745    ]));
746    if let Some(def) = &t.defined_at {
747        blocks.push(Block::note(format!("Re-exported here; defined as {def}.")));
748    }
749
750    let members: Vec<&ApiItem> = documented_members(&t.item).collect();
751    let data: Vec<&&ApiItem> = members
752        .iter()
753        .filter(|m| matches!(m.kind, ApiKind::Field | ApiKind::Variant))
754        .collect();
755    if !data.is_empty() {
756        let title = match t.item.kind {
757            ApiKind::Enum => "Variants",
758            ApiKind::Interface => "Embedded interfaces",
759            _ => "Fields",
760        };
761        blocks.push(Block::heading(2, title));
762        for m in data {
763            blocks.push(symbol_block(
764                m,
765                &k.join(&t.path, &m.name),
766                &t.file,
767                index,
768                module,
769                Some(&t.path),
770            ));
771        }
772    }
773
774    let methods: Vec<(usize, &ApiItem)> = documented_members_indexed(&t.item)
775        .filter(|(_, m)| !matches!(m.kind, ApiKind::Field | ApiKind::Variant))
776        .collect();
777    if !methods.is_empty() {
778        let title = if t.item.kind == ApiKind::Trait {
779            "Trait items"
780        } else {
781            "Methods"
782        };
783        blocks.push(Block::heading(2, title));
784        for (i, m) in methods {
785            // Members from `impl` blocks may live in another file.
786            let file = t.impl_files.get(&i).map(String::as_str).unwrap_or(&t.file);
787            blocks.push(symbol_block(
788                m,
789                &k.join(&t.path, &m.name),
790                file,
791                index,
792                module,
793                Some(&t.path),
794            ));
795        }
796    }
797
798    let mut traits: Vec<&str> = t
799        .item
800        .members
801        .iter()
802        .filter_map(|m| m.trait_impl.as_deref())
803        .collect();
804    traits.sort_unstable();
805    traits.dedup();
806    if !traits.is_empty() {
807        blocks.push(Block::heading(2, "Trait implementations"));
808        blocks.push(Block::List {
809            ordered: false,
810            items: traits
811                .iter()
812                .map(|tr| {
813                    let base = tr.split('<').next().unwrap_or(tr);
814                    let code = format!("impl {tr} for {}", t.item.name);
815                    match index.resolve(base, module, None) {
816                        Some(id) => vec![Inline::code_link(
817                            Target::Symbol { symbol: id.clone() },
818                            code,
819                        )],
820                        None => vec![Inline::code(code)],
821                    }
822                })
823                .collect(),
824        });
825    }
826    blocks
827}
828
829#[cfg(test)]
830mod signature_tests {
831    use super::pretty_signature;
832
833    #[test]
834    fn short_signatures_are_tidied() {
835        assert_eq!(pretty_signature("pub fn f( a: u8, )"), "pub fn f(a: u8)");
836        assert_eq!(pretty_signature("pub struct S< T >"), "pub struct S<T>");
837    }
838
839    #[test]
840    fn long_signatures_wrap_like_rustfmt() {
841        let s = "pub fn search_with_metadata( &self, pattern: &str, filter: QueryFilter, ) -> Result<QueryResponse, Error> where F: Fn(u8) -> u8";
842        assert_eq!(
843            pretty_signature(s),
844            "pub fn search_with_metadata(\n    &self,\n    pattern: &str,\n    filter: QueryFilter,\n) -> Result<QueryResponse, Error>\nwhere\n    F: Fn(u8) -> u8,"
845        );
846        let g = "pub fn run<T: Into<String>, F: Fn(T) -> T>(input: Vec<(T, u8)>, callback: F, extra_argument_name: HashMap<String, u8>) -> T";
847        let out = pretty_signature(g);
848        assert!(
849            out.starts_with(
850                "pub fn run<T: Into<String>, F: Fn(T) -> T>(\n    input: Vec<(T, u8)>,\n"
851            ),
852            "{out}"
853        );
854        assert!(out.ends_with(") -> T"), "{out}");
855    }
856}