Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to reexport crate #145

Merged
merged 3 commits into from
Mar 14, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "scale-info"
version = "2.0.1"
version = "2.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2021"
rust-version = "1.56.1"
Expand All @@ -17,7 +17,7 @@ include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE"]
[dependencies]
bitvec = { version = "1", default-features = false, features = ["alloc"], optional = true }
cfg-if = "1.0"
scale-info-derive = { version = "2.0.0", path = "derive", default-features = false, optional = true }
scale-info-derive = { version = "2.1.0", path = "derive", default-features = false, optional = true }
serde = { version = "1", default-features = false, optional = true, features = ["derive", "alloc"] }
derive_more = { version = "0.99.1", default-features = false, features = ["from"] }
scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] }
Expand Down
2 changes: 1 addition & 1 deletion derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "scale-info-derive"
version = "2.0.0"
version = "2.1.0"
authors = [
"Parity Technologies <admin@parity.io>",
"Centrality Developers <support@centrality.ai>",
Expand Down
45 changes: 45 additions & 0 deletions derive/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ pub struct Attributes {
bounds: Option<BoundsAttr>,
skip_type_params: Option<SkipTypeParamsAttr>,
capture_docs: Option<CaptureDocsAttr>,
crate_path: Option<CratePathAttr>,
}

impl Attributes {
Expand All @@ -44,6 +45,7 @@ impl Attributes {
let mut bounds = None;
let mut skip_type_params = None;
let mut capture_docs = None;
let mut crate_path = None;

let attributes_parser = |input: &ParseBuffer| {
let attrs: Punctuated<ScaleInfoAttr, Token![,]> =
Expand Down Expand Up @@ -87,6 +89,17 @@ impl Attributes {
}
capture_docs = Some(parsed_capture_docs);
}

ScaleInfoAttr::CratePath(parsed_crate_path) => {
if crate_path.is_some() {
return Err(syn::Error::new(
attr.span(),
"Duplicate `crate` attributes",
))
}

crate_path = Some(parsed_crate_path);
}
}
}
}
Expand Down Expand Up @@ -116,6 +129,7 @@ impl Attributes {
bounds,
skip_type_params,
capture_docs,
crate_path,
})
}

Expand All @@ -137,6 +151,11 @@ impl Attributes {
.as_ref()
.unwrap_or(&CaptureDocsAttr::Default)
}

/// Get the `#[scale_info(crate = path::to::crate)]` attribute, if present.
pub fn crate_path(&self) -> Option<&CratePathAttr> {
self.crate_path.as_ref()
}
}

/// Parsed representation of the `#[scale_info(bounds(...))]` attribute.
Expand Down Expand Up @@ -230,11 +249,34 @@ impl Parse for CaptureDocsAttr {
}
}

/// Parsed representation of the `#[scale_info(crate = "..")]` attribute.
#[derive(Clone)]
pub struct CratePathAttr {
path: syn::Path,
}

impl CratePathAttr {
pub fn path(&self) -> &syn::Path {
&self.path
}
}

impl Parse for CratePathAttr {
fn parse(input: &ParseBuffer) -> syn::Result<Self> {
input.parse::<Token![crate]>()?;
input.parse::<Token![=]>()?;
let path = input.parse::<syn::Path>()?;

Ok(Self { path })
}
}

/// Parsed representation of one of the `#[scale_info(..)]` attributes.
pub enum ScaleInfoAttr {
Bounds(BoundsAttr),
SkipTypeParams(SkipTypeParamsAttr),
CaptureDocs(CaptureDocsAttr),
CratePath(CratePathAttr),
}

