Skip to main content

xur_runtime/
doc.rs

1//! A description of everything a [`Registry`] provides, for generated API
2//! docs: every module (lazy ones expanded), its functions with parameter
3//! names and types and return types, its types with their fields, variants,
4//! methods and Rust doc comments, and the methods of the built-in types.
5//!
6//! [`dump`] builds a [`DocTree`]; with the `serde` feature it serializes, so
7//! a tool can write it out as JSON.
8
9use facet::{StructType, Type, UserType};
10
11use xur_resolve::{NativeFnId, NativeTypeId};
12
13use crate::BuiltinType;
14use crate::registry::Registry;
15
16/// Everything a registry provides.
17#[derive(Debug, Clone, PartialEq)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize))]
19pub struct DocTree {
20    /// Every module, sorted by path, including modules with no items of
21    /// their own (they still group submodules).
22    pub modules: Vec<DocModule>,
23    /// The methods of built-in values (`str`, `list`, `bytes`, ...).
24    pub builtins: Vec<DocBuiltin>,
25}
26
27/// One module, `std::fs` say.
28#[derive(Debug, Clone, PartialEq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize))]
30pub struct DocModule {
31    /// The full path, `std::re::pe`.
32    pub path: String,
33    pub functions: Vec<DocFn>,
34    pub types: Vec<DocType>,
35}
36
37/// A function or method.
38#[derive(Debug, Clone, PartialEq)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize))]
40pub struct DocFn {
41    pub name: String,
42    /// The parameters after the receiver, for a method. Empty for a raw
43    /// function that names none (see `raw`).
44    pub params: Vec<DocParam>,
45    /// The return type, when known.
46    pub ret: Option<String>,
47    /// Whether it works on Xur values directly: it may take arguments its
48    /// `params` don't list, of any type.
49    pub raw: bool,
50}
51
52/// A parameter.
53#[derive(Debug, Clone, PartialEq)]
54#[cfg_attr(feature = "serde", derive(serde::Serialize))]
55pub struct DocParam {
56    pub name: Option<String>,
57    pub ty: Option<String>,
58    /// Whether it may be left out (only trailing parameters can be).
59    pub optional: bool,
60}
61
62/// A native type.
63#[derive(Debug, Clone, PartialEq)]
64#[cfg_attr(feature = "serde", derive(serde::Serialize))]
65pub struct DocType {
66    pub name: String,
67    /// `struct`, `enum` or `opaque`.
68    pub kind: &'static str,
69    /// The Rust doc comment on the type, if any.
70    pub doc: Option<String>,
71    pub fields: Vec<DocField>,
72    pub variants: Vec<DocVariant>,
73    /// Associated functions, `Type::name(..)`.
74    pub functions: Vec<DocFn>,
75    /// Methods, `value.name(..)`, without the receiver.
76    pub methods: Vec<DocFn>,
77}
78
79/// A struct field, or a field of an enum variant.
80#[derive(Debug, Clone, PartialEq)]
81#[cfg_attr(feature = "serde", derive(serde::Serialize))]
82pub struct DocField {
83    pub name: String,
84    pub ty: String,
85    pub doc: Option<String>,
86}
87
88/// An enum variant.
89#[derive(Debug, Clone, PartialEq)]
90#[cfg_attr(feature = "serde", derive(serde::Serialize))]
91pub struct DocVariant {
92    pub name: String,
93    pub fields: Vec<DocField>,
94    pub doc: Option<String>,
95}
96
97/// The methods of one kind of built-in value.
98#[derive(Debug, Clone, PartialEq)]
99#[cfg_attr(feature = "serde", derive(serde::Serialize))]
100pub struct DocBuiltin {
101    /// `str`, `list`, ...
102    pub name: String,
103    pub methods: Vec<DocFn>,
104}
105
106const BUILTINS: [BuiltinType; 12] = [
107    BuiltinType::Bool,
108    BuiltinType::Int,
109    BuiltinType::Float,
110    BuiltinType::Str,
111    BuiltinType::Tuple,
112    BuiltinType::List,
113    BuiltinType::Map,
114    BuiltinType::Bytes,
115    BuiltinType::Ptr,
116    BuiltinType::Range,
117    BuiltinType::Record,
118    BuiltinType::Struct,
119];
120
121/// Describes everything `registry` provides, expanding lazy modules. Modules
122/// whose path starts with one of `skip` (`std::test`, say) are left out.
123pub fn dump(registry: &Registry, skip: &[&str]) -> DocTree {
124    let mut modules = Vec::new();
125    for root in registry.decls() {
126        walk(registry, Vec::new(), root, skip, &mut modules);
127    }
128    modules.sort_by(|a, b| a.path.cmp(&b.path));
129    let builtins = BUILTINS
130        .iter()
131        .filter_map(|&ty| {
132            let mut methods: Vec<_> = registry
133                .builtin_methods(ty)
134                .iter()
135                .filter_map(|name| registry.builtin_method(ty, name))
136                .map(|id| describe_fn(registry, id, Receiver::Excluded))
137                .collect();
138            methods.sort_by(|a, b| a.name.cmp(&b.name));
139            (!methods.is_empty()).then(|| DocBuiltin {
140                name: ty.to_string(),
141                methods,
142            })
143        })
144        .collect();
145    DocTree { modules, builtins }
146}
147
148fn walk(
149    registry: &Registry,
150    mut path: Vec<String>,
151    module: xur_resolve::NativeModule,
152    skip: &[&str],
153    out: &mut Vec<DocModule>,
154) {
155    path.push(module.name.clone());
156    let joined = path.join("::");
157    if skip
158        .iter()
159        .any(|s| joined == *s || joined.starts_with(&format!("{s}::")))
160    {
161        return;
162    }
163    let module = if module.lazy {
164        registry.expand(&path)
165    } else {
166        module
167    };
168    let mut functions: Vec<_> = module
169        .functions
170        .iter()
171        .map(|decl| describe_fn(registry, decl.id, Receiver::None))
172        .collect();
173    functions.sort_by(|a, b| a.name.cmp(&b.name));
174    let mut types: Vec<_> = module
175        .types
176        .iter()
177        .map(|decl| describe_type(registry, decl.id, &decl.functions))
178        .collect();
179    types.sort_by(|a, b| a.name.cmp(&b.name));
180    out.push(DocModule {
181        path: joined,
182        functions,
183        types,
184    });
185    for child in module.modules {
186        walk(registry, path.clone(), child, skip, out);
187    }
188}
189
190/// Whether a function's signature starts with a receiver to leave out.
191#[derive(Clone, Copy, PartialEq)]
192enum Receiver {
193    /// A function: every parameter is listed.
194    None,
195    /// A native type's method: the signature's first parameter is `self`.
196    Included,
197    /// A built-in type's method: the signature has no receiver.
198    Excluded,
199}
200
201fn describe_fn(registry: &Registry, id: NativeFnId, receiver: Receiver) -> DocFn {
202    let f = registry.function(id);
203    let skip = usize::from(receiver == Receiver::Included);
204    let name_at = |i: usize| {
205        f.param_names
206            .get(i)
207            .filter(|n| !n.is_empty() && n.as_str() != "_")
208            .cloned()
209    };
210    let params = match &f.signature {
211        Some(sig) => sig
212            .param_types
213            .iter()
214            .enumerate()
215            .skip(skip)
216            .map(|(i, ty)| DocParam {
217                name: name_at(i),
218                ty: Some(registry.type_desc_name(ty)),
219                optional: i >= sig.required,
220            })
221            .collect(),
222        None => (skip..f.param_names.len())
223            .map(|i| DocParam {
224                name: name_at(i),
225                ty: None,
226                optional: false,
227            })
228            .collect(),
229    };
230    DocFn {
231        name: f.name.clone(),
232        params,
233        ret: registry.native_return_name(id),
234        raw: f.signature.is_none(),
235    }
236}
237
238fn describe_type(
239    registry: &Registry,
240    id: NativeTypeId,
241    decls: &[xur_resolve::NativeFnDecl],
242) -> DocType {
243    let shape = registry.type_shape(id);
244    let mut functions = Vec::new();
245    let mut methods = Vec::new();
246    for decl in decls {
247        let f = registry.function(decl.id);
248        let is_method = match &f.signature {
249            Some(sig) => sig.params.first() == Some(&shape),
250            None => f.param_names.first().is_some_and(|n| n == "self"),
251        };
252        if is_method {
253            methods.push(describe_fn(registry, decl.id, Receiver::Included));
254        } else {
255            functions.push(describe_fn(registry, decl.id, Receiver::None));
256        }
257    }
258    functions.sort_by(|a, b| a.name.cmp(&b.name));
259    methods.sort_by(|a, b| a.name.cmp(&b.name));
260    let (kind, fields, variants) = match shape.ty {
261        Type::User(UserType::Struct(st)) => ("struct", fields_of(registry, &st), Vec::new()),
262        Type::User(UserType::Enum(en)) => (
263            "enum",
264            Vec::new(),
265            en.variants
266                .iter()
267                .map(|v| DocVariant {
268                    name: v.name.to_string(),
269                    fields: fields_of(registry, &v.data),
270                    doc: doc_text(v.doc),
271                })
272                .collect(),
273        ),
274        _ => ("opaque", Vec::new(), Vec::new()),
275    };
276    DocType {
277        name: registry.type_name(id),
278        kind,
279        doc: doc_text(shape.doc),
280        fields,
281        variants,
282        functions,
283        methods,
284    }
285}
286
287fn fields_of(registry: &Registry, st: &StructType) -> Vec<DocField> {
288    st.fields
289        .iter()
290        .map(|field| DocField {
291            name: field.name.to_string(),
292            ty: registry.shape_xur_name(field.shape()),
293            doc: doc_text(field.doc),
294        })
295        .collect()
296}
297
298/// Joins a doc comment's lines (each with its leading space) into text.
299fn doc_text(lines: &[&str]) -> Option<String> {
300    let text = lines
301        .iter()
302        .map(|line| line.strip_prefix(' ').unwrap_or(line))
303        .collect::<Vec<_>>()
304        .join("\n");
305    let text = text.trim();
306    (!text.is_empty()).then(|| text.to_string())
307}
308
309#[cfg(test)]
310mod tests {
311    use facet::Facet;
312
313    use super::*;
314    use crate::{OptionalArg, XurStr};
315
316    /// A counter.
317    #[derive(Facet, Clone)]
318    struct Counter {
319        /// The count.
320        n: i64,
321    }
322
323    fn registry() -> Registry {
324        let registry = Registry::new();
325        registry.module("app").named_function(
326            "greet",
327            &["name", "times"],
328            |n: XurStr, _t: OptionalArg<i64>| n.to_string(),
329        );
330        registry
331            .module("app")
332            .ty::<Counter>("Counter")
333            .named_function("new", &["n"], |n: i64| Counter { n })
334            .named_method("add", &["by"], |c: &Counter, by: i64| c.n + by);
335        registry.lazy_module("app::later", |m| {
336            m.named_function("go", &["x"], |x: f64| x);
337        });
338        registry.lazy_module("app::test", |m| {
339            m.function("hidden", || 1i64);
340        });
341        registry.builtin(BuiltinType::Str).named_method(
342            "shout",
343            &["suffix"],
344            |s: &str, suffix: XurStr| format!("{}{}", s.to_uppercase(), &*suffix),
345        );
346        registry
347    }
348
349    #[test]
350    fn dumps_modules_functions_types_and_builtins() {
351        let tree = dump(&registry(), &["app::test"]);
352        let paths: Vec<_> = tree.modules.iter().map(|m| m.path.as_str()).collect();
353        assert_eq!(paths, ["app", "app::later"]);
354
355        let app = &tree.modules[0];
356        let greet = &app.functions[0];
357        assert_eq!(greet.name, "greet");
358        assert_eq!(
359            greet.params,
360            [
361                DocParam {
362                    name: Some("name".into()),
363                    ty: Some("str".into()),
364                    optional: false
365                },
366                DocParam {
367                    name: Some("times".into()),
368                    ty: Some("i64".into()),
369                    optional: true
370                },
371            ]
372        );
373        assert_eq!(greet.ret.as_deref(), Some("str"));
374
375        let counter = &app.types[0];
376        assert_eq!(counter.kind, "struct");
377        assert_eq!(counter.doc.as_deref(), Some("A counter."));
378        assert_eq!(counter.fields[0].ty, "i64");
379        assert_eq!(counter.fields[0].doc.as_deref(), Some("The count."));
380        assert_eq!(counter.functions[0].name, "new");
381        let add = &counter.methods[0];
382        assert_eq!(add.name, "add");
383        assert_eq!(add.params.len(), 1);
384        assert_eq!(add.params[0].name.as_deref(), Some("by"));
385
386        assert_eq!(tree.modules[1].functions[0].name, "go");
387
388        let str_methods = &tree
389            .builtins
390            .iter()
391            .find(|b| b.name == "str")
392            .unwrap()
393            .methods;
394        assert_eq!(str_methods[0].name, "shout");
395        assert_eq!(str_methods[0].params[0].name.as_deref(), Some("suffix"));
396    }
397}