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
//! Versioned, portable workspace records.
//!
//! Map keys are the authoritative entity IDs; records do not duplicate them.
//! Targets and items are keyed within a package. Maps and sets serialize in
//! sorted order; vectors retain semantic declaration or event order. This model
//! does not resolve references, assign IDs, inspect paths, or collect provenance.
//! Paths use the same validated spelling as diagnostics. A missing root path
//! means the declared repository or package root, never a machine checkout.

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

use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub use crate::configuration::{
    ConceptKind, ContentNavigation, ExecutionEngine, ExecutionMode, PackageKind, PackageVisibility,
    RelationshipKind,
};
use crate::diagnostics::{Diagnostic, DiagnosticPath};
use crate::documents::AuthoredFormat;

use super::{
    Document, Fingerprint, ItemAlias, ItemLanguageData, JuliaCallableRole, JuliaDeclaration,
    JuliaVisibility, PackageMetadata, Provenance, SourceSpan, SourcedSignature,
};

/// Current portable workspace schema version.
pub const WORKSPACE_SCHEMA_VERSION: u32 = 16;

/// The supported schema version, serialized as the integer `15`.
///
/// Deserialization rejects unsupported versions instead of interpreting another
/// schema as this one. The workspace version field is required even though a
/// newly constructed Rust workspace defaults to the current version.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SchemaVersion;

impl Serialize for SchemaVersion {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u32(WORKSPACE_SCHEMA_VERSION)
    }
}

impl<'de> Deserialize<'de> for SchemaVersion {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let version = u32::deserialize(deserializer)?;
        if version != WORKSPACE_SCHEMA_VERSION {
            return Err(serde::de::Error::custom(format!(
                "unsupported workspace IR schema version {version}; expected {WORKSPACE_SCHEMA_VERSION}"
            )));
        }
        Ok(Self)
    }
}

/// One coherent documentation snapshot from explicitly supplied repositories.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Workspace {
    /// Required wire-schema discriminator.
    pub schema_version: SchemaVersion,
    /// Project display name.
    pub name: String,
    /// Repositories keyed by workspace repository ID.
    pub repositories: BTreeMap<String, Repository>,
    /// Packages keyed by workspace package ID.
    pub packages: BTreeMap<String, Package>,
    /// Authored collections keyed by workspace collection ID.
    pub content_collections: BTreeMap<String, ContentCollection>,
    /// Pages keyed by semantic page ID, independent of rendered URLs.
    pub pages: BTreeMap<String, Page>,
    /// Concepts keyed by workspace concept ID.
    pub concepts: BTreeMap<String, Concept>,
    /// Relationships in declaration order.
    pub relationships: Vec<PackageRelationship>,
    /// Unique diagnostics in the common model's deterministic order.
    pub diagnostics: BTreeSet<Diagnostic>,
    /// Snapshot evidence in producer-defined source order.
    pub provenance: Vec<Provenance>,
}

/// Portable repository identity and observed revision information.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Repository {
    /// Canonical public origin, never a local checkout path.
    pub canonical_url: Option<String>,
    /// Forge-specific source-link template.
    pub source_link_template: Option<String>,
    /// Declared or observed revision when available.
    pub revision: Option<String>,
    /// Observed working-tree state; `None` means unknown.
    pub dirty: Option<bool>,
    /// Fingerprint of declared inputs when collected.
    pub declared_input_fingerprint: Option<Fingerprint>,
}

/// A documented package or internal component.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Package {
    /// Site-wide URL slug, separate from the package ID.
    pub slug: String,
    /// Package display name.
    pub name: String,
    /// Ecosystem of the public API.
    pub ecosystem: String,
    /// Extracted package version, if available.
    pub version: Option<String>,
    /// Extracted package information, including ecosystem-specific source evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<PackageMetadata>,
    /// Owning repository ID.
    pub repository: String,
    /// Repository-relative package root; `None` means the repository root.
    pub path: Option<DiagnosticPath>,
    /// Package-relative metadata file.
    pub metadata_path: DiagnosticPath,
    /// Package or component classification.
    pub kind: PackageKind,
    /// Navigation and search visibility.
    pub visibility: PackageVisibility,
    /// Extraction targets keyed by package-scoped target ID.
    pub extraction_targets: BTreeMap<String, ExtractionTarget>,
    /// API items keyed by package-scoped semantic item ID.
    pub items: BTreeMap<String, Item>,
}

