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
use std::{
    fmt,
    io::{self, Read, Write},
};

use rbx_dom_weak::types::VariantType;

/// An error that can occur when deserializing an XML-format model or place.
#[derive(Debug)]
pub struct DecodeError {
    // This indirection drops the size of the error type substantially (~150
    // bytes to 8 on 64-bit), which is important since it's passed around every
    // function!
    inner: Box<DecodeErrorImpl>,
}

impl DecodeError {
    pub(crate) fn new_from_reader<R: Read>(
        kind: DecodeErrorKind,
        reader: &xml::EventReader<R>,
    ) -> DecodeError {
        use xml::common::Position;

        let pos = reader.position();

        DecodeError {
            inner: Box::new(DecodeErrorImpl {
                kind,
                line: (pos.row + 1) as usize,
                column: pos.column as usize,
            }),
        }
    }

    /// 1-based line number in the document where the error occured.
    pub fn line(&self) -> usize {
        self.inner.line
    }

    /// 1-based column number in the document where the error occured.
    pub fn column(&self) -> usize {
        self.inner.column
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, output: &mut fmt::Formatter) -> fmt::Result {
        write!(
            output,
            "line {}, column {}: {}",
            self.inner.line, self.inner.column, self.inner.kind
        )
    }
}

impl std::error::Error for DecodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.inner.kind.source()
    }
}

#[derive(Debug)]
struct DecodeErrorImpl {
    kind: DecodeErrorKind,
    line: usize,
    column: usize,
}

#[derive(Debug)]
pub(crate) enum DecodeErrorKind {
    // Errors from other crates
    Xml(xml::reader::Error),
    ParseFloat(std::num::ParseFloatError),
    ParseInt(std::num::ParseIntError),
    DecodeBase64(base64::DecodeError),

    // Errors specific to rbx_xml
    WrongDocVersion(String),
    UnexpectedEof,
    UnexpectedXmlEvent(xml::reader::XmlEvent),
    MissingAttribute(&'static str),
    UnknownProperty {
        class_name: String,
        property_name: String,
    },
    InvalidContent(&'static str),
    NameMustBeString(VariantType),
    UnsupportedPropertyConversion {
        class_name: String,
        property_name: String,
        expected_type: VariantType,
        actual_type: VariantType,
        message: String,
    },
}

impl fmt::Display for DecodeErrorKind {
    fn fmt(&self, output: &mut fmt::Formatter) -> fmt::Result {
        use self::DecodeErrorKind::*;

        match self {
            Xml(err) => write!(output, "{}", err),
            ParseFloat(err) => write!(output, "{}", err),
            ParseInt(err) => write!(output, "{}", err),
            DecodeBase64(err) => write!(output, "{}", err),

            WrongDocVersion(version) => {
                write!(output, "Invalid version '{}', expected version 4", version)
            }
            UnexpectedEof => write!(output, "Unexpected end-of-file"),
            UnexpectedXmlEvent(event) => write!(output, "Unexpected XML event {:?}", event),
            MissingAttribute(attribute_name) => {
                write!(output, "Missing attribute '{}'", attribute_name)
            }
            UnknownProperty {
                class_name,
                property_name,
            } => write!(
                output,
                "Property {}.{} is unknown",
                class_name, property_name
            ),
            InvalidContent(explain) => write!(output, "Invalid text content: {}", explain),
            NameMustBeString(ty) => write!(
                output,
                "The 'Name' property must be of type String, but it was {:?}",
                ty
            ),
            UnsupportedPropertyConversion {
                class_name,
                property_name,
                expected_type,
                actual_type,
                message,
            } => write!(
                output,
                "Property {}.{} is expected to be of type {:?}, but it was of type {:?} \
                 When trying to convert, this error occured: {}",
                class_name, property_name, expected_type, actual_type, message
            ),
        }
    }
}

impl std::error::Error for DecodeErrorKind {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use self::DecodeErrorKind::*;

        match self {
            Xml(err) => Some(err),
            ParseFloat(err) => Some(err),
            ParseInt(err) => Some(err),
            DecodeBase64(err) => Some(err),

            WrongDocVersion(_)
            | UnexpectedEof
            | UnexpectedXmlEvent(_)
            | MissingAttribute(_)
            | UnknownProperty { .. }
            | InvalidContent(_)
            | NameMustBeString(_)
            | UnsupportedPropertyConversion { .. } => None,
        }
    }
}

impl From<xml::reader::Error> for DecodeErrorKind {
    fn from(error: xml::reader::Error) -> DecodeErrorKind {
        DecodeErrorKind::Xml(error)
    }
}

impl From<std::num::ParseFloatError> for DecodeErrorKind {
    fn from(error: std::num::ParseFloatError) -> DecodeErrorKind {
        DecodeErrorKind::ParseFloat(error)
    }
}

impl From<std::num::ParseIntError> for DecodeErrorKind {
    fn from(error: std::num::ParseIntError) -> DecodeErrorKind {
        DecodeErrorKind::ParseInt(error)
    }
}

impl From<base64::DecodeError> for DecodeErrorKind {
    fn from(error: base64::DecodeError) -> DecodeErrorKind {
        DecodeErrorKind::DecodeBase64(error)
    }
}

/// An error that can occur when serializing an XML-format model or place.
#[derive(Debug)]
pub struct EncodeError {
    // This Box helps reduce the size of EncodeError a lot, which is important.
    kind: Box<EncodeErrorKind>,
}

impl EncodeError {
    pub(crate) fn new_from_writer<W: Write>(
        kind: EncodeErrorKind,
        _writer: &xml::EventWriter<W>,
    ) -> EncodeError {
        EncodeError {
            kind: Box::new(kind),
        }
    }
}

impl fmt::Display for EncodeError {
    fn fmt(&self, output: &mut fmt::Formatter) -> fmt::Result {
        write!(output, "{}", self.kind)
    }
}

impl std::error::Error for EncodeError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.kind.source()
    }
}

