Skip to main content

nb_api/parser/
document.rs

1//! Public document model: kinds, partitions, accessors, iterators.
2
3use std::ops::Range;
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8use super::helpers::{parse_todo_state_from_title, tag_token_spans_in};
9
10/// Distinguishes the three document kinds recognized by the parser.
11///
12/// [`DocumentKind::Note`] is the default for `.md` files and any
13/// path whose extension is not `.todo.md` or `.bookmark.md`.
14///
15/// [`DocumentKind::Todo`] is for `.todo.md` files. The Todo
16/// [`TodoState`] is derived from the title line via
17/// [`NoteDocument::todo_state`].
18///
19/// [`DocumentKind::Bookmark`] is for `.bookmark.md` files.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
22#[serde(rename_all = "lowercase")]
23pub enum DocumentKind {
24    Note,
25    Todo,
26    Bookmark,
27}
28
29/// The parsed checkbox state of a Todo title.
30///
31/// Surfaced via [`NoteDocument::todo_state`] as
32/// `Option<TodoState>`; `None` when the title has no checkbox
33/// marker (permissive acceptance).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
36#[serde(rename_all = "lowercase")]
37pub enum TodoState {
38    Open,
39    Done,
40}
41
42/// How the parser determines the [`DocumentKind`] for an input.
43///
44/// [`ParseContext::FromPath`] infers from the file extension:
45/// `.todo.md` → Todo, `.bookmark.md` → Bookmark, `.md` (or other)
46/// → Note. The bare `.todo` extension (without `.md`) maps to
47/// Note deterministically — the `.todo` extension is a `show
48/// --type` classification only, not mutation-authoritative.
49///
50/// [`ParseContext::Explicit`] sets the kind directly, overriding
51/// any inference.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
54#[serde(rename_all = "snake_case", tag = "kind")]
55pub enum ParseContext {
56    FromPath(PathBuf),
57    Explicit(DocumentKind),
58}
59
60/// A parsed `nb` note, todo, or bookmark.
61///
62/// `NoteDocument` owns the complete original source as
63/// `Vec<u8>`. The source is byte-identical to the input passed
64/// to [`parse`]. The kind-specific ownership partition is
65/// exposed via accessor methods (e.g., [`NoteDocument::title`],
66/// [`NoteDocument::body`], [`NoteDocument::url`]) and the
67/// [`NoteDocument::tag_token_spans`] view.
68///
69/// See the P1 specification for the full contract.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct NoteDocument {
72    pub(crate) source: Vec<u8>,
73    pub(crate) partition: Partition,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub(crate) enum Partition {
78    Note(NotePartition),
79    Todo(TodoPartition),
80    Bookmark(BookmarkPartition),
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub(crate) struct NotePartition {
85    pub(crate) prefix_range: Range<usize>,
86    pub(crate) title_range: Option<Range<usize>>,
87    pub(crate) tags_prefix_range: Option<Range<usize>>,
88    pub(crate) separator_ranges: Vec<Range<usize>>,
89    pub(crate) body_ranges: Vec<Range<usize>>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub(crate) struct TodoPartition {
94    pub(crate) prefix_range: Range<usize>,
95    pub(crate) title_range: Option<Range<usize>>,
96    pub(crate) separator_ranges: Vec<Range<usize>>,
97    pub(crate) tag_section_range: Option<Range<usize>>,
98    pub(crate) body_ranges: Vec<Range<usize>>,
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub(crate) struct BookmarkPartition {
103    pub(crate) prefix_range: Range<usize>,
104    pub(crate) title_range: Option<Range<usize>>,
105    pub(crate) url_range: Option<Range<usize>>,
106    pub(crate) separator_ranges: Vec<Range<usize>>,
107    pub(crate) tag_section_range: Option<Range<usize>>,
108    pub(crate) body_ranges: Vec<Range<usize>>,
109}
110
111impl NoteDocument {
112    /// The original source bytes, byte-identical to the input
113    /// passed to [`parse`].
114    pub fn source(&self) -> &[u8] {
115        &self.source
116    }
117
118    /// Returns a slice into the retained `source` bytes,
119    /// byte-identical to the original input. Equivalent to
120    /// [`NoteDocument::source`].
121    pub fn emit(&self) -> &[u8] {
122        &self.source
123    }
124
125    /// Verify the ownership partition satisfies the P1
126    /// invariants: union covers `[0, source.len())` exactly,
127    /// ranges are pairwise disjoint, each range is half-open
128    /// and within bounds. Returns `Ok(())` on success or an
129    /// `Err(&'static str)` describing the first violation.
130    ///
131    /// Used by integration tests and by `parse` itself when
132    /// the `debug_assertions` cfg flag is enabled. Production
133    /// callers do not need to invoke this; it exists to surface
134    /// parser regressions during testing.
135    pub fn verify_partition(&self) -> Result<(), &'static str> {
136        let source_len = self.source.len();
137        let mut covered: Vec<(usize, usize)> = Vec::new();
138        let mut check = |r: &std::ops::Range<usize>, name: &str| -> Result<(), &'static str> {
139            if r.start > r.end {
140                return Err("range not half-open (start > end)");
141            }
142            if r.end > source_len {
143                return Err("range extends past source.len()");
144            }
145            covered.push((r.start, r.end));
146            let _ = name;
147            Ok(())
148        };
149        match &self.partition {
150            Partition::Note(note) => {
151                check(&note.prefix_range, "prefix")?;
152                if let Some(r) = &note.title_range {
153                    check(r, "title")?;
154                }
155                if let Some(r) = &note.tags_prefix_range {
156                    check(r, "tags_prefix")?;
157                }
158                for r in &note.separator_ranges {
159                    check(r, "separator")?;
160                }
161                for r in &note.body_ranges {
162                    check(r, "body")?;
163                }
164            }
165            Partition::Todo(todo) => {
166                check(&todo.prefix_range, "prefix")?;
167                if let Some(r) = &todo.title_range {
168                    check(r, "title")?;
169                }
170                for r in &todo.separator_ranges {
171                    check(r, "separator")?;
172                }
173                if let Some(r) = &todo.tag_section_range {
174                    check(r, "tag_section")?;
175                }
176                for r in &todo.body_ranges {
177                    check(r, "body")?;
178                }
179            }
180            Partition::Bookmark(bookmark) => {
181                check(&bookmark.prefix_range, "prefix")?;
182                if let Some(r) = &bookmark.title_range {
183                    check(r, "title")?;
184                }
185                if let Some(r) = &bookmark.url_range {
186                    check(r, "url")?;
187                }
188                for r in &bookmark.separator_ranges {
189                    check(r, "separator")?;
190                }
191                if let Some(r) = &bookmark.tag_section_range {
192                    check(r, "tag_section")?;
193                }
194                for r in &bookmark.body_ranges {
195                    check(r, "body")?;
196                }
197            }
198        }
199        covered.sort_by_key(|&(s, _)| s);
200        // Adjacency check: ranges must touch end-to-end
201        // (previous.end == next.start) with no overlap AND no
202        // gap. A gap means a byte was not assigned to any
203        // partition region.
204        for window in covered.windows(2) {
205            if window[0].1 > window[1].0 {
206                return Err("ranges overlap");
207            }
208            if window[0].1 < window[1].0 {
209                return Err("partition leaves a gap (internal unassigned bytes)");
210            }
211        }
212        if covered.first().map(|r| r.0) != Some(0) {
213            return Err("partition does not start at byte 0");
214        }
215        if covered.last().map(|r| r.1) != Some(source_len) {
216            return Err("partition does not cover to source.len()");
217        }
218        Ok(())
219    }
220
221    /// The [`DocumentKind`] of this document.
222    pub fn kind(&self) -> DocumentKind {
223        match &self.partition {
224            Partition::Note(_) => DocumentKind::Note,
225            Partition::Todo(_) => DocumentKind::Todo,
226            Partition::Bookmark(_) => DocumentKind::Bookmark,
227        }
228    }
229
230    /// For Todo documents, the parsed checkbox state. `None` for
231    /// non-Todo documents and for Todo documents whose title has
232    /// no `[ ]`/`[x]` prefix (permissive acceptance).
233    pub fn todo_state(&self) -> Option<TodoState> {
234        match &self.partition {
235            Partition::Todo(todo) => {
236                let title = todo.title_range.as_ref()?;
237                let line = self.source.get(title.start..title.end)?;
238                parse_todo_state_from_title(line)
239            }
240            _ => None,
241        }
242    }
243
244    /// The raw title line bytes (including trailing newline);
245    /// `None` if no valid ATX H1 title.
246    pub fn title(&self) -> Option<&[u8]> {
247        let range = self.title_range()?;
248        Some(&self.source[range])
249    }
250
251    /// `Option<Result<&str, std::str::Utf8Error>>` view of the
252    /// title. `None` for no title; `Some(Ok(_))` for valid UTF-8;
253    /// `Some(Err(_))` for invalid UTF-8.
254    pub fn title_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
255        self.title().map(std::str::from_utf8)
256    }
257
258    /// For Note documents, the raw tags prefix line bytes
259    /// (including trailing newline); `None` otherwise.
260    pub fn tags_prefix(&self) -> Option<&[u8]> {
261        let NotePartition {
262            tags_prefix_range, ..
263        } = match &self.partition {
264            Partition::Note(note) => note,
265            _ => return None,
266        };
267        Some(&self.source[tags_prefix_range.clone()?])
268    }
269
270    /// For Todo/Bookmark documents, the raw tags-section bytes
271    /// (the entire H2 Tags section including its trailing
272    /// newline); `None` otherwise.
273    pub fn tag_section(&self) -> Option<&[u8]> {
274        let range = self.tag_section_range()?;
275        Some(&self.source[range])
276    }
277
278    /// Iterator over tag token byte spans (`&[u8]`). Tokens come
279    /// from `tags_prefix_range` for Note documents and from
280    /// `tag_section_range` for Todo/Bookmark documents. Spans
281    /// reference bytes owned by the source.
282    pub fn tags(&self) -> TagsIter<'_> {
283        TagsIter {
284            doc: self,
285            token_spans: self.tag_token_spans().into_iter(),
286        }
287    }
288
289    /// Iterator yielding `Result<&str, std::str::Utf8Error>` per
290    /// tag token.
291    pub fn tags_str(&self) -> TagsStrIter<'_> {
292        TagsStrIter {
293            doc: self,
294            token_spans: self.tag_token_spans().into_iter(),
295        }
296    }
297
298    /// All tag token spans across the document. For Note,
299    /// tokens come from `tags_prefix_range`; for Todo/Bookmark,
300    /// from `tag_section_range`. Spans reference bytes owned by
301    /// the source and SHALL NOT themselves own bytes.
302    pub fn tag_token_spans(&self) -> Vec<Range<usize>> {
303        match &self.partition {
304            Partition::Note(note) => {
305                tag_token_spans_in(&self.source, note.tags_prefix_range.as_ref())
306            }
307            Partition::Todo(todo) => {
308                tag_token_spans_in(&self.source, todo.tag_section_range.as_ref())
309            }
310            Partition::Bookmark(bookmark) => {
311                tag_token_spans_in(&self.source, bookmark.tag_section_range.as_ref())
312            }
313        }
314    }
315
316    /// Body partition ranges in source order (half-open byte offsets).
317    pub fn body_ranges(&self) -> Vec<Range<usize>> {
318        match &self.partition {
319            Partition::Note(note) => note.body_ranges.clone(),
320            Partition::Todo(todo) => todo.body_ranges.clone(),
321            Partition::Bookmark(bookmark) => bookmark.body_ranges.clone(),
322        }
323    }
324
325    /// Iterator over body byte ranges (in source order).
326    pub fn body(&self) -> BodyFragments<'_> {
327        BodyFragments {
328            source: &self.source,
329            ranges: self.body_ranges().into_iter(),
330        }
331    }
332
333    /// Concatenated body fragment bytes in source order (fingerprint domain).
334    pub fn body_bytes(&self) -> Vec<u8> {
335        let mut out = Vec::new();
336        for fragment in self.body() {
337            out.extend_from_slice(fragment);
338        }
339        out
340    }
341
342    /// Title line byte range when present (includes trailing newline).
343    pub fn title_byte_range(&self) -> Option<Range<usize>> {
344        self.title_range()
345    }
346
347    /// Tags-prefix (Note) or tags-section (Todo/Bookmark) byte range.
348    pub fn tags_byte_range(&self) -> Option<Range<usize>> {
349        match &self.partition {
350            Partition::Note(note) => note.tags_prefix_range.clone(),
351            Partition::Todo(todo) => todo.tag_section_range.clone(),
352            Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
353        }
354    }
355
356    /// For Bookmark documents, the raw URL line bytes (including
357    /// trailing newline); `None` for non-Bookmark documents or
358    /// Bookmarks without a `<URL>` line.
359    pub fn url(&self) -> Option<&[u8]> {
360        let BookmarkPartition { url_range, .. } = match &self.partition {
361            Partition::Bookmark(bookmark) => bookmark,
362            _ => return None,
363        };
364        url_range.as_ref().map(|r| &self.source[r.clone()])
365    }
366
367    /// `Option<Result<&str, std::str::Utf8Error>>` view of the
368    /// URL.
369    pub fn url_str(&self) -> Option<Result<&str, std::str::Utf8Error>> {
370        self.url().map(std::str::from_utf8)
371    }
372
373    fn title_range(&self) -> Option<Range<usize>> {
374        match &self.partition {
375            Partition::Note(note) => note.title_range.clone(),
376            Partition::Todo(todo) => todo.title_range.clone(),
377            Partition::Bookmark(bookmark) => bookmark.title_range.clone(),
378        }
379    }
380
381    fn tag_section_range(&self) -> Option<Range<usize>> {
382        match &self.partition {
383            Partition::Note(_) => None,
384            Partition::Todo(todo) => todo.tag_section_range.clone(),
385            Partition::Bookmark(bookmark) => bookmark.tag_section_range.clone(),
386        }
387    }
388}
389
390/// Iterator over tag token byte slices.
391pub struct TagsIter<'a> {
392    doc: &'a NoteDocument,
393    token_spans: std::vec::IntoIter<Range<usize>>,
394}
395
396impl<'a> Iterator for TagsIter<'a> {
397    type Item = &'a [u8];
398    fn next(&mut self) -> Option<Self::Item> {
399        self.token_spans.next().map(|r| &self.doc.source[r])
400    }
401}
402
403/// Iterator over tag token string slices, surfacing UTF-8 errors.
404pub struct TagsStrIter<'a> {
405    doc: &'a NoteDocument,
406    token_spans: std::vec::IntoIter<Range<usize>>,
407}
408
409impl<'a> Iterator for TagsStrIter<'a> {
410    type Item = Result<&'a str, std::str::Utf8Error>;
411    fn next(&mut self) -> Option<Self::Item> {
412        self.token_spans
413            .next()
414            .map(|r| std::str::from_utf8(&self.doc.source[r]))
415    }
416}
417
418/// Iterator over body byte ranges.
419pub struct BodyFragments<'a> {
420    source: &'a [u8],
421    ranges: std::vec::IntoIter<Range<usize>>,
422}
423
424impl<'a> Iterator for BodyFragments<'a> {
425    type Item = &'a [u8];
426    fn next(&mut self) -> Option<Self::Item> {
427        self.ranges.next().map(|r| &self.source[r])
428    }
429}