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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2019-2022 Moonsong Labs.
// Copyright (c) 2023 Parity Technologies (UK) Ltd.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::*;

impl Precompile {
	/// Main expand function, which expands everything else.
	pub fn expand(&self) -> impl ToTokens {
		let enum_ = self.expand_enum_decl();
		let enum_impl = self.expand_enum_impl();
		let precomp_impl = self.expand_precompile_impl();
		let test_signature = self.expand_test_solidity_signature();

		quote! {
			#enum_
			#enum_impl
			#precomp_impl
			#test_signature
		}
	}

	/// Expands the call enum declaration.
	pub fn expand_enum_decl(&self) -> impl ToTokens {
		let enum_ident = &self.enum_ident;
		let (_impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

		let type_parameters = self.generics.type_params().map(|p| &p.ident);

		let variants: Vec<_> = self.variants_content.keys().collect();
		let idents: Vec<Vec<_>> = self
			.variants_content
			.values()
			.map(|v| v.arguments.iter().map(|a| &a.ident).collect())
			.collect();
		let types: Vec<Vec<_>> = self
			.variants_content
			.values()
			.map(|v| v.arguments.iter().map(|a| &a.ty).collect())
			.collect();

		quote!(
			#[allow(non_camel_case_types)]
			pub enum #enum_ident #ty_generics #where_clause {
				#(
					#variants {
						#(
							#idents: #types
						),*
					},
				)*

