-
Notifications
You must be signed in to change notification settings - Fork 556
/
Copy pathstorage_access.rs
297 lines (277 loc) · 11.7 KB
/
storage_access.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
use std::sync::Arc;
use cairo_lang_defs::plugin::{DynGeneratedFileAuxData, PluginGeneratedFile, PluginResult};
use cairo_lang_semantic::plugin::TrivialPluginAuxData;
use cairo_lang_syntax::attribute::structured::{
AttributeArg, AttributeArgVariant, AttributeStructurize,
};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::helpers::QueryAttrs;
use cairo_lang_syntax::node::{ast, Terminal, TypedSyntaxNode};
use indoc::formatdoc;
/// Derive the `Store` trait for structs annotated with `derive(starknet::Store)`.
pub fn handle_struct(db: &dyn SyntaxGroup, struct_ast: ast::ItemStruct) -> PluginResult {
let mut reads_values = Vec::new();
let mut reads_values_at_offset = Vec::new();
let mut reads_fields = Vec::new();
let mut writes = Vec::new();
let mut writes_at_offset = Vec::new();
let mut sizes = Vec::new();
for (i, field) in struct_ast.members(db).elements(db).iter().enumerate() {
let field_name = field.name(db).as_syntax_node().get_text_without_trivia(db);
let field_type = field.type_clause(db).ty(db).as_syntax_node().get_text_without_trivia(db);
if i == 0 {
reads_values.push(format!(
"let {field_name} = starknet::Store::<{field_type}>::read(address_domain, base)?;"
));
reads_values_at_offset.push(format!(
"let {field_name} = \
starknet::Store::<{field_type}>::read_at_offset(address_domain, base, offset)?;"
));
} else {
let subsequent_read = format!(
"let {field_name} = \
starknet::Store::<{field_type}>::read_at_offset(address_domain, base, \
current_offset)?;"
);
reads_values.push(subsequent_read.clone());
reads_values_at_offset.push(subsequent_read);
}
if i < struct_ast.members(db).elements(db).len() - 1 {
if i == 0 {
reads_values.push(format!(
"let mut current_offset = starknet::Store::<{field_type}>::size();"
));
reads_values_at_offset.push(format!(
"let mut current_offset = offset + starknet::Store::<{field_type}>::size();"
));
} else {
let subsequent_read =
format!("current_offset += starknet::Store::<{field_type}>::size();");
reads_values.push(subsequent_read.clone());
reads_values_at_offset.push(subsequent_read);
}
}
reads_fields.push(format!("{field_name},"));
if i == 0 {
writes.push(format!(
"starknet::Store::<{field_type}>::write(address_domain, base, \
value.{field_name})?;"
));
writes_at_offset.push(format!(
"starknet::Store::<{field_type}>::write_at_offset(address_domain, base, offset, \
value.{field_name})?;"
));
} else {
let subsequent_write = format!(
"starknet::Store::<{field_type}>::write_at_offset(address_domain, base, \
current_offset, value.{field_name})?;"
);
writes.push(subsequent_write.clone());
writes_at_offset.push(subsequent_write);
}
if i < struct_ast.members(db).elements(db).len() - 1 {
if i == 0 {
writes.push(format!(
"let mut current_offset = starknet::Store::<{field_type}>::size();"
));
writes_at_offset.push(format!(
"let mut current_offset = offset + starknet::Store::<{field_type}>::size();"
));
} else {
let subsequent_write =
format!("current_offset += starknet::Store::<{field_type}>::size();");
writes.push(subsequent_write.clone());
writes_at_offset.push(subsequent_write);
}
}
sizes.push(format!("starknet::Store::<{field_type}>::size()"));
}
let sa_impl = formatdoc!(
"
impl Store{struct_name} of starknet::Store::<{struct_name}> {{
fn read(address_domain: u32, base: starknet::StorageBaseAddress) -> \
starknet::SyscallResult<{struct_name}> {{
{reads_values}
starknet::SyscallResult::Ok(
{struct_name} {{
{reads_fields}
}}
)
}}
fn write(address_domain: u32, base: starknet::StorageBaseAddress, value: \
{struct_name}) -> starknet::SyscallResult<()> {{
{writes}
starknet::SyscallResult::Ok(())
}}
fn read_at_offset(address_domain: u32, base: starknet::StorageBaseAddress, offset: u8) \
-> starknet::SyscallResult<{struct_name}> {{
{reads_values_at_offset}
starknet::SyscallResult::Ok(
{struct_name} {{
{reads_fields}
}}
)
}}
#[inline(always)]
fn write_at_offset(address_domain: u32, base: starknet::StorageBaseAddress, offset: \
u8, value: {struct_name}) -> starknet::SyscallResult<()> {{
{writes_at_offset}
starknet::SyscallResult::Ok(())
}}
#[inline(always)]
fn size() -> u8 {{
{sizes}
}}
}}",
struct_name = struct_ast.name(db).as_syntax_node().get_text_without_trivia(db),
reads_values_at_offset = reads_values_at_offset.join("\n "),
reads_values = reads_values.join("\n "),
reads_fields = reads_fields.join("\n "),
writes = writes.join("\n "),
writes_at_offset = writes_at_offset.join("\n "),
sizes = sizes.join(" +\n ")
);
let diagnostics = vec![];
PluginResult {
code: Some(PluginGeneratedFile {
name: "storage_access_impl".into(),
content: sa_impl,
aux_data: DynGeneratedFileAuxData(Arc::new(TrivialPluginAuxData {})),
}),
diagnostics,
remove_original_item: false,
}
}
/// Derive the `StorageAccess` trait for structs annotated with `derive(starknet::Store)`.
pub fn handle_enum(db: &dyn SyntaxGroup, enum_ast: ast::ItemEnum) -> PluginResult {
let enum_name = enum_ast.name(db).as_syntax_node().get_text_without_trivia(db);
let mut match_idx = Vec::new();
let mut match_idx_at_offset = Vec::new();
let mut match_value = Vec::new();
let mut match_value_at_offset = Vec::new();
let mut match_size = "".to_string();
for (i, variant) in enum_ast.variants(db).elements(db).iter().enumerate() {
let variant_name = variant.name(db).text(db);
let variant_type = match variant.type_clause(db) {
ast::OptionTypeClause::Empty(_) => "()".to_string(),
ast::OptionTypeClause::TypeClause(tc) => {
tc.ty(db).as_syntax_node().get_text_without_trivia(db)
}
};
match_idx.push(format!(
"if idx == {i} {{ \
starknet::SyscallResult::Ok(\
{enum_name}::{variant_name}(\
starknet::Store::read_at_offset(address_domain, base, 1_u8)?\
)\
) \
}}",
));
match_idx_at_offset.push(format!(
"if idx == {i} {{ \
starknet::SyscallResult::Ok(\
{enum_name}::{variant_name}(\
starknet::Store::read_at_offset(address_domain, base, offset + 1_u8)?\
)\
) \
}}",
));
match_value.push(format!(
"{enum_name}::{variant_name}(x) => {{ starknet::Store::write(address_domain, base, \
{i})?; starknet::Store::write_at_offset(address_domain, base, 1_u8, x)?; }}"
));
match_value_at_offset.push(format!(
"{enum_name}::{variant_name}(x) => {{ \
starknet::Store::write_at_offset(address_domain, base, offset, {i})?; \
starknet::Store::write_at_offset(address_domain, base, offset + 1_u8, x)?; }}"
));
if match_size.is_empty() {
match_size = format!("starknet::Store::<{variant_type}>::size()");
} else {
match_size =
format!("cmp::max(starknet::Store::<{variant_type}>::size(), {match_size})");
}
}
let sa_impl = formatdoc!(
"
impl Store{enum_name} of starknet::Store::<{enum_name}> {{
fn read(address_domain: u32, base: starknet::StorageBaseAddress) -> \
starknet::SyscallResult<{enum_name}> {{
let idx = starknet::Store::<felt252>::read(address_domain, base)?;
{match_idx}
else {{
let mut message = Default::default();
message.append('Incorrect index:');
message.append(idx);
starknet::SyscallResult::Err(message)
}}
}}
fn write(address_domain: u32, base: starknet::StorageBaseAddress, value: {enum_name}) \
-> starknet::SyscallResult<()> {{
match value {{
{match_value}
}};
starknet::SyscallResult::Ok(())
}}
fn read_at_offset(address_domain: u32, base: starknet::StorageBaseAddress, offset: u8) \
-> starknet::SyscallResult<{enum_name}> {{
let idx = starknet::Store::<felt252>::read_at_offset(address_domain, base, \
offset)?;
{match_idx_at_offset}
else {{
let mut message = Default::default();
message.append('Incorrect index:');
message.append(idx);
starknet::SyscallResult::Err(message)
}}
}}
#[inline(always)]
fn write_at_offset(address_domain: u32, base: starknet::StorageBaseAddress, offset: \
u8, value: {enum_name}) -> starknet::SyscallResult<()> {{
match value {{
{match_value_at_offset}
}};
starknet::SyscallResult::Ok(())
}}
#[inline(always)]
fn size() -> u8 {{
1_u8 + {match_size}
}}
}}",
enum_name = enum_name,
match_idx = match_idx.join("\n else "),
match_idx_at_offset = match_idx_at_offset.join("\n else "),
match_value = match_value.join(",\n "),
match_value_at_offset = match_value_at_offset.join(",\n "),
match_size = match_size
);
let diagnostics = vec![];
PluginResult {
code: Some(PluginGeneratedFile {
name: "storage_access_impl".into(),
content: sa_impl,
aux_data: DynGeneratedFileAuxData(Arc::new(TrivialPluginAuxData {})),
}),
diagnostics,
remove_original_item: false,
}
}
/// Returns true if the type should be derived as a storage_access.
pub fn derive_storage_access_needed<T: QueryAttrs>(with_attrs: &T, db: &dyn SyntaxGroup) -> bool {
with_attrs.query_attr(db, "derive").into_iter().any(|attr| {
let attr = attr.structurize(db);
for arg in &attr.args {
let AttributeArg {
variant: AttributeArgVariant::Unnamed { value: ast::Expr::Path(path), .. },
..
} = arg
else {
continue;
};
if path.as_syntax_node().get_text_without_trivia(db) == "starknet::Store" {
return true;
}
}
false
})
}