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
//! CMSIS-SVD file parser
//!
//! # Usage
//!
//! ``` no_run
//! use svd_parser as svd;
//!
//! use std::fs::File;
//! use std::io::Read;
//!
//! let xml = &mut String::new();
//! File::open("STM32F30x.svd").unwrap().read_to_string(xml);
//!
//! println!("{:?}", svd::parse(xml));
//! ```
//!
//! # References
//!
//! - [SVD Schema file](https://www.keil.com/pack/doc/CMSIS/SVD/html/schema_1_2_gr.html)
//! - [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)
//!
//! Parse traits.
//! These support parsing of SVD types from XML

pub use svd::ValidateLevel;
pub use svd_rs as svd;

pub use anyhow::Context;
use roxmltree::{Document, Node, NodeId};
// ElementExt extends XML elements with useful methods
pub mod elementext;
use crate::elementext::ElementExt;
// Types defines simple types and parse/encode implementations
pub mod types;

#[derive(Clone, Copy, Debug, Default)]
#[non_exhaustive]
/// Advanced parser options
pub struct Config {
    /// SVD error check level
    pub validate_level: ValidateLevel,
    #[cfg(feature = "expand")]
    /// Expand arrays and resolve derivedFrom
    // TODO: split it on several independent options
    pub expand: bool,
    #[cfg(feature = "expand")]
    /// Derive register properties from parents
    pub expand_properties: bool,
    /// Skip parsing and emitting `enumeratedValues` and `writeConstraint` in `Field`
    pub ignore_enums: bool,
}

impl Config {
    /// SVD error check level
    pub fn validate_level(mut self, lvl: ValidateLevel) -> Self {
        self.validate_level = lvl;
        self
    }

    #[cfg(feature = "expand")]
    /// Expand arrays and derive
    pub fn expand(mut self, val: bool) -> Self {
        self.expand = val;
        self
    }

    #[cfg(feature = "expand")]
    /// Takes register `size`, `access`, `reset_value` and `reset_mask`
    /// from peripheral or device properties if absent in register
    pub fn expand_properties(mut self, val: bool) -> Self {
        self.expand_properties = val;
        self
    }

    /// Skip parsing `enumeratedValues` and `writeConstraint` in `Field`
    pub fn ignore_enums(mut self, val: bool) -> Self {
        self.ignore_enums = val;
        self
    }
}

/// Parse trait allows SVD objects to be parsed from XML elements.
pub trait Parse {
    /// Object returned by parse method
    type Object;
    /// Parsing error
    type Error;
    /// Advanced parse options
    type Config;
    /// Parse an XML/SVD element into it's corresponding `Object`.
    fn parse(elem: &Node, config: &Self::Config) -> Result<Self::Object, Self::Error>;
}

/// Parses an optional child element with the provided name and Parse function
/// Returns an none if the child doesn't exist, Ok(Some(e)) if parsing succeeds,
/// and Err() if parsing fails.
pub fn optional<T>(n: &str, e: &Node, config: &T::Config) -> Result<Option<T::Object>, SVDErrorAt>
where
    T: Parse<Error = SVDErrorAt>,
{
    let child = match e.get_child(n) {
        Some(c) => c,
        None => return Ok(None),
    };

    match T::parse(&child, config) {
        Ok(r) => Ok(Some(r)),
        Err(e) => Err(e),
    }
}

use crate::svd::Device;
/// Parses the contents of an SVD (XML) string
pub fn parse(xml: &str) -> anyhow::Result<Device> {
    parse_with_config(xml, &Config::default())
}
/// Parses the contents of an SVD (XML) string
pub fn parse_with_config(xml: &str, config: &Config) -> anyhow::Result<Device> {
    fn get_name<'a>(node: &'a Node) -> Option<&'a str> {
        node.children()
            .find(|t| t.has_tag_name("name"))
            .and_then(|t| t.text())
    }

    let xml = trim_utf8_bom(xml);
    let tree = Document::parse(xml)?;
    let root = tree.root();
    let xmldevice = root
        .get_child("device")
        .ok_or_else(|| SVDError::MissingTag("device".to_string()).at(root.id()))?;

    #[allow(unused_mut)]
    let mut device = match Device::parse(&xmldevice, config) {
        Ok(o) => Ok(o),
        Err(e) => {
            let id = e.id;
            let node = tree.get_node(id).unwrap();
            let pos = tree.text_pos_at(node.range().start);
            let tagname = node.tag_name().name();
            let mut res = Err(e.into());
            if tagname.is_empty() {
                res = res.with_context(|| format!("at {}", pos))
            } else if let Some(name) = get_name(&node) {
                res = res.with_context(|| format!("Parsing {} `{}` at {}", tagname, name, pos))
            } else {
                res = res.with_context(|| format!("Parsing unknown {} at {}", tagname, pos))
            }
            for parent in node.ancestors().skip(1) {
                if parent.id() == NodeId::new(0) {
                    break;
                }
                let tagname = parent.tag_name().name();
                match tagname {
                    "device" | "peripheral" | "register" | "field" | "enumeratedValue"
                    | "interrupt" => {
                        if let Some(name) = get_name(&parent) {
                            res = res.with_context(|| format!("In {} `{}`", tagname, name));
                        } else {
                            res = res.with_context(|| format!("In unknown {}", tagname));
                        }
                    }
                    _ => {}
                }
            }
            res
        }
    }?;

    #[cfg(feature = "expand")]
    if config.expand_properties {
        expand::expand_properties(&mut device);
    }

    #[cfg(feature = "expand")]
    if config.expand {
        device = expand::expand(&device)?;
    }
    Ok(device)
}

