jots 0.1.0

Jot Syntax 1.0 RC1 parser (https://jotsyntax.org)
Documentation
//! Decode raw specifier / annotation / todo-body strings into typed fields.
//! All routines mirror the Perl `_decode_*` helpers.

use crate::grammar;
use crate::types::{BookmarkRange, Fragment, Todo};

#[derive(Debug, Default)]
pub struct DecodedSpec {
    pub fragment: Option<Fragment>,
    pub bookmark: Option<String>,
    pub bookmark_range: Option<BookmarkRange>,
}

pub fn decode_specifier(text: Option<&str>) -> DecodedSpec {
    let Some(text) = text.filter(|t| !t.is_empty()) else {
        return DecodedSpec::default();
    };

    if let Ok(Some(c)) = grammar::DECODE_BMR_RANGE.captures(text) {
        let start = c.get(1).map(|m| m.as_str().to_string()).filter(|s| !s.is_empty());
        let end = c.get(2).map(|m| m.as_str().to_string()).filter(|s| !s.is_empty());
        return DecodedSpec {
            bookmark_range: Some(BookmarkRange {
                start_bookmark: start,
                end_bookmark: end,
            }),
            ..DecodedSpec::default()
        };
    }
    if let Ok(Some(c)) = grammar::DECODE_BM.captures(text) {
        return DecodedSpec {
            bookmark: Some(c[1].to_string()),
            ..DecodedSpec::default()
        };
    }
    if let Ok(Some(c)) = grammar::DECODE_FRAG_RANGE.captures(text) {
        let start: u64 = c[1].parse().unwrap_or(0);
        let end: u64 = c[2].parse().unwrap_or(0);
        return DecodedSpec {
            fragment: Some(Fragment {
                start,
                end,
                raw: text.to_string(),
            }),
            ..DecodedSpec::default()
        };
    }
    if let Ok(Some(c)) = grammar::DECODE_FRAG_OFFSET.captures(text) {
        let start: u64 = c[1].parse().unwrap_or(0);
        let len: u64 = c[2].parse().unwrap_or(0);
        return DecodedSpec {
            fragment: Some(Fragment {
                start,
                end: start.saturating_add(len),
                raw: text.to_string(),
            }),
            ..DecodedSpec::default()
        };
    }
    if let Ok(Some(c)) = grammar::DECODE_FRAG_SINGLE.captures(text) {
        let n: u64 = c[1].parse().unwrap_or(0);
        return DecodedSpec {
            fragment: Some(Fragment {
                start: n,
                end: n,
                raw: text.to_string(),
            }),
            ..DecodedSpec::default()
        };
    }

    DecodedSpec::default()
}

/// Decode `[::cat][..tag]…` into (category, deduped tags). The grammar
/// already enforces category-before-tags (§1.6.3), so we only consume from
/// the front in that order.
pub fn decode_annotations(text: &str) -> (Option<String>, Vec<String>) {
    let mut rest = text;
    let mut category = None;
    if let Ok(Some(c)) = grammar::DECODE_CATEGORY_PREFIX.captures(rest) {
        let m = c.get(0).unwrap();
        category = Some(c[1].to_ascii_lowercase());
        rest = &rest[m.end()..];
    }
    let mut tags: Vec<String> = Vec::new();
    let mut seen = std::collections::HashSet::new();
    while let Ok(Some(c)) = grammar::DECODE_TAG_PREFIX.captures(rest) {
        let m = c.get(0).unwrap();
        let t = c[1].to_ascii_lowercase();
        if seen.insert(t.clone()) {
            tags.push(t);
        }
        rest = &rest[m.end()..];
    }
    (category, tags)
}

/// Decode the body of a todo line (everything after `??`). Returns `None`
/// when the body doesn't conform to the grammar — `parse` then emits
/// `Jots/Parsing/TodoMissingAction` (§4.2.10).
pub fn decode_todo_body(body: &str) -> Option<Todo> {
    let trimmed = body.trim_matches([' ', '\t'].as_ref());
    let caps = grammar::DECODE_TODO_BODY.captures(trimmed).ok().flatten()?;
    let imp = caps.get(1).map(|m| m.as_str().len() as u8).unwrap_or(0);
    let action = caps[2].to_string();
    let due = caps.get(3).map(|m| m.as_str().to_string());
    let annot = caps.get(4).map(|m| m.as_str()).unwrap_or("");
    let desc_raw = caps.get(5).map(|m| m.as_str()).unwrap_or("");
    let (category, tags) = decode_annotations(annot);

    let description = desc_raw.trim_matches([' ', '\t'].as_ref()).to_string();

    Some(Todo {
        importance: imp,
        action,
        categories: category.into_iter().collect(),
        tags,
        due,
        description,
        references: Vec::new(),
        cross_references: Vec::new(),
        file_references: Vec::new(),
        cross_file_references: Vec::new(),
        inter_jot_resources: Vec::new(),
        resources: Vec::new(),
        urls: Vec::new(),
        loc: None,
        raw: None,
    })
}

/// §4.4.9 — semantic ISO 8601 date validation. Mirrors `_is_valid_iso_date`.
pub fn is_valid_iso_date(s: &str) -> bool {
    let Ok(Some(c)) = grammar::ISO_DATE_VALIDATOR.captures(s) else {
        return false;
    };
    let y: i32 = c[1].parse().unwrap_or(0);
    let m: u32 = c[2].parse().unwrap_or(0);
    let d: u32 = c[3].parse().unwrap_or(0);
    if !(1..=12).contains(&m) {
        return false;
    }
    if !(1..=31).contains(&d) {
        return false;
    }
    let days = [31u32, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let mut max = days[(m - 1) as usize];
    if m == 2 {
        let leap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
        if leap {
            max = 29;
        }
    }
    if d > max {
        return false;
    }
    if let Some(h_match) = c.get(4) {
        let h: u32 = h_match.as_str().parse().unwrap_or(0);
        let mn: u32 = c[5].parse().unwrap_or(0);
        if h > 23 {
            return false;
        }
        if mn > 59 {
            return false;
        }
        if let Some(s_match) = c.get(6) {
            let s_val: u32 = s_match.as_str().parse().unwrap_or(0);
            if s_val > 60 {
                return false;
            }
        }
    }
    true
}