Skip to main content

devpage_core/code/
mod.rs

1//! The code reference: a page for every module, type and function of the
2//! code a site names, in the style of DocC — made from the code itself,
3//! live, and never written to disk.
4//!
5//! A site enables it as the system extension `code`, one namespace per
6//! language:
7//!
8//! ```yaml
9//! extensions:
10//!   code:
11//!     config:
12//!       rust:
13//!         files: ["../core/src/**/*.rs"]
14//! ```
15//!
16//! Each file is parsed by its namespace's grammar and query ([`extract`]),
17//! every file's declarations are linked into items ([`rust`]), and a
18//! item's page is rendered on request ([`render`]) at
19//! `<site folder>/reference/<namespace>/<path>`. A save re-parses that one
20//! file and links again in memory; nothing is cached on disk.
21
22mod extract;
23mod render;
24mod rust;
25
26use std::collections::{BTreeMap, HashMap};
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Mutex, OnceLock, RwLock};
29
30use anyhow::{Context, Result, bail};
31use globset::{GlobSet, GlobSetBuilder};
32use serde::Deserialize;
33
34use crate::folder::{ServedFolder, lexical};
35
36pub use extract::{Declaration, Extracted, Grammar, Visibility};
37
38/// One thing of the code, after every file is linked: a module, a type, a
39/// function — what a reference page is about.
40#[derive(Debug, Clone, Default)]
41pub struct Item {
42    /// Its path as the language names it: crate, modules, item.
43    pub path: Vec<String>,
44    /// What it is, as the query names it: `module`, `struct`, `function`….
45    pub kind: String,
46    /// Its declaration as written, without its body.
47    pub signature: String,
48    /// Its doc comment, as Markdown.
49    pub doc: String,
50    /// Where it is declared.
51    pub file: PathBuf,
52    /// The line it is declared on, from 1.
53    pub line: usize,
54    /// Whether a `pub` path reaches it from its crate's root.
55    pub public: bool,
56    /// Its fields, variants and methods, shown as sections of its page.
57    pub members: Vec<Member>,
58    /// The traits it implements, by name.
59    pub implements: Vec<String>,
60}
61
62/// A part of an item shown on its page: a field, a variant, a method.
63#[derive(Debug, Clone)]
64pub struct Member {
65    /// Its name as declared: the last part of its id,
66    /// `namespace:path::name`.
67    pub name: String,
68    /// What it is: `field`, `variant`, `method`….
69    pub kind: String,
70    /// Its declaration as written, without its body.
71    pub signature: String,
72    /// Its doc comment, as Markdown.
73    pub doc: String,
74    /// Where it is declared.
75    pub file: PathBuf,
76    /// The line it is declared on, from 1.
77    pub line: usize,
78    /// Whether it is reachable: `pub`, or a trait's item or an enum's variant.
79    pub public: bool,
80}
81
82/// Every item of a namespace, by path, and the paths `pub use` makes
83/// another name for.
84#[derive(Debug, Default)]
85pub struct Items {
86    /// Every item, by its path.
87    pub items: BTreeMap<Vec<String>, Item>,
88    /// Each other name a `pub use` gives an item, to the path it stands for.
89    pub aliases: BTreeMap<Vec<String>, Vec<String>>,
90}
91
92/// The `code` extension's `config`: its namespaces.
93#[derive(Debug, Deserialize)]
94#[serde(transparent)]
95struct Config(BTreeMap<String, NamespaceConfig>);
96
97/// One namespace as written.
98#[derive(Debug, Deserialize)]
99#[serde(deny_unknown_fields)]
100struct NamespaceConfig {
101    /// The language its files are written in; the namespace's name when
102    /// left out.
103    language: Option<String>,
104    /// Glob patterns of its files, relative to the document file.
105    files: Vec<String>,
106    /// A query file replacing the language's built-in query.
107    query: Option<String>,
108    /// Whether items no `pub` path reaches get pages too.
109    #[serde(default)]
110    private: bool,
111}
112
113/// One namespace: its files, its parser and the items they make now.
114struct Namespace {
115    /// Its name in the configuration, and in its pages' addresses.
116    name: String,
117    /// The language its files are written in.
118    language: String,
119    /// The parser of its files, replaced when its query file changes.
120    grammar: RwLock<Arc<Grammar>>,
121    /// Its `files` patterns, made absolute.
122    patterns: GlobSet,
123    /// The folder each pattern's files are under: its literal prefix.
124    roots: Vec<PathBuf>,
125    /// The query file, when the project wrote its own; a change to it
126    /// re-parses every file.
127    query: Option<PathBuf>,
128    /// Whether items no `pub` path reaches get pages too.
129    private: bool,
130    /// Each of its files' declarations, by path.
131    files: Mutex<BTreeMap<PathBuf, Arc<Extracted>>>,
132    /// Its items, as its files were last linked.
133    items: RwLock<Arc<Items>>,
134    /// Why its query file, saved while devpage runs, doesn't compile: its
135    /// line and the error. `None` while the query in use is the file's.
136    query_error: RwLock<Option<(usize, String)>>,
137}
138
139/// The code reference of one site.
140pub struct Index {
141    /// The site's folder: pages are under its `reference/`.
142    base: PathBuf,
143    /// The served folder the site is in, which page addresses are made from.
144    served: ServedFolder,
145    /// The configuration it was made from, to tell a reload from a change.
146    configuration: String,
147    /// Its namespaces, in the order of their names.
148    namespaces: Vec<Namespace>,
149    /// Markdown that adds to an item's page, by `namespace:path`.
150    prose: RwLock<BTreeMap<String, Prose>>,
151    /// Prose files for an id another prose file already adds to: each with
152    /// its id and the file that adds to it first.
153    twice: RwLock<Vec<(Prose, String, PathBuf)>>,
154}
155
156/// A Markdown file headed ``# ``rust:path`` ``: what it adds to that
157/// item's page.
158#[derive(Debug, Clone)]
159pub struct Prose {
160    /// The Markdown file it is read from.
161    pub file: PathBuf,
162    /// The line of its heading, from 1.
163    pub line: usize,
164    /// What follows its heading.
165    pub body: String,
166}
167
168/// Every site's code reference, by its document file.
169static INDEXES: OnceLock<Mutex<BTreeMap<PathBuf, Arc<Index>>>> = OnceLock::new();
170
171/// Every site's code reference, by its document file, made empty on first use.
172fn indexes() -> &'static Mutex<BTreeMap<PathBuf, Arc<Index>>> {
173    INDEXES.get_or_init(Default::default)
174}
175
176/// Enables the code reference of the site whose document file is `doc`,
177/// in the folder `base`, from its `config` — or disables it when `config`
178/// is `None`. Loading the same configuration again keeps the index.
179pub fn configure(
180    doc: &Path,
181    base: &Path,
182    served: &ServedFolder,
183    config: Option<&serde_yaml::Value>,
184) -> Result<()> {
185    let Some(config) = config else {
186        indexes().lock().unwrap().remove(doc);
187        return Ok(());
188    };
189    let configuration = serde_yaml::to_string(config)?;
190    if let Some(index) = indexes().lock().unwrap().get(doc)
191        && index.configuration == configuration
192        && index.served == *served
193    {
194        return Ok(());
195    }
196    let Config(namespaces) = serde_yaml::from_value(config.clone()).context("extensions: code")?;
197    if namespaces.is_empty() {
198        bail!("extensions: code: config lists no namespaces");
199    }
200    let mut built = Vec::new();
201    for (name, namespace) in namespaces {
202        built.push(
203            Namespace::new(&name, namespace, base, served)
204                .with_context(|| format!("extensions: code: {name}"))?,
205        );
206    }
207    let index = Index {
208        base: base.to_path_buf(),
209        served: served.clone(),
210        configuration,
211        namespaces: built,
212        prose: RwLock::default(),
213        twice: RwLock::default(),
214    };
215    for namespace in &index.namespaces {
216        namespace.parse_all();
217    }
218    index.read_prose();
219    indexes()
220        .lock()
221        .unwrap()
222        .insert(doc.to_path_buf(), Arc::new(index));
223    Ok(())
224}
225
226/// Forgets every code reference of a document under `folder`: for server
227/// mode, a version it no longer holds, whose items would otherwise stay in
228/// memory for good.
229pub fn forget(folder: &Path) {
230    let canonical = folder.canonicalize().ok();
231    indexes().lock().unwrap().retain(|doc, _| {
232        !doc.starts_with(folder) && canonical.as_ref().is_none_or(|c| !doc.starts_with(c))
233    });
234}
235
236/// The code reference of the site whose document file is `doc`, if it has
237/// one.
238pub fn for_document(doc: &Path) -> Option<Arc<Index>> {
239    indexes().lock().unwrap().get(doc).cloned()
240}
241
242/// The code reference whose pages lie where `path` — a lexical path in the
243/// served folder — is: its nearest site's, when that site has one and
244/// `path` is under its `reference/`.
245pub fn at(folder: &crate::folder::Folder, path: &Path) -> Option<Arc<Index>> {
246    if !folder.served().contains(path) {
247        return None;
248    }
249    let site = folder.site(path)?;
250    // The site's document loaded, so its code reference is configured.
251    folder.owner(path)?.document.ok()?;
252    for_document(&site).filter(|index| index.owns(path))
253}
254
255/// Every folder a code reference of `served` reads from: watched whatever
256/// the site's `watch` list or `.gitignore` says.
257pub fn input_roots(served: &ServedFolder) -> Vec<PathBuf> {
258    indexes()
259        .lock()
260        .unwrap()
261        .values()
262        .filter(|index| index.served == *served)
263        .flat_map(|index| {
264            index
265                .namespaces
266                .iter()
267                .flat_map(|namespace| namespace.roots.clone())
268                .collect::<Vec<_>>()
269        })
270        .collect()
271}
272
273/// Brings every code reference of `served` up to date after `files`
274/// changed: each changed source file parsed again, each namespace linked
275/// again. Whether any page may now read differently.
276pub fn changed(served: &ServedFolder, files: &[PathBuf]) -> bool {
277    let all: Vec<Arc<Index>> = indexes()
278        .lock()
279        .unwrap()
280        .values()
281        .filter(|index| index.served == *served)
282        .cloned()
283        .collect();
284    let mut any = false;
285    for index in all {
286        any |= index.changed(files);
287    }
288    any
289}
290
291impl Namespace {
292    /// The namespace `name` as `config` writes it, its patterns relative to
293    /// `base`, with no file parsed yet; an error when its language, query or a
294    /// pattern is wrong.
295    fn new(
296        name: &str,
297        config: NamespaceConfig,
298        base: &Path,
299        served: &ServedFolder,
300    ) -> Result<Self> {
301        let language = config.language.as_deref().unwrap_or(name);
302        let query_file = match &config.query {
303            Some(query) => match served.file(&base.join(query)) {
304                Some(file) => Some(file),
305                None => bail!("query {query} does not exist"),
306            },
307            None => None,
308        };
309        let grammar = grammar(language, query_file.as_deref())?;
310        if config.files.is_empty() {
311            bail!("files lists no patterns");
312        }
313        let mut patterns = GlobSetBuilder::new();
314        let mut roots = Vec::new();
315        for pattern in &config.files {
316            let absolute = lexical(&base.join(pattern));
317            if !served.contains(&absolute) {
318                bail!("files {pattern} is outside the served folder");
319            }
320            // The folder before the first glob character is matched as
321            // written — on Windows it starts `\\?\` — and the rest as the
322            // pattern.
323            let root = literal_prefix(&absolute);
324            let rest = absolute.strip_prefix(&root).unwrap_or(&absolute);
325            let text = if rest.as_os_str().is_empty() {
326                // A pattern naming one file.
327                globset::escape(&glob_path(&root))
328            } else {
329                format!(
330                    "{}/{}",
331                    globset::escape(glob_path(&root).trim_end_matches('/')),
332                    glob_path(rest)
333                )
334            };
335            patterns.add(
336                globset::GlobBuilder::new(&text)
337                    .literal_separator(true)
338                    .build()
339                    .with_context(|| format!("files {pattern}"))?,
340            );
341            roots.push(root);
342        }
343        Ok(Self {
344            name: name.to_string(),
345            language: language.to_string(),
346            grammar: RwLock::new(Arc::new(grammar)),
347            patterns: patterns.build()?,
348            roots,
349            query: query_file,
350            private: config.private,
351            files: Mutex::default(),
352            items: RwLock::default(),
353            query_error: RwLock::default(),
354        })
355    }
356
357    /// Whether `file` is one of the namespace's files.
358    fn includes(&self, file: &Path) -> bool {
359        self.patterns.is_match(glob_path(file))
360    }
361
362    /// Every file of the namespace parsed, across the machine's cores, then
363    /// linked.
364    fn parse_all(&self) {
365        let mut found = Vec::new();
366        for root in &self.roots {
367            let walk = ignore::WalkBuilder::new(root)
368                .hidden(true)
369                .require_git(false)
370                .build();
371            for entry in walk.flatten() {
372                let path = entry.path();
373                if entry.file_type().is_some_and(|t| t.is_file()) && self.includes(path) {
374                    found.push(path.to_path_buf());
375                }
376            }
377        }
378        found.sort();
379        found.dedup();
380        let threads = std::thread::available_parallelism().map_or(1, |n| n.get());
381        let chunk = found.len().div_ceil(threads).max(1);
382        let grammar = self.grammar.read().unwrap().clone();
383        let grammar = &*grammar;
384        let parsed: Vec<(PathBuf, Arc<Extracted>)> = std::thread::scope(|scope| {
385            let handles: Vec<_> = found
386                .chunks(chunk)
387                .map(|files| {
388                    scope.spawn(move || {
389                        files
390                            .iter()
391                            .filter_map(|file| {
392                                let source = std::fs::read_to_string(file).ok()?;
393                                Some((file.clone(), Arc::new(grammar.extract(&source))))
394                            })
395                            .collect::<Vec<_>>()
396                    })
397                })
398                .collect();
399            handles
400                .into_iter()
401                .flat_map(|handle| handle.join().unwrap_or_default())
402                .collect()
403        });
404        *self.files.lock().unwrap() = parsed.into_iter().collect();
405        self.link();
406    }
407
408    /// Every file's declarations linked into items.
409    fn link(&self) {
410        let files = self.files.lock().unwrap().clone();
411        let mut crates = HashMap::new();
412        let units: Vec<(Vec<String>, rust::Unit)> = files
413            .iter()
414            .filter_map(|(file, extracted)| {
415                Some((
416                    rust::module_of(file, &mut crates)?,
417                    rust::Unit { file, extracted },
418                ))
419            })
420            .collect();
421        let items = rust::link(&units, self.private);
422        *self.items.write().unwrap() = Arc::new(items);
423    }
424
425    /// The items now.
426    fn items(&self) -> Arc<Items> {
427        self.items.read().unwrap().clone()
428    }
429}
430
431/// The parser for `language`: its built-in grammar with its built-in query,
432/// or the query in `query`.
433fn grammar(language: &str, query: Option<&Path>) -> Result<Grammar> {
434    let (grammar, built_in, docs) = match language {
435        "rust" => (
436            tree_sitter_rust::LANGUAGE.into(),
437            include_str!("rust.scm"),
438            extract::Docs::Rust,
439        ),
440        other => bail!("language {other} is not one devpage knows: rust"),
441    };
442    let source = match query {
443        Some(file) => {
444            std::fs::read_to_string(file).with_context(|| format!("reading {}", file.display()))?
445        }
446        None => built_in.to_string(),
447    };
448    Grammar::new(grammar, &source, docs).map_err(|error| match query {
449        Some(file) => error.context(format!("query {}", file.display())),
450        None => error,
451    })
452}
453
454/// An absolute path as a glob pattern matches it: `/` between its parts on
455/// every platform.
456pub(crate) fn glob_path(path: &Path) -> String {
457    path.to_string_lossy().replace('\\', "/")
458}
459
460/// The part of an absolute pattern before its first glob character: the
461/// folder its files are under.
462pub(crate) fn literal_prefix(pattern: &Path) -> PathBuf {
463    let mut prefix = PathBuf::new();
464    for part in pattern.components() {
465        // A drive or a `\\?\` prefix is never part of the glob.
466        let text = part.as_os_str().to_string_lossy();
467        if matches!(part, std::path::Component::Normal(_)) && text.contains(['*', '?', '[', '{']) {
468            break;
469        }
470        prefix.push(part);
471    }
472    prefix
473}
474
475/// One page of a code reference, as search reads it.
476pub struct Searched {
477    /// The address of its page, or of its section on its type's page.
478    pub url: String,
479    /// The name of what it is about.
480    pub title: String,
481    /// Where it is: the reference, then each module above it.
482    pub trail: Vec<String>,
483    /// Its doc comment and the prose that adds to it.
484    pub prose: String,
485    /// Its declaration.
486    pub code: String,
487}
488
489/// The kinds the sidebar's tree lists; the rest are left to their pages.
490const NAVIGATED: [&str; 7] = [
491    "module", "struct", "enum", "union", "trait", "type", "macro",
492];
493
494/// What a page address of the code reference names.
495pub enum Page {
496    /// A namespace's root: every crate it holds.
497    Namespace(usize),
498    /// An item, by its path.
499    Item(usize, Vec<String>),
500    /// A member of the item at the path, by its index.
501    Member(usize, Vec<String>, usize),
502}
503
504impl Index {
505    /// The folder the reference's pages are under.
506    fn reference(&self) -> PathBuf {
507        self.base.join("reference")
508    }
509
510    /// The page at `path` — a lexical path in the served folder — if it is
511    /// one of the reference's. An alias names the item it stands for.
512    pub fn page(&self, path: &Path) -> Option<Page> {
513        let relative = path.strip_prefix(self.reference()).ok()?;
514        let mut parts = relative
515            .components()
516            .map(|part| part.as_os_str().to_string_lossy().into_owned());
517        let name = parts.next()?;
518        let at = self.namespaces.iter().position(|n| n.name == name)?;
519        let segments: Vec<String> = parts.collect();
520        if segments.is_empty() {
521            return Some(Page::Namespace(at));
522        }
523        let items = self.namespaces[at].items();
524        let segments = items.aliases.get(&segments).cloned().unwrap_or(segments);
525        if items.items.contains_key(&segments) {
526            return Some(Page::Item(at, segments));
527        }
528        // A member's page is under its type's: `Store/read`.
529        let (name, owner) = segments.split_last()?;
530        let owner = items.aliases.get(owner).cloned().unwrap_or(owner.to_vec());
531        let member = items
532            .items
533            .get(&owner)?
534            .members
535            .iter()
536            .position(|member| member.name == *name)?;
537        Some(Page::Member(at, owner, member))
538    }
539
540    /// The Markdown of the page `page`.
541    pub fn markdown(&self, page: &Page) -> String {
542        let prose = self.prose.read().unwrap();
543        match page {
544            Page::Namespace(at) => {
545                let namespace = &self.namespaces[*at];
546                render::namespace(self, &namespace.name, &namespace.items())
547            }
548            Page::Item(at, path) => {
549                let namespace = &self.namespaces[*at];
550                let items = namespace.items();
551                let id = format!("{}:{}", namespace.name, path.join("::"));
552                render::item(
553                    self,
554                    &namespace.name,
555                    &items,
556                    &items.items[path],
557                    prose.get(&id),
558                )
559            }
560            Page::Member(at, path, member) => {
561                let namespace = &self.namespaces[*at];
562                let items = namespace.items();
563                let owner = &items.items[path];
564                let member = &owner.members[*member];
565                let id = format!("{}:{}::{}", namespace.name, path.join("::"), member.name);
566                render::member(self, &namespace.name, owner, member, prose.get(&id))
567            }
568        }
569    }
570
571    /// The address of a page: a namespace's with no `path`, an item's, or a
572    /// member's under its type's.
573    pub(crate) fn address(&self, namespace: &str, path: &[String]) -> String {
574        let mut file = self.reference().join(namespace);
575        for segment in path {
576            file.push(segment);
577        }
578        self.served.url(&file).unwrap_or_default()
579    }
580
581    /// The page the sidebar lists for `page`: its own, or — for a member,
582    /// which the sidebar leaves to its type's page — its type's.
583    pub fn listed(&self, page: &Page) -> PathBuf {
584        let (at, mut path) = match page {
585            Page::Namespace(at) => (*at, &[][..]),
586            Page::Item(at, path) | Page::Member(at, path, _) => (*at, &path[..]),
587        };
588        // A function, a constant: the sidebar lists its module.
589        let items = self.namespaces[at].items();
590        if let Some(item) = items.items.get(path)
591            && !NAVIGATED.contains(&item.kind.as_str())
592        {
593            path = &path[..path.len() - 1];
594        }
595        let mut file = self.reference().join(&self.namespaces[at].name);
596        for segment in path {
597            file.push(segment);
598        }
599        file
600    }
601
602    /// Every page of the reference as search reads it: each item's and
603    /// each member's, in path order.
604    pub fn searched(&self) -> Vec<Searched> {
605        let prose = self.prose.read().unwrap();
606        let mut out = Vec::new();
607        for namespace in &self.namespaces {
608            let items = namespace.items();
609            let reference = format!("{} reference", render::title_case(&namespace.name));
610            let added = |path: &[String]| {
611                let id = format!("{}:{}", namespace.name, path.join("::"));
612                prose.get(&id).map(|p| p.body.clone()).unwrap_or_default()
613            };
614            for (path, item) in &items.items {
615                let mut trail = vec![reference.clone()];
616                trail.extend(path[..path.len() - 1].iter().cloned());
617                out.push(Searched {
618                    url: self.address(&namespace.name, path),
619                    title: path.last().cloned().unwrap_or_default(),
620                    trail: trail.clone(),
621                    prose: format!("{}\n\n{}", render::doc_markdown(&item.doc), added(path)),
622                    code: item.signature.clone(),
623                });
624                trail.push(path.last().cloned().unwrap_or_default());
625                for member in &item.members {
626                    let mut member_path = path.clone();
627                    member_path.push(member.name.clone());
628                    out.push(Searched {
629                        url: self.address(&namespace.name, &member_path),
630                        title: member.name.clone(),
631                        trail: trail.clone(),
632                        prose: format!(
633                            "{}\n\n{}",
634                            render::doc_markdown(&member.doc),
635                            added(&member_path)
636                        ),
637                        code: member.signature.clone(),
638                    });
639                }
640            }
641        }
642        out
643    }
644
645    /// The sidebar's tree under a Topics entry for the page at `path`: for a
646    /// namespace, its crates; under each module, its modules and types by
647    /// kind. Functions and members are left to the pages, so the tree every
648    /// page carries stays small.
649    pub fn navigator(&self, path: &Path) -> Vec<crate::nav::Group> {
650        let Some(page) = self.page(path) else {
651            return Vec::new();
652        };
653        let (at, under) = match page {
654            Page::Namespace(at) => (at, Vec::new()),
655            Page::Item(at, path) => (at, path),
656            Page::Member(..) => return Vec::new(),
657        };
658        let namespace = &self.namespaces[at];
659        let items = namespace.items();
660        self.nav_children(&namespace.name, &items, &under)
661    }
662
663    /// The sidebar's groups for the items directly under `under`: its
664    /// modules, each with its own, and its types, by kind.
665    fn nav_children(
666        &self,
667        namespace: &str,
668        items: &Items,
669        under: &[String],
670    ) -> Vec<crate::nav::Group> {
671        const SHOWN: [(&str, &str); 7] = [
672            ("module", "Modules"),
673            ("struct", "Structures"),
674            ("enum", "Enumerations"),
675            ("union", "Unions"),
676            ("trait", "Traits"),
677            ("type", "Type Aliases"),
678            ("macro", "Macros"),
679        ];
680        let children: Vec<&Item> = items
681            .items
682            .values()
683            .filter(|item| item.path.len() == under.len() + 1 && item.path.starts_with(under))
684            .collect();
685        let mut groups = Vec::new();
686        for (kind, title) in SHOWN {
687            let entries: Vec<crate::nav::Entry> = children
688                .iter()
689                .filter(|item| item.kind == kind)
690                .map(|item| crate::nav::Entry {
691                    label: item.path.last().cloned().unwrap_or_default(),
692                    file: {
693                        let mut file = self.reference().join(namespace);
694                        for segment in &item.path {
695                            file.push(segment);
696                        }
697                        file
698                    },
699                    children: if kind == "module" {
700                        self.nav_children(namespace, items, &item.path)
701                    } else {
702                        Vec::new()
703                    },
704                })
705                .collect();
706            if !entries.is_empty() {
707                // A namespace's crates are one untitled group.
708                let title = (!under.is_empty()).then(|| title.to_string());
709                groups.push(crate::nav::Group { title, entries });
710            }
711        }
712        groups
713    }
714
715    /// A source file's address and its name, for an item's "declared in".
716    pub(crate) fn source(&self, file: &Path) -> Option<(String, String)> {
717        Some((self.served.url(file)?, self.served.name(file)?))
718    }
719
720    /// The ids `path`'s page holds, for a link's `#fragment`; `None` when
721    /// `path` is no page of the reference.
722    pub fn ids(&self, path: &Path) -> Option<Vec<String>> {
723        let page = self.page(path)?;
724        let rendered = crate::page::content(
725            &crate::widgets::Widgets::default(),
726            path,
727            self.markdown(&page),
728        );
729        Some(rendered.ids().into_iter().collect())
730    }
731
732    /// Whether `path` lies where the reference's pages are.
733    pub fn owns(&self, path: &Path) -> bool {
734        path.starts_with(self.reference())
735    }
736
737    /// The page nearest to `path`, which names none: the item of the same
738    /// last name, else the closest path by edit distance.
739    pub fn closest(&self, path: &Path) -> Option<String> {
740        let relative = path.strip_prefix(self.reference()).ok()?;
741        let mut parts = relative
742            .components()
743            .map(|part| part.as_os_str().to_string_lossy().into_owned());
744        let name = parts.next()?;
745        let namespace = self.namespaces.iter().find(|n| n.name == name)?;
746        let wanted: Vec<String> = parts.collect();
747        let last = wanted.last()?;
748        let items = namespace.items();
749        let joined = wanted.join("::");
750        // Every page: each item's, and each of its members'.
751        let pages = items.items.iter().flat_map(|(path, item)| {
752            std::iter::once(path.clone()).chain(item.members.iter().map(move |member| {
753                let mut path = path.clone();
754                path.push(member.name.clone());
755                path
756            }))
757        });
758        let best = pages.min_by_key(|path| {
759            (
760                path.last() != Some(last),
761                distance(&path.join("::"), &joined),
762            )
763        })?;
764        Some(self.address(&namespace.name, &best))
765    }
766
767    /// Every changed file of a namespace parsed again and the namespace
768    /// linked again; prose read again when a Markdown file changed.
769    fn changed(&self, files: &[PathBuf]) -> bool {
770        let mut any = false;
771        for namespace in &self.namespaces {
772            // A new query reads every file anew; one that doesn't compile
773            // is a problem, and the last that did keeps reading.
774            if namespace
775                .query
776                .as_ref()
777                .is_some_and(|query| files.iter().any(|f| f == query))
778            {
779                match grammar(&namespace.language, namespace.query.as_deref()) {
780                    Ok(grammar) => {
781                        *namespace.grammar.write().unwrap() = Arc::new(grammar);
782                        *namespace.query_error.write().unwrap() = None;
783                        namespace.parse_all();
784                    }
785                    Err(error) => {
786                        let message = error.root_cause().to_string();
787                        let line = message
788                            .strip_prefix("line ")
789                            .and_then(|rest| rest.split(':').next())
790                            .and_then(|line| line.parse().ok())
791                            .unwrap_or(1);
792                        let message = message
793                            .split_once(": ")
794                            .map_or(message.clone(), |(_, rest)| rest.to_string());
795                        *namespace.query_error.write().unwrap() = Some((line, message));
796                    }
797                }
798                any = true;
799                continue;
800            }
801            // A file new to the namespace walks its folders again, so a
802            // `.gitignore`d one is still left out.
803            if files.iter().any(|file| {
804                namespace.includes(file)
805                    && file.is_file()
806                    && !namespace.files.lock().unwrap().contains_key(file)
807            }) {
808                namespace.parse_all();
809                any = true;
810                continue;
811            }
812            let mut touched = false;
813            for file in files {
814                if !namespace.includes(file) {
815                    continue;
816                }
817                let mut parsed = namespace.files.lock().unwrap();
818                if !parsed.contains_key(file) {
819                    continue;
820                }
821                match std::fs::read_to_string(file) {
822                    Ok(source) => {
823                        let grammar = namespace.grammar.read().unwrap().clone();
824                        parsed.insert(file.clone(), Arc::new(grammar.extract(&source)));
825                    }
826                    Err(_) => {
827                        parsed.remove(file);
828                    }
829                }
830                touched = true;
831            }
832            if touched {
833                namespace.link();
834                any = true;
835            }
836        }
837        if files.iter().any(|file| {
838            file.extension().is_some_and(|ext| ext == "md") && file.starts_with(&self.base)
839        }) {
840            any |= self.read_prose();
841        }
842        any
843    }
844
845    /// Every Markdown file of the site headed ``# ``<namespace>:<path>`` ``:
846    /// whether what they add changed.
847    fn read_prose(&self) -> bool {
848        let mut found: BTreeMap<String, Prose> = BTreeMap::new();
849        let mut twice = Vec::new();
850        let walk = ignore::WalkBuilder::new(&self.base)
851            .hidden(true)
852            .require_git(false)
853            .build();
854        let mut files: Vec<PathBuf> = walk
855            .flatten()
856            .map(|entry| entry.into_path())
857            .filter(|path| path.extension().is_some_and(|ext| ext == "md"))
858            .collect();
859        // In path order, so the first of two for one id is always the same.
860        files.sort();
861        for path in files {
862            let Ok(source) = std::fs::read_to_string(&path) else {
863                continue;
864            };
865            let Some((id, line, body)) = prose_of(&source) else {
866                continue;
867            };
868            let added = Prose {
869                file: path,
870                line,
871                body,
872            };
873            match found.get(&id) {
874                Some(first) => twice.push((added, id, first.file.clone())),
875                None => {
876                    found.insert(id, added);
877                }
878            }
879        }
880        *self.twice.write().unwrap() = twice;
881        let mut prose = self.prose.write().unwrap();
882        let same = prose.len() == found.len()
883            && prose
884                .iter()
885                .zip(&found)
886                .all(|((a, x), (b, y))| a == b && x.body == y.body && x.file == y.file);
887        *prose = found;
888        !same
889    }
890
891    /// Every file the reference is made from, for a publish to carry: each
892    /// namespace's source files, the `Cargo.toml` that names each one's
893    /// crate, its query file, and every prose file.
894    pub fn files(&self) -> Vec<PathBuf> {
895        let mut files = std::collections::BTreeSet::new();
896        for namespace in &self.namespaces {
897            for file in namespace.files.lock().unwrap().keys() {
898                files.insert(file.clone());
899                let mut at = file.parent();
900                while let Some(folder) = at {
901                    let manifest = folder.join("Cargo.toml");
902                    if manifest.is_file() {
903                        files.insert(manifest);
904                        break;
905                    }
906                    at = folder.parent();
907                }
908            }
909            files.extend(namespace.query.clone());
910        }
911        let prose = self.prose.read().unwrap();
912        files.extend(prose.values().map(|prose| prose.file.clone()));
913        files.extend(
914            self.twice
915                .read()
916                .unwrap()
917                .iter()
918                .map(|(prose, ..)| prose.file.clone()),
919        );
920        files
921            .into_iter()
922            .filter(|file| self.served.contains(file))
923            .collect()
924    }
925
926    /// What is wrong with the reference, for its pages to list and
927    /// `devpage check` to report: a prose file whose id names nothing, and
928    /// a query saved while devpage runs that doesn't compile.
929    pub fn problems(&self) -> Vec<crate::problem::Problem> {
930        let mut problems: Vec<crate::problem::Problem> = self
931            .orphans()
932            .into_iter()
933            .map(|(prose, id)| crate::problem::Problem {
934                file: self.served.name(&prose.file).unwrap_or_default(),
935                line: Some(prose.line),
936                column: None,
937                message: format!("``{id}`` names no code"),
938                target: None,
939            })
940            .collect();
941        for (prose, id, first) in self.twice.read().unwrap().iter() {
942            problems.push(crate::problem::Problem {
943                file: self.served.name(&prose.file).unwrap_or_default(),
944                line: Some(prose.line),
945                column: None,
946                message: format!(
947                    "``{id}`` is added to by {} already",
948                    self.served.name(first).unwrap_or_default()
949                ),
950                target: None,
951            });
952        }
953        for namespace in &self.namespaces {
954            if let Some((line, message)) = namespace.query_error.read().unwrap().clone()
955                && let Some(query) = &namespace.query
956            {
957                problems.push(crate::problem::Problem {
958                    file: self.served.name(query).unwrap_or_default(),
959                    line: Some(line),
960                    column: None,
961                    message: format!("query doesn't compile: {message}"),
962                    target: None,
963                });
964            }
965        }
966        problems
967    }
968
969    /// Every prose file whose id names no item: `(file, id)`.
970    pub fn orphans(&self) -> Vec<(Prose, String)> {
971        let prose = self.prose.read().unwrap();
972        prose
973            .iter()
974            .filter(|(id, _)| {
975                let Some((name, path)) = id.split_once(':') else {
976                    return true;
977                };
978                // An item's id, or a member's under its type's.
979                let mut file = self.reference().join(name);
980                for segment in path.split("::") {
981                    file.push(segment);
982                }
983                self.page(&file).is_none()
984            })
985            .map(|(id, prose)| (prose.clone(), id.clone()))
986            .collect()
987    }
988}
989
990/// A prose file's id and what it adds: the file's first line is
991/// ``# ``<id>`` ``; the rest is the body.
992fn prose_of(source: &str) -> Option<(String, usize, String)> {
993    let mut lines = source.lines().enumerate();
994    let (at, first) = lines.find(|(_, line)| !line.trim().is_empty())?;
995    let id = first
996        .trim()
997        .strip_prefix("# ``")?
998        .strip_suffix("``")?
999        .trim()
1000        .to_string();
1001    id.contains(':').then(|| {
1002        let body = lines.map(|(_, line)| line).collect::<Vec<_>>().join("\n");
1003        (id, at + 1, body)
1004    })
1005}
1006
1007/// The edit distance between two names.
1008fn distance(a: &str, b: &str) -> usize {
1009    let b: Vec<char> = b.chars().collect();
1010    let mut row: Vec<usize> = (0..=b.len()).collect();
1011    for (i, ca) in a.chars().enumerate() {
1012        let mut previous = row[0];
1013        row[0] = i + 1;
1014        for (j, cb) in b.iter().enumerate() {
1015            let next = (row[j + 1] + 1)
1016                .min(row[j] + 1)
1017                .min(previous + usize::from(ca != *cb));
1018            previous = row[j + 1];
1019            row[j + 1] = next;
1020        }
1021    }
1022    row[b.len()]
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    /// A version server mode drops takes its code reference with it.
1028    #[test]
1029    fn a_forgotten_folder_holds_no_code_reference() {
1030        let dir = std::env::temp_dir().join(format!("devpage-code-forget-{}", std::process::id()));
1031        let _ = std::fs::remove_dir_all(&dir);
1032        std::fs::create_dir_all(dir.join("lib/src")).unwrap();
1033        std::fs::write(dir.join("lib/Cargo.toml"), "[package]\nname = \"a\"\n").unwrap();
1034        std::fs::write(dir.join("lib/src/lib.rs"), "pub struct A;\n").unwrap();
1035        std::fs::write(dir.join("README.md"), "# A\n").unwrap();
1036        std::fs::write(
1037            dir.join("devpage.yml"),
1038            "kind: site\ntitle: A\nroot: README.md\nextensions:\n  code:\n    config:\n      rust:\n        files: [\"lib/src/**/*.rs\"]\n",
1039        )
1040        .unwrap();
1041        let served = crate::folder::ServedFolder::new(&dir).unwrap();
1042        let doc = crate::document::Document::load(&dir.join("devpage.yml"), &served).unwrap();
1043        assert!(super::for_document(&doc.path()).is_some());
1044        super::forget(&dir);
1045        assert!(super::for_document(&doc.path()).is_none());
1046    }
1047
1048    /// devpage's own code, as its docs' code reference reads it: every
1049    /// item, field, variant and method has a doc comment, so every page of
1050    /// the reference says what it is.
1051    #[test]
1052    fn every_item_of_devpages_code_is_documented() {
1053        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1054            .parent()
1055            .unwrap()
1056            .canonicalize()
1057            .unwrap();
1058        let served = crate::folder::ServedFolder::new(&root).unwrap();
1059        let doc = crate::document::Document::load(&root.join("docs/devpage.yml"), &served).unwrap();
1060        let index = super::for_document(&doc.path()).unwrap();
1061        let mut undocumented = Vec::new();
1062        for namespace in &index.namespaces {
1063            for item in namespace.items().items.values() {
1064                let file = served.name(&item.file).unwrap_or_default();
1065                if item.doc.trim().is_empty() {
1066                    undocumented.push(format!("{file}:{}: {}", item.line, item.path.join("::")));
1067                }
1068                for member in &item.members {
1069                    if member.doc.trim().is_empty() {
1070                        let file = served.name(&member.file).unwrap_or_default();
1071                        undocumented.push(format!(
1072                            "{file}:{}: {}::{}",
1073                            member.line,
1074                            item.path.join("::"),
1075                            member.name
1076                        ));
1077                    }
1078                }
1079            }
1080        }
1081        assert!(
1082            undocumented.is_empty(),
1083            "undocumented:\n{}",
1084            undocumented.join("\n")
1085        );
1086    }
1087}