/// Return the &str trimmed UTF-8 BOM if the input &str contains the BOM.
fn trim_utf8_bom(s: &str) -> &str {
    if s.len() > 2 && s.as_bytes().starts_with(b"\xef\xbb\xbf") {
        &s[3..]
    } else {
        s
    }
}

mod array;
use array::parse_array;

mod access;
mod addressblock;
mod bitrange;
mod cluster;
mod cpu;
mod device;
mod dimelement;
mod endian;
mod enumeratedvalue;
mod enumeratedvalues;
mod field;
mod interrupt;
mod modifiedwritevalues;
mod peripheral;
mod protection;
mod readaction;
mod register;
mod registercluster;
mod registerproperties;
mod usage;
mod writeconstraint;

#[cfg(feature = "expand")]
pub mod expand;

#[cfg(feature = "expand")]
pub use expand::{expand, expand_properties};
/// SVD parse Errors.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SVDError {
    #[error("{0}")]
    Svd(#[from] svd::SvdError),
    #[error("Expected a <{0}> tag, found none")]
    MissingTag(String),
    #[error("Expected content in <{0}> tag, found none")]
    EmptyTag(String),
    #[error("Failed to parse `{0}`")]
    ParseInt(#[from] std::num::ParseIntError),
    #[error("Unknown endianness `{0}`")]
    UnknownEndian(String),
    #[error("unknown access variant '{0}' found")]
    UnknownAccessType(String),
    #[error("Bit range invalid, {0:?}")]
    InvalidBitRange(bitrange::InvalidBitRange),
    #[error("Unknown write constraint")]
    UnknownWriteConstraint,
    #[error("Multiple wc found")]
    MoreThanOneWriteConstraint,
    #[error("Unknown usage variant")]
    UnknownUsageVariant,
    #[error("Unknown usage variant for addressBlock")]
    UnknownAddressBlockUsageVariant,
    #[error("Expected a <{0}>, found ...")]
    NotExpectedTag(String),
    #[error("Invalid RegisterCluster (expected register or cluster), found {0}")]
    InvalidRegisterCluster(String),
    #[error("Invalid modifiedWriteValues variant, found {0}")]
    InvalidModifiedWriteValues(String),
    #[error("Invalid readAction variant, found {0}")]
    InvalidReadAction(String),
    #[error("Invalid protection variant, found {0}")]
    InvalidProtection(String),
    #[error("The content of the element could not be parsed to a boolean value {0}: {1}")]
    InvalidBooleanValue(String, core::str::ParseBoolError),
    #[error("dimIndex tag must contain {0} indexes, found {1}")]
    IncorrectDimIndexesCount(usize, usize),
    #[error("Failed to parse dimIndex")]
    DimIndexParse,
    #[error("Name `{0}` in tag `{1}` is missing a %s placeholder")]
    MissingPlaceholder(String, String),
}

#[derive(Clone, Debug, PartialEq)]
pub struct SVDErrorAt {
    error: SVDError,
    id: NodeId,
}

impl std::fmt::Display for SVDErrorAt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.error.fmt(f)
    }
}

impl std::error::Error for SVDErrorAt {}

impl SVDError {
    pub fn at(self, id: NodeId) -> SVDErrorAt {
        SVDErrorAt { error: self, id }
    }
}

pub(crate) fn check_has_placeholder(name: &str, tag: &str) -> Result<(), SVDError> {
    if name.contains("%s") {
        Ok(())
    } else {
        Err(SVDError::MissingPlaceholder(
            name.to_string(),
            tag.to_string(),
        ))
    }
}

#[test]
fn test_trim_utf8_bom_from_str() {
    // UTF-8 BOM + "xyz"
    let bom_str = std::str::from_utf8(b"\xef\xbb\xbfxyz").unwrap();
    assert_eq!("xyz", trim_utf8_bom(bom_str));
    assert_eq!("xyz", trim_utf8_bom("xyz"));
}