Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

Allow usage of path in construct_runtime! #8801

Merged
18 commits merged into from
Jun 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions frame/support/procedural/src/construct_runtime/expand/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// This file is part of Substrate.

// Copyright (C) 2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

use crate::construct_runtime::Pallet;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::Ident;

pub fn expand_outer_config(
runtime: &Ident,
pallet_decls: &[Pallet],
scrate: &TokenStream,
) -> TokenStream {
let mut types = TokenStream::new();
let mut fields = TokenStream::new();
let mut build_storage_calls = TokenStream::new();

for decl in pallet_decls {
if let Some(pallet_entry) = decl.find_part("Config") {
let config = format_ident!("{}Config", decl.name);
let mod_name = decl.pallet.mod_name();
let field_name = if let Some(inst) = decl.instance.as_ref() {
format_ident!("{}_{}", mod_name, inst)
} else {
mod_name
};
let part_is_generic = !pallet_entry.generics.params.is_empty();

types.extend(expand_config_types(runtime, decl, &config, part_is_generic));
fields.extend(quote!(pub #field_name: #config,));
build_storage_calls.extend(expand_config_build_storage_call(scrate, runtime, decl, &field_name));
}
}

quote!{
#types

#[cfg(any(feature = "std", test))]
use #scrate::serde as __genesis_config_serde_import__;
#[cfg(any(feature = "std", test))]
#[derive(#scrate::serde::Serialize, #scrate::serde::Deserialize, Default)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
#[serde(crate = "__genesis_config_serde_import__")]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isn't it possible to use #scrate::serde directly here ?
But we can do as a polishing follow-up

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yeah, I was just copy and pasting the code from the old macros and didn't really think about whether we needed to prepend #scrate. My thinking was that if it worked in the old macro verbatim, there's no reason why it wouldn't work on the new proc macros.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's interesting how using #scrate::serde actually produces 2 errors:

error[E0433]: failed to resolve: could not find `serde` in `hidden_include`
   --> frame/support/test/tests/construct_runtime.rs:223:1
    |
223 | / frame_support::construct_runtime!(
224 | |     pub enum Runtime where
225 | |         Block = Block,
226 | |         NodeBlock = Block,
...   |
242 | |     }
243 | | );
    | |__^ could not find `serde` in `hidden_include`
    |
    = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0433]: failed to resolve: could not find `serde` in `hidden_include`
   --> frame/support/test/tests/construct_runtime.rs:278:2
    |
278 | /     frame_support::construct_runtime!(
279 | |         pub enum RuntimeOriginTest where
280 | |             Block = Block,
281 | |             NodeBlock = Block,
...   |
287 | |         }
288 | |     );
    | |______^ could not find `serde` in `hidden_include`
    |
    = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because you are deriving 2 traits. Nothing special here

#[allow(non_snake_case)]
pub struct GenesisConfig {
#fields
}

#[cfg(any(feature = "std", test))]
impl #scrate::sp_runtime::BuildStorage for GenesisConfig {
fn assimilate_storage(
&self,
storage: &mut #scrate::sp_runtime::Storage,
) -> std::result::Result<(), String> {
#build_storage_calls

#scrate::BasicExternalities::execute_with_storage(storage, || {
<AllPalletsWithSystem as #scrate::traits::OnGenesis>::on_genesis();
});

Ok(())
}
}
}
}

fn expand_config_types(
runtime: &Ident,
decl: &Pallet,
config: &Ident,
part_is_generic: bool,
) -> TokenStream {
let path = &decl.pallet;

match (decl.instance.as_ref(), part_is_generic) {
(Some(inst), true) => quote!{
#[cfg(any(feature = "std", test))]
pub type #config = #path::GenesisConfig<#runtime, #path::#inst>;
},
(None, true) => quote!{
#[cfg(any(feature = "std", test))]
pub type #config = #path::GenesisConfig<#runtime>;
},
(_, false) => quote!{
#[cfg(any(feature = "std", test))]
pub type #config = #path::GenesisConfig;
},
}
}