#[derive(Debug)]
pub(crate) enum EncodeErrorKind {
    Io(io::Error),
    Xml(xml::writer::Error),

    UnknownProperty {
        class_name: String,
        property_name: String,
    },
    UnsupportedPropertyType(VariantType),
    UnsupportedPropertyConversion {
        class_name: String,
        property_name: String,
        expected_type: VariantType,
        actual_type: VariantType,
        message: String,
    },
}

impl fmt::Display for EncodeErrorKind {
    fn fmt(&self, output: &mut fmt::Formatter) -> fmt::Result {
        use self::EncodeErrorKind::*;

        match self {
            Io(err) => write!(output, "{}", err),
            Xml(err) => write!(output, "{}", err),

            UnknownProperty {
                class_name,
                property_name,
            } => write!(
                output,
                "Property {}.{} is unknown",
                class_name, property_name
            ),
            UnsupportedPropertyType(ty) => {
                write!(output, "Properties of type {:?} cannot be encoded yet", ty)
            }
            UnsupportedPropertyConversion {
                class_name,
                property_name,
                expected_type,
                actual_type,
                message,
            } => write!(
                output,
                "Property {}.{} is expected to be of type {:?}, but it was of type {:?} \
                 When trying to convert the value, this error occured: {}",
                class_name, property_name, expected_type, actual_type, message
            ),
        }
    }
}

impl std::error::Error for EncodeErrorKind {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use self::EncodeErrorKind::*;

        match self {
            Io(err) => Some(err),
            Xml(err) => Some(err),

            UnknownProperty { .. }
            | UnsupportedPropertyType(_)
            | UnsupportedPropertyConversion { .. } => None,
        }
    }
}

impl From<xml::writer::Error> for EncodeErrorKind {
    fn from(error: xml::writer::Error) -> EncodeErrorKind {
        EncodeErrorKind::Xml(error)
    }
}

impl From<io::Error> for EncodeErrorKind {
    fn from(error: io::Error) -> EncodeErrorKind {
        EncodeErrorKind::Io(error)
    }
}