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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
use std::{collections::HashMap, io::Read};

use log::trace;
use rbx_dom_weak::{
    types::{Ref, SharedString, Variant, VariantType},
    InstanceBuilder, WeakDom,
};
use rbx_reflection::DataType;

use crate::{
    compat::{TodoValueConversion, TodoValueConversionType},
    core::find_canonical_property_descriptor,
    error::{DecodeError, DecodeErrorKind},
    types::read_value_xml,
};

use crate::deserializer_core::{XmlEventReader, XmlReadEvent};

pub fn decode_internal<R: Read>(source: R, options: DecodeOptions) -> Result<WeakDom, DecodeError> {
    let mut tree = WeakDom::new(InstanceBuilder::new("DataModel"));

    let root_id = tree.root_ref();

    let mut iterator = XmlEventReader::from_source(source);
    let mut state = ParseState::new(&mut tree, options);

    deserialize_root(&mut iterator, &mut state, root_id)?;
    apply_referent_rewrites(&mut state);
    apply_shared_string_rewrites(&mut state);

    Ok(tree)
}

/// Describes the strategy that rbx_xml should use when deserializing
/// properties.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DecodePropertyBehavior {
    /// Ignores properties that aren't known by rbx_xml.
    ///
    /// The default and safest option. With this set, properties that are newer
    /// than the reflection database rbx_xml uses won't show up when
    /// deserializing files.
    IgnoreUnknown,

    /// Read properties that aren't known by rbx_xml.
    ///
    /// With this option set, properties that are newer than rbx_xml's
    /// reflection database will show up. It may be problematic to depend on
    /// these properties, since rbx_xml may start supporting them with
    /// non-reflection specific names at a future date.
    ReadUnknown,

    /// Returns an error if any properties are found that aren't known by
    /// rbx_xml.
    ErrorOnUnknown,

    /// Completely turns off rbx_xml's reflection database. Property names and
    /// types will appear exactly as they are in XML.
    ///
    /// This setting is useful for debugging the model format. It leaves the
    /// user to deal with oddities like how `Part.FormFactor` is actually
    /// serialized as `Part.formFactorRaw`.
    NoReflection,
}

/// Options available for deserializing an XML-format model or place.
#[derive(Debug, Clone)]
pub struct DecodeOptions {
    property_behavior: DecodePropertyBehavior,
}

impl DecodeOptions {
    /// Constructs a `DecodeOptions` with all values set to their defaults.
    #[inline]
    pub fn new() -> Self {
        DecodeOptions {
            property_behavior: DecodePropertyBehavior::IgnoreUnknown,
        }
    }

    /// Determines how rbx_xml will deserialize properties, especially unknown
    /// ones.
    #[inline]
    pub fn property_behavior(self, property_behavior: DecodePropertyBehavior) -> Self {
        DecodeOptions { property_behavior }
    }

    /// A utility function to determine whether or not we should reference the
    /// reflection database at all.
    pub(crate) fn use_reflection(&self) -> bool {
        self.property_behavior != DecodePropertyBehavior::NoReflection
    }
}

impl Default for DecodeOptions {
    fn default() -> DecodeOptions {
        DecodeOptions::new()
    }
}

/// The state needed to deserialize an XML model into an `WeakDom`.
pub struct ParseState<'a> {
    tree: &'a mut WeakDom,
    options: DecodeOptions,

    /// Metadata deserialized from 'Meta' fields in the file.
    /// Known fields are:
    /// - ExplicitAutoJoints
    metadata: HashMap<String, String>,

    /// A map referent strings to IDs. This map is filled up as instances are
    /// deserialized, and referred to when filling out Ref properties.
    ///
    /// We need to do that step in two passes because it's possible for
    /// instances to refer to instances that are later in the file.
    referents_to_ids: HashMap<String, Ref>,

    /// A list of Ref property rewrites to apply. After the first
    /// deserialization pass, we enumerate over this list and fill in the
    /// correct Ref value by using the referents map.
    referent_rewrites: Vec<ReferentRewrite>,

    /// A map from shared string hashes (currently MD5, decided by Roblox) to
    /// the actual SharedString type.
    known_shared_strings: HashMap<String, SharedString>,

    /// A list of SharedString properties to set in the tree as a secondary
    /// pass. This works just like referent rewriting since the shared string
    /// dictionary is usually at the end of the XML file.
    shared_string_rewrites: Vec<SharedStringRewrite>,
}

