sp_runtime_interface_proc_macro/pass_by/
codec.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
18//! Derive macro implementation of `PassBy` with the associated type set to `Codec`.
19//!
20//! It is required that the type implements `Encode` and `Decode` from the `parity-scale-codec`
21//! crate.
22
23use crate::utils::{generate_crate_access, generate_runtime_interface_include};
24
25use syn::{parse_quote, DeriveInput, Generics, Result};
26
27use quote::quote;
28
29use proc_macro2::TokenStream;
30
31/// The derive implementation for `PassBy` with `Codec`.
32pub fn derive_impl(mut input: DeriveInput) -> Result<TokenStream> {
33	add_trait_bounds(&mut input.generics);
34	let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
35	let crate_include = generate_runtime_interface_include();
36	let crate_ = generate_crate_access();
37	let ident = input.ident;
38
39	let res = quote! {
40		const _: () = {
41			#crate_include
42
43			impl #impl_generics #crate_::pass_by::PassBy for #ident #ty_generics #where_clause {
44				type PassBy = #crate_::pass_by::Codec<#ident>;
45			}
46		};
47	};
48
49	Ok(res)
50}
51
52/// Add the `codec::Codec` trait bound to every type parameter.
53fn add_trait_bounds(generics: &mut Generics) {
54	let crate_ = generate_crate_access();
55
56	generics
57		.type_params_mut()
58		.for_each(|type_param| type_param.bounds.push(parse_quote!(#crate_::codec::Codec)));
59}