#![allow(clippy::result_large_err)]
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use indexmap::IndexMap;
use serde_json::json;
use tabnas::{
ActionError, AltSpec, Context, GrammarError, GrammarSpec, ImperativeLexMatcher, LexCheckResult,
Lexer, Options, Plugin, PluginError, Rule, RuleState, Tabnas, Token, Value,
};
use tabnas_hoover::{
hoover, Block, Consume, EndSpec, HooverOptions, HooverRuleFilter, HooverRuleSpec, StartSpec,
};
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub const VERSION: &str = "0.5.23";
pub use tabnas::TabnasError as IniError;
const GRAMMAR_TEXT: &str = r#"
# INI Grammar Definition
# Parsed by a standard Jsonic instance and passed to jsonic.grammar()
# Function references (@ prefixed) are resolved against the refs map
{
options: rule: { start: ini exclude: jsonic }
options: lex: { emptyResult: {} }
options: fixed: token: { '#EQ': '=' '#DOT': '.' '#OB': null '#CB': null '#CL': null }
options: line: { check: '@line-check' }
options: number: { lex: false }
options: string: { lex: true chars: QUOTE_CHARS abandon: true }
options: text: { lex: false }
# Declared error codes. The CODE is the cross-runtime contract; the message
# text is not (see AGENTS.md). Both runtimes read this one block, so the two
# catalogues cannot drift. Keys stay alphabetical: admin's descriptor
# generator compares the TS and Go extractions and sorts only one side.
options: error: {
duplicate_section: 'duplicate section header: [{section}]'
unterminated_section: 'unterminated section header: [{src}'
}
# A hint for each declared code, keyed alike. Without one the engine falls
# back to its hint for an UNKNOWN code, which tells the reader the error is
# probably a bug in jsonic or a plugin -- wrong for both of these.
options: hint: {
duplicate_section: 'The section [{section}] is declared more than once, and the\nsection.duplicate option is error. Combine the two sections, or set\nsection.duplicate to merge or override to allow a repeated header.'
unterminated_section: 'A section header must be closed with ] on the same line, as in\n[name] or [a.b].'
}
options: comment: def: {
hash: { eatline: true }
slash: null
multi: null
semi: { line: true start: ';' lex: true eatline: true }
}
rule: ini: open: [
{ s: '#OS' p: table b: 1 }
{ s: ['#HK #ST #VL' '#EQ'] p: table b: 2 }
{ s: ['#HV' '#OS'] p: table b: 2 }
{ s: ['#HK #ST #VL'] p: table b: 1 }
{ s: '#ZZ' }
]
rule: table: open: [
# Raised when the table's own before-open handler saw a section path it
# had already declared and section.duplicate is 'error'. It flags the
# rule rather than raising there, because a state action cannot raise a
# coded error in both runtimes: TS can return a bad token from bo, Go
# discards the return value, and a ctx error set in bo is overwritten by
# alternate matching. An error ALTERNATE is the path both runtimes share.
{ c: '@is-duplicate-section' e: '@duplicate-section' }
{ s: '#OS' p: dive }
{ s: ['#HK #ST #VL' '#EQ'] p: map b: 2 }
{ s: ['#HV' '#OS'] p: map b: 2 }
{ s: ['#HK #ST #VL'] p: map b: 1 }
{ s: '#CS' p: map }
{ s: '#ZZ' }
]
rule: table: close: [
{ s: '#OS' r: table b: 1 g: end }
{ s: '#CS' r: table a: '@table-close-dive' g: close }
{ s: '#ZZ' g: end }
]
rule: dive: open: [
{ s: ['#DK' '#DOT'] a: '@dive-push' p: dive }
{ s: '#DK' a: '@dive-push' }
# The root header, []: the closing bracket where the first segment is
# due. It names no section, so the dive records no path, and the table
# that follows writes into the root again, wherever the document is.
# Only the first segment's place takes it (the dive the table pushed):
# after a dot, as in [a.], the bracket is still unexpected.
{ s: '#CS' c: '@is-table-parent' b: 1 }
]
rule: dive: close: [
{ s: '#CS' b: 1 g: close }
# A section header lives on one line, so anything other than the closing
# bracket here means the header was never closed. Unconditional (no s
# key), so it matches only after the '#CS' alternate above has been
# tried, and raises unterminated_section rather than the engine's
# generic 'unexpected'.
{ e: '@dive-unterminated' }
]
rule: map: open: {
alts: [
{ s: ['#HK #ST #VL' '#EQ'] c: '@is-table-parent' p: pair b: 2 }
{ s: ['#HK #ST #VL'] c: '@is-table-parent' p: pair b: 1 }
]
inject: { append: true }
}
rule: map: close: [
{ s: '#OS' b: 1 g: end }
{ s: '#ZZ' g: end }
]
rule: pair: open: [
{ s: ['#HK #ST #VL' '#EQ'] c: '@is-table-grandparent' p: val a: '@pair-key-eq' }
{ s: ['#HK #ST #VL'] c: '@is-table-grandparent' a: '@pair-key-bool' }
]
rule: pair: close: [
{ s: ['#HK #ST #VL' '#CL'] c: '@is-table-grandparent' e: '@pair-close-err' }
{ s: ['#HK #ST #VL'] b: 1 r: pair g: comma }
{ s: '#OS' b: 1 g: end }
]
}
"#;
const QUOTE_CHARS: &str = "'\"";
const HOOVER_ORDER: f64 = 8.5e6;
const MULTILINE_ORDER: f64 = 8.4e6;
const PROBE_ORDER: f64 = 0.5e6;
const PROBE_REF: &str = "@ini-inval-probe";
const MULTILINE_REF: &str = "@ini-multiline";
const LINE_CHECK_REF: &str = "@line-check";
const COMMENT_CHECK_REF: &str = "@ini-comment-check";
const TEXT_CHECK_REF: &str = "@ini-text-check";
const STRING_CHECK_REF: &str = "@ini-string-check";
pub const PLUGIN_NAME: &str = "ini";
pub const DEPTH_LIMIT: usize = 127;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Duplicate {
#[default]
Merge,
Override,
Error,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MultilineOptions {
pub continuation: Option<String>,
pub indent: Option<bool>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SectionOptions {
pub duplicate: Duplicate,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CommentOptions {
pub inline: Option<InlineCommentOptions>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InlineCommentOptions {
pub active: Option<bool>,
pub chars: Option<Vec<String>>,
pub escape: Option<InlineEscapeOptions>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InlineEscapeOptions {
pub backslash: Option<bool>,
pub whitespace: Option<bool>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct IniOptions {
pub multiline: Option<MultilineOptions>,
pub section: Option<SectionOptions>,
pub comment: Option<CommentOptions>,
}
impl IniOptions {
pub fn new() -> Self {
Self::default()
}
pub fn with_multiline(mut self) -> Self {
self.multiline = Some(MultilineOptions::default());
self
}
pub fn with_inline_comments(mut self) -> Self {
let inline = self
.comment
.get_or_insert_with(CommentOptions::default)
.inline
.get_or_insert_with(InlineCommentOptions::default);
inline.active = Some(true);
self
}
pub fn with_duplicate(mut self, duplicate: Duplicate) -> Self {
self.section = Some(SectionOptions { duplicate });
self
}
}
#[derive(Clone, Debug)]
struct Resolved {
multiline: bool,
continuation: Option<char>,
indent: bool,
dup_section: Duplicate,
inline_active: bool,
inline_chars: Vec<char>,
inline_char_str: Vec<String>,
esc_backslash: bool,
esc_whitespace: bool,
}
impl Resolved {
fn is_inline_char(&self, c: char) -> bool {
self.inline_chars.contains(&c)
}
}
fn one_code_unit(text: &str) -> Option<char> {
let mut characters = text.chars();
let first = characters.next()?;
(characters.next().is_none() && first.len_utf16() == 1).then_some(first)
}
fn resolve(options: &IniOptions) -> Resolved {
let mut resolved = Resolved {
multiline: false,
continuation: None,
indent: false,
dup_section: Duplicate::Merge,
inline_active: false,
inline_chars: vec!['#', ';'],
inline_char_str: vec!["#".to_string(), ";".to_string()],
esc_backslash: true,
esc_whitespace: false,
};
if let Some(multiline) = &options.multiline {
resolved.multiline = true;
resolved.continuation = match multiline.continuation.as_deref() {
None => Some('\\'),
Some(text) => one_code_unit(text),
};
resolved.indent = multiline.indent.unwrap_or(false);
}
if let Some(section) = &options.section {
resolved.dup_section = section.duplicate;
}
if let Some(inline) = options.comment.as_ref().and_then(|c| c.inline.as_ref()) {
resolved.inline_active = inline.active.unwrap_or(false);
if let Some(chars) = inline.chars.as_ref() {
resolved.inline_char_str = chars.clone();
resolved.inline_chars = chars
.iter()
.filter_map(|text| one_code_unit(text))
.collect();
}
if let Some(escape) = &inline.escape {
resolved.esc_backslash = escape.backslash.unwrap_or(true);
resolved.esc_whitespace = escape.whitespace.unwrap_or(false);
}
}
resolved
}
thread_local! {
static IN_VAL: Cell<bool> = const { Cell::new(false) };
static IN_VALUE: Cell<bool> = const { Cell::new(false) };
}
fn in_val_rule(rule: &Rule) -> bool {
rule.name.as_str() == "val"
}
fn in_value_position(rule: &Rule) -> bool {
in_val_rule(rule)
&& rule.state == RuleState::Open
&& rule.parent_rule.as_ref().is_some_and(|parent| {
let name = parent.name.as_str();
name == "pair" || name == "elem"
})
}
#[derive(Debug, Default)]
struct StringCheckConfig {
quotes: Vec<char>,
escape_char: char,
}
fn set_node(rule: &mut Rule, value: Value) {
rule.node = Rc::new(RefCell::new(value));
}
fn js_string(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Text(text) => text.string.clone(),
Value::Undefined => "undefined".to_string(),
Value::Null => "null".to_string(),
Value::Bool(flag) => flag.to_string(),
Value::Number(number) => js_number_to_string(*number),
Value::Array(items) => js_array_string(items),
_ => "[object Object]".to_string(),
}
}
fn js_array_string(items: &[Value]) -> String {
let mut joined = String::new();
for (index, item) in items.iter().enumerate() {
if 0 < index {
joined.push(',');
}
match item {
Value::Null | Value::Undefined => {}
other => joined.push_str(&js_string(other)),
}
}
joined
}
fn js_number_to_string(number: f64) -> String {
if number.is_nan() {
return "NaN".to_string();
}
if number == 0.0 {
return "0".to_string();
}
if number < 0.0 {
return format!("-{}", js_number_to_string(-number));
}
if number.is_infinite() {
return "Infinity".to_string();
}
let shortest = format!("{number:e}");
let shortest_k = shortest
.split_once('e')
.map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
.expect("a finite f64 always formats with an exponent");
let exponential = format!("{:.*e}", shortest_k - 1, number);
let (mantissa, exponent) = exponential
.split_once('e')
.expect("a finite f64 always formats with an exponent");
let digits = mantissa
.chars()
.filter(|digit| *digit != '.')
.collect::<String>();
let digits = digits.trim_end_matches('0');
let digits = if digits.is_empty() { "0" } else { digits };
let k = digits.len() as i32;
let n = exponent
.parse::<i32>()
.expect("a formatted exponent is an integer")
+ 1;
if (k..=21).contains(&n) {
let mut text = digits.to_string();
text.push_str(&"0".repeat((n - k) as usize));
text
} else if (1..=21).contains(&n) {
let point = n as usize;
format!("{}.{}", &digits[..point], &digits[point..])
} else if (-5..=0).contains(&n) {
format!("0.{}{}", "0".repeat(-n as usize), digits)
} else {
let sign = if n - 1 < 0 { '-' } else { '+' };
let power = (n - 1).abs();
if k == 1 {
format!("{digits}e{sign}{power}")
} else {
format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
}
}
}
fn object_get(value: &Value, key: &str) -> Option<Value> {
match value {
Value::Object(entries) => entries.get(key).cloned(),
Value::MapRef(map) => map.value.get(key).cloned(),
_ => None,
}
}
fn object_insert(value: &mut Value, key: String, entry: Value) {
match value {
Value::Object(entries) => {
Arc::make_mut(entries).insert(key, entry);
}
Value::MapRef(map) => {
Arc::make_mut(map).value.insert(key, entry);
}
_ => {
let mut entries = IndexMap::new();
entries.insert(key, entry);
*value = Value::object(entries);
}
}
}
fn object_take(node: &mut Value, key: &str) -> Option<Value> {
match node {
Value::Object(entries) => Arc::make_mut(entries)
.get_mut(key)
.map(|slot| std::mem::replace(slot, Value::Undefined)),
Value::MapRef(map) => Arc::make_mut(map)
.value
.get_mut(key)
.map(|slot| std::mem::replace(slot, Value::Undefined)),
_ => None,
}
}
fn is_object(value: &Value) -> bool {
matches!(value, Value::Object(_) | Value::MapRef(_))
}
fn empty_object() -> Value {
Value::object(IndexMap::new())
}
fn token_string(token: &Token) -> String {
if token.is_no_token() {
return String::new();
}
match &token.val {
Value::String(text) => text.clone(),
Value::Text(text) => text.string.clone(),
Value::Undefined => token.src.as_str().to_string(),
other => js_string(other),
}
}
fn bool_key(token: &Token) -> Option<String> {
if let Some(name) = array_key_name(token) {
return Some(format!("{name}[]"));
}
match &token.val {
Value::String(text) if !text.is_empty() => Some(text.clone()),
Value::Text(text) if !text.string.is_empty() => Some(text.string.clone()),
_ => None,
}
}
fn alt_err_token(rule: &Rule, context: &Context) -> Option<Token> {
if rule.os() > 0 {
if let Some(token) = rule.o0().filter(|token| !token.is_no_token()) {
return Some(token.clone());
}
}
context.t0().cloned().or_else(|| Some(Token::no_token()))
}
fn dive_of(bag: Option<&Value>) -> Option<Vec<String>> {
match bag? {
Value::Array(items) => Some(items.iter().map(js_string).collect()),
_ => None,
}
}
fn dive_value(dive: &[String]) -> Value {
Value::array(dive.iter().cloned().map(Value::String).collect())
}
fn integralize(value: &mut serde_json::Value) {
match value {
serde_json::Value::Number(number) => {
if let Some(float) = number.as_f64() {
if float.fract() == 0.0 && float.abs() < 9.007_199_254_740_992e15 {
*value = serde_json::Value::from(float as i64);
}
}
}
serde_json::Value::Array(items) => items.iter_mut().for_each(integralize),
serde_json::Value::Object(entries) => {
entries.values_mut().for_each(integralize);
}
_ => {}
}
}
fn grammar_document(resolved: &Resolved) -> Result<serde_json::Value, GrammarError> {
static PARSED: OnceLock<Result<serde_json::Value, String>> = OnceLock::new();
let parsed = PARSED
.get_or_init(|| {
tabnas_jsonic::make()
.parse(GRAMMAR_TEXT)
.map(|value| value.to_json())
.map_err(|error| error.to_string())
})
.clone()
.map_err(GrammarError)?;
let mut document = parsed;
integralize(&mut document);
let options = document
.get_mut("options")
.and_then(serde_json::Value::as_object_mut)
.ok_or_else(|| GrammarError("tabnas-ini: the grammar has no `options` table".into()))?;
options
.entry("string")
.or_insert_with(|| json!({}))
.as_object_mut()
.ok_or_else(|| GrammarError("tabnas-ini: options.string must be a table".into()))?
.insert("chars".into(), json!(QUOTE_CHARS));
for (family, reference) in [
("comment", COMMENT_CHECK_REF),
("text", TEXT_CHECK_REF),
("string", STRING_CHECK_REF),
] {
options
.entry(family)
.or_insert_with(|| json!({}))
.as_object_mut()
.ok_or_else(|| GrammarError(format!("tabnas-ini: options.{family} must be a table")))?
.insert("check".into(), json!(reference));
}
let mut matchers = json!({
"iniprobe": { "order": PROBE_ORDER, "make": PROBE_REF },
});
if resolved.multiline || (resolved.inline_active && resolved.esc_whitespace) {
matchers.as_object_mut().expect("a literal object").insert(
"multiline".into(),
json!({ "order": MULTILINE_ORDER, "make": MULTILINE_REF }),
);
}
options
.entry("lex")
.or_insert_with(|| json!({}))
.as_object_mut()
.ok_or_else(|| GrammarError("tabnas-ini: options.lex must be a table".into()))?
.insert("match".into(), matchers);
Ok(document)
}
pub fn ini(parser: &mut Tabnas, options: &IniOptions) -> Result<(), IniPluginError> {
let resolved = Arc::new(resolve(options));
if !parser.rule_names().iter().any(|name| name == "val") {
return Err(IniPluginError(
"tabnas-ini: the jsonic grammar must be installed first: call \
tabnas_jsonic::jsonic(&mut parser) before tabnas_ini::ini(..), or use make()"
.into(),
));
}
let string_config = register_lex_hooks(parser, &resolved);
register_multiline(parser, &resolved);
install_hoover(parser, &resolved)?;
register_refs(parser, &resolved);
let document = grammar_document(&resolved)?;
let spec = GrammarSpec::from_value(document)?;
parser.grammar(&spec)?;
let config = parser.config();
let _ = string_config.set(StringCheckConfig {
quotes: config.string.chars.chars().collect(),
escape_char: config.string.escape_char,
});
install_val_rule(parser, &resolved);
parser.parse_guard(DEPTH_GUARD, within_depth_limit);
for name in ["list", "elem"] {
parser.remove_rule(name);
}
Ok(())
}
pub fn plugin(options: IniOptions) -> Plugin {
Plugin::new(PLUGIN_NAME, move |parser, _bag| {
ini(parser, &options).map_err(|error| PluginError(error.0))
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IniPluginError(pub String);
impl std::fmt::Display for IniPluginError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.0)
}
}
impl std::error::Error for IniPluginError {}
impl From<GrammarError> for IniPluginError {
fn from(error: GrammarError) -> Self {
IniPluginError(error.0)
}
}
impl From<PluginError> for IniPluginError {
fn from(error: PluginError) -> Self {
IniPluginError(error.0)
}
}
impl From<tabnas_hoover::HooverError> for IniPluginError {
fn from(error: tabnas_hoover::HooverError) -> Self {
IniPluginError(error.0)
}
}
pub fn make() -> Tabnas {
make_with(&IniOptions::default())
}
pub fn make_with(options: &IniOptions) -> Tabnas {
let mut parser = tabnas_jsonic::make();
parser
.use_plugin(plugin(options.clone()), None)
.expect("the INI grammar document is fixed, and the jsonic base is installed");
parser
.set_options(|options| options.lex.window = true)
.expect("lex.window sets");
parser
}
pub fn parse(src: &str) -> Result<Value, IniError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}
pub fn parse_with(src: &str, options: &IniOptions) -> Result<Value, IniError> {
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: "ini-render",
source: Some(include_str!("../translate/render.alc")),
}),
transduce: Some(TranslationPart {
entry: "ini-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 => "",
}
}
fn register_lex_hooks(
parser: &mut Tabnas,
resolved: &Resolved,
) -> Arc<OnceLock<StringCheckConfig>> {
parser.imperative_lex_match_ref(PROBE_REF, |_lexer, rule, _context| {
IN_VAL.with(|flag| flag.set(in_val_rule(rule)));
IN_VALUE.with(|flag| flag.set(in_value_position(rule)));
None
});
parser.imperative_lex_check_ref(LINE_CHECK_REF, |_lexer| {
if IN_VAL.with(Cell::get) {
LexCheckResult::Skip
} else {
LexCheckResult::Continue
}
});
parser.imperative_lex_check_ref(COMMENT_CHECK_REF, |_lexer| {
if IN_VALUE.with(Cell::get) {
LexCheckResult::Skip
} else {
LexCheckResult::Continue
}
});
parser.imperative_lex_check_ref(TEXT_CHECK_REF, |_lexer| {
if IN_VALUE.with(Cell::get) {
LexCheckResult::Skip
} else {
LexCheckResult::Continue
}
});
let config: Arc<OnceLock<StringCheckConfig>> = Arc::new(OnceLock::new());
let for_check = Arc::clone(&config);
let inline = Arc::new(resolved.clone());
parser.imperative_lex_check_ref(STRING_CHECK_REF, move |lexer: &mut Lexer<'_>| {
let Some(string_config) = for_check.get() else {
return LexCheckResult::Continue;
};
if !IN_VALUE.with(Cell::get) {
return LexCheckResult::Continue;
}
if string_quote_wraps_value(lexer, string_config, &inline) {
LexCheckResult::Continue
} else {
LexCheckResult::Skip
}
});
config
}
fn string_quote_wraps_value(
lexer: &mut Lexer<'_>,
config: &StringCheckConfig,
resolved: &Resolved,
) -> bool {
let mut exhausted = !lexer.windowed();
loop {
let rest = lexer.window();
if let Some(answer) = quote_wraps_value(rest, config, resolved, exhausted) {
return answer;
}
let ahead = rest.len();
let read = rest.chars().count();
lexer.fill(read.saturating_mul(2).max(read + 1));
if lexer.window().len() <= ahead {
exhausted = true;
}
}
}
fn quote_wraps_value(
remaining: &str,
config: &StringCheckConfig,
resolved: &Resolved,
exhausted: bool,
) -> Option<bool> {
let mut characters = remaining.chars();
let Some(quote) = characters.next() else {
return if exhausted { Some(true) } else { None };
};
if !config.quotes.contains("e) {
return Some(true);
}
let after_quote = loop {
let Some(character) = characters.next() else {
return if exhausted { Some(true) } else { None };
};
if character == config.escape_char {
characters.next();
continue;
}
if character == quote {
break characters.as_str();
}
if character == '\n' {
return Some(true);
}
};
let tail = after_quote.trim_start_matches([' ', '\t']);
let spaced = tail.len() < after_quote.len();
let next = tail.chars().next();
if !exhausted && (tail.is_empty() || "\r" == tail) {
return None;
}
let at_line_end = match next {
None | Some('\n') => true,
Some('\r') => tail.starts_with("\r\n"),
_ => false,
};
let at_inline_comment = resolved.inline_active
&& next.is_some_and(|character| resolved.is_inline_char(character))
&& (!resolved.esc_whitespace || spaced);
Some(at_line_end || at_inline_comment)
}
fn install_hoover(parser: &mut Tabnas, resolved: &Resolved) -> Result<(), IniPluginError> {
let inline_in_fixed = resolved.inline_active && !resolved.esc_whitespace;
let mut eol_end: Vec<String> = vec!["\n".into(), "\r\n".into()];
if inline_in_fixed {
eol_end.extend(resolved.inline_char_str.iter().cloned());
}
eol_end.push(String::new());
let mut key_end: Vec<String> = vec!["=".into(), "\n".into(), "\r\n".into()];
if inline_in_fixed {
key_end.extend(resolved.inline_char_str.iter().cloned());
}
key_end.push(String::new());
let mut eol_escape: HashMap<String, String> = HashMap::new();
eol_escape.insert("\\".into(), "\\".into());
let mut key_escape = eol_escape.clone();
if resolved.inline_active && resolved.esc_backslash {
for ch in &resolved.inline_char_str {
eol_escape.insert(ch.clone(), ch.clone());
key_escape.insert(ch.clone(), ch.clone());
}
}
let endofline = Block {
name: "endofline".into(),
start: Some(StartSpec {
fixed: None,
consume: Consume::All,
rule: Some(HooverRuleSpec {
parent: Some(HooverRuleFilter::include(&["pair", "elem"])),
..Default::default()
}),
}),
end: EndSpec {
fixed: eol_end,
consume: Consume::Only(vec!["\n".into(), "\r\n".into()]),
},
token: None,
escape_char: Some('\\'),
escape: eol_escape,
allow_unknown_escape: Some(true),
preserve_escape_char: true,
trim: true,
};
let key = Block {
name: "key".into(),
start: Some(StartSpec {
fixed: None,
consume: Consume::All,
rule: Some(HooverRuleSpec {
current: Some(HooverRuleFilter::exclude(&["dive"])),
state: Some("oc".into()),
..Default::default()
}),
}),
end: EndSpec {
fixed: key_end,
consume: Consume::Never,
},
token: Some("#HK".into()),
escape_char: None,
escape: key_escape,
allow_unknown_escape: None,
preserve_escape_char: false,
trim: true,
};
let divekey = Block {
name: "divekey".into(),
start: Some(StartSpec {
fixed: None,
consume: Consume::All,
rule: Some(HooverRuleSpec {
current: Some(HooverRuleFilter::include(&["dive"])),
..Default::default()
}),
}),
end: EndSpec {
fixed: vec![
"]".into(),
".".into(),
"\n".into(),
"\r\n".into(),
String::new(),
],
consume: Consume::Never,
},
token: Some("#DK".into()),
escape_char: Some('\\'),
escape: HashMap::from([
("]".to_string(), "]".to_string()),
(".".to_string(), ".".to_string()),
("\\".to_string(), "\\".to_string()),
]),
allow_unknown_escape: Some(true),
preserve_escape_char: true,
trim: true,
};
hoover(
parser,
HooverOptions::new(vec![endofline, key, divekey]).with_lex_order(HOOVER_ORDER),
)?;
Ok(())
}
const DECLARED: &str = "ini_declared";
fn declared_clear(context: &mut Context) {
context.u.insert(DECLARED.to_string(), empty_object());
}
fn declared_has(context: &Context, key: &str) -> bool {
match context.u.get(DECLARED) {
Some(Value::Object(entries)) => entries.contains_key(key),
_ => false,
}
}
fn declared_add(context: &mut Context, key: String) {
let mut set = context
.u
.insert(DECLARED.to_string(), Value::Undefined)
.filter(is_object)
.unwrap_or_else(empty_object);
object_insert(&mut set, key, Value::Bool(true));
context.u.insert(DECLARED.to_string(), set);
}
fn open_section(root: &mut Value, dive: &[String], override_last: bool) -> Value {
if !is_object(root) {
*root = empty_object();
}
let mut levels: Vec<Value> = Vec::with_capacity(dive.len() + 1);
levels.push(std::mem::replace(root, Value::Undefined));
for (index, key) in dive.iter().enumerate() {
let last = index + 1 == dive.len();
let parent = levels.last_mut().expect("a level is always on the stack");
let child = match object_take(parent, key) {
Some(value) if is_object(&value) && !(last && override_last) => value,
_ => empty_object(),
};
levels.push(child);
}
let mut current = levels.pop().expect("one level per segment plus the root");
let section = current.clone();
for key in dive.iter().rev() {
let mut parent = levels.pop().expect("one level per segment plus the root");
object_insert(&mut parent, key.clone(), current);
current = parent;
}
*root = current;
section
}
fn close_section(root: &mut Value, dive: &[String], section: Value) {
if dive.is_empty() {
return;
}
if !is_object(root) {
*root = empty_object();
}
let mut levels: Vec<Value> = Vec::with_capacity(dive.len());
levels.push(std::mem::replace(root, Value::Undefined));
for key in &dive[..dive.len() - 1] {
let parent = levels.last_mut().expect("a level is always on the stack");
let child = match object_take(parent, key) {
Some(value) if is_object(&value) => value,
_ => empty_object(),
};
levels.push(child);
}
let mut current = section;
for key in dive.iter().rev() {
let mut parent = levels.pop().expect("one level per segment");
object_insert(&mut parent, key.clone(), current);
current = parent;
}
*root = current;
}
fn depth(context: &Context) -> usize {
let is_level = |name: &str| name == "map" || name == "list" || name == "dive";
let ancestors = context
.rule_stack
.iter()
.filter(|rule| is_level(&rule.name))
.count();
let current = usize::from(
context
.rule
.as_ref()
.is_some_and(|rule| is_level(&rule.name)),
);
ancestors + current
}
fn within_depth_limit(context: &Context) -> bool {
depth(context) <= DEPTH_LIMIT
}
const DEPTH_GUARD: &str = "depth";
const INI_PATH: &str = "ini_path";
fn register_refs(parser: &mut Tabnas, resolved: &Resolved) {
parser.state_action_ref("@ini-bo", |rule, context| {
set_node(rule, empty_object());
declared_clear(context);
Ok(())
});
let for_table_bo = Arc::new(resolved.clone());
parser.state_action_ref("@table-bo", move |rule, context| {
table_before_open(rule, context, &for_table_bo)
});
parser.state_action_ref("@table-bc", table_before_close);
parser.state_action_ref("@dive-bc", |rule, _context| {
if let Some(dive) = rule
.child_rule
.as_ref()
.and_then(|child| dive_of(child.u.get("dive")))
{
rule.u_mut().insert("dive".into(), dive_value(&dive));
}
Ok(())
});
parser.action_with_context("@table-close-dive", |rule, _context| {
if let Some(dive) = rule
.child_rule
.as_ref()
.and_then(|child| dive_of(child.u.get("dive")))
{
rule.u_mut().insert("dive".into(), dive_value(&dive));
}
Ok(())
});
parser.action_with_context("@dive-push", |rule, _context| {
let mut dive = rule
.parent_rule
.as_ref()
.and_then(|parent| dive_of(parent.u.get("dive")))
.unwrap_or_default();
if let Some(existing) = dive_of(rule.u.get("dive")) {
dive = existing;
}
let segment = rule.o0().map(token_string).unwrap_or_default();
dive.push(segment);
rule.u_mut().insert("dive".into(), dive_value(&dive));
Ok(())
});
parser.action_with_context("@pair-key-eq", pair_key_eq);
parser.subscribe_lex(mark_array_key);
parser.action_with_context("@pair-key-bool", |rule, _context| {
let Some(key) = rule.o0().and_then(bool_key) else {
return Ok(());
};
if let Some(parent) = rule
.parent_rule
.as_ref()
.map(|parent| Rc::clone(&parent.node))
{
object_insert(&mut parent.borrow_mut(), key, Value::Bool(true));
}
Ok(())
});
parser.action_with_context("@val-empty", |rule, _context| {
set_node(rule, Value::String(String::new()));
Ok(())
});
parser.alt_condition("@is-table-parent", |rule, _context| {
rule.parent_rule
.as_ref()
.is_some_and(|parent| parent.name.as_str() == "table")
});
parser.alt_condition("@is-table-grandparent", |rule, _context| {
rule.parent_rule
.as_ref()
.and_then(|parent| parent.parent_rule.clone())
.is_some_and(|grandparent| grandparent.name.as_str() == "table")
});
parser.alt_condition("@is-duplicate-section", |rule, _context| {
rule.u.contains_key("dupsec")
});
parser.alt_error("@duplicate-section", |rule, context| {
let mut token = alt_err_token(rule, context)?;
let section = match rule.u.get("dupsec") {
Some(Value::String(path)) => path.clone(),
_ => String::new(),
};
token.bad_with_details(
"duplicate_section",
[("section".to_string(), Value::String(section))],
);
Some(token)
});
parser.alt_error("@dive-unterminated", |rule, context| {
let mut token = alt_err_token(rule, context)?;
token.bad("unterminated_section");
Some(token)
});
parser.alt_error("@pair-close-err", |rule, _context| rule.c1().cloned());
}
fn table_before_open(
rule: &mut Rule,
context: &mut Context,
resolved: &Resolved,
) -> Result<(), ActionError> {
let Some(root) = rule
.parent_rule
.as_ref()
.map(|parent| Rc::clone(&parent.node))
else {
return Ok(());
};
rule.node = Rc::clone(&root);
let Some(dive) = rule
.prev_rule
.as_ref()
.and_then(|prev| dive_of(prev.u.get("dive")))
.filter(|dive| !dive.is_empty())
else {
return Ok(());
};
let section_key = dive.join("\u{0}");
let is_duplicate = declared_has(context, §ion_key);
if is_duplicate && resolved.dup_section == Duplicate::Error {
rule.u_mut()
.insert("dupsec".into(), Value::String(dive.join(".")));
return Ok(());
}
let override_last = is_duplicate && resolved.dup_section == Duplicate::Override;
let section = open_section(&mut root.borrow_mut(), &dive, override_last);
rule.u_mut().insert(INI_PATH.into(), dive_value(&dive));
set_node(rule, section);
declared_add(context, section_key);
Ok(())
}
fn table_before_close(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
let child_is_self = rule
.child_rule
.as_ref()
.is_some_and(|child| Rc::ptr_eq(&child.node, &rule.node));
if child_is_self {
rule.child_node = Value::Undefined;
} else if let Value::Object(entries) = rule.child_node.clone() {
let mut node = rule.node.borrow_mut();
if is_object(&node) {
for (key, value) in entries.iter() {
object_insert(&mut node, key.clone(), value.clone());
}
}
}
let Some(dive) = dive_of(rule.u.get(INI_PATH)) else {
return Ok(());
};
let Some(root) = rule
.parent_rule
.as_ref()
.map(|parent| Rc::clone(&parent.node))
else {
return Ok(());
};
let section = rule.node.borrow().clone();
close_section(&mut root.borrow_mut(), &dive, section);
Ok(())
}
fn mark_array_key(token: &mut Token, rule: &mut Rule, _context: &mut Context) {
if rule.name.as_str() == "val" && rule.state == RuleState::Open {
return;
}
let name = token.name.as_str();
if name != "#HK" && name != "#ST" {
return;
}
let text = match &token.val {
Value::String(text) => text.as_str(),
Value::Text(text) => text.string.as_str(),
_ => return,
};
if text.len() > 2 && text.ends_with("[]") {
let stripped = text[..text.len() - 2].to_string();
token.val = Value::array(vec![Value::String(stripped)]);
}
}
fn array_key_name(token: &Token) -> Option<String> {
match &token.val {
Value::Array(items) if items.len() == 1 => match &items[0] {
Value::String(name) => Some(name.clone()),
_ => None,
},
_ => None,
}
}
fn key_of(token: &Token) -> (String, bool) {
match array_key_name(token) {
Some(name) => (name, true),
None => (token_string(token), false),
}
}
fn pair_key_eq(rule: &mut Rule, _context: &mut Context) -> Result<(), ActionError> {
let (key, array_key) = rule.o0().map(key_of).unwrap_or_default();
if array_key {
let spelt = format!("{key}[]");
if matches!(
object_get(&rule.node.borrow(), &spelt),
Some(Value::Array(_))
) {
rule.u_mut().insert("key".into(), Value::String(spelt));
rule.u_mut().insert("ini_array".into(), Value::Bool(true));
return Ok(());
}
}
let existing = object_get(&rule.node.borrow(), &key);
if matches!(existing, Some(Value::Array(_))) {
rule.u_mut().insert("key".into(), Value::String(key));
rule.u_mut().insert("ini_array".into(), Value::Bool(true));
return Ok(());
}
if array_key {
let array = match existing {
Some(value) if !value.is_undefined() => Value::array(vec![value]),
_ => Value::array(Vec::new()),
};
object_insert(&mut rule.node.borrow_mut(), key.clone(), array);
rule.u_mut().insert("key".into(), Value::String(key));
rule.u_mut().insert("ini_array".into(), Value::Bool(true));
return Ok(());
}
rule.u_mut().insert("key".into(), Value::String(key));
rule.u_mut().insert("pair".into(), Value::Bool(true));
Ok(())
}
fn is_json_list_alt(alt: &AltSpec) -> bool {
let mut tags: Vec<&str> = alt
.g
.split(',')
.map(str::trim)
.filter(|tag| !tag.is_empty())
.collect();
tags.sort_unstable();
tags == ["json", "list"]
}
fn install_val_rule(parser: &mut Tabnas, _resolved: &Resolved) {
let os = parser.token("#OS");
let cs = parser.token("#CS");
let eq = parser.token("#EQ");
let dot = parser.token("#DOT");
let zz = parser.token("#ZZ");
let st = parser.token("#ST");
parser.define_rule("val", move |spec| {
spec.add_bo(|rule, _context| set_node(rule, Value::Undefined));
let kept: Vec<AltSpec> = std::mem::take(&mut spec.open)
.into_iter()
.filter(|alt| !is_json_list_alt(alt))
.collect();
let mut open = vec![
AltSpec {
s: vec![vec![os, cs, eq, dot]],
r: Some("val".to_string()),
u: HashMap::from([("ini_prev".to_string(), Value::Bool(true))]),
..Default::default()
},
AltSpec {
s: vec![vec![zz]],
a: vec!["@val-empty".to_string()],
..Default::default()
},
];
open.extend(kept);
spec.open = open;
spec.add_ac(move |rule, _context| val_after_close(rule, st));
});
}
fn overflowed_json_number(text: &str) -> Option<f64> {
let trimmed = text.trim_matches([' ', '\t', '\n', '\r']);
if !is_json_number(trimmed) {
return None;
}
trimmed
.parse::<f64>()
.ok()
.filter(|value| value.is_infinite())
}
fn is_json_number(text: &str) -> bool {
let mut chars = text.chars().peekable();
if chars.peek() == Some(&'-') {
chars.next();
}
match chars.next() {
Some('0') => {}
Some(digit) if digit.is_ascii_digit() => {
while chars.peek().is_some_and(char::is_ascii_digit) {
chars.next();
}
}
_ => return false,
}
if chars.peek() == Some(&'.') {
chars.next();
if !chars.peek().is_some_and(char::is_ascii_digit) {
return false;
}
while chars.peek().is_some_and(char::is_ascii_digit) {
chars.next();
}
}
if matches!(chars.peek(), Some('e' | 'E')) {
chars.next();
if matches!(chars.peek(), Some('+' | '-')) {
chars.next();
}
if !chars.peek().is_some_and(char::is_ascii_digit) {
return false;
}
while chars.peek().is_some_and(char::is_ascii_digit) {
chars.next();
}
}
chars.next().is_none()
}
fn replace_lone_surrogates(text: &str) -> Option<String> {
fn escaped_unit(bytes: &[u8], at: usize) -> Option<u16> {
if bytes.get(at) != Some(&b'\\') || bytes.get(at + 1) != Some(&b'u') {
return None;
}
let digits = bytes.get(at + 2..at + 6)?;
digits.iter().try_fold(0u16, |unit, byte| {
let digit = (*byte as char).to_digit(16)?;
Some(unit * 16 + digit as u16)
})
}
const HIGH: std::ops::Range<u16> = 0xD800..0xDC00;
const LOW: std::ops::Range<u16> = 0xDC00..0xE000;
let bytes = text.as_bytes();
let mut repaired = String::new();
let mut copied = 0usize;
let mut index = 0usize;
let mut in_string = false;
let mut replaced = false;
while index < bytes.len() {
match bytes[index] {
b'"' => {
in_string = !in_string;
index += 1;
}
b'\\' if in_string => match escaped_unit(bytes, index) {
Some(unit)
if HIGH.contains(&unit)
&& escaped_unit(bytes, index + 6)
.is_some_and(|next| LOW.contains(&next)) =>
{
index += 12;
}
Some(unit) if HIGH.contains(&unit) || LOW.contains(&unit) => {
repaired.push_str(&text[copied..index]);
repaired.push_str("\\ufffd");
index += 6;
copied = index;
replaced = true;
}
Some(_) => index += 6,
None => {
index += 1;
index += text[index..]
.chars()
.next()
.map_or(0, char::len_utf8)
.max(1);
}
},
_ => index += 1,
}
}
replaced.then(|| {
repaired.push_str(&text[copied..]);
repaired
})
}
fn val_after_close(rule: &mut Rule, st: tabnas::Tin) {
let single_quoted = rule
.o0()
.is_some_and(|token| token.tin == st && token.src.as_str().starts_with('\''));
if single_quoted {
let text = match &*rule.node.borrow() {
Value::String(text) => Some(text.clone()),
Value::Text(text) => Some(text.string.clone()),
_ => None,
};
if let Some(text) = text {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&text) {
set_node(rule, Value::from_json(&parsed));
} else if let Some(number) = overflowed_json_number(&text) {
set_node(rule, Value::Number(number));
} else if let Some(repaired) = replace_lone_surrogates(&text) {
if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&repaired) {
set_node(rule, Value::from_json(&parsed));
}
}
}
}
if rule
.prev_rule
.as_ref()
.is_some_and(|prev| prev.u.contains_key("ini_prev"))
{
let mut text = js_string(&rule.node.borrow());
let mut cursor = rule.prev_rule.clone();
while let Some(link) = cursor {
if !link.u.contains_key("ini_prev") {
break;
}
let source = link
.o
.first()
.map(|token| token.src.as_str().to_string())
.unwrap_or_default();
text = format!("{source}{text}");
*link.node.borrow_mut() = Value::String(text.clone());
cursor = link.prev_rule.clone();
}
set_node(rule, Value::String(text));
}
let Some(parent) = rule.parent_rule.clone() else {
return;
};
if !parent.u.contains_key("ini_array") {
return;
}
let Some(Value::String(key)) = parent.u.get("key").cloned() else {
return;
};
let value = rule.node.borrow().clone();
let mut node = parent.node.borrow_mut();
let mut items = match object_get(&node, &key) {
Some(Value::Array(items)) => (*items).clone(),
_ => Vec::new(),
};
items.push(value);
object_insert(&mut node, key, Value::array(items));
}
struct ValueConfig {
lex: bool,
definitions: HashMap<String, Value>,
}
impl ValueConfig {
fn from_options(options: &Options) -> Self {
Self {
lex: options.value.lex,
definitions: options
.value
.definitions
.iter()
.map(|(source, definition)| {
(
source.clone(),
definition.val.clone().unwrap_or(Value::Undefined),
)
})
.collect(),
}
}
fn resolve(&self, text: &str) -> Value {
if self.lex {
if let Some(value) = self.definitions.get(text) {
return value.clone();
}
}
Value::String(text.to_string())
}
}
fn register_multiline(parser: &mut Tabnas, resolved: &Resolved) {
let resolved = Arc::new(resolved.clone());
parser.lex_match_factory_ref(MULTILINE_REF, move |options: &Options| {
let config = Arc::new(ValueConfig::from_options(options));
let resolved = Arc::clone(&resolved);
let matcher: ImperativeLexMatcher = Arc::new(
move |lexer: &mut Lexer<'_>, rule: &mut Rule, _context: &mut Context| {
multiline_match(lexer, rule, &resolved, &config)
},
);
Some(matcher)
});
}
fn multiline_match(
lexer: &mut Lexer<'_>,
rule: &Rule,
resolved: &Resolved,
config: &ValueConfig,
) -> Option<Token> {
let parent_is_pair = rule.parent_rule.as_ref().is_some_and(|parent| {
let name = parent.name.as_str();
name == "pair" || name == "elem"
});
if !parent_is_pair || rule.state != RuleState::Open {
return None;
}
let source = lexer.window();
let mut rest = source;
let mut text = String::new();
while let Some(c) = rest.chars().next() {
if resolved.inline_active && resolved.is_inline_char(c) {
if resolved.esc_whitespace {
if matches!(text.chars().last(), Some(' ') | Some('\t')) {
break;
}
text.push(c);
rest = &rest[c.len_utf8()..];
continue;
}
break;
}
if resolved.continuation == Some(c) {
let after = &rest[c.len_utf8()..];
if let Some(next) = after
.strip_prefix('\n')
.or_else(|| after.strip_prefix("\r\n"))
{
rest = next.trim_start_matches([' ', '\t']);
continue;
}
}
if '\n' == c || rest.starts_with("\r\n") {
let after = if '\r' == c { &rest[2..] } else { &rest[1..] };
if resolved.indent && after.starts_with([' ', '\t']) {
rest = after.trim_start_matches([' ', '\t']);
text.push(' ');
continue;
}
rest = after;
break;
}
if '\\' == c {
let after = &rest[1..];
if let Some(next) = after.chars().next() {
if resolved.inline_active && resolved.esc_backslash && resolved.is_inline_char(next)
{
text.push(next);
rest = &after[next.len_utf8()..];
continue;
}
if '\\' == next {
text.push('\\');
rest = &after[1..];
continue;
}
}
}
text.push(c);
rest = &rest[c.len_utf8()..];
}
let value = config.resolve(tabnas_hoover::js_trim(&text));
let consumed: String = source[..source.len() - rest.len()].to_string();
let advance = consumed.chars().count();
let point = lexer.point();
lexer.advance_chars(advance);
let tin = lexer.token_tin("#HV");
let mut token = lexer.token("#HV", tin, value, consumed, point);
token
.use_data_mut()
.insert("block".to_string(), Value::String("endofline".to_string()));
Some(token)
}