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
//! QMD policy validation and preparation without execution or local paths.

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

use panache_parser::syntax::{
    AstNode, ChunkInfoItem, CodeBlock, SyntaxKind, SyntaxNode, YamlBlockMapKey, YamlFlowMapKey,
};

use crate::configuration::{ContentConfiguration, ExecutionConfigurationError, ExecutionMode};
use crate::diagnostics::{Diagnostic, DiagnosticCode, Severity};
use crate::execution::{EffectiveOption, ExecutionDefaults, OptionOrigin, PreparedCell};
use crate::ir::{Attributes, Block, CodeCell, Inline, SourceSpan};
use crate::validation::validate_document_execution;

use super::{AuthoredFormat, DocumentParse, ParseMode, parse_document_with_resources, span};

mod options;
mod scalars;

/// A validated authored document and, when valid QMD, its preparation data.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreparedDocument {
    /// Original document with source-ordered parser and policy diagnostics.
    pub parsed: DocumentParse,
    /// Absent for GFM or any document with an error diagnostic.
    pub preparation: Option<QmdPreparation>,
}

/// Pure preparation under `qmd-mvp-v1`, before kernel language selection.
///
/// Valid disabled pages retain their cells and options. This record is not an
/// execution request or proof of authorization; callers still gate dispatch on
/// the command being run. In particular, checks must never dispatch execution.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct QmdPreparation {
    /// Effective inheritable options with winning declaration origins.
    pub defaults: ExecutionDefaults,
    /// Top-level `execute: false`, which no cell can override.
    pub page_veto: bool,
    /// Every authored cell in source order, including disabled cells.
    pub cells: Vec<PreparedCell>,
    /// Complete authored identifiers and cell labels, independent of generated output.
    pub authored_anchors: BTreeSet<String>,
    /// Collection authority, no veto, and at least one `eval: true` cell.
    ///
    /// This is preliminary eligibility, not a request to discover a kernel.
    /// The executor must still match the explicitly selected kernel's language.
    pub execution_eligible: bool,
}

/// Parse, validate, and prepare a collection's document without performing I/O.
///
/// The original document is retained unchanged. QMD validation checks every
/// declaration, including overridden options and disabled cells. Errors remain
/// in `parsed.diagnostics` and prevent preparation; warnings do not. Effective
/// options use hashpipe, inline, document, then policy-default precedence.
/// No kernel is discovered, no environment input is read, and no artifact is
/// created. Rendering and execution consume the prepared options separately.
///
/// # Errors
///
/// Returns an error when the collection's execution configuration is invalid.
pub fn prepare_collection_document(
    source: &str,
    collection: &ContentConfiguration,
) -> Result<PreparedDocument, ExecutionConfigurationError> {
    prepare_collection_document_with_resources(source, collection, &|target, _| target.to_owned())
}

// Resolve each destination while its syntax range is available. Reference
// definitions supply their own range rather than the range of a later use.
pub(crate) fn prepare_collection_document_with_resources(
    source: &str,
    collection: &ContentConfiguration,
    resource_target: &dyn Fn(&str, SourceSpan) -> String,
) -> Result<PreparedDocument, ExecutionConfigurationError> {
    collection.validate_execution()?;
    let mut parsed = parse_document_with_resources(
        source,
        collection.format,
        ParseMode::Collection,
        resource_target,
    );
    if collection.format == AuthoredFormat::Documenter
        && collection.execution.mode == ExecutionMode::Execute
        && let Err(diagnostics) = super::documenter::examples(source)
    {
        parsed.diagnostics.extend(diagnostics);
    }
    if collection.format != AuthoredFormat::Qmd {
        return Ok(PreparedDocument {
            parsed,
            preparation: None,
        });
    }
    let authority = validate_document_execution(&parsed.document, collection)?;
    // Selectors have one authoritative diagnostic, even if their values also
    // contain YAML syntax outside the supported subset.
    parsed.diagnostics.retain(|diagnostic| {
        diagnostic.code != DiagnosticCode::InvalidQmdMetadata
            || !authority.iter().any(|authority| {
                std::iter::once(authority.span)
                    .flatten()
                    .chain(authority.related_spans.iter().copied())
                    .any(|range| diagnostic.span.is_some_and(|s| contains(range, s)))
            })
    });
    parsed.diagnostics.extend(authority);
    // Rebuild ambiguity diagnostics for every tier, including overridden ones.
    parsed
        .diagnostics
        .retain(|d| d.code != DiagnosticCode::AmbiguousCellOption);
    let mut context = PreparationContext {
        source,
        diagnostics: &mut parsed.diagnostics,
        cells: Vec::new(),
        anchors: BTreeMap::new(),
    };
    let (defaults, page_veto) = options::document_defaults(
        source,
        parsed.document.frontmatter.as_ref(),
        context.diagnostics,
    );
    context.blocks(&parsed.document.blocks, &defaults);
    context.check_anchors();
    let authored_anchors = context.anchors.into_keys().collect();
    let cells = context.cells;
    let execution_eligible = collection.execution.mode == ExecutionMode::Execute
        && !page_veto
        && cells.iter().any(|cell| cell.options.execution.eval.value);
    parsed.diagnostics.sort();
    let preparation = (!parsed
        .diagnostics
        .iter()
        .any(|d| d.severity == Severity::Error))
    .then_some(QmdPreparation {
        defaults,
        page_veto,
        cells,
        authored_anchors,
        execution_eligible,
    });
    Ok(PreparedDocument {
        parsed,
        preparation,
    })
}

