sway_core/language/ty/declaration/
struct.rs

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
use std::{
    cmp::Ordering,
    hash::{Hash, Hasher},
};

use monomorphization::MonomorphizeHelper;
use sway_types::{Ident, Named, Span, Spanned};

use crate::{
    engine_threading::*,
    error::module_can_be_changed,
    has_changes,
    language::{parsed::StructDeclaration, CallPath, Visibility},
    transform,
    type_system::*,
    Namespace,
};

use super::TyDeclParsedType;

#[derive(Clone, Debug)]
pub struct TyStructDecl {
    pub call_path: CallPath,
    pub fields: Vec<TyStructField>,
    pub type_parameters: Vec<TypeParameter>,
    pub visibility: Visibility,
    pub span: Span,
    pub attributes: transform::AttributesMap,
}

impl TyDeclParsedType for TyStructDecl {
    type ParsedType = StructDeclaration;
}

impl Named for TyStructDecl {
    fn name(&self) -> &Ident {
        &self.call_path.suffix
    }
}

impl EqWithEngines for TyStructDecl {}
impl PartialEqWithEngines for TyStructDecl {
    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
        self.call_path == other.call_path
            && self.fields.eq(&other.fields, ctx)
            && self.type_parameters.eq(&other.type_parameters, ctx)
            && self.visibility == other.visibility
    }
}

impl HashWithEngines for TyStructDecl {
    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
        let TyStructDecl {
            call_path,
            fields,
            type_parameters,
            visibility,
            // these fields are not hashed because they aren't relevant/a
            // reliable source of obj v. obj distinction
            span: _,
            attributes: _,
        } = self;
        call_path.hash(state);
        fields.hash(state, engines);
        type_parameters.hash(state, engines);
        visibility.hash(state);
    }
}

impl SubstTypes for TyStructDecl {
    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
        has_changes! {
            self.fields.subst(ctx);
            self.type_parameters.subst(ctx);
        }
    }
}

impl Spanned for TyStructDecl {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

impl MonomorphizeHelper for TyStructDecl {
    fn type_parameters(&self) -> &[TypeParameter] {
        &self.type_parameters
    }

    fn name(&self) -> &Ident {
        &self.call_path.suffix
    }

    fn has_self_type_param(&self) -> bool {
        false
    }
}

impl TyStructDecl {
    /// Returns names of the [TyStructField]s of the struct `self` accessible in the given context.
    /// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
    /// the names of all fields.
    /// Suitable for error reporting.
    pub(crate) fn accessible_fields_names(&self, is_public_struct_access: bool) -> Vec<Ident> {
        TyStructField::accessible_fields_names(&self.fields, is_public_struct_access)
    }

    /// Returns [TyStructField] with the given `field_name`, or `None` if the field with the
    /// name `field_name` does not exist.
    pub(crate) fn find_field(&self, field_name: &Ident) -> Option<&TyStructField> {
        self.fields.iter().find(|field| field.name == *field_name)
    }

    /// For the given `field_name` returns the zero-based index and the type of the field
    /// within the struct memory layout, or `None` if the field with the
    /// name `field_name` does not exist.
    pub(crate) fn get_field_index_and_type(&self, field_name: &Ident) -> Option<(u64, TypeId)> {
        // TODO-MEMLAY: Warning! This implementation assumes that fields are laid out in
        //              memory in the order of their declaration.
        //              This assumption can be changed in the future.
        self.fields
            .iter()
            .enumerate()
            .find(|(_, field)| field.name == *field_name)
            .map(|(idx, field)| (idx as u64, field.type_argument.type_id))
    }

    /// Returns true if the struct `self` has at least one private field.
    pub(crate) fn has_private_fields(&self) -> bool {
        self.fields.iter().any(|field| field.is_private())
    }

    /// Returns true if the struct `self` has fields (it is not empty)
    /// and all fields are private.
    pub(crate) fn has_only_private_fields(&self) -> bool {
        !self.is_empty() && self.fields.iter().all(|field| field.is_private())
    }

