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
use xmltree::Element;

use crate::error::*;
#[cfg(feature = "unproven")]
use crate::new_element;
use crate::types::Parse;

#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BitRange {
    pub offset: u32,
    pub width: u32,
    pub range_type: BitRangeType,
}

impl BitRange {
    pub fn lsb(&self) -> u32 {
        self.offset
    }
    pub fn msb(&self) -> u32 {
        self.offset + self.width - 1
    }
}

#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BitRangeType {
    BitRange,
    OffsetWidth,
    MsbLsb,
}

impl Parse for BitRange {
    type Object = BitRange;
    type Error = anyhow::Error;

    fn parse(tree: &Element) -> Result<BitRange> {
        let (end, start, range_type): (u32, u32, BitRangeType) = if let Some(range) =
            tree.get_child("bitRange")
        {
            let text = range
                .text
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("text missing"))?; // TODO: Make into a proper error, text empty or something similar
                                                                  // TODO: If the `InvalidBitRange` enum was an error we could context into here somehow so that
                                                                  // the output would be similar to the parse error
            if !text.starts_with('[') {
                return Err(
                    SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::Syntax).into(),
                ); // TODO: Maybe have a MissingOpen/MissingClosing variant
            }
            if !text.ends_with(']') {
                return Err(
                    SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::Syntax).into(),
                ); // TODO: Maybe have a MissingOpen/MissingClosing variant
            }

            let mut parts = text[1..text.len() - 1].split(':');
            (
                parts
                    .next()
                    .ok_or_else(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::Syntax)
                    })?
                    .parse::<u32>()
                    .with_context(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::ParseError)
                    })?,
                parts
                    .next()
                    .ok_or_else(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::Syntax)
                    })?
                    .parse::<u32>()
                    .with_context(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::ParseError)
                    })?,
                BitRangeType::BitRange,
            )
        // TODO: Consider matching instead so we can say which of these tags are missing
        } else if let (Some(lsb), Some(msb)) = (tree.get_child("lsb"), tree.get_child("msb")) {
            (
                // TODO: `u32::parse` should not hide it's errors
                u32::parse(msb).with_context(|| {
                    SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::MsbLsb)
                })?,
                u32::parse(lsb).with_context(|| {
                    SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::MsbLsb)
                })?,
                BitRangeType::MsbLsb,
            )
        } else if let (Some(offset), Some(width)) =
            (tree.get_child("bitOffset"), tree.get_child("bitWidth"))
        {
            (
                // Special case because offset and width are directly provided
                // (ie. do not need to be calculated as in the final step)
                return Ok(BitRange {
                    // TODO: capture that error comes from offset/width tag
                    // TODO: `u32::parse` should not hide it's errors
                    offset: u32::parse(offset).with_context(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::ParseError)
                    })?,
                    width: u32::parse(width).with_context(|| {
                        SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::ParseError)
                    })?,
                    range_type: BitRangeType::OffsetWidth,
                })
            )
        } else {
            return Err(SVDError::InvalidBitRange(tree.clone(), InvalidBitRange::Syntax).into());
        };

        Ok(BitRange {
            offset: start,
            width: end - start + 1,
            range_type,
        })
    }
}
#[cfg(feature = "unproven")]
impl BitRange {
    // TODO: Encode method differs from Encode trait as it acts on a set of possible children, create an interface or decide how to better do this
    pub fn encode(&self) -> Result<Vec<Element>> {
        match self.range_type {
            BitRangeType::BitRange => Ok(vec![new_element(
                "bitRange",
                Some(format!("[{}:{}]", self.msb(), self.lsb())),
            )]),
            BitRangeType::MsbLsb => Ok(vec![
                new_element("lsb", Some(format!("{}", self.lsb()))),
                new_element("msb", Some(format!("{}", self.msb()))),
            ]),
            BitRangeType::OffsetWidth => Ok(vec![
                new_element("bitOffset", Some(format!("{}", self.offset))),
                new_element("bitWidth", Some(format!("{}", self.width))),
            ]),
        }
    }
}

#[cfg(test)]
#[cfg(feature = "unproven")]
mod tests {
    use super::*;

    #[test]
    fn decode_encode() {
        let types = vec![
            (
                BitRange {
                    offset: 16,
                    width: 4,
                    range_type: BitRangeType::BitRange,
                },
                String::from(
                    "
                <fake><bitRange>[19:16]</bitRange></fake>
            ",
                ),
            ),
            (
                BitRange {
                    offset: 16,
                    width: 4,
                    range_type: BitRangeType::OffsetWidth,
                },
                String::from(
                    "
                <fake><bitOffset>16</bitOffset><bitWidth>4</bitWidth></fake>
            ",
                ),
            ),
            (
                BitRange {
                    offset: 16,
                    width: 4,
                    range_type: BitRangeType::MsbLsb,
                },
                String::from(
                    "
                <fake><lsb>16</lsb><msb>19</msb></fake>
            ",
                ),
            ),
        ];

        for (a, s) in types {
            let tree1 = Element::parse(s.as_bytes()).unwrap();
            let value = BitRange::parse(&tree1).unwrap();
            assert_eq!(value, a, "Parsing `{}` expected `{:?}`", s, a);
            let mut tree2 = new_element("fake", None);
            tree2.children = value.encode().unwrap();
            assert_eq!(tree1, tree2, "Encoding {:?} expected {}", a, s);
        }
    }
}