xur-runtime 0.1.8

Values, native-function registry and facet conversions for the Xur language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! 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 std::collections::BTreeMap;

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

use xur_resolve::{NativeFnId, NativeTypeId};

use crate::BuiltinType;
use crate::TypeDesc;
use crate::registry::{ALIAS_INLINE_MAX, 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>,
    /// Named unions signatures show by name (`TypeName`), with the types
    /// each accepts.
    pub aliases: BTreeMap<String, Vec<String>>,
}

/// 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,
    /// Whether it takes any number of further arguments (the last only).
    pub rest: 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,
        aliases: aliases(registry),
    }
}

/// Every named union some signature shows by name, with its options.
fn aliases(registry: &Registry) -> BTreeMap<String, Vec<String>> {
    fn visit(registry: &Registry, desc: &TypeDesc, out: &mut BTreeMap<String, Vec<String>>) {
        match desc {
            TypeDesc::Alias(name, options) => {
                if options.len() > ALIAS_INLINE_MAX {
                    out.entry((*name).to_string()).or_insert_with(|| {
                        options.iter().map(|o| registry.type_desc_name(o)).collect()
                    });
                }
                options.iter().for_each(|o| visit(registry, o, out));
            }
            TypeDesc::Generic(_, items) | TypeDesc::Union(items) | TypeDesc::Tuple(items) => {
                items.iter().for_each(|o| visit(registry, o, out));
            }
            TypeDesc::Shape(_) | TypeDesc::Name(_) | TypeDesc::Unknown => {}
        }
    }
    let mut out = BTreeMap::new();
    for i in 0..registry.function_count() {
        let f = registry.function(NativeFnId(i as u32));
        if let Some(sig) = &f.signature {
            sig.param_types
                .iter()
                .for_each(|t| visit(registry, t, &mut out));
            visit(registry, &sig.ret_type, &mut out);
        }
        if let Some(raw) = &f.raw_sig {
            raw.params
                .iter()
                .for_each(|p| visit(registry, &p.ty, &mut out));
            if let Some(ret) = &raw.ret {
                visit(registry, ret, &mut out);
            }
        }
    }
    out
}

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, &f.raw_sig) {
        (None, Some(raw)) => raw
            .params
            .iter()
            .map(|p| DocParam {
                name: Some(p.name.to_string()),
                ty: Some(registry.type_desc_name(&p.ty)),
                optional: p.optional,
                rest: p.rest,
            })
            .collect(),
        (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,
                rest: false,
            })
            .collect(),
        (None, None) => (skip..f.param_names.len())
            .map(|i| DocParam {
                name: name_at(i),
                ty: None,
                optional: false,
                rest: false,
            })
            .collect(),
    };
    DocFn {
        name: f.name.clone(),
        params,
        ret: registry.native_return_name(id),
        raw: f.signature.is_none() && f.raw_sig.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 {
            // Taking the type, or a reference to it, first.
            Some(sig) => sig.params.first().is_some_and(|first| {
                *first == shape
                    || matches!(first.ty, Type::Pointer(PointerType::Reference(p)) if p.target() == 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)
            .named_function("double", &["c"], |c: &Counter| c.n * 2);
        registry.lazy_module("app::later", |m| {
            m.named_function("go", &["x"], |x: f64| x);
        });
        registry.module("app").raw_function_sig(
            "format",
            crate::registry::RawSig::new()
                .param("template", "str")
                .rest("args", "any")
                .returns("str"),
            |_, _| Ok(crate::Value::Unit),
        );
        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 format = &app.functions[0];
        assert_eq!(format.name, "format");
        assert!(!format.raw);
        assert_eq!(format.ret.as_deref(), Some("str"));
        assert!(format.params[1].rest);
        let greet = &app.functions[1];
        assert_eq!(greet.name, "greet");
        assert_eq!(
            greet.params,
            [
                DocParam {
                    name: Some("name".into()),
                    ty: Some("str".into()),
                    optional: false,
                    rest: false,
                },
                DocParam {
                    name: Some("times".into()),
                    ty: Some("i64".into()),
                    optional: true,
                    rest: false,
                },
            ]
        );
        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");
        // A function taking `&Counter` first is a method too.
        assert_eq!(counter.methods[1].name, "double");
        assert!(counter.methods[1].params.is_empty());
        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"));
    }
}