    /// Returns true if the struct `self` does not have any fields.
    pub(crate) fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

/// Provides information about the struct access within a particular [Namespace].
pub struct StructAccessInfo {
    /// True if the programmer who can change the code in the [Namespace]
    /// can also change the struct declaration.
    struct_can_be_changed: bool,
    /// True if the struct access is public, i.e., outside of the module in
    /// which the struct is defined.
    is_public_struct_access: bool,
}

impl StructAccessInfo {
    pub fn get_info(engines: &Engines, struct_decl: &TyStructDecl, namespace: &Namespace) -> Self {
        assert!(
            struct_decl.call_path.is_absolute,
            "The call path of the struct declaration must always be absolute."
        );

        let struct_can_be_changed =
            module_can_be_changed(engines, namespace, &struct_decl.call_path.prefixes);
        let is_public_struct_access =
            !namespace.module_is_submodule_of(engines, &struct_decl.call_path.prefixes, true);

        Self {
            struct_can_be_changed,
            is_public_struct_access,
        }
    }
}

impl From<StructAccessInfo> for (bool, bool) {
    /// Deconstructs `struct_access_info` into (`struct_can_be_changed`, `is_public_struct_access`)
    fn from(struct_access_info: StructAccessInfo) -> (bool, bool) {
        let StructAccessInfo {
            struct_can_be_changed,
            is_public_struct_access,
        } = struct_access_info;
        (struct_can_be_changed, is_public_struct_access)
    }
}

#[derive(Debug, Clone)]
pub struct TyStructField {
    pub visibility: Visibility,
    pub name: Ident,
    pub span: Span,
    pub type_argument: TypeArgument,
    pub attributes: transform::AttributesMap,
}

impl TyStructField {
    pub fn is_private(&self) -> bool {
        matches!(self.visibility, Visibility::Private)
    }

    pub fn is_public(&self) -> bool {
        matches!(self.visibility, Visibility::Public)
    }

    /// Returns [TyStructField]s from the `fields` that are accessible in the given context.
    /// If `is_public_struct_access` is true, only public fields are returned, otherwise
    /// all fields.
    pub(crate) fn accessible_fields(
        fields: &[TyStructField],
        is_public_struct_access: bool,
    ) -> impl Iterator<Item = &TyStructField> {
        fields
            .iter()
            .filter(move |field| !is_public_struct_access || field.is_public())
    }

    /// Returns names of the [TyStructField]s from the `fields` that are accessible in the given context.
    /// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
    /// the names of all fields.
    /// Suitable for error reporting.
    pub(crate) fn accessible_fields_names(
        fields: &[TyStructField],
        is_public_struct_access: bool,
    ) -> Vec<Ident> {
        Self::accessible_fields(fields, is_public_struct_access)
            .map(|field| field.name.clone())
            .collect()
    }
}

impl Spanned for TyStructField {
    fn span(&self) -> Span {
        self.span.clone()
    }
}

impl HashWithEngines for TyStructField {
    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
        let TyStructField {
            visibility,
            name,
            type_argument,
            // these fields are not hashed because they aren't relevant/a
            // reliable source of obj v. obj distinction
            span: _,
            attributes: _,
        } = self;
        visibility.hash(state);
        name.hash(state);
        type_argument.hash(state, engines);
    }
}

impl EqWithEngines for TyStructField {}
impl PartialEqWithEngines for TyStructField {
    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
        self.name == other.name && self.type_argument.eq(&other.type_argument, ctx)
    }
}

impl OrdWithEngines for TyStructField {
    fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
        let TyStructField {
            name: ln,
            type_argument: lta,
            // these fields are not compared because they aren't relevant for ordering
            span: _,
            attributes: _,
            visibility: _,
        } = self;
        let TyStructField {
            name: rn,
            type_argument: rta,
            // these fields are not compared because they aren't relevant for ordering
            span: _,
            attributes: _,
            visibility: _,
        } = other;
        ln.cmp(rn).then_with(|| lta.cmp(rta, ctx))
    }
}

impl SubstTypes for TyStructField {
    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
        self.type_argument.subst_inner(ctx)
    }
}