// Data formats behind one registry.
//
// Every parser turns a document into the builder's `Json` value, so
// configuration, `_data` files and front matter all share one representation.
// Adding a format means registering a parser, not editing the pipeline.
///|
/// Parse YAML with `moonbit-community/yaml`, taking the first document.
pub fn parse_yaml(text : StringView) -> Json {
let docs = @yaml.Yaml::load_from_string(text) catch {
_ => ([] : Array[@yaml.Yaml])
}
if docs.length() == 0 {
Json::object(Map([]))
} else {
docs[0].to_json()
}
}
///|
/// Parse JSON with the core parser.
pub fn parse_json(text : StringView) -> Json {
@json.parse(text) catch {
_ => Json::object(Map([]))
}
}
///|
/// Parse TOML with `moonbit-community/toml`.
pub fn parse_toml(text : StringView) -> Json {
let value = @toml.parse(text.to_owned()) catch {
_ => return Json::object(Map([]))
}
toml_to_json(value)
}
///|
/// Whether a document parses cleanly. Parsers used by the registry are
/// deliberately forgiving; configuration loading uses this check to warn
/// instead of silently falling back to every default.
pub fn parse_ok(text : StringView, ext : StringView) -> Bool {
match ext.to_lower() {
"json" => {
let _ = @json.parse(text) catch { _ => return false }
true
}
"toml" => {
let _ = @toml.parse(text.to_owned()) catch { _ => return false }
true
}
"yaml" | "yml" => {
let docs = @yaml.Yaml::load_from_string(text) catch { _ => return false }
docs.length() > 0
}
_ => true
}
}
// Convert a TOML value tree into the core JSON representation.
///|
fn toml_to_json(value : @toml.TomlValue) -> Json {
match value {
@toml.TomlString(s) => Json::string(s)
@toml.TomlInteger(i) => Json::number(i.to_double())
@toml.TomlFloat(f) => Json::number(f)
@toml.TomlBoolean(b) => Json::boolean(b)
@toml.TomlArray(items) =>
Json::array(items.map(fn(item) { toml_to_json(item) }))
@toml.TomlTable(table) => {
let result : Map[String, Json] = Map([])
for key, item in table {
result.set(key, toml_to_json(item))
}
Json::object(result)
}
@toml.TomlDateTime(dt) => Json::string(dt.to_string())
}
}
///|
/// A registry of data formats, keyed by the extension that selects them.
///
/// `FormatRegistry::builtin()` covers YAML, JSON, TOML and INI. New formats
/// (CSV, JSON5, KDL, ...) are added with `register` and are then usable for
/// configuration, data files and front matter alike.
pub struct FormatRegistry {
parsers : Map[String, (StringView) -> Json]
aliases : Map[String, String]
fallback : Ref[String]
}
///|
/// Create an empty registry with no fallback: unknown formats yield `{}`.
pub fn FormatRegistry::new() -> FormatRegistry {
FormatRegistry::{
parsers: Map([]),
aliases: Map([]),
fallback: { val: "", },
}
}
///|
/// Create a registry with YAML, JSON, TOML and INI registered.
///
/// YAML owns `.yaml` / `.yml` and is also the fallback for unknown extensions,
/// matching the behaviour of the single-format loader Fus shipped with.
pub fn FormatRegistry::builtin() -> FormatRegistry {
let registry = FormatRegistry::new()
registry.register("yaml", parse_yaml)
registry.register("yml", parse_yaml)
registry.register("json", parse_json)
registry.register("toml", parse_toml)
registry.register("ini", parse_ini)
registry.set_fallback("yaml")
registry
}
///|
/// Register `parser` for one extension (case-insensitive, no leading dot).
pub fn FormatRegistry::register(
self : FormatRegistry,
ext : StringView,
parser : (StringView) -> Json,
) -> Unit {
self.parsers.set(ext.to_lower().to_owned(), parser)
}
///|
/// Point `from` at the parser already registered for `to`.
pub fn FormatRegistry::register_alias(
self : FormatRegistry,
from : StringView,
to : StringView,
) -> Unit {
self.aliases.set(from.to_lower().to_owned(), to.to_lower().to_owned())
}
///|
/// Choose the parser used when an extension is not registered.
pub fn FormatRegistry::set_fallback(
self : FormatRegistry,
ext : StringView,
) -> Unit {
self.fallback.val = ext.to_lower().to_owned()
}
///|
/// Whether an extension can be parsed by this registry.
pub fn FormatRegistry::supports(
self : FormatRegistry,
ext : StringView,
) -> Bool {
match self.resolve(ext) {
Some(_) => true
None => false
}
}
// Follow aliases until a registered extension is found.
///|
fn FormatRegistry::resolve(self : FormatRegistry, ext : StringView) -> String? {
let mut key = ext.to_lower().to_owned()
for i = 0; i < 8; i = i + 1 {
if self.parsers.contains(key) {
return Some(key)
}
match self.aliases.get(key) {
Some(next) => key = next
None => return None
}
}
None
}
///|
/// Parse `text` as `ext`.
///
/// An unregistered extension falls back to the configured fallback parser (YAML
/// in `builtin`), and a parser error yields an empty object: a broken data file
/// should not abort a build.
pub fn FormatRegistry::parse(
self : FormatRegistry,
text : StringView,
ext : StringView,
) -> Json {
let key = match self.resolve(ext) {
Some(k) => k
None => self.fallback.val
}
match self.parsers.get(key) {
Some(parser) => parser(text)
None => Json::object(Map([]))
}
}
///|
/// Every registered extension, sorted, for diagnostics and docs.
pub fn FormatRegistry::extensions(self : FormatRegistry) -> Array[String] {
let result : Array[String] = []
for key, _ in self.parsers {
result.push(key)
}
result.sort_by(fn(a, b) { @core.compare_lex(a, b) })
result
}
///|
/// Lowercase extension of `path` without the leading dot, ready for `parse`.
pub fn format_of_path(path : StringView) -> String {
let ext = @core.extname(path)
let bare = if ext.has_prefix(".") {
@core.slice(ext, 1, ext.length())
} else {
ext
}
bare.to_lower()
}
///|
/// Parse `text` as the named format using the built-in registry.
pub fn parse_format(text : StringView, format : StringView) -> Json {
FormatRegistry::builtin().parse(text, format)
}