struct PreparationContext<'a> {
    source: &'a str,
    diagnostics: &'a mut Vec<Diagnostic>,
    cells: Vec<PreparedCell>,
    anchors: BTreeMap<String, Vec<Anchor>>,
}

struct Anchor {
    span: SourceSpan,
    cell: bool,
}

impl PreparationContext<'_> {
    fn blocks(&mut self, blocks: &[Block], defaults: &ExecutionDefaults) {
        for block in blocks {
            match block {
                Block::CodeCell(cell) => self.cell(cell, defaults),
                Block::BlockQuote { blocks, .. } | Block::Container { blocks, .. } => {
                    self.blocks(blocks, defaults)
                }
                Block::Callout {
                    attributes, blocks, ..
                }
                | Block::Component {
                    attributes, blocks, ..
                }
                | Block::Tabset {
                    attributes, blocks, ..
                } => {
                    self.attributes(attributes);
                    self.blocks(blocks, defaults);
                }
                Block::List { items, .. } => {
                    for item in items {
                        self.blocks(&item.blocks, defaults);
                    }
                }
                Block::Table { caption, rows, .. } => {
                    self.inlines(caption);
                    for row in rows {
                        for cell in &row.cells {
                            self.blocks(&cell.blocks, defaults);
                        }
                    }
                }
                Block::Heading {
                    attributes,
                    inlines,
                    ..
                } => {
                    self.attributes(attributes);
                    self.inlines(inlines);
                }
                Block::Paragraph { inlines, .. } => self.inlines(inlines),
                Block::ApiDocumentation { .. }
                | Block::ThematicBreak { .. }
                | Block::CodeBlock { .. }
                | Block::Unsupported { .. }
                | Block::DisplayMath { .. } => {}
            }
        }
    }

    fn inlines(&mut self, inlines: &[Inline]) {
        for inline in inlines {
            match inline {
                Inline::Link {
                    attributes,
                    inlines,
                    ..
                } => {
                    self.attributes(attributes);
                    self.inlines(inlines);
                }
                Inline::Image {
                    attributes, alt, ..
                } => {
                    self.attributes(attributes);
                    self.inlines(alt);
                }
                Inline::Emphasis { inlines, .. }
                | Inline::Strong { inlines, .. }
                | Inline::Styled { inlines, .. }
                | Inline::Citation { inlines, .. }
                | Inline::Strikeout { inlines, .. } => self.inlines(inlines),
                _ => {}
            }
        }
    }

    fn attributes(&mut self, attributes: &Attributes) {
        if let Some(id) = &attributes.identifier {
            self.anchors
                .entry(id.value.clone())
                .or_default()
                .push(Anchor {
                    span: id.span,
                    cell: false,
                });
        }
    }

    fn cell(&mut self, cell: &CodeCell, defaults: &ExecutionDefaults) {
        let mut options = options::cell_options(self.source, cell, defaults, self.diagnostics);
        for class in &cell.classes {
            self.diagnostics.push(error(
                DiagnosticCode::UnsupportedCellOption,
                "Cell fence classes are unsupported.",
                class.span,
            ));
        }
        if let Some(identifier) = &cell.identifier {
            if !options::valid_label(&identifier.value) {
                self.diagnostics.push(error(
                    DiagnosticCode::InvalidCellOption,
                    "Cell identifiers must match [A-Za-z][A-Za-z0-9_.:-]*.",
                    identifier.span,
                ));
            }
            if let Some(label) = &options.label.value {
                if label != &identifier.value {
                    let mut diagnostic = error(
                        DiagnosticCode::InvalidCellOption,
                        "The cell label and fence identifier must agree.",
                        origin_span(options.label.origin).unwrap(),
                    );
                    diagnostic.related_spans.push(identifier.span);
                    self.diagnostics.push(diagnostic);
                }
            } else {
                options.label = EffectiveOption {
                    value: Some(identifier.value.clone()),
                    origin: OptionOrigin::FenceIdentifier {
                        span: identifier.span,
                    },
                };
            }
        }
        if let Some(label) = &options.label.value {
            self.anchors.entry(label.clone()).or_default().push(Anchor {
                span: origin_span(options.label.origin).unwrap(),
                cell: true,
            });
        }
        self.cells.push(PreparedCell {
            ordinal: self.cells.len(),
            cell: cell.clone(),
            options,
        });
    }

    fn check_anchors(&mut self) {
        for anchors in self.anchors.values_mut() {
            if anchors.len() < 2 || !anchors.iter().any(|a| a.cell) {
                continue;
            }
            anchors.sort_by_key(|a| (a.span.start, a.span.end));
            let mut diagnostic = error(
                DiagnosticCode::InvalidCellOption,
                "A cell label conflicts with another authored anchor on this page.",
                anchors[0].span,
            );
            diagnostic
                .related_spans
                .extend(anchors[1..].iter().map(|a| a.span));
            self.diagnostics.push(diagnostic);
        }
    }
}

