use std::ops::Range;
use super::ParseError;
use super::extension::{self, Extensions, PDFA_EXTENSION};
use super::mapping::{ADOBE_META, RDF, XML};
use super::tree::{Binding, Element, Node, Scope};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RdfValue {
Text(String),
Array {
kind: ArrayKind,
items: Vec<ArrayItem>,
},
Other(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ArrayKind {
Alt,
Seq,
Bag,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArrayItem {
pub lang: Option<String>,
pub value: RdfValue,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RdfProperty {
pub namespace: String,
pub name: String,
pub value: RdfValue,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum Place {
Attribute(Range<usize>),
Element(Range<usize>),
}
#[derive(Debug, Clone)]
pub(super) struct Located {
pub(super) property: RdfProperty,
pub(super) prefix: String,
pub(super) place: Place,
pub(super) removal_start: usize,
pub(super) description: usize,
pub(super) declarations: Vec<Binding>,
}
#[derive(Debug, Clone)]
pub(super) struct Description {
pub(super) qualified: String,
pub(super) start_tag: Range<usize>,
pub(super) empty: bool,
pub(super) insert_at: usize,
pub(super) indent: String,
pub(super) own_indent: String,
pub(super) scope: Scope,
pub(super) declarations: Vec<Binding>,
pub(super) attributes: Vec<Range<usize>>,
pub(super) has_about: bool,
pub(super) children: Vec<Range<usize>>,
}
#[derive(Debug, Clone, Default)]
pub(super) struct Rdf {
pub(super) descriptions: Vec<Description>,
pub(super) properties: Vec<Located>,
pub(super) scope: Scope,
pub(super) others: Vec<Range<usize>>,
pub(super) extensions: Option<Extensions>,
}
pub(super) fn read(text: &str, top: &[Node]) -> Result<Rdf, ParseError> {
let mut scope = Scope::default();
let rdf = find_rdf(top, &mut scope).ok_or(ParseError::NoRdf)?;
let scope = scope.with(&rdf.declarations);
let mut out = Rdf {
scope: scope.clone(),
..Rdf::default()
};
for node in &rdf.children {
match node {
Node::Element(e) if e.name.is(RDF, "Description") => description(text, e, &scope, &mut out),
Node::Element(e) => out.others.push(e.span.clone()),
Node::Other { span } => out.others.push(span.clone()),
Node::Text { .. } => {}
}
}
Ok(out)
}
fn find_rdf<'a>(nodes: &'a [Node], scope: &mut Scope) -> Option<&'a Element> {
for node in nodes {
let Node::Element(e) = node else { continue };
if e.name.is(RDF, "RDF") {
return Some(e);
}
if e.name.namespace == ADOBE_META
&& let Some(found) = e.child_elements().find(|c| c.name.is(RDF, "RDF"))
{
*scope = scope.with(&e.declarations);
return Some(found);
}
}
None
}
fn description(text: &str, e: &Element, outer: &Scope, out: &mut Rdf) {
let index = out.descriptions.len();
let scope = outer.with(&e.declarations);
let mut attributes = Vec::new();
for a in &e.attrs {
attributes.push(a.span.clone());
if a.name.namespace.is_empty() || a.name.namespace == RDF || a.name.namespace == XML {
continue;
}
out.properties.push(Located {
property: RdfProperty {
namespace: a.name.namespace.clone(),
name: a.name.local.clone(),
value: RdfValue::Text(a.value.clone()),
},
prefix: a.name.prefix.clone(),
place: Place::Attribute(a.span.clone()),
removal_start: whitespace_before(text, a.span.start),
description: index,
declarations: Vec::new(),
});
}
let mut children = Vec::new();
let mut insert_at = e.start_tag.end;
let mut indent = None;
let mut previous: Option<&Node> = None;
for node in &e.children {
if let Node::Element(child) = node {
let removal_start = match previous {
Some(Node::Text { span, value }) if value.trim().is_empty() => span.start,
_ => child.span.start,
};
if indent.is_none() {
indent = Some(line_indent(text, child.span.start));
}
if out.extensions.is_none() && child.name.is(PDFA_EXTENSION, "schemas") {
out.extensions = Some(extension::read(text, child, &scope));
}
out.properties.push(Located {
property: RdfProperty {
namespace: child.name.namespace.clone(),
name: child.name.local.clone(),
value: value_of(text, child),
},
prefix: child.name.prefix.clone(),
place: Place::Element(child.span.clone()),
removal_start,
description: index,
declarations: child.declarations.clone(),
});
children.push(child.span.clone());
insert_at = child.span.end;
}
previous = Some(node);
}
let own_indent = line_indent(text, e.span.start);
let indent = indent.unwrap_or_else(|| format!("{own_indent} "));
out.descriptions.push(Description {
qualified: e.name.qualified(),
start_tag: e.start_tag.clone(),
empty: e.empty,
insert_at,
indent,
own_indent,
has_about: e.attr(RDF, "about").is_some(),
scope,
declarations: e.declarations.clone(),
attributes,
children,
});
}
fn value_of(text: &str, e: &Element) -> RdfValue {
let verbatim = || RdfValue::Other(text.get(e.span.clone()).unwrap_or_default().to_owned());
let qualifies = e
.attrs
.iter()
.any(|a| !(a.name.is(XML, "lang") || (a.name.namespace.is_empty() && a.name.local == "about")));
if qualifies {
return verbatim();
}
let mut elements = e.child_elements();
let Some(first) = elements.next() else {
return RdfValue::Text(e.text());
};
if elements.next().is_some() || first.name.namespace != RDF {
return verbatim();
}
let kind = match first.name.local.as_str() {
"Alt" => ArrayKind::Alt,
"Seq" => ArrayKind::Seq,
"Bag" => ArrayKind::Bag,
_ => return verbatim(),
};
let mut items = Vec::new();
for li in first.child_elements() {
if !li.name.is(RDF, "li") {
return verbatim();
}
items.push(ArrayItem {
lang: li.attr(XML, "lang").map(|a| a.value.clone()),
value: value_of(text, li),
});
}
RdfValue::Array { kind, items }
}
fn whitespace_before(text: &str, at: usize) -> usize {
let before = text.get(..at).unwrap_or_default();
before.trim_end_matches([' ', '\t', '\n', '\r']).len()
}
fn line_indent(text: &str, at: usize) -> String {
let before = text.get(..at).unwrap_or_default();
let line_start = before.rfind('\n').map_or(0, |i| i + 1);
let indent = before.get(line_start..).unwrap_or_default();
if indent.chars().all(|c| c == ' ' || c == '\t') {
format!("\n{indent}")
} else {
"\n".to_owned()
}
}