xur-runtime 0.1.7

Values, native-function registry and facet conversions for the Xur language
Documentation
//! A description of everything a [`Registry`] provides, for generated API
//! docs: every module (lazy ones expanded), its functions with parameter
//! names and types and return types, its types with their fields, variants,
//! methods and Rust doc comments, and the methods of the built-in types.
//!
//! [`dump`] builds a [`DocTree`]; with the `serde` feature it serializes, so
//! a tool can write it out as JSON.

use facet::{StructType, Type, UserType};

use xur_resolve::{NativeFnId, NativeTypeId};

use crate::BuiltinType;
use crate::registry::Registry;

/// Everything a registry provides.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocTree {
    /// Every module, sorted by path, including modules with no items of
    /// their own (they still group submodules).
    pub modules: Vec<DocModule>,
    /// The methods of built-in values (`str`, `list`, `bytes`, ...).
    pub builtins: Vec<DocBuiltin>,
}

/// One module, `std::fs` say.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocModule {
    /// The full path, `std::re::pe`.
    pub path: String,
    pub functions: Vec<DocFn>,
    pub types: Vec<DocType>,
}

/// A function or method.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocFn {
    pub name: String,
    /// The parameters after the receiver, for a method. Empty for a raw
    /// function that names none (see `raw`).
    pub params: Vec<DocParam>,
    /// The return type, when known.
    pub ret: Option<String>,
    /// Whether it works on Xur values directly: it may take arguments its
    /// `params` don't list, of any type.
    pub raw: bool,
}

/// A parameter.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocParam {
    pub name: Option<String>,
    pub ty: Option<String>,
    /// Whether it may be left out (only trailing parameters can be).
    pub optional: bool,
}

/// A native type.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocType {
    pub name: String,
    /// `struct`, `enum` or `opaque`.
    pub kind: &'static str,
    /// The Rust doc comment on the type, if any.
    pub doc: Option<String>,
    pub fields: Vec<DocField>,
    pub variants: Vec<DocVariant>,
    /// Associated functions, `Type::name(..)`.
    pub functions: Vec<DocFn>,
    /// Methods, `value.name(..)`, without the receiver.
    pub methods: Vec<DocFn>,
}

/// A struct field, or a field of an enum variant.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocField {
    pub name: String,
    pub ty: String,
    pub doc: Option<String>,
}

/// An enum variant.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocVariant {
    pub name: String,
    pub fields: Vec<DocField>,
    pub doc: Option<String>,
}

/// The methods of one kind of built-in value.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocBuiltin {
    /// `str`, `list`, ...
    pub name: String,
    pub methods: Vec<DocFn>,
}

const BUILTINS: [BuiltinType; 12] = [
    BuiltinType::Bool,
    BuiltinType::Int,
    BuiltinType::Float,
    BuiltinType::Str,
    BuiltinType::Tuple,
    BuiltinType::List,
    BuiltinType::Map,
    BuiltinType::Bytes,
    BuiltinType::Ptr,
    BuiltinType::Range,
    BuiltinType::Record,
    BuiltinType::Struct,
];

/// Describes everything `registry` provides, expanding lazy modules. Modules
/// whose path starts with one of `skip` (`std::test`, say) are left out.
pub fn dump(registry: &Registry, skip: &[&str]) -> DocTree {
    let mut modules = Vec::new();
    for root in registry.decls() {
        walk(registry, Vec::new(), root, skip, &mut modules);
    }
    modules.sort_by(|a, b| a.path.cmp(&b.path));
    let builtins = BUILTINS
        .iter()
        .filter_map(|&ty| {
            let mut methods: Vec<_> = registry
                .builtin_methods(ty)
                .iter()
                .filter_map(|name| registry.builtin_method(ty, name))
                .map(|id| describe_fn(registry, id, Receiver::Excluded))
                .collect();
            methods.sort_by(|a, b| a.name.cmp(&b.name));
            (!methods.is_empty()).then(|| DocBuiltin {
                name: ty.to_string(),
                methods,
            })
        })
        .collect();
    DocTree { modules, builtins }
}

fn walk(
    registry: &Registry,
    mut path: Vec<String>,
    module: xur_resolve::NativeModule,
    skip: &[&str],
    out: &mut Vec<DocModule>,
) {
    path.push(module.name.clone());
    let joined = path.join("::");
    if skip
        .iter()
        .any(|s| joined == *s || joined.starts_with(&format!("{s}::")))
    {
        return;
    }
    let module = if module.lazy {
        registry.expand(&path)
    } else {
        module
    };
    let mut functions: Vec<_> = module
        .functions
        .iter()
        .map(|decl| describe_fn(registry, decl.id, Receiver::None))
        .collect();
    functions.sort_by(|a, b| a.name.cmp(&b.name));
    let mut types: Vec<_> = module
        .types
        .iter()
        .map(|decl| describe_type(registry, decl.id, &decl.functions))
        .collect();
    types.sort_by(|a, b| a.name.cmp(&b.name));
    out.push(DocModule {
        path: joined,
        functions,
        types,
    });
    for child in module.modules {
        walk(registry, path.clone(), child, skip, out);
    }
}

/// Whether a function's signature starts with a receiver to leave out.
#[derive(Clone, Copy, PartialEq)]
enum Receiver {
    /// A function: every parameter is listed.
    None,
    /// A native type's method: the signature's first parameter is `self`.
    Included,
    /// A built-in type's method: the signature has no receiver.
    Excluded,
}

