diplodocus 0.15.0

Build coherent documentation websites for polyglot software projects.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Static Documenter assembly over already extracted Julia declarations.

use std::collections::{BTreeMap, BTreeSet};

use fatou_parser::ast::{AstNode, AstToken, Expr, StringLiteral};

use crate::diagnostics::{
    Diagnostic, DiagnosticCode, DiagnosticEntity, DiagnosticSource, Severity,
};
use crate::documents::AuthoredFormat;
use crate::ir::*;

#[derive(Default)]
struct Options {
    modules: Vec<String>,
    pages: Vec<String>,
    private: Option<bool>,
    public: Option<bool>,
}

fn options(source: &str) -> Result<Options, &'static str> {
    let parsed = fatou_parser::parser::parse(source);
    if !parsed.diagnostics.is_empty() {
        return Err("Malformed Documenter directive options.");
    }
    let module_name = regex::Regex::new(
        r"^[\p{XID_Start}_][\p{XID_Continue}]*(?:\.[\p{XID_Start}_][\p{XID_Continue}]*)*$",
    )
    .unwrap();
    let mut options = Options::default();
    let mut seen = BTreeSet::new();
    for node in parsed.cst.children() {
        let Some(Expr::AssignmentExpr(assignment)) = Expr::cast(node) else {
            return Err("Documenter options must be literal assignments.");
        };
        if assignment.op().is_none_or(|op| op.text() != "=") {
            return Err("Documenter options require `=` assignments.");
        }
        let Some(Expr::Name(name)) = assignment.lhs() else {
            return Err("Documenter options require simple names.");
        };
        let name = name.syntax().text().to_string();
        if !seen.insert(name.clone()) {
            return Err("Duplicate Documenter directive option.");
        }
        let value = assignment.rhs().ok_or("Missing Documenter option value.")?;
        match name.as_str() {
            "Modules" => {
                let Expr::VectExpr(modules) = value else {
                    return Err("`Modules` must be a literal vector of module names.");
                };
                for module in modules.syntax().children() {
                    let name = module.text().to_string();
                    if !module_name.is_match(&name) || options.modules.contains(&name) {
                        return Err("`Modules` requires distinct, qualified module names.");
                    }
                    options.modules.push(name);
                }
                if options.modules.is_empty() {
                    return Err("`Modules` must contain at least one module.");
                }
            }
            "Private" | "Public" => {
                let boolean = match value.syntax().text().to_string().as_str() {
                    "true" => true,
                    "false" => false,
                    _ => return Err("`Private` and `Public` must be literal booleans."),
                };
                if name == "Private" {
                    options.private = Some(boolean);
                } else {
                    options.public = Some(boolean);
                }
            }
            "Pages" => {
                let Expr::VectExpr(pages) = value else {
                    return Err("`Pages` must be a literal vector of source-file suffix strings.");
                };
                for page in pages.syntax().children() {
                    let literal = page
                        .children()
                        .next()
                        .and_then(StringLiteral::cast)
                        .filter(|literal| {
                            literal.prefix().is_none()
                                && literal.suffix().is_none()
                                && literal.interpolations().next().is_none()
                        })
                        .ok_or("`Pages` requires ordinary strings without interpolation.")?;
                    let path = fatou_parser::parser::string_value(
                        &literal
                            .content_tokens()
                            .map(|token| token.text().to_owned())
                            .collect::<String>(),
                    )
                    .map_err(|_| "Invalid string escape in `Pages`.")?;
                    if path.is_empty() {
                        return Err("`Pages` entries must not be empty.");
                    }
                    let path = normalized_suffix(&path);
                    if options.pages.contains(&path) {
                        return Err("`Pages` requires distinct source-file suffixes.");
                    }
                    options.pages.push(path);
                }
            }
            _ => {
                return Err(
                    "Supported `@autodocs` options are `Modules`, `Pages`, `Private`, and `Public`.",
                );
            }
        }
    }
    Ok(options)
}

fn normalized_suffix(path: &str) -> String {
    let mut parts = Vec::new();
    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." if parts.last().is_some_and(|part| *part != "..") => {
                parts.pop();
            }
            _ => parts.push(part),
        }
    }
    format!(
        "{}{}",
        if path.starts_with('/') { "/" } else { "" },
        if parts.is_empty() && !path.starts_with('/') {
            ".".into()
        } else {
            parts.join("/")
        }
    )
}

