jots 0.2.0

Jot Syntax 1.0 RC6 parser (https://jotsyntax.org)
Documentation
//! Parser configuration. Defaults from §9; loading order from §9 (env > local
//! `.jot.toml` > `$HOME/.jot.toml` > defaults).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// Internal config representation. `None` means "use the default"; a `Some`
/// value carries either a clean bool or the raw string from a config source
/// so §15.1 (`Jots/Validation/InvalidFlagValue`) can flag bad inputs.
#[derive(Debug, Clone, Default)]
pub struct Config {
    pub flags: BTreeMap<String, FlagValue>,
    /// Variant toggle: `false` = Jot Syntax (ASCII identifiers),
    /// `true` = Iota Syntaxis (Unicode XID identifiers). API-level
    /// only — deliberately NOT a §9 config flag: the spec's flag
    /// list is closed and shared verbatim by both variants, so this
    /// is never read from `.jot.toml` or `JOTS_*` env vars.
    pub unicode: bool,
}

#[derive(Debug, Clone)]
pub enum FlagValue {
    Bool(bool),
    /// Held verbatim so an invalid string ("maybe", "yes") still surfaces as a
    /// `Jots/Validation/InvalidFlagValue` diagnostic instead of being silently
    /// coerced to false.
    Raw(String),
}

pub const FLAG_KEYS: &[&str] = &[
    "parse_tags",
    "parse_categories",
    "parse_references",
    "parse_file_references",
    "parse_resources",
    "parse_todos",
    "parse_urls",
    "parse_bookmarks",
    "parse_hashtags_as_tags",
    "emit_loc",
];

const ENV_MAP: &[(&str, &str)] = &[
    ("JOTS_PARSE_TAGS", "parse_tags"),
    ("JOTS_PARSE_CATEGORIES", "parse_categories"),
    ("JOTS_PARSE_REFERENCES", "parse_references"),
    ("JOTS_PARSE_FILE_REFERENCES", "parse_file_references"),
    ("JOTS_PARSE_RESOURCES", "parse_resources"),
    ("JOTS_PARSE_TODOS", "parse_todos"),
    ("JOTS_PARSE_URLS", "parse_urls"),
    ("JOTS_PARSE_BOOKMARKS", "parse_bookmarks"),
    ("JOTS_PARSE_HASHTAGS_AS_TAGS", "parse_hashtags_as_tags"),
    ("JOTS_EMIT_LOC", "emit_loc"),
    ("JOTS_CATEGORY_ROOT", "category_root"),
];

/// Resolved `category_root` (§9.1). The flag is a string, not a boolean,
/// so it lives outside `FLAG_KEYS` and has its own validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CategoryRoot {
    /// Unset or empty: every category path is accepted.
    Unset,
    /// A single `<word>`, case-folded for comparison.
    Root(String),
    /// Not a single `<word>` (several segments, sigils, whitespace, or a
    /// boolean). Reported as `Jots/Validation/InvalidCategoryRoot`; the
    /// parser then proceeds as if the flag were unset. Carries the
    /// display form of the offending value.
    Invalid(String),
}

impl Config {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn set(&mut self, key: &str, value: FlagValue) {
        self.flags.insert(key.to_string(), value);
    }

    pub fn set_bool(&mut self, key: &str, value: bool) {
        self.flags.insert(key.to_string(), FlagValue::Bool(value));
    }

    /// §9.1 — resolve `category_root` against the `<word>` production of
    /// the active variant.
    pub fn category_root(&self) -> CategoryRoot {
        let Some(v) = self.flags.get("category_root") else {
            return CategoryRoot::Unset;
        };
        let s = match v {
            FlagValue::Raw(s) => s.as_str(),
            FlagValue::Bool(b) => return CategoryRoot::Invalid(b.to_string()),
        };
        if s.is_empty() {
            return CategoryRoot::Unset;
        }
        let g = crate::grammar::grammar(self.unicode);
        if g.word_full.is_match(s).unwrap_or(false) {
            CategoryRoot::Root(s.to_lowercase())
        } else {
            CategoryRoot::Invalid(s.to_string())
        }
    }

    /// Mirrors `_config_is_false` from the Perl reference: anything other than
    /// recognized truthy strings/booleans falls through to the default.
    /// Returns `true` when the flag should be considered enabled.
    pub fn enabled(&self, key: &str, default: bool) -> bool {
        let Some(v) = self.flags.get(key) else {
            return default;
        };
        match v {
            FlagValue::Bool(b) => *b,
            FlagValue::Raw(s) => {
                let lower = s.to_ascii_lowercase();
                match lower.as_str() {
                    "true" | "1" => true,
                    "false" | "0" | "" => false,
                    // Lenient fallback: anything we don't recognize is treated
                    // as "not false" so parsing proceeds (the diagnostic comes
                    // from §15.1, emitted separately).
                    _ => true,
                }
            }
        }
    }
}

/// Walk: defaults ← `~/.jot.toml` ← every `.jot.toml` from filesystem root
/// down to CWD ← `JOTS_*` env vars. Returns a Config holding only explicit
/// overrides; defaults are applied at lookup time.
pub fn load() -> Config {
    let mut cfg = Config::new();

    if let Some(home) = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")) {
        let path = Path::new(&home).join(".jot.toml");
        merge_toml(&mut cfg, &path);
    }

    let cwd = std::env::current_dir().ok();
    if let Some(cwd) = cwd {
        let mut chain: Vec<PathBuf> = Vec::new();
        let mut cur = Some(cwd.as_path());
        while let Some(d) = cur {
            chain.push(d.to_path_buf());
            cur = d.parent();
        }
        // Apply root-first so deeper directories override.
        for d in chain.iter().rev() {
            merge_toml(&mut cfg, &d.join(".jot.toml"));
        }
    }

    for (env_key, cfg_key) in ENV_MAP {
        if let Ok(val) = std::env::var(env_key) {
            cfg.set(cfg_key, FlagValue::Raw(val));
        }
    }

    cfg
}

fn merge_toml(cfg: &mut Config, path: &Path) {
    let Ok(text) = std::fs::read_to_string(path) else {
        return;
    };
    let Ok(parsed) = text.parse::<toml::Value>() else {
        return;
    };
    let toml::Value::Table(table) = parsed else {
        return;
    };
    for (k, v) in table {
        let val = match v {
            toml::Value::Boolean(b) => FlagValue::Bool(b),
            toml::Value::String(s) => FlagValue::Raw(s),
            toml::Value::Integer(i) => FlagValue::Raw(i.to_string()),
            other => FlagValue::Raw(other.to_string()),
        };
        cfg.flags.insert(k, val);
    }
}

/// §15.1 — recognized flag-value forms. Matches `_is_valid_flag_value`.
pub fn is_valid_flag_value(v: &FlagValue) -> bool {
    match v {
        FlagValue::Bool(_) => true,
        FlagValue::Raw(s) => {
            let lower = s.to_ascii_lowercase();
            matches!(lower.as_str(), "true" | "false" | "1" | "0" | "")
        }
    }
}