#![allow(clippy::result_large_err)]
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::OnceLock;
use serde_json::{json, Map, Value as Json};
use tabnas::{
Context, GrammarError, GrammarSpec, Plugin, PluginError, RuleSnapshot, RuleState, 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.19";
#[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 }
]
# A dotted key is a replace loop, as a dotted header is: each segment
# ending in a dot re-enters dive in the same frame (r), so rule depth
# stays what one segment needs however long the key, and only the value
# nests. The loop at the close takes the next dotted key without
# returning to the pair, and begins it from the table that holds both.
rule: dive: {
open: [
{
s: ['#ST #NR #ID' '#DOT']
r: dive
a: '@dive-key-dot'
}
{
s: ['#ST #NR #ID' '#CL']
p: val
u: { dive_end: true }
}
]
close: [
{
s: ['#ST #NR #ID' '#DOT']
b: 2
r: dive
}
{}
]
}
}
"#;
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: a key given a second value, a table or table-array header over a\nkey that already holds a value, a header written a second time, a header for\na table that a dotted key or an inline table had already defined, or the same\nname twice inside 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 const DEPTH_LIMIT: usize = 127;
pub const DEPTH_GUARD: &str = "depth";
fn depth(context: &Context) -> usize {
let below = context.rule_stack.last();
let current = context
.rule
.as_ref()
.map_or(0, |rule| current_levels(rule, below));
1 + levels_on_stack(context) + current
}
fn levels_on_stack(context: &Context) -> usize {
let stack = &context.rule_stack;
STACK_COUNT.with(|count| {
let mut count = count.borrow_mut();
let here = std::ptr::from_ref(context) as usize;
if count.context != here || 1 == context.iteration || context.iteration < count.iteration {
count.context = here;
count.frames.clear();
}
count.iteration = context.iteration;
let top = count.frames.len().min(stack.len());
let mut kept = top;
while kept > 0 && count.frames[kept - 1].0 != stack[kept - 1].i {
kept -= 1;
}
#[cfg(test)]
{
count.examined += (top - kept) + 1 + (stack.len() - kept);
}
count.frames.truncate(kept);
let mut levels = count.frames.last().map_or(0, |&(_, at)| at);
for position in kept..stack.len() {
let below = position.checked_sub(1).map(|under| &stack[under]);
levels += frame_levels(&stack[position], below);
count.frames.push((stack[position].i, levels));
}
levels
})
}
struct StackCount {
context: usize,
iteration: usize,
frames: Vec<(usize, usize)>,
#[cfg(test)]
examined: usize,
}
thread_local! {
static STACK_COUNT: RefCell<StackCount> = const {
RefCell::new(StackCount {
context: 0,
iteration: 0,
frames: Vec::new(),
#[cfg(test)]
examined: 0,
})
};
}
fn frame_levels(rule: &Rc<RuleSnapshot>, below: Option<&Rc<RuleSnapshot>>) -> usize {
match rule.name.as_ref() {
"map" => usize::from(below.is_none_or(|below| "table" != below.name.as_ref())),
"list" => 1,
"table" | "dive" => node::snapshot_path(Some(rule)).len(),
_ => 0,
}
}
fn current_levels(rule: &Rc<RuleSnapshot>, below: Option<&Rc<RuleSnapshot>>) -> usize {
match rule.name.as_ref() {
"table" => {
let entered = rule.n.get("table_dive").copied().unwrap_or(0);
1 + usize::try_from(entered).unwrap_or(0)
}
"dive" if RuleState::Open == rule.state => {
let previous = rule.prev_rule.as_ref();
if refs::continues_key(previous) {
node::snapshot_path(previous).len()
} else {
0
}
}
_ => frame_levels(rule, below),
}
}
fn within_depth_limit(context: &Context) -> bool {
depth(context) <= DEPTH_LIMIT
}
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)?;
parser.parse_guard(DEPTH_GUARD, within_depth_limit);
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
}
#[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: "toml-render",
source: Some(include_str!("../translate/render.alc")),
}),
transduce: Some(TranslationPart {
entry: "toml-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 std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use super::*;
fn walked(context: &Context) -> usize {
let mut levels = 1;
let mut below = None;
for rule in &context.rule_stack {
levels += frame_levels(rule, below);
below = Some(rule);
}
let current = context
.rule
.as_ref()
.map_or(0, |rule| current_levels(rule, below));
levels + current
}
fn segments(n: usize) -> String {
vec!["a"; n].join(".")
}
#[test]
fn the_kept_count_is_the_walked_count_at_every_step() {
let differences = Arc::new(Mutex::new(Vec::new()));
let steps = Arc::new(AtomicUsize::new(0));
let (seen, stepped) = (differences.clone(), steps.clone());
let mut parser = make();
parser.parse_guard(DEPTH_GUARD, move |context| {
let (kept, walked) = (depth(context), walked(context));
if kept != walked {
seen.lock().unwrap().push((context.iteration, kept, walked));
}
stepped.fetch_add(1, Ordering::Relaxed);
kept <= DEPTH_LIMIT
});
let nested = |open: &str, inner: &str, close: &str, n: usize| {
format!("{}{inner}{}", open.repeat(n), close.repeat(n))
};
let sources = [
"a = 1".to_string(),
"a = 1\nb.c = 2\nd.e.f = 3".to_string(),
"a.b = 1\nc.d = 2".to_string(),
"[a.b]\nc = 1\n[[d.e]]\nf = {g = [1, {h.i = 2}]}\n[[d.e]]\nj.k = 3".to_string(),
"[[a]]\n[[a.b]]\n[[a.b.c]]\nx = 1".to_string(),
"k.k = {p.q = 1\nr.s = {t.u = 2\nv.w = 3}}".to_string(),
"x = [{p.q = 1\na.b.c = 2}, [[3]]]".to_string(),
"a = \"unterminated".to_string(),
"a = 1\n[a]".to_string(),
"a = ]".to_string(),
format!("{} = 1", segments(127)),
format!("{} = 1", segments(128)),
format!("[{}]\nx = 1", segments(127)),
format!("x = {}", nested("[", "", "]", 127)),
format!("x = {}", nested("{a = ", "1", "}", 130)),
format!("{} = {{p.q = 1\n{} = 1}}", segments(100), segments(28)),
nested(&format!("{} = {{p.q = 1\n", segments(25)), "z = 1", "}", 6),
];
for source in sources.iter().chain(sources.iter()) {
let _ = parser.parse(source);
}
let steps = steps.load(Ordering::Relaxed);
assert!(steps > 3_000, "{steps} steps");
assert_eq!(*differences.lock().unwrap(), Vec::new());
}
#[test]
fn a_step_counts_what_changed_not_the_whole_stack() {
let steps = Arc::new(AtomicUsize::new(0));
let walk = Arc::new(AtomicUsize::new(0));
let (stepped, walked) = (steps.clone(), walk.clone());
let mut parser = make();
parser.parse_guard(DEPTH_GUARD, move |context| {
stepped.fetch_add(1, Ordering::Relaxed);
walked.fetch_add(context.rule_stack.len(), Ordering::Relaxed);
within_depth_limit(context)
});
let levels = 120;
let src = format!("x = {}1{}", "[".repeat(levels), "]".repeat(levels));
let examined = || STACK_COUNT.with(|count| count.borrow().examined);
let before = examined();
parser.parse(&src).expect("parses");
let work = examined() - before;
let steps = steps.load(Ordering::Relaxed);
let walk = walk.load(Ordering::Relaxed);
assert!(steps > 2 * levels, "{steps} steps");
assert!(
walk > levels / 2 * steps,
"a shallow stack: {walk} frames in {steps} steps"
);
assert!(
work <= 3 * steps,
"{work} frames looked at in {steps} steps"
);
}
}