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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! ink! 5.0 host function related migrations.
use ink_analyzer_ir::ast;
use ink_analyzer_ir::ast::AstNode;
use ink_analyzer_ir::syntax::SyntaxNode;
use ink_analyzer_ir::{InkEntity, InkFile};
use super::common;
use super::traversal::{walk_call, walk_method_call, Visitor};
use crate::{resolution, TextEdit};
/// Computes text edits for ink! 5.0 host function related migrations.
pub fn migrate(results: &mut Vec<TextEdit>, file: &InkFile) {
for fn_item in file.syntax().descendants().filter_map(ast::Fn::cast) {
if let Some(body) = fn_item.body() {
let mut visitor = BodyVisitor::new();
visitor.visit_block(&body);
results.extend(visitor.results);
}
}
}
struct BodyVisitor {
results: Vec<TextEdit>,
}
impl BodyVisitor {
fn new() -> Self {
Self {
results: Vec::new(),
}
}
}
impl Visitor for BodyVisitor {
fn visit_call(&mut self, expr: &ast::CallExpr) {
// Extracts call path.
let Some(call_path) = expr.expr().and_then(|call_expr| match call_expr {
ast::Expr::PathExpr(path) => path.path(),
_ => None,
}) else {
walk_call(self, expr);
return;
};
// Handles `Self::env().instantiate_contract::<..>(..)` and `Self::env().invoke_contract::<..>(..)` calls.
let is_self_type_env_call = {
call_path
.qualifier()
.zip(
call_path
.segment()
.as_ref()
.and_then(ast::PathSegment::name_ref),
)
.is_some_and(|(qualifier, name)| {
qualifier.to_string() == "Self" && name.to_string() == "env"
})
};
if is_self_type_env_call {
chained_env_host_fn_call(&mut self.results, expr.syntax());
return;
}
// Migrate `Call::<..>::new()` to `CallV1::<..>::new()`.
let call_type_new_info =
call_path
.qualifier()
.zip(call_path.segment())
.and_then(|(qualifier, segment)| {
if segment.to_string() == "new" {
let type_path = common::last_segment_generic_args(&qualifier).and_then(
|generic_args| common::simplify_path(&qualifier, &generic_args),
);
let is_call_type = resolution::is_external_crate_item(
"Call",
type_path.as_ref().unwrap_or(&qualifier),
&["ink_env::call", "ink::env::call"],
expr.syntax(),
);
is_call_type.then_some(qualifier)
} else {
None
}
});
if let Some(call_type_path) = call_type_new_info {
let generic_args_list = common::last_segment_generic_args(&call_type_path)
.as_ref()
.map(ToString::to_string);
self.results.push(TextEdit::replace(
format!(
"ink::env::call::CallV1{}",
generic_args_list.as_deref().unwrap_or_default()
),
call_type_path.syntax().text_range(),
));
}
// Represents a `build_call::<..>(..)`, `build_create::<..>(..)`,
// `instantiate_contract::<..>(..)` or `invoke_contract::<..>(..)` call.
enum HostFnWrapper {
#[allow(dead_code)]
BuildCall(ast::Path),
#[allow(dead_code)]
BuildCreate(ast::Path),
InstantiateContract(ast::Path),
InvokeContract(ast::Path),
}
let host_fn_wrapper_path = if common::is_call_path(
&call_path,
"build_call",
&["ink_env::call", "ink::env::call"],
expr.syntax(),
) {
Some(HostFnWrapper::BuildCall(call_path))
} else if common::is_call_path(
&call_path,
"build_create",
&["ink_env::call", "ink::env::call"],
expr.syntax(),
) {
Some(HostFnWrapper::BuildCreate(call_path))
} else if common::is_call_path(
&call_path,
"instantiate_contract",
&["ink_env", "ink::env"],
expr.syntax(),
) {
Some(HostFnWrapper::InstantiateContract(call_path))
} else if common::is_call_path(
&call_path,
"invoke_contract",
&["ink_env", "ink::env"],
expr.syntax(),
) {
Some(HostFnWrapper::InvokeContract(call_path))
} else {
None
};
let Some(host_fn_wrapper_path) = host_fn_wrapper_path else {
walk_call(self, expr);
return;
};
// Migrate host function wrapper APIs.
match host_fn_wrapper_path {
// Add `.instantiate_v1(..)` to `build_create::<..>(..)`.
HostFnWrapper::BuildCreate(_) => {
self.results.push(TextEdit::insert(
".instantiate_v1()".to_owned(),
expr.syntax().text_range().end(),
));
}
// Replace `.call(..)` with `.call_v1(..)`.
HostFnWrapper::BuildCall(_) => {
let Some((_, host_fn_name_ref)) = chained_host_fn_call(
expr.syntax(),
"call",
&[
"call_type",
"call_flags",
"returns",
"exec_input",
"delegate",
"gas_limit",
"transferred_value",
"code_hash",
],
) else {
return;
};
self.results.push(TextEdit::replace(
"call_v1".to_owned(),
host_fn_name_ref.syntax().text_range(),
));
}
// Replace `instantiate_contract::<..>(..)` with `instantiate_contract_v1::<..>(..)` or
// `invoke_contract::<..>(..)` with `invoke_contract::<..>(..)`.
HostFnWrapper::InstantiateContract(ref path)
| HostFnWrapper::InvokeContract(ref path) => {
let Some(name_ref) = path.segment().as_ref().and_then(ast::PathSegment::name_ref)
else {
return;
};
self.results.push(TextEdit::replace(
format!("{name_ref}_v1"),
name_ref.syntax().text_range(),
));
}
}
fn chained_host_fn_call(
ref_node: &SyntaxNode,
name: &str,
allowed_intermediates: &[&str],
) -> Option<(ast::MethodCallExpr, ast::NameRef)> {
ref_node
.parent()
.and_then(ast::MethodCallExpr::cast)
.and_then(|method_call| {
method_call.name_ref().and_then(|method_name_ref| {
let method_name = method_name_ref.to_string();
if method_name == name {
Some((method_call, method_name_ref))
} else if allowed_intermediates.contains(&method_name.as_str()) {
chained_host_fn_call(method_call.syntax(), name, allowed_intermediates)
} else {
None
}
})
})
}
}
fn visit_method_call(&mut self, expr: &ast::MethodCallExpr) {
let is_self_env_call = expr
.receiver()
.and_then(|receiver| match receiver {
ast::Expr::PathExpr(path) => Some(path),
_ => None,
})
.is_some_and(|receiver| {
receiver.to_string() == "self"
&& expr
.name_ref()
.is_some_and(|name| name.to_string() == "env")
});
if !is_self_env_call {
walk_method_call(self, expr);
}
chained_env_host_fn_call(&mut self.results, expr.syntax());
}
}
/// Computes text edits for `Self::env()` and `self.env()` host function related migrations.
fn chained_env_host_fn_call(results: &mut Vec<TextEdit>, ref_node: &SyntaxNode) {
let Some(chained_v1_method_name) = ref_node
.parent()
.and_then(ast::MethodCallExpr::cast)
.as_ref()
.and_then(ast::MethodCallExpr::name_ref)
.filter(|method_name| {
matches!(
method_name.to_string().as_str(),
"instantiate_contract" | "invoke_contract"
)
})
else {
return;
};
results.push(TextEdit::replace(
format!("{chained_v1_method_name}_v1"),
chained_v1_method_name.syntax().text_range(),
));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::text_edits_from_fixtures;
use quote::quote;
use test_utils::quote_as_pretty_string;
#[test]
fn migrate_works() {
for (code, expected_results) in [
// build_call::<..>().call(..)
(
quote! { use ink::env::call::build_call; },
quote! {
let result = build_call::<DefaultEnvironment>()
.call(AccountId::from([0x42; 32]))
.gas_limit(5000)
.transferred_value(10)
.exec_input(
ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
.push_arg(42u8)
.push_arg(true)
.push_arg(&[0x10u8; 32]),
)
.returns::<()>()
.invoke();
},
vec![("call_v1", Some("<-call("), Some(".call"))],
),
(
quote! { use ink_env::call::build_call; },
quote! {
let result = build_call::<DefaultEnvironment>()
.call(AccountId::from([0x42; 32]))
.gas_limit(5000)
.transferred_value(10)
.exec_input(
ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
.push_arg(42u8)
.push_arg(true)
.push_arg(&[0x10u8; 32]),
)
.returns::<()>()
.invoke();
},
vec![("call_v1", Some("<-call("), Some(".call"))],
),
(
quote! {},
quote! {
let result = ink::env::call::build_call::<DefaultEnvironment>()
.call(AccountId::from([0x42; 32]))
.gas_limit(5000)
.transferred_value(10)
.exec_input(
ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
.push_arg(42u8)
.push_arg(true)
.push_arg(&[0x10u8; 32]),
)
.returns::<()>()
.invoke();
},
vec![("call_v1", Some("<-call("), Some(".call"))],
),
(
quote! { use ink::env::call; },
quote! {
let result = call::build_call::<DefaultEnvironment>()
.call(AccountId::from([0x42; 32]))
.gas_limit(5000)
.transferred_value(10)
.exec_input(
ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
.push_arg(42u8)
.push_arg(true)
.push_arg(&[0x10u8; 32]),
)
.returns::<()>()
.invoke();
},
vec![("call_v1", Some("<-call("), Some(".call"))],
),
// build_create::<..>()
(
quote! { use ink::env::call::build_create; },
quote! {
let my_contract: MyContractRef = build_create::<MyContractRef>()
.code_hash(Hash::from([0x42; 32]))
.gas_limit(4000)
.endowment(25)
.exec_input(
ExecutionInput::new(
Selector::new(ink::selector_bytes!("my_constructor"))
)
.push_arg(42)
.push_arg(true)
.push_arg(&[0x10u8; 32]),
)
.salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF])
.returns::<MyContractRef>()
.instantiate();
},
vec![(
".instantiate_v1()",
Some("<MyContractRef>()"),
Some("<MyContractRef>()"),
)],
),
// instantiate_contract::<..>()
(
quote! { use ink::env::instantiate_contract; },
quote! {
instantiate_contract::<E, ContractRef, Args, Salt, R>(params);
},
vec![(
"instantiate_contract_v1",
Some("<-instantiate_contract->"),
Some("instantiate_contract->"),
)],
),
// invoke_contract::<..>()
(
quote! { use ink::env::invoke_contract; },
quote! {
invoke_contract::<E, Args, R>(params);
},
vec![(
"invoke_contract_v1",
Some("<-invoke_contract->"),
Some("invoke_contract->"),
)],
),
// self.env().instantiate_contract::<..>()
(
quote! {},
quote! {
self.env()
.instantiate_contract(&create_params)
},
vec![(
"instantiate_contract_v1",
Some("<-instantiate_contract->"),
Some("instantiate_contract->"),
)],
),
// self.env().invoke_contract::<..>()
(
quote! {},
quote! {
self.env()
.invoke_contract(&call_params)
},
vec![(
"invoke_contract_v1",
Some("<-invoke_contract->"),
Some("invoke_contract->"),
)],
),
// Self::env().instantiate_contract::<..>()
(
quote! {},
quote! {
Self::env()
.instantiate_contract(&create_params)
},
vec![(
"instantiate_contract_v1",
Some("<-instantiate_contract->"),
Some("instantiate_contract->"),
)],
),
// Self::env().invoke_contract::<..>()
(
quote! {},
quote! {
Self::env()
.invoke_contract(&call_params)
},
vec![(
"invoke_contract_v1",
Some("<-invoke_contract->"),
Some("invoke_contract->"),
)],
),
// Call::<..>::new()
(
quote! { use ink::env::call::Call; },
quote! {
let call = Call::new(AccountId::from([0x42; 32]))
.gas_limit(5000)
.transferred_value(10);
},
vec![("ink::env::call::CallV1", Some("<-Call->"), Some("Call->"))],
),
]
.into_iter()
.flat_map(|(imports, code, expected_results)| {
[
(
quote_as_pretty_string! {
#imports
fn my_fn() {
#code
}
},
expected_results.clone(),
),
(
quote_as_pretty_string! {
#imports
fn my_fn() {
let closure = || {
#code
};
closure();
}
},
expected_results,
),
]
}) {
let mut results = Vec::new();
let file = InkFile::parse(&code);
migrate(&mut results, &file);
assert_eq!(results, text_edits_from_fixtures(&code, expected_results));
}
}
}