mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-04-26 12:17:58 +00:00
Implements mocking of runtime apis (#5448)
* Implements mocking of runtime apis This pr adds support for easily mock runtime api implementations for tests by using the `mock_impl_runtime_apis!` macro. The syntax is similar to `impl_runtime_apis!`. The mocked implementation automatically implements `ApiExt`, `ApiErrorExt` and `Core` as these are required by the runtime api traits, but not required in tests or only a subset of them. * Fix warnings * Update primitives/api/proc-macro/src/utils.rs Co-Authored-By: Nikolay Volf <nikvolf@gmail.com> * Review feedback Co-authored-by: Nikolay Volf <nikvolf@gmail.com>
This commit is contained in:
@@ -19,7 +19,7 @@ use crate::utils::{
|
||||
fold_fn_decl_for_client_side, extract_parameter_names_types_and_borrows,
|
||||
generate_native_call_generator_fn_name, return_type_extract_type,
|
||||
generate_method_runtime_api_impl_name, generate_call_api_at_fn_name, prefix_function_with_trait,
|
||||
replace_wild_card_parameter_names,
|
||||
replace_wild_card_parameter_names, AllowSelfRefInParameters,
|
||||
};
|
||||
|
||||
use proc_macro2::{TokenStream, Span};
|
||||
@@ -198,7 +198,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result<TokenStream> {
|
||||
|
||||
// Generate a native call generator for each function of the given trait.
|
||||
for fn_ in fns {
|
||||
let params = extract_parameter_names_types_and_borrows(&fn_)?;
|
||||
let params = extract_parameter_names_types_and_borrows(&fn_, AllowSelfRefInParameters::No)?;
|
||||
let trait_fn_name = &fn_.ident;
|
||||
let fn_name = generate_native_call_generator_fn_name(&fn_.ident);
|
||||
let output = return_type_replace_block_with_node_block(fn_.output.clone());
|
||||
@@ -592,7 +592,10 @@ impl<'a> ToClientSideDecl<'a> {
|
||||
|
||||
// Get types and if the value is borrowed from all parameters.
|
||||
// If there is an error, we push it as the block to the user.
|
||||
let param_types = match extract_parameter_names_types_and_borrows(fn_sig) {
|
||||
let param_types = match extract_parameter_names_types_and_borrows(
|
||||
fn_sig,
|
||||
AllowSelfRefInParameters::No,
|
||||
) {
|
||||
Ok(res) => res.into_iter().map(|v| {
|
||||
let ty = v.1;
|
||||
let borrow = v.2;
|
||||
@@ -629,7 +632,10 @@ impl<'a> ToClientSideDecl<'a> {
|
||||
mut method: TraitItemMethod,
|
||||
context: TokenStream,
|
||||
) -> TraitItemMethod {
|
||||
let params = match extract_parameter_names_types_and_borrows(&method.sig) {
|
||||
let params = match extract_parameter_names_types_and_borrows(
|
||||
&method.sig,
|
||||
AllowSelfRefInParameters::No,
|
||||
) {
|
||||
Ok(res) => res.into_iter().map(|v| v.0).collect::<Vec<_>>(),
|
||||
Err(e) => {
|
||||
self.errors.push(e.to_compile_error());
|
||||
@@ -780,7 +786,7 @@ fn generate_runtime_api_id(trait_name: &str) -> TokenStream {
|
||||
let mut res = [0; 8];
|
||||
res.copy_from_slice(blake2_rfc::blake2b::blake2b(8, &[], trait_name.as_bytes()).as_bytes());
|
||||
|
||||
quote!( const ID: [u8; 8] = [ #( #res ),* ]; )
|
||||
quote!( const ID: [u8; 8] = [ #( #res ),* ]; )
|
||||
}
|
||||
|
||||
/// Generates the const variable that holds the runtime api version.
|
||||
|
||||
@@ -19,7 +19,8 @@ use crate::utils::{
|
||||
generate_runtime_mod_name_for_trait, generate_method_runtime_api_impl_name,
|
||||
extract_parameter_names_types_and_borrows, generate_native_call_generator_fn_name,
|
||||
return_type_extract_type, generate_call_api_at_fn_name, prefix_function_with_trait,
|
||||
extract_all_signature_types,
|
||||
extract_all_signature_types, extract_block_type_from_trait_path, extract_impl_trait,
|
||||
AllowSelfRefInParameters, RequireQualifiedTraitPath,
|
||||
};
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
@@ -66,7 +67,7 @@ fn generate_impl_call(
|
||||
input: &Ident,
|
||||
impl_trait: &Path
|
||||
) -> Result<TokenStream> {
|
||||
let params = extract_parameter_names_types_and_borrows(signature)?;
|
||||
let params = extract_parameter_names_types_and_borrows(signature, AllowSelfRefInParameters::No)?;
|
||||
|
||||
let c = generate_crate_access(HIDDEN_INCLUDES_ID);
|
||||
let c_iter = iter::repeat(&c);
|
||||
@@ -93,50 +94,6 @@ fn generate_impl_call(
|
||||
)
|
||||
}
|
||||
|
||||
/// Extract the trait that is implemented in the given `ItemImpl`.
|
||||
fn extract_impl_trait<'a>(impl_: &'a ItemImpl) -> Result<&'a Path> {
|
||||
impl_.trait_.as_ref().map(|v| &v.1).ok_or_else(
|
||||
|| Error::new(impl_.span(), "Only implementation of traits are supported!")
|
||||
).and_then(|p| {
|
||||
if p.segments.len() > 1 {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(
|
||||
Error::new(
|
||||
p.span(),
|
||||
"The implemented trait has to be referenced with a path, \
|
||||
e.g. `impl client::Core for Runtime`."
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Extracts the runtime block identifier.
|
||||
fn extract_runtime_block_ident(trait_: &Path) -> Result<&TypePath> {
|
||||
let span = trait_.span();
|
||||
let generics = trait_
|
||||
.segments
|
||||
.last()
|
||||
.ok_or_else(|| Error::new(span, "Empty path not supported"))?;
|
||||
|
||||
match &generics.arguments {
|
||||
PathArguments::AngleBracketed(ref args) => {
|
||||
args.args.first().and_then(|v| match v {
|
||||
GenericArgument::Type(Type::Path(ref block)) => Some(block),
|
||||
_ => None
|
||||
}).ok_or_else(|| Error::new(args.span(), "Missing `Block` generic parameter."))
|
||||
},
|
||||
PathArguments::None => {
|
||||
let span = trait_.segments.last().as_ref().unwrap().span();
|
||||
Err(Error::new(span, "Missing `Block` generic parameter."))
|
||||
},
|
||||
PathArguments::Parenthesized(_) => {
|
||||
Err(Error::new(generics.arguments.span(), "Unexpected parentheses in path!"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate all the implementation calls for the given functions.
|
||||
fn generate_impl_calls(
|
||||
impls: &[ItemImpl],
|
||||
@@ -145,7 +102,7 @@ fn generate_impl_calls(
|
||||
let mut impl_calls = Vec::new();
|
||||
|
||||
for impl_ in impls {
|
||||
let impl_trait_path = extract_impl_trait(impl_)?;
|
||||
let impl_trait_path = extract_impl_trait(impl_, RequireQualifiedTraitPath::Yes)?;
|
||||
let impl_trait = extend_with_runtime_decl_path(impl_trait_path.clone());
|
||||
let impl_trait_ident = &impl_trait_path
|
||||
.segments
|
||||
@@ -307,11 +264,19 @@ fn generate_runtime_api_base_structures() -> Result<TokenStream> {
|
||||
res
|
||||
}
|
||||
|
||||
fn runtime_version_at(
|
||||
fn has_api<A: #crate_::RuntimeApiInfo + ?Sized>(
|
||||
&self,
|
||||
at: &#crate_::BlockId<Block>,
|
||||
) -> std::result::Result<#crate_::RuntimeVersion, C::Error> {
|
||||
self.call.runtime_version_at(at)
|
||||
) -> std::result::Result<bool, C::Error> where Self: Sized {
|
||||
self.call.runtime_version_at(at).map(|v| v.has_api_with(&A::ID, |v| v == A::VERSION))
|
||||
}
|
||||
|
||||
fn has_api_with<A: #crate_::RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
|
||||
&self,
|
||||
at: &#crate_::BlockId<Block>,
|
||||
pred: P,
|
||||
) -> std::result::Result<bool, C::Error> where Self: Sized {
|
||||
self.call.runtime_version_at(at).map(|v| v.has_api_with(&A::ID, pred))
|
||||
}
|
||||
|
||||
fn record_proof(&mut self) {
|
||||
@@ -450,7 +415,7 @@ fn generate_api_impl_for_runtime(impls: &[ItemImpl]) -> Result<TokenStream> {
|
||||
// we put the `RuntimeBlock` as first argument for the trait generics.
|
||||
for impl_ in impls.iter() {
|
||||
let mut impl_ = impl_.clone();
|
||||
let trait_ = extract_impl_trait(&impl_)?.clone();
|
||||
let trait_ = extract_impl_trait(&impl_, RequireQualifiedTraitPath::Yes)?.clone();
|
||||
let trait_ = extend_with_runtime_decl_path(trait_);
|
||||
|
||||
impl_.trait_.as_mut().unwrap().1 = trait_;
|
||||
@@ -506,7 +471,10 @@ impl<'a> Fold for ApiRuntimeImplToApiRuntimeApiImpl<'a> {
|
||||
}).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let (param_types, error) = match extract_parameter_names_types_and_borrows(&input.sig) {
|
||||
let (param_types, error) = match extract_parameter_names_types_and_borrows(
|
||||
&input.sig,
|
||||
AllowSelfRefInParameters::No,
|
||||
) {
|
||||
Ok(res) => (
|
||||
res.into_iter().map(|v| {
|
||||
let ty = v.1;
|
||||
@@ -645,13 +613,13 @@ fn generate_api_impl_for_runtime_api(impls: &[ItemImpl]) -> Result<TokenStream>
|
||||
let mut result = Vec::with_capacity(impls.len());
|
||||
|
||||
for impl_ in impls {
|
||||
let impl_trait_path = extract_impl_trait(&impl_)?;
|
||||
let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::Yes)?;
|
||||
let impl_trait = &impl_trait_path
|
||||
.segments
|
||||
.last()
|
||||
.ok_or_else(|| Error::new(impl_trait_path.span(), "Empty trait path not possible!"))?
|
||||
.clone();
|
||||
let runtime_block = extract_runtime_block_ident(impl_trait_path)?;
|
||||
let runtime_block = extract_block_type_from_trait_path(impl_trait_path)?;
|
||||
let runtime_type = &impl_.self_ty;
|
||||
let mut runtime_mod_path = extend_with_runtime_decl_path(impl_trait_path.clone());
|
||||
// remove the trait to get just the module path
|
||||
@@ -682,7 +650,9 @@ fn generate_runtime_api_versions(impls: &[ItemImpl]) -> Result<TokenStream> {
|
||||
let mut processed_traits = HashSet::new();
|
||||
|
||||
for impl_ in impls {
|
||||
let mut path = extend_with_runtime_decl_path(extract_impl_trait(&impl_)?.clone());
|
||||
let mut path = extend_with_runtime_decl_path(
|
||||
extract_impl_trait(&impl_, RequireQualifiedTraitPath::Yes)?.clone(),
|
||||
);
|
||||
// Remove the trait
|
||||
let trait_ = path
|
||||
.segments
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
mod impl_runtime_apis;
|
||||
mod mock_impl_runtime_apis;
|
||||
mod decl_runtime_apis;
|
||||
mod utils;
|
||||
|
||||
@@ -29,6 +30,11 @@ pub fn impl_runtime_apis(input: TokenStream) -> TokenStream {
|
||||
impl_runtime_apis::impl_runtime_apis_impl(input)
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn mock_impl_runtime_apis(input: TokenStream) -> TokenStream {
|
||||
mock_impl_runtime_apis::mock_impl_runtime_apis_impl(input)
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn decl_runtime_apis(input: TokenStream) -> TokenStream {
|
||||
decl_runtime_apis::decl_runtime_apis_impl(input)
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
// Copyright 2020 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate 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.
|
||||
|
||||
// Substrate 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 Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::utils::{
|
||||
generate_crate_access, generate_hidden_includes,
|
||||
generate_method_runtime_api_impl_name, extract_parameter_names_types_and_borrows,
|
||||
return_type_extract_type, extract_block_type_from_trait_path, extract_impl_trait,
|
||||
AllowSelfRefInParameters, RequireQualifiedTraitPath,
|
||||
};
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
|
||||
use quote::quote;
|
||||
|
||||
use syn::{
|
||||
spanned::Spanned, parse_macro_input, Ident, Type, ItemImpl, ImplItem, TypePath, parse_quote,
|
||||
parse::{Parse, ParseStream, Result, Error}, fold::{self, Fold},
|
||||
};
|
||||
|
||||
/// Unique identifier used to make the hidden includes unique for this macro.
|
||||
const HIDDEN_INCLUDES_ID: &str = "MOCK_IMPL_RUNTIME_APIS";
|
||||
|
||||
/// The structure used for parsing the runtime api implementations.
|
||||
struct RuntimeApiImpls {
|
||||
impls: Vec<ItemImpl>,
|
||||
}
|
||||
|
||||
impl Parse for RuntimeApiImpls {
|
||||
fn parse(input: ParseStream) -> Result<Self> {
|
||||
let mut impls = Vec::new();
|
||||
|
||||
while !input.is_empty() {
|
||||
impls.push(ItemImpl::parse(input)?);
|
||||
}
|
||||
|
||||
if impls.is_empty() {
|
||||
Err(Error::new(Span::call_site(), "No api implementation given!"))
|
||||
} else {
|
||||
Ok(Self { impls })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Implement the `ApiExt` trait, `ApiErrorExt` trait and the `Core` runtime api.
|
||||
fn implement_common_api_traits(
|
||||
error_type: Option<Type>,
|
||||
block_type: TypePath,
|
||||
self_ty: Type,
|
||||
) -> Result<TokenStream> {
|
||||
let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID);
|
||||
|
||||
let error_type = error_type.map(|e| quote!(#e)).unwrap_or_else(|| quote!(String));
|
||||
|
||||
Ok(quote!(
|
||||
impl #crate_::ApiErrorExt for #self_ty {
|
||||
type Error = #error_type;
|
||||
}
|
||||
|
||||
impl #crate_::ApiExt<#block_type> for #self_ty {
|
||||
type StateBackend = #crate_::InMemoryBackend<#crate_::HashFor<#block_type>>;
|
||||
|
||||
fn map_api_result<F: FnOnce(&Self) -> std::result::Result<R, E>, R, E>(
|
||||
&self,
|
||||
map_call: F,
|
||||
) -> std::result::Result<R, E> where Self: Sized {
|
||||
map_call(self)
|
||||
}
|
||||
|
||||
fn has_api<A: #crate_::RuntimeApiInfo + ?Sized>(
|
||||
&self,
|
||||
_: &#crate_::BlockId<#block_type>,
|
||||
) -> std::result::Result<bool, #error_type> where Self: Sized {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn has_api_with<A: #crate_::RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
|
||||
&self,
|
||||
at: &#crate_::BlockId<#block_type>,
|
||||
pred: P,
|
||||
) -> std::result::Result<bool, #error_type> where Self: Sized {
|
||||
Ok(pred(A::VERSION))
|
||||
}
|
||||
|
||||
fn record_proof(&mut self) {
|
||||
unimplemented!("`record_proof` not implemented for runtime api mocks")
|
||||
}
|
||||
|
||||
fn extract_proof(&mut self) -> Option<#crate_::StorageProof> {
|
||||
unimplemented!("`extract_proof` not implemented for runtime api mocks")
|
||||
}
|
||||
|
||||
fn into_storage_changes(
|
||||
&self,
|
||||
_: &Self::StateBackend,
|
||||
_: Option<&#crate_::ChangesTrieState<
|
||||
#crate_::HashFor<#block_type>,
|
||||
#crate_::NumberFor<#block_type>,
|
||||
>>,
|
||||
_: <#block_type as #crate_::BlockT>::Hash,
|
||||
) -> std::result::Result<
|
||||
#crate_::StorageChanges<Self::StateBackend, #block_type>,
|
||||
String
|
||||
> where Self: Sized {
|
||||
unimplemented!("`into_storage_changes` not implemented for runtime api mocks")
|
||||
}
|
||||
}
|
||||
|
||||
impl #crate_::Core<#block_type> for #self_ty {
|
||||
fn Core_version_runtime_api_impl(
|
||||
&self,
|
||||
_: &#crate_::BlockId<#block_type>,
|
||||
_: #crate_::ExecutionContext,
|
||||
_: Option<()>,
|
||||
_: Vec<u8>,
|
||||
) -> std::result::Result<#crate_::NativeOrEncoded<#crate_::RuntimeVersion>, #error_type> {
|
||||
unimplemented!("Not required for testing!")
|
||||
}
|
||||
|
||||
fn Core_execute_block_runtime_api_impl(
|
||||
&self,
|
||||
_: &#crate_::BlockId<#block_type>,
|
||||
_: #crate_::ExecutionContext,
|
||||
_: Option<#block_type>,
|
||||
_: Vec<u8>,
|
||||
) -> std::result::Result<#crate_::NativeOrEncoded<()>, #error_type> {
|
||||
unimplemented!("Not required for testing!")
|
||||
}
|
||||
|
||||
fn Core_initialize_block_runtime_api_impl(
|
||||
&self,
|
||||
_: &#crate_::BlockId<#block_type>,
|
||||
_: #crate_::ExecutionContext,
|
||||
_: Option<&<#block_type as #crate_::BlockT>::Header>,
|
||||
_: Vec<u8>,
|
||||
) -> std::result::Result<#crate_::NativeOrEncoded<()>, #error_type> {
|
||||
unimplemented!("Not required for testing!")
|
||||
}
|
||||
}
|
||||
))
|
||||
}
|
||||
|
||||
/// Auxialiry structure to fold a runtime api trait implementation into the expected format.
|
||||
///
|
||||
/// This renames the methods, changes the method parameters and extracts the error type.
|
||||
struct FoldRuntimeApiImpl<'a> {
|
||||
/// The block type that is being used.
|
||||
block_type: &'a TypePath,
|
||||
/// The identifier of the trait being implemented.
|
||||
impl_trait: &'a Ident,
|
||||
/// Stores the error type that is being found in the trait implementation as associated type
|
||||
/// with the name `Error`.
|
||||
error_type: &'a mut Option<Type>,
|
||||
}
|
||||
|
||||
impl<'a> Fold for FoldRuntimeApiImpl<'a> {
|
||||
fn fold_impl_item_method(&mut self, mut input: syn::ImplItemMethod) -> syn::ImplItemMethod {
|
||||
let block = {
|
||||
let crate_ = generate_crate_access(HIDDEN_INCLUDES_ID);
|
||||
|
||||
let (param_names, param_types, error) = match extract_parameter_names_types_and_borrows(
|
||||
&input.sig,
|
||||
AllowSelfRefInParameters::YesButIgnore,
|
||||
) {
|
||||
Ok(res) => (
|
||||
res.iter().map(|v| v.0.clone()).collect::<Vec<_>>(),
|
||||
res.iter().map(|v| {
|
||||
let ty = &v.1;
|
||||
let borrow = &v.2;
|
||||
quote!( #borrow #ty )
|
||||
}).collect::<Vec<_>>(),
|
||||
None
|
||||
),
|
||||
Err(e) => (Vec::new(), Vec::new(), Some(e.to_compile_error())),
|
||||
};
|
||||
|
||||
let block_type = &self.block_type;
|
||||
|
||||
// Rewrite the input parameters.
|
||||
input.sig.inputs = parse_quote! {
|
||||
&self,
|
||||
_: &#crate_::BlockId<#block_type>,
|
||||
_: #crate_::ExecutionContext,
|
||||
params: Option<( #( #param_types ),* )>,
|
||||
_: Vec<u8>,
|
||||
};
|
||||
|
||||
input.sig.ident = generate_method_runtime_api_impl_name(
|
||||
&self.impl_trait,
|
||||
&input.sig.ident,
|
||||
);
|
||||
let ret_type = return_type_extract_type(&input.sig.output);
|
||||
|
||||
// Generate the correct return type.
|
||||
input.sig.output = parse_quote!(
|
||||
-> std::result::Result<#crate_::NativeOrEncoded<#ret_type>, Self::Error>
|
||||
);
|
||||
|
||||
let orig_block = input.block.clone();
|
||||
|
||||
// Generate the new method implementation that calls into the runtime.
|
||||
parse_quote!(
|
||||
{
|
||||
// Get the error to the user (if we have one).
|
||||
#error
|
||||
|
||||
let (#( #param_names ),*) = params
|
||||
.expect("Mocked runtime apis don't support calling deprecated api versions");
|
||||
|
||||
let __fn_implementation__ = move || #orig_block;
|
||||
|
||||
Ok(#crate_::NativeOrEncoded::Native(__fn_implementation__()))
|
||||
}
|
||||
)
|
||||
};
|
||||
|
||||
let mut input = fold::fold_impl_item_method(self, input);
|
||||
// We need to set the block, after we modified the rest of the ast, otherwise we would
|
||||
// modify our generated block as well.
|
||||
input.block = block;
|
||||
input
|
||||
}
|
||||
|
||||
fn fold_impl_item(&mut self, input: ImplItem) -> ImplItem {
|
||||
match input {
|
||||
ImplItem::Type(ty) => {
|
||||
if ty.ident == "Error" {
|
||||
if let Some(error_type) = self.error_type {
|
||||
if *error_type != ty.ty {
|
||||
let error = Error::new(
|
||||
ty.span(),
|
||||
"Error type can not change between runtime apis",
|
||||
);
|
||||
ImplItem::Verbatim(error.to_compile_error())
|
||||
} else {
|
||||
ImplItem::Verbatim(Default::default())
|
||||
}
|
||||
} else {
|
||||
*self.error_type = Some(ty.ty);
|
||||
ImplItem::Verbatim(Default::default())
|
||||
}
|
||||
} else {
|
||||
let error = Error::new(
|
||||
ty.span(),
|
||||
"Only associated type with name `Error` is allowed",
|
||||
);
|
||||
ImplItem::Verbatim(error.to_compile_error())
|
||||
}
|
||||
},
|
||||
o => fold::fold_impl_item(self, o),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of [`generate_runtime_api_impls`].
|
||||
struct GeneratedRuntimeApiImpls {
|
||||
/// All the runtime api implementations.
|
||||
impls: TokenStream,
|
||||
/// The error type that should be used by the runtime apis.
|
||||
error_type: Option<Type>,
|
||||
/// The block type that is being used by the runtime apis.
|
||||
block_type: TypePath,
|
||||
/// The type the traits are implemented for.
|
||||
self_ty: Type,
|
||||
}
|
||||
|
||||
/// Generate the runtime api implementations from the given trait implementations.
|
||||
///
|
||||
/// This folds the method names, changes the method parameters, method return type,
|
||||
/// extracts the error type, self type and the block type.
|
||||
fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result<GeneratedRuntimeApiImpls> {
|
||||
let mut result = Vec::with_capacity(impls.len());
|
||||
let mut error_type = None;
|
||||
let mut global_block_type: Option<TypePath> = None;
|
||||
let mut self_ty: Option<Box<Type>> = None;
|
||||
|
||||
for impl_ in impls {
|
||||
let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::No)?;
|
||||
let impl_trait = &impl_trait_path
|
||||
.segments
|
||||
.last()
|
||||
.ok_or_else(|| Error::new(impl_trait_path.span(), "Empty trait path not possible!"))?
|
||||
.clone();
|
||||
let block_type = extract_block_type_from_trait_path(impl_trait_path)?;
|
||||
|
||||
self_ty = match self_ty.take() {
|
||||
Some(self_ty) => {
|
||||
if self_ty == impl_.self_ty {
|
||||
Some(self_ty)
|
||||
} else {
|
||||
let mut error =Error::new(
|
||||
impl_.self_ty.span(),
|
||||
"Self type should not change between runtime apis",
|
||||
);
|
||||
|
||||
error.combine(Error::new(
|
||||
self_ty.span(),
|
||||
"First self type found here",
|
||||
));
|
||||
|
||||
return Err(error)
|
||||
}
|
||||
},
|
||||
None => Some(impl_.self_ty.clone()),
|
||||
};
|
||||
|
||||
global_block_type = match global_block_type.take() {
|
||||
Some(global_block_type) => {
|
||||
if global_block_type == *block_type {
|
||||
Some(global_block_type)
|
||||
} else {
|
||||
let mut error = Error::new(
|
||||
block_type.span(),
|
||||
"Block type should be the same between all runtime apis.",
|
||||
);
|
||||
|
||||
error.combine(Error::new(
|
||||
global_block_type.span(),
|
||||
"First block type found here",
|
||||
));
|
||||
|
||||
return Err(error)
|
||||
}
|
||||
},
|
||||
None => Some(block_type.clone()),
|
||||
};
|
||||
|
||||
let mut visitor = FoldRuntimeApiImpl {
|
||||
block_type,
|
||||
impl_trait: &impl_trait.ident,
|
||||
error_type: &mut error_type,
|
||||
};
|
||||
|
||||
result.push(visitor.fold_item_impl(impl_.clone()));
|
||||
}
|
||||
|
||||
Ok(GeneratedRuntimeApiImpls {
|
||||
impls: quote!( #( #result )* ),
|
||||
error_type,
|
||||
block_type: global_block_type.expect("There is a least one runtime api; qed"),
|
||||
self_ty: *self_ty.expect("There is at least one runtime api; qed"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The implementation of the `mock_impl_runtime_apis!` macro.
|
||||
pub fn mock_impl_runtime_apis_impl(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
// Parse all impl blocks
|
||||
let RuntimeApiImpls { impls: api_impls } = parse_macro_input!(input as RuntimeApiImpls);
|
||||
|
||||
mock_impl_runtime_apis_impl_inner(&api_impls).unwrap_or_else(|e| e.to_compile_error()).into()
|
||||
}
|
||||
|
||||
fn mock_impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result<TokenStream> {
|
||||
let hidden_includes = generate_hidden_includes(HIDDEN_INCLUDES_ID);
|
||||
let GeneratedRuntimeApiImpls { impls, error_type, block_type, self_ty } =
|
||||
generate_runtime_api_impls(api_impls)?;
|
||||
let api_traits = implement_common_api_traits(error_type, block_type, self_ty)?;
|
||||
|
||||
Ok(quote!(
|
||||
#hidden_includes
|
||||
|
||||
#impls
|
||||
|
||||
#api_traits
|
||||
))
|
||||
}
|
||||
@@ -18,7 +18,7 @@ use proc_macro2::{TokenStream, Span};
|
||||
|
||||
use syn::{
|
||||
Result, Ident, Signature, parse_quote, Type, Pat, spanned::Spanned, FnArg, Error, token::And,
|
||||
ImplItem, ReturnType,
|
||||
ImplItem, ReturnType, PathArguments, Path, GenericArgument, TypePath, ItemImpl,
|
||||
};
|
||||
|
||||
use quote::quote;
|
||||
@@ -126,13 +126,21 @@ pub fn generate_unique_pattern(pat: Pat, counter: &mut u32) -> Pat {
|
||||
},
|
||||
_ => pat,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow `&self` in parameters of a method.
|
||||
pub enum AllowSelfRefInParameters {
|
||||
/// Allows `&self` in parameters, but doesn't return it as part of the parameters.
|
||||
YesButIgnore,
|
||||
No,
|
||||
}
|
||||
|
||||
/// Extracts the name, the type and `&` or ``(if it is a reference or not)
|
||||
/// for each parameter in the given function signature.
|
||||
pub fn extract_parameter_names_types_and_borrows(sig: &Signature)
|
||||
-> Result<Vec<(Pat, Type, Option<And>)>>
|
||||
{
|
||||
pub fn extract_parameter_names_types_and_borrows(
|
||||
sig: &Signature,
|
||||
allow_self: AllowSelfRefInParameters,
|
||||
) -> Result<Vec<(Pat, Type, Option<And>)>> {
|
||||
let mut result = Vec::new();
|
||||
let mut generated_pattern_counter = 0;
|
||||
for input in sig.inputs.iter() {
|
||||
@@ -145,13 +153,20 @@ pub fn extract_parameter_names_types_and_borrows(sig: &Signature)
|
||||
t => { (t.clone(), None) },
|
||||
};
|
||||
|
||||
let name =
|
||||
generate_unique_pattern((*arg.pat).clone(), &mut generated_pattern_counter);
|
||||
let name = generate_unique_pattern(
|
||||
(*arg.pat).clone(),
|
||||
&mut generated_pattern_counter,
|
||||
);
|
||||
result.push((name, ty, borrow));
|
||||
},
|
||||
FnArg::Receiver(_) => {
|
||||
FnArg::Receiver(_) if matches!(allow_self, AllowSelfRefInParameters::No) => {
|
||||
return Err(Error::new(input.span(), "`self` parameter not supported!"))
|
||||
}
|
||||
},
|
||||
FnArg::Receiver(recv) => {
|
||||
if recv.mutability.is_some() || recv.reference.is_none() {
|
||||
return Err(Error::new(recv.span(), "Only `&self` is supported!"))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,3 +214,60 @@ pub fn extract_all_signature_types(items: &[ImplItem]) -> Vec<Type> {
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Extracts the block type from a trait path.
|
||||
///
|
||||
/// It is expected that the block type is the first type in the generic arguments.
|
||||
pub fn extract_block_type_from_trait_path(trait_: &Path) -> Result<&TypePath> {
|
||||
let span = trait_.span();
|
||||
let generics = trait_
|
||||
.segments
|
||||
.last()
|
||||
.ok_or_else(|| Error::new(span, "Empty path not supported"))?;
|
||||
|
||||
match &generics.arguments {
|
||||
PathArguments::AngleBracketed(ref args) => {
|
||||
args.args.first().and_then(|v| match v {
|
||||
GenericArgument::Type(Type::Path(ref block)) => Some(block),
|
||||
_ => None
|
||||
}).ok_or_else(|| Error::new(args.span(), "Missing `Block` generic parameter."))
|
||||
},
|
||||
PathArguments::None => {
|
||||
let span = trait_.segments.last().as_ref().unwrap().span();
|
||||
Err(Error::new(span, "Missing `Block` generic parameter."))
|
||||
},
|
||||
PathArguments::Parenthesized(_) => {
|
||||
Err(Error::new(generics.arguments.span(), "Unexpected parentheses in path!"))
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Should a qualified trait path be required?
|
||||
///
|
||||
/// e.g. `path::Trait` is qualified and `Trait` is not.
|
||||
pub enum RequireQualifiedTraitPath {
|
||||
Yes,
|
||||
No,
|
||||
}
|
||||
|
||||
/// Extract the trait that is implemented by the given `ItemImpl`.
|
||||
pub fn extract_impl_trait<'a>(
|
||||
impl_: &'a ItemImpl,
|
||||
require: RequireQualifiedTraitPath,
|
||||
) -> Result<&'a Path> {
|
||||
impl_.trait_.as_ref().map(|v| &v.1).ok_or_else(
|
||||
|| Error::new(impl_.span(), "Only implementation of traits are supported!")
|
||||
).and_then(|p| {
|
||||
if p.segments.len() > 1 || matches!(require, RequireQualifiedTraitPath::No) {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(
|
||||
Error::new(
|
||||
p.span(),
|
||||
"The implemented trait has to be referenced with a path, \
|
||||
e.g. `impl client::Core for Runtime`."
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user