Skip to main content

xidl_parser/hir/
struct_dcl.rs

1use super::*;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Serialize, Deserialize, Clone)]
5pub struct StructForwardDcl {
6    pub annotations: Vec<Annotation>,
7    pub ident: String,
8}
9
10#[derive(Debug, Serialize, Deserialize, Clone)]
11pub struct StructDcl {
12    pub annotations: Vec<Annotation>,
13    pub ident: String,
14    pub parent: Vec<ScopedName>,
15    pub member: Vec<Member>,
16}
17
18#[derive(Debug, Serialize, Deserialize, Clone)]
19pub struct Member {
20    pub annotations: Vec<Annotation>,
21    pub ty: TypeSpec,
22    pub ident: Vec<Declarator>,
23    pub default: Option<Default>,
24    pub field_id: Option<u32>,
25    pub recursive: bool,
26}
27
28#[derive(Debug, Serialize, Deserialize, Clone)]
29pub struct Default(pub ConstExpr);
30
31impl Member {
32    pub fn is_optional(&self) -> bool {
33        self.annotations.iter().any(|annotation| match annotation {
34            Annotation::Optional { .. } => true,
35            Annotation::ScopedName { name, .. } => name
36                .name
37                .last()
38                .map(|value| value.eq_ignore_ascii_case("optional"))
39                .unwrap_or(false),
40            _ => false,
41        })
42    }
43}
44
45impl From<crate::typed_ast::StructDef> for StructDcl {
46    fn from(value: crate::typed_ast::StructDef) -> Self {
47        let mut members = value
48            .member
49            .into_iter()
50            .map(Into::into)
51            .collect::<Vec<Member>>();
52        for (index, member) in members.iter_mut().enumerate() {
53            if member.field_id.is_none() {
54                member.field_id = Some((index + 1) as u32);
55            }
56        }
57        Self {
58            annotations: vec![],
59            ident: value.ident.0,
60            parent: value.parent.into_iter().map(Into::into).collect(),
61            member: members,
62        }
63    }
64}
65
66impl From<crate::typed_ast::Member> for Member {
67    fn from(value: crate::typed_ast::Member) -> Self {
68        let annotations = expand_annotations(value.annotations);
69        let field_id = annotation_id_value(&annotations);
70        Self {
71            annotations,
72            ty: value.ty.into(),
73            ident: value.ident.0.into_iter().map(Into::into).collect(),
74            default: value.default.map(Into::into),
75            field_id,
76            recursive: false,
77        }
78    }
79}
80
81impl From<crate::typed_ast::StructForwardDcl> for StructForwardDcl {
82    fn from(typed_ast: crate::typed_ast::StructForwardDcl) -> Self {
83        Self {
84            annotations: vec![],
85            ident: typed_ast.ident.0,
86        }
87    }
88}
89
90impl From<crate::typed_ast::Default> for Default {
91    fn from(value: crate::typed_ast::Default) -> Self {
92        Self(value.0.into())
93    }
94}