jots 0.2.0

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

use crate::config::{CategoryRoot, Config};
use crate::grammar::{self, Grammar};
use crate::types::{Blocker, 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(g: &Grammar, text: Option<&str>) -> DecodedSpec {
    let Some(text) = text.filter(|t| !t.is_empty()) else {
        return DecodedSpec::default();
    };

    if let Ok(Some(c)) = g.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)) = g.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()
}

/// Which annotation suffixes a construct may keep (§9.1, §9.2): the
/// `parse_categories` / `parse_tags` gates and the resolved category
/// root. A suffix the policy rejects ends the construct; the suffix and
/// everything after it is ordinary text (description text in a todo).
#[derive(Debug, Clone)]
pub struct SuffixPolicy {
    pub categories: bool,
    pub tags: bool,
    pub root: Option<String>,
}

impl SuffixPolicy {
    pub fn from_config(cfg: &Config) -> Self {
        SuffixPolicy {
            categories: cfg.enabled("parse_categories", true),
            tags: cfg.enabled("parse_tags", true),
            root: match cfg.category_root() {
                CategoryRoot::Root(r) => Some(r),
                _ => None,
            },
        }
    }

    /// Byte length of the prefix of `annot` the construct keeps. Equal
    /// to `annot.len()` when nothing is cut.
    pub fn cut(&self, g: &Grammar, annot: &str) -> usize {
        let mut rest = annot;
        let mut kept = 0;
        if let Ok(Some(c)) = g.decode_category_prefix.captures(rest) {
            let m = c.get(0).unwrap();
            if !self.categories {
                return 0;
            }
            if let Some(root) = &self.root {
                let first = c[1].split("::").next().unwrap_or("").to_lowercase();
                if &first != root {
                    return 0;
                }
            }
            kept = m.end();
            rest = &rest[m.end()..];
        }
        if !self.tags && rest.starts_with("..") {
            return kept;
        }
        annot.len()
    }
}

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

/// Parse-error class for a todo body that fails the grammar. Each
/// variant maps to one canonical code in Part III.
pub struct TodoError {
    pub code: &'static str,
    pub message: String,
}

fn todo_err(code: &'static str, message: impl Into<String>) -> TodoError {
    TodoError {
        code,
        message: message.into(),
    }
}

/// Decode the body of a todo line (everything after `??`). On grammar
/// failure returns the canonical parse-error condition — blocker-slot
/// errors, grammar-level malformed due dates, or the generic
/// `Jots/Parsing/TodoMissingAction` fallback (11.9).
pub fn decode_todo_body(
    g: &Grammar,
    body: &str,
    policy: &SuffixPolicy,
) -> Result<Todo, TodoError> {
    // Trailing whitespace is insignificant; leading whitespace means the
    // action does not immediately follow `??` and the classifiers below
    // decide which condition fires.
    let trimmed = body.trim_end_matches([' ', '\t']);

    let Some(caps) = g.decode_todo_body.captures(trimmed).ok().flatten() else {
        if grammar::TODO_WS_BEFORE_PAREN.is_match(trimmed).unwrap_or(false)
            || grammar::TODO_WS_AFTER_PAREN.is_match(trimmed).unwrap_or(false)
        {
            return Err(todo_err(
                "Jots/Parsing/WhitespaceInBlockers",
                "whitespace around or inside the blocker slot is not allowed",
            ));
        }
        if g.todo_malformed_due.is_match(trimmed).unwrap_or(false) {
            return Err(todo_err(
                "Jots/Parsing/MalformedDueDate",
                "'@' after the action does not introduce a valid ISO 8601 due date",
            ));
        }
        return Err(todo_err(
            "Jots/Parsing/TodoMissingAction",
            "todo '??' is missing an action",
        ));
    };

    let done = caps.get(1).is_some();
    let imp = caps.get(2).map(|m| m.as_str().len() as u8).unwrap_or(0);
    let blockers = decode_blockers(g, caps.get(3).map(|m| m.as_str()))?;
    let action = caps[4].to_string();
    let due = caps.get(5).map(|m| m.as_str().to_string());
    let annot_m = caps.get(6);
    let annot = annot_m.map(|m| m.as_str()).unwrap_or("");
    let desc_raw = caps.get(7).map(|m| m.as_str()).unwrap_or("");
    // §9.1 / §9.2 — a suffix the policy rejects ends the annotation
    // slot; it and the rest of the line become the description.
    let cut = policy.cut(g, annot);
    let (category, tags, desc_raw) = if cut < annot.len() {
        let (c, t) = decode_annotations(g, &annot[..cut]);
        let from = annot_m.unwrap().start() + cut;
        (c, t, &trimmed[from..])
    } else {
        let (c, t) = decode_annotations(g, annot);
        (c, t, desc_raw)
    };

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

    Ok(Todo {
        importance: imp,
        blockers,
        action,
        categories: category.into_iter().collect(),
        tags,
        due,
        completed: None,
        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,
        done,
    })
}

/// Validate and decode the blocker slot content (between the parens).
fn decode_blockers(g: &Grammar, slot: Option<&str>) -> Result<Vec<Blocker>, TodoError> {
    let Some(content) = slot else {
        return Ok(Vec::new());
    };
    if content.contains([' ', '\t']) {
        return Err(todo_err(
            "Jots/Parsing/WhitespaceInBlockers",
            "whitespace inside the blocker parens is not allowed",
        ));
    }
    if content.is_empty() {
        return Err(todo_err(
            "Jots/Parsing/EmptyBlockerList",
            "blocker slot '()' has no entries",
        ));
    }
    let mut blockers = Vec::new();
    for entry in content.split(',') {
        if entry.is_empty() {
            return Err(todo_err(
                "Jots/Parsing/EmptyBlockerEntry",
                "empty entry in blocker list",
            ));
        }
        if entry.starts_with('*') {
            let Ok(Some(c)) = g.blocker_entry_wildcard.captures(entry) else {
                return Err(todo_err(
                    "Jots/Parsing/InvalidWildcardBlocker",
                    "wildcard blocker entry requires a '::category' constraint",
                ));
            };
            blockers.push(Blocker {
                action: "*".to_string(),
                cat: Some(c[1].trim_start_matches("::").to_lowercase()),
                tags: decode_entry_tags(c.get(2).map(|m| m.as_str()).unwrap_or("")),
            });
        } else {
            let Ok(Some(c)) = g.blocker_entry_word.captures(entry) else {
                // Characters the blocker grammar cannot consume — the
                // generic fallback code per the §10.1 precedence rule.
                return Err(todo_err(
                    "Jots/Parsing/InvalidPayloadChars",
                    "blocker entry contains characters outside the blocker grammar",
                ));
            };
            blockers.push(Blocker {
                action: c[1].to_string(),
                cat: c
                    .get(2)
                    .map(|m| m.as_str().trim_start_matches("::").to_lowercase()),
                tags: decode_entry_tags(c.get(3).map(|m| m.as_str()).unwrap_or("")),
            });
        }
    }
    Ok(blockers)
}

fn decode_entry_tags(tail: &str) -> Vec<String> {
    let mut tags = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for seg in tail.split("..").filter(|s| !s.is_empty()) {
        let t = seg.to_lowercase();
        if seen.insert(t.clone()) {
            tags.push(t);
        }
    }
    tags
}

/// §13.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
}