sway_core/language/ty/declaration/
struct.rs

1use crate::{
2    decl_engine::MaterializeConstGenerics,
3    engine_threading::*,
4    error::module_can_be_changed,
5    has_changes,
6    language::{
7        parsed::StructDeclaration, ty::TyDeclParsedType, CallPath, CallPathType, Visibility,
8    },
9    transform,
10    type_system::*,
11    Namespace,
12};
13use ast_elements::type_parameter::ConstGenericExpr;
14use monomorphization::MonomorphizeHelper;
15use serde::{Deserialize, Serialize};
16use std::{
17    cmp::Ordering,
18    hash::{Hash, Hasher},
19};
20use sway_error::handler::{ErrorEmitted, Handler};
21use sway_types::{Ident, Named, Span, Spanned};
22
23#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct TyStructDecl {
25    pub call_path: CallPath,
26    pub fields: Vec<TyStructField>,
27    pub generic_parameters: Vec<TypeParameter>,
28    pub visibility: Visibility,
29    pub span: Span,
30    pub attributes: transform::Attributes,
31}
32
33impl TyDeclParsedType for TyStructDecl {
34    type ParsedType = StructDeclaration;
35}
36
37impl Named for TyStructDecl {
38    fn name(&self) -> &Ident {
39        &self.call_path.suffix
40    }
41}
42
43impl EqWithEngines for TyStructDecl {}
44impl PartialEqWithEngines for TyStructDecl {
45    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
46        self.call_path == other.call_path
47            && self.fields.eq(&other.fields, ctx)
48            && self.generic_parameters.eq(&other.generic_parameters, ctx)
49            && self.visibility == other.visibility
50    }
51}
52
53impl HashWithEngines for TyStructDecl {
54    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
55        let TyStructDecl {
56            call_path,
57            fields,
58            generic_parameters: type_parameters,
59            visibility,
60            // these fields are not hashed because they aren't relevant/a
61            // reliable source of obj v. obj distinction
62            span: _,
63            attributes: _,
64        } = self;
65        call_path.hash(state);
66        fields.hash(state, engines);
67        type_parameters.hash(state, engines);
68        visibility.hash(state);
69    }
70}
71
72impl SubstTypes for TyStructDecl {
73    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
74        has_changes! {
75            self.fields.subst(ctx);
76            self.generic_parameters.subst(ctx);
77        }
78    }
79}
80
81impl Spanned for TyStructDecl {
82    fn span(&self) -> Span {
83        self.span.clone()
84    }
85}
86
87impl MonomorphizeHelper for TyStructDecl {
88    fn type_parameters(&self) -> &[TypeParameter] {
89        &self.generic_parameters
90    }
91
92    fn name(&self) -> &Ident {
93        &self.call_path.suffix
94    }
95
96    fn has_self_type_param(&self) -> bool {
97        false
98    }
99}
100
101impl MaterializeConstGenerics for TyStructDecl {
102    fn materialize_const_generics(
103        &mut self,
104        _engines: &Engines,
105        _handler: &Handler,
106        _name: &str,
107        _value: &crate::language::ty::TyExpression,
108    ) -> Result<(), ErrorEmitted> {
109        for p in self.generic_parameters.iter_mut() {
110            match p {
111                TypeParameter::Const(p) if p.name.as_str() == _name => {
112                    p.expr = Some(ConstGenericExpr::from_ty_expression(_handler, _value)?);
113                }
114                _ => {}
115            }
116        }
117        Ok(())
118    }
119}
120
121impl TyStructDecl {
122    /// Returns names of the [TyStructField]s of the struct `self` accessible in the given context.
123    /// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
124    /// the names of all fields.
125    /// Suitable for error reporting.
126    pub(crate) fn accessible_fields_names(&self, is_public_struct_access: bool) -> Vec<Ident> {
127        TyStructField::accessible_fields_names(&self.fields, is_public_struct_access)
128    }
129
130    /// Returns [TyStructField] with the given `field_name`, or `None` if the field with the
131    /// name `field_name` does not exist.
132    pub(crate) fn find_field(&self, field_name: &Ident) -> Option<&TyStructField> {
133        self.fields.iter().find(|field| field.name == *field_name)
134    }
135
136    /// For the given `field_name` returns the zero-based index and the type of the field
137    /// within the struct memory layout, or `None` if the field with the
138    /// name `field_name` does not exist.
139    pub(crate) fn get_field_index_and_type(&self, field_name: &Ident) -> Option<(u64, TypeId)> {
140        // TODO-MEMLAY: Warning! This implementation assumes that fields are laid out in
141        //              memory in the order of their declaration.
142        //              This assumption can be changed in the future.
143        self.fields
144            .iter()
145            .enumerate()
146            .find(|(_, field)| field.name == *field_name)
147            .map(|(idx, field)| (idx as u64, field.type_argument.type_id()))
148    }
149
150    /// Returns true if the struct `self` has at least one private field.
151    pub(crate) fn has_private_fields(&self) -> bool {
152        self.fields.iter().any(|field| field.is_private())
153    }
154
155    /// Returns true if the struct `self` has fields (it is not empty)
156    /// and all fields are private.
157    pub(crate) fn has_only_private_fields(&self) -> bool {
158        !self.is_empty() && self.fields.iter().all(|field| field.is_private())
159    }
160
161    /// Returns true if the struct `self` does not have any fields.
162    pub(crate) fn is_empty(&self) -> bool {
163        self.fields.is_empty()
164    }
165}
166
167/// Provides information about the struct access within a particular [Namespace].
168pub struct StructAccessInfo {
169    /// True if the programmer who can change the code in the [Namespace]
170    /// can also change the struct declaration.
171    struct_can_be_changed: bool,
172    /// True if the struct access is public, i.e., outside of the module in
173    /// which the struct is defined.
174    is_public_struct_access: bool,
175}
176
177impl StructAccessInfo {
178    pub fn get_info(engines: &Engines, struct_decl: &TyStructDecl, namespace: &Namespace) -> Self {
179        assert!(
180            matches!(struct_decl.call_path.callpath_type, CallPathType::Full),
181            "The call path of the struct declaration must always be fully resolved."
182        );
183
184        let struct_can_be_changed =
185            module_can_be_changed(engines, namespace, &struct_decl.call_path.prefixes);
186        let is_public_struct_access =
187            !namespace.module_is_submodule_of(&struct_decl.call_path.prefixes, true);
188
189        Self {
190            struct_can_be_changed,
191            is_public_struct_access,
192        }
193    }
194}
195
196impl From<StructAccessInfo> for (bool, bool) {
197    /// Deconstructs `struct_access_info` into (`struct_can_be_changed`, `is_public_struct_access`)
198    fn from(struct_access_info: StructAccessInfo) -> (bool, bool) {
199        let StructAccessInfo {
200            struct_can_be_changed,
201            is_public_struct_access,
202        } = struct_access_info;
203        (struct_can_be_changed, is_public_struct_access)
204    }
205}
206
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct TyStructField {
209    pub visibility: Visibility,
210    pub name: Ident,
211    pub span: Span,
212    pub type_argument: GenericArgument,
213    pub attributes: transform::Attributes,
214}
215
216impl TyStructField {
217    pub fn is_private(&self) -> bool {
218        matches!(self.visibility, Visibility::Private)
219    }
220
221    pub fn is_public(&self) -> bool {
222        matches!(self.visibility, Visibility::Public)
223    }
224
225    /// Returns [TyStructField]s from the `fields` that are accessible in the given context.
226    /// If `is_public_struct_access` is true, only public fields are returned, otherwise
227    /// all fields.
228    pub(crate) fn accessible_fields(
229        fields: &[TyStructField],
230        is_public_struct_access: bool,
231    ) -> impl Iterator<Item = &TyStructField> {
232        fields
233            .iter()
234            .filter(move |field| !is_public_struct_access || field.is_public())
235    }
236
237    /// Returns names of the [TyStructField]s from the `fields` that are accessible in the given context.
238    /// If `is_public_struct_access` is true, only the names of the public fields are returned, otherwise
239    /// the names of all fields.
240    /// Suitable for error reporting.
241    pub(crate) fn accessible_fields_names(
242        fields: &[TyStructField],
243        is_public_struct_access: bool,
244    ) -> Vec<Ident> {
245        Self::accessible_fields(fields, is_public_struct_access)
246            .map(|field| field.name.clone())
247            .collect()
248    }
249}
250
251impl Spanned for TyStructField {
252    fn span(&self) -> Span {
253        self.span.clone()
254    }
255}
256
257impl HashWithEngines for TyStructField {
258    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
259        let TyStructField {
260            visibility,
261            name,
262            type_argument,
263            // these fields are not hashed because they aren't relevant/a
264            // reliable source of obj v. obj distinction
265            span: _,
266            attributes: _,
267        } = self;
268        visibility.hash(state);
269        name.hash(state);
270        type_argument.hash(state, engines);
271    }
272}
273
274impl EqWithEngines for TyStructField {}
275impl PartialEqWithEngines for TyStructField {
276    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
277        self.name == other.name && self.type_argument.eq(&other.type_argument, ctx)
278    }
279}
280
281impl OrdWithEngines for TyStructField {
282    fn cmp(&self, other: &Self, ctx: &OrdWithEnginesContext) -> Ordering {
283        let TyStructField {
284            name: ln,
285            type_argument: lta,
286            // these fields are not compared because they aren't relevant for ordering
287            span: _,
288            attributes: _,
289            visibility: _,
290        } = self;
291        let TyStructField {
292            name: rn,
293            type_argument: rta,
294            // these fields are not compared because they aren't relevant for ordering
295            span: _,
296            attributes: _,
297            visibility: _,
298        } = other;
299        ln.cmp(rn).then_with(|| lta.cmp(rta, ctx))
300    }
301}
302
303impl SubstTypes for TyStructField {
304    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
305        self.type_argument.subst_inner(ctx)
306    }
307}