impl Package {
    /// Item IDs that belong in automatic API navigation, search, and indexes.
    ///
    /// Julia methods inherit discovery from their family or type. The root and
    /// enclosing modules remain discoverable as containers, without exposing
    /// private children or fields. Aliases share their canonical item's visibility.
    /// Package visibility is applied separately by the consumer.
    pub fn discoverable_items(&self) -> BTreeSet<&str> {
        let mut discoverable: BTreeSet<_> = self
            .items
            .iter()
            .filter(|(_, item)| match &item.language_data {
                Some(ItemLanguageData::Julia(data)) => match &data.declaration {
                    JuliaDeclaration::Module { .. } if data.defining_module.is_empty() => true,
                    JuliaDeclaration::Callable {
                        role: JuliaCallableRole::Method { .. },
                        ..
                    } => false,
                    _ => item.discoverable(),
                },
                _ => item.discoverable(),
            })
            .map(|(id, _)| id.as_str())
            .collect();

        for (id, item) in &self.items {
            if let Some(ItemLanguageData::Julia(data)) = &item.language_data
                && let JuliaDeclaration::Callable {
                    role: JuliaCallableRole::Method { family, .. },
                    ..
                } = &data.declaration
                && discoverable.contains(family.item.as_str())
            {
                discoverable.insert(id.as_str());
            }
        }

        let modules: BTreeMap<_, _> = self
            .items
            .iter()
            .filter(|(_, item)| {
                matches!(&item.language_data, Some(ItemLanguageData::Julia(data))
                    if matches!(data.declaration, JuliaDeclaration::Module { .. }))
            })
            .map(|(id, item)| (item.qualified_name.as_str(), id.as_str()))
            .collect();
        let mut pending: Vec<_> = discoverable.iter().copied().collect();
        while let Some(id) = pending.pop() {
            if let Some(ItemLanguageData::Julia(data)) = &self.items[id].language_data
                && let Some(&module) = modules.get(data.defining_module.as_str())
                && discoverable.insert(module)
            {
                pending.push(module);
            }
        }
        discoverable
    }
}

/// One authoritative source consumed by an extractor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExtractionTarget {
    /// Selected extractor identifier.
    pub extractor: String,
    /// Package-relative root; `None` means the package root.
    pub path: Option<DiagnosticPath>,
    /// Target role, such as `public-api`.
    pub role: String,
}

/// Authored sources with independent ownership and repository location.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContentCollection {
    /// Project or package owner.
    pub owner: ContentOwner,
    /// Repository containing these sources.
    pub repository: String,
    /// Repository-relative source directory or file; `None` means the repository root.
    pub path: Option<DiagnosticPath>,
    /// URL mount relative to the owner's documentation root.
    pub mount: String,
    /// Explicit authored profile.
    pub format: AuthoredFormat,
    /// Sidebar inclusion, independent of page rendering and search visibility.
    #[serde(default, skip_serializing_if = "ContentNavigation::is_default")]
    pub navigation: ContentNavigation,
    /// Portable declared execution settings.
    pub execution: ExecutionConfiguration,
}

/// Portable execution settings, separate from configuration's filesystem paths.
///
/// This is a declaration record, not execution authority. Collection policy and
/// document authority must still be validated before any execution.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExecutionConfiguration {
    /// Requested execution mode.
    pub mode: ExecutionMode,
    /// Selected engine when enabled.
    pub engine: Option<ExecutionEngine>,
    /// Explicit kernel selector when enabled.
    pub kernel: Option<String>,
    /// Repository-relative project file for prepared native Julia execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub julia_project: Option<DiagnosticPath>,
    /// Normalized repository-relative input files, sorted by path.
    pub declared_environment_inputs: BTreeSet<DiagnosticPath>,
}

