Unverified Commit 2021becf authored by Hero Bird's avatar Hero Bird Committed by GitHub

Remove old modules after storage2 transition (#446)

* [core] remove old storage module

# Conflicts:
#	core/src/storage/alloc/bump_alloc.rs
#	core/src/storage/alloc/dyn_alloc.rs
#	core/src/storage/cell/sync_cell.rs
#	core/src/storage/chunk/sync_chunk/chunk.rs
#	core/src/storage/collections/binary_heap/duplex_sync_chunk.rs
#	core/src/storage/collections/binary_heap/impls.rs
#	core/src/storage/collections/bitvec/block.rs
#	core/src/storage/collections/bitvec/pack.rs
#	core/src/storage/collections/bitvec/vec.rs
#	core/src/storage/collections/btree_map/impls.rs
#	core/src/storage/collections/btree_map/node.rs
#	core/src/storage/collections/hash_map/impls.rs
#	core/src/storage/collections/stash/impls.rs
#	core/src/storage/collections/vec/impls.rs
#	core/src/storage/value.rs

* [abi] remove old layout module

# Conflicts:
#	abi/src/layout.rs
#	abi/src/lib.rs

* [abi] remove abi_derive sub crate

# Conflicts:
#	abi/derive/src/has_layout.rs
#	abi/derive/src/impl_wrapper.rs
#	abi/src/lib.rs

* [core/derive] remove Flush and AllocateUsing derives + tests

* [abi] remove unused function

* [abi] remove unused tests and simplify imports
parent f0747864
Pipeline #96631 failed with stages
in 5 minutes and 23 seconds
......@@ -15,7 +15,6 @@ categories = ["no-std", "embedded"]
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE"]
[dependencies]
ink_abi_derive = { version = "2.1.0", path = "derive", default-features = false, optional = true }
ink_prelude = { version = "2.1.0", path = "../prelude/", default-features = false }
ink_primitives = { version = "2.1.0", path = "../primitives/", default-features = false }
......@@ -33,11 +32,8 @@ default = [
"derive",
]
std = [
"ink_abi_derive/std",
"ink_prelude/std",
"serde/std",
"scale-info/std",
]
derive = [
"ink_abi_derive"
]
derive = []
[package]
name = "ink_abi_derive"
version = "2.1.0"
authors = ["Parity Technologies <admin@parity.io>"]
edition = "2018"
license = "APACHE-2.0"
readme = "README.md"
repository = "https://github.com/paritytech/ink"
documentation = "https://substrate.dev/substrate-contracts-workshop/#/"
homepage = "https://www.parity.io/"
description = "[ink!] Rust based eDSL for writing smart contracts for Substrate"
keywords = ["wasm", "parity", "webassembly", "blockchain", "edsl"]
categories = ["no-std", "embedded"]
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE"]
[lib]
proc-macro = true
[dependencies]
quote = "1.0"
syn = { version = "1.0", features = ["full"] }
proc-macro2 = "1.0"
[features]
default = ["std"]
std = []
../../LICENSE
\ No newline at end of file
../../README.md
\ No newline at end of file
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
// 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.
macro_rules! bail {
($($args:tt)*) => {
return Err(format_err!($($args)*).into())
}
}
macro_rules! format_err {
($tokens:expr, $($msg:tt)*) => {
match &$tokens {
t => {
syn::parse::Error::new_spanned(t, format_args!($($msg)*))
}
}
}
}
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
// 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 proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
self,
parse::Result,
parse_quote,
punctuated::Punctuated,
Data,
DataStruct,
DeriveInput,
Field,
Fields,
Token,
};
use crate::impl_wrapper::wrap;
pub fn generate(input: TokenStream2) -> TokenStream2 {
match generate_impl(input) {
Ok(output) => output,
Err(err) => err.to_compile_error(),
}
}
pub fn generate_impl(input: TokenStream2) -> Result<TokenStream2> {
let mut ast: DeriveInput = syn::parse2(input)?;
ast.generics.type_params_mut().for_each(|p| {
p.bounds.push(parse_quote!(_ink_abi::HasLayout));
});
let ident = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let layout = match &ast.data {
Data::Struct(ref s) => generate_struct_layout(s),
Data::Enum(ref _e) => bail!(&ast, "enums are not supported"),
Data::Union(ref _u) => bail!(&ast, "unions are not supported"),
};
let has_layout_impl = quote! {
impl #impl_generics _ink_abi::HasLayout for #ident #ty_generics #where_clause {
fn layout(&self) -> _ink_abi::StorageLayout {
#layout.into()
}
}
};
Ok(wrap(has_layout_impl))
}
fn generate_fields_layout<'a>(
fields: &'a Punctuated<Field, Token![,]>,
) -> impl Iterator<Item = TokenStream2> + 'a {
fields.iter().enumerate().map(|(n, field)| {
let ident = &field.ident;
if let Some(ident) = ident {
quote! {
_ink_abi::LayoutField::new(stringify!(#ident), self.#ident.layout())
}
} else {
let n = proc_macro2::Literal::usize_unsuffixed(n);
quote! {
_ink_abi::LayoutField::new(stringify!(#n), self.#n.layout())
}
}
})
}
fn generate_struct_fields_layout(fields: &Punctuated<Field, Token![,]>) -> TokenStream2 {
let fields_layout = generate_fields_layout(fields);
quote! {
use scale_info::Metadata as _;
_ink_abi::LayoutStruct::new(Self::meta_type(), __core::vec![
#( #fields_layout, )*
])
}
}
fn generate_struct_layout(data_struct: &DataStruct) -> TokenStream2 {
match data_struct.fields {
Fields::Named(ref fs) => generate_struct_fields_layout(&fs.named),
Fields::Unnamed(ref fs) => generate_struct_fields_layout(&fs.unnamed),
Fields::Unit => {
quote! {
_ink_abi::LayoutStruct::new(<Self as scale_info::Metadata>::meta_type(), Vec::new())
}
}
}
}
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
// 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 proc_macro2::TokenStream as TokenStream2;
use quote::quote;
pub fn wrap(impl_quote: TokenStream2) -> TokenStream2 {
quote! {
#[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]
const _: () = {
#[allow(unknown_lints)]
#[cfg_attr(feature = "cargo-clippy", allow(useless_attribute))]
#[allow(rust_2018_idioms)]
use scale_info as _scale_info;
use ink_abi as _ink_abi;
#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(feature = "std")]
mod __core {
pub use ::core::*;
pub use ::std::{vec, vec::Vec};
}
#[cfg(not(feature = "std"))]
mod __core {
pub use ::core::*;
pub use ::alloc::{vec, vec::Vec};
}
#impl_quote;
};
}
}
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
// 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.
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(not(feature = "std"))]
extern crate alloc;
#[macro_use]
mod error;
mod has_layout;
mod impl_wrapper;
use proc_macro::TokenStream;
#[proc_macro_derive(HasLayout)]
pub fn has_layout(input: TokenStream) -> TokenStream {
has_layout::generate(input.into()).into()
}
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
// 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.
#[cfg(not(feature = "std"))]
use alloc::{
string::String,
vec::Vec,
};
use derive_more::From;
use scale_info::{
form::{
CompactForm,
Form,
MetaForm,
},
IntoCompact,
Registry,
};
use serde::{
Serialize,
Serializer,
};
/// Implemented by types that have a storage layout.
///
/// Has to be used on previously allocated instances of the types.
pub trait HasLayout {
fn layout(&self) -> StorageLayout;
}
impl From<ink_primitives::Key> for LayoutKey {
fn from(key: ink_primitives::Key) -> Self {
LayoutKey(key.0)
}
}
impl HasLayout for ink_primitives::Key {
fn layout(&self) -> StorageLayout {
LayoutRange::cell(*self, <[u8; 32] as scale_info::Metadata>::meta_type()).into()
}
}
/// Either a concrete layout bound or another layout sub-struct.
#[derive(Debug, PartialEq, Eq, Serialize, From)]
#[serde(bound = "F::TypeId: Serialize")]
#[serde(rename_all = "lowercase")]
pub enum StorageLayout<F: Form = MetaForm> {
/// A concrete layout bound.
Range(LayoutRange<F>),
/// A nested sub-struct with layout bounds.
Struct(LayoutStruct<F>),
}
impl IntoCompact for StorageLayout {
type Output = StorageLayout<CompactForm>;
fn into_compact(self, registry: &mut Registry) -> Self::Output {
match self {
StorageLayout::Range(layout_range) => {
StorageLayout::Range(layout_range.into_compact(registry))
}
StorageLayout::Struct(layout_struct) => {
StorageLayout::Struct(layout_struct.into_compact(registry))
}
}
}
}
/// A concrete range of keys.
///
/// Basically a thin-wrapper around keys from `ink_core` library for serialization purposes.
#[derive(Debug, PartialEq, Eq, From, Serialize)]
#[serde(transparent)]
pub struct LayoutKey(
/// Internals must be compatible with `ink_primitives::Key`.
pub [u8; 32],
);
/// A struct storage layout.
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(bound = "F::TypeId: Serialize")]
pub struct LayoutStruct<F: Form = MetaForm> {
#[serde(rename = "type")]
self_ty: F::TypeId,
/// The sub-fields of the struct.
fields: Vec<LayoutField<F>>,
}
impl LayoutStruct {
/// Creates a new layout struct.
pub fn new<F>(self_ty: <MetaForm as Form>::TypeId, fields: F) -> Self
where
F: IntoIterator<Item = LayoutField>,
{
Self {
self_ty,
fields: fields.into_iter().collect::<Vec<_>>(),
}
}
}
impl IntoCompact for LayoutStruct {
type Output = LayoutStruct<CompactForm>;
fn into_compact(self, registry: &mut Registry) -> Self::Output {
LayoutStruct {
self_ty: registry.register_type(&self.self_ty),
fields: self
.fields
.into_iter()
.map(|field| field.into_compact(registry))
.collect::<Vec<_>>(),
}
}
}
/// The layout for a particular field of a struct layout.
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(bound = "F::TypeId: Serialize")]
pub struct LayoutField<F: Form = MetaForm> {
/// The name of the field.
name: F::String,
/// The kind of the field.
///
/// This is either a direct layout bound
/// or another recursive layout sub-struct.
#[serde(rename = "layout")]
sub_layout: StorageLayout<F>,
}
impl LayoutField {
/// Creates a new layout field from the given name and sub-structural layout.
pub fn new(name: <MetaForm as Form>::String, sub_layout: StorageLayout) -> Self {
Self { name, sub_layout }
}
/// Creates a new layout field for the given field instance.
pub fn of<T>(name: <MetaForm as Form>::String, field: &T) -> Self
where
T: HasLayout,
{
Self::new(name, field.layout())
}
}
impl IntoCompact for LayoutField {
type Output = LayoutField<CompactForm>;
fn into_compact(self, registry: &mut Registry) -> Self::Output {
LayoutField {
name: registry.register_string(self.name),
sub_layout: self.sub_layout.into_compact(registry),
}
}
}
/// Direct range of associated storage keys.
///
/// This may represent either a single cell, a whole chunk of cells or something in between.
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(bound = "F::TypeId: Serialize")]
pub struct LayoutRange<F: Form = MetaForm> {
/// The single key for cells or the starting key address for chunks.
#[serde(serialize_with = "serialize_key")]
offset: LayoutKey,
/// The amount of associated key addresses starting from the offset key.
len: u32,
/// The element type stored under the associated keys.
#[serde(rename = "elemType")]
elem_ty: F::TypeId,
}
impl IntoCompact for LayoutRange {
type Output = LayoutRange<CompactForm>;
fn into_compact(self, registry: &mut Registry) -> Self::Output {
LayoutRange {
offset: self.offset,
len: self.len,
elem_ty: registry.register_type(&self.elem_ty),
}
}
}
impl LayoutRange {
/// Creates a layout range representing a single cell.
pub fn cell<K>(at: K, elem_ty: <MetaForm as Form>::TypeId) -> Self
where
K: Into<LayoutKey>,
{
Self {
offset: at.into(),
len: 1,
elem_ty,
}
}
/// Creates a layout range for a whole chunk starting at the offset key.
pub fn chunk<K>(offset: K, elem_ty: <MetaForm as Form>::TypeId) -> Self
where
K: Into<LayoutKey>,
{
Self {
offset: offset.into(),
len: 0xFFFF_FFFF,
elem_ty,
}
}
}
fn serialize_key<S>(key: &LayoutKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
super::hex_encode(&key.0[..], serializer)
}
......@@ -20,50 +20,34 @@ extern crate alloc;
#[cfg(test)]
mod tests;
mod layout;
pub mod layout2;
mod specs;
mod utils;
pub use self::{
layout::{
HasLayout,
LayoutField,
LayoutKey,
LayoutRange,
LayoutStruct,
StorageLayout,
},
specs::{
ConstructorSpec,
ConstructorSpecBuilder,
ContractSpec,
ContractSpecBuilder,
DisplayName,
EventParamSpec,
EventParamSpecBuilder,
EventSpec,
EventSpecBuilder,
MessageParamSpec,
MessageParamSpecBuilder,
MessageSpec,
MessageSpecBuilder,
ReturnTypeSpec,
TypeSpec,
},
pub use self::specs::{
ConstructorSpec,
ConstructorSpecBuilder,
ContractSpec,
ContractSpecBuilder,
DisplayName,
EventParamSpec,
EventParamSpecBuilder,
EventSpec,
EventSpecBuilder,
MessageParamSpec,
MessageParamSpecBuilder,
MessageSpec,
MessageSpecBuilder,
ReturnTypeSpec,
TypeSpec,
};
use core::fmt::Write as _;
#[cfg(feature = "derive")]
pub use ink_abi_derive::HasLayout;
use scale_info::{
form::CompactForm,
IntoCompact as _,
Registry,
};
use serde::{
Serialize,
Serializer,
};
use serde::Serialize;
/// An entire ink! project for ABI file generation purposes.
#[derive(Debug, Serialize)]
......@@ -90,15 +74,3 @@ impl InkProject {
}
}
}
fn hex_encode<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut hex = String::with_capacity(bytes.len() * 2 + 2);
write!(hex, "0x").expect("failed writing to string");
for byte in bytes {
write!(hex, "{:02x}", byte).expect("failed writing to string");
}
serializer.serialize_str(&hex)
}
......@@ -15,10 +15,6 @@
use super::*;
use assert_json_diff::assert_json_eq;
use scale_info::{
form::{
Form,
MetaForm,
},
IntoCompact,
Registry,
};
......@@ -49,52 +45,6 @@ fn spec_constructor_selector_must_serialize_to_hex() {
);
}
#[test]
fn layout_range_json() {
// given
let type_id = <MetaForm as Form>::TypeId::new::<u32>();
let offset = LayoutKey([1; 32]);
let layout = StorageLayout::Range(LayoutRange::cell(offset, type_id));
let mut registry = Registry::new();
// when
let json = serde_json::to_value(&layout.into_compact(&mut registry)).unwrap();
// then
assert_json_eq!(
json,
json!({
"range": {
"offset": "0x0101010101010101010101010101010101010101010101010101010101010101",
"len": 1,
"elemType": 1
}
})
);
}
#[test]
fn layout_struct_json() {
// given
let type_id = <MetaForm as Form>::TypeId::new::<u32>();
let layout = StorageLayout::Struct(LayoutStruct::new(type_id, Vec::new()));