struct ReferentRewrite {
    id: Ref,
    property_name: String,
    referent_value: String,
}

struct SharedStringRewrite {
    id: Ref,
    property_name: String,
    shared_string_hash: String,
}

impl<'a> ParseState<'a> {
    fn new(tree: &mut WeakDom, options: DecodeOptions) -> ParseState {
        ParseState {
            tree,
            options,
            metadata: HashMap::new(),
            referents_to_ids: HashMap::new(),
            referent_rewrites: Vec::new(),
            known_shared_strings: HashMap::new(),
            shared_string_rewrites: Vec::new(),
        }
    }

    /// Marks that a property on this instance needs to be rewritten once we
    /// have a complete view of how referents map to Ref values.
    ///
    /// This is used to deserialize non-null Ref values correctly.
    pub fn add_referent_rewrite(&mut self, id: Ref, property_name: String, referent_value: String) {
        self.referent_rewrites.push(ReferentRewrite {
            id,
            property_name,
            referent_value,
        });
    }

    /// Marks that a property on this instance needs to be rewritten once we
    /// have a complete view of how referents map to Ref values.
    ///
    /// This is used to deserialize non-null Ref values correctly.
    pub fn add_shared_string_rewrite(
        &mut self,
        id: Ref,
        property_name: String,
        shared_string_hash: String,
    ) {
        self.shared_string_rewrites.push(SharedStringRewrite {
            id,
            property_name,
            shared_string_hash,
        });
    }
}

fn apply_referent_rewrites(state: &mut ParseState) {
    for rewrite in &state.referent_rewrites {
        let new_value = match state.referents_to_ids.get(&rewrite.referent_value) {
            Some(id) => *id,
            None => continue,
        };

        let instance = state
            .tree
            .get_by_ref_mut(rewrite.id)
            .expect("rbx_xml bug: had ID in referent rewrite list that didn't end up in the tree");

        instance
            .properties
            .insert(rewrite.property_name.clone(), Variant::Ref(new_value));
    }
}

fn apply_shared_string_rewrites(state: &mut ParseState) {
    for rewrite in &state.shared_string_rewrites {
        let new_value = match state.known_shared_strings.get(&rewrite.shared_string_hash) {
            Some(v) => v.clone(),
            None => continue,
        };

        let instance = state.tree.get_by_ref_mut(rewrite.id).expect(
            "rbx_xml bug: had ID in SharedString rewrite list that didn't end up in the tree",
        );

        instance.properties.insert(
            rewrite.property_name.clone(),
            Variant::SharedString(new_value),
        );
    }
}

fn deserialize_root<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
    parent_id: Ref,
) -> Result<(), DecodeError> {
    match reader.expect_next()? {
        XmlReadEvent::StartDocument { .. } => {}
        _ => unreachable!(),
    }

    let doc_attributes = reader.expect_start_with_name("roblox")?;

    let mut doc_version = None;

    for attribute in doc_attributes.into_iter() {
        if attribute.name.local_name.as_str() == "version" {
            doc_version = Some(attribute.value);
        }
    }

    let doc_version =
        doc_version.ok_or_else(|| reader.error(DecodeErrorKind::MissingAttribute("version")))?;

    if doc_version != "4" {
        return Err(reader.error(DecodeErrorKind::WrongDocVersion(doc_version)));
    }

    loop {
        match reader.expect_peek()? {
            XmlReadEvent::StartElement { name, .. } => {
                match name.local_name.as_str() {
                    "Item" => {
                        deserialize_instance(reader, state, parent_id)?;
                    }
                    "External" => {
                        // This tag is always meaningless, there's nothing to do
                        // here except skip it.
                        reader.eat_unknown_tag()?;
                    }
                    "Meta" => {
                        deserialize_metadata(reader, state)?;
                    }
                    "SharedStrings" => {
                        deserialize_shared_string_dict(reader, state)?;
                    }
                    _ => {
                        let event = reader.expect_next().unwrap();
                        return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                    }
                }
            }
            XmlReadEvent::EndElement { name } => {
                if name.local_name == "roblox" {
                    reader.expect_next().unwrap();
                    break;
                } else {
                    let event = reader.expect_next().unwrap();
                    return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                }
            }
            XmlReadEvent::EndDocument => break,
            _ => {
                let event = reader.expect_next().unwrap();
                return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
            }
        }
    }

    Ok(())
}