fn expand_config_build_storage_call(
scrate: &TokenStream,
runtime: &Ident,
decl: &Pallet,
field_name: &Ident,
) -> TokenStream {
let path = &decl.pallet;
let instance = if let Some(inst) = decl.instance.as_ref() {
quote!(#path::#inst)
} else {
quote!(#path::__InherentHiddenInstance)
};

quote!{
#scrate::sp_runtime::BuildModuleGenesisStorage::
<#runtime, #instance>::build_module_genesis_storage(&self.#field_name, storage)?;
}
}
146 changes: 146 additions & 0 deletions frame/support/procedural/src/construct_runtime/expand/event.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// This file is part of Substrate.

// Copyright (C) 2021 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License

use crate::construct_runtime::{Pallet, parse::PalletPath};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{Generics, Ident};

pub fn expand_outer_event(
runtime: &Ident,
pallet_decls: &[Pallet],
scrate: &TokenStream,
) -> syn::Result<TokenStream> {
let mut event_variants = TokenStream::new();
let mut event_conversions = TokenStream::new();
let mut events_metadata = TokenStream::new();

for pallet_decl in pallet_decls {
if let Some(pallet_entry) = pallet_decl.find_part("Event") {
let path = &pallet_decl.pallet;
let index = pallet_decl.index;
let instance = pallet_decl.instance.as_ref();
let generics = &pallet_entry.generics;

if instance.is_some() && generics.params.is_empty() {
let msg = format!(
"Instantiable pallet with no generic `Event` cannot \
be constructed: pallet `{}` must have generic `Event`",
pallet_decl.name,
);
return Err(syn::Error::new(pallet_decl.name.span(), msg));
gui1117 marked this conversation as resolved.
Show resolved Hide resolved
}

let part_is_generic = !generics.params.is_empty();
let pallet_event = match (instance, part_is_generic) {
(Some(inst), true) => quote!(#path::Event::<#runtime, #path::#inst>),
(Some(inst), false) => quote!(#path::Event::<#path::#inst>),
(None, true) => quote!(#path::Event::<#runtime>),
(None, false) => quote!(#path::Event),
};

event_variants.extend(expand_event_variant(runtime, path, index, instance, generics));
event_conversions.extend(expand_event_conversion(scrate, path, instance, &pallet_event));
events_metadata.extend(expand_event_metadata(scrate, path, &pallet_event));
}
}

Ok(quote!{
#[derive(
Clone, PartialEq, Eq,
#scrate::codec::Encode,
#scrate::codec::Decode,
#scrate::RuntimeDebug,
)]
#[allow(non_camel_case_types)]
pub enum Event {
#event_variants
}

#event_conversions
})
}

fn expand_event_variant(
runtime: &Ident,
path: &PalletPath,
index: u8,
instance: Option<&Ident>,
generics: &Generics,
) -> TokenStream {
let part_is_generic = !generics.params.is_empty();
let mod_name = &path.mod_name();

match (instance, part_is_generic) {
(Some(inst), true) => {
let variant = format_ident!("{}_{}", mod_name, inst);
gui1117 marked this conversation as resolved.
Show resolved Hide resolved
quote!(#[codec(index = #index)] #variant(#path::Event<#runtime, #path::#inst>),)
}
(Some(inst), false) => {
let variant = format_ident!("{}_{}", mod_name, inst);
quote!(#[codec(index = #index)] #variant(#path::Event<#path::#inst>),)
}
(None, true) => {
quote!(#[codec(index = #index)] #mod_name(#path::Event<#runtime>),)
}
(None, false) => {
quote!(#[codec(index = #index)] #mod_name(#path::Event),)
}
}
}

fn expand_event_conversion(
scrate: &TokenStream,
path: &PalletPath,
instance: Option<&Ident>,
pallet_event: &TokenStream,
) -> TokenStream {
let mod_name = path.mod_name();
let variant = if let Some(inst) = instance {
format_ident!("{}_{}", mod_name, inst)
} else {
mod_name
};

quote!{
impl From<#pallet_event> for Event {
fn from(x: #pallet_event) -> Self {
Event::#variant(x)
}
}
impl #scrate::sp_std::convert::TryInto<#pallet_event> for Event {
type Error = ();

fn try_into(self) -> #scrate::sp_std::result::Result<#pallet_event, Self::Error> {
match self {
Self::#variant(evt) => Ok(evt),
_ => Err(()),
}
}
}
}
}

fn expand_event_metadata(
scrate: &TokenStream,
path: &PalletPath,
pallet_event: &TokenStream,
) -> TokenStream {
let mod_name = path.mod_name();

quote!{(stringify!(#mod_name), #scrate::event::FnEncode(#pallet_event::metadata)),}
}
Loading