Skip to main content

submilli_engine/
docs_view.rs

1//! Documentation as one reader can use it: the callables whose capabilities
2//! the reader may hold, the types those callables still reach, and the
3//! Markdown regions whose conditions hold.
4//!
5//! The engine does not know the policy. An embedder answers through
6//! [`DocAvailability`], and [`Unscoped`] answers for an author reading
7//! everything. A projection is a copy for documentation: the declaration a
8//! program compiles against is never changed.
9
10use std::collections::{BTreeMap, BTreeSet};
11
12use crate::doc_directives::{DirectiveError, parse_doc_directives};
13use crate::stdlib::capabilities;
14use crate::{
15    DocCapability, DocCapabilityBindingKind, DocCapabilityLiteral, DocComment, MethodSig,
16    NamespaceSymbol, PackageDeclaration, TypeKind, TypeSymbol, ValueKind, ValueSymbol,
17};
18
19/// Whether a reader could use a capability.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum Availability {
22    /// No call can proceed.
23    Denied,
24    /// Some call could proceed. `notes` say what limits it, such as a filter
25    /// or a person's approval, as sentences documentation shows the reader.
26    Available { notes: Vec<String> },
27}
28
29impl Availability {
30    /// Available with nothing to note.
31    pub const OPEN: Self = Availability::Available { notes: Vec::new() };
32
33    pub fn is_available(&self) -> bool {
34        matches!(self, Availability::Available { .. })
35    }
36}
37
38/// The reader's side of documentation: which capabilities it could use.
39pub trait DocAvailability {
40    /// A capability a callable's `@capability` tag names. [`known_context`]
41    /// gives the context the tag's literal bindings fix ahead of the call.
42    fn tag(&self, tag: &DocCapability) -> Availability;
43
44    /// A capability a Markdown region names, with nothing known of the call.
45    fn capability(&self, name: &str) -> Availability;
46}
47
48/// Everything available: documentation as its author reads it.
49pub struct Unscoped;
50
51impl DocAvailability for Unscoped {
52    fn tag(&self, _tag: &DocCapability) -> Availability {
53        Availability::OPEN
54    }
55
56    fn capability(&self, _name: &str) -> Availability {
57        Availability::OPEN
58    }
59}
60
61/// The context fields a tag's literal bindings fix, in the form the runtime
62/// checks them. A literal the runtime would refuse, a relative path, which
63/// the runtime resolves against the session's working directory, or a number
64/// that does not parse, is left out, which leaves the field unknown.
65pub fn known_context(tag: &DocCapability) -> serde_json::Value {
66    let catalogued = capabilities::find_any(&tag.capability);
67    let mut fields = serde_json::Map::new();
68    for binding in &tag.bindings {
69        let DocCapabilityBindingKind::Literal { value, .. } = &binding.kind else {
70            continue;
71        };
72        let value = match value {
73            DocCapabilityLiteral::String(text) => {
74                let normalization = catalogued
75                    .and_then(|capability| {
76                        capability
77                            .filter_fields
78                            .iter()
79                            .find(|field| field.name == binding.field)
80                    })
81                    .map_or(capabilities::FieldNormalization::Verbatim, |field| {
82                        field.normalization
83                    });
84                if normalization == capabilities::FieldNormalization::VfsPath
85                    && !text.starts_with('/')
86                {
87                    continue;
88                }
89                match normalization.apply(text) {
90                    Ok(text) => serde_json::Value::String(text),
91                    Err(_) => continue,
92                }
93            }
94            DocCapabilityLiteral::Number(number) => {
95                let Some(number) = number
96                    .parse::<f64>()
97                    .ok()
98                    .and_then(serde_json::Number::from_f64)
99                else {
100                    continue;
101                };
102                serde_json::Value::Number(number)
103            }
104            DocCapabilityLiteral::Boolean(value) => serde_json::Value::Bool(*value),
105            DocCapabilityLiteral::Null => serde_json::Value::Null,
106        };
107        fields.insert(binding.field.clone(), value);
108    }
109    serde_json::Value::Object(fields)
110}
111
112/// A declaration narrowed to what a reader can use.
113#[derive(Debug, Clone)]
114pub struct Projection {
115    /// The callables the reader could call, each tagged one's documentation
116    /// noting what limits it, and the types they reach.
117    pub declaration: PackageDeclaration,
118    /// Whether the package is worth showing: some callable that needs a
119    /// capability is left, or none ever needed one, as in a package of pure
120    /// helpers or only types. The ungated helpers of a package whose every
121    /// gated callable was removed, such as its working directory, do not count.
122    pub usable: bool,
123}
124
125/// Narrow `defs` to what `availability` allows. A callable stays when every
126/// capability its tags name is available, since a call checks each of them.
127/// A type stays when a remaining callable reaches it, or when no callable
128/// ever did, as with a type a package exports on its own.
129pub fn project_declaration(
130    defs: &PackageDeclaration,
131    availability: &dyn DocAvailability,
132) -> Projection {
133    let mut declaration = defs.clone();
134    let mut gated = Gated::default();
135    retain_values(&mut declaration.values, availability, &mut gated);
136    for symbol in declaration.types.values_mut() {
137        retain_members(symbol, availability, &mut gated);
138    }
139    let mut pending: Vec<&mut NamespaceSymbol> = declaration.namespaces.values_mut().collect();
140    while let Some(namespace) = pending.pop() {
141        retain_values(&mut namespace.values, availability, &mut gated);
142        for symbol in namespace.types.values_mut() {
143            retain_members(symbol, availability, &mut gated);
144        }
145        pending.extend(namespace.namespaces.values_mut());
146    }
147    if gated.removed > 0 {
148        drop_unreached_types(defs, &mut declaration);
149    }
150    Projection {
151        declaration,
152        usable: gated.kept > 0 || gated.removed == 0,
153    }
154}
155
156/// `markdown` with the regions whose conditions fail removed, or the
157/// directives that make it malformed.
158pub fn scoped_documentation(
159    markdown: &str,
160    availability: &dyn DocAvailability,
161) -> Result<String, Vec<DirectiveError>> {
162    let document = parse_doc_directives(markdown)?;
163    Ok(document
164        .render(&|condition| condition.holds(|name| availability.capability(name).is_available())))
165}
166
167/// How many callables that need a capability a projection kept and removed.
168#[derive(Default)]
169struct Gated {
170    kept: usize,
171    removed: usize,
172}
173
174fn retain_values(
175    values: &mut BTreeMap<String, ValueSymbol>,
176    availability: &dyn DocAvailability,
177    gated: &mut Gated,
178) {
179    values.retain(|_, symbol| match &mut symbol.kind {
180        ValueKind::Function { doc, .. } => keep_callable(doc, availability, gated),
181        ValueKind::Let { .. } | ValueKind::Const { .. } => true,
182    });
183}
184
185fn retain_members(symbol: &mut TypeSymbol, availability: &dyn DocAvailability, gated: &mut Gated) {
186    match &mut symbol.kind {
187        TypeKind::Interface { methods, .. } => retain_methods(methods, availability, gated),
188        TypeKind::Class {
189            methods,
190            method_visibility,
191            statics,
192            static_visibility,
193            ..
194        } => {
195            retain_methods(methods, availability, gated);
196            method_visibility.retain(|name, _| methods.contains_key(name));
197            retain_methods(statics, availability, gated);
198            static_visibility.retain(|name, _| statics.contains_key(name));
199        }
200        TypeKind::NumberEnum { .. } | TypeKind::StringEnum { .. } | TypeKind::Alias { .. } => {}
201    }
202}
203
204fn retain_methods(
205    methods: &mut BTreeMap<String, MethodSig>,
206    availability: &dyn DocAvailability,
207    gated: &mut Gated,
208) {
209    methods.retain(|_, method| keep_callable(&mut method.doc, availability, gated));
210}
211
212/// Whether a callable with `doc` stays, adding to its summary what limits it.
213fn keep_callable(
214    doc: &mut Option<DocComment>,
215    availability: &dyn DocAvailability,
216    gated: &mut Gated,
217) -> bool {
218    let Some(doc) = doc.as_mut().filter(|doc| !doc.capabilities.is_empty()) else {
219        return true;
220    };
221    let mut notes: Vec<String> = Vec::new();
222    for tag in &doc.capabilities {
223        match availability.tag(tag) {
224            Availability::Denied => {
225                gated.removed = gated.removed.saturating_add(1);
226                return false;
227            }
228            Availability::Available { notes: tag_notes } => {
229                for note in tag_notes {
230                    if !notes.contains(&note) {
231                        notes.push(note);
232                    }
233                }
234            }
235        }
236    }
237    for note in notes {
238        if !doc.summary.is_empty() {
239            doc.summary.push('\n');
240        }
241        doc.summary.push_str(&note);
242    }
243    gated.kept = gated.kept.saturating_add(1);
244    true
245}
246
247/// Remove the types only removed callables reached. Reach starts from the
248/// values, from the types neither a value nor another type mentions, which a
249/// package exports on their own, and, after projection, from a class or interface that kept a
250/// callable needing a capability, which a reader can still use whatever
251/// returned it. A type `original` never reached stays.
252fn drop_unreached_types(original: &PackageDeclaration, projected: &mut PackageDeclaration) {
253    let mentioned: BTreeSet<String> = original
254        .types
255        .values()
256        .flat_map(crate::packages::type_symbol_references)
257        .collect();
258    let reached_by_values = reached_types(original, Vec::new());
259    let exported_alone: Vec<String> = original
260        .types
261        .values()
262        .map(|symbol| symbol.mangled_name.as_str().to_string())
263        .filter(|mangled| !mentioned.contains(mangled) && !reached_by_values.contains(mangled))
264        .collect();
265    let reached_before = reached_types(original, exported_alone.clone());
266    let mut roots = exported_alone;
267    roots.extend(
268        projected
269            .types
270            .values()
271            .filter(|symbol| keeps_gated_member(symbol))
272            .map(|symbol| symbol.mangled_name.as_str().to_string()),
273    );
274    let reached_after = reached_types(projected, roots);
275    let stays = |symbol: &TypeSymbol| {
276        let mangled = symbol.mangled_name.as_str();
277        !reached_before.contains(mangled) || reached_after.contains(mangled)
278    };
279    projected.types.retain(|_, symbol| stays(symbol));
280    let mut pending: Vec<&mut NamespaceSymbol> = projected.namespaces.values_mut().collect();
281    while let Some(namespace) = pending.pop() {
282        namespace.types.retain(|_, symbol| stays(symbol));
283        pending.extend(namespace.namespaces.values_mut());
284    }
285}
286
287fn keeps_gated_member(symbol: &TypeSymbol) -> bool {
288    let gated = |methods: &BTreeMap<String, MethodSig>| {
289        methods.values().any(|method| {
290            method
291                .doc
292                .as_ref()
293                .is_some_and(|doc| !doc.capabilities.is_empty())
294        })
295    };
296    match &symbol.kind {
297        TypeKind::Interface { methods, .. } => gated(methods),
298        TypeKind::Class {
299            methods, statics, ..
300        } => gated(methods) || gated(statics),
301        TypeKind::NumberEnum { .. } | TypeKind::StringEnum { .. } | TypeKind::Alias { .. } => false,
302    }
303}
304
305/// The mangled names of the types reached from `declaration`'s values, in
306/// every namespace, and from `roots`, through the types they mention.
307/// Namespace types are mirrored into `declaration.types`, so they are found
308/// there.
309fn reached_types(declaration: &PackageDeclaration, roots: Vec<String>) -> BTreeSet<String> {
310    let by_mangled: BTreeMap<&str, &TypeSymbol> = declaration
311        .types
312        .values()
313        .map(|symbol| (symbol.mangled_name.as_str(), symbol))
314        .collect();
315    let mut values = vec![serde_json::to_value(&declaration.values)];
316    let mut namespaces: Vec<&NamespaceSymbol> = declaration.namespaces.values().collect();
317    while let Some(namespace) = namespaces.pop() {
318        values.push(serde_json::to_value(&namespace.values));
319        namespaces.extend(namespace.namespaces.values());
320    }
321    let mut pending = roots;
322    pending.extend(crate::packages::type_references(&values));
323    let mut reached = BTreeSet::new();
324    while let Some(mangled) = pending.pop() {
325        if !reached.insert(mangled.clone()) {
326            continue;
327        }
328        let Some(symbol) = by_mangled.get(mangled.as_str()) else {
329            continue;
330        };
331        pending.extend(crate::packages::type_symbol_references(symbol));
332    }
333    reached
334}
335
336#[cfg(test)]
337mod tests {
338    use super::*;
339
340    /// Capabilities in `denied` are unavailable, ones in `noted` carry a note.
341    struct Fixed {
342        denied: &'static [&'static str],
343        noted: &'static [&'static str],
344    }
345
346    impl Fixed {
347        fn answer(&self, name: &str) -> Availability {
348            if self.denied.contains(&name) {
349                Availability::Denied
350            } else if self.noted.contains(&name) {
351                Availability::Available {
352                    notes: vec![format!("`{name}` is restricted.")],
353                }
354            } else {
355                Availability::OPEN
356            }
357        }
358    }
359
360    impl DocAvailability for Fixed {
361        fn tag(&self, tag: &DocCapability) -> Availability {
362            self.answer(&tag.capability)
363        }
364
365        fn capability(&self, name: &str) -> Availability {
366            self.answer(name)
367        }
368    }
369
370    fn declaration(source: &str) -> PackageDeclaration {
371        crate::compile_package(
372            "@acme/pkg",
373            crate::ModulePath::from("lib"),
374            &[crate::PackageSourceModule {
375                path: crate::ModulePath::from("lib"),
376                source,
377            }],
378            &[],
379        )
380        .unwrap_or_else(|diagnostics| panic!("compile failed: {diagnostics:#?}"))
381        .declaration
382    }
383
384    const SOURCE: &str = r#"
385        export interface Issue { id: string; title: string; }
386        export interface Draft { title: string; }
387        export interface Team { name: string; }
388        export interface Standalone { note: string; }
389
390        /** List issues.
391         * @capability acme.test/read */
392        export function listIssues(team: Team): Issue[] { return []; }
393
394        /** Create an issue.
395         * @capability acme.test/write */
396        export function createIssue(draft: Draft): Issue { return { id: "1", title: draft.title }; }
397
398        /** Download an issue.
399         * @capability acme.test/read
400         * @capability acme.test/write */
401        export function exportIssue(id: string): void {}
402
403        export function helper(): string { return "x"; }
404
405        export class Client {
406            /** @capability acme.test/read */
407            get(id: string): Issue { return { id, title: "" }; }
408            /** @capability acme.test/write */
409            update(draft: Draft): void {}
410        }
411    "#;
412
413    #[test]
414    fn denied_callables_and_the_types_only_they_reach_are_removed() {
415        let defs = declaration(SOURCE);
416        let projection = project_declaration(
417            &defs,
418            &Fixed {
419                denied: &["acme.test/write"],
420                noted: &[],
421            },
422        );
423        let declaration = &projection.declaration;
424        assert!(projection.usable);
425        assert!(declaration.values.contains_key("listIssues"));
426        assert!(declaration.values.contains_key("helper"));
427        assert!(!declaration.values.contains_key("createIssue"));
428        // Every tag counts: one denied capability removes the callable.
429        assert!(!declaration.values.contains_key("exportIssue"));
430        assert!(declaration.types.contains_key("Issue"));
431        assert!(declaration.types.contains_key("Team"));
432        assert!(declaration.types.contains_key("Standalone"));
433        assert!(!declaration.types.contains_key("Draft"));
434        let Some(TypeKind::Class {
435            methods,
436            method_visibility,
437            ..
438        }) = declaration.types.get("Client").map(|symbol| &symbol.kind)
439        else {
440            panic!("Client stays");
441        };
442        assert!(methods.contains_key("get"));
443        assert!(!methods.contains_key("update"));
444        assert!(!method_visibility.contains_key("update"));
445        // The compiled declaration is untouched.
446        assert!(defs.values.contains_key("createIssue"));
447    }
448
449    #[test]
450    fn a_class_keeps_its_place_by_what_it_still_offers() {
451        let defs = declaration(
452            r#"
453            export interface Secret { value: string; }
454            export interface Page { text: string; }
455            export class Session {
456                /** @capability acme.test/read */
457                read(): Page { return { text: "" }; }
458                /** @capability acme.test/write */
459                rotate(): Secret { return { value: "" }; }
460            }
461            /** @capability acme.test/connect */
462            export function connect(): Session { return new Session(); }
463            "#,
464        );
465        let projection = project_declaration(
466            &defs,
467            &Fixed {
468                denied: &["acme.test/connect", "acme.test/write"],
469                noted: &[],
470            },
471        );
472        let types = &projection.declaration.types;
473        // Only the removed `connect` reached `Session`, but `read` still works.
474        assert!(types.contains_key("Session"), "{types:?}");
475        assert!(types.contains_key("Page"));
476        // Only the removed `rotate` reached `Secret`.
477        assert!(!types.contains_key("Secret"));
478    }
479
480    #[test]
481    fn unscoped_projection_keeps_everything() {
482        let defs = declaration(SOURCE);
483        let projection = project_declaration(&defs, &Unscoped);
484        assert_eq!(projection.declaration, defs);
485        assert!(projection.usable);
486    }
487
488    #[test]
489    fn types_reexported_from_sibling_modules_are_reached_by_the_signatures_naming_them() {
490        let modules = [
491            crate::PackageSourceModule {
492                path: crate::ModulePath::from("lib"),
493                source: r#"
494                    import type { SearchResult, Draft } from "./model";
495                    export { SearchResult, Draft } from "./model";
496                    /** @capability acme.test/read */
497                    export function search(q: string): SearchResult[] { return []; }
498                    /** @capability acme.test/write */
499                    export function save(draft: Draft): void {}
500                "#,
501            },
502            crate::PackageSourceModule {
503                path: crate::ModulePath::from("model"),
504                source: r#"
505                    export interface SearchResult { title: string; }
506                    export interface Draft { title: string; }
507                "#,
508            },
509        ];
510        let defs =
511            crate::compile_package("@acme/pkg", crate::ModulePath::from("lib"), &modules, &[])
512                .unwrap_or_else(|diagnostics| panic!("compile failed: {diagnostics:#?}"))
513                .declaration;
514        let Some(ValueKind::Function { ret, .. }) = defs.values.get("search").map(|v| &v.kind)
515        else {
516            panic!("search is a function");
517        };
518        let crate::Type::Array(element) = ret else {
519            panic!("search returns an array: {ret:?}");
520        };
521        let crate::Type::InterfaceRef { mangled, .. } = element.as_ref() else {
522            panic!("search returns interfaces: {element:?}");
523        };
524        assert_eq!(&defs.types["SearchResult"].mangled_name, mangled);
525
526        let projection = project_declaration(
527            &defs,
528            &Fixed {
529                denied: &["acme.test/write"],
530                noted: &[],
531            },
532        );
533        assert!(projection.declaration.types.contains_key("SearchResult"));
534        assert!(!projection.declaration.types.contains_key("Draft"));
535
536        let rendered = crate::packages::render_packages_d_ts(&[&defs], &[]);
537        assert!(rendered.contains("interface SearchResult {"), "{rendered}");
538        assert!(
539            rendered.contains("search(q: string): SearchResult[]"),
540            "{rendered}"
541        );
542    }
543
544    #[test]
545    fn notes_follow_the_summary() {
546        let defs = declaration(SOURCE);
547        let projection = project_declaration(
548            &defs,
549            &Fixed {
550                denied: &[],
551                noted: &["acme.test/read"],
552            },
553        );
554        let rendered = crate::packages::render_declarations(&projection.declaration);
555        assert!(
556            rendered.contains(" * List issues.\n * `acme.test/read` is restricted.\n"),
557            "{rendered}"
558        );
559        // One note per distinct sentence, however many tags repeat it.
560        assert_eq!(rendered.matches("is restricted.").count(), 3, "{rendered}");
561    }
562
563    #[test]
564    fn a_package_with_nothing_left_to_call_is_not_usable() {
565        let defs = declaration(SOURCE);
566        let projection = project_declaration(
567            &defs,
568            &Fixed {
569                denied: &["acme.test/read", "acme.test/write"],
570                noted: &[],
571            },
572        );
573        // `helper` is left, but it needs no capability.
574        assert!(!projection.usable);
575        let gated_only = declaration(
576            r#"
577                export interface Issue { id: string; }
578                /** @capability acme.test/read */
579                export function listIssues(): Issue[] { return []; }
580            "#,
581        );
582        let projection = project_declaration(
583            &gated_only,
584            &Fixed {
585                denied: &["acme.test/read"],
586                noted: &[],
587            },
588        );
589        assert!(!projection.usable);
590        assert!(projection.declaration.types.is_empty());
591    }
592
593    #[test]
594    fn recursive_and_generic_types_terminate_and_stay_whole() {
595        let defs = declaration(
596            r#"
597                export interface Node { children: Node[]; parent: Box<Node> | undefined; }
598                export interface Box<T> { value: T; }
599                /** @capability acme.test/read */
600                export function tree(): Node { return { children: [], parent: undefined }; }
601                /** @capability acme.test/write */
602                export function boxed(): Box<string> { return { value: "" }; }
603            "#,
604        );
605        let projection = project_declaration(
606            &defs,
607            &Fixed {
608                denied: &["acme.test/write"],
609                noted: &[],
610            },
611        );
612        assert!(projection.declaration.types.contains_key("Node"));
613        assert!(projection.declaration.types.contains_key("Box"));
614    }
615
616    #[test]
617    fn known_context_normalizes_literals() {
618        let defs = declaration(
619            r#"
620                /** @capability fs.read { path: "/a/../b.txt", recursive: true } */
621                export function read(): void {}
622                /** @capability fs.read { path: "notes.txt" } */
623                export function readRelative(): void {}
624            "#,
625        );
626        let Some(ValueKind::Function { doc: Some(doc), .. }) =
627            defs.values.get("read").map(|symbol| &symbol.kind)
628        else {
629            panic!("read is documented");
630        };
631        let context = known_context(&doc.capabilities[0]);
632        assert_eq!(
633            context,
634            serde_json::json!({ "path": "/b.txt", "recursive": true })
635        );
636        let Some(ValueKind::Function { doc: Some(doc), .. }) =
637            defs.values.get("readRelative").map(|symbol| &symbol.kind)
638        else {
639            panic!("readRelative is documented");
640        };
641        // The runtime resolves a relative path against the working directory.
642        assert_eq!(known_context(&doc.capabilities[0]), serde_json::json!({}));
643    }
644
645    #[test]
646    fn regions_follow_availability() {
647        let markdown = "Intro.\n\n<!-- submilli:if capability=\"acme.test/write\" -->\n\nWrite.\n\n<!-- submilli:endif -->\n\nEnd.\n";
648        let denied = Fixed {
649            denied: &["acme.test/write"],
650            noted: &[],
651        };
652        assert_eq!(
653            scoped_documentation(markdown, &denied).unwrap(),
654            "Intro.\n\nEnd.\n"
655        );
656        assert_eq!(
657            scoped_documentation(markdown, &Unscoped).unwrap(),
658            "Intro.\n\nWrite.\n\nEnd.\n"
659        );
660        assert!(scoped_documentation("<!-- submilli:endif -->\n", &Unscoped).is_err());
661    }
662}