/// Ownership does not depend on the repository containing a document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum ContentOwner {
    /// Project-wide documentation.
    Project,
    /// Documentation owned by one workspace package.
    Package {
        /// Workspace package ID.
        package: String,
    },
}

/// A page before URL assignment and rendering.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Page {
    /// Project or package owner.
    pub owner: ContentOwner,
    /// Semantic origin of the page.
    pub kind: PageKind,
    /// Display title.
    pub title: String,
    /// Structured content and its own source evidence.
    pub document: SourcedDocument,
}

/// Semantic page categories, independent of site routes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum PageKind {
    /// An authored collection page.
    Authored {
        /// Owning content collection ID.
        collection: String,
    },
    /// An API reference page.
    Api {
        /// Documented item.
        item: ItemReference,
    },
    /// A conceptual API group page.
    Concept {
        /// Workspace concept ID.
        concept: String,
    },
    /// Automatically discovered package documentation.
    PackageDocumentation {
        /// Stable purpose and route beneath the package root.
        role: PackagePageRole,
    },
    /// A generated project or package overview.
    Overview,
}

/// Conventional package pages, independent of source filenames.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PackagePageRole {
    /// Package README or DESCRIPTION overview.
    Overview,
    /// Release notes.
    News,
    /// Contributors and bibliography information.
    Authors,
    /// License declarations and local license text.
    License,
    /// Contribution guidelines and code of conduct.
    Community,
}

impl PackagePageRole {
    /// Stable filename under the package's documentation root.
    pub fn filename(self) -> &'static str {
        match self {
            Self::Overview => "index.html",
            Self::News => "news.html",
            Self::Authors => "authors.html",
            Self::License => "license.html",
            Self::Community => "community.html",
        }
    }

    /// Human-readable title of a supporting package page.
    pub fn title(self) -> &'static str {
        match self {
            Self::Overview => "Overview",
            Self::News => "News",
            Self::Authors => "Authors and citation",
            Self::License => "License",
            Self::Community => "Community",
        }
    }
}

/// Portable document envelope; the existing authored syntax tree is unchanged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourcedDocument {
    /// Structured content with document-relative byte spans.
    pub document: Document,
    /// Original authored or extractor-specific format.
    pub source_format: DocumentFormat,
    /// Original source location, which may differ from the item's definition.
    pub source_location: Option<SourceLocation>,
    /// Optional raw source retained for diagnostics.
    pub raw_source: Option<String>,
    /// Evaluated Markdown whose byte ranges index the rendered document.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generated_source: Option<String>,
    /// Document-specific evidence in source order.
    pub provenance: Vec<Provenance>,
}

/// Provenance of a document's original syntax.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum DocumentFormat {
    /// An authored Markdown profile.
    Authored {
        /// Explicit input profile.
        format: AuthoredFormat,
    },
    /// Extracted documentation, such as `numpy-docstring` or `rd`.
    Extracted {
        /// Stable source-format identifier.
        name: String,
    },
    /// Structured content generated without a source document.
    Generated,
}

/// An extracted API entity, whose ID is its key in the package's item map.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Item {
    /// Language-neutral item classification.
    pub kind: ItemKind,
    /// Unqualified display name.
    pub name: String,
    /// Language-qualified name; not assumed unique across overloads or aliases.
    pub qualified_name: String,
    /// Typed language semantics after reconciling all authoritative inputs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language_data: Option<ItemLanguageData>,
    /// Additional lookup names for this canonical entity, in declaration order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<ItemAlias>,
    /// Signatures in declaration order, each with independent source evidence.
    pub signatures: Vec<SourcedSignature>,
    /// Structured documentation when available.
    pub documentation: Option<SourcedDocument>,
    /// Definition location when available.
    pub source_location: Option<SourceLocation>,
    /// Child item IDs within this package, in declaration order.
    pub children: Vec<String>,
    /// Extraction evidence in source order.
    pub provenance: Vec<Provenance>,
}