				#[doc(hidden)]
				__phantom(
					::core::marker::PhantomData<( #( #type_parameters ),* )>,
					::core::convert::Infallible
				),
			}
		)
	}

	/// Expands the parse function for each variants.
	pub fn expand_variants_parse_fn(&self) -> impl ToTokens {
		let span = Span::call_site();

		let fn_parse = self
			.variants_content
			.keys()
			.map(Self::variant_ident_to_parse_fn);

		let modifier_check = self.variants_content.values().map(|variant| {
			let modifier = match variant.modifier {
				Modifier::NonPayable => "NonPayable",
				Modifier::Payable => "Payable",
				Modifier::View => "View",
			};

			let modifier = syn::Ident::new(modifier, span);

			quote!(
				use ::precompile_utils::solidity::modifier::FunctionModifier;
				use ::precompile_utils::evm::handle::PrecompileHandleExt;
				handle.check_function_modifier(FunctionModifier::#modifier)?;
			)
		});

		let variant_parsing = self
			.variants_content
			.iter()
			.map(|(variant_ident, variant)| {
				Self::expand_variant_parsing_from_handle(variant_ident, variant)
			});

		quote!(
			#(
				fn #fn_parse(
					handle: &mut impl PrecompileHandle
				) -> ::precompile_utils::EvmResult<Self> {
					use ::precompile_utils::solidity::revert::InjectBacktrace;

					#modifier_check
					#variant_parsing
				}
			)*
		)
	}

	/// Generates the parsing code for a variant, reading the input from the handle and
	/// parsing it using Reader.
	fn expand_variant_parsing_from_handle(
		variant_ident: &syn::Ident,
		variant: &Variant,
	) -> impl ToTokens {
		if variant.arguments.is_empty() {
			quote!( Ok(Self::#variant_ident {})).to_token_stream()
		} else {
			use case::CaseExt;

			let args_parse = variant.arguments.iter().map(|arg| {
				let ident = &arg.ident;
				let span = ident.span();
				let name = ident.to_string().to_camel_lowercase();

				quote_spanned!(span=> #ident: input.read().in_field(#name)?,)
			});
			let args_count = variant.arguments.len();

			quote!(
				let mut input = handle.read_after_selector()?;
				input.expect_arguments(#args_count)?;

				Ok(Self::#variant_ident {
					#(#args_parse)*
				})
			)
			.to_token_stream()
		}
	}

	/// Expands the call enum impl block.
	pub fn expand_enum_impl(&self) -> impl ToTokens {
		let enum_ident = &self.enum_ident;
		let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

		let match_selectors = self.selector_to_variant.keys();
		let match_selectors2 = self.selector_to_variant.keys();

		let variants_parsing = self.expand_variants_parse_fn();

		let variants_ident2: Vec<_> = self.variants_content.keys().collect();
		let variants_selectors_fn: Vec<_> = self
			.variants_content
			.keys()
			.map(|name| format_ident!("{}_selectors", name))
			.collect();
		let variants_selectors: Vec<_> = self
			.variants_content
			.values()
			.map(|variant| &variant.selectors)
			.collect();

		let variants_list: Vec<Vec<_>> = self
			.variants_content
			.values()
			.map(|variant| variant.arguments.iter().map(|arg| &arg.ident).collect())
			.collect();

		let variants_encode: Vec<_> = self
			.variants_content
			.values()
			.map(Self::expand_variant_encoding)
			.collect();

		let parse_call_data_fn = self.expand_enum_parse_call_data();
		let execute_fn = self.expand_enum_execute_fn();

		quote!(
			impl #impl_generics #enum_ident #ty_generics #where_clause {
				#parse_call_data_fn

				#variants_parsing

				#execute_fn

				pub fn supports_selector(selector: u32) -> bool {
					match selector {
						#(
							#match_selectors => true,
						)*
						_ => false,
					}
				}

				pub fn selectors() -> &'static [u32] {
					&[#(
						#match_selectors2
					),*]
				}

				#(
					pub fn #variants_selectors_fn() -> &'static [u32] {
						&[#(
							#variants_selectors
						),*]
					}
				)*

				pub fn encode(self) -> ::sp_std::vec::Vec<u8> {
					use ::precompile_utils::solidity::codec::Writer;
					match self {
						#(
							Self::#variants_ident2 { #(#variants_list),* } => {
								#variants_encode
							},
						)*
						Self::__phantom(_, _) => panic!("__phantom variant should not be used"),
					}
				}
			}

			impl #impl_generics From<#enum_ident #ty_generics> for ::sp_std::vec::Vec<u8>
			#where_clause
			{
				fn from(a: #enum_ident #ty_generics) -> ::sp_std::vec::Vec<u8> {
					a.encode()
				}
			}
		)
	}

	/// Expand the execute fn of the enum.
	fn expand_enum_execute_fn(&self) -> impl ToTokens {
		let impl_type = &self.impl_type;

		let variants_ident: Vec<_> = self.variants_content.keys().collect();

		let variants_arguments: Vec<Vec<_>> = self
			.variants_content
			.values()
			.map(|variant| variant.arguments.iter().map(|arg| &arg.ident).collect())
			.collect();

		// If there is no precompile set there is no discriminant.
		let opt_discriminant_arg = self
			.precompile_set_discriminant_type
			.as_ref()
			.map(|ty| quote!( discriminant: #ty,));

		let variants_call = self
			.variants_content
			.iter()
			.map(|(variant_ident, variant)| {
				let arguments = variant.arguments.iter().map(|arg| &arg.ident);

				let output_span = variant.fn_output.span();
				let opt_discriminant_arg = self
					.precompile_set_discriminant_fn
					.as_ref()
					.map(|_| quote!(discriminant,));

				let write_output = quote_spanned!(output_span=>
					::precompile_utils::solidity::encode_return_value(output?)
				);

				quote!(
					let output = <#impl_type>::#variant_ident(
						#opt_discriminant_arg
						handle,
						#(#arguments),*
					);
					#write_output
				)
			});

		quote!(
			pub fn execute(
				self,
				#opt_discriminant_arg
				handle: &mut impl PrecompileHandle
			) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> {
				use ::precompile_utils::solidity::codec::Writer;
				use ::fp_evm::{PrecompileOutput, ExitSucceed};

				let output = match self {
					#(
						Self::#variants_ident { #(#variants_arguments),* } => {
							#variants_call
						},
					)*
					Self::__phantom(_, _) => panic!("__phantom variant should not be used"),
				};

				Ok(PrecompileOutput {
					exit_status: ExitSucceed::Returned,
					output
				})
			}
		)
	}

	/// Expand how a variant can be Solidity encoded.
	fn expand_variant_encoding(variant: &Variant) -> impl ToTokens {
		match variant.selectors.first() {
			Some(selector) => {
				let write_arguments = variant.arguments.iter().map(|arg| {
					let ident = &arg.ident;
					let span = ident.span();
					quote_spanned!(span=> .write(#ident))
				});

				quote!(
					Writer::new_with_selector(#selector)
					#(#write_arguments)*
					.build()
				)
				.to_token_stream()
			}
			None => quote!(Default::default()).to_token_stream(),
		}
	}

	/// Expand the main parsing function that, based on the selector in the
	/// input, dispatch the decoding to one of the variants parsing function.
	fn expand_enum_parse_call_data(&self) -> impl ToTokens {
		let selectors = self.selector_to_variant.keys();
		let parse_fn = self
			.selector_to_variant
			.values()
			.map(Self::variant_ident_to_parse_fn);

		let match_fallback = match &self.fallback_to_variant {
			Some(variant) => {
				let parse_fn = Self::variant_ident_to_parse_fn(variant);
				quote!(_ => Self::#parse_fn(handle),).to_token_stream()
			}
			None => quote!(
				Some(_) => Err(RevertReason::UnknownSelector.into()),
				None => Err(RevertReason::read_out_of_bounds("selector").into()),
			)
			.to_token_stream(),
		};

		quote!(
			pub fn parse_call_data(
				handle: &mut impl PrecompileHandle
			) -> ::precompile_utils::EvmResult<Self> {
				use ::precompile_utils::solidity::revert::RevertReason;

				let input = handle.input();

				let selector = input.get(0..4).map(|s| {
					let mut buffer = [0u8; 4];
					buffer.copy_from_slice(s);
					u32::from_be_bytes(buffer)
				});

				match selector {
					#(
						Some(#selectors) => Self::#parse_fn(handle),
					)*
					#match_fallback
				}
			}
		)
	}

	fn variant_ident_to_parse_fn(ident: &syn::Ident) -> syn::Ident {
		format_ident!("_parse_{}", ident)
	}

	/// Expands the impl of the Precomile(Set) trait.
	pub fn expand_precompile_impl(&self) -> impl ToTokens {
		let impl_type = &self.impl_type;
		let enum_ident = &self.enum_ident;
		let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

		if let Some(discriminant_fn) = &self.precompile_set_discriminant_fn {
			let opt_pre_check = self.pre_check.as_ref().map(|ident| {
				let span = ident.span();
				quote_spanned!(span=>
					let _: () = <#impl_type>::#ident(discriminant, handle)
						.map_err(|err| Some(err))?;
				)
			});

			quote!(
				impl #impl_generics ::fp_evm::PrecompileSet for #impl_type #where_clause {
					fn execute(
						&self,
						handle: &mut impl PrecompileHandle
					) -> Option<::precompile_utils::EvmResult<::fp_evm::PrecompileOutput>> {
						use ::precompile_utils::precompile_set::DiscriminantResult;

						let discriminant = <#impl_type>::#discriminant_fn(
							handle.code_address(),
							handle.remaining_gas()
						);

						if let DiscriminantResult::Some(_, cost) | DiscriminantResult::None(cost) = discriminant {
							let result = handle.record_cost(cost);
							if let Err(e) = result {
								return Some(Err(e.into()));
							}
						}

						let discriminant = match discriminant {
							DiscriminantResult::Some(d, _) => d,
							DiscriminantResult::None(cost) => return None,
							DiscriminantResult::OutOfGas => return Some(Err(ExitError::OutOfGas.into()))
						};

						#opt_pre_check

						Some(
							<#enum_ident #ty_generics>::parse_call_data(handle)
								.and_then(|call| call.execute(discriminant, handle))
						)
					}

					fn is_precompile(&self, address: H160, gas: u64) -> ::fp_evm::IsPrecompileResult {
						<#impl_type>::#discriminant_fn(address, gas).into()
					}
				}
			)
			.to_token_stream()
		} else {
			let opt_pre_check = self.pre_check.as_ref().map(|ident| {
				let span = ident.span();
				quote_spanned!(span=>let _: () = <#impl_type>::#ident(handle)?;)
			});

			quote!(
				impl #impl_generics ::fp_evm::Precompile for #impl_type #where_clause {
					fn execute(
						handle: &mut impl PrecompileHandle
					) -> ::precompile_utils::EvmResult<::fp_evm::PrecompileOutput> {
						#opt_pre_check

						<#enum_ident #ty_generics>::parse_call_data(handle)?.execute(handle)
					}
				}
			)
			.to_token_stream()
		}
	}

	/// Expands the Solidity signature test.
	/// The macro expands an "inner" function in all build profiles, which is
	/// then called by a test in test profile. This allows to display errors that occurs in
	/// the expansion of the test without having to build in test profile, which is usually
	/// related to the use of a type parameter in one of the parsed parameters of a method.
	pub fn expand_test_solidity_signature(&self) -> impl ToTokens {
		let variant_test: Vec<_> = self
			.variants_content
			.iter()
			.map(|(ident, variant)| {
				let span = ident.span();

				let solidity = &variant.solidity_arguments_type;
				let name = ident.to_string();
				let types: Vec<_> = variant.arguments.iter().map(|arg| &arg.ty).collect();

				quote_spanned!(span=>
					assert_eq!(
						#solidity,
						<(#(#types,)*) as Codec>::signature(),
						"{} function signature doesn't match (left: attribute, right: computed \
						from Rust types)",
						#name
					);
				)
			})
			.collect();

		let test_name = format_ident!("__{}_test_solidity_signatures", self.impl_ident);
		let inner_name = format_ident!("__{}_test_solidity_signatures_inner", self.impl_ident);

		if let Some(test_types) = &self.test_concrete_types {
			let (impl_generics, _ty_generics, where_clause) = self.generics.split_for_impl();

			quote!(
				#[allow(non_snake_case)]
				pub(crate) fn #inner_name #impl_generics () #where_clause {
					use ::precompile_utils::solidity::Codec;
					#(#variant_test)*
				}

				#[test]
				#[allow(non_snake_case)]
				fn #test_name() {
					#inner_name::< #(#test_types),* >();
				}
			)
			.to_token_stream()
		} else {
			quote!(
				#[allow(non_snake_case)]
				pub(crate) fn #inner_name() {
					use ::precompile_utils::solidity::Codec;
					#(#variant_test)*
				}

				#[test]
				#[allow(non_snake_case)]
				fn #test_name() {
					#inner_name();
				}
			)
			.to_token_stream()
		}
	}
}