#![allow(clippy::result_large_err)]
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};
use indexmap::IndexMap;
use tabnas::{
Context, LexMatcher, Options, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_CM, TIN_LN,
TIN_SP,
};
mod bom;
mod entity;
mod lex;
mod namespace;
pub use bom::{decode_bom, strip_bom};
pub const VERSION: &str = "0.7.10";
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}
pub use tabnas::TabnasError as XmlError;
pub const GRAMMAR_TEXT: &str = r##"
{
"rule": {
"xml": {
"open": [
{
"s": "#ZZ"
},
{
"s": "#TX",
"r": "xml",
"a": "@doc-text-open"
},
{
"p": "element",
"c": "@no-root-yet"
}
],
"close": [
{
"s": "#ZZ",
"g": "end"
},
{
"s": "#TX",
"r": "xml",
"a": "@doc-text-close",
"g": "comma"
}
]
},
"element": {
"open": [
{
"s": "#XSC",
"a": "@element-selfclose",
"u": {
"selfclose": 1
}
},
{
"s": "#XOP",
"p": "content",
"a": "@element-open"
}
],
"close": [
{
"c": "@element-is-selfclosed"
},
{
"s": "#XCL",
"a": "@element-close",
"g": "close"
}
]
},
"content": {
"open": [
{
"s": "#XCL",
"b": 1
},
{
"p": "child"
}
],
"close": [
{
"s": "#XCL",
"b": 1,
"g": "close"
},
{
"r": "content"
}
]
},
"child": {
"open": [
{
"s": "#TX",
"a": "@child-text"
},
{
"s": "#XOP",
"b": 1,
"p": "element"
},
{
"s": "#XSC",
"b": 1,
"p": "element"
}
]
}
}
}"##;
const PLUGIN_NAME: &str = "xml";
const XML_BC: &str = "@xml-bc";
const CHILD_BC: &str = "@child-bc";
const ELEMENT_BC: &str = "@element-bc";
const NO_ROOT_YET: &str = "@no-root-yet";
const DOC_TEXT_OPEN: &str = "@doc-text-open";
const DOC_TEXT_CLOSE: &str = "@doc-text-close";
const ELEMENT_OPEN: &str = "@element-open";
const ELEMENT_SELFCLOSE: &str = "@element-selfclose";
const ELEMENT_CLOSE: &str = "@element-close";
const CHILD_TEXT: &str = "@child-text";
const ELEMENT_IS_SELFCLOSED: &str = "@element-is-selfclosed";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XmlOptions {
pub namespaces: bool,
pub entities: bool,
pub custom_entities: IndexMap<String, String>,
pub strict_entities: bool,
pub strict_namespaces: bool,
pub embed: bool,
}
impl Default for XmlOptions {
fn default() -> Self {
XmlOptions {
namespaces: true,
entities: true,
custom_entities: IndexMap::new(),
strict_entities: true,
strict_namespaces: false,
embed: false,
}
}
}
impl XmlOptions {
pub fn from_value(value: &Value) -> Self {
let bag = value.to_json();
let field = |name: &str| bag.get(name);
let not_false = |name: &str| field(name) != Some(&serde_json::Value::Bool(false));
let is_true = |name: &str| field(name) == Some(&serde_json::Value::Bool(true));
let custom_entities = custom_entities(value);
XmlOptions {
namespaces: not_false("namespaces"),
entities: not_false("entities"),
custom_entities,
strict_entities: not_false("strictEntities"),
strict_namespaces: is_true("strictNamespaces"),
embed: is_true("embed"),
}
}
pub fn to_value(&self) -> Value {
let mut custom = IndexMap::new();
for (name, text) in &self.custom_entities {
custom.insert(name.clone(), Value::String(text.clone()));
}
let mut bag = IndexMap::new();
bag.insert("namespaces".to_string(), Value::Bool(self.namespaces));
bag.insert("entities".to_string(), Value::Bool(self.entities));
bag.insert("customEntities".to_string(), Value::object(custom));
bag.insert(
"strictEntities".to_string(),
Value::Bool(self.strict_entities),
);
bag.insert(
"strictNamespaces".to_string(),
Value::Bool(self.strict_namespaces),
);
bag.insert("embed".to_string(), Value::Bool(self.embed));
Value::object(bag)
}
}
fn custom_entities(bag: &Value) -> IndexMap<String, String> {
let fields = match bag {
Value::Object(fields) => &**fields,
Value::MapRef(map) => &map.value,
_ => return IndexMap::new(),
};
let entries = match fields.get("customEntities") {
Some(Value::Object(entries)) => &**entries,
Some(Value::MapRef(map)) => &map.value,
_ => return IndexMap::new(),
};
entries
.iter()
.map(|(name, replacement)| {
let text = match replacement {
Value::String(text) => text.clone(),
Value::Text(text) => text.string.clone(),
Value::Undefined => format!("&{name};"),
other => js_string(other),
};
(name.clone(), text)
})
.collect()
}
fn js_string(value: &Value) -> String {
match value {
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::String(text) => text.clone(),
Value::Text(text) => text.string.clone(),
Value::Array(items) => items
.iter()
.map(|item| match item {
Value::Undefined | Value::Null => String::new(),
other => js_string(other),
})
.collect::<Vec<_>>()
.join(","),
Value::ListRef(list) => js_string(&Value::array(list.value.clone())),
Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
}
}
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 set_node(rule: &mut Rule, value: Value) {
rule.node = Rc::new(RefCell::new(value));
}
fn flag(rule: &Rule, name: &str) -> bool {
matches!(rule.u.get(name), Some(Value::Bool(true)))
}
fn token_string(token: Option<&Token>) -> Option<String> {
match token.map(|token| &token.val) {
Some(Value::String(text)) => Some(text.clone()),
_ => None,
}
}
fn element_of(token: Option<&Token>, context: &Context) -> Value {
let (name, attributes) = match token.map(|token| &token.val) {
Some(Value::Object(tag)) => {
let name = match tag.get("name") {
Some(Value::String(name)) => name.clone(),
_ => String::new(),
};
let attributes = match tag.get("attributes") {
Some(Value::Object(attributes)) => (**attributes).clone(),
_ => IndexMap::new(),
};
(name, attributes)
}
_ => (String::new(), IndexMap::new()),
};
let attributes = apply_attr_defaults(attributes, &name, context);
let mut element = IndexMap::new();
element.insert("name".to_string(), Value::String(name.clone()));
element.insert("localName".to_string(), Value::String(name));
element.insert("attributes".to_string(), Value::object(attributes));
element.insert("children".to_string(), Value::array(Vec::new()));
Value::object(element)
}
fn apply_attr_defaults(
mut attributes: IndexMap<String, Value>,
element: &str,
context: &Context,
) -> IndexMap<String, Value> {
if let Some(defaults) = lex::dtd_attr_defaults(context, element) {
for (name, value) in defaults {
if !attributes.contains_key(&name) {
attributes.insert(name, value);
}
}
}
attributes
}
fn push_child(node: &mut Value, child: Value) {
if let Some(children) = node
.as_object_mut()
.and_then(|element| element.get_mut("children"))
.and_then(Value::as_array_mut)
{
children.push(child);
}
}
fn check_doc_text(token: Option<&Token>, context: &Context) -> Option<Token> {
let token = token?;
let Value::String(text) = &token.val else {
return None;
};
if text
.bytes()
.all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
{
return None;
}
let mut bad = token.clone();
lex::discount_bom(context, &mut bad.site);
bad.bad("text_at_top_level");
Some(bad)
}
pub fn xml(parser: &mut Tabnas, options: &XmlOptions) -> Result<(), PluginError> {
if parser.rules.contains_key("xml") {
return Ok(());
}
let embed = options.embed;
let namespaces = options.namespaces;
let strict_namespaces = options.strict_namespaces;
let tokens = lex::Tokens {
xig: parser.token("#XIG"),
xop: parser.token("#XOP"),
xcl: parser.token("#XCL"),
xsc: parser.token("#XSC"),
};
let state = Arc::new(lex::MatcherState {
decoder: entity::EntityDecoder::new(&options.custom_entities),
entities: options.entities,
strict: options.strict_entities,
tokens,
});
let matcher = lex::matcher(state);
parser.set_options(|o: &mut Options| {
o.lex.matchers.insert(
"xmltag".to_string(),
LexMatcher {
name: "xmltag".to_string(),
order: 100_000.0,
matcher: None,
imperative: Some(matcher),
factory: None,
},
);
o.lex.empty_result = Value::Undefined;
o.ender = vec!["<".to_string()];
if !embed {
o.rule.start = "xml".to_string();
o.rule.exclude = "jsonic,imp".to_string();
for name in ["#OB", "#CB", "#OS", "#CS", "#CL", "#CA"] {
o.fixed.tokens.shift_remove(name);
}
o.number.lex = false;
o.value.lex = false;
o.string.lex = false;
o.comment.lex = false;
o.space.lex = false;
o.line.lex = false;
o.result.fail = vec![Value::Undefined, Value::Null];
o.lex.empty = false;
}
o.token_set.insert(
"IGNORE".to_string(),
vec![TIN_SP, TIN_LN, TIN_CM, tokens.xig],
);
for (code, message) in ERROR_MESSAGES {
o.error.insert((*code).to_string(), (*message).to_string());
}
for (code, hint) in ERROR_HINTS {
o.hint.insert((*code).to_string(), (*hint).to_string());
}
})?;
register_refs(parser, namespaces, strict_namespaces, embed);
parser
.grammar_json(GRAMMAR_TEXT)
.map_err(|error| PluginError(format!("xml: apply grammar: {error}")))?;
if embed {
let splice = serde_json::json!({
"rule": {
"val": {
"open": [
{ "s": "#XOP", "b": 1, "p": "element", "g": "xml" },
{ "s": "#XSC", "b": 1, "p": "element", "g": "xml" },
],
},
},
});
let splice = tabnas::GrammarSpec::from_value(splice)
.map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
parser
.grammar(&splice)
.map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
} else {
for name in ["val", "map", "list", "pair", "elem"] {
parser.remove_rule(name);
}
}
Ok(())
}
fn register_refs(parser: &mut Tabnas, namespaces: bool, strict_namespaces: bool, embed: bool) {
parser.state_action_with_next_ref(XML_BC, move |rule, context, _next, _out| {
if rule.child_node.is_undefined() {
return Ok(None);
}
let mut root = rule.child_node.clone();
context.u.insert("rootSeen".to_string(), Value::Bool(true));
if namespaces {
if let Err(code) = namespace::resolve_namespaces(&mut root, strict_namespaces) {
let mut token = context.t0().cloned().unwrap_or_else(Token::no_token);
token.bad(code);
return Ok(Some(token));
}
}
*rule.node.borrow_mut() = root;
Ok(None)
});
parser.alt_condition(NO_ROOT_YET, |_rule, context| {
!matches!(context.u.get("rootSeen"), Some(Value::Bool(true)))
});
parser.action_with_match_ref(DOC_TEXT_OPEN, |rule, context, _matched| {
Ok(check_doc_text(rule.o0(), context))
});
parser.action_with_match_ref(DOC_TEXT_CLOSE, |rule, context, _matched| {
Ok(check_doc_text(rule.c0(), context))
});
parser.action_with_context(ELEMENT_OPEN, |rule, context| {
let element = element_of(rule.o0(), context);
set_node(rule, element);
Ok(())
});
parser.action_with_context(ELEMENT_SELFCLOSE, |rule, context| {
let element = element_of(rule.o0(), context);
set_node(rule, element);
Ok(())
});
parser.action_with_match_ref(ELEMENT_CLOSE, |rule, _context, _matched| {
let open_name = match &*rule.node.borrow() {
Value::Object(element) => match element.get("name") {
Some(Value::String(name)) => name.clone(),
_ => String::new(),
},
_ => String::new(),
};
let close_name = token_string(rule.c0()).unwrap_or_default();
if open_name == close_name {
return Ok(None);
}
let Some(mut token) = rule.c0().cloned() else {
return Ok(None);
};
token.bad_with_details(
"xml_mismatched_tag",
[
("openname".to_string(), Value::String(open_name)),
("closename".to_string(), Value::String(close_name)),
],
);
Ok(Some(token))
});
parser.action_with_context(CHILD_TEXT, |rule, _context| {
let text = rule
.o0()
.map_or(Value::Undefined, |token| token.val.clone());
push_child(&mut rule.node.borrow_mut(), text);
rule.u_mut().insert("done".to_string(), Value::Bool(true));
Ok(())
});
parser.state_action_ref(CHILD_BC, |rule, _context| {
if flag(rule, "done") || rule.child_node.is_undefined() {
return Ok(());
}
let child = rule.child_node.clone();
push_child(&mut rule.node.borrow_mut(), child);
Ok(())
});
parser.alt_condition(
ELEMENT_IS_SELFCLOSED,
|rule, _context| matches!(rule.u.get("selfclose"), Some(Value::Number(n)) if *n == 1.0),
);
if embed && namespaces {
parser.state_action_ref(ELEMENT_BC, move |rule, _context| {
let under_val = rule
.parent_rule
.as_ref()
.is_some_and(|parent| parent.name.as_str() == "val");
if !under_val || !matches!(&*rule.node.borrow(), Value::Object(_)) {
return Ok(());
}
let mut element = rule.node.borrow().clone();
let _ = namespace::resolve_namespaces(&mut element, strict_namespaces);
*rule.node.borrow_mut() = element;
Ok(())
});
}
}
pub fn plugin() -> Plugin {
Plugin::new(PLUGIN_NAME, |parser, options| {
xml(parser, &XmlOptions::from_value(options))
})
.with_defaults(XmlOptions::default().to_value())
}
pub fn make_with(options: &XmlOptions) -> Tabnas {
let mut parser = tabnas_jsonic::make();
parser
.use_plugin(plugin(), Some(options.to_value()))
.expect("the xml grammar documents are fixed and valid");
parser
}
pub fn make() -> Tabnas {
make_with(&XmlOptions::default())
}
pub fn parse(src: &str) -> Result<Value, XmlError> {
static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
DEFAULT.get_or_init(make).parse(src)
}
const ERROR_MESSAGES: &[(&str, &str)] = &[
(
"xml_mismatched_tag",
"closing tag </{closename}> does not match opening tag <{openname}>",
),
("xml_invalid_tag", "invalid tag: {src}"),
("unterminated_comment", "unterminated comment: {src}"),
("unterminated_cdata", "unterminated CDATA section: {src}"),
(
"unterminated_pi",
"unterminated processing instruction: {src}",
),
(
"unterminated_doctype",
"unterminated DOCTYPE declaration: {src}",
),
("comment_double_dash", "comment body cannot contain \"--\""),
(
"cdata_terminator_in_text",
"character data cannot contain \"]]>\"",
),
(
"pi_target_invalid",
"processing instruction target is missing or invalid",
),
(
"lt_in_attr_value",
"\"<\" is not allowed in an attribute value",
),
(
"bad_entity_ref",
"malformed entity reference (need &name; or &#NNN; or &#xHHH;)",
),
("duplicate_attribute", "duplicate attribute name in tag"),
("invalid_xml_char", "illegal control character in XML data"),
(
"reserved_namespace",
"invalid use of a reserved namespace prefix or URI",
),
(
"unbound_prefix",
"element or attribute uses an undeclared namespace prefix",
),
(
"invalid_namespace_uri",
"namespace name cannot contain white space",
),
("undeclared_entity", "reference to undeclared entity"),
(
"unparsed_entity_ref",
"reference to an unparsed (NDATA) entity",
),
(
"external_entity_in_attr",
"attribute value cannot reference an external entity",
),
(
"text_at_top_level",
"character data is not allowed outside the root element",
),
];
const ERROR_HINTS: &[(&str, &str)] = &[
(
"xml_mismatched_tag",
"Each opening tag must be paired with a matching closing tag.\nExpected </{openname}> but found </{closename}>.",
),
("xml_invalid_tag", "The tag syntax is not valid XML."),
(
"unterminated_comment",
"The comment starting at this position has no closing \"-->\".",
),
(
"unterminated_cdata",
"The CDATA section starting at this position has no closing \"]]>\".",
),
(
"unterminated_pi",
"The processing instruction starting at this position has no closing \"?>\".",
),
(
"unterminated_doctype",
"The DOCTYPE declaration starting at this position has no closing \">\".",
),
(
"comment_double_dash",
"XML 1.0 disallows \"--\" inside a comment body.",
),
(
"cdata_terminator_in_text",
"The literal \"]]>\" must only appear as the end of a CDATA section.",
),
(
"pi_target_invalid",
"A processing instruction must start with a Name; the XML declaration <?xml...?> is the special case.",
),
(
"lt_in_attr_value",
"Use the entity reference < to include \"<\" in an attribute value.",
),
(
"bad_entity_ref",
"Replace literal \"&\" with &, or terminate the entity reference with \";\".",
),
(
"duplicate_attribute",
"Each attribute name in an open tag must be unique.",
),
(
"invalid_xml_char",
"Only #x9, #xA, #xD and code points >= #x20 are legal XML characters.",
),
(
"reserved_namespace",
"The \"xml\" prefix is fixed to http://www.w3.org/XML/1998/namespace; the \"xmlns\" prefix cannot be redeclared, and neither URI may be bound to any other prefix or as the default namespace.",
),
(
"unbound_prefix",
"Declare the prefix with xmlns:prefix=\"...\" on this element or one of its ancestors.",
),
(
"invalid_namespace_uri",
"A namespace name is a URI reference, and a URI reference cannot contain white space; note that a line break inside the declaration becomes a space under attribute-value normalisation.",
),
(
"undeclared_entity",
"Declare the entity in the DOCTYPE internal subset, add it to the customEntities option, or set strictEntities: false to allow unresolved references through.",
),
(
"unparsed_entity_ref",
"XML 1.0 \u{a7}4.1 (WFC: Parsed Entity) \u{2014} an entity declared with an NDATA notation is unparsed, and its name may only appear as the value of an ENTITY-typed attribute, never in an entity reference.",
),
(
"external_entity_in_attr",
"XML 1.0 \u{a7}4.1 (WFC: No External Entity References) \u{2014} an attribute value may not reference an entity whose replacement text lives in an external file.",
),
(
"text_at_top_level",
"An XML document is \"prolog element Misc*\": outside the single root element only comments, processing instructions and white space may appear.",
),
];