fn describe_fn(registry: &Registry, id: NativeFnId, receiver: Receiver) -> DocFn {
    let f = registry.function(id);
    let skip = usize::from(receiver == Receiver::Included);
    let name_at = |i: usize| {
        f.param_names
            .get(i)
            .filter(|n| !n.is_empty() && n.as_str() != "_")
            .cloned()
    };
    let params = match &f.signature {
        Some(sig) => sig
            .param_types
            .iter()
            .enumerate()
            .skip(skip)
            .map(|(i, ty)| DocParam {
                name: name_at(i),
                ty: Some(registry.type_desc_name(ty)),
                optional: i >= sig.required,
            })
            .collect(),
        None => (skip..f.param_names.len())
            .map(|i| DocParam {
                name: name_at(i),
                ty: None,
                optional: false,
            })
            .collect(),
    };
    DocFn {
        name: f.name.clone(),
        params,
        ret: registry.native_return_name(id),
        raw: f.signature.is_none(),
    }
}

fn describe_type(
    registry: &Registry,
    id: NativeTypeId,
    decls: &[xur_resolve::NativeFnDecl],
) -> DocType {
    let shape = registry.type_shape(id);
    let mut functions = Vec::new();
    let mut methods = Vec::new();
    for decl in decls {
        let f = registry.function(decl.id);
        let is_method = match &f.signature {
            Some(sig) => sig.params.first() == Some(&shape),
            None => f.param_names.first().is_some_and(|n| n == "self"),
        };
        if is_method {
            methods.push(describe_fn(registry, decl.id, Receiver::Included));
        } else {
            functions.push(describe_fn(registry, decl.id, Receiver::None));
        }
    }
    functions.sort_by(|a, b| a.name.cmp(&b.name));
    methods.sort_by(|a, b| a.name.cmp(&b.name));
    let (kind, fields, variants) = match shape.ty {
        Type::User(UserType::Struct(st)) => ("struct", fields_of(registry, &st), Vec::new()),
        Type::User(UserType::Enum(en)) => (
            "enum",
            Vec::new(),
            en.variants
                .iter()
                .map(|v| DocVariant {
                    name: v.name.to_string(),
                    fields: fields_of(registry, &v.data),
                    doc: doc_text(v.doc),
                })
                .collect(),
        ),
        _ => ("opaque", Vec::new(), Vec::new()),
    };
    DocType {
        name: registry.type_name(id),
        kind,
        doc: doc_text(shape.doc),
        fields,
        variants,
        functions,
        methods,
    }
}

fn fields_of(registry: &Registry, st: &StructType) -> Vec<DocField> {
    st.fields
        .iter()
        .map(|field| DocField {
            name: field.name.to_string(),
            ty: registry.shape_xur_name(field.shape()),
            doc: doc_text(field.doc),
        })
        .collect()
}

/// Joins a doc comment's lines (each with its leading space) into text.
fn doc_text(lines: &[&str]) -> Option<String> {
    let text = lines
        .iter()
        .map(|line| line.strip_prefix(' ').unwrap_or(line))
        .collect::<Vec<_>>()
        .join("\n");
    let text = text.trim();
    (!text.is_empty()).then(|| text.to_string())
}

#[cfg(test)]
mod tests {
    use facet::Facet;

    use super::*;
    use crate::{OptionalArg, XurStr};

    /// A counter.
    #[derive(Facet, Clone)]
    struct Counter {
        /// The count.
        n: i64,
    }

    fn registry() -> Registry {
        let registry = Registry::new();
        registry.module("app").named_function(
            "greet",
            &["name", "times"],
            |n: XurStr, _t: OptionalArg<i64>| n.to_string(),
        );
        registry
            .module("app")
            .ty::<Counter>("Counter")
            .named_function("new", &["n"], |n: i64| Counter { n })
            .named_method("add", &["by"], |c: &Counter, by: i64| c.n + by);
        registry.lazy_module("app::later", |m| {
            m.named_function("go", &["x"], |x: f64| x);
        });
        registry.lazy_module("app::test", |m| {
            m.function("hidden", || 1i64);
        });
        registry.builtin(BuiltinType::Str).named_method(
            "shout",
            &["suffix"],
            |s: &str, suffix: XurStr| format!("{}{}", s.to_uppercase(), &*suffix),
        );
        registry
    }

    #[test]
    fn dumps_modules_functions_types_and_builtins() {
        let tree = dump(&registry(), &["app::test"]);
        let paths: Vec<_> = tree.modules.iter().map(|m| m.path.as_str()).collect();
        assert_eq!(paths, ["app", "app::later"]);

        let app = &tree.modules[0];
        let greet = &app.functions[0];
        assert_eq!(greet.name, "greet");
        assert_eq!(
            greet.params,
            [
                DocParam {
                    name: Some("name".into()),
                    ty: Some("str".into()),
                    optional: false
                },
                DocParam {
                    name: Some("times".into()),
                    ty: Some("i64".into()),
                    optional: true
                },
            ]
        );
        assert_eq!(greet.ret.as_deref(), Some("str"));

        let counter = &app.types[0];
        assert_eq!(counter.kind, "struct");
        assert_eq!(counter.doc.as_deref(), Some("A counter."));
        assert_eq!(counter.fields[0].ty, "i64");
        assert_eq!(counter.fields[0].doc.as_deref(), Some("The count."));
        assert_eq!(counter.functions[0].name, "new");
        let add = &counter.methods[0];
        assert_eq!(add.name, "add");
        assert_eq!(add.params.len(), 1);
        assert_eq!(add.params[0].name.as_deref(), Some("by"));

        assert_eq!(tree.modules[1].functions[0].name, "go");

        let str_methods = &tree
            .builtins
            .iter()
            .find(|b| b.name == "str")
            .unwrap()
            .methods;
        assert_eq!(str_methods[0].name, "shout");
        assert_eq!(str_methods[0].params[0].name.as_deref(), Some("suffix"));
    }
}