impl Item {
    /// Whether the declaration's own facts qualify it for API discovery.
    ///
    /// Use [`Package::discoverable_items`] for automatic indexes, which also
    /// account for Julia method ownership and enclosing module containers.
    pub fn discoverable(&self) -> bool {
        match &self.language_data {
            Some(ItemLanguageData::Cpp(data)) => data.family.is_none(),
            Some(ItemLanguageData::R(data)) => !data.internal,
            Some(ItemLanguageData::Python(data)) => {
                data.visibility != super::PythonVisibility::Private
                    && !matches!(
                        &data.declaration,
                        super::PythonDeclaration::Callable {
                            role: super::PythonCallableRole::Overload { .. },
                            ..
                        }
                    )
            }
            Some(ItemLanguageData::Julia(data)) => {
                data.visibility != JuliaVisibility::Private
                    && !matches!(data.declaration, JuliaDeclaration::Field { .. })
            }
            _ => true,
        }
    }
}

/// Common API item categories; typed language extensions are a separate layer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ItemKind {
    /// A module.
    Module,
    /// A callable function.
    Function,
    /// A method associated with a type or generic.
    Method,
    /// A type declaration.
    Type,
    /// A class declaration.
    Class,
    /// A named constant.
    Constant,
    /// A field or attribute.
    Field,
    /// A namespace.
    Namespace,
}

/// A package-scoped semantic item reference, independent of its rendered URL.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ItemReference {
    /// Workspace package ID.
    pub package: String,
    /// Extractor-assigned item ID within that package.
    pub item: String,
}

/// A package-scoped extraction target reference.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TargetReference {
    /// Workspace package ID.
    pub package: String,
    /// Target ID within that package.
    pub target: String,
}

/// A file and optional source range without a machine-specific root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceLocation {
    /// Workspace repository ID.
    pub repository: String,
    /// Normalized repository-relative path.
    pub path: DiagnosticPath,
    /// Zero-based, half-open source-file byte range when proven.
    pub span: Option<SourceSpan>,
}

/// One contiguous part of expanded Markdown and the source bytes it came from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IncludeSourceRange {
    /// Byte range in the expanded page.
    pub expanded: SourceSpan,
    /// Original repository file and byte range.
    pub original: SourceLocation,
    /// One-based line number at the start of the original range.
    pub line: usize,
    /// Directives traversed from the main page to this source.
    pub include_chain: Vec<SourceLocation>,
}

/// An explicit group of corresponding APIs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Concept {
    /// Degree of correspondence among the members.
    pub kind: ConceptKind,
    /// Resolved member identities, sorted by package and item ID.
    pub members: BTreeSet<ItemReference>,
    /// Optional conceptual documentation.
    pub documentation: Option<SourcedDocument>,
}

/// An implementation or release dependency between packages.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PackageRelationship {
    /// Relationship origin.
    pub from: PackageReference,
    /// Relationship destination.
    pub to: PackageReference,
    /// Relationship semantics.
    pub kind: RelationshipKind,
    /// Constraint retained in the destination ecosystem's syntax.
    pub version_constraint: Option<String>,
    /// Declaration or extraction evidence in source order.
    pub provenance: Vec<Provenance>,
}

/// Explicitly distinguishes workspace IDs from external package coordinates.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)]
pub enum PackageReference {
    /// A package represented in this workspace.
    Workspace {
        /// Workspace package ID.
        package: String,
    },
    /// A package that need not have a supplied repository.
    External {
        /// External package ecosystem.
        ecosystem: String,
        /// Published package name in that ecosystem.
        name: String,
    },
}