forked from stellar/rs-soroban-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathderive_spec_fn.rs
More file actions
209 lines (195 loc) · 7.57 KB
/
derive_spec_fn.rs
File metadata and controls
209 lines (195 loc) · 7.57 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
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use stellar_xdr::curr as stellar_xdr;
use stellar_xdr::{
ScSpecEntry, ScSpecFunctionInputV0, ScSpecFunctionV0, ScSpecTypeDef, ScSymbol, StringM, VecM,
WriteXdr, SCSYMBOL_LIMIT,
};
use syn::TypeReference;
use syn::{
punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Error, FnArg, Ident, Pat,
ReturnType, Type, TypePath,
};
use crate::attribute::pass_through_attr_to_gen_code;
use crate::syn_ext::ty_to_safe_ident_str;
use crate::{doc::docs_from_attrs, map_type::map_type, DEFAULT_XDR_RW_LIMITS};
#[allow(clippy::too_many_arguments)]
pub fn derive_fn_spec(
ty: &Type,
ident: &Ident,
attrs: &[Attribute],
inputs: &Punctuated<FnArg, Comma>,
output: &ReturnType,
export: bool,
) -> Result<TokenStream2, TokenStream2> {
// Collect errors as they are encountered and emit them at the end.
let mut errors = Vec::<Error>::new();
// Prepare the env input.
let env_input = inputs.first().and_then(|a| match a {
FnArg::Typed(pat_type) => {
let mut ty = &*pat_type.ty;
if let Type::Reference(TypeReference { elem, .. }) = ty {
ty = elem;
}
if let Type::Path(TypePath {
path: syn::Path { segments, .. },
..
}) = ty
{
if segments.last().map_or(false, |s| s.ident == "Env") {
Some(())
} else {
None
}
} else {
None
}
}
FnArg::Receiver(_) => None,
});
// Prepare the argument inputs.
let spec_args: Vec<_> = inputs
.iter()
.skip(if env_input.is_some() { 1 } else { 0 })
.enumerate()
.map(|(i, a)| match a {
FnArg::Typed(pat_type) => {
let name = if let Pat::Ident(pat_ident) = *pat_type.pat.clone() {
pat_ident.ident.to_string()
} else {
errors.push(Error::new(a.span(), "argument not supported"));
"".to_string()
};
// Strip any underscore prefix characters. Implementations that do not use an
// argument will prefix an underscore to the variable name to signal to the
// compiler that the developer acknowledges they will not be using the parameter.
// Keeping the underscore out of the spec ensures that the spec doesn't communicate
// implementation details and doesn't change when implementations start or stop
// using a variable in the implementation. It also ensures spec consistency between
// implementations of the same trait even if some of those implementations do not
// use all the inputs.
let name = name.trim_start_matches("_");
// If fn is a __check_auth implementation, allow the first argument,
// signature_payload of type Bytes (32 size), to be a Hash.
let allow_hash = ident == "__check_auth" && i == 0;
match map_type(&pat_type.ty, true, allow_hash) {
Ok(type_) => {
let name = name.try_into().unwrap_or_else(|_| {
const MAX: u32 = 30;
errors.push(Error::new(
a.span(),
format!("argument name too long, max length {} characters", MAX),
));
StringM::<MAX>::default()
});
ScSpecFunctionInputV0 {
doc: "".try_into().unwrap(),
name,
type_,
}
}
Err(e) => {
errors.push(e);
ScSpecFunctionInputV0 {
doc: "".try_into().unwrap(),
name: "arg".try_into().unwrap(),
type_: ScSpecTypeDef::I32,
}
}
}
}
FnArg::Receiver(_) => {
errors.push(Error::new(a.span(), "self argument not supported"));
ScSpecFunctionInputV0 {
doc: "".try_into().unwrap(),
name: "".try_into().unwrap(),
type_: ScSpecTypeDef::I32,
}
}
})
.collect();
// Prepare the output.
let spec_result = match output {
ReturnType::Type(_, ty) => vec![match map_type(ty, true, true) {
Ok(spec) => spec,
Err(e) => {
errors.push(e);
ScSpecTypeDef::I32
}
}],
ReturnType::Default => vec![],
};
// Generated code spec.
let name = &format!("{}", ident);
let spec_entry = ScSpecEntry::FunctionV0(ScSpecFunctionV0 {
doc: docs_from_attrs(attrs),
name: name.try_into().unwrap_or_else(|_| {
errors.push(Error::new(
ident.span(),
format!(
"contract function name is too long: {}, max is {}",
name.len(),
SCSYMBOL_LIMIT,
),
));
ScSymbol::default()
}),
inputs: spec_args.try_into().unwrap_or_else(|_| {
const MAX: u32 = 10;
errors.push(Error::new(
inputs.iter().nth(MAX as usize).span(),
format!(
"contract function has too many parameters, max count {} parameters",
MAX,
),
));
VecM::<_, { u32::MAX }>::default()
}),
outputs: spec_result.try_into().unwrap(),
});
let spec_xdr = spec_entry.to_xdr(DEFAULT_XDR_RW_LIMITS).unwrap();
let spec_xdr_lit = proc_macro2::Literal::byte_string(spec_xdr.as_slice());
let spec_xdr_len = spec_xdr.len();
let spec_ident = format_ident!("__SPEC_XDR_FN_{}", ident.to_string().to_uppercase());
let spec_fn_ident = format_ident!("spec_xdr_{}", ident.to_string());
// If errors have occurred, render them instead.
if !errors.is_empty() {
let compile_errors = errors.iter().map(Error::to_compile_error);
return Err(quote! { #(#compile_errors)* });
}
// Filter attributes to those that should be passed through to the generated code.
let attrs = attrs
.iter()
.filter(|attr| pass_through_attr_to_gen_code(attr))
.collect::<Vec<_>>();
let ty_str = ty_to_safe_ident_str(ty);
let hidden_mod_ident = format_ident!("__{}__{}__spec", ty_str, ident);
let exported = if export {
Some(quote! {
#[doc(hidden)]
#(#attrs)*
#[allow(non_snake_case)]
pub mod #hidden_mod_ident {
#[doc(hidden)]
#[allow(non_snake_case)]
#[allow(non_upper_case_globals)]
#(#attrs)*
#[cfg_attr(target_family = "wasm", link_section = "contractspecv0")]
pub static #spec_ident: [u8; #spec_xdr_len] = super::#ty::#spec_fn_ident();
}
})
} else {
None
};
// Generated code.
Ok(quote! {
#exported
impl #ty {
#[allow(non_snake_case)]
#(#attrs)*
pub const fn #spec_fn_ident() -> [u8; #spec_xdr_len] {
*#spec_xdr_lit
}
}
})
}