referrerpolicy=no-referrer-when-downgrade

frame_support_procedural/no_bound/
ord.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use syn::spanned::Spanned;
19
20/// Derive Ord but do not bound any generic.
21pub fn derive_ord_no_bound(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
22	let input: syn::DeriveInput = match syn::parse(input) {
23		Ok(input) => input,
24		Err(e) => return e.to_compile_error().into(),
25	};
26
27	let name = &input.ident;
28	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
29
30	let impl_ = match input.data {
31		syn::Data::Struct(struct_) => match struct_.fields {
32			syn::Fields::Named(named) => {
33				let fields = named
34					.named
35					.iter()
36					.map(|i| &i.ident)
37					.map(|i| quote::quote_spanned!(i.span() => self.#i.cmp(&other.#i) ));
38
39				quote::quote!( core::cmp::Ordering::Equal #( .then_with(|| #fields) )* )
40			},
41			syn::Fields::Unnamed(unnamed) => {
42				let fields = unnamed
43					.unnamed
44					.iter()
45					.enumerate()
46					.map(|(i, _)| syn::Index::from(i))
47					.map(|i| quote::quote_spanned!(i.span() => self.#i.cmp(&other.#i) ));
48
49				quote::quote!( core::cmp::Ordering::Equal #( .then_with(|| #fields) )* )
50			},
51			syn::Fields::Unit => {
52				quote::quote!(core::cmp::Ordering::Equal)
53			},
54		},
55		syn::Data::Enum(_) => {
56			let msg = "Enum type not supported by `derive(OrdNoBound)`";
57			return syn::Error::new(input.span(), msg).to_compile_error().into()
58		},
59		syn::Data::Union(_) => {
60			let msg = "Union type not supported by `derive(OrdNoBound)`";
61			return syn::Error::new(input.span(), msg).to_compile_error().into()
62		},
63	};
64
65	quote::quote!(
66		const _: () = {
67			#[allow(deprecated)]
68			impl #impl_generics core::cmp::Ord for #name #ty_generics #where_clause {
69				fn cmp(&self, other: &Self) -> core::cmp::Ordering {
70					#impl_
71				}
72			}
73		};
74	)
75	.into()
76}