nb_api/parser/mod.rs
1//! Structural parser for `nb` notes, todos, and bookmarks.
2//!
3//! Defines [`NoteDocument`] — the canonical byte-range partition
4//! for any source file produced or accepted by `nb 7.24.0` — plus
5//! the [`DocumentKind`], [`TodoState`], [`ParseContext`], and
6//! accessor types required by the `add-note-document-model` (P1)
7//! specification.
8//!
9//! Permissive acceptance is the contract: `parse` succeeds for
10//! every input that can be losslessly partitioned into a
11//! [`NoteDocument`], including the frozen W1 and E1-E11
12//! noncanonical forms. The only refusal cases at the parse layer
13//! are [`ParseErrorKind::MissingTitle`] for Todo/Bookmark files
14//! with no non-blank line. Notes are permissive on empty source.
15//!
16//! Mandatory-title/URL/state enforcement belongs to a separate
17//! canonical validator (P5+), not to the parser. Operation
18//! boundaries (`do`/`undo` for Todo) enforce checkbox state at
19//! the operation level, not the parse level.
20//!
21//! Format dispatch (R3 revision) precedes byte parsing on
22//! `ParseContext::FromPath`. Files whose final filename matches
23//! a recognized-but-unsupported dotted suffix (e.g., `.org`,
24//! `.latex`, `.tex`, `.adoc`, `.asciidoc`) are rejected with
25//! `NbError::UnsupportedDocumentFormat` *before* any byte parsing
26//! runs. The list of supported extensions lives in the public
27//! constant [`SUPPORTED_DOCUMENT_EXTENSIONS`].
28//!
29//! [`ParseErrorKind`]: crate::error::ParseErrorKind
30//! [`NbError::ParseError`]: crate::error::NbError::ParseError
31
32mod assemble;
33mod classify;
34mod dispatch;
35mod document;
36mod helpers;
37mod types;
38
39pub use dispatch::SUPPORTED_DOCUMENT_EXTENSIONS;
40pub use document::{
41 BodyFragments, DocumentKind, NoteDocument, ParseContext, TagsIter,
42 TagsStrIter, TodoState,
43};
44
45use crate::error::NbError;
46use crate::tokenizer::tokenize;
47
48use assemble::{
49 assemble_bookmark, assemble_note, assemble_todo, translate_parse_failure,
50};
51use classify::{classify_bookmark, classify_note, classify_todo};
52use dispatch::{FormatDispatch, format_dispatch};
53use document::Partition;
54
55/// Parse bytes into a [`NoteDocument`].
56///
57/// Permissive acceptance: returns `Ok` for every input that can
58/// be losslessly partitioned, including the frozen W1 and
59/// E1-E11 noncanonical forms. The only refusal cases at the
60/// parse layer are [`ParseErrorKind::MissingTitle`] for
61/// Todo/Bookmark files with no non-blank line. Notes are
62/// permissive on empty source.
63pub fn parse(
64 bytes: &[u8],
65 context: ParseContext,
66) -> Result<NoteDocument, NbError> {
67 let kind = match context {
68 ParseContext::FromPath(path) => match format_dispatch(&path) {
69 FormatDispatch::SupportedKind(kind) => kind,
70 FormatDispatch::Rejected(extension) => {
71 // Format dispatch precedes byte parsing. The
72 // owned `Vec<String>` for the supported list
73 // ensures the resulting NbError round-trips
74 // through serde cleanly.
75 return Err(NbError::UnsupportedDocumentFormat {
76 extension,
77 supported: SUPPORTED_DOCUMENT_EXTENSIONS
78 .iter()
79 .map(|s| s.to_string())
80 .collect(),
81 });
82 },
83 FormatDispatch::MarkdownNote => DocumentKind::Note,
84 },
85 // `Explicit(DocumentKind)` bypasses path dispatch and
86 // is treated as Markdown without going through
87 // format-dispatch. It can NEVER produce
88 // `UnsupportedDocumentFormat` per the spec, but remains
89 // subject to the selected Markdown kind's ordinary
90 // parse failures (e.g., `Explicit(Todo)` with empty
91 // bytes returns `MissingTitle`).
92 ParseContext::Explicit(kind) => kind,
93 };
94 let mut source = Vec::with_capacity(bytes.len());
95 source.extend_from_slice(bytes);
96 let (preamble, lines) = tokenize(&source);
97 let partition = match kind {
98 DocumentKind::Note => {
99 let tokens = classify_note(&lines);
100 match assemble_note(&source, &preamble, &lines, &tokens) {
101 Ok(p) => Partition::Note(p),
102 Err(failure) => return Err(translate_parse_failure(failure)),
103 }
104 },
105 DocumentKind::Todo => {
106 let tokens = classify_todo(&lines);
107 match assemble_todo(&source, &preamble, &lines, &tokens) {
108 Ok(p) => Partition::Todo(p),
109 Err(failure) => return Err(translate_parse_failure(failure)),
110 }
111 },
112 DocumentKind::Bookmark => {
113 let tokens = classify_bookmark(&lines);
114 match assemble_bookmark(&source, &preamble, &lines, &tokens) {
115 Ok(p) => Partition::Bookmark(p),
116 Err(failure) => return Err(translate_parse_failure(failure)),
117 }
118 },
119 };
120 let doc = NoteDocument { source, partition };
121 // Sanity-check the partition in debug builds. Production
122 // callers do not pay this cost; the panic on invariant
123 // violation surfaces parser regressions during testing.
124 debug_assert!(doc.verify_partition().is_ok());
125 Ok(doc)
126}