sp-api: Support expanding the macro code (#13573)

* sp-api: Support expanding the macro code

This pr introduces the `expander` crate to expand the generated source code into a file. This gives
better error reporting when trying to fix issues in the macro itself as Rustc will point to the line
in this file. The feature can be enabled by setting `SP_API_EXPAND=1` at compile time.

Besides that the generated code is changed to fix warnings in the exanped version.

* Fixes
This commit is contained in:
Bastian Köcher
2023-03-14 22:14:58 +01:00
committed by GitHub
parent ef165cec3e
commit 4ef1d0df02
9 changed files with 124 additions and 101 deletions
@@ -24,29 +24,19 @@ use syn::{
use quote::{format_ident, quote};
use std::env;
use proc_macro_crate::{crate_name, FoundCrate};
use crate::common::API_VERSION_ATTRIBUTE;
fn generate_hidden_includes_mod_name(unique_id: &'static str) -> Ident {
Ident::new(&format!("sp_api_hidden_includes_{}", unique_id), Span::call_site())
}
use inflector::Inflector;
/// Generates the hidden includes that are required to make the macro independent from its scope.
pub fn generate_hidden_includes(unique_id: &'static str) -> TokenStream {
let mod_name = generate_hidden_includes_mod_name(unique_id);
/// Generates the access to the `sc_client` crate.
pub fn generate_crate_access() -> TokenStream {
match crate_name("sp-api") {
Ok(FoundCrate::Itself) => quote!(),
Ok(FoundCrate::Name(client_name)) => {
let client_name = Ident::new(&client_name, Span::call_site());
quote!(
#[doc(hidden)]
mod #mod_name {
pub extern crate #client_name as sp_api;
}
)
Ok(FoundCrate::Itself) => quote!(sp_api),
Ok(FoundCrate::Name(renamed_name)) => {
let renamed_name = Ident::new(&renamed_name, Span::call_site());
quote!(#renamed_name)
},
Err(e) => {
let err = Error::new(Span::call_site(), e).to_compile_error();
@@ -55,19 +45,12 @@ pub fn generate_hidden_includes(unique_id: &'static str) -> TokenStream {
}
}
/// Generates the access to the `sc_client` crate.
pub fn generate_crate_access(unique_id: &'static str) -> TokenStream {
if env::var("CARGO_PKG_NAME").unwrap() == "sp-api" {
quote!(sp_api)
} else {
let mod_name = generate_hidden_includes_mod_name(unique_id);
quote!( self::#mod_name::sp_api )
}
}
/// Generates the name of the module that contains the trait declaration for the runtime.
pub fn generate_runtime_mod_name_for_trait(trait_: &Ident) -> Ident {
Ident::new(&format!("runtime_decl_for_{}", trait_), Span::call_site())
Ident::new(
&format!("runtime_decl_for_{}", trait_.to_string().to_snake_case()),
Span::call_site(),
)
}
/// Get the type of a `syn::ReturnType`.