fn members(item: &Item) -> &[ItemReference] {
    match &item.language_data {
        Some(ItemLanguageData::Julia(data)) => match &data.declaration {
            JuliaDeclaration::Callable {
                role: JuliaCallableRole::Family { methods },
                ..
            } => methods,
            JuliaDeclaration::Type { constructors, .. } => constructors,
            _ => &[],
        },
        _ => &[],
    }
}

struct Entry {
    item: ItemReference,
    selection: Vec<ItemReference>,
}

struct CatalogEntry {
    page: String,
    entry: Entry,
    anchor: String,
}

fn entry(workspace: &Workspace, item: ItemReference) -> Entry {
    let selection = std::iter::once(&item)
        .chain(members(
            &workspace.packages[&item.package].items[&item.item],
        ))
        .cloned()
        .collect();
    Entry { item, selection }
}

fn documented(workspace: &Workspace, reference: &ItemReference) -> bool {
    let item = &workspace.packages[&reference.package].items[&reference.item];
    item.documentation.is_some()
        || members(item)
            .iter()
            .any(|member| documented(workspace, member))
}

fn explicit(
    workspace: &Workspace,
    owner: &ContentOwner,
    source: &str,
) -> Result<Vec<Entry>, String> {
    let parsed = fatou_parser::parser::parse(source);
    if !parsed.diagnostics.is_empty() {
        return Err("Malformed `@docs` selectors.".into());
    }
    let binding = regex::Regex::new(
        r"^(?:@?[\p{XID_Start}_][\p{XID_Continue}!]*)(?:\.@?[\p{XID_Start}_][\p{XID_Continue}!]*)*$",
    ).unwrap();
    let owner = match owner {
        ContentOwner::Package { package } => Some(package.as_str()),
        ContentOwner::Project => None,
    };
    let mut entries = Vec::new();
    for node in parsed.cst.children() {
        let target = node.text().to_string();
        let target = target.trim();
        if !binding.is_match(target)
            && !crate::extractors::julia::method_selector(target)
                .is_some_and(|(name, _)| binding.is_match(&name))
        {
            return Err("`@docs` supports binding names and exact method selectors.".into());
        }
        let item = crate::validation::resolve_item(workspace, owner, target)
            .or_else(|code| {
                // Julia modules bind their own name, as in `SLOPE.SLOPE`.
                if code == DiagnosticCode::UnresolvedItemReference
                    && let Some((parent, name)) = target.rsplit_once('.')
                    && parent.rsplit('.').next() == Some(name)
                    && let Ok(reference) = crate::validation::resolve_item(workspace, owner, parent)
                    && matches!(&workspace.packages[&reference.package].items[&reference.item].language_data,
                        Some(ItemLanguageData::Julia(data)) if matches!(data.declaration, JuliaDeclaration::Module { .. })) {
                    return Ok(reference);
                }
                Err(code)
            })
            .map_err(|code| format!("`@docs` selector `{target}` must identify exactly one extracted Julia item ({code:?})."))?;
        if !matches!(
            workspace.packages[&item.package].items[&item.item].language_data,
            Some(ItemLanguageData::Julia(_))
        ) {
            return Err(format!(
                "`@docs` selector `{target}` must identify a Julia item."
            ));
        }
        if !documented(workspace, &item) {
            return Err(format!(
                "`@docs` selector `{target}` has no retained documentation."
            ));
        }
        entries.push(entry(workspace, item));
    }
    if entries.is_empty() {
        return Err("`@docs` requires at least one binding or method selector.".into());
    }
    Ok(entries)
}

