sway_core/language/ty/declaration/storage.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 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
use std::hash::{Hash, Hasher};
use sway_error::{
error::{CompileError, StructFieldUsageContext},
handler::{ErrorEmitted, Handler},
};
use sway_types::{Ident, Named, Span, Spanned};
use crate::{
engine_threading::*,
ir_generation::storage::get_storage_key_string,
language::parsed::StorageDeclaration,
transform::{self},
ty::*,
type_system::*,
Namespace,
};
#[derive(Clone, Debug)]
pub struct TyStorageDecl {
pub fields: Vec<TyStorageField>,
pub span: Span,
pub attributes: transform::AttributesMap,
pub storage_keyword: Ident,
}
impl TyDeclParsedType for TyStorageDecl {
type ParsedType = StorageDeclaration;
}
impl Named for TyStorageDecl {
fn name(&self) -> &Ident {
&self.storage_keyword
}
}
impl EqWithEngines for TyStorageDecl {}
impl PartialEqWithEngines for TyStorageDecl {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.fields.eq(&other.fields, ctx) && self.attributes == other.attributes
}
}
impl HashWithEngines for TyStorageDecl {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageDecl {
fields,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
storage_keyword: _,
} = self;
fields.hash(state, engines);
}
}
impl Spanned for TyStorageDecl {
fn span(&self) -> Span {
self.span.clone()
}
}
impl TyStorageDecl {
/// Given a path that consists of `fields`, where the first field is one of the storage fields,
/// find the type information of all the elements in the path and return it as a [TyStorageAccess].
///
/// The first element in the `fields` must be one of the storage fields.
/// The last element in the `fields` can, but must not be, a struct.
/// All the elements in between must be structs.
///
/// An error is returned if the above constraints are violated or if the access to the struct fields
/// fails. E.g, if the struct field does not exists or is an inaccessible private field.
#[allow(clippy::too_many_arguments)]
pub fn apply_storage_load(
&self,
handler: &Handler,
engines: &Engines,
namespace: &Namespace,
namespace_names: &[Ident],
fields: &[Ident],
storage_fields: &[TyStorageField],
storage_keyword_span: Span,
) -> Result<(TyStorageAccess, TypeId), ErrorEmitted> {
let type_engine = engines.te();
let decl_engine = engines.de();
// The resulting storage access descriptors, built on the go as we move through the `fields`.
let mut access_descriptors = vec![];
// The field we've analyzed before the current field we are on, and its type id.
let mut previous_field: &Ident;
let mut previous_field_type_id: TypeId;
let (first_field, remaining_fields) = fields.split_first().expect(
"Having at least one element in the storage load is guaranteed by the grammar.",
);
let (initial_field_type, initial_field_key, initial_field_name) =
match storage_fields.iter().find(|sf| {
&sf.name == first_field
&& sf.namespace_names.len() == namespace_names.len()
&& sf
.namespace_names
.iter()
.zip(namespace_names.iter())
.all(|(n1, n2)| n1 == n2)
}) {
Some(TyStorageField {
type_argument,
key_expression,
name,
..
}) => (type_argument.type_id, key_expression, name),
None => {
return Err(handler.emit_err(CompileError::StorageFieldDoesNotExist {
field_name: first_field.into(),
available_fields: storage_fields
.iter()
.map(|sf| (sf.namespace_names.clone(), sf.name.clone()))
.collect(),
storage_decl_span: self.span(),
}));
}
};
access_descriptors.push(TyStorageAccessDescriptor {
name: first_field.clone(),
type_id: initial_field_type,
span: first_field.span(),
});
previous_field = first_field;
previous_field_type_id = initial_field_type;
// Storage cannot contain references, so there is no need for checking
// if the declaration is a reference to a struct. References can still
// be erroneously declared in the storage, and the type behind a concrete
// field access might be a reference to struct, but we do not treat that
// as a special case but just another one "not a struct".
// The FieldAccessOnNonStruct error message will explain that in the case
// of storage access, fields can be accessed only on structs.
let get_struct_decl = |type_id: TypeId| match &*type_engine.get(type_id) {
TypeInfo::Struct(decl_ref) => Some(decl_engine.get_struct(decl_ref)),
_ => None,
};
let mut struct_field_names = vec![];
for field in remaining_fields {
match get_struct_decl(previous_field_type_id) {
Some(struct_decl) => {
let (struct_can_be_changed, is_public_struct_access) =
StructAccessInfo::get_info(engines, &struct_decl, namespace).into();
match struct_decl.find_field(field) {
Some(struct_field) => {
if is_public_struct_access && struct_field.is_private() {
return Err(handler.emit_err(CompileError::StructFieldIsPrivate {
field_name: field.into(),
struct_name: struct_decl.call_path.suffix.clone(),
field_decl_span: struct_field.name.span(),
struct_can_be_changed,
usage_context: StructFieldUsageContext::StorageAccess,
}));
}
// Everything is fine. Push the storage access descriptor and move to the next field.
let current_field_type_id = struct_field.type_argument.type_id;
access_descriptors.push(TyStorageAccessDescriptor {
name: field.clone(),
type_id: current_field_type_id,
span: field.span(),
});
struct_field_names.push(field.as_str().to_string());
previous_field = field;
previous_field_type_id = current_field_type_id;
}
None => {
// Since storage cannot be passed to other modules, the access
// is always in the module of the storage declaration.
// If the struct cannot be instantiated in this module at all,
// we will just show the error, without any additional help lines
// showing available fields or anything.
// Note that if the struct is empty it can always be instantiated.
let struct_can_be_instantiated =
!is_public_struct_access || !struct_decl.has_private_fields();
let available_fields = if struct_can_be_instantiated {
struct_decl.accessible_fields_names(is_public_struct_access)
} else {
vec![]
};
return Err(handler.emit_err(CompileError::StructFieldDoesNotExist {
field_name: field.into(),
available_fields,
is_public_struct_access,
struct_name: struct_decl.call_path.suffix.clone(),
struct_decl_span: struct_decl.span(),
struct_is_empty: struct_decl.is_empty(),
usage_context: StructFieldUsageContext::StorageAccess,
}));
}
}
}
None => {
return Err(handler.emit_err(CompileError::FieldAccessOnNonStruct {
actually: engines.help_out(previous_field_type_id).to_string(),
storage_variable: Some(previous_field.to_string()),
field_name: field.into(),
span: previous_field.span(),
}))
}
};
}
let return_type = access_descriptors[access_descriptors.len() - 1].type_id;
Ok((
TyStorageAccess {
fields: access_descriptors,
key_expression: initial_field_key.clone().map(Box::new),
storage_field_names: namespace_names
.iter()
.map(|n| n.as_str().to_string())
.chain(vec![initial_field_name.as_str().to_string()])
.collect(),
struct_field_names,
storage_keyword_span,
},
return_type,
))
}
}
impl Spanned for TyStorageField {
fn span(&self) -> Span {
self.span.clone()
}
}
#[derive(Clone, Debug)]
pub struct TyStorageField {
pub name: Ident,
pub namespace_names: Vec<Ident>,
pub key_expression: Option<TyExpression>,
pub type_argument: TypeArgument,
pub initializer: TyExpression,
pub(crate) span: Span,
pub attributes: transform::AttributesMap,
}
impl TyStorageField {
/// Returns the full name of the [TyStorageField], consisting
/// of its name preceded by its full namespace path.
/// E.g., "storage::ns1::ns1.name".
pub fn full_name(&self) -> String {
get_storage_key_string(
&self
.namespace_names
.iter()
.map(|i| i.as_str().to_string())
.chain(vec![self.name.as_str().to_string()])
.collect::<Vec<_>>(),
)
}
}
impl EqWithEngines for TyStorageField {}
impl PartialEqWithEngines for TyStorageField {
fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
self.name == other.name
&& self.namespace_names.eq(&other.namespace_names)
&& self.type_argument.eq(&other.type_argument, ctx)
&& self.initializer.eq(&other.initializer, ctx)
}
}
impl HashWithEngines for TyStorageField {
fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
let TyStorageField {
name,
namespace_names,
key_expression,
type_argument,
initializer,
// these fields are not hashed because they aren't relevant/a
// reliable source of obj v. obj distinction
span: _,
attributes: _,
} = self;
name.hash(state);
namespace_names.hash(state);
key_expression.hash(state, engines);
type_argument.hash(state, engines);
initializer.hash(state, engines);
}
}