use facet::{StructType, Type, UserType};
use xur_resolve::{NativeFnId, NativeTypeId};
use crate::BuiltinType;
use crate::registry::Registry;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocTree {
pub modules: Vec<DocModule>,
pub builtins: Vec<DocBuiltin>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocModule {
pub path: String,
pub functions: Vec<DocFn>,
pub types: Vec<DocType>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocFn {
pub name: String,
pub params: Vec<DocParam>,
pub ret: Option<String>,
pub raw: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocParam {
pub name: Option<String>,
pub ty: Option<String>,
pub optional: bool,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocType {
pub name: String,
pub kind: &'static str,
pub doc: Option<String>,
pub fields: Vec<DocField>,
pub variants: Vec<DocVariant>,
pub functions: Vec<DocFn>,
pub methods: Vec<DocFn>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocField {
pub name: String,
pub ty: String,
pub doc: Option<String>,
}
#[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>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DocBuiltin {
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,
];
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);
}
}
#[derive(Clone, Copy, PartialEq)]
enum Receiver {
None,
Included,
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()
}
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};
#[derive(Facet, Clone)]
struct Counter {
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(®istry(), &["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"));
}
}