-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathsyn_ext.rs
More file actions
489 lines (453 loc) · 15.4 KB
/
syn_ext.rs
File metadata and controls
489 lines (453 loc) · 15.4 KB
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
489
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote, ToTokens};
use std::collections::HashMap;
use syn::{
parse::{Parse, ParseStream},
punctuated::Punctuated,
token::Comma,
AngleBracketedGenericArguments, Attribute, GenericArgument, LitStr, Path, PathArguments,
PathSegment, ReturnType, Signature, Token, TypePath,
};
use syn::{
spanned::Spanned, token::And, Error, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, ItemTrait,
Lifetime, Pat, PatIdent, PatType, TraitItem, TraitItemFn, Type, TypeReference, Visibility,
};
/// Gets methods from the implementation that have public visibility. For
/// methods that are inherently implemented this is methods that have a pub
/// visibility keyword. For methods that are implementing a trait the pub is
/// assumed and so all methods are returned.
pub fn impl_pub_methods(imp: &ItemImpl) -> Vec<ImplItemFn> {
imp.items
.iter()
.filter_map(|i| match i {
ImplItem::Fn(m) => Some(m.clone()),
_ => None,
})
.filter(|m| imp.trait_.is_some() || matches!(m.vis, Visibility::Public(_)))
.collect()
}
/// Gets methods from the trait.
pub fn trait_methods(imp: &ItemTrait) -> impl Iterator<Item = &TraitItemFn> {
imp.items.iter().filter_map(|i| match i {
TraitItem::Fn(m) => Some(m),
_ => None,
})
}
/// Returns the ident of the function argument, if it has one.
pub fn fn_arg_ident(arg: &FnArg) -> Result<Ident, Error> {
if let FnArg::Typed(pat_type) = arg {
if let Pat::Ident(pat_ident) = *pat_type.pat.clone() {
return Ok(pat_ident.ident);
}
}
Err(Error::new(
arg.span(),
"argument in this form is not supported, use simple named arguments only",
))
}
/// Validate that the function argument type is not a mutable reference.
///
/// Returns an error indicating that contract functions arguments cannot be a mutable reference.
/// Even though reference (&) are supported, mutable references (&mut) are not, because it is
/// semanatically confusing for a contract function to receive an external input that it looks like
/// it could mutate.
pub fn fn_arg_type_validate_no_mut(ty: &Type) -> Result<(), Error> {
match ty {
Type::Reference(TypeReference { mutability: Some(_), .. }) => {
Err(Error::new(ty.span(), "mutable references (&mut) are not supported in contract function parameters, use immutable references (&) instead"))
}
_ => Ok(()),
}
}
/// Modifies a Pat removing any 'mut' on an Ident.
pub fn pat_unwrap_mut(p: Pat) -> Pat {
match p {
Pat::Ident(PatIdent {
attrs,
by_ref,
mutability: Some(_),
ident,
subpat,
}) => Pat::Ident(PatIdent {
attrs,
by_ref,
mutability: None,
ident,
subpat,
}),
_ => p,
}
}
/// Unwraps a reference, returning the type within the reference.
///
/// If the type is not a reference, returns the type as-is.
pub fn type_unwrap_ref(t: Type) -> Type {
match t {
Type::Reference(TypeReference { elem, .. }) => *elem,
_ => t,
}
}
/// Returns a clone of the type from the FnArg, converted into an immutable reference to the type
/// with the given lifetime.
pub fn fn_arg_ref_type(arg: &FnArg, lifetime: Option<&Lifetime>) -> Result<Type, Error> {
if let FnArg::Typed(pat_type) = arg {
Ok(Type::Reference(TypeReference {
and_token: And::default(),
lifetime: lifetime.cloned(),
mutability: None,
elem: Box::new(type_unwrap_ref(*pat_type.ty.clone())),
}))
} else {
Err(Error::new(
arg.span(),
"argument in this form is not supported, use simple named arguments only",
))
}
}
/// Returns a clone of FnArg, converted into an immutable reference with the given lifetime.
/// Mutability from the ident is stripped.
pub fn fn_arg_make_ref(arg: &FnArg, lifetime: Option<&Lifetime>) -> FnArg {
if let FnArg::Typed(pat_type) = arg {
return FnArg::Typed(PatType {
attrs: pat_type.attrs.clone(),
pat: Box::new(pat_unwrap_mut(*pat_type.pat.clone())),
colon_token: pat_type.colon_token,
ty: Box::new(Type::Reference(TypeReference {
and_token: And::default(),
lifetime: lifetime.cloned(),
mutability: None,
elem: Box::new(type_unwrap_ref(*pat_type.ty.clone())),
})),
});
}
arg.clone()
}
/// Returns a clone of FnArg with the type as an Into if the arg is a typed
/// arg. Mutability from the ident is stripped.
pub fn fn_arg_make_into(arg: &FnArg) -> FnArg {
if let FnArg::Typed(pat_type) = arg {
let ty = &pat_type.ty;
return FnArg::Typed(PatType {
attrs: pat_type.attrs.clone(),
pat: Box::new(pat_unwrap_mut(*pat_type.pat.clone())),
colon_token: pat_type.colon_token,
ty: Box::new(syn::parse_quote! { impl Into<#ty> }),
});
}
arg.clone()
}
pub enum HasFnsItem {
Trait(ItemTrait),
Impl(ItemImpl),
}
impl HasFnsItem {
pub fn name(&'_ self) -> String {
match self {
HasFnsItem::Trait(t) => t.ident.to_string(),
HasFnsItem::Impl(i) => {
let ty = &i.self_ty;
quote!(#ty).to_string()
}
}
}
pub fn fns(&self) -> Vec<Fn> {
match self {
HasFnsItem::Trait(t) => trait_methods(t)
.map(|m| Fn {
ident: m.sig.ident.clone(),
attrs: m.attrs.clone(),
inputs: m.sig.inputs.clone(),
output: m.sig.output.clone(),
})
.collect(),
HasFnsItem::Impl(i) => impl_pub_methods(i)
.iter()
.map(|m| Fn {
ident: m.sig.ident.clone(),
attrs: m.attrs.clone(),
inputs: m.sig.inputs.clone(),
output: m.sig.output.clone(),
})
.collect(),
}
}
}
impl Parse for HasFnsItem {
fn parse(input: ParseStream) -> syn::Result<Self> {
_ = input.call(Attribute::parse_outer);
_ = input.parse::<Token![pub]>();
let lookahead = input.lookahead1();
if lookahead.peek(Token![trait]) {
let t = input.parse()?;
Ok(HasFnsItem::Trait(t))
} else if lookahead.peek(Token![impl]) {
let mut imp = input.parse()?;
flatten_associated_items_in_impl_fns(&mut imp)?;
Ok(HasFnsItem::Impl(imp))
} else {
Err(lookahead.error())
}
}
}
impl ToTokens for HasFnsItem {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
HasFnsItem::Trait(t) => t.to_tokens(tokens),
HasFnsItem::Impl(i) => i.to_tokens(tokens),
}
}
}
pub struct Fn {
pub ident: Ident,
pub attrs: Vec<Attribute>,
pub inputs: Punctuated<FnArg, Comma>,
pub output: ReturnType,
}
impl Fn {
pub fn output(&self) -> Type {
let t = match &self.output {
ReturnType::Default => quote!(()),
ReturnType::Type(_, typ) => match unpack_result(typ) {
Some((t, _)) => quote!(#t),
None => quote!(#typ),
},
};
Type::Verbatim(t)
}
pub fn try_output(&self, crate_path: &Path) -> Type {
let (t, e) = match &self.output {
ReturnType::Default => (quote!(()), quote!(#crate_path::Error)),
ReturnType::Type(_, typ) => match unpack_result(typ) {
Some((t, e)) => (quote!(#t), quote!(#e)),
None => (quote!(#typ), quote!(#crate_path::Error)),
},
};
Type::Verbatim(quote! {
Result<
Result<#t, <#t as #crate_path::TryFromVal<#crate_path::Env, #crate_path::Val>>::Error>,
Result<#e, #crate_path::InvokeError>
>
})
}
}
impl From<&ImplItemFn> for Fn {
fn from(m: &ImplItemFn) -> Self {
Self {
ident: m.sig.ident.clone(),
attrs: m.attrs.clone(),
inputs: m.sig.inputs.clone(),
output: m.sig.output.clone(),
}
}
}
impl Parse for Fn {
fn parse(input: ParseStream) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let sig: Signature = input.parse()?;
Ok(Fn {
ident: sig.ident.clone(),
attrs,
inputs: sig.inputs.clone(),
output: sig.output.clone(),
})
}
}
/// Converts a Vec<LitStr> containing "attrs + signature" strings into Vec<Fn>.
pub fn strs_to_fns(fn_strs: &[LitStr]) -> Result<Vec<Fn>, Error> {
fn_strs
.iter()
.map(|f| {
syn::parse_str::<Fn>(&f.value())
.map_err(|e| Error::new(f.span(), format!("failed to parse function: {e}")))
})
.collect()
}
fn unpack_result(typ: &Type) -> Option<(Type, Type)> {
match &typ {
Type::Path(TypePath { path, .. }) => {
if let Some(PathSegment {
ident,
arguments:
PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }),
}) = path.segments.last()
{
let args = args.iter().collect::<Vec<_>>();
match (&ident.to_string()[..], args.as_slice()) {
("Result", [GenericArgument::Type(t), GenericArgument::Type(e)]) => {
Some((t.clone(), e.clone()))
}
_ => None,
}
} else {
None
}
}
_ => None,
}
}
fn flatten_associated_items_in_impl_fns(imp: &mut ItemImpl) -> Result<(), Error> {
// TODO: Flatten associated consts used in functions.
// Flatten associated types used in functions.
let associated_types: HashMap<Ident, Type> = imp
.items
.iter()
.filter_map(|item| match item {
ImplItem::Type(i) => Some((i.ident.clone(), i.ty.clone())),
_ => None,
})
.collect();
// Resolve Self::* in function input types and return types.
for item in imp.items.iter_mut() {
if let ImplItem::Fn(f) = item {
for input in f.sig.inputs.iter_mut() {
if let FnArg::Typed(t) = input {
if let Some(resolved) = resolve_self_type(&t.ty, &associated_types) {
*t.ty = resolved;
}
}
}
if let ReturnType::Type(_, ty) = &mut f.sig.output {
if let Some(resolved) = resolve_self_type(ty, &associated_types) {
**ty = resolved;
}
}
}
}
// Check for any remaining unresolved Self::* types in fn signatures.
for item in imp.items.iter() {
if let ImplItem::Fn(f) = item {
for input in f.sig.inputs.iter() {
if let FnArg::Typed(t) = input {
if let Some(ident) = self_type_ident(&t.ty) {
return Err(Error::new(
t.ty.span(),
format!(
"unresolved associated type `Self::{ident}` in function \
parameter; use a concrete type instead"
),
));
}
}
}
if let ReturnType::Type(_, ty) = &f.sig.output {
if let Some(ident) = self_type_ident(ty) {
return Err(Error::new(
ty.span(),
format!(
"unresolved associated type `Self::{ident}` in return type; \
use a concrete type instead"
),
));
}
}
}
}
Ok(())
}
/// If the type is `Self::Ident` and `Ident` exists in `associated_types`,
/// return the resolved type. Otherwise return `None`.
fn resolve_self_type(ty: &Type, associated_types: &HashMap<Ident, Type>) -> Option<Type> {
match self_type_ident(ty) {
Some(ident) => associated_types.get(ident).cloned(),
None => None,
}
}
/// If the type is `Self::Ident`, return the `Ident`. Otherwise return `None`.
fn self_type_ident(ty: &Type) -> Option<&Ident> {
if let Type::Path(TypePath { qself: None, path }) = ty {
let segments = &path.segments;
if segments.len() == 2
&& segments.first() == Some(&PathSegment::from(format_ident!("Self")))
{
if let Some(PathSegment {
arguments: PathArguments::None,
ident,
}) = segments.get(1)
{
return Some(ident);
}
}
}
None
}
pub fn ty_to_safe_ident_str(ty: &Type) -> String {
quote!(#ty).to_string().replace(' ', "").replace(':', "_")
}
pub fn ident_to_type(ident: Ident) -> Type {
Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: None,
segments: Punctuated::from_iter([PathSegment {
ident,
arguments: PathArguments::None,
}]),
},
})
}
/// Converts a path for use inside a declarative macro_rules.
///
/// If the first segment of the path is `crate`, converts it to `$crate`, otherwise returns the
/// path unaltered.
///
/// The return value is a TokenStream because while $crate is a special token that acts as a path
/// in a macro_rules it is not a valid identifier and syn's Ident type, used in Path, does not
/// permit it.
pub fn path_in_macro_rules(p: &Path) -> TokenStream {
let leading_colon = &p.leading_colon;
let mut segments = p.segments.iter();
let first = segments.next();
if leading_colon == &None
&& first
== Some(&PathSegment {
ident: Ident::new("crate", Span::call_site()),
arguments: PathArguments::None,
})
{
quote! { $crate #(::#segments)* }
} else {
quote! { #leading_colon #first #(::#segments)* }
}
}
#[cfg(test)]
mod test_path_in_macro_rules {
use crate::syn_ext::*;
use quote::quote;
use syn::parse2;
fn assert_paths_eq(input: TokenStream, expected: TokenStream) {
assert_eq!(
path_in_macro_rules(&parse2(input).unwrap()).to_string(),
expected.to_string(),
);
}
#[test]
fn test_unaltered_paths() {
let input = quote!(path::to::module);
let expected = quote!(path::to::module);
assert_paths_eq(input, expected);
}
#[test]
fn test_unaltered_global_paths() {
let input = quote!(::path::to::module);
let expected = quote!(::path::to::module);
assert_paths_eq(input, expected);
}
#[test]
fn test_crate() {
let input = quote!(crate);
let expected = quote!($crate);
assert_paths_eq(input, expected);
}
#[test]
fn test_crate_with_path() {
let input = quote!(crate::path::to);
let expected = quote!($crate::path::to);
assert_paths_eq(input, expected);
}
#[test]
fn test_crate_with_invalid_global() {
let input = quote!(::crate);
let expected = quote!(::crate);
assert_paths_eq(input, expected);
}
}