fn deserialize_metadata<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
) -> Result<(), DecodeError> {
    let name = {
        let attributes = reader.expect_start_with_name("Meta")?;

        let mut name = None;

        for attribute in attributes.into_iter() {
            if attribute.name.local_name.as_str() == "name" {
                name = Some(attribute.value);
            }
        }

        name.ok_or_else(|| reader.error(DecodeErrorKind::MissingAttribute("name")))?
    };

    let value = reader.read_characters()?;
    reader.expect_end_with_name("Meta")?;

    state.metadata.insert(name, value);
    Ok(())
}

fn deserialize_shared_string_dict<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
) -> Result<(), DecodeError> {
    reader.expect_start_with_name("SharedStrings")?;

    loop {
        match reader.expect_peek()? {
            XmlReadEvent::StartElement { name, .. } => {
                if name.local_name == "SharedString" {
                    deserialize_shared_string(reader, state)?;
                } else {
                    let event = reader.expect_next().unwrap();
                    return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                }
            }
            XmlReadEvent::EndElement { name } => {
                if name.local_name == "SharedStrings" {
                    break;
                } else {
                    let event = reader.expect_next().unwrap();
                    return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                }
            }
            _ => {
                let event = reader.expect_next().unwrap();
                return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
            }
        }
    }

    reader.expect_end_with_name("SharedStrings")?;
    Ok(())
}

fn deserialize_shared_string<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
) -> Result<(), DecodeError> {
    let attributes = reader.expect_start_with_name("SharedString")?;

    let mut md5_hash = None;
    for attribute in attributes.into_iter() {
        if attribute.name.local_name == "md5" {
            md5_hash = Some(attribute.value);
            break;
        }
    }

    let md5_hash =
        md5_hash.ok_or_else(|| reader.error(DecodeErrorKind::MissingAttribute("md5")))?;

    let buffer = reader.read_base64_characters()?;

    let value = SharedString::new(buffer);

    state.known_shared_strings.insert(md5_hash, value);

    reader.expect_end_with_name("SharedString")?;
    Ok(())
}

fn deserialize_instance<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
    parent_id: Ref,
) -> Result<(), DecodeError> {
    let (class_name, referent) = {
        let attributes = reader.expect_start_with_name("Item")?;

        let mut class = None;
        let mut referent = None;

        for attribute in attributes.into_iter() {
            match attribute.name.local_name.as_str() {
                "class" => class = Some(attribute.value),
                "referent" => referent = Some(attribute.value),
                _ => {}
            }
        }

        let class =
            class.ok_or_else(|| reader.error(DecodeErrorKind::MissingAttribute("class")))?;

        (class, referent)
    };

    trace!("Class {} with referent {:?}", class_name, referent);

    let builder = InstanceBuilder::new(class_name);
    let instance_id = state.tree.insert(parent_id, builder);

    if let Some(referent) = referent {
        state.referents_to_ids.insert(referent, instance_id);
    }

    let mut properties: HashMap<String, Variant> = HashMap::new();

    loop {
        match reader.expect_peek()? {
            XmlReadEvent::StartElement { name, .. } => match name.local_name.as_str() {
                "Properties" => {
                    deserialize_properties(reader, state, instance_id, &mut properties)?;
                }
                "Item" => {
                    deserialize_instance(reader, state, instance_id)?;
                }
                _ => {
                    let event = reader.expect_next().unwrap();
                    return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                }
            },
            XmlReadEvent::EndElement { name } => {
                if name.local_name != "Item" {
                    let event = reader.expect_next().unwrap();
                    return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
                }

                reader.expect_next().unwrap();

                break;
            }
            _ => {
                let event = reader.expect_next().unwrap();
                return Err(reader.error(DecodeErrorKind::UnexpectedXmlEvent(event)));
            }
        }
    }

    let instance = state.tree.get_by_ref_mut(instance_id).unwrap();

    instance.name = match properties.remove("Name") {
        Some(value) => match value {
            Variant::String(value) => value,
            _ => return Err(reader.error(DecodeErrorKind::NameMustBeString(value.ty()))),
        },

        // TODO: Use reflection to get default name instead. This should only
        // matter for ValueBase instances in files created by tools other than
        // Roblox Studio.
        None => instance.class.clone(),
    };

    instance.properties = properties;

    Ok(())
}

