cargo fmt with stable defaults (#876)

This commit is contained in:
James Wilson
2023-03-21 16:53:47 +00:00
committed by GitHub
parent c63ff6ec6d
commit 7c252fccf7
110 changed files with 663 additions and 1949 deletions
+9 -33
View File
@@ -4,26 +4,10 @@
use crate::api::CodegenError;
use super::{
CratePath,
Derives,
Field,
TypeDefParameters,
TypeGenerator,
TypeParameter,
TypePath,
};
use super::{CratePath, Derives, Field, TypeDefParameters, TypeGenerator, TypeParameter, TypePath};
use proc_macro2::TokenStream;
use quote::{
format_ident,
quote,
};
use scale_info::{
form::PortableForm,
Type,
TypeDef,
TypeDefPrimitive,
};
use quote::{format_ident, quote};
use scale_info::{form::PortableForm, Type, TypeDef, TypeDefPrimitive};
/// Representation of a type which consists of a set of fields. Used to generate Rust code for
/// either a standalone `struct` definition, or an `enum` variant.
@@ -98,11 +82,7 @@ impl CompositeDef {
}
/// Construct a definition which will generate code for an `enum` variant.
pub fn enum_variant_def(
ident: &str,
fields: CompositeDefFields,
docs: &[String],
) -> Self {
pub fn enum_variant_def(ident: &str, fields: CompositeDefFields, docs: &[String]) -> Self {
let name = format_ident!("{}", ident);
let docs_token = Some(quote! { #( #[doc = #docs ] )* });
Self {
@@ -186,20 +166,16 @@ impl CompositeDefFields {
type_gen: &TypeGenerator,
) -> Result<Self, CodegenError> {
if fields.is_empty() {
return Ok(Self::NoFields)
return Ok(Self::NoFields);
}
let mut named_fields = Vec::new();
let mut unnamed_fields = Vec::new();
for field in fields {
let type_path =
type_gen.resolve_field_type_path(field.ty().id(), parent_type_params);
let field_type = CompositeDefFieldType::new(
field.ty().id(),
type_path,
field.type_name().cloned(),
);
let type_path = type_gen.resolve_field_type_path(field.ty().id(), parent_type_params);
let field_type =
CompositeDefFieldType::new(field.ty().id(), type_path, field.type_name().cloned());
if let Some(name) = field.name() {
let field_name = format_ident!("{}", name);
@@ -210,7 +186,7 @@ impl CompositeDefFields {
}
if !named_fields.is_empty() && !unnamed_fields.is_empty() {
return Err(CodegenError::InvalidFields(name.into()))
return Err(CodegenError::InvalidFields(name.into()));
}
let res = if !named_fields.is_empty() {
+6 -18
View File
@@ -3,15 +3,9 @@
// see LICENSE for license details.
use crate::CratePath;
use syn::{
parse_quote,
Path,
};
use syn::{parse_quote, Path};
use std::collections::{
HashMap,
HashSet,
};
use std::collections::{HashMap, HashSet};
#[derive(Debug, Clone)]
pub struct DerivesRegistry {
@@ -92,17 +86,11 @@ impl Derives {
let mut attributes = HashSet::new();
derives.insert(syn::parse_quote!(#crate_path::ext::scale_encode::EncodeAsType));
let encode_crate_path =
quote::quote! { #crate_path::ext::scale_encode }.to_string();
attributes.insert(
syn::parse_quote!(#[encode_as_type(crate_path = #encode_crate_path)]),
);
let encode_crate_path = quote::quote! { #crate_path::ext::scale_encode }.to_string();
attributes.insert(syn::parse_quote!(#[encode_as_type(crate_path = #encode_crate_path)]));
derives.insert(syn::parse_quote!(#crate_path::ext::scale_decode::DecodeAsType));
let decode_crate_path =
quote::quote! { #crate_path::ext::scale_decode }.to_string();
attributes.insert(
syn::parse_quote!(#[decode_as_type(crate_path = #decode_crate_path)]),
);
let decode_crate_path = quote::quote! { #crate_path::ext::scale_decode }.to_string();
attributes.insert(syn::parse_quote!(#[decode_as_type(crate_path = #decode_crate_path)]));
derives.insert(syn::parse_quote!(#crate_path::ext::codec::Encode));
derives.insert(syn::parse_quote!(#crate_path::ext::codec::Decode));
+61 -113
View File
@@ -12,46 +12,20 @@ mod type_def_params;
mod type_path;
use darling::FromMeta;
use proc_macro2::{
Ident,
Span,
TokenStream,
};
use quote::{
quote,
ToTokens,
};
use scale_info::{
form::PortableForm,
PortableRegistry,
Type,
TypeDef,
};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use scale_info::{form::PortableForm, PortableRegistry, Type, TypeDef};
use std::collections::BTreeMap;
use crate::api::CodegenError;
pub use self::{
composite_def::{
CompositeDef,
CompositeDefFieldType,
CompositeDefFields,
},
derives::{
Derives,
DerivesRegistry,
},
substitutes::{
AbsolutePath,
TypeSubstitutes,
},
composite_def::{CompositeDef, CompositeDefFieldType, CompositeDefFields},
derives::{Derives, DerivesRegistry},
substitutes::{AbsolutePath, TypeSubstitutes},
type_def::TypeDefGen,
type_def_params::TypeDefParameters,
type_path::{
TypeParameter,
TypePath,
TypePathType,
},
type_path::{TypeParameter, TypePath, TypePathType},
};
pub type Field = scale_info::Field<PortableForm>;
@@ -104,13 +78,13 @@ impl<'a> TypeGenerator<'a> {
// Don't generate a type if it was substituted - the target type might
// not be in the type registry + our resolution already performs the substitution.
if self.type_substitutes.for_path(path).is_some() {
continue
continue;
}
let namespace = path.namespace();
// prelude types e.g. Option/Result have no namespace, so we don't generate them
if namespace.is_empty() {
continue
continue;
}
// Lazily create submodules for the encountered namespace path, if they don't exist
@@ -126,12 +100,7 @@ impl<'a> TypeGenerator<'a> {
innermost_module.types.insert(
path.clone(),
TypeDefGen::from_type(
ty.ty(),
self,
&self.crate_path,
self.should_gen_docs,
)?,
TypeDefGen::from_type(ty.ty(), self, &self.crate_path, self.should_gen_docs)?,
);
}
@@ -194,7 +163,7 @@ impl<'a> TypeGenerator<'a> {
.iter()
.find(|tp| tp.concrete_type_id == id)
{
return TypePath::Parameter(parent_type_param.clone())
return TypePath::Parameter(parent_type_param.clone());
}
let mut ty = self.resolve_type(id);
@@ -212,9 +181,8 @@ impl<'a> TypeGenerator<'a> {
.type_params()
.iter()
.filter_map(|f| {
f.ty().map(|f| {
self.resolve_type_path_recurse(f.id(), false, parent_type_params)
})
f.ty()
.map(|f| self.resolve_type_path_recurse(f.id(), false, parent_type_params))
})
.collect();
@@ -239,71 +207,53 @@ impl<'a> TypeGenerator<'a> {
)
}
}
TypeDef::Primitive(primitive) => {
TypePathType::Primitive {
def: primitive.clone(),
}
}
TypeDef::Array(arr) => {
TypePathType::Array {
len: arr.len() as usize,
of: Box::new(self.resolve_type_path_recurse(
arr.type_param().id(),
false,
parent_type_params,
)),
}
}
TypeDef::Sequence(seq) => {
TypePathType::Vec {
of: Box::new(self.resolve_type_path_recurse(
seq.type_param().id(),
false,
parent_type_params,
)),
}
}
TypeDef::Tuple(tuple) => {
TypePathType::Tuple {
elements: tuple
.fields()
.iter()
.map(|f| {
self.resolve_type_path_recurse(
f.id(),
false,
parent_type_params,
)
})
.collect(),
}
}
TypeDef::Compact(compact) => {
TypePathType::Compact {
inner: Box::new(self.resolve_type_path_recurse(
compact.type_param().id(),
false,
parent_type_params,
)),
is_field,
crate_path: self.crate_path.clone(),
}
}
TypeDef::BitSequence(bitseq) => {
TypePathType::BitVec {
bit_order_type: Box::new(self.resolve_type_path_recurse(
bitseq.bit_order_type().id(),
false,
parent_type_params,
)),
bit_store_type: Box::new(self.resolve_type_path_recurse(
bitseq.bit_store_type().id(),
false,
parent_type_params,
)),
crate_path: self.crate_path.clone(),
}
}
TypeDef::Primitive(primitive) => TypePathType::Primitive {
def: primitive.clone(),
},
TypeDef::Array(arr) => TypePathType::Array {
len: arr.len() as usize,
of: Box::new(self.resolve_type_path_recurse(
arr.type_param().id(),
false,
parent_type_params,
)),
},
TypeDef::Sequence(seq) => TypePathType::Vec {
of: Box::new(self.resolve_type_path_recurse(
seq.type_param().id(),
false,
parent_type_params,
)),
},
TypeDef::Tuple(tuple) => TypePathType::Tuple {
elements: tuple
.fields()
.iter()
.map(|f| self.resolve_type_path_recurse(f.id(), false, parent_type_params))
.collect(),
},
TypeDef::Compact(compact) => TypePathType::Compact {
inner: Box::new(self.resolve_type_path_recurse(
compact.type_param().id(),
false,
parent_type_params,
)),
is_field,
crate_path: self.crate_path.clone(),
},
TypeDef::BitSequence(bitseq) => TypePathType::BitVec {
bit_order_type: Box::new(self.resolve_type_path_recurse(
bitseq.bit_order_type().id(),
false,
parent_type_params,
)),
bit_store_type: Box::new(self.resolve_type_path_recurse(
bitseq.bit_store_type().id(),
false,
parent_type_params,
)),
crate_path: self.crate_path.clone(),
},
};
TypePath::Type(ty)
@@ -372,9 +322,7 @@ impl Module {
}
/// Returns the generated types.
pub fn types(
&self,
) -> impl Iterator<Item = (&scale_info::Path<PortableForm>, &TypeDefGen)> {
pub fn types(&self) -> impl Iterator<Item = (&scale_info::Path<PortableForm>, &TypeDefGen)> {
self.types.iter()
}
+14 -30
View File
@@ -2,18 +2,9 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use crate::{
api::CodegenError,
CratePath,
};
use std::{
borrow::Cow,
collections::HashMap,
};
use syn::{
parse_quote,
spanned::Spanned as _,
};
use crate::{api::CodegenError, CratePath};
use std::{borrow::Cow, collections::HashMap};
use syn::{parse_quote, spanned::Spanned as _};
use super::TypePath;
@@ -160,8 +151,7 @@ impl TypeSubstitutes {
.iter()
.position(|&src| src == arg)
.map(|src_idx| {
u8::try_from(src_idx)
.expect("type arguments to be fewer than 256; qed")
u8::try_from(src_idx).expect("type arguments to be fewer than 256; qed")
})
})
.collect();
@@ -201,15 +191,13 @@ impl TypeSubstitutes {
mapping: &TypeParamMapping,
) -> Cow<'a, [TypePath]> {
match mapping {
TypeParamMapping::Specified(mapping) => {
Cow::Owned(
mapping
.iter()
.filter_map(|&idx| params.get(idx as usize))
.cloned()
.collect(),
)
}
TypeParamMapping::Specified(mapping) => Cow::Owned(
mapping
.iter()
.filter_map(|&idx| params.get(idx as usize))
.cloned()
.collect(),
),
_ => Cow::Borrowed(params),
}
}
@@ -259,13 +247,9 @@ fn type_args(path_args: &syn::PathArguments) -> impl Iterator<Item = &syn::Path>
_ => None,
};
args_opt.into_iter().flatten().filter_map(|arg| {
match arg {
syn::GenericArgument::Type(syn::Type::Path(type_path)) => {
Some(&type_path.path)
}
_ => None,
}
args_opt.into_iter().flatten().filter_map(|arg| match arg {
syn::GenericArgument::Type(syn::Type::Path(type_path)) => Some(&type_path.path),
_ => None,
})
}
+2 -10
View File
@@ -4,12 +4,7 @@
use super::*;
use pretty_assertions::assert_eq;
use scale_info::{
meta_type,
scale,
Registry,
TypeInfo,
};
use scale_info::{meta_type, scale, Registry, TypeInfo};
use syn::parse_quote;
const MOD_PATH: &[&str] = &["subxt_codegen", "types", "tests"];
@@ -813,10 +808,7 @@ fn generics_nested() {
#[test]
fn generate_bitvec() {
use bitvec::{
order::{
Lsb0,
Msb0,
},
order::{Lsb0, Msb0},
vec::BitVec,
};
+14 -30
View File
@@ -5,24 +5,12 @@
use crate::api::CodegenError;
use super::{
CompositeDef,
CompositeDefFields,
CratePath,
Derives,
TypeDefParameters,
TypeGenerator,
CompositeDef, CompositeDefFields, CratePath, Derives, TypeDefParameters, TypeGenerator,
TypeParameter,
};
use proc_macro2::TokenStream;
use quote::{
format_ident,
quote,
};
use scale_info::{
form::PortableForm,
Type,
TypeDef,
};
use quote::{format_ident, quote};
use scale_info::{form::PortableForm, Type, TypeDef};
use syn::parse_quote;
/// Generates a Rust `struct` or `enum` definition based on the supplied [`scale-info::Type`].
@@ -55,18 +43,16 @@ impl TypeDefGen {
.type_params()
.iter()
.enumerate()
.filter_map(|(i, tp)| {
match tp.ty() {
Some(ty) => {
let tp_name = format_ident!("_{}", i);
Some(TypeParameter {
concrete_type_id: ty.id(),
original_name: tp.name().clone(),
name: tp_name,
})
}
None => None,
.filter_map(|(i, tp)| match tp.ty() {
Some(ty) => {
let tp_name = format_ident!("_{}", i);
Some(TypeParameter {
concrete_type_id: ty.id(),
original_name: tp.name().clone(),
name: tp_name,
})
}
None => None,
})
.collect::<Vec<_>>();
@@ -109,10 +95,8 @@ impl TypeDefGen {
type_gen,
)?;
type_params.update_unused(fields.field_types());
let docs =
should_gen_docs.then_some(v.docs()).unwrap_or_default();
let variant_def =
CompositeDef::enum_variant_def(v.name(), fields, docs);
let docs = should_gen_docs.then_some(v.docs()).unwrap_or_default();
let variant_def = CompositeDef::enum_variant_def(v.name(), fields, docs);
Ok((v.index(), variant_def))
})
.collect::<Result<Vec<_>, CodegenError>>()?;
+2 -5
View File
@@ -27,10 +27,7 @@ impl TypeDefParameters {
/// Update the set of unused type parameters by removing those that are used in the given
/// fields.
pub fn update_unused<'a>(
&mut self,
fields: impl Iterator<Item = &'a CompositeDefFieldType>,
) {
pub fn update_unused<'a>(&mut self, fields: impl Iterator<Item = &'a CompositeDefFieldType>) {
let mut used_type_params = BTreeSet::new();
for field in fields {
field.type_path.parent_type_params(&mut used_type_params)
@@ -43,7 +40,7 @@ impl TypeDefParameters {
/// Construct a [`core::marker::PhantomData`] for the type unused type params.
pub fn unused_params_phantom_data(&self) -> Option<syn::TypePath> {
if self.unused.is_empty() {
return None
return None;
}
let params = if self.unused.len() == 1 {
let param = self
+20 -32
View File
@@ -4,16 +4,9 @@
use crate::CratePath;
use proc_macro2::{
Ident,
TokenStream,
};
use proc_macro2::{Ident, TokenStream};
use quote::format_ident;
use scale_info::{
form::PortableForm,
Path,
TypeDefPrimitive,
};
use scale_info::{form::PortableForm, Path, TypeDefPrimitive};
use std::collections::BTreeSet;
use syn::parse_quote;
@@ -135,10 +128,7 @@ impl TypePathType {
let mut ty_path = path_segments
.iter()
.map(|s| syn::PathSegment::from(format_ident!("{}", s)))
.collect::<syn::punctuated::Punctuated<
syn::PathSegment,
syn::Token![::],
>>();
.collect::<syn::punctuated::Punctuated<syn::PathSegment, syn::Token![::]>>();
ty_path.insert(0, syn::PathSegment::from(root_mod_ident));
parse_quote!( #ty_path )
}
@@ -208,25 +198,23 @@ impl TypePathType {
let tuple = parse_quote! { (#( # elements, )* ) };
syn::Type::Tuple(tuple)
}
TypePathType::Primitive { def } => {
syn::Type::Path(match def {
TypeDefPrimitive::Bool => parse_quote!(::core::primitive::bool),
TypeDefPrimitive::Char => parse_quote!(::core::primitive::char),
TypeDefPrimitive::Str => parse_quote!(::std::string::String),
TypeDefPrimitive::U8 => parse_quote!(::core::primitive::u8),
TypeDefPrimitive::U16 => parse_quote!(::core::primitive::u16),
TypeDefPrimitive::U32 => parse_quote!(::core::primitive::u32),
TypeDefPrimitive::U64 => parse_quote!(::core::primitive::u64),
TypeDefPrimitive::U128 => parse_quote!(::core::primitive::u128),
TypeDefPrimitive::U256 => unimplemented!("not a rust primitive"),
TypeDefPrimitive::I8 => parse_quote!(::core::primitive::i8),
TypeDefPrimitive::I16 => parse_quote!(::core::primitive::i16),
TypeDefPrimitive::I32 => parse_quote!(::core::primitive::i32),
TypeDefPrimitive::I64 => parse_quote!(::core::primitive::i64),
TypeDefPrimitive::I128 => parse_quote!(::core::primitive::i128),
TypeDefPrimitive::I256 => unimplemented!("not a rust primitive"),
})
}
TypePathType::Primitive { def } => syn::Type::Path(match def {
TypeDefPrimitive::Bool => parse_quote!(::core::primitive::bool),
TypeDefPrimitive::Char => parse_quote!(::core::primitive::char),
TypeDefPrimitive::Str => parse_quote!(::std::string::String),
TypeDefPrimitive::U8 => parse_quote!(::core::primitive::u8),
TypeDefPrimitive::U16 => parse_quote!(::core::primitive::u16),
TypeDefPrimitive::U32 => parse_quote!(::core::primitive::u32),
TypeDefPrimitive::U64 => parse_quote!(::core::primitive::u64),
TypeDefPrimitive::U128 => parse_quote!(::core::primitive::u128),
TypeDefPrimitive::U256 => unimplemented!("not a rust primitive"),
TypeDefPrimitive::I8 => parse_quote!(::core::primitive::i8),
TypeDefPrimitive::I16 => parse_quote!(::core::primitive::i16),
TypeDefPrimitive::I32 => parse_quote!(::core::primitive::i32),
TypeDefPrimitive::I64 => parse_quote!(::core::primitive::i64),
TypeDefPrimitive::I128 => parse_quote!(::core::primitive::i128),
TypeDefPrimitive::I256 => unimplemented!("not a rust primitive"),
}),
TypePathType::Compact {
inner,
is_field,