#![allow(clippy::result_large_err)]
use std::sync::OnceLock;
use serde_json::{json, Map, Value as Json};
use tabnas::{GrammarError, GrammarSpec, Plugin, PluginError, Tabnas, Value, ValueDef};
mod datematcher;
mod daterange;
mod node;
mod refs;
mod strmatcher;
mod values;
pub use tabnas::TabnasError as TomlError;
pub use values::{toml_time, TomlTime, LOCAL_DATE, LOCAL_DATE_TIME, LOCAL_TIME, OFFSET_DATE_TIME};
pub const VERSION: &str = "0.5.9";
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub(crate) const GRAMMAR_TEXT: &str = r#"
# TOML Grammar Definition
# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
# Function references (@ prefixed) are resolved against the refs map.
# Regex references (@/pattern/flags) are resolved to RegExp instances.
{
options: rule: { start: toml exclude: jsonic }
options: lex: {
emptyResult: {}
match: string: make: '@make-toml-string-matcher'
}
options: fixed: token: { '#CL': '=' '#DOT': '.' }
options: match: {
token: { '#ID': '@/^[a-zA-Z0-9_-]+/' }
value: {
isodate: {
match: '@/^\\d\\d\\d\\d-\\d\\d-\\d\\d([Tt ]\\d\\d:\\d\\d(:\\d\\d(\\.\\d+)?)?([Zz]|[-+]\\d\\d:\\d\\d)?)?/'
val: '@isodate-val'
}
localtime: {
match: '@/^\\d\\d:\\d\\d(:\\d\\d(\\.\\d+)?)?/'
val: '@localtime-val'
}
}
}
options: tokenSet: {
KEY: ['#ST' '#ID' null null]
}
options: comment: def: { slash: null multi: null }
rule: toml: open: [
{ s: ['#ST #NR #ID' '#CL'] p: table b: 2 }
{ s: ['#OS' '#ST #NR #ID'] p: table b: 2 }
{ s: ['#OS' '#OS'] p: table b: 2 }
{ s: ['#ST #NR #ID' '#DOT'] p: table b: 2 }
{ s: '#ZZ' }
]
rule: table: {
open: [
{ s: ['#ST #NR #ID' '#CL'] p: map b: 2 }
{ s: ['#OS' '#ST #NR #ID'] r: table b: 1 }
{ s: ['#OS' '#OS'] r: table n: { table_array: 1 } }
{
s: ['#ST #NR #ID' '#DOT']
c: '@table-top-dive-cond'
p: dive
b: 2
u: { top_dive: true }
}
{
s: ['#ST #NR #ID' '#DOT']
r: table
c: '@lte-table-dive'
n: { table_dive: 1 }
a: '@table-dive-start'
g: 'dive,start'
}
{
s: ['#ST #NR #ID' '#DOT']
r: table
n: { table_dive: 1 }
a: '@table-dive-mid'
g: 'dive'
}
{
s: ['#ST #NR #ID' '#CS']
c: '@lte-table-dive'
p: '@table-end-p'
r: '@table-end-r'
a: '@table-key-cs-head'
}
{
s: ['#ST #NR #ID' '#CS']
p: '@table-end-p'
r: '@table-end-r'
a: '@table-key-cs-tail'
g: 'dive,end'
}
{
s: '#CS'
p: map
c: '@lte-table-array-1'
a: '@table-cs-push'
}
]
close: [
{ s: ['#OS' '#OS'] r: table b: 2 g: end }
{ s: ['#OS' '#ST #NR #ID'] r: table b: 1 g: end }
{ s: '#ZZ' g: end }
]
}
rule: map: {
open: [
{ s: '#OS' b: 1 }
{
s: ['#ST #NR #ID' '#CL']
c: '@map-is-table-parent'
p: pair
b: 2
}
{ s: ['#OB' '#ST #NR #ID'] b: 1 p: pair }
{ s: ['#ST #NR #ID' '#DOT'] p: dive b: 2 }
{ s: '#ZZ' }
]
close: [
{ s: '#OS' b: 1 g: end }
{ s: '#ZZ' g: end }
]
}
rule: pair: {
open: [
{
s: ['#ST #NR #ID' '#CL']
p: val
u: { pair: true }
a: '@pair-key-set'
}
{ s: ['#ST #NR #ID' '#DOT'] p: dive b: 2 }
]
close: [
{ s: ['#ST #NR #ID'] b: 1 r: pair g: comma }
{ s: ['#CA' '#ST #NR #ID'] b: 1 r: pair g: comma }
{ s: ['#OS'] b: 1 g: end }
{ s: ['#CA' '#CB'] c: '@lte-pk' b: 1 g: close }
]
}
rule: val: close: [
{ s: ['#ST #NR #ID'] b: 1 g: end }
{ s: ['#OS'] b: 1 g: end }
]
rule: elem: close: [
{ s: ['#CA' '#CS'] b: 1 g: comma }
]
rule: dive: {
open: [
{
s: ['#ST #NR #ID' '#DOT']
p: dive
n: { dive_key: 1 }
a: '@dive-key-dot'
}
{
s: ['#ST #NR #ID' '#CL']
p: val
n: { dive_key: 1 }
u: { dive_end: true }
}
]
close: [
{
s: ['#ST #NR #ID' '#DOT']
b: 2
r: dive
c: '@lte-dive-key-1'
n: { dive_key: 0 }
}
{}
]
}
}
"#;
const PLUGIN_NAME: &str = "toml";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TomlOptions;
const BOM_ORDER: f64 = 500_000.0;
const STRING_ORDER: f64 = 900_000.0;
const ISODATE_ORDER: f64 = 950_000.0;
const LOCALTIME_ORDER: f64 = 950_001.0;
fn grammar_document() -> Result<Json, GrammarError> {
let parsed = tabnas_jsonic::make()
.parse(GRAMMAR_TEXT)
.map_err(|error| GrammarError(format!("Grammar: parse grammar text: {error}")))?;
let mut document = parsed.to_json();
integerize(&mut document);
let Some(root) = document.as_object_mut() else {
return Err(GrammarError(
"Grammar: the grammar text is not a map".into(),
));
};
let options = root
.entry("options".to_string())
.or_insert_with(|| Json::Object(Map::new()));
let Some(options) = options.as_object_mut() else {
return Err(GrammarError("Grammar: options is not a map".into()));
};
adjust_token_sets(options);
adjust_value_matchers(options);
adjust_lex_matchers(options);
adjust_messages(options);
Ok(document)
}
fn integerize(value: &mut Json) {
match value {
Json::Number(number) => {
if let Some(float) = number.as_f64() {
#[allow(clippy::cast_possible_truncation)]
if float.is_finite() && 0.0 == float.fract() && float.abs() < 9.0e15 {
*value = Json::from(float as i64);
}
}
}
Json::Array(items) => items.iter_mut().for_each(integerize),
Json::Object(entries) => entries.values_mut().for_each(integerize),
_ => {}
}
}
fn adjust_token_sets(options: &mut Map<String, Json>) {
let Some(sets) = options.get_mut("tokenSet").and_then(Json::as_object_mut) else {
return;
};
for members in sets.values_mut() {
if let Some(list) = members.as_array_mut() {
list.retain(|member| member.is_string());
}
}
}
fn adjust_value_matchers(options: &mut Map<String, Json>) {
let Some(values) = options
.get_mut("match")
.and_then(Json::as_object_mut)
.and_then(|matchers| matchers.get_mut("value"))
.and_then(Json::as_object_mut)
else {
return;
};
for (name, ascii) in [
("isodate", datematcher::isodate_re().as_str()),
("localtime", datematcher::localtime_re().as_str()),
] {
let Some(entry) = values.get_mut(name).and_then(Json::as_object_mut) else {
continue;
};
if entry
.get("match")
.and_then(Json::as_str)
.is_some_and(|reference| reference.starts_with("@/"))
{
entry.insert("match".to_string(), json!(format!("@/{ascii}/")));
}
}
}
fn adjust_lex_matchers(options: &mut Map<String, Json>) {
let lex = options
.entry("lex".to_string())
.or_insert_with(|| Json::Object(Map::new()));
let Some(lex) = lex.as_object_mut() else {
return;
};
let matchers = lex
.entry("match".to_string())
.or_insert_with(|| Json::Object(Map::new()));
let Some(matchers) = matchers.as_object_mut() else {
return;
};
if let Some(string) = matchers.get_mut("string").and_then(Json::as_object_mut) {
string.insert("order".to_string(), json!(STRING_ORDER));
}
matchers.insert(
"bom".to_string(),
json!({ "order": BOM_ORDER, "make": "@bom-matcher" }),
);
matchers.insert(
"tomlisodate".to_string(),
json!({ "order": ISODATE_ORDER, "make": "@isodate-match" }),
);
matchers.insert(
"tomllocaltime".to_string(),
json!({ "order": LOCALTIME_ORDER, "make": "@localtime-match" }),
);
}
fn adjust_messages(options: &mut Map<String, Json>) {
options.insert(
"error".to_string(),
json!({
"toml_key_conflict": "cannot define {key}, {why}",
"invalid_datetime": "date or time is out of range",
}),
);
options.insert(
"hint".to_string(),
json!({
"toml_key_conflict": "\nTOML does not allow a key to be redefined, and a key that already holds a\nvalue is not a table you can add to. This usually means the same name was\nused twice - as a value and then as a table or table-array header, or twice\ninside one inline table.",
"invalid_datetime": "\nThe value has the shape of a date or time, but one of its components is out\nof range: month 1-12, day 1 to the length of that month, hour 0-23, minute\nand second 0-59 (a second may be 60, for a leap second), and the same limits\nagain for a +hh:mm offset. February is checked against the actual year, so\n2100-02-29 is rejected - 2100 is not a leap year.",
}),
);
}
pub fn toml(parser: &mut Tabnas) -> Result<(), GrammarError> {
refs::register(parser);
register_native_matchers(parser);
let document = grammar_document()?;
let spec = GrammarSpec::from_value(document)?;
parser.grammar(&spec)?;
register_special_floats(parser)?;
Ok(())
}
fn register_native_matchers(parser: &mut Tabnas) {
parser.imperative_lex_match_ref("@bom-matcher", datematcher::bom_matcher);
parser.imperative_lex_match_ref("@isodate-match", datematcher::isodate_matcher);
parser.imperative_lex_match_ref("@localtime-match", datematcher::localtime_matcher);
}
fn register_special_floats(parser: &mut Tabnas) -> Result<(), GrammarError> {
parser
.set_options(|options| {
let definitions = &mut options.value.definitions;
definitions.clear();
for (source, value) in [
("true", Value::Bool(true)),
("false", Value::Bool(false)),
("null", Value::Null),
("nan", Value::Number(f64::NAN)),
("+nan", Value::Number(f64::NAN)),
("-nan", Value::Number(f64::NAN)),
("inf", Value::Number(f64::INFINITY)),
("+inf", Value::Number(f64::INFINITY)),
("-inf", Value::Number(f64::NEG_INFINITY)),
] {
definitions.insert(
source.to_string(),
ValueDef {
val: Some(value),
matcher: None,
transform: None,
consume: false,
},
);
}
})
.map_err(|error| GrammarError(format!("Grammar: value definitions: {error}")))?;
Ok(())
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, _options| {
toml(parser).map_err(|error| PluginError(error.0))
})
.with_defaults(Value::object(indexmap::IndexMap::new()))
}
pub fn make() -> Tabnas {
make_with(TomlOptions)
}
pub fn make_with(_options: TomlOptions) -> Tabnas {
let mut parser = tabnas_jsonic::make();
parser
.use_plugin(plugin(), None)
.expect("the toml grammar document is fixed and valid");
parser
}
pub fn parse(src: &str) -> Result<Value, TomlError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}
#[doc(hidden)]
pub fn grammar_text() -> &'static str {
GRAMMAR_TEXT
}