#![allow(clippy::result_large_err)]
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::OnceLock;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tabnas::{
ActionError, Context, GrammarSetting, GrammarSpec, Plugin, PluginError, Rule, RuleSnapshot,
Tabnas, Token, Value,
};
mod lex;
mod number;
pub const VERSION: &str = "0.5.20";
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub use tabnas::TabnasError as ZonError;
pub const BIG_KEY: &str = "$big";
pub const GRAMMAR_TEXT: &str = r##"
# ZON Grammar Definition
# Parses Zig Object Notation (ZON) - a data format based on Zig anonymous
# struct literals.
#
# Example:
# .{
# .name = "example",
# .version = "0.0.1",
# .deps = .{ .foo = .{ .url = "https://..." } },
# .paths = .{ "build.zig", "src" },
# }
#
# The custom zon-dot lex matcher distinguishes struct (map) and tuple (list)
# openings at lex time by peeking ahead:
# .{ followed by .ident = -> emits #OB (struct / map)
# .{ otherwise -> emits #OS (tuple / list)
# Both close on } which lexes as #CB. The list rules below use #CB (not
# the default #CS) as the list terminator so that the single } character
# closes both struct and tuple literals.
#
# A bare .identifier emits #TX with val = identifier (the leading dot is
# stripped). This token is both a valid KEY (when followed by =) and a
# valid VAL (when used as an enum literal).
#
# The grammar is applied with { rule: { alt: { g: 'zon' } } } so every
# alt below is automatically tagged with the 'zon' group.
{
rule: val: open: [
# Empty .{} -> empty list.
{ s: '#OS #CB' b: 2 p: list g: 'list,empty' }
]
rule: list: open: [
# @array$ allocates the list node (an empty array). Under the new core
# the list node is no longer auto-seeded: @tabnas/json's @array$ only
# runs on its own #OS open alts, which ZON replaces here. Without this
# the elem rule's @elem-bc/replace would push onto an undefined node.
{ s: '#OS #CB' b: 1 a: '@array$' g: 'list,empty' }
{ s: '#OS' p: elem a: '@array$' g: 'list,open' }
]
rule: list: close: [
{ s: '#CB' g: 'list,close' }
]
rule: elem: close: [
{ s: '#CA #CB' b: 1 g: 'elem,trailing,comma' }
{ s: '#CA' r: elem g: 'elem,next,comma' }
{ s: '#CB' b: 1 g: 'elem,end' }
]
rule: pair: close: [
{ s: '#CA #CB' b: 1 g: 'pair,trailing,comma' }
{ s: '#CA' r: pair g: 'pair,next,comma' }
{ s: '#CB' b: 1 g: 'pair,end' }
]
}
"##;
const PLUGIN_NAME: &str = "zon";
const INIT_MARK: &str = "zon-init";
const PAIR_BC: &str = "@pair-bc/prepend";
const VAL_AC: &str = "@val-ac/prepend";
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct ZonOptions {
pub char_as_number: bool,
pub enum_tag: Option<String>,
}
impl ZonOptions {
pub fn to_value(&self) -> Value {
Value::from_json(&serde_json::to_value(self).expect("the options serialise"))
}
pub fn from_value(value: &Value) -> Self {
let field = |name: &str| match value {
Value::Object(fields) => fields.get(name),
Value::MapRef(map) => map.value.get(name),
_ => None,
};
ZonOptions {
char_as_number: field("charAsNumber").is_some_and(truthy),
enum_tag: field("enumTag").and_then(tag_of),
}
}
fn tag(&self) -> Option<String> {
self.enum_tag.clone().filter(|tag| !tag.is_empty())
}
}
fn truthy(value: &Value) -> bool {
match value {
Value::Undefined | Value::Null => false,
Value::Bool(flag) => *flag,
Value::Number(number) => *number != 0.0 && !number.is_nan(),
Value::String(text) => !text.is_empty(),
Value::Text(text) => !text.string.is_empty(),
_ => true,
}
}
fn tag_of(value: &Value) -> Option<String> {
match value {
Value::String(text) => Some(text.clone()),
Value::Text(text) => Some(text.string.clone()),
other if truthy(other) => Some(key_of(other)),
_ => None,
}
}
fn key_of(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Text(text) => text.string.clone(),
Value::Number(number) => number::js_number_to_string(*number),
Value::Bool(flag) => flag.to_string(),
Value::Null => "null".to_string(),
Value::Undefined => "undefined".to_string(),
other => integral_numbers(other.to_json()).to_string(),
}
}
fn options_document() -> serde_json::Value {
json!({
"rule": {
"exclude": "jsonic,imp",
"start": "val",
},
"fixed": {
"token": {
"#OB": null,
"#OS": null,
"#CS": null,
"#CL": "=",
},
},
"tokenSet": {
"KEY": ["#TX", null, null, null],
},
"string": {
"lex": false,
},
"number": {
"lex": false,
},
"error": {
"zon_number": "invalid ZON number literal: {src}",
"zon_ident": "invalid ZON identifier: {src}",
"zon_char": "invalid ZON character literal: {src}",
"zon_doc_comment": "doc comments are not allowed in ZON: {src}",
"zon_dup_field": "duplicate struct field name: {src}",
},
"hint": {
"zon_number": "A ZON number is a Zig literal, such as 0, 42, 1_000, 3.14, 1.e3, 0x2a,\n0x1.8p3, 0o17 or 0b101. After a lowercase base prefix every digit is of\nthat base, and there is at least one. A decimal integer part other\nthan 0 does not start with 0. Only decimal and hex numbers take a\nfraction or an exponent (e, or p for hex), and an exponent needs\ndigits. An underscore goes only between two digits. A negative zero is\nwritten -0.0, not -0, and nan takes no sign.",
"zon_ident": "A ZON field name is .name, a letter or underscore then letters, digits\nand underscores, or .@\"text\" for any other name; the quoted form must\nnot be empty or hold an invalid escape.",
"zon_char": "A ZON character literal holds exactly one character or escape between\nsingle quotes, as in 'a', and names a code point no higher than U+10FFFF.",
"zon_doc_comment": "ZON allows only plain // comments. Doc comments, /// and //!, belong to\nZig source; change them to //.",
"zon_dup_field": "A struct literal may name each field only once, and {src} appears\nagain. Remove or rename the repeated field.",
},
"comment": {
"lex": true,
"def": {
"hash": { "lex": false },
"slash": { "line": true, "start": "//", "lex": true, "eatline": false },
"multi": { "lex": false },
},
},
"value": {
"lex": true,
"def": {
"true": { "val": true },
"false": { "val": false },
},
},
"text": {
"lex": false,
},
"lex": {
"match": {
"zonDot": { "order": 1e5, "make": lex::DOT },
"zonMultiString": { "order": 1.1e5, "make": lex::MULTI_STRING },
"zonChar": { "order": 1.2e5, "make": lex::CHAR },
"zonNumber": { "order": 1.3e5, "make": lex::NUMBER },
"zonDocComment": { "order": 1.4e5, "make": lex::DOC_COMMENT },
"zonString": { "order": 1.5e5, "make": lex::STRING },
},
},
})
}
fn grammar_document() -> Result<serde_json::Value, PluginError> {
static RULES: OnceLock<Result<serde_json::Value, String>> = OnceLock::new();
let rules = RULES.get_or_init(|| {
let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
.map_err(|error| format!("zon: failed to parse grammar text: {error}"))?;
let document = integral_numbers(parsed.to_json());
if !document
.get("rule")
.is_some_and(serde_json::Value::is_object)
{
return Err("zon: grammar text did not parse to a rule table".to_string());
}
Ok(document)
});
let mut document = rules.clone().map_err(PluginError)?;
document["options"] = options_document();
Ok(document)
}
fn integral_numbers(value: serde_json::Value) -> serde_json::Value {
match value {
serde_json::Value::Number(number) => match number.as_f64() {
Some(f) if f.fract() == 0.0 && f.abs() < 9.0e15 => json!(f as i64),
_ => serde_json::Value::Number(number),
},
serde_json::Value::Array(items) => {
serde_json::Value::Array(items.into_iter().map(integral_numbers).collect())
}
serde_json::Value::Object(fields) => serde_json::Value::Object(
fields
.into_iter()
.map(|(key, value)| (key, integral_numbers(value)))
.collect(),
),
other => other,
}
}
fn pair_duplicate_guard(
rule: &mut Rule,
context: &mut Context,
_next: Option<&RuleSnapshot>,
_out: Option<Token>,
) -> Result<Option<Token>, ActionError> {
if !matches!(rule.u.get("pair"), Some(Value::Bool(true))) {
return Ok(None);
}
let Some(Value::String(key)) = rule.u.get("key").cloned() else {
return Ok(None);
};
let present = match &*rule.node.borrow() {
Value::Object(fields) => fields.contains_key(&key),
Value::MapRef(map) => map.value.contains_key(&key),
_ => false,
};
if !present {
return Ok(None);
}
let Some(mut token) = rule.o0().cloned().or_else(|| context.t0().cloned()) else {
return Ok(None);
};
token.bad_with_details("zon_dup_field", [("key".to_string(), Value::String(key))]);
Ok(Some(token))
}
fn enum_rewrap(tag: String) -> impl Fn(&mut Rule, &mut Context) -> Result<(), ActionError> {
move |rule, _context| {
if !rule.child_node.is_undefined() || rule.os() == 0 {
return Ok(());
}
let Some(token) = rule.o0() else {
return Ok(());
};
if !matches!(
token.use_data().get(lex::ENUM_MARK),
Some(Value::Bool(true))
) {
return Ok(());
}
let Value::String(name) = token.val.clone() else {
return Ok(());
};
let mut wrapped = IndexMap::new();
wrapped.insert(tag.clone(), Value::String(name));
rule.node = Rc::new(RefCell::new(Value::object(wrapped)));
Ok(())
}
}
pub fn zon(parser: &mut Tabnas, options: &ZonOptions) -> Result<(), PluginError> {
if parser.decoration::<bool>(INIT_MARK).is_some() {
return Ok(());
}
let names = parser.rule_names();
let missing: Vec<&str> = ["val", "map", "list", "pair", "elem"]
.into_iter()
.filter(|rule| !names.iter().any(|name| name.as_str() == *rule))
.collect();
if !missing.is_empty() {
return Err(PluginError(format!(
"zon: the instance has no {} rule; install the jsonic grammar first",
missing.join(", ")
)));
}
parser.state_action_with_next_ref(PAIR_BC, pair_duplicate_guard);
if let Some(tag) = options.tag() {
parser.state_action_ref(VAL_AC, enum_rewrap(tag));
}
lex::register(parser, options.char_as_number);
let spec = GrammarSpec::from_value(grammar_document()?)
.map_err(|error| PluginError(format!("zon: invalid grammar document: {error}")))?;
parser
.grammar_with_setting(&spec, &GrammarSetting::groups("zon"))
.map_err(|error| PluginError(format!("zon: failed to apply grammar: {error}")))?;
parser.decorate(INIT_MARK, true);
Ok(())
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, options| {
zon(parser, &ZonOptions::from_value(options))
})
.with_defaults(ZonOptions::default().to_value())
}
pub fn make_with(options: &ZonOptions) -> Tabnas {
let mut parser = tabnas_jsonic::make();
parser
.use_plugin(plugin(), Some(options.to_value()))
.expect("the zon grammar documents are fixed and valid");
parser
.set_options(|options| options.lex.window = true)
.expect("lex.window sets");
parser
}
pub fn make() -> Tabnas {
make_with(&ZonOptions::default())
}
pub fn parse(src: &str) -> Result<Value, ZonError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}
pub fn parse_with(src: &str, options: &ZonOptions) -> Result<Value, ZonError> {
make_with(options).parse(src)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
pub entry: &'static str,
pub source: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
pub manifest: &'static str,
pub lift: Option<TranslationPart>,
pub embed: Option<TranslationPart>,
pub render: Option<TranslationPart>,
pub transduce: Option<TranslationPart>,
}
const TRANSLATION: TranslationParts = TranslationParts {
manifest: include_str!("../translate/manifest.json"),
lift: None,
embed: None,
render: Some(TranslationPart {
entry: "zon-render",
source: Some(include_str!("../translate/render.alc")),
}),
transduce: Some(TranslationPart {
entry: "zon-transduce",
source: Some(include_str!("../translate/transduce.alc")),
}),
};
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
Some(TRANSLATION)
}
pub fn manifest_text() -> &'static str {
TRANSLATION.manifest
}
pub fn render_text() -> &'static str {
match TRANSLATION.render {
Some(part) => part.source.unwrap_or_default(),
None => "",
}
}
#[cfg(test)]
mod tests {
use super::options_document;
use std::fs;
use std::path::Path;
fn canonical_overrides() -> String {
let source =
fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
.expect("ts/src/zon.ts is readable");
let at = source
.find("grammarDef.options = ")
.expect("ts/src/zon.ts assigns grammarDef.options");
object_body(&source, at).to_string()
}
fn object_body(src: &str, from: usize) -> &str {
let bytes = src.as_bytes();
let mut i = from;
while i < bytes.len() && bytes[i] != b'{' {
i += 1;
}
assert!(i < bytes.len(), "no object literal after byte {from}");
let start = i + 1;
let mut depth = 1usize;
i = start;
while i < bytes.len() && 0 < depth {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'\'' => {
i += 1;
while i < bytes.len() && bytes[i] != b'\'' {
i += if bytes[i] == b'\\' { 2 } else { 1 };
}
i += 1;
}
b'{' => {
depth += 1;
i += 1;
}
b'}' => {
depth -= 1;
i += 1;
}
_ => i += 1,
}
}
assert_eq!(depth, 0, "unbalanced object literal after byte {from}");
&src[start..i - 1]
}
fn entries(body: &str) -> Vec<(String, usize)> {
let bytes = body.as_bytes();
let mut out = Vec::new();
let mut word = String::new();
let mut depth = 0usize;
let mut i = 0usize;
while i < bytes.len() {
match bytes[i] {
b'/' if bytes.get(i + 1) == Some(&b'/') => {
while i < bytes.len() && bytes[i] != b'\n' {
i += 1;
}
}
b'\'' => {
let start = i + 1;
i += 1;
while i < bytes.len() && bytes[i] != b'\'' {
i += if bytes[i] == b'\\' { 2 } else { 1 };
}
if 0 == depth {
word = body[start..i].to_string();
}
i += 1;
}
b'{' | b'[' | b'(' => {
depth += 1;
i += 1;
}
b'}' | b']' | b')' => {
depth -= 1;
i += 1;
}
b':' if 0 == depth => {
assert!(!word.is_empty(), "a value with no key in:\n{body}");
out.push((std::mem::take(&mut word), i + 1));
i += 1;
}
b',' if 0 == depth => {
word.clear();
i += 1;
}
c => {
if 0 == depth {
if c.is_ascii_alphanumeric() || b'_' == c || b'$' == c {
word.push(c as char);
} else {
word.clear();
}
}
i += 1;
}
}
}
out
}
fn keys(body: &str) -> Vec<String> {
entries(body).into_iter().map(|(key, _)| key).collect()
}
fn field<'a>(body: &'a str, key: &str) -> &'a str {
let (_, at) = entries(body)
.into_iter()
.find(|(name, _)| name == key)
.unwrap_or_else(|| panic!("the canonical literal has no {key} key"));
object_body(body, at)
}
fn ported_keys(value: &serde_json::Value) -> Vec<String> {
value
.as_object()
.expect("an object")
.keys()
.cloned()
.collect()
}
#[test]
fn the_option_override_surface_is_the_canonical_one() {
let canonical = canonical_overrides();
let ported = options_document();
assert_eq!(keys(&canonical), ported_keys(&ported));
assert_eq!(
keys(field(&canonical, "error")),
ported_keys(&ported["error"])
);
assert_eq!(
keys(field(field(&canonical, "fixed"), "token")),
ported_keys(&ported["fixed"]["token"])
);
let matchers = field(field(&canonical, "lex"), "match");
assert_eq!(keys(matchers), ported_keys(&ported["lex"]["match"]));
for (name, at) in entries(matchers) {
let body = object_body(matchers, at);
let (_, order_at) = entries(body)
.into_iter()
.find(|(field, _)| "order" == field)
.unwrap_or_else(|| panic!("{name} declares no order"));
let text: String = body[order_at..]
.chars()
.skip_while(char::is_ascii_whitespace)
.take_while(|c| !c.is_whitespace() && ',' != *c)
.collect();
let want: f64 = text
.parse()
.unwrap_or_else(|_| panic!("{name} has a non-numeric order {text:?}"));
assert_eq!(
ported["lex"]["match"][&name]["order"].as_f64(),
Some(want),
"{name}"
);
}
}
#[test]
fn the_two_override_differences_are_the_documented_ones() {
let canonical = canonical_overrides();
let ported = options_document();
assert_eq!(
keys(field(field(&canonical, "value"), "def")),
["true", "false", "null"]
);
assert_eq!(ported_keys(&ported["value"]["def"]), ["true", "false"]);
let source =
fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../ts/src/zon.ts"))
.expect("ts/src/zon.ts is readable");
assert!(source.contains("'zon-tokendesc'"));
assert!(source.contains("cfg.tokenDesc"));
assert_eq!(ported.get("config"), None);
}
}