fn deserialize_properties<R: Read>(
    reader: &mut XmlEventReader<R>,
    state: &mut ParseState,
    instance_id: Ref,
    props: &mut HashMap<String, Variant>,
) -> Result<(), DecodeError> {
    reader.expect_start_with_name("Properties")?;

    let class_name = state
        .tree
        .get_by_ref(instance_id)
        .expect("Couldn't find instance to deserialize properties into")
        .class
        .clone();

    log::trace!(
        "Deserializing properties for instance {:?}, whose ClassName is {}",
        instance_id,
        class_name
    );

    loop {
        let (xml_type_name, xml_property_name) = {
            match reader.expect_peek()? {
                XmlReadEvent::StartElement {
                    name, attributes, ..
                } => {
                    let mut xml_property_name = None;

                    for attribute in attributes {
                        if attribute.name.local_name.as_str() == "name" {
                            xml_property_name = Some(attribute.value.to_owned());
                            break;
                        }
                    }

                    let xml_property_name = match xml_property_name {
                        Some(value) => value,
                        None => return Err(reader.error(DecodeErrorKind::MissingAttribute("name"))),
                    };

                    (name.local_name.to_owned(), xml_property_name)
                }
                XmlReadEvent::EndElement { name } => {
                    if name.local_name == "Properties" {
                        reader.expect_next()?;
                        return Ok(());
                    } else {
                        let err = DecodeErrorKind::UnexpectedXmlEvent(reader.expect_next()?);
                        return Err(reader.error(err));
                    }
                }
                _ => {
                    let err = DecodeErrorKind::UnexpectedXmlEvent(reader.expect_next()?);
                    return Err(reader.error(err));
                }
            }
        };

        log::trace!(
            "Deserializing property {}.{}, of type {}",
            class_name,
            xml_property_name,
            xml_type_name
        );

        let maybe_descriptor = if state.options.use_reflection() {
            find_canonical_property_descriptor(&class_name, &xml_property_name)
        } else {
            None
        };

        if let Some(descriptor) = maybe_descriptor {
            let xml_value =
                read_value_xml(reader, state, &xml_type_name, instance_id, &descriptor.name)?;

            // The property descriptor might specify a different type than the
            // one we saw in the XML.
            //
            // This happens when property types are upgraded or if the
            // serialized data type is different than the canonical one.
            //
            // For example:
            // - Int/Float widening from 32-bit to 64-bit
            // - BrickColor properties turning into Color3
            let expected_type = match &descriptor.data_type {
                DataType::Value(data_type) => *data_type,
                DataType::Enum(_enum_name) => VariantType::Enum,

                // FIXME?
                _ => unimplemented!(),
            };

            let value = match xml_value.try_convert_ref(expected_type) {
                // In this case, the property descriptor disagreed with the type
                // in the file, but there was a conversion available.
                TodoValueConversionType::Converted(value) => value,

                // The property descriptor agreed with the type from the file,
                // or the type in the descriptor was unknown and the
                // deserializer is configured to ignore those issues
                TodoValueConversionType::Unnecessary => xml_value,

                // The property descriptor disagreed, and there was no
                // conversion available. This is always an error.
                TodoValueConversionType::Failed => {
                    return Err(
                        reader.error(DecodeErrorKind::UnsupportedPropertyConversion {
                            class_name: class_name.clone(),
                            property_name: descriptor.name.to_string(),
                            expected_type,
                            actual_type: xml_value.ty(),
                        }),
                    );
                }
            };

            props.insert(descriptor.name.to_string(), value);
        } else {
            match state.options.property_behavior {
                DecodePropertyBehavior::IgnoreUnknown => {
                    // We don't care about this property, so we can read it and
                    // throw it into the void.

                    read_value_xml(
                        reader,
                        state,
                        &xml_type_name,
                        instance_id,
                        &xml_property_name,
                    )?;
                }
                DecodePropertyBehavior::ReadUnknown | DecodePropertyBehavior::NoReflection => {
                    // We'll take this value as-is with no conversions on either
                    // the name or value.

                    let value = read_value_xml(
                        reader,
                        state,
                        &xml_type_name,
                        instance_id,
                        &xml_property_name,
                    )?;
                    props.insert(xml_property_name, value);
                }
                DecodePropertyBehavior::ErrorOnUnknown => {
                    return Err(reader.error(DecodeErrorKind::UnknownProperty {
                        class_name,
                        property_name: xml_property_name,
                    }));
                }
            }
        }
    }
}