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
// 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::*;
use syn::{GenericArgument, Type};

pub fn main(_: TokenStream, input: TokenStream) -> TokenStream {
	let item = parse_macro_input!(input as ItemType);

	let ItemType {
		attrs,
		vis,
		type_token,
		ident,
		generics,
		eq_token,
		ty,
		semi_token,
	} = item;

	if let Type::Tuple(ref type_tuple) = *ty {
		let variants: Vec<(Ident, u64)> = type_tuple
			.elems
			.iter()
			.filter_map(extract_precompile_name_and_prefix)
			.collect();

		let ident_expressions: Vec<&Ident> = variants.iter().map(|(ident, _)| ident).collect();
		let variant_expressions: Vec<&u64> = variants.iter().map(|(_, id)| id).collect();

		(quote! {
			#(#attrs)*
			#vis #type_token #ident #generics #eq_token #ty #semi_token

			#[derive(num_enum::TryFromPrimitive, num_enum::IntoPrimitive, Debug)]
			#[repr(u64)]
			pub enum PrecompileName {
				#(
					#ident_expressions = #variant_expressions,
				)*
			}

			impl PrecompileName {
				pub fn from_address(address: sp_core::H160) -> Option<Self> {
					let _u64 = address.to_low_u64_be();
					if address == sp_core::H160::from_low_u64_be(_u64) {
						use num_enum::TryFromPrimitive;
						Self::try_from_primitive(_u64).ok()
					} else {
						None
					}
				}
			}
		})
		.into()
	} else {
		quote_spanned! {
			ty.span() => compile_error!("Expected tuple");
		}
		.into()
	}
}

fn extract_precompile_name_and_prefix(type_: &Type) -> Option<(Ident, u64)> {
	match type_ {
		Type::Path(type_path) => {
			if let Some(path_segment) = type_path.path.segments.last() {
				match path_segment.ident.to_string().as_ref() {
					"PrecompileAt" => {
						extract_precompile_name_and_prefix_for_precompile_at(path_segment)
					}
					_ => None,
				}
			} else {
				None
			}
		}
		_ => None,
	}
}

fn extract_precompile_name_and_prefix_for_precompile_at(
	path_segment: &syn::PathSegment,
) -> Option<(Ident, u64)> {
	if let syn::PathArguments::AngleBracketed(generics) = &path_segment.arguments {
		let mut iter = generics.args.iter();
		if let (
			Some(GenericArgument::Type(Type::Path(type_path_1))),
			Some(GenericArgument::Type(Type::Path(type_path_2))),
		) = (iter.next(), iter.next())
		{
			if let (Some(path_segment_1), Some(path_segment_2)) = (
				type_path_1.path.segments.last(),
				type_path_2.path.segments.last(),
			) {
				if let syn::PathArguments::AngleBracketed(generics_) = &path_segment_1.arguments {
					if let Some(GenericArgument::Const(Expr::Lit(lit))) = generics_.args.first() {
						if let Lit::Int(int) = &lit.lit {
							if let Ok(precompile_id) = int.base10_parse() {
								if &path_segment_2.ident.to_string() == "CollectivePrecompile" {
									if let Some(instance_ident) =
										precompile_instance_ident(path_segment_2)
									{
										return Some((instance_ident, precompile_id));
									}
								} else {
									return Some((path_segment_2.ident.clone(), precompile_id));
								}
							}
						}
					}
				}
			}
		}
	}

	None
}

fn precompile_instance_ident(path_segment: &syn::PathSegment) -> Option<Ident> {
	if let syn::PathArguments::AngleBracketed(generics_) = &path_segment.arguments {
		if let Some(GenericArgument::Type(Type::Path(instance_type_path))) = generics_.args.last() {
			if let Some(instance_type) = instance_type_path.path.segments.last() {
				return Some(instance_type.ident.clone());
			}
		}
	}

	None
}