aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir/src/adt.rs
blob: 03770ed7db4ae6515b3fadfe14285fef608e15e6 (plain)
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
use std::sync::Arc;

use ra_syntax::{SmolStr, ast::{self, NameOwner, StructFlavor}};

use crate::{
    DefId, Cancelable,
    db::{HirDatabase},
    module::Module,
    ty::{Ty},
};

pub struct Struct {
    def_id: DefId,
}

impl Struct {
    pub(crate) fn new(def_id: DefId) -> Self {
        Struct { def_id }
    }

    pub fn def_id(&self) -> DefId {
        self.def_id
    }

    pub fn variant_data(&self, db: &impl HirDatabase) -> Cancelable<Arc<VariantData>> {
        Ok(db.struct_data(self.def_id)?.variant_data.clone())
    }

    pub fn struct_data(&self, db: &impl HirDatabase) -> Cancelable<Arc<StructData>> {
        Ok(db.struct_data(self.def_id)?)
    }

    pub fn name(&self, db: &impl HirDatabase) -> Cancelable<SmolStr> {
        Ok(db.struct_data(self.def_id)?.name.clone())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructData {
    name: SmolStr,
    variant_data: Arc<VariantData>,
}

impl StructData {
    pub(crate) fn new(
        db: &impl HirDatabase,
        module: &Module,
        struct_def: ast::StructDef,
    ) -> Cancelable<StructData> {
        let name = struct_def
            .name()
            .map(|n| n.text())
            .unwrap_or(SmolStr::new("[error]"));
        let variant_data = VariantData::new(db, module, struct_def.flavor())?;
        let variant_data = Arc::new(variant_data);
        Ok(StructData { name, variant_data })
    }

    pub fn name(&self) -> &SmolStr {
        &self.name
    }

    pub fn variant_data(&self) -> &Arc<VariantData> {
        &self.variant_data
    }
}

pub struct Enum {
    def_id: DefId,
}

impl Enum {
    pub(crate) fn new(def_id: DefId) -> Self {
        Enum { def_id }
    }

    pub fn def_id(&self) -> DefId {
        self.def_id
    }

    pub fn name(&self, db: &impl HirDatabase) -> Cancelable<SmolStr> {
        Ok(db.enum_data(self.def_id)?.name.clone())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumData {
    name: SmolStr,
    variants: Vec<(SmolStr, Arc<VariantData>)>,
}

impl EnumData {
    pub(crate) fn new(
        db: &impl HirDatabase,
        module: &Module,
        enum_def: ast::EnumDef,
    ) -> Cancelable<Self> {
        let name = enum_def
            .name()
            .map(|n| n.text())
            .unwrap_or(SmolStr::new("[error]"));
        let variants = if let Some(evl) = enum_def.variant_list() {
            evl.variants()
                .map(|v| {
                    Ok((
                        v.name()
                            .map(|n| n.text())
                            .unwrap_or_else(|| SmolStr::new("[error]")),
                        Arc::new(VariantData::new(db, module, v.flavor())?),
                    ))
                })
                .collect::<Cancelable<_>>()?
        } else {
            Vec::new()
        };
        Ok(EnumData { name, variants })
    }
}

/// A single field of an enum variant or struct
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructField {
    name: SmolStr,
    ty: Ty,
}

/// Fields of an enum variant or struct
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VariantData {
    Struct(Vec<StructField>),
    Tuple(Vec<StructField>),
    Unit,
}

impl VariantData {
    pub fn new(db: &impl HirDatabase, module: &Module, flavor: StructFlavor) -> Cancelable<Self> {
        Ok(match flavor {
            StructFlavor::Tuple(fl) => {
                let fields = fl
                    .fields()
                    .enumerate()
                    .map(|(i, fd)| {
                        Ok(StructField {
                            name: SmolStr::new(i.to_string()),
                            ty: Ty::new_opt(db, &module, fd.type_ref())?,
                        })
                    })
                    .collect::<Cancelable<_>>()?;
                VariantData::Tuple(fields)
            }
            StructFlavor::Named(fl) => {
                let fields = fl
                    .fields()
                    .map(|fd| {
                        Ok(StructField {
                            name: fd
                                .name()
                                .map(|n| n.text())
                                .unwrap_or_else(|| SmolStr::new("[error]")),
                            ty: Ty::new_opt(db, &module, fd.type_ref())?,
                        })
                    })
                    .collect::<Cancelable<_>>()?;
                VariantData::Struct(fields)
            }
            StructFlavor::Unit => VariantData::Unit,
        })
    }

    pub(crate) fn get_field_ty(&self, field_name: &str) -> Option<Ty> {
        self.fields().iter().find(|f| f.name == field_name).map(|f| f.ty.clone())
    }

    pub fn fields(&self) -> &[StructField] {
        match *self {
            VariantData::Struct(ref fields) | VariantData::Tuple(ref fields) => fields,
            _ => &[],
        }
    }
    pub fn is_struct(&self) -> bool {
        if let VariantData::Struct(..) = *self {
            true
        } else {
            false
        }
    }
    pub fn is_tuple(&self) -> bool {
        if let VariantData::Tuple(..) = *self {
            true
        } else {
            false
        }
    }
    pub fn is_unit(&self) -> bool {
        if let VariantData::Unit = *self {
            true
        } else {
            false
        }
    }
}