fn select(workspace: &Workspace, options: &Options) -> Result<Vec<Entry>, &'static str> {
    if options.modules.is_empty() {
        return Err("`@autodocs` requires `Modules = [Module, ...]`.");
    }
    let mut selected = Vec::new();
    for module in &options.modules {
        let packages: Vec<_> = workspace.packages.iter().filter(|(_, package)| {
            package.items.values().any(|item| matches!(&item.language_data,
                Some(ItemLanguageData::Julia(data)) if data.defining_module == *module
                    || matches!(data.declaration, JuliaDeclaration::Module { .. }) && item.qualified_name == *module))
        }).collect();
        let [(package_id, package)] = packages.as_slice() else {
            return Err("Each `Modules` entry must identify one extracted Julia module.");
        };
        let mut entries: Vec<_> = package
            .items
            .iter()
            .filter_map(|(id, item)| {
                let Some(ItemLanguageData::Julia(data)) = &item.language_data else {
                    return None;
                };
                if data.defining_module != *module
                    || matches!(
                        data.declaration,
                        JuliaDeclaration::Field { .. }
                            | JuliaDeclaration::Callable {
                                role: JuliaCallableRole::Method { .. },
                                ..
                            }
                    )
                    || (data.visibility == JuliaVisibility::Private
                        && options.private == Some(false))
                    || (data.visibility != JuliaVisibility::Private
                        && options.public == Some(false))
                    || (item.documentation.is_none()
                        && !members(item)
                            .iter()
                            .any(|member| package.items[&member.item].documentation.is_some()))
                {
                    return None;
                }
                let order = match data.declaration {
                    JuliaDeclaration::Module { .. } => 0,
                    JuliaDeclaration::Constant => 1,
                    JuliaDeclaration::Type { .. } => 2,
                    JuliaDeclaration::Callable {
                        binding: JuliaCallableKind::Macro,
                        ..
                    } => 4,
                    _ => 3,
                };
                let mut entry = entry(
                    workspace,
                    ItemReference {
                        package: (*package_id).clone(),
                        item: id.clone(),
                    },
                );
                let mut page_order = 0;
                if !options.pages.is_empty() {
                    let mut matched: Vec<_> = entry
                        .selection
                        .into_iter()
                        .filter_map(|reference| {
                            let document = package.items[&reference.item].documentation.as_ref()?;
                            let path = document.source_location.as_ref()?.path.as_str();
                            let index = options
                                .pages
                                .iter()
                                .position(|suffix| path.ends_with(suffix))?;
                            Some((index, reference))
                        })
                        .collect();
                    matched.sort_by_key(|(index, _)| *index);
                    page_order = matched.first()?.0;
                    entry.selection = matched
                        .into_iter()
                        .map(|(_, reference)| reference)
                        .collect();
                }
                Some((page_order, order, &item.qualified_name, entry))
            })
            .collect();
        entries.sort_by(|a, b| (&a.0, &a.1, a.2).cmp(&(&b.0, &b.1, b.2)));
        selected.extend(entries.into_iter().map(|(_, _, _, entry)| entry));
    }
    Ok(selected)
}

pub(super) fn assemble(
    workspace: &mut Workspace,
    prepared: &BTreeMap<String, super::PreparedPage>,
) {
    let pages: Vec<_> = workspace
        .pages
        .iter()
        .filter_map(|(id, page)| {
            let PageKind::Authored { collection } = &page.kind else {
                return None;
            };
            (workspace.content_collections[collection].format == AuthoredFormat::Documenter)
                .then(|| (id.clone(), collection.clone()))
        })
        .collect();
    let mut catalog: BTreeMap<String, Vec<CatalogEntry>> = BTreeMap::new();
    for (id, collection) in &pages {
        let mut page = workspace.pages.remove(id).unwrap();
        let location = page.document.source_location.clone().unwrap();
        rewrite(&mut page.document.document.blocks, &mut |block| {
            let Block::CodeBlock {
                language: Some(language),
                source,
                span,
                ..
            } = block
            else {
                return None;
            };
            if !matches!(language.as_str(), "@docs" | "@autodocs" | "@index") {
                return None;
            }
            let result = match language.as_str() {
                "@docs" => explicit(workspace, &page.owner, source).map(Some),
                "@autodocs" => options(source)
                    .and_then(|options| select(workspace, &options))
                    .map(Some)
                    .map_err(str::to_owned),
                _ => {
                    if source.trim().is_empty() {
                        Ok(None)
                    } else {
                        Err("`@index` currently accepts an empty body only.".into())
                    }
                }
            };
            match result {
                Ok(Some(items)) => {
                    let entries = catalog.entry(collection.clone()).or_default();
                    let mut blocks = Vec::new();
                    for entry in items {
                        if entries.iter().any(|other| {
                            other.entry.item == entry.item
                                || entry
                                    .selection
                                    .iter()
                                    .any(|reference| other.entry.selection.contains(reference))
                        }) {
                            workspace.diagnostics.insert(error(&location, collection, &prepared[id].relative, *span, "An API item or its documentation may appear in only one `@docs` or `@autodocs` selection per collection."));
                            continue;
                        }
                        let digest = crate::provenance::fingerprint_bytes(
                            format!("{}:{}", entry.item.package, entry.item.item).as_bytes(),
                        );
                        let identifier = format!("api-{}", digest.value);
                        blocks.push(Block::ApiDocumentation {
                            item: entry.item.clone(),
                            selection: entry.selection.clone(),
                            identifier: identifier.clone(),
                            span: *span,
                        });
                        entries.push(CatalogEntry {
                            page: id.clone(),
                            entry,
                            anchor: identifier,
                        });
                    }
                    Some(blocks)
                }
                Ok(None) => None,
                Err(message) => {
                    workspace.diagnostics.insert(error(
                        &location,
                        collection,
                        &prepared[id].relative,
                        *span,
                        &message,
                    ));
                    None
                }
            }
        });
        workspace.pages.insert(id.clone(), page);
    }
    for (id, collection) in pages {
        let mut page = workspace.pages.remove(&id).unwrap();
        let from = page.document.source_location.as_ref().unwrap();
        rewrite(&mut page.document.document.blocks, &mut |block| {
            let Block::CodeBlock {
                language: Some(language),
                span,
                ..
            } = block
            else {
                return None;
            };
            if language != "@index" {
                return None;
            }
            let mut entries: Vec<_> = catalog.get(&collection).into_iter().flatten().collect();
            entries.sort_by_key(|entry| {
                let item = &entry.entry.item;
                &workspace.packages[&item.package].items[&item.item].qualified_name
            });
            Some(vec![Block::List {
                ordered: false,
                items: entries
                    .into_iter()
                    .map(|entry| {
                        let item = &entry.entry.item;
                        let anchor = &entry.anchor;
                        let target = workspace
                            .pages
                            .get(&entry.page)
                            .map_or(from, |page| page.document.source_location.as_ref().unwrap());
                        let target = format!(
                            "{}#{anchor}",
                            relative_link(from.path.as_str(), target.path.as_str())
                        );
                        ListItem {
                            checked: None,
                            blocks: vec![Block::Paragraph {
                                inlines: vec![Inline::Link {
                                    inlines: vec![Inline::Code {
                                        value: workspace.packages[&item.package].items[&item.item]
                                            .qualified_name
                                            .clone(),
                                        span: *span,
                                    }],
                                    target,
                                    title: None,
                                    attributes: Attributes::default(),
                                    span: *span,
                                }],
                                span: *span,
                            }],
                            span: *span,
                        }
                    })
                    .collect(),
                span: *span,
            }])
        });
        workspace.pages.insert(id, page);
    }
}

