Skip to main content

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, TagsStrIter, TodoState,
42};
43
44use crate::error::NbError;
45use crate::tokenizer::tokenize;
46
47use assemble::{assemble_bookmark, assemble_note, assemble_todo, translate_parse_failure};
48use classify::{classify_bookmark, classify_note, classify_todo};
49use dispatch::{FormatDispatch, format_dispatch};
50use document::Partition;
51
52/// Parse bytes into a [`NoteDocument`].
53///
54/// Permissive acceptance: returns `Ok` for every input that can
55/// be losslessly partitioned, including the frozen W1 and
56/// E1-E11 noncanonical forms. The only refusal cases at the
57/// parse layer are [`ParseErrorKind::MissingTitle`] for
58/// Todo/Bookmark files with no non-blank line. Notes are
59/// permissive on empty source.
60pub fn parse(bytes: &[u8], context: ParseContext) -> Result<NoteDocument, NbError> {
61    let kind = match context {
62        ParseContext::FromPath(path) => match format_dispatch(&path) {
63            FormatDispatch::SupportedKind(kind) => kind,
64            FormatDispatch::Rejected(extension) => {
65                // Format dispatch precedes byte parsing. The
66                // owned `Vec<String>` for the supported list
67                // ensures the resulting NbError round-trips
68                // through serde cleanly.
69                return Err(NbError::UnsupportedDocumentFormat {
70                    extension,
71                    supported: SUPPORTED_DOCUMENT_EXTENSIONS
72                        .iter()
73                        .map(|s| s.to_string())
74                        .collect(),
75                });
76            }
77            FormatDispatch::MarkdownNote => DocumentKind::Note,
78        },
79        // `Explicit(DocumentKind)` bypasses path dispatch and
80        // is treated as Markdown without going through
81        // format-dispatch. It can NEVER produce
82        // `UnsupportedDocumentFormat` per the spec, but remains
83        // subject to the selected Markdown kind's ordinary
84        // parse failures (e.g., `Explicit(Todo)` with empty
85        // bytes returns `MissingTitle`).
86        ParseContext::Explicit(kind) => kind,
87    };
88    let mut source = Vec::with_capacity(bytes.len());
89    source.extend_from_slice(bytes);
90    let (preamble, lines) = tokenize(&source);
91    let partition = match kind {
92        DocumentKind::Note => {
93            let tokens = classify_note(&lines);
94            match assemble_note(&source, &preamble, &lines, &tokens) {
95                Ok(p) => Partition::Note(p),
96                Err(failure) => return Err(translate_parse_failure(failure)),
97            }
98        }
99        DocumentKind::Todo => {
100            let tokens = classify_todo(&lines);
101            match assemble_todo(&source, &preamble, &lines, &tokens) {
102                Ok(p) => Partition::Todo(p),
103                Err(failure) => return Err(translate_parse_failure(failure)),
104            }
105        }
106        DocumentKind::Bookmark => {
107            let tokens = classify_bookmark(&lines);
108            match assemble_bookmark(&source, &preamble, &lines, &tokens) {
109                Ok(p) => Partition::Bookmark(p),
110                Err(failure) => return Err(translate_parse_failure(failure)),
111            }
112        }
113    };
114    let doc = NoteDocument { source, partition };
115    // Sanity-check the partition in debug builds. Production
116    // callers do not pay this cost; the panic on invariant
117    // violation surfaces parser regressions during testing.
118    debug_assert!(doc.verify_partition().is_ok());
119    Ok(doc)
120}