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