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
use crate::common::FilePosition;
use crate::idl;

use super::errors::ValidationError;
use super::fqtn::FQTN;
use super::namespace::Namespace;
use super::r#type::Type;
use super::typemap::TypeMap;

pub struct Struct {
    pub fqtn: FQTN,
    pub generics: Vec<String>,
    pub fields: Vec<Field>,
    pub position: FilePosition,
}

#[derive(Clone)]
pub struct Field {
    pub name: String,
    pub type_: Type,
    pub optional: bool,
    // FIXME add options
    pub length: (Option<i64>, Option<i64>),
    pub position: FilePosition,
}

impl Struct {
    pub(crate) fn from_idl(istruct: &idl::Struct, ns: &Namespace) -> Self {
        let fields = istruct
            .fields
            .iter()
            .map(|ifield| Field::from_idl(ifield, ns))
            .collect();
        Self {
            fqtn: FQTN::new(&istruct.name, ns),
            generics: istruct.generics.clone(),
            fields,
            position: istruct.position.clone(),
        }
    }
    pub(crate) fn resolve(&mut self, type_map: &TypeMap) -> Result<(), ValidationError> {
        for field in self.fields.iter_mut() {
            field.type_.resolve(type_map)?;
        }
        Ok(())
    }
}

impl Field {
    pub fn from_idl(ifield: &idl::Field, ns: &Namespace) -> Self {
        let mut length: (Option<i64>, Option<i64>) = (None, None);
        for option in &ifield.options {
            match (option.name.as_str(), &option.value) {
                ("length", idl::Value::Range(min, max)) => length = (*min, *max),
                (name, _) => panic!("Unsupported option: {}", name),
            }
        }
        Field {
            name: ifield.name.clone(),
            type_: Type::from_idl(&ifield.type_, ns),
            optional: ifield.optional,
            // FIXME add options
            //options: ifield.options
            length,
            position: ifield.position.clone(),
        }
    }
}