referrerpolicy=no-referrer-when-downgrade

frame_support_procedural/no_bound/
partial_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 PartialOrd but do not bound any generic.
21pub fn derive_partial_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_) =>
32			match struct_.fields {
33				syn::Fields::Named(named) => {
34					let fields =
35						named.named.iter().map(|i| &i.ident).map(
36							|i| quote::quote_spanned!(i.span() => self.#i.partial_cmp(&other.#i)),
37						);
38
39					quote::quote!(
40						Some(core::cmp::Ordering::Equal)
41							#(
42								.and_then(|order| {
43									let next_order = #fields?;
44									Some(order.then(next_order))
45								})
46							)*
47					)
48				},
49				syn::Fields::Unnamed(unnamed) => {
50					let fields =
51						unnamed.unnamed.iter().enumerate().map(|(i, _)| syn::Index::from(i)).map(
52							|i| quote::quote_spanned!(i.span() => self.#i.partial_cmp(&other.#i)),
53						);
54
55					quote::quote!(
56						Some(core::cmp::Ordering::Equal)
57							#(
58								.and_then(|order| {
59									let next_order = #fields?;
60									Some(order.then(next_order))
61								})
62							)*
63					)
64				},
65				syn::Fields::Unit => {
66					quote::quote!(Some(core::cmp::Ordering::Equal))
67				},
68			},
69		syn::Data::Enum(_) => {
70			let msg = "Enum type not supported by `derive(PartialOrdNoBound)`";
71			return syn::Error::new(input.span(), msg).to_compile_error().into()
72		},
73		syn::Data::Union(_) => {
74			let msg = "Union type not supported by `derive(PartialOrdNoBound)`";
75			return syn::Error::new(input.span(), msg).to_compile_error().into()
76		},
77	};
78
79	quote::quote!(
80		const _: () = {
81			#[allow(deprecated)]
82			impl #impl_generics core::cmp::PartialOrd for #name #ty_generics #where_clause {
83				fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
84					#impl_
85				}
86			}
87		};
88	)
89	.into()
90}