Skip to content
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
2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn_single_line = false
where_single_line = false
imports_indent = "Block"
imports_layout = "Vertical" # changed
merge_imports = true # changed
imports_granularity = "Crate" # changed
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added

### Changed

### Fixed
- Derive: use known crate name aliases [(#61)](https://github.com/paritytech/scale-info/pull/61)

## [0.5.0] - 2021-01-27
### Added
Expand Down
1 change: 1 addition & 0 deletions derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ proc-macro = true
quote = "1.0"
syn = { version = "1.0", features = ["derive", "visit", "visit-mut"] }
proc-macro2 = "1.0"
proc-macro-crate = "0.1.5"
43 changes: 0 additions & 43 deletions derive/src/impl_wrapper.rs

This file was deleted.

66 changes: 45 additions & 21 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
extern crate alloc;
extern crate proc_macro;

mod impl_wrapper;
mod trait_bounds;

use alloc::{
Expand All @@ -28,7 +27,10 @@ use alloc::{
vec::Vec,
};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro2::{
Span,
TokenStream as TokenStream2,
};
use quote::quote;
use syn::{
parse::{
Expand All @@ -48,6 +50,7 @@ use syn::{
ExprLit,
Field,
Fields,
Ident,
Lifetime,
Lit,
Meta,
Expand All @@ -73,42 +76,63 @@ fn generate(input: TokenStream2) -> Result<TokenStream2> {
fn generate_type(input: TokenStream2) -> Result<TokenStream2> {
let mut ast: DeriveInput = syn::parse2(input.clone())?;

let scale_info = crate_name_ident("scale-info")?;
let parity_scale_codec = crate_name_ident("parity-scale-codec")?;

let ident = &ast.ident;

ast.generics
.lifetimes_mut()
.for_each(|l| *l = parse_quote!('static));

let (_, ty_generics, _) = ast.generics.split_for_impl();
let where_clause = trait_bounds::make_where_clause(ident, &ast.generics, &ast.data)?;
let where_clause = trait_bounds::make_where_clause(
ident,
&ast.generics,
&ast.data,
&scale_info,
&parity_scale_codec,
)?;

let generic_type_ids = ast.generics.type_params().map(|ty| {
let ty_ident = &ty.ident;
quote! {
::scale_info::meta_type::<#ty_ident>()
:: #scale_info ::meta_type::<#ty_ident>()
}
});

let ast: DeriveInput = syn::parse2(input.clone())?;
let build_type = match &ast.data {
Data::Struct(ref s) => generate_composite_type(s),
Data::Enum(ref e) => generate_variant_type(e),
Data::Struct(ref s) => generate_composite_type(s, &scale_info),
Data::Enum(ref e) => generate_variant_type(e, &scale_info),
Data::Union(_) => return Err(Error::new_spanned(input, "Unions not supported")),
};
let generic_types = ast.generics.type_params();
let type_info_impl = quote! {
impl <#( #generic_types ),*> ::scale_info::TypeInfo for #ident #ty_generics #where_clause {
impl <#( #generic_types ),*> :: #scale_info ::TypeInfo for #ident #ty_generics #where_clause {
type Identity = Self;
fn type_info() -> ::scale_info::Type {
::scale_info::Type::builder()
.path(::scale_info::Path::new(stringify!(#ident), module_path!()))
.type_params(::scale_info::prelude::vec![ #( #generic_type_ids ),* ])
fn type_info() -> :: #scale_info ::Type {
:: #scale_info ::Type::builder()
.path(:: #scale_info ::Path::new(stringify!(#ident), module_path!()))
.type_params(:: #scale_info ::prelude::vec![ #( #generic_type_ids ),* ])
.#build_type
}
}
};

Ok(impl_wrapper::wrap(ident, "TYPE_INFO", type_info_impl))
Ok(quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _: () = {
#type_info_impl;
};
})
}

/// Get the name of a crate, to be robust against renamed dependencies.
fn crate_name_ident(name: &str) -> Result<Ident> {
proc_macro_crate::crate_name(name)
.map(|crate_name| Ident::new(&crate_name, Span::call_site()))
.map_err(|e| syn::Error::new(Span::call_site(), &e))
}

type FieldsList = Punctuated<Field, Comma>;
Expand Down Expand Up @@ -181,7 +205,7 @@ fn clean_type_string(input: &str) -> String {
.replace("& \'", "&'")
}

fn generate_composite_type(data_struct: &DataStruct) -> TokenStream2 {
fn generate_composite_type(data_struct: &DataStruct, scale_info: &Ident) -> TokenStream2 {
let fields = match data_struct.fields {
Fields::Named(ref fs) => {
let fields = generate_fields(&fs.named);
Expand All @@ -198,13 +222,13 @@ fn generate_composite_type(data_struct: &DataStruct) -> TokenStream2 {
}
};
quote! {
composite(::scale_info::build::Fields::#fields)
composite(:: #scale_info ::build::Fields::#fields)
}
}

type VariantList = Punctuated<Variant, Comma>;

fn generate_c_like_enum_def(variants: &VariantList) -> TokenStream2 {
fn generate_c_like_enum_def(variants: &VariantList, scale_info: &Ident) -> TokenStream2 {
let variants = variants.into_iter().enumerate().map(|(i, v)| {
let name = &v.ident;
let discriminant = if let Some((
Expand All @@ -228,7 +252,7 @@ fn generate_c_like_enum_def(variants: &VariantList) -> TokenStream2 {
});
quote! {
variant(
::scale_info::build::Variants::fieldless()
:: #scale_info ::build::Variants::fieldless()
#( #variants )*
)
}
Expand All @@ -241,11 +265,11 @@ fn is_c_like_enum(variants: &VariantList) -> bool {
variants.iter().all(|v| matches!(v.fields, Fields::Unit))
}

fn generate_variant_type(data_enum: &DataEnum) -> TokenStream2 {
fn generate_variant_type(data_enum: &DataEnum, scale_info: &Ident) -> TokenStream2 {
let variants = &data_enum.variants;

if is_c_like_enum(&variants) {
return generate_c_like_enum_def(variants)
return generate_c_like_enum_def(variants, scale_info)
}

let variants = variants.into_iter().map(|v| {
Expand All @@ -257,7 +281,7 @@ fn generate_variant_type(data_enum: &DataEnum) -> TokenStream2 {
quote! {
.variant(
#v_name,
::scale_info::build::Fields::named()
:: #scale_info ::build::Fields::named()
#( #fields)*
)
}
Expand All @@ -267,7 +291,7 @@ fn generate_variant_type(data_enum: &DataEnum) -> TokenStream2 {
quote! {
.variant(
#v_name,
::scale_info::build::Fields::unnamed()
:: #scale_info ::build::Fields::unnamed()
#( #fields)*
)
}
Expand All @@ -281,7 +305,7 @@ fn generate_variant_type(data_enum: &DataEnum) -> TokenStream2 {
});
quote! {
variant(
::scale_info::build::Variants::with_fields()
:: #scale_info ::build::Variants::with_fields()
#( #variants)*
)
}
Expand Down
10 changes: 6 additions & 4 deletions derive/src/trait_bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ pub fn make_where_clause<'a>(
input_ident: &'a Ident,
generics: &'a Generics,
data: &'a syn::Data,
scale_info: &Ident,
parity_scale_codec: &Ident,
) -> Result<WhereClause> {
let mut where_clause = generics.where_clause.clone().unwrap_or_else(|| {
WhereClause {
Expand All @@ -57,21 +59,21 @@ pub fn make_where_clause<'a>(
if is_compact {
where_clause
.predicates
.push(parse_quote!(#ty : ::scale::HasCompact));
.push(parse_quote!(#ty : :: #parity_scale_codec ::HasCompact));
where_clause
.predicates
.push(parse_quote!(<#ty as ::scale::HasCompact>::Type : ::scale_info::TypeInfo + 'static));
.push(parse_quote!(<#ty as :: #parity_scale_codec ::HasCompact>::Type : :: #scale_info ::TypeInfo + 'static));
} else {
where_clause
.predicates
.push(parse_quote!(#ty : ::scale_info::TypeInfo + 'static));
.push(parse_quote!(#ty : :: #scale_info ::TypeInfo + 'static));
}
});

generics.type_params().into_iter().for_each(|type_param| {
let ident = type_param.ident.clone();
let mut bounds = type_param.bounds.clone();
bounds.push(parse_quote!(::scale_info::TypeInfo));
bounds.push(parse_quote!(:: #scale_info ::TypeInfo));
bounds.push(parse_quote!('static));
where_clause
.predicates
Expand Down
5 changes: 1 addition & 4 deletions test_suite/tests/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
#![cfg_attr(not(feature = "std"), no_std)]

use pretty_assertions::assert_eq;
use scale::{
Compact,
Encode,
};
use scale::Encode;
use scale_info::{
build::*,
prelude::{
Expand Down