fn origin_span(origin: OptionOrigin) -> Option<SourceSpan> {
    match origin {
        OptionOrigin::Default => None,
        OptionOrigin::Document { span }
        | OptionOrigin::Inline { span }
        | OptionOrigin::Hashpipe { span }
        | OptionOrigin::FenceIdentifier { span } => Some(span),
    }
}

fn error(code: DiagnosticCode, message: impl Into<String>, span: SourceSpan) -> Diagnostic {
    Diagnostic {
        code,
        severity: Severity::Error,
        message: message.into(),
        span: Some(span),
        related_spans: Vec::new(),
        related_entity: None,
        source: None,
    }
}

fn contains(outer: SourceSpan, inner: SourceSpan) -> bool {
    outer.start <= inner.start && inner.end <= outer.end
}

/// Inspect syntax that Panache's semantic YAML projection deliberately omits.
pub(super) fn syntax_diagnostics(root: &SyntaxNode) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    for code in root.descendants().filter_map(CodeBlock::cast) {
        if code.executable_cell().is_some()
            && let Some(info) = code.info()
        {
            let identifiers = info
                .chunk_items()
                .filter_map(|item| match item {
                    ChunkInfoItem::Id(id) => Some(span(id.range())),
                    _ => None,
                })
                .collect::<Vec<_>>();
            if identifiers.len() > 1 {
                let mut diagnostic = error(
                    DiagnosticCode::InvalidCellOption,
                    "A cell fence may declare only one identifier.",
                    identifiers[0],
                );
                diagnostic
                    .related_spans
                    .extend_from_slice(&identifiers[1..]);
                diagnostics.push(diagnostic);
            }
        }
    }
    for element in root.descendants_with_tokens() {
        if matches!(
            element.kind(),
            SyntaxKind::YAML_TAG | SyntaxKind::YAML_ANCHOR | SyntaxKind::YAML_ALIAS
        ) {
            let parent = element.parent().expect("YAML token parent");
            let code = yaml_diagnostic_code(&parent);
            diagnostics.push(error(
                code,
                "YAML tags, anchors, and aliases are unsupported.",
                span(element.text_range()),
            ));
        }
        if let Some(node) = element.as_node() {
            let invalid_key = match node.kind() {
                SyntaxKind::YAML_BLOCK_MAP_KEY => YamlBlockMapKey::cast(node.clone())
                    .unwrap()
                    .scalar()
                    .is_none(),
                SyntaxKind::YAML_FLOW_MAP_KEY => YamlFlowMapKey::cast(node.clone())
                    .unwrap()
                    .scalar()
                    .is_none(),
                _ => false,
            };
            if invalid_key {
                diagnostics.push(error(
                    yaml_diagnostic_code(node),
                    "QMD option and metadata keys must be scalars.",
                    span(node.text_range()),
                ));
            }
            if node.kind() == SyntaxKind::CHUNK_LABEL {
                diagnostics.push(error(
                    DiagnosticCode::UnsupportedCellOption,
                    "Bare cell labels are unsupported; use a fence identifier or the label option.",
                    span(node.text_range()),
                ));
            }
        }
    }
    diagnostics
}

fn yaml_diagnostic_code(node: &SyntaxNode) -> DiagnosticCode {
    if node
        .ancestors()
        .any(|n| n.kind() == SyntaxKind::HASHPIPE_YAML_CONTENT)
    {
        DiagnosticCode::InvalidCellOption
    } else {
        DiagnosticCode::InvalidQmdMetadata
    }
}