diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 1cc93ad2..488b505e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -18,7 +18,7 @@ jobs: uses: actions-rs/toolchain@v1 with: profile: minimal - toolchain: nightly + toolchain: stable override: true components: rustfmt, clippy target: wasm32-unknown-unknown diff --git a/.rustfmt.toml b/.rustfmt.toml deleted file mode 100644 index 33407627..00000000 --- a/.rustfmt.toml +++ /dev/null @@ -1,64 +0,0 @@ -max_width = 90 # changed -hard_tabs = false -tab_spaces = 4 -newline_style = "Auto" -use_small_heuristics = "Default" -indent_style = "Block" -wrap_comments = false -format_code_in_doc_comments = false -comment_width = 80 -normalize_comments = true # changed -normalize_doc_attributes = false -format_strings = false -format_macro_matchers = false -format_macro_bodies = true -empty_item_single_line = true -struct_lit_single_line = true -fn_single_line = false -where_single_line = false -imports_indent = "Block" -imports_layout = "Vertical" # changed -imports_granularity = "Crate" # changed -reorder_imports = true -reorder_modules = true -reorder_impl_items = false -type_punctuation_density = "Wide" -space_before_colon = false -space_after_colon = true -spaces_around_ranges = false -binop_separator = "Front" -remove_nested_parens = true -combine_control_expr = false # changed -overflow_delimited_expr = false -struct_field_align_threshold = 0 -enum_discrim_align_threshold = 0 -match_arm_blocks = true -force_multiline_blocks = true # changed -fn_params_layout = "Tall" -brace_style = "SameLineWhere" -control_brace_style = "AlwaysSameLine" -trailing_semicolon = false # changed -trailing_comma = "Vertical" -match_block_trailing_comma = false -blank_lines_upper_bound = 1 -blank_lines_lower_bound = 0 -edition = "2021" # changed -version = "One" -merge_derives = true -use_try_shorthand = true # changed -use_field_init_shorthand = true # changed -force_explicit_abi = true -condense_wildcard_suffixes = false -color = "Auto" -unstable_features = true # changed -disable_all_formatting = false -skip_children = false -hide_parse_errors = false -error_on_line_overflow = false -error_on_unformatted = false -ignore = [] - -# Below are `rustfmt` internal settings -# -# emit_mode = "Files" -# make_backup = false diff --git a/derive/src/attr.rs b/derive/src/attr.rs index 5460a2b9..056c7736 100644 --- a/derive/src/attr.rs +++ b/derive/src/attr.rs @@ -13,10 +13,7 @@ // limitations under the License. use syn::{ - parse::{ - Parse, - ParseBuffer, - }, + parse::{Parse, ParseBuffer}, punctuated::Punctuated, spanned::Spanned, Token, @@ -55,7 +52,7 @@ impl Attributes { for attr in &item.attrs { if !attr.path.is_ident(SCALE_INFO) { - continue + continue; } let scale_info_attrs = attr.parse_args_with(attributes_parser)?; @@ -67,7 +64,7 @@ impl Attributes { return Err(syn::Error::new( attr.span(), "Duplicate `bounds` attributes", - )) + )); } bounds = Some(parsed_bounds); } @@ -76,7 +73,7 @@ impl Attributes { return Err(syn::Error::new( attr.span(), "Duplicate `skip_type_params` attributes", - )) + )); } skip_type_params = Some(parsed_skip_type_params); } @@ -85,7 +82,7 @@ impl Attributes { return Err(syn::Error::new( attr.span(), "Duplicate `capture_docs` attributes", - )) + )); } capture_docs = Some(parsed_capture_docs); } @@ -95,7 +92,7 @@ impl Attributes { return Err(syn::Error::new( attr.span(), "Duplicate `crate` attributes", - )) + )); } crate_path = Some(parsed_crate_path); @@ -119,7 +116,7 @@ impl Attributes { - skip it with `#[scale_info(skip_type_params({}))]`", type_param.ident, type_param.ident ); - return Err(syn::Error::new(type_param.span(), msg)) + return Err(syn::Error::new(type_param.span(), msg)); } } } @@ -239,12 +236,10 @@ impl Parse for CaptureDocsAttr { "default" => Ok(Self::Default), "always" => Ok(Self::Always), "never" => Ok(Self::Never), - _ => { - Err(syn::Error::new_spanned( - capture_docs_lit, - r#"Invalid capture_docs value. Expected one of: "default", "always", "never" "#, - )) - } + _ => Err(syn::Error::new_spanned( + capture_docs_lit, + r#"Invalid capture_docs value. Expected one of: "default", "always", "never" "#, + )), } } } diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 1fb1a1b3..ad2cd545 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -19,34 +19,17 @@ mod attr; mod trait_bounds; mod utils; -use self::attr::{ - Attributes, - CaptureDocsAttr, - CratePathAttr, -}; +use self::attr::{Attributes, CaptureDocsAttr, CratePathAttr}; use proc_macro::TokenStream; -use proc_macro2::{ - Span, - TokenStream as TokenStream2, -}; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{ - parse::{ - Error, - Result, - }, + parse::{Error, Result}, parse_quote, punctuated::Punctuated, token::Comma, visit_mut::VisitMut, - Data, - DataEnum, - DataStruct, - DeriveInput, - Field, - Fields, - Ident, - Lifetime, + Data, DataEnum, DataStruct, DeriveInput, Field, Fields, Ident, Lifetime, }; #[proc_macro_derive(TypeInfo, attributes(scale_info, codec))] @@ -97,7 +80,11 @@ impl TypeInfoImpl { 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)) { + 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>()) } } else { quote! { ::core::option::Option::None } @@ -110,9 +97,7 @@ impl TypeInfoImpl { let build_type = match &self.ast.data { 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")) - } + Data::Union(_) => return Err(Error::new_spanned(&self.ast, "Unions not supported")), }; let docs = self.generate_docs(&self.ast.attrs); @@ -204,11 +189,7 @@ impl TypeInfoImpl { .collect() } - fn generate_variant_type( - &self, - data_enum: &DataEnum, - scale_info: &syn::Path, - ) -> TokenStream2 { + fn generate_variant_type(&self, data_enum: &DataEnum, scale_info: &syn::Path) -> TokenStream2 { let variants = &data_enum.variants; let variants = variants @@ -272,8 +253,7 @@ impl TypeInfoImpl { if meta.path.get_ident().map_or(false, |ident| ident == "doc") { if let syn::Lit::Str(lit) = &meta.lit { let lit_value = lit.value(); - let stripped = - lit_value.strip_prefix(' ').unwrap_or(&lit_value); + let stripped = lit_value.strip_prefix(' ').unwrap_or(&lit_value); let lit: syn::Lit = parse_quote!(#stripped); Some(lit) } else { diff --git a/derive/src/trait_bounds.rs b/derive/src/trait_bounds.rs index da28f486..d2faf94d 100644 --- a/derive/src/trait_bounds.rs +++ b/derive/src/trait_bounds.rs @@ -18,21 +18,11 @@ use syn::{ parse_quote, punctuated::Punctuated, spanned::Spanned, - visit::{ - self, - Visit, - }, - Generics, - Result, - Type, - TypePath, - WhereClause, + visit::{self, Visit}, + Generics, Result, Type, TypePath, WhereClause, }; -use crate::{ - attr::Attributes, - utils, -}; +use crate::{attr::Attributes, utils}; /// Generates a where clause for a `TypeInfo` impl, adding `TypeInfo + 'static` bounds to all /// relevant generic types including associated types (e.g. `T::A: TypeInfo`), correctly dealing @@ -54,12 +44,13 @@ pub fn make_where_clause<'a>( data: &'a syn::Data, scale_info: &syn::Path, ) -> Result { - let mut where_clause = generics.where_clause.clone().unwrap_or_else(|| { - WhereClause { + let mut where_clause = generics + .where_clause + .clone() + .unwrap_or_else(|| WhereClause { where_token: ::default(), predicates: Punctuated::new(), - } - }); + }); // Use custom bounds as where clause. if let Some(custom_bounds) = attrs.bounds() { @@ -72,7 +63,7 @@ pub fn make_where_clause<'a>( where_clause.predicates.push(parse_quote!(#ident: 'static)) } - return Ok(where_clause) + return Ok(where_clause); } for lifetime in generics.lifetimes() { @@ -87,7 +78,7 @@ pub fn make_where_clause<'a>( .collect::>(); if ty_params_ids.is_empty() { - return Ok(where_clause) + return Ok(where_clause); } let types = collect_types_to_bind(input_ident, data, &ty_params_ids)?; @@ -160,7 +151,7 @@ fn type_or_sub_type_path_starts_with_ident(ty: &Type, ident: &Ident) -> bool { if let Some(segment) = i.path.segments.first() { if &segment.ident == self.ident { self.result = true; - return + return; } } } @@ -199,33 +190,25 @@ fn collect_types_to_bind( }; let types = match *data { - syn::Data::Struct(ref data) => { - match &data.fields { + syn::Data::Struct(ref data) => match &data.fields { + syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) + | syn::Fields::Unnamed(syn::FieldsUnnamed { + unnamed: fields, .. + }) => types_from_fields(fields), + syn::Fields::Unit => Vec::new(), + }, + + syn::Data::Enum(ref data) => data + .variants + .iter() + .flat_map(|variant| match &variant.fields { syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) | syn::Fields::Unnamed(syn::FieldsUnnamed { unnamed: fields, .. }) => types_from_fields(fields), syn::Fields::Unit => Vec::new(), - } - } - - syn::Data::Enum(ref data) => { - data.variants - .iter() - .flat_map(|variant| { - match &variant.fields { - syn::Fields::Named(syn::FieldsNamed { - named: fields, .. - }) - | syn::Fields::Unnamed(syn::FieldsUnnamed { - unnamed: fields, - .. - }) => types_from_fields(fields), - syn::Fields::Unit => Vec::new(), - } - }) - .collect() - } + }) + .collect(), syn::Data::Union(ref data) => { return Err(syn::Error::new( diff --git a/derive/src/utils.rs b/derive/src/utils.rs index cb2f4967..35f8a140 100644 --- a/derive/src/utils.rs +++ b/derive/src/utils.rs @@ -18,16 +18,7 @@ use proc_macro2::TokenStream; use quote::quote; -use syn::{ - parse::Parse, - spanned::Spanned, - AttrStyle, - Attribute, - Lit, - Meta, - NestedMeta, - Variant, -}; +use syn::{parse::Parse, spanned::Spanned, AttrStyle, Attribute, Lit, Meta, NestedMeta, Variant}; /// Look for a `#[codec(index = $int)]` attribute on a variant. If no attribute /// is found, fall back to the discriminant or just the variant index. @@ -58,7 +49,7 @@ pub fn maybe_index(variant: &Variant) -> Option { let byte = v .base10_parse::() .expect("Internal error. `#[codec(index = …)]` attribute syntax must be checked in `parity-scale-codec`. This is a bug."); - return Some(byte) + return Some(byte); } } } @@ -76,7 +67,7 @@ pub fn is_compact(field: &syn::Field) -> bool { codec_meta_item(outer_attrs, |meta| { if let NestedMeta::Meta(Meta::Path(ref path)) = meta { if path.is_ident("compact") { - return Some(()) + return Some(()); } } @@ -90,7 +81,7 @@ pub fn should_skip(attrs: &[Attribute]) -> bool { codec_meta_item(attrs.iter(), |meta| { if let NestedMeta::Meta(Meta::Path(ref path)) = meta { if path.is_ident("skip") { - return Some(path.span()) + return Some(path.span()); } } diff --git a/src/build.rs b/src/build.rs index 75129e98..909dd6f9 100644 --- a/src/build.rs +++ b/src/build.rs @@ -122,27 +122,12 @@ //! } //! ``` -use crate::prelude::{ - marker::PhantomData, - vec::Vec, -}; +use crate::prelude::{marker::PhantomData, vec::Vec}; use crate::{ - form::{ - Form, - MetaForm, - PortableForm, - }, - Field, - MetaType, - Path, - Type, - TypeDef, - TypeDefComposite, - TypeDefVariant, - TypeInfo, - TypeParameter, - Variant, + form::{Form, MetaForm, PortableForm}, + Field, MetaType, Path, Type, TypeDef, TypeDefComposite, TypeDefVariant, TypeInfo, + TypeParameter, Variant, }; /// State types for type builders which require a Path. @@ -316,11 +301,8 @@ impl FieldsBuilder { where B: Fn( FieldBuilder, - ) -> FieldBuilder< - MetaForm, - field_state::NameAssigned, - field_state::TypeAssigned, - >, + ) + -> FieldBuilder, { let builder = builder(FieldBuilder::new()); self.push_field(builder.finalize()) @@ -333,11 +315,8 @@ impl FieldsBuilder { where B: Fn( FieldBuilder, - ) -> FieldBuilder< - MetaForm, - field_state::NameNotAssigned, - field_state::TypeAssigned, - >, + ) + -> FieldBuilder, { let builder = builder(FieldBuilder::new()); self.push_field(builder.finalize()) @@ -356,16 +335,9 @@ impl FieldsBuilder { pub fn field_portable(self, builder: B) -> Self where B: Fn( - FieldBuilder< - PortableForm, - field_state::NameNotAssigned, - field_state::TypeNotAssigned, - >, - ) -> FieldBuilder< - PortableForm, - field_state::NameAssigned, - field_state::TypeAssigned, - >, + FieldBuilder, + ) + -> FieldBuilder, { let builder = builder(FieldBuilder::new()); self.push_field(builder.finalize()) @@ -377,11 +349,7 @@ impl FieldsBuilder { pub fn field_portable(self, builder: B) -> Self where B: Fn( - FieldBuilder< - PortableForm, - field_state::NameNotAssigned, - field_state::TypeNotAssigned, - >, + FieldBuilder, ) -> FieldBuilder< PortableForm, field_state::NameNotAssigned, diff --git a/src/form.rs b/src/form.rs index 63c41ea7..c02214a9 100644 --- a/src/form.rs +++ b/src/form.rs @@ -29,15 +29,9 @@ //! Other forms, such as a portable form that is still bound to the registry //! (also via lifetime tracking) are possible but current not needed. -use crate::prelude::{ - any::TypeId, - fmt::Debug, -}; +use crate::prelude::{any::TypeId, fmt::Debug}; -use crate::{ - interner::UntrackedSymbol, - meta_type::MetaType, -}; +use crate::{interner::UntrackedSymbol, meta_type::MetaType}; #[cfg(feature = "schema")] use schemars::JsonSchema; @@ -60,14 +54,7 @@ pub trait Form { /// The type representing the type. type Type: PartialEq + Eq + PartialOrd + Ord + Clone + Debug + JsonSchemaMaybe; /// The string type. - type String: AsRef - + PartialEq - + Eq - + PartialOrd - + Ord - + Clone - + Debug - + JsonSchemaMaybe; + type String: AsRef + PartialEq + Eq + PartialOrd + Ord + Clone + Debug + JsonSchemaMaybe; } /// A meta meta-type. diff --git a/src/impls.rs b/src/impls.rs index feb4e5dd..7fd6f8fb 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -13,22 +13,12 @@ // limitations under the License. use crate::prelude::{ - borrow::{ - Cow, - ToOwned, - }, + borrow::{Cow, ToOwned}, boxed::Box, - collections::{ - BTreeMap, - BTreeSet, - VecDeque, - }, + collections::{BTreeMap, BTreeSet, VecDeque}, fmt, marker::PhantomData, - ops::{ - Range, - RangeInclusive, - }, + ops::{Range, RangeInclusive}, rc::Rc, string::String, sync::Arc, @@ -37,28 +27,12 @@ use crate::prelude::{ }; use crate::{ - build::*, - MetaType, - Path, - Type, - TypeDefArray, - TypeDefCompact, - TypeDefPrimitive, - TypeDefSequence, - TypeDefTuple, - TypeInfo, + build::*, MetaType, Path, Type, TypeDefArray, TypeDefCompact, TypeDefPrimitive, + TypeDefSequence, TypeDefTuple, TypeInfo, }; use core::num::{ - NonZeroI128, - NonZeroI16, - NonZeroI32, - NonZeroI64, - NonZeroI8, - NonZeroU128, - NonZeroU16, - NonZeroU32, - NonZeroU64, - NonZeroU8, + NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroU128, NonZeroU16, + NonZeroU32, NonZeroU64, NonZeroU8, }; macro_rules! impl_metadata_for_primitives { diff --git a/src/interner.rs b/src/interner.rs index b8667b8a..601b4bba 100644 --- a/src/interner.rs +++ b/src/interner.rs @@ -23,19 +23,13 @@ //! registry. use crate::prelude::{ - collections::btree_map::{ - BTreeMap, - Entry, - }, + collections::btree_map::{BTreeMap, Entry}, marker::PhantomData, vec::Vec, }; #[cfg(feature = "serde")] -use serde::{ - Deserialize, - Serialize, -}; +use serde::{Deserialize, Serialize}; #[cfg(feature = "schema")] use schemars::JsonSchema; @@ -44,9 +38,7 @@ use schemars::JsonSchema; /// /// This can be used by self-referential types but /// can no longer be used to resolve instances. -#[derive( - Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, scale::Encode, scale::Decode, -)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, scale::Encode, scale::Decode)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(transparent))] pub struct UntrackedSymbol { @@ -201,11 +193,9 @@ where /// Returns the symbol of the given element or `None` if it hasn't been /// interned already. pub fn get(&self, sym: &T) -> Option> { - self.map.get(sym).map(|&id| { - Symbol { - id: id as u32, - marker: PhantomData, - } + self.map.get(sym).map(|&id| Symbol { + id: id as u32, + marker: PhantomData, }) } @@ -214,7 +204,7 @@ where pub fn resolve(&self, sym: Symbol) -> Option<&T> { let idx = sym.id as usize; if idx >= self.vec.len() { - return None + return None; } self.vec.get(idx) } @@ -231,16 +221,12 @@ mod tests { type StringInterner = Interner<&'static str>; - fn assert_id( - interner: &mut StringInterner, - new_symbol: &'static str, - expected_id: u32, - ) { + fn assert_id(interner: &mut StringInterner, new_symbol: &'static str, expected_id: u32) { let actual_id = interner.intern_or_get(new_symbol).1.id; assert_eq!(actual_id, expected_id,); } - fn assert_resolve(interner: &mut StringInterner, symbol_id: u32, expected_str: E) + fn assert_resolve(interner: &StringInterner, symbol_id: u32, expected_str: E) where E: Into>, { @@ -259,9 +245,9 @@ mod tests { assert_id(&mut interner, "1 2 3", 2); assert_id(&mut interner, "Hello", 0); - assert_resolve(&mut interner, 0, "Hello"); - assert_resolve(&mut interner, 1, ", World!"); - assert_resolve(&mut interner, 2, "1 2 3"); - assert_resolve(&mut interner, 3, None); + assert_resolve(&interner, 0, "Hello"); + assert_resolve(&interner, 1, ", World!"); + assert_resolve(&interner, 2, "1 2 3"); + assert_resolve(&interner, 3, None); } } diff --git a/src/lib.rs b/src/lib.rs index 0e8a6415..1e0b4911 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -345,15 +345,8 @@ pub use scale; pub use self::{ meta_type::MetaType, - portable::{ - PortableRegistry, - PortableRegistryBuilder, - PortableType, - }, - registry::{ - IntoPortable, - Registry, - }, + portable::{PortableRegistry, PortableRegistryBuilder, PortableType}, + registry::{IntoPortable, Registry}, ty::*, }; diff --git a/src/meta_type.rs b/src/meta_type.rs index cf9fc270..ad23138e 100644 --- a/src/meta_type.rs +++ b/src/meta_type.rs @@ -15,22 +15,11 @@ use crate::prelude::{ any::TypeId, cmp::Ordering, - fmt::{ - Debug, - Error as FmtError, - Formatter, - }, - hash::{ - Hash, - Hasher, - }, + fmt::{Debug, Error as FmtError, Formatter}, + hash::{Hash, Hasher}, }; -use crate::{ - form::MetaForm, - Type, - TypeInfo, -}; +use crate::{form::MetaForm, Type, TypeInfo}; /// A metatype abstraction. /// @@ -59,7 +48,7 @@ impl Eq for MetaType {} impl PartialOrd for MetaType { fn partial_cmp(&self, other: &Self) -> Option { - self.type_id.partial_cmp(&other.type_id) + Some(self.cmp(other)) } } diff --git a/src/portable.rs b/src/portable.rs index f83142f9..e9bc1da4 100644 --- a/src/portable.rs +++ b/src/portable.rs @@ -26,17 +26,8 @@ use crate::{ form::PortableForm, interner::Interner, - prelude::{ - collections::BTreeMap, - fmt::Debug, - mem, - vec::Vec, - }, - Path, - Registry, - Type, - TypeDef, - TypeDefPrimitive, + prelude::{collections::BTreeMap, fmt::Debug, mem, vec::Vec}, + Path, Registry, Type, TypeDef, TypeDefPrimitive, }; use scale::Encode; @@ -56,11 +47,9 @@ impl From for PortableRegistry { PortableRegistry { types: registry .types() - .map(|(k, v)| { - PortableType { - id: k.id, - ty: v.clone(), - } + .map(|(k, v)| PortableType { + id: k.id, + ty: v.clone(), }) .collect::>(), } @@ -108,7 +97,7 @@ impl PortableRegistry { ) -> u32 { // Type already retained; just return the new ID for it: if let Some(id) = retained_mappings.get(&id) { - return *id + return *id; } // Zero-allocation default implementation that is used as @@ -136,57 +125,39 @@ impl PortableRegistry { match &mut ty.ty.type_def { TypeDef::Composite(composite) => { for field in composite.fields.iter_mut() { - let new_id = - retain_type(field.ty.id, types, new_types, retained_mappings); + let new_id = retain_type(field.ty.id, types, new_types, retained_mappings); field.ty = new_id.into(); } } TypeDef::Variant(variant) => { for var in variant.variants.iter_mut() { for field in var.fields.iter_mut() { - let new_id = retain_type( - field.ty.id, - types, - new_types, - retained_mappings, - ); + let new_id = + retain_type(field.ty.id, types, new_types, retained_mappings); field.ty = new_id.into(); } } } TypeDef::Sequence(sequence) => { - let new_id = retain_type( - sequence.type_param.id, - types, - new_types, - retained_mappings, - ); + let new_id = + retain_type(sequence.type_param.id, types, new_types, retained_mappings); sequence.type_param = new_id.into(); } TypeDef::Array(array) => { - let new_id = retain_type( - array.type_param.id, - types, - new_types, - retained_mappings, - ); + let new_id = + retain_type(array.type_param.id, types, new_types, retained_mappings); array.type_param = new_id.into(); } TypeDef::Tuple(tuple) => { for ty in tuple.fields.iter_mut() { - let new_id = - retain_type(ty.id, types, new_types, retained_mappings); + let new_id = retain_type(ty.id, types, new_types, retained_mappings); *ty = new_id.into(); } } TypeDef::Primitive(_) => (), TypeDef::Compact(compact) => { - let new_id = retain_type( - compact.type_param.id, - types, - new_types, - retained_mappings, - ); + let new_id = + retain_type(compact.type_param.id, types, new_types, retained_mappings); compact.type_param = new_id.into(); } TypeDef::BitSequence(bit_seq) => { @@ -218,7 +189,7 @@ impl PortableRegistry { for id in 0..self.types.len() as u32 { // We don't care about the type; move on: if !filter(id) { - continue + continue; } retain_type(id, &mut self.types, &mut new_types, &mut retained_mappings); @@ -309,11 +280,9 @@ impl PortableRegistryBuilder { .elements() .iter() .enumerate() - .map(|(i, ty)| { - PortableType { - id: i as u32, - ty: ty.clone(), - } + .map(|(i, ty)| PortableType { + id: i as u32, + ty: ty.clone(), }) .collect(); PortableRegistry { types } @@ -323,11 +292,7 @@ impl PortableRegistryBuilder { #[cfg(test)] mod tests { use super::*; - use crate::{ - build::*, - prelude::vec, - *, - }; + use crate::{build::*, prelude::vec, *}; // Type IDs generated by `build_registry`. const U32_TY_ID: u32 = 0; @@ -420,9 +385,7 @@ mod tests { .variant("A".into(), |v| { v.index(0).fields( Fields::::named() - .field_portable(|f| { - f.name("primitive".into()).ty(u32_type_id) - }) + .field_portable(|f| f.name("primitive".into()).ty(u32_type_id)) .field_portable(|f| { f.name("vec_of_u32".into()).ty(vec_u32_type_id) }), @@ -446,8 +409,7 @@ mod tests { assert_eq!(ids_result.get(&VEC_U32_TY_ID), Some(&1)); assert_eq!(registry.types.len(), 2); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -468,8 +430,7 @@ mod tests { assert_eq!(ids_result.get(&ARRAY_U32_TY_ID), Some(&1)); assert_eq!(registry.types.len(), 2); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -491,11 +452,9 @@ mod tests { assert_eq!(ids_result.get(&TUPLE_TY_ID), Some(&2)); assert_eq!(registry.types.len(), 3); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); assert_eq!(registry.resolve(1).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -518,11 +477,9 @@ mod tests { assert_eq!(ids_result.get(&COMPACT_TY_ID), Some(&3)); assert_eq!(registry.types.len(), 4); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); assert_eq!(registry.resolve(1).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -551,11 +508,9 @@ mod tests { assert_eq!(ids_result.get(&BIT_SEQ_TY_ID), Some(&2)); assert_eq!(registry.types.len(), 3); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U64, vec![]); assert_eq!(registry.resolve(1).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -577,8 +532,7 @@ mod tests { assert_eq!(ids_result.get(&COMPOSITE_TY_ID), Some(&2)); assert_eq!(registry.types.len(), 3); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), @@ -608,8 +562,7 @@ mod tests { assert_eq!(ids_result.get(&VARIANT_TY_ID), Some(&2)); assert_eq!(registry.types.len(), 3); - let expected_ty = - Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); + let expected_ty = Type::new(Path::default(), vec![], TypeDefPrimitive::U32, vec![]); assert_eq!(registry.resolve(0).unwrap(), &expected_ty); let expected_ty = Type::new( Path::default(), diff --git a/src/registry.rs b/src/registry.rs index a5304b71..de45fd88 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -25,20 +25,12 @@ use crate::{ form::Form, - prelude::{ - any::TypeId, - collections::BTreeMap, - fmt::Debug, - vec::Vec, - }, + prelude::{any::TypeId, collections::BTreeMap, fmt::Debug, vec::Vec}, }; use crate::{ form::PortableForm, - interner::{ - Interner, - UntrackedSymbol, - }, + interner::{Interner, UntrackedSymbol}, meta_type::MetaType, Type, }; @@ -157,9 +149,7 @@ impl Registry { } /// Returns an iterator over the types with their keys - pub fn types( - &self, - ) -> impl Iterator, &Type)> { + pub fn types(&self) -> impl Iterator, &Type)> { self.types.iter() } } @@ -167,13 +157,7 @@ impl Registry { #[cfg(test)] mod tests { use super::*; - use crate::{ - build::Fields, - meta_type, - Path, - TypeDef, - TypeInfo, - }; + use crate::{build::Fields, meta_type, Path, TypeDef, TypeInfo}; #[test] fn recursive_struct_with_references() { diff --git a/src/tests.rs b/src/tests.rs index 735bc913..8ff51f95 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -17,10 +17,7 @@ use crate::{ prelude::{ borrow::Cow, boxed::Box, - collections::{ - BTreeMap, - BTreeSet, - }, + collections::{BTreeMap, BTreeSet}, string::String, vec, }, @@ -62,13 +59,14 @@ fn prelude_items() { Type::builder() .path(Path::prelude("Option")) .type_params(named_type_params![(T, u128)]) - .variant(Variants::new().variant("None", |v| v.index(0)).variant( - "Some", - |v| { - v.index(1) - .fields(Fields::unnamed().field(|f| f.ty::())) - } - )) + .variant( + Variants::new() + .variant("None", |v| v.index(0)) + .variant("Some", |v| { + v.index(1) + .fields(Fields::unnamed().field(|f| f.ty::())) + }) + ) ); assert_type!( Result, @@ -144,10 +142,7 @@ fn collections() { #[test] fn bitvec() { use bitvec::{ - order::{ - Lsb0, - Msb0, - }, + order::{Lsb0, Msb0}, vec::BitVec, }; @@ -231,9 +226,7 @@ fn struct_with_generics() { Type::builder() .path(Path::new("MyStruct", module_path!())) .type_params(type_params!(T)) - .composite( - Fields::named().field(|f| f.ty::().name("data").type_name("T")), - ) + .composite(Fields::named().field(|f| f.ty::().name("data").type_name("T"))) } } @@ -251,8 +244,7 @@ fn struct_with_generics() { .path(Path::new("MyStruct", "scale_info::tests")) .type_params(named_type_params![(T, Box>)]) .composite( - Fields::named() - .field(|f| f.ty::>>().name("data").type_name("T")), + Fields::named().field(|f| f.ty::>>().name("data").type_name("T")), ); assert_type!(SelfTyped, expected_type); } @@ -275,9 +267,7 @@ fn basic_struct_with_phantoms() { Type::builder() .path(Path::new("SomeStruct", module_path!())) .type_params(type_params!(T)) - .composite( - Fields::named().field(|f| f.ty::().name("a").type_name("u8")), - ) + .composite(Fields::named().field(|f| f.ty::().name("a").type_name("u8"))) } } @@ -315,14 +305,12 @@ fn basic_enum_with_index() { Variants::new() .variant("A", |v| { v.index(3).fields( - Fields::unnamed() - .field(|f| f.ty::().type_name("bool")), + Fields::unnamed().field(|f| f.ty::().type_name("bool")), ) }) .variant("B", |v| { v.index(0).fields( - Fields::named() - .field(|f| f.ty::().name("b").type_name("u8")), + Fields::named().field(|f| f.ty::().name("b").type_name("u8")), ) }) .variant("C", |v| { @@ -342,14 +330,12 @@ fn basic_enum_with_index() { .variant( Variants::new() .variant("A", |v| { - v.index(3).fields( - Fields::unnamed().field(|f| f.ty::().type_name("bool")), - ) + v.index(3) + .fields(Fields::unnamed().field(|f| f.ty::().type_name("bool"))) }) .variant("B", |v| { - v.index(0).fields( - Fields::named().field(|f| f.ty::().name("b").type_name("u8")), - ) + v.index(0) + .fields(Fields::named().field(|f| f.ty::().name("b").type_name("u8"))) }) .variant("C", |v| { v.index(2).fields( diff --git a/src/ty/composite.rs b/src/ty/composite.rs index 8bd48b6e..83bfbf7f 100644 --- a/src/ty/composite.rs +++ b/src/ty/composite.rs @@ -15,23 +15,13 @@ use crate::prelude::vec::Vec; use crate::{ - form::{ - Form, - MetaForm, - PortableForm, - }, - Field, - IntoPortable, - Registry, + form::{Form, MetaForm, PortableForm}, + Field, IntoPortable, Registry, }; use derive_more::From; use scale::Encode; #[cfg(feature = "serde")] -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; /// A composite type, consisting of either named (struct) or unnamed (tuple /// struct) fields diff --git a/src/ty/fields.rs b/src/ty/fields.rs index f99faea6..2a072d2e 100644 --- a/src/ty/fields.rs +++ b/src/ty/fields.rs @@ -14,22 +14,13 @@ use crate::{ build::FieldBuilder, - form::{ - Form, - MetaForm, - PortableForm, - }, + form::{Form, MetaForm, PortableForm}, prelude::vec::Vec, - IntoPortable, - Registry, + IntoPortable, Registry, }; use scale::Encode; #[cfg(feature = "serde")] -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; /// A field of a struct-like data type. /// diff --git a/src/ty/mod.rs b/src/ty/mod.rs index 5843c372..35c059d7 100644 --- a/src/ty/mod.rs +++ b/src/ty/mod.rs @@ -12,43 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::prelude::{ - vec, - vec::Vec, -}; +use crate::prelude::{vec, vec::Vec}; use crate::{ build::TypeBuilder, - form::{ - Form, - MetaForm, - PortableForm, - }, - IntoPortable, - MetaType, - Registry, - TypeInfo, + form::{Form, MetaForm, PortableForm}, + IntoPortable, MetaType, Registry, TypeInfo, }; use derive_more::From; use scale::Encode; #[cfg(feature = "serde")] -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; mod composite; mod fields; mod path; mod variant; -pub use self::{ - composite::*, - fields::*, - path::*, - variant::*, -}; +pub use self::{composite::*, fields::*, path::*, variant::*}; /// A [`Type`] definition with optional metadata. #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] @@ -138,12 +119,7 @@ where F: Form, { /// Create a [`Type`]. - pub fn new( - path: Path, - type_params: I, - type_def: D, - docs: Vec, - ) -> Type + pub fn new(path: Path, type_params: I, type_def: D, docs: Vec) -> Type where I: IntoIterator>, D: Into>, @@ -233,10 +209,7 @@ impl IntoPortable for TypeParameter { impl TypeParameter { /// Create a new [`TypeParameter`]. - pub fn new( - name: ::String, - ty: Option<::Type>, - ) -> Self { + pub fn new(name: ::String, ty: Option<::Type>) -> Self { Self { name, ty } } } diff --git a/src/ty/path.rs b/src/ty/path.rs index 574e83c7..112b25d3 100644 --- a/src/ty/path.rs +++ b/src/ty/path.rs @@ -13,31 +13,18 @@ // limitations under the License. use crate::prelude::{ - fmt::{ - Display, - Error as FmtError, - Formatter, - }, + fmt::{Display, Error as FmtError, Formatter}, vec::Vec, }; use crate::{ - form::{ - Form, - MetaForm, - PortableForm, - }, + form::{Form, MetaForm, PortableForm}, utils::is_rust_identifier, - IntoPortable, - Registry, + IntoPortable, Registry, }; use scale::Encode; #[cfg(feature = "serde")] -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; /// Represents the path of a type definition. /// @@ -99,8 +86,7 @@ impl Path { pub fn new(ident: &'static str, module_path: &'static str) -> Path { let mut segments = module_path.split("::").collect::>(); segments.push(ident); - Self::from_segments(segments) - .expect("All path segments should be valid Rust identifiers") + Self::from_segments(segments).expect("All path segments should be valid Rust identifiers") } /// Create a Path from the given segments @@ -115,10 +101,10 @@ impl Path { { let segments = segments.into_iter().collect::>(); if segments.is_empty() { - return Err(PathError::MissingSegments) + return Err(PathError::MissingSegments); } if let Some(err_at) = segments.iter().position(|seg| !is_rust_identifier(seg)) { - return Err(PathError::InvalidIdentifier { segment: err_at }) + return Err(PathError::InvalidIdentifier { segment: err_at }); } Ok(Path { segments }) } @@ -280,8 +266,7 @@ mod tests { #[test] fn path_display() { - let path = - Path::new("Planet", "hello::world").into_portable(&mut Default::default()); + let path = Path::new("Planet", "hello::world").into_portable(&mut Default::default()); assert_eq!("hello::world::Planet", format!("{}", path)) } } diff --git a/src/ty/variant.rs b/src/ty/variant.rs index a647018e..929a1962 100644 --- a/src/ty/variant.rs +++ b/src/ty/variant.rs @@ -15,23 +15,13 @@ use crate::prelude::vec::Vec; use crate::{ - form::{ - Form, - MetaForm, - PortableForm, - }, - Field, - IntoPortable, - Registry, + form::{Form, MetaForm, PortableForm}, + Field, IntoPortable, Registry, }; use derive_more::From; use scale::Encode; #[cfg(feature = "serde")] -use serde::{ - de::DeserializeOwned, - Deserialize, - Serialize, -}; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; /// A Enum type (consisting of variants). /// @@ -198,12 +188,7 @@ where T: Form, { /// Creates a new variant. - pub fn new( - name: T::String, - fields: Vec>, - index: u8, - docs: Vec, - ) -> Self { + pub fn new(name: T::String, fields: Vec>, index: u8, docs: Vec) -> Self { Self { name, fields, diff --git a/src/utils.rs b/src/utils.rs index ba3d54e0..3e067ef9 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -17,19 +17,15 @@ pub fn is_rust_identifier(s: &str) -> bool { // Only ascii encoding is allowed. // Note: Maybe this check is superseded by the `head` and `tail` check. if !s.is_ascii() { - return false + return false; } // Trim valid raw identifier prefix let trimmed = s.trim_start_matches("r#"); if let Some((&head, tail)) = trimmed.as_bytes().split_first() { // Check if head and tail make up a proper Rust identifier. - let head_ok = - head == b'_' || head.is_ascii_lowercase() || head.is_ascii_uppercase(); + let head_ok = head == b'_' || head.is_ascii_lowercase() || head.is_ascii_uppercase(); let tail_ok = tail.iter().all(|&ch| { - ch == b'_' - || ch.is_ascii_lowercase() - || ch.is_ascii_uppercase() - || ch.is_ascii_digit() + ch == b'_' || ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch.is_ascii_digit() }); head_ok && tail_ok } else { diff --git a/test_suite/Cargo.toml b/test_suite/Cargo.toml index 9f03bf57..b17ee11c 100644 --- a/test_suite/Cargo.toml +++ b/test_suite/Cargo.toml @@ -20,4 +20,4 @@ scale = { package = "parity-scale-codec", version = "3", default-features = fals serde = "1.0" serde_json = "1.0" pretty_assertions = "0.6.1" -trybuild = "1.0.54" +trybuild = "1.0.79" diff --git a/test_suite/tests/codec.rs b/test_suite/tests/codec.rs index 53993858..76967027 100644 --- a/test_suite/tests/codec.rs +++ b/test_suite/tests/codec.rs @@ -16,28 +16,13 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(dead_code)] -use info::{self as scale_info,}; -use pretty_assertions::{ - assert_eq, - assert_ne, -}; -use scale::{ - Decode, - Encode, -}; +use info::{self as scale_info}; +use pretty_assertions::{assert_eq, assert_ne}; +use scale::{Decode, Encode}; use scale_info::{ form::PortableForm, - prelude::{ - num::NonZeroU32, - string::String, - vec, - vec::Vec, - }, - IntoPortable as _, - MetaType, - PortableRegistry, - Registry, - TypeInfo, + prelude::{num::NonZeroU32, string::String, vec, vec::Vec}, + IntoPortable as _, MetaType, PortableRegistry, Registry, TypeInfo, }; #[derive(TypeInfo)] diff --git a/test_suite/tests/derive.rs b/test_suite/tests/derive.rs index 21d24a8a..c9905060 100644 --- a/test_suite/tests/derive.rs +++ b/test_suite/tests/derive.rs @@ -14,28 +14,16 @@ #![cfg_attr(not(feature = "std"), no_std)] -use core::ops::{ - Range, - RangeInclusive, -}; +use core::ops::{Range, RangeInclusive}; -use info::{self as scale_info,}; +use info::{self as scale_info}; use pretty_assertions::assert_eq; use scale::Encode; use scale_info::{ build::*, named_type_params, - prelude::{ - boxed::Box, - marker::PhantomData, - vec, - vec::Vec, - }, - MetaType, - Path, - Type, - TypeInfo, - TypeParameter, + prelude::{boxed::Box, marker::PhantomData, vec, vec::Vec}, + MetaType, Path, Type, TypeInfo, TypeParameter, }; fn assert_type(expected: E) @@ -246,9 +234,10 @@ fn enum_derive() { Variants::new() .variant("A", |v| { v.index(0) - .fields(Fields::unnamed().field(|f| { - f.ty::().type_name("T").docs(&["Unnamed field."]) - })) + .fields( + Fields::unnamed() + .field(|f| f.ty::().type_name("T").docs(&["Unnamed field."])), + ) .docs(&["Unnamed fields variant."]) }) .variant("B", |v| { @@ -286,15 +275,12 @@ fn enum_derive_with_codec_index() { .variant( Variants::new() .variant("A", |v| { - v.index(5).fields( - Fields::unnamed().field(|f| f.ty::().type_name("T")), - ) + v.index(5) + .fields(Fields::unnamed().field(|f| f.ty::().type_name("T"))) }) .variant("B", |v| { - v.index(0).fields( - Fields::named() - .field(|f| f.ty::().name("b").type_name("T")), - ) + v.index(0) + .fields(Fields::named().field(|f| f.ty::().name("b").type_name("T"))) }) .variant("C", |v| v.index(13)), ); @@ -314,20 +300,14 @@ fn recursive_type_derive() { let ty = Type::builder().path(Path::new("Tree", "derive")).variant( Variants::new() .variant("Leaf", |v| { - v.index(0).fields( - Fields::named() - .field(|f| f.ty::().name("value").type_name("i32")), - ) + v.index(0) + .fields(Fields::named().field(|f| f.ty::().name("value").type_name("i32"))) }) .variant("Node", |v| { v.index(1).fields( Fields::named() - .field(|f| { - f.ty::>().name("right").type_name("Box") - }) - .field(|f| { - f.ty::>().name("left").type_name("Box") - }), + .field(|f| f.ty::>().name("right").type_name("Box")) + .field(|f| f.ty::>().name("left").type_name("Box")), ) }), ); @@ -345,9 +325,9 @@ fn fields_with_type_alias() { a: BoolAlias, } - let ty = Type::builder().path(Path::new("S", "derive")).composite( - Fields::named().field(|f| f.ty::().name("a").type_name("BoolAlias")), - ); + let ty = Type::builder() + .path(Path::new("S", "derive")) + .composite(Fields::named().field(|f| f.ty::().name("a").type_name("BoolAlias"))); assert_type!(S, ty); } @@ -452,20 +432,17 @@ fn scale_compact_types_work_in_enums() { .variant( Variants::new() .variant("Id", |v| { - v.index(0).fields( - Fields::unnamed().field(|f| f.ty::().type_name("AccountId")), - ) + v.index(0) + .fields(Fields::unnamed().field(|f| f.ty::().type_name("AccountId"))) }) .variant("Index", |v| { v.index(1).fields( - Fields::unnamed() - .field(|f| f.compact::().type_name("AccountIndex")), + Fields::unnamed().field(|f| f.compact::().type_name("AccountIndex")), ) }) .variant("Address32", |v| { v.index(2).fields( - Fields::unnamed() - .field(|f| f.ty::<[u8; 32]>().type_name("[u8; 32]")), + Fields::unnamed().field(|f| f.ty::<[u8; 32]>().type_name("[u8; 32]")), ) }), ); @@ -531,9 +508,8 @@ fn enum_variants_with_fields_marked_scale_skip_are_skipped() { let ty = Type::builder().path(Path::new("Skippy", "derive")).variant( Variants::new() .variant("Bajs", |v| { - v.index(0).fields( - Fields::named().field(|f| f.ty::().name("b").type_name("bool")), - ) + v.index(0) + .fields(Fields::named().field(|f| f.ty::().name("b").type_name("bool"))) }) .variant("Coo", |v| { v.index(1) @@ -563,9 +539,7 @@ fn type_parameters_with_default_bound_works() { let ty = Type::builder() .path(Path::new("Bat", "derive")) .type_params(named_type_params![(TTT, MetaFormy)]) - .composite( - Fields::named().field(|f| f.ty::().name("one").type_name("TTT")), - ); + .composite(Fields::named().field(|f| f.ty::().name("one").type_name("TTT"))); assert_type!(Bat, ty); } @@ -578,14 +552,13 @@ fn whitespace_scrubbing_works() { a: (u8, (bool, u8)), } - let ty = - Type::builder() - .path(Path::new("A", "derive")) - .composite(Fields::named().field(|f| { - f.ty::<(u8, (bool, u8))>() - .name("a") - .type_name("(u8, (bool, u8))") - })); + let ty = Type::builder() + .path(Path::new("A", "derive")) + .composite(Fields::named().field(|f| { + f.ty::<(u8, (bool, u8))>() + .name("a") + .type_name("(u8, (bool, u8))") + })); assert_type!(A, ty); } @@ -647,14 +620,12 @@ fn never_capture_docs() { a: bool, } - let enum_ty = - Type::builder() - .path(Path::new("E", "derive")) - .variant(Variants::new().variant("A", |v| { - v.index(0).fields( - Fields::named().field(|f| f.ty::().name("a").type_name("u32")), - ) - })); + let enum_ty = Type::builder() + .path(Path::new("E", "derive")) + .variant(Variants::new().variant("A", |v| { + v.index(0) + .fields(Fields::named().field(|f| f.ty::().name("a").type_name("u32"))) + })); let struct_ty = Type::builder() .path(Path::new("S", "derive")) diff --git a/test_suite/tests/json.rs b/test_suite/tests/json.rs index 220cf36f..e066110c 100644 --- a/test_suite/tests/json.rs +++ b/test_suite/tests/json.rs @@ -16,32 +16,21 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(dead_code)] -use info::{self as scale_info,}; +use info::{self as scale_info}; use scale_info::prelude::{ boxed::Box, collections::VecDeque, marker::PhantomData, - ops::{ - Range, - RangeInclusive, - }, + ops::{Range, RangeInclusive}, string::String, vec, vec::Vec, }; -use pretty_assertions::{ - assert_eq, - assert_ne, -}; +use pretty_assertions::{assert_eq, assert_ne}; use scale::Encode; use scale_info::{ - form::PortableForm, - meta_type, - IntoPortable as _, - PortableRegistry, - Registry, - TypeInfo, + form::PortableForm, meta_type, IntoPortable as _, PortableRegistry, Registry, TypeInfo, }; use serde_json::json; @@ -97,20 +86,12 @@ fn test_sequences_have_same_type() { #[test] fn test_builtins() { // arrays - assert_json_for_type::<[u8; 2]>( - json!({ "def": { "array": { "len": 2, "type": 0 } } }), - ); - assert_json_for_type::<[bool; 4]>( - json!({ "def": { "array": { "len": 4, "type": 0 } } }), - ); - assert_json_for_type::<[char; 8]>( - json!({ "def": { "array": { "len": 8, "type": 0 } } }), - ); + assert_json_for_type::<[u8; 2]>(json!({ "def": { "array": { "len": 2, "type": 0 } } })); + assert_json_for_type::<[bool; 4]>(json!({ "def": { "array": { "len": 4, "type": 0 } } })); + assert_json_for_type::<[char; 8]>(json!({ "def": { "array": { "len": 8, "type": 0 } } })); // tuples assert_json_for_type::<(u8, bool)>(json!({ "def": { "tuple": [ 0, 1 ] } })); - assert_json_for_type::<(u8, bool, char, u128)>( - json!({ "def": { "tuple": [ 0, 1, 2, 3 ] } }), - ); + assert_json_for_type::<(u8, bool, char, u128)>(json!({ "def": { "tuple": [ 0, 1, 2, 3 ] } })); assert_json_for_type::<(u8, bool, char, u128, i32, u32)>(json!({ "def": { "tuple": [ 0, 1, 2, 3, 4, 5 ] @@ -243,11 +224,7 @@ fn test_struct_with_some_fields_marked_as_compact() { #[codec(compact)] c: u64, } - use scale_info::{ - build::Fields, - Path, - Type, - }; + use scale_info::{build::Fields, Path, Type}; impl TypeInfo for Dense { type Identity = Self; fn type_info() -> Type { diff --git a/test_suite/tests/ui/fail_duplicate_bounds_params.stderr b/test_suite/tests/ui/fail_duplicate_bounds_params.stderr index cd76cddf..7c3d8be9 100644 --- a/test_suite/tests/ui/fail_duplicate_bounds_params.stderr +++ b/test_suite/tests/ui/fail_duplicate_bounds_params.stderr @@ -2,4 +2,4 @@ error: Duplicate `bounds` attributes --> tests/ui/fail_duplicate_bounds_params.rs:6:1 | 6 | #[scale_info(bounds(), bounds())] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^ diff --git a/test_suite/tests/ui/fail_with_invalid_codec_attrs.stderr b/test_suite/tests/ui/fail_with_invalid_codec_attrs.stderr index 90d52022..6246d1c9 100644 --- a/test_suite/tests/ui/fail_with_invalid_codec_attrs.stderr +++ b/test_suite/tests/ui/fail_with_invalid_codec_attrs.stderr @@ -2,13 +2,13 @@ error: Invalid attribute on field, only `#[codec(skip)]`, `#[codec(compact)]` an --> tests/ui/fail_with_invalid_codec_attrs.rs:8:7 | 8 | #[codec(skip, compact)] - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^ error: Invalid attribute on field, only `#[codec(skip)]`, `#[codec(compact)]` and `#[codec(encoded_as = "$EncodeAs")]` are accepted. --> tests/ui/fail_with_invalid_codec_attrs.rs:14:19 | 14 | Thing(#[codec(index = 3)] u32), - | ^^^^^^^^^ + | ^^^^^ error: expected literal --> tests/ui/fail_with_invalid_codec_attrs.rs:19:21