1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
use crate::{
attribute::{Attribute, AttributeValue, DefaultDecl},
error::Error,
namespaces::ParseNamespace,
parse::Parse,
prolog::subset::entity::{entity_value::EntityValue, EntitySource},
IResult, Name,
};
use nom::{
branch::alt,
bytes::complete::tag,
combinator::{map, map_res, opt},
multi::{many0, many1},
sequence::{delimited, pair, tuple},
};
use std::{cell::RefCell, collections::HashMap, rc::Rc};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TagState {
Start,
End,
Empty,
}
#[derive(Clone, PartialEq, Eq)]
pub struct Tag {
pub name: Name,
pub attributes: Option<Vec<Attribute>>, // Attribute::Instance
pub state: TagState,
}
impl<'a> Parse<'a> for Tag {
type Args = ();
type Output = IResult<&'a str, Self>;
}
impl<'a> ParseNamespace<'a> for Tag {}
// TODO: Investigate. The hardcoded bracket codes is kind of a hack to get reference element parsing to work. Unsure of how this is going to impact invalid XML.
// Tried to use decode, but having some lifetime issues
impl Tag {
pub fn new(name: Name, attributes: Option<Vec<Attribute>>, state: TagState) -> Self {
Self {
name,
attributes,
state,
}
}
// [40] STag ::= '<' Name (S Attribute)* S? '>'
// Namespaces (Third Edition) [12] STag ::= '<' QName (S Attribute)* S? '>'
pub fn parse_start_tag(
input: &str,
entity_references: Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
entity_source: EntitySource,
) -> IResult<&str, Self> {
map(
tuple((
alt((tag("<"), tag("<"), tag("<"))),
alt((Self::parse_qualified_name, Self::parse_name)),
many0(pair(Self::parse_multispace1, |i| {
Attribute::parse_attribute(i, entity_references.clone(), entity_source.clone())
})),
Self::parse_multispace0,
alt((tag(">"), tag(">"), tag(">"))),
)),
|(_open_char, name, attributes, _whitespace, _close_char)| {
let attributes: Vec<_> = attributes
.into_iter()
.map(|(_whitespace, attr)| attr)
.collect();
Self {
name,
attributes: if attributes.is_empty() {
// check doctype here, if within that, add them to the tag else, None
None
} else {
Some(attributes)
},
state: TagState::Start,
}
},
)(input)
}
pub fn parse_start_tag_by_name<'a>(
input: &'a str,
tag_name: &'a str,
attributes: &Option<Vec<Attribute>>,
entity_references: &Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
entity_source: EntitySource,
) -> IResult<&'a str, Self> {
let mut current_input = input;
loop {
let result: IResult<&'a str, Self> = map_res(
tuple((
alt((tag("<"), tag("<"), tag("<"))),
map_res(
alt((Self::parse_qualified_name, Self::parse_name)),
|name| {
if name.local_part == tag_name {
Ok(name)
} else {
Err(nom::Err::Error(nom::error::Error::new(
"Start Tag doesn't match",
nom::error::ErrorKind::Tag,
)))
}
},
),
many0(pair(Self::parse_multispace1, |i| {
Attribute::parse_attribute(i, entity_references.clone(), entity_source.clone())
})),
Self::parse_multispace0,
alt((tag(">"), tag(">"), tag(">"))),
)),
|(_open_char, name, attributes_vec, _whitespace, _close_char)| -> Result<Self, nom::Err<Error>> {
let parsed_attributes: Vec<_> = attributes_vec
.into_iter()
.map(|(_whitespace, attr)| attr)
.collect();
if let Some(expected_attributes) = attributes {
if expected_attributes == &parsed_attributes {
Ok(Self {
name,
attributes: if parsed_attributes.is_empty() {
None
} else {
Some(parsed_attributes)
},
state: TagState::Start,
})
} else {
Err(nom::Err::Error(nom::error::Error::new(
"Attributes do not match",
nom::error::ErrorKind::Tag,
).into()))
}
} else {
Ok(Self {
name,
attributes: if parsed_attributes.is_empty() {
None
} else {
Some(parsed_attributes)
},
state: TagState::Start,
})
}
},
)(current_input);
match result {
Ok((next_input, tag)) => return Ok((next_input, tag)),
Err(nom::Err::Error(_)) => {
if current_input.is_empty() {
return Err(nom::Err::Error(
nom::error::Error::new(current_input, nom::error::ErrorKind::Tag)
.into(),
));
}
// Move forward in the input string to avoid infinite loop
current_input = ¤t_input[1..];
}
Err(e) => return Err(e),
}
}
}
// [42] ETag ::= '</' Name S? '>'
// Namespaces (Third Edition) [13] ETag ::= '</' QName S? '>'
pub fn parse_end_tag(input: &str) -> IResult<&str, Self> {
delimited(
alt((tag("</"), tag("</"), tag("</"))),
map(
tuple((
Self::parse_multispace0,
alt((Self::parse_qualified_name, Self::parse_name)),
Self::parse_multispace0,
)),
|(_open_tag, name, _close_tag)| Self {
name,
attributes: None, // Attributes are not parsed for end tags
state: TagState::End,
},
),
alt((tag(">"), tag(">"), tag(">"))),
)(input)
}
// [42] ETag ::= '</' Name S? '>'
// Namespaces (Third Edition) [13] ETag ::= '</' QName S? '>'
pub fn parse_end_tag_by_name<'a>(input: &'a str, tag_name: &'a str) -> IResult<&'a str, Self> {
delimited(
alt((tag("</"), tag("</"), tag("</"))),
map(
tuple((
Self::parse_multispace0,
map_res(
alt((Self::parse_qualified_name, Self::parse_name)),
|name| {
if name.local_part == tag_name {
Ok(name)
} else {
Err(nom::Err::Error(nom::error::Error::new(
"END TAG FAILING",
nom::error::ErrorKind::Tag,
)))
}
},
),
Self::parse_multispace0,
)),
|(_open_tag, name, _close_tag)| Self {
name, //: Name::new(None, name),
attributes: None, // Attributes are not parsed for end tags
state: TagState::End,
},
),
alt((tag(">"), tag(">"), tag(">"))),
)(input)
}
// [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
// Namespaces (Third Edition) [14] EmptyElemTag ::= '<' QName (S Attribute)* S? '/>'
pub fn parse_empty_element_tag(
input: &str,
entity_references: Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
entity_source: EntitySource,
) -> IResult<&str, Self> {
map(
tuple((
alt((tag("<"), tag("<"), tag("<"))),
alt((Self::parse_qualified_name, Self::parse_name)),
opt(many1(pair(Self::parse_multispace1, |i| {
Attribute::parse(i, (entity_references.clone(), entity_source.clone()))
}))),
Self::parse_multispace0,
alt((tag("/>"), tag("/>"), tag("/>"))),
)),
|(_open_tag, name, attributes, _whitespace, _close_tag)| Self {
name,
attributes: attributes
.map(|attr| attr.into_iter().map(|(_whitespace, attr)| attr).collect()),
state: TagState::Empty,
},
)(input)
}
// [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>'
// Namespaces (Third Edition) [14] EmptyElemTag ::= '<' QName (S Attribute)* S? '/>'
pub fn parse_empty_element_tag_by_name<'a>(
input: &'a str,
tag_name: &'a str,
_attributes: &Option<Vec<Attribute>>, //TODO: implement empty tag attribute matching
entity_references: &Rc<RefCell<HashMap<(Name, EntitySource), EntityValue>>>,
entity_source: EntitySource,
) -> IResult<&'a str, Self> {
map(
tuple((
alt((tag("<"), tag("<"), tag("<"))),
tag(tag_name),
opt(many1(pair(Self::parse_multispace1, |i| {
Attribute::parse(i, (entity_references.clone(), entity_source.clone()))
}))),
Self::parse_multispace0,
alt((tag("/>"), tag("/>"), tag("/>"))),
)),
|(_open_tag, name, attributes, _whitespace, _close_tag)| Self {
name: Name::new(None, name),
attributes: attributes
.map(|attr| attr.into_iter().map(|(_whitespace, attr)| attr).collect()),
state: TagState::Empty,
},
)(input)
}
pub fn merge_default_attributes(&mut self, default_attributes: &[Attribute]) {
let existing_attributes = self.attributes.get_or_insert_with(Vec::new);
let mut seen_names = std::collections::HashSet::new();
for default_attr in default_attributes {
if let Attribute::Definition {
name, default_decl, ..
} = default_attr
{
if seen_names.contains(name) {
// Skip if this name has already been processed.
continue;
}
seen_names.insert(name.clone());
// Only add the attribute if it doesn't already exist and has a default value
let exists = existing_attributes.iter().any(|attr| matches!(attr, Attribute::Instance { name: existing_name, .. } if existing_name == name));
if !exists {
if let DefaultDecl::Value(val) = default_decl {
existing_attributes.push(Attribute::Instance {
name: name.clone(),
value: AttributeValue::Value(val.clone()),
});
}
}
}
}
// If no attributes were added (and none were already present), set attributes to None
if existing_attributes.is_empty() {
self.attributes = None;
}
}
pub fn add_attributes(&mut self, new_attributes: Vec<Attribute>) {
self.attributes = if new_attributes.is_empty() {
None
} else {
Some(new_attributes)
};
}
}