-
Notifications
You must be signed in to change notification settings - Fork 99
Move MaxEncodedLen from Substrate
#268
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
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
98943ed
move MaxEncodedLen trait from Substrate
coriolinus f665e41
Move derive macro and tests from Substrate
coriolinus 17eda6d
only run ui tests when derive feature enabled
coriolinus 24b4680
reduce note-taking documentation
coriolinus 7010204
Merge branch 'master' into prgn-max-encoded-len
Xanewok 6bc8904
Bless trybuild `tests/max_encoded_len_ui/union.rs` test
Xanewok b79e84a
Update docs (these files are not part of substrate)
coriolinus 7a465d5
Mention new `MaxEncodedLen` trait in the CHANGELOG.md
Xanewok ccfa540
Prepare a 2.2.0-rc.1 release
Xanewok 9f24e9d
incorporate changes made to Substrate version of MaxEncodedLen
coriolinus 67474db
remove redundant no_std
coriolinus 395dbaa
Rewrite fn max_encoded_len_trait for clarity
coriolinus 7f2db6a
simplify logic checking for invalid attr
coriolinus 39e542a
remove bogus whitespace
coriolinus 5189f84
use Path::is_ident() helper
coriolinus 04b3ad3
rm unused import
coriolinus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| // 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::utils::codec_crate_path; | ||
| use quote::{quote, quote_spanned}; | ||
| use syn::{ | ||
| Data, DeriveInput, Fields, GenericParam, Generics, TraitBound, Type, TypeParamBound, | ||
| parse_quote, spanned::Spanned, | ||
| }; | ||
|
|
||
| /// impl for `#[derive(MaxEncodedLen)]` | ||
| pub fn derive_max_encoded_len(input: proc_macro::TokenStream) -> proc_macro::TokenStream { | ||
| let input: DeriveInput = match syn::parse(input) { | ||
| Ok(input) => input, | ||
| Err(e) => return e.to_compile_error().into(), | ||
| }; | ||
|
|
||
| let mel_trait = match max_encoded_len_trait(&input) { | ||
| Ok(mel_trait) => mel_trait, | ||
| Err(e) => return e.to_compile_error().into(), | ||
| }; | ||
|
|
||
| let name = &input.ident; | ||
| let generics = add_trait_bounds(input.generics, mel_trait.clone()); | ||
| let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); | ||
|
|
||
| let data_expr = data_length_expr(&input.data); | ||
|
|
||
| quote::quote!( | ||
| const _: () = { | ||
| impl #impl_generics #mel_trait for #name #ty_generics #where_clause { | ||
| fn max_encoded_len() -> usize { | ||
| #data_expr | ||
| } | ||
| } | ||
| }; | ||
| ) | ||
| .into() | ||
| } | ||
|
|
||
| fn max_encoded_len_trait(input: &DeriveInput) -> syn::Result<TraitBound> { | ||
| let mel = codec_crate_path(&input.attrs)?; | ||
| Ok(parse_quote!(#mel::MaxEncodedLen)) | ||
| } | ||
|
|
||
| // Add a bound `T: MaxEncodedLen` to every type parameter T. | ||
| fn add_trait_bounds(mut generics: Generics, mel_trait: TraitBound) -> Generics { | ||
| for param in &mut generics.params { | ||
| if let GenericParam::Type(ref mut type_param) = *param { | ||
| type_param.bounds.push(TypeParamBound::Trait(mel_trait.clone())); | ||
| } | ||
| } | ||
| generics | ||
| } | ||
|
|
||
| /// generate an expression to sum up the max encoded length from several fields | ||
| fn fields_length_expr(fields: &Fields) -> proc_macro2::TokenStream { | ||
| let type_iter: Box<dyn Iterator<Item = &Type>> = match fields { | ||
| Fields::Named(ref fields) => Box::new(fields.named.iter().map(|field| &field.ty)), | ||
| Fields::Unnamed(ref fields) => Box::new(fields.unnamed.iter().map(|field| &field.ty)), | ||
| Fields::Unit => Box::new(std::iter::empty()), | ||
| }; | ||
| // expands to an expression like | ||
| // | ||
| // 0 | ||
| // .saturating_add(<type of first field>::max_encoded_len()) | ||
| // .saturating_add(<type of second field>::max_encoded_len()) | ||
| // | ||
| // We match the span of each field to the span of the corresponding | ||
| // `max_encoded_len` call. This way, if one field's type doesn't implement | ||
| // `MaxEncodedLen`, the compiler's error message will underline which field | ||
| // caused the issue. | ||
| let expansion = type_iter.map(|ty| { | ||
| quote_spanned! { | ||
| ty.span() => .saturating_add(<#ty>::max_encoded_len()) | ||
| } | ||
| }); | ||
| quote! { | ||
| 0_usize #( #expansion )* | ||
| } | ||
| } | ||
|
|
||
| // generate an expression to sum up the max encoded length of each field | ||
| fn data_length_expr(data: &Data) -> proc_macro2::TokenStream { | ||
| match *data { | ||
| Data::Struct(ref data) => fields_length_expr(&data.fields), | ||
| Data::Enum(ref data) => { | ||
| // We need an expression expanded for each variant like | ||
| // | ||
| // 0 | ||
| // .max(<variant expression>) | ||
| // .max(<variant expression>) | ||
| // .saturating_add(1) | ||
| // | ||
| // The 1 derives from the discriminant; see | ||
| // https://github.com/paritytech/parity-scale-codec/ | ||
| // blob/f0341dabb01aa9ff0548558abb6dcc5c31c669a1/derive/src/encode.rs#L211-L216 | ||
| // | ||
| // Each variant expression's sum is computed the way an equivalent struct's would be. | ||
|
|
||
| let expansion = data.variants.iter().map(|variant| { | ||
| let variant_expression = fields_length_expr(&variant.fields); | ||
| quote! { | ||
| .max(#variant_expression) | ||
| } | ||
| }); | ||
|
|
||
| quote! { | ||
| 0_usize #( #expansion )* .saturating_add(1) | ||
| } | ||
| } | ||
| Data::Union(ref data) => { | ||
| // https://github.com/paritytech/parity-scale-codec/ | ||
| // blob/f0341dabb01aa9ff0548558abb6dcc5c31c669a1/derive/src/encode.rs#L290-L293 | ||
| syn::Error::new(data.union_token.span(), "Union types are not supported") | ||
| .to_compile_error() | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.