Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minicom XML parser/writer #138

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ derive-from = []
strict = []

[dependencies]
xmltree = "0.8"
minidom = "0.13.0"
anyhow = "1.0.19"
thiserror = "1.0.5"
rayon = "1.5.0"
Expand Down
39 changes: 21 additions & 18 deletions src/elementext.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
//! SVD Element Extensions.
//! This module is extends xmltree::Element objects with convenience methods
//! This module is extends minidom::Element objects with convenience methods

use xmltree::Element;
use minidom::Element;

use crate::types::{BoolParse, Parse};

use crate::error::*;

/// Defines extensions for implementation over xmltree::Element
/// Defines extensions for implementation over minidom::Element
pub trait ElementExt {
fn get_child_text_opt<K>(&self, k: K) -> Result<Option<String>>
where
String: PartialEq<K>;
String: PartialEq<K>,
K: AsRef<str>;
fn get_child_text<K>(&self, k: K) -> Result<String>
where
String: PartialEq<K>,
K: core::fmt::Display + Clone;
K: core::fmt::Display + Clone + AsRef<str>;

fn get_text(&self) -> Result<String>;

Expand All @@ -29,13 +30,14 @@ pub trait ElementExt {
fn debug(&self);
}

/// Implements extensions for xmltree::Element
/// Implements extensions for minidom::Element
impl ElementExt for Element {
fn get_child_text_opt<K>(&self, k: K) -> Result<Option<String>>
where
String: PartialEq<K>,
K: AsRef<str>,
{
if let Some(child) = self.get_child(k) {
if let Some(child) = self.get_child(k, "") {
match child.get_text() {
Err(e) => match e.downcast_ref() {
// if tag is empty just ignore it
Expand All @@ -51,26 +53,26 @@ impl ElementExt for Element {
fn get_child_text<K>(&self, k: K) -> Result<String>
where
String: PartialEq<K>,
K: core::fmt::Display + Clone,
K: core::fmt::Display + Clone + AsRef<str>,
{
self.get_child_text_opt(k.clone())?
.ok_or_else(|| SVDError::MissingTag(self.clone(), format!("{}", k)).into())
}

/// Get text contained by an XML Element
fn get_text(&self) -> Result<String> {
match self.text.as_ref() {
Some(s) => Ok(s.clone()),
match self.texts().next() {
Some(s) => Ok(s.to_string()),
// FIXME: Doesn't look good because SVDError doesn't format by itself. We already
// capture the element and this information can be used for getting the name
// This would fix ParseError
None => Err(SVDError::EmptyTag(self.clone(), self.name.clone()).into()),
None => Err(SVDError::EmptyTag(self.clone(), self.name().to_string()).into()),
}
}

/// Get a named child element from an XML Element
fn get_child_elem<'a>(&'a self, n: &str) -> Result<&'a Element> {
match self.get_child(n) {
match self.get_child(n, "") {
Some(s) => Ok(s),
None => Err(SVDError::MissingTag(self.clone(), n.to_string()).into()),
}
Expand All @@ -96,16 +98,17 @@ impl ElementExt for Element {

// Merges the children of two elements, maintaining the name and description of the first
fn merge(&mut self, r: &Self) {
for c in &r.children {
self.children.push(c.clone());
for c in r.children() {
self.append_child(c.clone());
}
}

fn debug(&self) {
println!("<{}>", self.name);
for c in &self.children {
println!("{}: {:?}", c.name, c.text)
let name = self.name();
println!("<{}>", name);
for c in self.children() {
println!("{}: {:?}", c.name(), c.text())
}
println!("</{}>", self.name);
println!("</{}>", name);
}
}
2 changes: 1 addition & 1 deletion src/encode.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Encode traits.
//! These support encoding of SVD types to XML

use xmltree::Element;
use minidom::Element;

/// Encode trait allows SVD objects to be encoded into XML elements.
pub trait Encode {
Expand Down
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

pub use anyhow::{Context, Result};
use core::u64;
use minidom::Element;
use once_cell::sync::Lazy;
use regex::Regex;
use xmltree::Element;

#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
Expand Down
47 changes: 23 additions & 24 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,11 @@
//! - [SVD file database](https://github.com/posborne/cmsis-svd/tree/master/data)
//! - [Sample SVD file](https://www.keil.com/pack/doc/CMSIS/SVD/html/svd_Example_pg.html)

#![deny(warnings)]
//#![deny(warnings)]

use std::collections::HashMap;
use xmltree::Element;
pub const NS: &str = "SVD";

use minidom::{Element, ElementBuilder};

// ElementExt extends XML elements with useful methods
pub mod elementext;
Expand All @@ -52,15 +53,15 @@ pub use derive_from::DeriveFrom;
/// Parses the contents of an SVD (XML) string
pub fn parse(xml: &str) -> Result<Device> {
let xml = trim_utf8_bom(xml);
let tree = Element::parse(xml.as_bytes())?;
let tree: Element = xml.parse()?;
Device::parse(&tree)
}

/// Encodes a device object to an SVD (XML) string
pub fn encode(d: &Device) -> Result<String> {
let root = d.encode()?;
let mut wr = Vec::new();
root.write(&mut wr).unwrap();
root.write_to(&mut wr).unwrap();
Ok(String::from_utf8(wr).unwrap())
}

Expand All @@ -74,15 +75,11 @@ fn trim_utf8_bom(s: &str) -> &str {
}

/// Helper to create new base xml elements
pub(crate) fn new_element(name: &str, text: Option<String>) -> Element {
Element {
prefix: None,
namespace: None,
namespaces: None,
name: String::from(name),
attributes: HashMap::new(),
children: Vec::new(),
text,
pub(crate) fn new_element(name: &str, text: Option<String>) -> ElementBuilder {
if let Some(text) = text {
Element::builder(name, NS).append(text)
} else {
Element::builder(name, NS)
}
}

Expand All @@ -98,29 +95,31 @@ pub fn run_test<
>(
tests: &[(T, &str)],
) {
for t in tests {
let mut tree1 = Element::parse(t.1.as_bytes()).unwrap();
/*for t in tests {
let mut tree1: Element = t.1.parse().unwrap();
let elem = T::parse(&tree1).unwrap();
// Hack to make assert be order agnostic
tree1.children.sort_by(|e1, e2| e1.name.cmp(&e2.name));
tree1.children.iter_mut().for_each(|e| {
e.children.sort_by(|e1, e2| e1.name.cmp(&e2.name));
let mut children1 = tree1.children().collect::<Vec<_>>();
children1.sort_by(|e1, e2| e1.name().cmp(&e2.name()));
children1.iter_mut().for_each(|e| {
e.children.sort_by(|e1, e2| e1.name().cmp(&e2.name()));
});
assert_eq!(
elem, t.0,
"Error parsing xml` (mismatch between parsed and expected)"
);
let mut tree2 = elem.encode().unwrap();
// Hack to make assert be order agnostic
tree2.children.sort_by(|e1, e2| e1.name.cmp(&e2.name));
tree2.children.iter_mut().for_each(|e| {
e.children.sort_by(|e1, e2| e1.name.cmp(&e2.name));
let mut children2 = tree2.children().collect::<Vec<_>>();
children2.sort_by(|e1, e2| e1.name().cmp(&e2.name()));
children2.iter_mut().for_each(|e| {
e.children.sort_by(|e1, e2| e1.name().cmp(&e2.name()));
});
assert_eq!(
tree1, tree2,
children1, children1,
"Error encoding xml (mismatch between encoded and original)"
);
}
}*/
}

#[cfg(test)]
Expand Down
4 changes: 2 additions & 2 deletions src/parse.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Parse traits.
//! These support parsing of SVD types from XML

use xmltree::Element;
use minidom::Element;

/// Parse trait allows SVD objects to be parsed from XML elements.
pub trait Parse {
Expand All @@ -20,7 +20,7 @@ pub fn optional<'a, T>(n: &str, e: &'a Element) -> anyhow::Result<Option<T::Obje
where
T: Parse<Error = anyhow::Error>,
{
let child = match e.get_child(n) {
let child = match e.get_child(n, "") {
Some(c) => c,
None => return Ok(None),
};
Expand Down
4 changes: 2 additions & 2 deletions src/svd/access.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use xmltree::Element;
use minidom::Element;

use crate::elementext::ElementExt;
use crate::encode::Encode;
Expand Down Expand Up @@ -46,7 +46,7 @@ impl Encode for Access {
Access::WriteOnce => String::from("writeOnce"),
};

Ok(new_element("access", Some(text)))
Ok(new_element("access", Some(text)).build())
}
}

Expand Down
23 changes: 7 additions & 16 deletions src/svd/addressblock.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use std::collections::HashMap;

use crate::elementext::ElementExt;
use xmltree::Element;
use crate::NS;
use minidom::Element;

use crate::types::Parse;

Expand Down Expand Up @@ -34,19 +33,11 @@ impl Encode for AddressBlock {
type Error = anyhow::Error;

fn encode(&self) -> Result<Element> {
Ok(Element {
prefix: None,
namespace: None,
namespaces: None,
name: String::from("addressBlock"),
attributes: HashMap::new(),
children: vec![
new_element("offset", Some(format!("{}", self.offset))),
new_element("size", Some(format!("0x{:08.x}", self.size))),
new_element("usage", Some(self.usage.clone())),
],
text: None,
})
Ok(Element::builder("addressBlock", NS)
.append(new_element("offset", Some(format!("{}", self.offset))))
.append(new_element("size", Some(format!("0x{:08.x}", self.size))))
.append(new_element("usage", Some(self.usage.clone())))
.build())
}
}

Expand Down
Loading