Skip to main content

quillmark_core/document/
mod.rs

1//! # Document Module
2//!
3//! Parsing functionality for markdown documents with YAML frontmatter.
4//!
5//! ## Overview
6//!
7//! The `document` module provides the [`Document::from_markdown`] function for parsing
8//! markdown documents into a typed in-memory model.
9//!
10//! ## Key Types
11//!
12//! - [`Document`]: Typed in-memory Quillmark document — `main` card plus composable cards.
13//! - [`Card`]: A single card block, main or composable, with a sentinel,
14//!   typed frontmatter, and a body.
15//! - [`Sentinel`]: Discriminates the `QUILL:` frontmatter from composable card blocks.
16//! - [`Frontmatter`]: Ordered list of items (fields + comments) parsed from a YAML fence.
17//!
18//! ## Examples
19//!
20//! ### Basic Parsing
21//!
22//! ```
23//! use quillmark_core::Document;
24//!
25//! let markdown = r#"---
26//! QUILL: my_quill
27//! title: My Document
28//! author: John Doe
29//! ---
30//!
31//! # Introduction
32//!
33//! Document content here.
34//! "#;
35//!
36//! let doc = Document::from_markdown(markdown).unwrap();
37//! let title = doc.main()
38//!     .frontmatter()
39//!     .get("title")
40//!     .and_then(|v| v.as_str())
41//!     .unwrap_or("Untitled");
42//! assert_eq!(title, "My Document");
43//! assert_eq!(doc.cards().len(), 0);
44//! ```
45//!
46//! ### Accessing the plate wire format
47//!
48//! ```
49//! use quillmark_core::Document;
50//!
51//! let doc = Document::from_markdown(
52//!     "---\nQUILL: my_quill\ntitle: Hi\n---\n\nBody here.\n"
53//! ).unwrap();
54//! let json = doc.to_plate_json();
55//! assert_eq!(json["QUILL"], "my_quill");
56//! assert_eq!(json["title"], "Hi");
57//! assert_eq!(json["BODY"], "\nBody here.\n");
58//! assert!(json["CARDS"].is_array());
59//! ```
60//!
61//! ## Error Handling
62//!
63//! [`Document::from_markdown`] returns errors for:
64//! - Malformed YAML syntax
65//! - Unclosed frontmatter blocks
66//! - Multiple global frontmatter blocks
67//! - Both QUILL and CARD specified in the same block
68//! - Reserved field name usage
69//! - Name collisions
70//!
71//! See [PARSE.md](https://github.com/nibsbin/quillmark/blob/main/designs/PARSE.md) for
72//! comprehensive documentation of the Extended YAML Metadata Standard.
73
74use crate::error::ParseError;
75use crate::version::QuillReference;
76use crate::Diagnostic;
77
78pub mod assemble;
79pub mod edit;
80pub mod emit;
81pub mod fences;
82pub mod frontmatter;
83pub mod limits;
84pub mod prescan;
85pub mod sentinel;
86
87pub use edit::EditError;
88pub use frontmatter::{Frontmatter, FrontmatterItem};
89
90// Re-export the sentinel type (defined below in this module file).
91// `Sentinel` is exported at the crate root via `lib.rs`.
92
93#[cfg(test)]
94mod tests;
95
96/// Parse result carrying both the parsed document and any non-fatal warnings
97/// (e.g. near-miss sentinel lints emitted per spec §4.2).
98#[derive(Debug)]
99pub struct ParseOutput {
100    /// The successfully parsed document.
101    pub document: Document,
102    /// Non-fatal warnings collected during parsing.
103    pub warnings: Vec<Diagnostic>,
104}
105
106/// Discriminator for a [`Card`].
107///
108/// The document frontmatter carries `QUILL: <ref>` and is the document-level
109/// *main* card; every composable card carries a kind — written as the
110/// ```` ```card <kind> ```` info string (canonical) or a legacy `CARD: <kind>`
111/// sentinel. `Sentinel` captures that distinction in the typed model so every
112/// card is one uniform shape.
113#[derive(Debug, Clone, PartialEq)]
114pub enum Sentinel {
115    /// The document entry card, carrying the `QUILL` reference.
116    Main(QuillReference),
117    /// A composable card with the given kind tag.
118    Card(String),
119}
120
121impl Sentinel {
122    /// String form of this sentinel's value: the quill reference for `Main`,
123    /// the tag for `Card`.
124    pub fn as_str(&self) -> String {
125        match self {
126            Sentinel::Main(r) => r.to_string(),
127            Sentinel::Card(t) => t.clone(),
128        }
129    }
130
131    /// Returns `true` if this is a `Main` sentinel.
132    pub fn is_main(&self) -> bool {
133        matches!(self, Sentinel::Main(_))
134    }
135}
136
137/// A single metadata fence parsed from a Quillmark Markdown document.
138///
139/// A `Card` is the uniform shape for both the document entry (main) fence and
140/// composable card fences. `sentinel` distinguishes the two.
141///
142/// Every card has:
143/// - `sentinel` — the `QUILL` reference (for main) or `CARD` tag (for composable).
144/// - `frontmatter` — ordered items parsed from the YAML fence body (with the
145///   sentinel key already removed).
146/// - `body` — the Markdown text that follows the closing fence, up to the next
147///   fence (or EOF).
148///
149/// ## Card body absence
150///
151/// If a card block has no trailing Markdown content (e.g. the next block or
152/// EOF immediately follows the closing fence), `body` is the empty string `""`.
153/// It is never `None`; callers that need to distinguish "absent" from "empty"
154/// should check `card.body().is_empty()`.
155#[derive(Debug, Clone, PartialEq)]
156pub struct Card {
157    sentinel: Sentinel,
158    frontmatter: Frontmatter,
159    body: String,
160}
161
162impl Card {
163    /// Create a `Card` directly from a sentinel, a typed frontmatter, and a
164    /// body. Does **not** validate the sentinel tag or any field names —
165    /// callers are responsible for providing already-valid data. For
166    /// user-facing construction of composable cards use [`Card::new`]
167    /// (defined in `edit.rs`).
168    pub fn new_with_sentinel(sentinel: Sentinel, frontmatter: Frontmatter, body: String) -> Self {
169        Self {
170            sentinel,
171            frontmatter,
172            body,
173        }
174    }
175
176    /// The sentinel discriminating this card as main or composable.
177    pub fn sentinel(&self) -> &Sentinel {
178        &self.sentinel
179    }
180
181    /// The card tag — the card kind for composable cards, or the string
182    /// form of the quill reference for main cards.
183    pub fn tag(&self) -> String {
184        self.sentinel.as_str()
185    }
186
187    /// Typed frontmatter (map-keyed view and ordered item list).
188    pub fn frontmatter(&self) -> &Frontmatter {
189        &self.frontmatter
190    }
191
192    /// Mutable access to the frontmatter.
193    pub fn frontmatter_mut(&mut self) -> &mut Frontmatter {
194        &mut self.frontmatter
195    }
196
197    /// Markdown body that follows this card's closing fence.
198    ///
199    /// Empty string when no trailing content is present.
200    pub fn body(&self) -> &str {
201        &self.body
202    }
203
204    /// Returns `true` if this is the document entry (main) card.
205    pub fn is_main(&self) -> bool {
206        self.sentinel.is_main()
207    }
208
209    /// Replace this card's sentinel. Internal helper; public mutators
210    /// ([`Document::set_quill_ref`], the parser) call this.
211    pub(crate) fn replace_sentinel(&mut self, sentinel: Sentinel) {
212        self.sentinel = sentinel;
213    }
214
215    /// Overwrite the body string. Internal helper used by [`Card::replace_body`].
216    pub(crate) fn overwrite_body(&mut self, body: String) {
217        self.body = body;
218    }
219}
220
221/// A fully-parsed, typed in-memory Quillmark document.
222///
223/// `Document` is the canonical representation of a Quillmark Markdown file.
224/// Markdown is both the import and export format; the structured data here
225/// is primary.
226///
227/// ## Structure
228///
229/// - `main` — the entry `Card` (sentinel is `Sentinel::Main(reference)`).
230/// - `cards` — ordered composable cards (each with `Sentinel::Card(tag)`).
231///
232/// Backend plates consume the flat JSON wire shape produced by
233/// [`Document::to_plate_json`]. That method is the **only** place in core
234/// that reconstructs `{"QUILL": ..., "CARDS": [...], "BODY": "..."}`.
235#[derive(Debug, Clone)]
236pub struct Document {
237    main: Card,
238    cards: Vec<Card>,
239    warnings: Vec<Diagnostic>,
240}
241
242// Equality is defined over the structural content only — `warnings` are
243// parse-time observations that depend on what the source text happened to
244// contain (near-miss sentinels, unsupported tag drops, etc.) and so differ
245// between a source document and its round-tripped emission. Two documents
246// are equal when their `main` and `cards` match.
247impl PartialEq for Document {
248    fn eq(&self, other: &Self) -> bool {
249        self.main == other.main && self.cards == other.cards
250    }
251}
252
253impl Document {
254    /// Create a `Document` from a pre-built main `Card` and composable cards.
255    ///
256    /// The caller must guarantee that `main.sentinel` is `Sentinel::Main(_)`
257    /// and every card in `cards` has `sentinel` = `Sentinel::Card(_)`.
258    pub fn from_main_and_cards(main: Card, cards: Vec<Card>, warnings: Vec<Diagnostic>) -> Self {
259        debug_assert!(main.sentinel.is_main(), "main card must be Sentinel::Main");
260        debug_assert!(
261            cards.iter().all(|c| !c.sentinel.is_main()),
262            "composable cards must be Sentinel::Card"
263        );
264        Self {
265            main,
266            cards,
267            warnings,
268        }
269    }
270
271    /// Parse a Quillmark Markdown document, discarding any non-fatal warnings.
272    pub fn from_markdown(markdown: &str) -> Result<Self, ParseError> {
273        assemble::decompose(markdown)
274    }
275
276    /// Parse a Quillmark Markdown document, returning warnings alongside the document.
277    pub fn from_markdown_with_warnings(markdown: &str) -> Result<ParseOutput, ParseError> {
278        assemble::decompose_with_warnings(markdown)
279            .map(|(document, warnings)| ParseOutput { document, warnings })
280    }
281
282    // ── Accessors ──────────────────────────────────────────────────────────────
283
284    /// The document's main (entry) card.
285    pub fn main(&self) -> &Card {
286        &self.main
287    }
288
289    /// Mutable access to the main card.
290    pub fn main_mut(&mut self) -> &mut Card {
291        &mut self.main
292    }
293
294    /// The quill reference (`name@version-selector`) carried by the main card's
295    /// sentinel. Convenience reader over `doc.main().sentinel()`.
296    pub fn quill_reference(&self) -> &QuillReference {
297        match &self.main.sentinel {
298            Sentinel::Main(r) => r,
299            Sentinel::Card(_) => {
300                unreachable!("main card must carry Sentinel::Main by construction")
301            }
302        }
303    }
304
305    /// Ordered list of composable card blocks.
306    pub fn cards(&self) -> &[Card] {
307        &self.cards
308    }
309
310    /// Mutable access to the composable cards slice.
311    pub fn cards_mut(&mut self) -> &mut [Card] {
312        &mut self.cards
313    }
314
315    /// Internal mutable access to the backing `Vec<Card>`. Used by edit
316    /// operations ([`Document::push_card`], etc.) that need to insert or
317    /// remove elements.
318    pub(crate) fn cards_vec_mut(&mut self) -> &mut Vec<Card> {
319        &mut self.cards
320    }
321
322    /// Non-fatal warnings collected during parsing.
323    pub fn warnings(&self) -> &[Diagnostic] {
324        &self.warnings
325    }
326
327    // ── Wire format ────────────────────────────────────────────────────────────
328
329    /// Serialize this document to the JSON shape expected by backend plates.
330    ///
331    /// The output has the following top-level keys, which match what
332    /// `lib.typ.template` reads at Typst runtime:
333    ///
334    /// ```json
335    /// {
336    ///   "QUILL": "<ref>",
337    ///   "<field>": <value>,
338    ///   ...
339    ///   "BODY": "<global-body>",
340    ///   "CARDS": [
341    ///     { "CARD": "<tag>", "<field>": <value>, ..., "BODY": "<card-body>" },
342    ///     ...
343    ///   ]
344    /// }
345    /// ```
346    ///
347    /// This is the **only** place in `quillmark-core` that knows about the plate
348    /// wire format. All internal consumers (Quill, backends) call this instead
349    /// of constructing the shape by hand.
350    pub fn to_plate_json(&self) -> serde_json::Value {
351        let mut map = serde_json::Map::new();
352
353        // QUILL first — plate authors expect this at the top.
354        map.insert(
355            "QUILL".to_string(),
356            serde_json::Value::String(self.quill_reference().to_string()),
357        );
358
359        // Frontmatter fields in insertion order.
360        for (key, value) in self.main.frontmatter.iter() {
361            map.insert(key.clone(), value.as_json().clone());
362        }
363
364        // Global body.
365        map.insert(
366            "BODY".to_string(),
367            serde_json::Value::String(self.main.body.clone()),
368        );
369
370        // Cards array.
371        let cards_array: Vec<serde_json::Value> = self
372            .cards
373            .iter()
374            .map(|card| {
375                let mut card_map = serde_json::Map::new();
376                card_map.insert("CARD".to_string(), serde_json::Value::String(card.tag()));
377                for (key, value) in card.frontmatter.iter() {
378                    card_map.insert(key.clone(), value.as_json().clone());
379                }
380                card_map.insert(
381                    "BODY".to_string(),
382                    serde_json::Value::String(card.body.clone()),
383                );
384                serde_json::Value::Object(card_map)
385            })
386            .collect();
387
388        map.insert("CARDS".to_string(), serde_json::Value::Array(cards_array));
389
390        serde_json::Value::Object(map)
391    }
392}