fn error(
    source: &SourceLocation,
    collection: &str,
    path: &crate::diagnostics::DiagnosticPath,
    span: SourceSpan,
    message: &str,
) -> Diagnostic {
    let mut diagnostic = Diagnostic::new(
        DiagnosticCode::UnsupportedAuthoredSyntax,
        Severity::Error,
        message,
    )
    .with_entity(DiagnosticEntity::Document {
        collection: collection.into(),
        path: path.clone(),
    })
    .with_source(DiagnosticSource::Repository {
        repository: source.repository.clone(),
        path: source.path.clone(),
    });
    diagnostic.span = Some(span);
    diagnostic
}

fn relative_link(from: &str, to: &str) -> String {
    let mut from: Vec<_> = from.split('/').collect();
    from.pop();
    let to: Vec<_> = to.split('/').collect();
    let common = from.iter().zip(&to).take_while(|(a, b)| a == b).count();
    let path = std::iter::repeat_n("..", from.len() - common)
        .chain(to[common..].iter().copied())
        .collect::<Vec<_>>()
        .join("/");
    const PATH: &percent_encoding::AsciiSet = &percent_encoding::CONTROLS
        .add(b' ')
        .add(b'#')
        .add(b'?')
        .add(b'%');
    percent_encoding::utf8_percent_encode(&path, PATH).to_string()
}

fn rewrite(blocks: &mut Vec<Block>, f: &mut impl FnMut(&Block) -> Option<Vec<Block>>) {
    let mut result = Vec::new();
    for mut block in std::mem::take(blocks) {
        if let Some(replacement) = f(&block) {
            result.extend(replacement);
            continue;
        }
        match &mut block {
            Block::BlockQuote { blocks, .. }
            | Block::Callout { blocks, .. }
            | Block::Container { blocks, .. }
            | Block::Component { blocks, .. }
            | Block::Tabset { blocks, .. } => rewrite(blocks, f),
            Block::List { items, .. } => {
                for item in items {
                    rewrite(&mut item.blocks, f);
                }
            }
            Block::Table { rows, .. } => {
                for row in rows {
                    for cell in &mut row.cells {
                        rewrite(&mut cell.blocks, f);
                    }
                }
            }
            _ => {}
        }
        result.push(block);
    }
    *blocks = result;
}