impl Parse for ScaleInfoAttr {
Expand All @@ -249,6 +291,9 @@ impl Parse for ScaleInfoAttr {
} else if lookahead.peek(keywords::capture_docs) {
let capture_docs = input.parse()?;
Ok(Self::CaptureDocs(capture_docs))
} else if lookahead.peek(Token![crate]) {
let crate_path = input.parse()?;
Ok(Self::CratePath(crate_path))
} else {
Err(lookahead.error())
}
Expand Down
55 changes: 30 additions & 25 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ mod utils;
use self::attr::{
Attributes,
CaptureDocsAttr,
CratePathAttr,
};
use proc_macro::TokenStream;
use proc_macro2::{
Expand Down Expand Up @@ -69,73 +70,71 @@ fn generate(input: TokenStream2) -> Result<TokenStream2> {

struct TypeInfoImpl {
ast: DeriveInput,
scale_info: Ident,
attrs: Attributes,
}

impl TypeInfoImpl {
fn parse(input: TokenStream2) -> Result<Self> {
let ast: DeriveInput = syn::parse2(input)?;
let scale_info = crate_name_ident("scale-info")?;
let attrs = attr::Attributes::from_ast(&ast)?;

Ok(Self {
ast,
scale_info,
attrs,
})
Ok(Self { ast, attrs })
}

fn expand(&self) -> Result<TokenStream2> {
let ident = &self.ast.ident;
let scale_info = &self.scale_info;
let scale_info = crate_path(self.attrs.crate_path())?;

let where_clause = trait_bounds::make_where_clause(
&self.attrs,
ident,
&self.ast.generics,
&self.ast.data,
&self.scale_info,
&scale_info,
)?;

let (impl_generics, ty_generics, _) = self.ast.generics.split_for_impl();

let type_params = self.ast.generics.type_params().map(|tp| {
let ty_ident = &tp.ident;
let ty = if self.attrs.skip_type_params().map_or(true, |skip| !skip.skip(tp)) {
quote! { ::core::option::Option::Some(:: #scale_info ::meta_type::<#ty_ident>()) }
quote! { ::core::option::Option::Some(#scale_info ::meta_type::<#ty_ident>()) }
} else {
quote! { ::core::option::Option::None }
};
quote! {
:: #scale_info ::TypeParameter::new(::core::stringify!(#ty_ident), #ty)
#scale_info ::TypeParameter::new(::core::stringify!(#ty_ident), #ty)
}
});

let build_type = match &self.ast.data {
Data::Struct(ref s) => self.generate_composite_type(s),
Data::Enum(ref e) => self.generate_variant_type(e, scale_info),
Data::Struct(ref s) => self.generate_composite_type(s, &scale_info),
Data::Enum(ref e) => self.generate_variant_type(e, &scale_info),
Data::Union(_) => {
return Err(Error::new_spanned(&self.ast, "Unions not supported"))
}
};
let docs = self.generate_docs(&self.ast.attrs);

Ok(quote! {
impl #impl_generics :: #scale_info ::TypeInfo for #ident #ty_generics #where_clause {
impl #impl_generics #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(::core::stringify!(#ident), ::core::module_path!()))
.type_params(:: #scale_info ::prelude::vec![ #( #type_params ),* ])
fn type_info() -> #scale_info ::Type {
#scale_info ::Type::builder()
.path(#scale_info ::Path::new(::core::stringify!(#ident), ::core::module_path!()))
.type_params(#scale_info ::prelude::vec![ #( #type_params ),* ])
#docs
.#build_type
}
}
})
}

fn generate_composite_type(&self, data_struct: &DataStruct) -> TokenStream2 {
fn generate_composite_type(
&self,
data_struct: &DataStruct,
scale_info: &syn::Path,
) -> TokenStream2 {
let fields = match data_struct.fields {
Fields::Named(ref fs) => {
let fields = self.generate_fields(&fs.named);
Expand All @@ -151,9 +150,9 @@ impl TypeInfoImpl {
}
}
};
let scale_info = &self.scale_info;

quote! {
composite(:: #scale_info ::build::Fields::#fields)
composite(#scale_info ::build::Fields::#fields)
}
}

Expand Down Expand Up @@ -201,7 +200,7 @@ impl TypeInfoImpl {
fn generate_variant_type(
&self,
data_enum: &DataEnum,
scale_info: &Ident,
scale_info: &syn::Path,
) -> TokenStream2 {
let variants = &data_enum.variants;

Expand All @@ -219,15 +218,15 @@ impl TypeInfoImpl {
Fields::Named(ref fs) => {
let fields = self.generate_fields(&fs.named);
Some(quote! {
.fields(:: #scale_info::build::Fields::named()
.fields(#scale_info::build::Fields::named()
#( #fields )*
)
})
}
Fields::Unnamed(ref fs) => {
let fields = self.generate_fields(&fs.unnamed);
Some(quote! {
.fields(:: #scale_info::build::Fields::unnamed()
.fields(#scale_info::build::Fields::unnamed()
#( #fields )*
)
})
Expand All @@ -246,7 +245,7 @@ impl TypeInfoImpl {
});
quote! {
variant(
:: #scale_info ::build::Variants::new()
#scale_info ::build::Variants::new()
#( #variants )*
)
}
Expand Down Expand Up @@ -301,6 +300,12 @@ fn crate_name_ident(name: &str) -> Result<Ident> {
.map_err(|e| syn::Error::new(Span::call_site(), &e))
}

fn crate_path(crate_path_attr: Option<&CratePathAttr>) -> Result<syn::Path> {
crate_path_attr
.map(|path_attr| Ok(path_attr.path().clone()))
.unwrap_or_else(|| crate_name_ident("scale-info").map(|ident| ident.into()))
}

fn clean_type_string(input: &str) -> String {
input
.replace(" ::", "::")
Expand Down
2 changes: 1 addition & 1 deletion derive/src/trait_bounds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn make_where_clause<'a>(
input_ident: &'a Ident,
generics: &'a Generics,
data: &'a syn::Data,
scale_info: &Ident,
scale_info: &syn::Path,
) -> Result<WhereClause> {
let mut where_clause = generics.where_clause.clone().unwrap_or_else(|| {
WhereClause {
Expand Down
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,22 @@
//! binary size as small as possible, so the `docs` feature would be disabled. In case the docs for
//! some types is necessary they could be enabled on a per-type basis with the above attribute.
//!
//! #### `#[scale_info(crate = path::to::crate)]`
//!
//! Specify a path to the scale-info crate instance to use when referring to the APIs from generated
//! code. This is normally only applicable when invoking re-exported scale-info derives from a public
//! macro in a different crate. For example:
//! ```ignore
//! use scale_info_reexport::info::TypeInfo;
//!
//! #[derive(TypeInfo)]
//! #[scale_info(crate = scale_info_reexport::info)]
//! enum TestEnum {
//! FirstVariant,
//! SecondVariant,
//! }
//! ```
//!
//! # Forms
//!
//! To bridge between compile-time type information and runtime the
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: expected one of: `bounds`, `skip_type_params`, `capture_docs`
error: expected one of: `bounds`, `skip_type_params`, `capture_docs`, `crate`
--> tests/ui/fail_with_invalid_scale_info_attrs.rs:5:14
|
5 | #[scale_info(foo)]
Expand Down