diff --git a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/bounds_tests.rs b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/bounds_tests.rs index fb65d0aab86e..0d70ce089a6a 100644 --- a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/bounds_tests.rs +++ b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/bounds_tests.rs @@ -18,29 +18,29 @@ fn empty_module_no_errors() { } #[test] -fn invalid_type_param_in_fn_return_types() { +fn invalid_type_param_in_fn_return_() { use SignatureToken::*; let mut m = basic_test_module(); - m.function_signatures[0].return_types = vec![TypeParameter(0)]; + m.function_signatures[0].return_ = vec![TypeParameter(0)]; m.freeze().unwrap_err(); } #[test] -fn invalid_type_param_in_fn_arg_types() { +fn invalid_type_param_in_fn_parameters() { use SignatureToken::*; let mut m = basic_test_module(); - m.function_signatures[0].arg_types = vec![TypeParameter(0)]; + m.function_signatures[0].parameters = vec![TypeParameter(0)]; m.freeze().unwrap_err(); } #[test] -fn invalid_struct_in_fn_return_types() { +fn invalid_struct_in_fn_return_() { use SignatureToken::*; let mut m = basic_test_module(); - m.function_signatures[0].return_types = vec![Struct(StructHandleIndex::new(1), vec![])]; + m.function_signatures[0].return_ = vec![Struct(StructHandleIndex::new(1), vec![])]; m.freeze().unwrap_err(); } @@ -76,10 +76,7 @@ fn invalid_locals_id_in_call() { use Bytecode::*; let mut m = basic_test_module(); - m.function_defs[0].code.code = vec![Call( - FunctionHandleIndex::new(0), - LocalsSignatureIndex::new(1), - )]; + m.function_defs[0].code.code = vec![Call(FunctionHandleIndex::new(0), SignatureIndex::new(1))]; m.freeze().unwrap_err(); } @@ -89,12 +86,8 @@ fn invalid_type_param_in_call() { use SignatureToken::*; let mut m = basic_test_module(); - m.locals_signatures - .push(LocalsSignature(vec![TypeParameter(0)])); - m.function_defs[0].code.code = vec![Call( - FunctionHandleIndex::new(0), - LocalsSignatureIndex::new(1), - )]; + m.locals_signatures.push(Signature(vec![TypeParameter(0)])); + m.function_defs[0].code.code = vec![Call(FunctionHandleIndex::new(0), SignatureIndex::new(1))]; m.freeze().unwrap_err(); } @@ -104,14 +97,9 @@ fn invalid_struct_as_type_actual_in_exists() { use SignatureToken::*; let mut m = basic_test_module(); - m.locals_signatures.push(LocalsSignature(vec![Struct( - StructHandleIndex::new(3), - vec![], - )])); - m.function_defs[0].code.code = vec![Call( - FunctionHandleIndex::new(0), - LocalsSignatureIndex::new(1), - )]; + m.locals_signatures + .push(Signature(vec![Struct(StructHandleIndex::new(3), vec![])])); + m.function_defs[0].code.code = vec![Call(FunctionHandleIndex::new(0), SignatureIndex::new(1))]; m.freeze().unwrap_err(); } diff --git a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/signature_tests.rs b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/signature_tests.rs index ea5eaba01e2a..138fc26417c8 100644 --- a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/signature_tests.rs +++ b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/signature_tests.rs @@ -17,7 +17,7 @@ use vm::file_format::{Bytecode::*, CompiledModule, SignatureToken::*, *}; #[test] fn test_reference_of_reference() { let mut m = basic_test_module(); - m.locals_signatures[0] = LocalsSignature(vec![Reference(Box::new(Reference(Box::new( + m.locals_signatures[0] = Signature(vec![Reference(Box::new(Reference(Box::new( SignatureToken::Bool, ))))]); let errors = SignatureChecker::new(&m.freeze().unwrap()).verify(); @@ -115,20 +115,24 @@ fn no_verify_locals_good() { signature: FunctionSignatureIndex(1), }, ], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![ FunctionSignature { - return_types: vec![], - arg_types: vec![Address], - type_formals: vec![], + return_: vec![], + parameters: vec![Address], + type_parameters: vec![], }, FunctionSignature { - return_types: vec![], - arg_types: vec![U64], - type_formals: vec![], + return_: vec![], + parameters: vec![U64], + type_parameters: vec![], }, ], - locals_signatures: vec![LocalsSignature(vec![Address]), LocalsSignature(vec![U64])], + locals_signatures: vec![Signature(vec![Address]), Signature(vec![U64])], identifiers: vec![ Identifier::new("Bad").unwrap(), Identifier::new("blah").unwrap(), @@ -145,7 +149,7 @@ fn no_verify_locals_good() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Ret], }, }, @@ -155,7 +159,7 @@ fn no_verify_locals_good() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(1), + locals: SignatureIndex(1), code: vec![Ret], }, }, @@ -181,13 +185,17 @@ fn no_verify_locals_bad1() { name: IdentifierIndex(1), signature: FunctionSignatureIndex(0), }], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![FunctionSignature { - return_types: vec![], - arg_types: vec![Address], - type_formals: vec![], + return_: vec![], + parameters: vec![Address], + type_parameters: vec![], }], - locals_signatures: vec![LocalsSignature(vec![U64])], + locals_signatures: vec![Signature(vec![U64])], identifiers: vec![ Identifier::new("Bad").unwrap(), Identifier::new("blah").unwrap(), @@ -202,7 +210,7 @@ fn no_verify_locals_bad1() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Ret], }, }], @@ -226,13 +234,17 @@ fn no_verify_locals_bad2() { name: IdentifierIndex(1), signature: FunctionSignatureIndex(0), }], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![FunctionSignature { - return_types: vec![], - arg_types: vec![Address], - type_formals: vec![], + return_: vec![], + parameters: vec![Address], + type_parameters: vec![], }], - locals_signatures: vec![LocalsSignature(vec![])], + locals_signatures: vec![Signature(vec![])], identifiers: vec![ Identifier::new("Bad").unwrap(), Identifier::new("blah").unwrap(), @@ -247,7 +259,7 @@ fn no_verify_locals_bad2() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Ret], }, }], @@ -272,13 +284,17 @@ fn no_verify_locals_bad3() { name: IdentifierIndex(1), signature: FunctionSignatureIndex(0), }], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![FunctionSignature { - return_types: vec![], - arg_types: vec![Address], - type_formals: vec![], + return_: vec![], + parameters: vec![Address], + type_parameters: vec![], }], - locals_signatures: vec![LocalsSignature(vec![U64, Address])], + locals_signatures: vec![Signature(vec![U64, Address])], identifiers: vec![ Identifier::new("Bad").unwrap(), Identifier::new("blah").unwrap(), @@ -293,7 +309,7 @@ fn no_verify_locals_bad3() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Ret], }, }], @@ -318,13 +334,17 @@ fn no_verify_locals_bad4() { name: IdentifierIndex(1), signature: FunctionSignatureIndex(0), }], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![FunctionSignature { - return_types: vec![], - arg_types: vec![U64, Address], - type_formals: vec![], + return_: vec![], + parameters: vec![U64, Address], + type_parameters: vec![], }], - locals_signatures: vec![LocalsSignature(vec![U64, U64, Address])], + locals_signatures: vec![Signature(vec![U64, U64, Address])], identifiers: vec![ Identifier::new("Bad").unwrap(), Identifier::new("blah").unwrap(), @@ -339,7 +359,7 @@ fn no_verify_locals_bad4() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Ret], }, }], diff --git a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/unused_entry_tests.rs b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/unused_entry_tests.rs index 735ce819fcec..4795ebaa3e9e 100644 --- a/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/unused_entry_tests.rs +++ b/language/bytecode-verifier/bytecode_verifier_tests/src/unit_tests/unused_entry_tests.rs @@ -5,15 +5,15 @@ use bytecode_verifier::UnusedEntryChecker; use libra_types::{identifier::Identifier, vm_error::StatusCode}; use proptest::prelude::*; use vm::file_format::{ - CompiledModule, FieldDefinition, IdentifierIndex, LocalsSignature, ModuleHandleIndex, - SignatureToken, StructHandle, StructHandleIndex, TypeSignature, TypeSignatureIndex, + CompiledModule, FieldDefinition, IdentifierIndex, ModuleHandleIndex, Signature, SignatureToken, + StructHandle, StructHandleIndex, TypeSignature, TypeSignatureIndex, }; proptest! { #[test] fn unused_locals_signature(module in CompiledModule::valid_strategy(10)) { let mut module = module.into_inner(); - module.locals_signatures.push(LocalsSignature(vec![])); + module.locals_signatures.push(Signature(vec![])); let module = module.freeze().unwrap(); let unused_entry_checker = UnusedEntryChecker::new(&module); prop_assert!(!unused_entry_checker.verify().is_empty()); @@ -50,7 +50,7 @@ proptest! { module: ModuleHandleIndex::new(0), name: IdentifierIndex::new(struct_name_idx), is_nominal_resource: false, - type_formals: vec![], + type_parameters: vec![], }); module.field_defs.push(FieldDefinition{ diff --git a/language/bytecode-verifier/invalid-mutations/src/bounds.rs b/language/bytecode-verifier/invalid-mutations/src/bounds.rs index 5030ac77eaea..a9e3266b01cb 100644 --- a/language/bytecode-verifier/invalid-mutations/src/bounds.rs +++ b/language/bytecode-verifier/invalid-mutations/src/bounds.rs @@ -12,9 +12,8 @@ use vm::{ errors::{append_err_info, bounds_error}, file_format::{ AddressPoolIndex, CompiledModule, CompiledModuleMut, FieldDefinitionIndex, - FunctionHandleIndex, FunctionSignatureIndex, IdentifierIndex, LocalsSignatureIndex, - ModuleHandleIndex, StructFieldInformation, StructHandleIndex, TableIndex, - TypeSignatureIndex, + FunctionHandleIndex, FunctionSignatureIndex, IdentifierIndex, ModuleHandleIndex, + SignatureIndex, StructFieldInformation, StructHandleIndex, TableIndex, TypeSignatureIndex, }, internals::ModuleIndex, views::{ModuleView, SignatureTokenView}, @@ -52,12 +51,14 @@ impl PointerKind { ModuleHandle => &[One(AddressPool), One(Identifier)], StructHandle => &[One(ModuleHandle), One(Identifier)], FunctionHandle => &[One(ModuleHandle), One(Identifier), One(FunctionSignature)], + StructInstantiation => &[One(StructHandle), One(Signature)], + FunctionInstantiation => &[One(FunctionHandle), One(Signature)], StructDefinition => &[One(StructHandle), One(FieldDefinition)], FieldDefinition => &[One(StructHandle), One(Identifier), One(TypeSignature)], - FunctionDefinition => &[One(FunctionHandle), One(LocalsSignature)], + FunctionDefinition => &[One(FunctionHandle), One(Signature)], TypeSignature => &[Optional(StructHandle)], FunctionSignature => &[Star(StructHandle)], - LocalsSignature => &[Star(StructHandle)], + Signature => &[Star(StructHandle)], Identifier => &[], ByteArrayPool => &[], AddressPool => &[], @@ -67,6 +68,9 @@ impl PointerKind { LocalPool => &[], CodeDefinition => &[], TypeParameter => &[], + FieldHandle => &[], + FieldInstantiation => &[], + FieldOffset => &[], } } @@ -82,12 +86,14 @@ pub static VALID_POINTER_SRCS: &[IndexKind] = &[ IndexKind::ModuleHandle, IndexKind::StructHandle, IndexKind::FunctionHandle, + IndexKind::StructInstantiation, + IndexKind::FunctionInstantiation, IndexKind::StructDefinition, IndexKind::FieldDefinition, IndexKind::FunctionDefinition, IndexKind::TypeSignature, IndexKind::FunctionSignature, - IndexKind::LocalsSignature, + IndexKind::Signature, ]; #[cfg(test)] @@ -174,7 +180,7 @@ pub struct ApplyOutOfBoundsContext { // Some precomputations done for signatures. type_sig_structs: Vec, function_sig_structs: Vec, - locals_sig_structs: Vec<(LocalsSignatureIndex, usize)>, + locals_sig_structs: Vec<(SignatureIndex, usize)>, } impl ApplyOutOfBoundsContext { @@ -229,7 +235,7 @@ impl ApplyOutOfBoundsContext { // are going to be modifiable, so pick among them. IndexKind::TypeSignature => self.type_sig_structs.len(), IndexKind::FunctionSignature => self.function_sig_structs.len(), - IndexKind::LocalsSignature => self.locals_sig_structs.len(), + IndexKind::Signature => self.locals_sig_structs.len(), // For the other sorts it's always possible to change an index. src_kind => self.module.kind_count(src_kind), }; @@ -352,8 +358,8 @@ impl ApplyOutOfBoundsContext { (FunctionDefinition, FunctionHandle) => { self.module.function_defs[src_idx].function = FunctionHandleIndex::new(new_idx) } - (FunctionDefinition, LocalsSignature) => { - self.module.function_defs[src_idx].code.locals = LocalsSignatureIndex::new(new_idx) + (FunctionDefinition, Signature) => { + self.module.function_defs[src_idx].code.locals = SignatureIndex::new(new_idx) } (TypeSignature, StructHandle) => { // For this and the other signatures, the source index will be picked from @@ -366,16 +372,16 @@ impl ApplyOutOfBoundsContext { (FunctionSignature, StructHandle) => match &self.function_sig_structs[src_idx] { FunctionSignatureTokenIndex::ReturnType(actual_src_idx, ret_idx) => { src_idx = actual_src_idx.into_index(); - self.module.function_signatures[src_idx].return_types[*ret_idx] + self.module.function_signatures[src_idx].return_[*ret_idx] .debug_set_sh_idx(StructHandleIndex::new(new_idx)); } FunctionSignatureTokenIndex::ArgType(actual_src_idx, arg_idx) => { src_idx = actual_src_idx.into_index(); - self.module.function_signatures[src_idx].arg_types[*arg_idx] + self.module.function_signatures[src_idx].parameters[*arg_idx] .debug_set_sh_idx(StructHandleIndex::new(new_idx)); } }, - (LocalsSignature, StructHandle) => { + (Signature, StructHandle) => { let (actual_src_idx, arg_idx) = self.locals_sig_structs[src_idx]; src_idx = actual_src_idx.into_index(); self.module.locals_signatures[src_idx].0[arg_idx] @@ -434,13 +440,13 @@ impl ApplyOutOfBoundsContext { /// Returns the indexes of locals signatures that contain struct handles inside them. fn locals_sig_structs<'b>( module: &'b CompiledModule, - ) -> impl Iterator + 'b { + ) -> impl Iterator + 'b { let module_view = ModuleView::new(module); module_view .locals_signatures() .enumerate() .flat_map(|(idx, signature)| { - let idx = LocalsSignatureIndex::new(idx as u16); + let idx = SignatureIndex::new(idx as u16); Self::find_struct_tokens(signature.tokens(), move |arg_idx| (idx, arg_idx)) }) } diff --git a/language/bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs b/language/bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs index f9163909e43b..567e404009a1 100644 --- a/language/bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs +++ b/language/bytecode-verifier/invalid-mutations/src/bounds/code_unit.rs @@ -10,7 +10,7 @@ use vm::{ file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, CodeOffset, CompiledModuleMut, FieldDefinitionIndex, FunctionHandleIndex, LocalIndex, StructDefinitionIndex, TableIndex, - NO_TYPE_ACTUALS, + NO_TYPE_ARGUMENTS, }, internals::ModuleIndex, IndexKind, @@ -72,7 +72,7 @@ macro_rules! struct_bytecode { let new_idx = (dst_len + $offset) as TableIndex; ( // TODO: check this again once generics is implemented - $bytecode_ident($idx_type::new(new_idx), NO_TYPE_ACTUALS), + $bytecode_ident($idx_type::new(new_idx), NO_TYPE_ARGUMENTS), bytecode_offset_err( $idx_type::KIND, new_idx as usize, diff --git a/language/bytecode-verifier/invalid-mutations/src/signature.rs b/language/bytecode-verifier/invalid-mutations/src/signature.rs index dfedbfa9e8d2..934cab349658 100644 --- a/language/bytecode-verifier/invalid-mutations/src/signature.rs +++ b/language/bytecode-verifier/invalid-mutations/src/signature.rs @@ -66,18 +66,18 @@ impl<'a> ApplySignatureDoubleRefContext<'a> { idx2, ), SignatureIndex::FunctionReturn(idx1) => ( - &mut self.module.function_signatures[*idx1].return_types[idx2], + &mut self.module.function_signatures[*idx1].return_[idx2], IndexKind::FunctionSignature, *idx1, ), SignatureIndex::FunctionArg(idx1) => ( - &mut self.module.function_signatures[*idx1].arg_types[idx2], + &mut self.module.function_signatures[*idx1].parameters[idx2], IndexKind::FunctionSignature, *idx1, ), SignatureIndex::Locals(idx1) => ( &mut self.module.locals_signatures[*idx1].0[idx2], - IndexKind::LocalsSignature, + IndexKind::Signature, *idx1, ), }; @@ -124,10 +124,10 @@ impl<'a> ApplySignatureDoubleRefContext<'a> { let mut res = RepeatVec::new(); res.extend(SignatureIndex::Type, self.module.type_signatures.len()); for (idx, sig) in self.module.function_signatures.iter().enumerate() { - res.extend(SignatureIndex::FunctionReturn(idx), sig.return_types.len()); + res.extend(SignatureIndex::FunctionReturn(idx), sig.return_.len()); } for (idx, sig) in self.module.function_signatures.iter().enumerate() { - res.extend(SignatureIndex::FunctionArg(idx), sig.arg_types.len()); + res.extend(SignatureIndex::FunctionArg(idx), sig.parameters.len()); } for (idx, sig) in self.module.locals_signatures.iter().enumerate() { res.extend(SignatureIndex::Locals(idx), sig.0.len()); diff --git a/language/bytecode-verifier/src/abstract_state.rs b/language/bytecode-verifier/src/abstract_state.rs index 90d0a58f0075..ef0e1eb78484 100644 --- a/language/bytecode-verifier/src/abstract_state.rs +++ b/language/bytecode-verifier/src/abstract_state.rs @@ -49,7 +49,7 @@ impl AbstractValue { pub fn is_unrestricted_value(&self) -> bool { match self { AbstractValue::Reference(_) => false, - AbstractValue::Value(Kind::Unrestricted) => true, + AbstractValue::Value(Kind::Copyable) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, } } @@ -58,7 +58,7 @@ impl AbstractValue { pub fn is_possibly_resource(&self) -> bool { match self { AbstractValue::Reference(_) => false, - AbstractValue::Value(Kind::Unrestricted) => false, + AbstractValue::Value(Kind::Copyable) => false, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => true, } } @@ -101,24 +101,28 @@ impl AbstractState { let function_signature_view = function_definition_view.signature(); let mut locals = BTreeMap::new(); let mut borrow_graph = BorrowGraph::new(); - for (arg_idx, arg_type_view) in function_signature_view.arg_tokens().enumerate() { - if arg_type_view.is_reference() { + for (arg_idx, parameter_view) in function_signature_view.arg_tokens().enumerate() { + if parameter_view.is_reference() { let id = RefID::new(arg_idx); borrow_graph.add(id); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { - signature: arg_type_view.as_inner().clone(), + signature: parameter_view.as_inner().clone(), value: AbstractValue::Reference(id), }, ); } else { - let arg_kind = arg_type_view - .kind(&function_definition_view.signature().as_inner().type_formals); + let arg_kind = parameter_view.kind( + &function_definition_view + .signature() + .as_inner() + .type_parameters, + ); locals.insert( arg_idx as LocalIndex, TypedAbstractValue { - signature: arg_type_view.as_inner().clone(), + signature: parameter_view.as_inner().clone(), value: AbstractValue::Value(arg_kind), }, ); @@ -162,13 +166,13 @@ impl AbstractState { match self.locals[&idx].value { AbstractValue::Reference(_) => true, AbstractValue::Value(Kind::All) | AbstractValue::Value(Kind::Resource) => false, - AbstractValue::Value(Kind::Unrestricted) => !self.is_local_borrowed(idx), + AbstractValue::Value(Kind::Copyable) => !self.is_local_borrowed(idx), } } /// checks if the stack frame of the function being analyzed can be safely destroyed. /// safe destruction requires that all references in locals have already been destroyed - /// and all values in locals are unrestricted and unborrowed. + /// and all values in locals are copyable and unborrowed. pub fn is_frame_safe_to_destroy(&self) -> bool { self.locals .values() @@ -183,7 +187,7 @@ impl AbstractState { match local.value { AbstractValue::Reference(id) => self.remove(id), AbstractValue::Value(kind) => { - checked_verify!(kind == Kind::Unrestricted); + checked_verify!(kind == Kind::Copyable); } } } @@ -395,7 +399,7 @@ impl AbstractState { // Join error, a resource is available along one path but not the other (None, Some(v)) | (Some(v), None) if v.value.is_possibly_resource() => return None, - // The local has a unrestricted value on one side but not the other, nothing to add + // The local has a copyable value on one side but not the other, nothing to add (Some(v), None) => { // A reference exists on one side, but not the other. Release if let AbstractValue::Reference(id) = &v.value { diff --git a/language/bytecode-verifier/src/check_duplication.rs b/language/bytecode-verifier/src/check_duplication.rs index 6353cd70c4f7..280d14f58f8e 100644 --- a/language/bytecode-verifier/src/check_duplication.rs +++ b/language/bytecode-verifier/src/check_duplication.rs @@ -69,7 +69,7 @@ impl<'a> DuplicationChecker<'a> { } if let Some(idx) = Self::first_duplicate_element(self.module.locals_signatures()) { errors.push(verification_error( - IndexKind::LocalsSignature, + IndexKind::Signature, idx, StatusCode::DUPLICATE_ELEMENT, )) diff --git a/language/bytecode-verifier/src/instantiation_loops.rs b/language/bytecode-verifier/src/instantiation_loops.rs index a1b91e3ebcc6..a8844fc69b10 100644 --- a/language/bytecode-verifier/src/instantiation_loops.rs +++ b/language/bytecode-verifier/src/instantiation_loops.rs @@ -24,7 +24,7 @@ use vm::{ access::ModuleAccess, file_format::{ Bytecode, CompiledModule, FunctionDefinition, FunctionDefinitionIndex, FunctionHandleIndex, - LocalsSignatureIndex, SignatureToken, TypeParameterIndex, + SignatureIndex, SignatureToken, TypeParameterIndex, }, }; @@ -137,7 +137,7 @@ impl<'a> InstantiationLoopChecker<'a> { &mut self, caller_idx: FunctionDefinitionIndex, callee_idx: FunctionDefinitionIndex, - type_actuals_idx: LocalsSignatureIndex, + type_actuals_idx: SignatureIndex, ) { let type_actuals = &self.module.locals_signature_at(type_actuals_idx).0; diff --git a/language/bytecode-verifier/src/resources.rs b/language/bytecode-verifier/src/resources.rs index 7701308a40b6..fd9134b8e60d 100644 --- a/language/bytecode-verifier/src/resources.rs +++ b/language/bytecode-verifier/src/resources.rs @@ -27,7 +27,7 @@ impl<'a> ResourceTransitiveChecker<'a> { let any_resource_field = fields.any(|field| { field .type_signature() - .contains_nominal_resource(struct_def.type_formals()) + .contains_nominal_resource(struct_def.type_parameters()) }); if any_resource_field { errors.push(verification_error( diff --git a/language/bytecode-verifier/src/signature.rs b/language/bytecode-verifier/src/signature.rs index 38293cb40501..b9775e3a63a1 100644 --- a/language/bytecode-verifier/src/signature.rs +++ b/language/bytecode-verifier/src/signature.rs @@ -57,18 +57,18 @@ impl<'a> SignatureChecker<'a> { .iter() .enumerate() .flat_map(move |(idx, sig)| { - let context = (self.module.struct_handles(), sig.type_formals.as_slice()); - let errors_return_types = sig.return_types.iter().flat_map(move |ty| { + let context = (self.module.struct_handles(), sig.type_parameters.as_slice()); + let errors_return_ = sig.return_.iter().flat_map(move |ty| { check_signature(context, ty) .into_iter() .map(move |err| append_err_info(err, IndexKind::FunctionSignature, idx)) }); - let errors_arg_types = sig.arg_types.iter().flat_map(move |ty| { + let errors_parameters = sig.parameters.iter().flat_map(move |ty| { check_signature(context, ty) .into_iter() .map(move |err| append_err_info(err, IndexKind::FunctionSignature, idx)) }); - errors_return_types.chain(errors_arg_types) + errors_return_.chain(errors_parameters) }) } @@ -89,7 +89,7 @@ impl<'a> SignatureChecker<'a> { let end = start + (field_count as usize); let context = ( self.module.struct_handles(), - struct_handle.type_formals.as_slice(), + struct_handle.type_parameters.as_slice(), ); let errors = self.module.field_defs()[start..end] @@ -142,14 +142,14 @@ impl<'a> SignatureChecker<'a> { let func_sig = self.module.function_signature_at(func_handle.signature); let context = ( self.module.struct_handles(), - func_sig.type_formals.as_slice(), + func_sig.type_parameters.as_slice(), ); let locals_idx = func_def.code.locals; let locals = &self.module.locals_signature_at(locals_idx).0; let errors_locals = locals.iter().flat_map(move |ty| { check_signature(context, ty).into_iter().map(move |err| { append_err_info( - append_err_info(err, IndexKind::LocalsSignature, locals_idx.0 as usize), + append_err_info(err, IndexKind::Signature, locals_idx.0 as usize), IndexKind::FunctionDefinition, func_def_idx, ) @@ -173,7 +173,7 @@ impl<'a> SignatureChecker<'a> { &self.module.locals_signature_at(*type_actuals_idx).0; check_generic_instance( context, - &func_sig.type_formals, + &func_sig.type_parameters, type_actuals, ) } @@ -185,7 +185,7 @@ impl<'a> SignatureChecker<'a> { &self.module.locals_signature_at(*type_actuals_idx).0; check_generic_instance( context, - &struct_handle.type_formals, + &struct_handle.type_parameters, type_actuals, ) } @@ -201,7 +201,7 @@ impl<'a> SignatureChecker<'a> { &self.module.locals_signature_at(*type_actuals_idx).0; check_generic_instance( context, - &struct_handle.type_formals, + &struct_handle.type_parameters, type_actuals, ) } @@ -239,7 +239,7 @@ fn check_generic_instance( if constraints.len() != type_actuals.len() { errors.push( - VMStatus::new(StatusCode::NUMBER_OF_TYPE_ACTUALS_MISMATCH).with_message(format!( + VMStatus::new(StatusCode::NUMBER_OF_TYPE_ARGUMENTS_MISMATCH).with_message(format!( "expected {} type actuals got {}", constraints.len(), type_actuals.len() @@ -291,7 +291,7 @@ fn check_signature_no_refs( Vector(ty) => check_signature_no_refs(context, ty), Struct(idx, type_actuals) => { let sh = &struct_handles[idx.0 as usize]; - check_generic_instance(context, &sh.type_formals, type_actuals) + check_generic_instance(context, &sh.type_parameters, type_actuals) } } } diff --git a/language/bytecode-verifier/src/stack_usage_verifier.rs b/language/bytecode-verifier/src/stack_usage_verifier.rs index 9bd177d730d5..a5f9b0b3f2fe 100644 --- a/language/bytecode-verifier/src/stack_usage_verifier.rs +++ b/language/bytecode-verifier/src/stack_usage_verifier.rs @@ -151,8 +151,8 @@ impl<'a> StackUsageVerifier<'a> { Bytecode::Call(idx, _) => { let function_handle = self.module.function_handle_at(*idx); let signature = self.module.function_signature_at(function_handle.signature); - let arg_count = signature.arg_types.len() as u32; - let return_count = signature.return_types.len() as u32; + let arg_count = signature.parameters.len() as u32; + let return_count = signature.return_.len() as u32; (arg_count, return_count) } diff --git a/language/bytecode-verifier/src/type_memory_safety.rs b/language/bytecode-verifier/src/type_memory_safety.rs index ba45d43786f1..6684a24ab7c7 100644 --- a/language/bytecode-verifier/src/type_memory_safety.rs +++ b/language/bytecode-verifier/src/type_memory_safety.rs @@ -20,7 +20,7 @@ use vm::{ errors::err_at_offset, file_format::{ Bytecode, CompiledModule, FieldDefinitionIndex, FunctionDefinition, Kind, LocalIndex, - LocalsSignatureIndex, SignatureToken, StructDefinitionIndex, + SignatureIndex, SignatureToken, StructDefinitionIndex, }, views::{ FunctionDefinitionView, FunctionSignatureView, LocalsSignatureView, ModuleView, @@ -51,8 +51,8 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let errors: Vec = function_signature_view .arg_tokens() .enumerate() - .flat_map(|(arg_idx, arg_type_view)| { - let arg_token = arg_type_view.as_inner(); + .flat_map(|(arg_idx, parameter_view)| { + let arg_token = parameter_view.as_inner(); let local_token = locals_signature_view .token_at(arg_idx as LocalIndex) .as_inner(); @@ -106,12 +106,12 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { } /// Gives the current constraints on the type formals in the current function. - fn type_formals(&self) -> &[Kind] { + fn type_parameters(&self) -> &[Kind] { &self .function_definition_view .signature() .as_inner() - .type_formals + .type_parameters } fn is_readable_reference(state: &AbstractState, signature: &SignatureToken, id: RefID) -> bool { @@ -235,7 +235,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { offset: usize, mut_: bool, idx: StructDefinitionIndex, - type_actuals_idx: LocalsSignatureIndex, + type_actuals_idx: SignatureIndex, ) { let struct_definition = self.module().struct_def_at(idx); if !StructDefinitionView::new(self.module(), struct_definition).is_nominal_resource() { @@ -249,7 +249,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let type_actuals = &self.module().locals_signature_at(type_actuals_idx).0; let struct_type = SignatureToken::Struct(struct_definition.struct_handle, type_actuals.clone()); - SignatureTokenView::new(self.module(), &struct_type).kind(self.type_formals()); + SignatureTokenView::new(self.module(), &struct_type).kind(self.type_parameters()); let operand = self.stack.pop().unwrap(); if operand.signature != SignatureToken::Address { errors.push(err_at_offset( @@ -285,8 +285,8 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { Bytecode::Pop => { let operand = self.stack.pop().unwrap(); let kind = SignatureTokenView::new(self.module(), &operand.signature) - .kind(self.type_formals()); - if kind != Kind::Unrestricted { + .kind(self.type_parameters()); + if kind != Kind::Copyable { errors.push(err_at_offset(StatusCode::POP_RESOURCE_ERROR, offset)); return; } @@ -410,42 +410,42 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { Bytecode::LdU8(_) => { self.stack.push(TypedAbstractValue { signature: SignatureToken::U8, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::LdU64(_) => { self.stack.push(TypedAbstractValue { signature: SignatureToken::U64, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::LdU128(_) => { self.stack.push(TypedAbstractValue { signature: SignatureToken::U128, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::LdAddr(_) => { self.stack.push(TypedAbstractValue { signature: SignatureToken::Address, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::LdByteArray(_) => { self.stack.push(TypedAbstractValue { signature: SignatureToken::Vector(Box::new(SignatureToken::U8)), - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::LdTrue | Bytecode::LdFalse => { self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } @@ -460,15 +460,15 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { value: AbstractValue::Reference(id), }); } else { - match signature_view.kind(self.type_formals()) { + match signature_view.kind(self.type_parameters()) { Kind::Resource | Kind::All => { errors.push(err_at_offset(StatusCode::COPYLOC_RESOURCE_ERROR, offset)) } - Kind::Unrestricted => { + Kind::Copyable => { if !state.is_local_mutably_borrowed(*idx) { self.stack.push(TypedAbstractValue { signature: signature_view.as_inner().clone(), - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }) } else { errors.push(err_at_offset( @@ -522,14 +522,14 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { FunctionSignatureView::new(self.module(), function_signature); let mut all_references_to_borrow_from = BTreeSet::new(); let mut mutable_references_to_borrow_from = BTreeSet::new(); - for arg_type in function_signature.arg_types.iter().rev() { + for parameter in function_signature.parameters.iter().rev() { let arg = self.stack.pop().unwrap(); - if arg.signature != arg_type.substitute(type_actuals) { + if arg.signature != parameter.substitute(type_actuals) { errors.push(err_at_offset(StatusCode::CALL_TYPE_MISMATCH_ERROR, offset)); return; } if let AbstractValue::Reference(id) = arg.value { - if arg_type.is_mutable_reference() { + if parameter.is_mutable_reference() { if state.is_borrowed(id) { errors.push(err_at_offset( StatusCode::CALL_BORROWED_MUTABLE_REFERENCE_ERROR, @@ -556,7 +556,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { } else { let return_type = return_type_view.as_inner().substitute(type_actuals); let kind = SignatureTokenView::new(self.module(), &return_type) - .kind(self.type_formals()); + .kind(self.type_parameters()); self.stack.push(TypedAbstractValue { signature: return_type, value: AbstractValue::Value(kind), @@ -574,8 +574,8 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let type_actuals = &self.module().locals_signature_at(*type_actuals_idx).0; let struct_type = SignatureToken::Struct(struct_definition.struct_handle, type_actuals.clone()); - let kind = - SignatureTokenView::new(self.module(), &struct_type).kind(self.type_formals()); + let kind = SignatureTokenView::new(self.module(), &struct_type) + .kind(self.type_parameters()); let struct_definition_view = StructDefinitionView::new(self.module(), struct_definition); @@ -649,7 +649,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { .substitute(type_actuals); // Get the kind of the type. let kind = SignatureTokenView::new(self.module(), &field_type) - .kind(self.type_formals()); + .kind(self.type_parameters()); self.stack.push(TypedAbstractValue { signature: field_type, value: AbstractValue::Value(kind), @@ -684,14 +684,14 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { _ => panic!("Unreachable"), }; if SignatureTokenView::new(self.module(), &inner_signature) - .kind(self.type_formals()) - != Kind::Unrestricted + .kind(self.type_parameters()) + != Kind::Copyable { errors.push(err_at_offset(StatusCode::READREF_RESOURCE_ERROR, offset)) } else { self.stack.push(TypedAbstractValue { signature: inner_signature, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); state.remove(operand_id); } @@ -703,12 +703,12 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let val_operand = self.stack.pop().unwrap(); if let SignatureToken::MutableReference(signature) = ref_operand.signature { let kind = SignatureTokenView::new(self.module(), &signature) - .kind(self.type_formals()); + .kind(self.type_parameters()); match kind { Kind::Resource | Kind::All => { errors.push(err_at_offset(StatusCode::WRITEREF_RESOURCE_ERROR, offset)) } - Kind::Unrestricted => { + Kind::Copyable => { if val_operand.signature != *signature { errors.push(err_at_offset( StatusCode::WRITEREF_TYPE_MISMATCH_ERROR, @@ -740,7 +740,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand.signature.is_integer() { self.stack.push(TypedAbstractValue { signature: SignatureToken::U8, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -754,7 +754,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand.signature.is_integer() { self.stack.push(TypedAbstractValue { signature: SignatureToken::U64, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -768,7 +768,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand.signature.is_integer() { self.stack.push(TypedAbstractValue { signature: SignatureToken::U128, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -791,7 +791,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand1.signature.is_integer() && operand1.signature == operand2.signature { self.stack.push(TypedAbstractValue { signature: operand1.signature, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -807,7 +807,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand2.signature.is_integer() && operand1.signature == SignatureToken::U8 { self.stack.push(TypedAbstractValue { signature: operand2.signature, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -825,7 +825,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { { self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -840,7 +840,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand.signature == SignatureToken::Bool { self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -854,8 +854,8 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let operand1 = self.stack.pop().unwrap(); let operand2 = self.stack.pop().unwrap(); let kind1 = SignatureTokenView::new(self.module(), &operand1.signature) - .kind(self.type_formals()); - let is_copyable = kind1 == Kind::Unrestricted; + .kind(self.type_parameters()); + let is_copyable = kind1 == Kind::Copyable; if is_copyable && operand1.signature == operand2.signature { if let AbstractValue::Reference(id) = operand1.value { if Self::is_readable_reference(state, &operand1.signature, id) { @@ -881,7 +881,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { } self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -897,7 +897,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { if operand1.signature.is_integer() && operand1.signature == operand2.signature { self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -922,13 +922,13 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let type_actuals = &self.module().locals_signature_at(*type_actuals_idx).0; let struct_type = SignatureToken::Struct(struct_definition.struct_handle, type_actuals.clone()); - SignatureTokenView::new(self.module(), &struct_type).kind(self.type_formals()); + SignatureTokenView::new(self.module(), &struct_type).kind(self.type_parameters()); let operand = self.stack.pop().unwrap(); if operand.signature == SignatureToken::Address { self.stack.push(TypedAbstractValue { signature: SignatureToken::Bool, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } else { errors.push(err_at_offset( @@ -964,7 +964,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let type_actuals = &self.module().locals_signature_at(*type_actuals_idx).0; let struct_type = SignatureToken::Struct(struct_definition.struct_handle, type_actuals.clone()); - SignatureTokenView::new(self.module(), &struct_type).kind(self.type_formals()); + SignatureTokenView::new(self.module(), &struct_type).kind(self.type_parameters()); let operand = self.stack.pop().unwrap(); if operand.signature == SignatureToken::Address { @@ -995,7 +995,7 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { let type_actuals = &self.module().locals_signature_at(*type_actuals_idx).0; let struct_type = SignatureToken::Struct(struct_definition.struct_handle, type_actuals.clone()); - SignatureTokenView::new(self.module(), &struct_type).kind(self.type_formals()); + SignatureTokenView::new(self.module(), &struct_type).kind(self.type_parameters()); let value_operand = self.stack.pop().unwrap(); if value_operand.signature != struct_type { @@ -1012,21 +1012,21 @@ impl<'a> TypeAndMemorySafetyAnalysis<'a> { | Bytecode::GetTxnSequenceNumber => { self.stack.push(TypedAbstractValue { signature: SignatureToken::U64, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::GetTxnSenderAddress => { self.stack.push(TypedAbstractValue { signature: SignatureToken::Address, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } Bytecode::GetTxnPublicKey => { self.stack.push(TypedAbstractValue { signature: SignatureToken::ByteArray, - value: AbstractValue::Value(Kind::Unrestricted), + value: AbstractValue::Value(Kind::Copyable), }); } } diff --git a/language/bytecode-verifier/src/unused_entries.rs b/language/bytecode-verifier/src/unused_entries.rs index b33bd30fedde..c8a6b3dff720 100644 --- a/language/bytecode-verifier/src/unused_entries.rs +++ b/language/bytecode-verifier/src/unused_entries.rs @@ -95,7 +95,7 @@ impl<'a> UnusedEntryChecker<'a> { let iter_locals_signatures = Self::collect_errors(&self.locals_signatures, |idx| { verification_error( - IndexKind::LocalsSignature, + IndexKind::Signature, idx, StatusCode::UNUSED_LOCALS_SIGNATURE, ) diff --git a/language/bytecode-verifier/src/verifier.rs b/language/bytecode-verifier/src/verifier.rs index fc3207a54a65..9ca0a7d675b2 100644 --- a/language/bytecode-verifier/src/verifier.rs +++ b/language/bytecode-verifier/src/verifier.rs @@ -305,12 +305,12 @@ impl fmt::Display for VerifiedScript { pub fn verify_main_signature(script: &CompiledScript) -> Vec { let function_handle = &script.function_handle_at(script.main().function); let function_signature = &script.function_signature_at(function_handle.signature); - if !function_signature.return_types.is_empty() { + if !function_signature.return_.is_empty() { return vec![VMStatus::new(StatusCode::INVALID_MAIN_FUNCTION_SIGNATURE)]; } - for arg_type in &function_signature.arg_types { - if !(arg_type.is_primitive() - || *arg_type == SignatureToken::Vector(Box::new(SignatureToken::U8))) + for parameter in &function_signature.parameters { + if !(parameter.is_primitive() + || *parameter == SignatureToken::Vector(Box::new(SignatureToken::U8))) { return vec![VMStatus::new(StatusCode::INVALID_MAIN_FUNCTION_SIGNATURE)]; } @@ -431,14 +431,14 @@ fn verify_native_structs(module_view: &ModuleView) -> Vec StructSourceMap { Ok(count) => (0..count).for_each(|_| self.fields.push(Location::default())), } - for i in 0..struct_handle.type_formals.len() { + for i in 0..struct_handle.type_parameters.len() { let name = format!("Ty{}", i); self.add_type_parameter((Identifier::new(name)?, Location::default())); } @@ -183,7 +183,7 @@ impl FunctionSourceMap { let locals = module.locals_signature_at(function_code.locals); // Generate names for each type parameter - for i in 0..function_signature.type_formals.len() { + for i in 0..function_signature.type_parameters.len() { let name = format!("Ty{}", i); self.add_type_parameter((Identifier::new(name)?, Location::default())); } diff --git a/language/compiler/ir-to-bytecode/src/compiler.rs b/language/compiler/ir-to-bytecode/src/compiler.rs index 7b49d78970ed..6094b16466d5 100644 --- a/language/compiler/ir-to-bytecode/src/compiler.rs +++ b/language/compiler/ir-to-bytecode/src/compiler.rs @@ -22,7 +22,7 @@ use vm::{ file_format::{ self, Bytecode, CodeOffset, CodeUnit, CompiledModule, CompiledModuleMut, CompiledProgram, CompiledScript, CompiledScriptMut, FieldDefinition, FieldDefinitionIndex, - FunctionDefinition, FunctionSignature, Kind, LocalsSignature, MemberCount, SignatureToken, + FunctionDefinition, FunctionSignature, Kind, MemberCount, Signature, SignatureToken, StructDefinition, StructFieldInformation, StructHandleIndex, TableIndex, }, }; @@ -39,7 +39,7 @@ macro_rules! record_src_loc { .source_map .add_struct_field_mapping($context.current_struct_definition_index(), $field.span)?; }}; - (function_type_formals: $context:expr, $var:expr) => { + (function_type_parameters: $context:expr, $var:expr) => { for (ty_var, _) in $var.iter() { let source_name = (Identifier::from(ty_var.name()), ty_var.span); $context.source_map.add_function_type_parameter_mapping( @@ -55,7 +55,7 @@ macro_rules! record_src_loc { $location, )?; }}; - (struct_type_formals: $context:expr, $var:expr) => { + (struct_type_parameters: $context:expr, $var:expr) => { for (ty_var, _) in $var.iter() { let source_name = (Identifier::from(ty_var.name()), ty_var.span); $context.source_map.add_struct_type_parameter_mapping( @@ -192,7 +192,7 @@ impl InferredType { struct FunctionFrame { local_count: u8, locals: HashMap, - local_types: LocalsSignature, + local_types: Signature, // i64 to allow the bytecode verifier to catch errors of // - negative stack sizes // - excessivley large stack sizes @@ -366,6 +366,8 @@ pub fn compile_script<'a, T: 'a + ModuleAccess>( module_handles, struct_handles, function_handles, + struct_instantiations: vec![], + function_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -401,7 +403,7 @@ pub fn compile_module<'a, T: 'a + ModuleAccess>( module: self_name.clone(), name: s.name.clone(), }; - let (_, tys) = type_formals(&s.type_formals)?; + let (_, tys) = type_parameters(&s.type_parameters)?; context.declare_struct_handle_index(ident, s.is_nominal_resource, tys)?; } @@ -434,6 +436,10 @@ pub fn compile_module<'a, T: 'a + ModuleAccess>( module_handles, struct_handles, function_handles, + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -465,7 +471,9 @@ fn compile_imports( Ok(()) } -fn type_formals(ast_tys: &[(TypeVar, ast::Kind)]) -> Result<(HashMap, Vec)> { +fn type_parameters( + ast_tys: &[(TypeVar, ast::Kind)], +) -> Result<(HashMap, Vec)> { let mut m = HashMap::new(); let mut tys = vec![]; for (idx, (ty_var, k)) in ast_tys.iter().enumerate() { @@ -482,7 +490,7 @@ fn kind(ast_k: &ast::Kind) -> Kind { match ast_k { ast::Kind::All => Kind::All, ast::Kind::Resource => Kind::Resource, - ast::Kind::Unrestricted => Kind::Unrestricted, + ast::Kind::Copyable => Kind::Copyable, } } @@ -517,7 +525,7 @@ fn compile_type(context: &mut Context, ty: &Type) -> Result { SignatureToken::Struct(sh_idx, tokens) } Type::TypeParameter(ty_var) => { - SignatureToken::TypeParameter(context.type_formal_index(ty_var)?) + SignatureToken::TypeParameter(context.type_parameter_index(ty_var)?) } }) } @@ -526,19 +534,19 @@ fn function_signature( context: &mut Context, f: &ast::FunctionSignature, ) -> Result { - let (map, _) = type_formals(&f.type_formals)?; - context.bind_type_formals(map)?; - let return_types = compile_types(context, &f.return_type)?; - let arg_types = f + let (map, _) = type_parameters(&f.type_parameters)?; + context.bind_type_parameters(map)?; + let return_ = compile_types(context, &f.return_type)?; + let parameters = f .formals .iter() .map(|(_, ty)| compile_type(context, ty)) .collect::>()?; - let type_formals = f.type_formals.iter().map(|(_, k)| kind(k)).collect(); + let type_parameters = f.type_parameters.iter().map(|(_, k)| kind(k)).collect(); Ok(FunctionSignature { - return_types, - arg_types, - type_formals, + return_, + parameters, + type_parameters, }) } @@ -556,9 +564,9 @@ fn compile_structs( }; let sh_idx = context.struct_handle_index(sident.clone())?; record_src_loc!(struct_decl: context, s.span); - record_src_loc!(struct_type_formals: context, &s.type_formals); - let (map, _) = type_formals(&s.type_formals)?; - context.bind_type_formals(map)?; + record_src_loc!(struct_type_parameters: context, &s.type_parameters); + let (map, _) = type_parameters(&s.type_parameters)?; + context.bind_type_parameters(map)?; let field_information = compile_fields(context, &mut field_defs, sh_idx, s.value.fields)?; context.declare_struct_definition_index(s.value.name)?; struct_defs.push(StructDefinition { @@ -626,8 +634,8 @@ fn compile_function( ) -> Result { record_src_loc!(function_decl: context, ast_function.span, function_index); record_src_loc!( - function_type_formals: context, - &ast_function.signature.type_formals + function_type_parameters: context, + &ast_function.signature.type_parameters ); let fh_idx = context.function_handle(self_name.clone(), name)?.1; @@ -648,8 +656,8 @@ fn compile_function( let code = match ast_function.body { FunctionBody::Move { locals, code } => { - let (m, _) = type_formals(&ast_function.signature.type_formals)?; - context.bind_type_formals(m)?; + let (m, _) = type_parameters(&ast_function.signature.type_parameters)?; + context.bind_type_parameters(m)?; compile_function_body(context, ast_function.signature.formals, locals, code)? } FunctionBody::Native => { @@ -674,7 +682,7 @@ fn compile_function_body( block: Block_, ) -> Result { let mut function_frame = FunctionFrame::new(); - let mut locals_signature = LocalsSignature(vec![]); + let mut locals_signature = Signature(vec![]); for (var, t) in formals { let sig = compile_type(context, &t)?; function_frame.define_local(&var, sig.clone())?; @@ -891,7 +899,7 @@ fn compile_command( compile_lvalues(context, function_frame, code, lvalues)?; } Cmd_::Unpack(name, tys, bindings, e) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; compile_expression(context, function_frame, code, *e)?; @@ -1055,7 +1063,7 @@ fn compile_expression( } }, Exp_::Pack(name, tys, fields) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; let def_idx = context.struct_definition_index(&name)?; @@ -1242,7 +1250,7 @@ fn compile_call( vec_deque![InferredType::Address] } Builtin::Exists(name, tys) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; let def_idx = context.struct_definition_index(&name)?; push_instr!(call.span, Bytecode::Exists(def_idx, type_actuals_id)); @@ -1251,7 +1259,7 @@ fn compile_call( vec_deque![InferredType::Bool] } Builtin::BorrowGlobal(mut_, name, tys) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; let def_idx = context.struct_definition_index(&name)?; push_instr! {call.span, @@ -1278,7 +1286,7 @@ fn compile_call( }] } Builtin::MoveFrom(name, tys) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; let def_idx = context.struct_definition_index(&name)?; push_instr!(call.span, Bytecode::MoveFrom(def_idx, type_actuals_id)); @@ -1294,7 +1302,7 @@ fn compile_call( vec_deque![InferredType::Struct(sh_idx)] } Builtin::MoveToSender(name, tys) => { - let tokens = LocalsSignature(compile_types(context, &tys)?); + let tokens = Signature(compile_types(context, &tys)?); let type_actuals_id = context.locals_signature_index(tokens)?; let def_idx = context.struct_definition_index(&name)?; @@ -1339,7 +1347,7 @@ fn compile_call( name, type_actuals, } => { - let tokens = LocalsSignature(compile_types(context, &type_actuals)?); + let tokens = Signature(compile_types(context, &type_actuals)?); let type_actuals_id = context.locals_signature_index(tokens)?; let fh_idx = context.function_handle(module.clone(), name.clone())?.1; let fcall = Bytecode::Call(fh_idx, type_actuals_id); @@ -1351,7 +1359,7 @@ fn compile_call( function_frame.push()?; let signature = &context.function_signature(module, name)?.0; signature - .return_types + .return_ .iter() .map(InferredType::from_signature_token) .collect() diff --git a/language/compiler/ir-to-bytecode/src/context.rs b/language/compiler/ir-to-bytecode/src/context.rs index 2348fbdd38e3..9d68b58efb88 100644 --- a/language/compiler/ir-to-bytecode/src/context.rs +++ b/language/compiler/ir-to-bytecode/src/context.rs @@ -15,9 +15,9 @@ use vm::{ file_format::{ AddressPoolIndex, ByteArrayPoolIndex, FieldDefinitionIndex, FunctionDefinitionIndex, FunctionHandle, FunctionHandleIndex, FunctionSignature, FunctionSignatureIndex, - IdentifierIndex, Kind, LocalsSignature, LocalsSignatureIndex, ModuleHandle, - ModuleHandleIndex, SignatureToken, StructDefinitionIndex, StructHandle, StructHandleIndex, - TableIndex, TypeSignature, TypeSignatureIndex, + IdentifierIndex, Kind, ModuleHandle, ModuleHandleIndex, Signature, SignatureIndex, + SignatureToken, StructDefinitionIndex, StructHandle, StructHandleIndex, TableIndex, + TypeSignature, TypeSignatureIndex, }, }; @@ -143,7 +143,7 @@ pub struct MaterializedPools { /// Function signature pool pub function_signatures: Vec, /// Locals signatures pool - pub locals_signatures: Vec, + pub locals_signatures: Vec, /// Identifier pool pub identifiers: Vec, /// Byte array pool @@ -176,13 +176,13 @@ pub struct Context<'a> { module_handles: HashMap, struct_handles: HashMap, type_signatures: HashMap, - locals_signatures: HashMap, + locals_signatures: HashMap, identifiers: HashMap, byte_array_pool: HashMap, address_pool: HashMap, // Current generic/type formal context - type_formals: TypeFormalMap, + type_parameters: TypeFormalMap, // The current function index that we are on current_function_index: FunctionDefinitionIndex, @@ -226,7 +226,7 @@ impl<'a> Context<'a> { identifiers: HashMap::new(), byte_array_pool: HashMap::new(), address_pool: HashMap::new(), - type_formals: HashMap::new(), + type_parameters: HashMap::new(), current_function_index: FunctionDefinitionIndex(0), source_map: ModuleSourceMap::new(current_module.clone()), }; @@ -277,8 +277,8 @@ impl<'a> Context<'a> { } /// Bind the type formals into a "pool" for the current context. - pub fn bind_type_formals(&mut self, m: HashMap) -> Result<()> { - self.type_formals = m + pub fn bind_type_parameters(&mut self, m: HashMap) -> Result<()> { + self.type_parameters = m .into_iter() .map(|(k, idx)| { if idx > TABLE_MAX_SIZE { @@ -328,8 +328,8 @@ impl<'a> Context<'a> { } /// Get the type formal index, fails if it is not bound. - pub fn type_formal_index(&mut self, t: &TypeVar_) -> Result { - match self.type_formals.get(&t) { + pub fn type_parameter_index(&mut self, t: &TypeVar_) -> Result { + match self.type_parameters.get(&t) { None => bail!("Unbound type parameter {}", t), Some(idx) => Ok(*idx), } @@ -389,11 +389,8 @@ impl<'a> Context<'a> { } /// Get the locals signature pool index, adds it if missing. - pub fn locals_signature_index( - &mut self, - locals: LocalsSignature, - ) -> Result { - Ok(LocalsSignatureIndex(get_or_add_item( + pub fn locals_signature_index(&mut self, locals: Signature) -> Result { + Ok(SignatureIndex(get_or_add_item( &mut self.locals_signatures, locals, )?)) @@ -440,7 +437,7 @@ impl<'a> Context<'a> { &mut self, sname: QualifiedStructIdent, is_nominal_resource: bool, - type_formals: Vec, + type_parameters: Vec, ) -> Result { let module = self.module_handle_index(&sname.module)?; let name = self.identifier_index(sname.name.as_inner())?; @@ -450,7 +447,7 @@ impl<'a> Context<'a> { module, name, is_nominal_resource, - type_formals, + type_parameters, }, ); Ok(StructHandleIndex(get_or_add_item_ref( @@ -552,7 +549,7 @@ impl<'a> Context<'a> { let dep = self.dependency(&mident)?; match dep.struct_handle(s) { None => bail!("Unbound struct {}", s), - Some(shandle) => Ok((shandle.is_nominal_resource, shandle.type_formals.clone())), + Some(shandle) => Ok((shandle.is_nominal_resource, shandle.type_parameters.clone())), } } @@ -563,8 +560,8 @@ impl<'a> Context<'a> { match self.structs.get(&s) { Some(sh) => Ok(StructHandleIndex(*self.struct_handles.get(sh).unwrap())), None => { - let (is_nominal_resource, type_formals) = self.dep_struct_handle(&s)?; - self.declare_struct_handle_index(s, is_nominal_resource, type_formals) + let (is_nominal_resource, type_parameters) = self.dep_struct_handle(&s)?; + self.declare_struct_handle_index(s, is_nominal_resource, type_parameters) } } } @@ -619,21 +616,21 @@ impl<'a> Context<'a> { dep: &QualifiedModuleIdent, orig: FunctionSignature, ) -> Result { - let return_types = orig - .return_types + let return_ = orig + .return_ .into_iter() .map(|t| self.reindex_signature_token(dep, t)) .collect::>()?; - let arg_types = orig - .arg_types + let parameters = orig + .parameters .into_iter() .map(|t| self.reindex_signature_token(dep, t)) .collect::>()?; - let type_formals = orig.type_formals; + let type_parameters = orig.type_parameters; Ok(FunctionSignature { - return_types, - arg_types, - type_formals, + return_, + parameters, + type_parameters, }) } diff --git a/language/compiler/ir-to-bytecode/syntax/src/lexer.rs b/language/compiler/ir-to-bytecode/syntax/src/lexer.rs index fe38bb2d7e0f..36f0c9ddb36b 100644 --- a/language/compiler/ir-to-bytecode/syntax/src/lexer.rs +++ b/language/compiler/ir-to-bytecode/syntax/src/lexer.rs @@ -103,7 +103,7 @@ pub enum Tok { U64, U128, Vector, - Unrestricted, + Copyable, While, LBrace, Pipe, @@ -455,7 +455,7 @@ fn get_name_token(name: &str) -> Tok { "u8" => Tok::U8, "u64" => Tok::U64, "u128" => Tok::U128, - "unrestricted" => Tok::Unrestricted, + "copyable" => Tok::Copyable, "while" => Tok::While, _ => Tok::NameValue, } diff --git a/language/compiler/ir-to-bytecode/syntax/src/syntax.rs b/language/compiler/ir-to-bytecode/syntax/src/syntax.rs index 17d583cce0ec..38bce46df799 100644 --- a/language/compiler/ir-to-bytecode/syntax/src/syntax.rs +++ b/language/compiler/ir-to-bytecode/syntax/src/syntax.rs @@ -1115,7 +1115,7 @@ fn parse_function_block_<'input>( // Kind: Kind = { // "resource" => Kind::Resource, -// "unrestricted" => Kind::Unrestricted, +// "copyable" => Kind::Copyable, // } fn parse_kind<'input>( @@ -1123,7 +1123,7 @@ fn parse_kind<'input>( ) -> Result> { let k = match tokens.peek() { Tok::Resource => Kind::Resource, - Tok::Unrestricted => Kind::Unrestricted, + Tok::Copyable => Kind::Copyable, _ => { return Err(ParseError::InvalidToken { location: tokens.start_loc(), @@ -1222,7 +1222,7 @@ fn parse_type_var<'input>( // > )?> =>? { // } -fn parse_type_formal<'input>( +fn parse_type_parameter<'input>( tokens: &mut Lexer<'input>, ) -> Result<(TypeVar, Kind), ParseError> { let type_var = parse_type_var(tokens)?; @@ -1258,7 +1258,7 @@ fn parse_type_actuals<'input>( // => (n, vec![]), // } -fn parse_name_and_type_formals<'input>( +fn parse_name_and_type_parameters<'input>( tokens: &mut Lexer<'input>, ) -> Result<(String, Vec<(TypeVar, Kind)>), ParseError> { let mut has_types = false; @@ -1269,7 +1269,7 @@ fn parse_name_and_type_formals<'input>( parse_name(tokens)? }; let k = if has_types { - let list = parse_comma_list(tokens, &[Tok::Greater], parse_type_formal, true)?; + let list = parse_comma_list(tokens, &[Tok::Greater], parse_type_parameter, true)?; consume_token(tokens, Tok::Greater)?; list } else { @@ -1694,14 +1694,14 @@ fn parse_synthetic_<'input>( // } // MoveFunctionDecl : (FunctionName, Function) = { -// "(" "(" ")" // // =>? { ... } // } // NativeFunctionDecl: (FunctionName, Function) = { -// +// // "(" > ")" // // ";" =>? { ... } @@ -1726,7 +1726,7 @@ fn parse_function_decl<'input>( false }; - let (name, type_formals) = parse_name_and_type_formals(tokens)?; + let (name, type_parameters) = parse_name_and_type_parameters(tokens)?; consume_token(tokens, Tok::LParen)?; let args = parse_comma_list(tokens, &[Tok::RParen], parse_arg_decl, true)?; consume_token(tokens, Tok::RParen)?; @@ -1761,7 +1761,7 @@ fn parse_function_decl<'input>( }, args, ret.unwrap_or_else(|| vec![]), - type_formals, + type_parameters, acquires.unwrap_or_else(Vec::new), specifications, if is_native { @@ -1886,10 +1886,10 @@ fn parse_script<'input>( // "resource" => true // } // StructDecl: StructDefinition_ = { -// "{" > "}" =>? { ... } // -// ";" =>? { ... } +// ";" =>? { ... } // } fn parse_struct_decl<'input>( @@ -1915,7 +1915,7 @@ fn parse_struct_decl<'input>( }; tokens.advance()?; - let (name, type_formals) = parse_name_and_type_formals(tokens)?; + let (name, type_parameters) = parse_name_and_type_parameters(tokens)?; if is_native { consume_token(tokens, Tok::Semicolon)?; @@ -1923,7 +1923,7 @@ fn parse_struct_decl<'input>( return Ok(spanned( start_loc, end_loc, - StructDefinition_::native(is_nominal_resource, name, type_formals)?, + StructDefinition_::native(is_nominal_resource, name, type_parameters)?, )); } @@ -1947,7 +1947,7 @@ fn parse_struct_decl<'input>( StructDefinition_::move_declared( is_nominal_resource, name, - type_formals, + type_parameters, fields, invariants, )?, diff --git a/language/compiler/src/ir_stdlib/modules/libra_account.mvir b/language/compiler/src/ir_stdlib/modules/libra_account.mvir index d5227df54d93..5312487263c7 100644 --- a/language/compiler/src/ir_stdlib/modules/libra_account.mvir +++ b/language/compiler/src/ir_stdlib/modules/libra_account.mvir @@ -74,7 +74,7 @@ module LibraAccount { // A handle for a event such that: // 1. Other modules can emit event to this handle. // 2. Storage can use this handle to prove the total number of events that happened in the past. - resource EventHandle { + resource EventHandle { // Total number of events emitted to this event stream. counter: u64, // A globally unique ID for this event stream. @@ -538,12 +538,12 @@ module LibraAccount { } // Use EventHandleGenerator to generate a unique event handle that one can emit an event to. - new_event_handle_impl(counter: &mut Self.EventHandleGenerator, sender: address): Self.EventHandle { + new_event_handle_impl(counter: &mut Self.EventHandleGenerator, sender: address): Self.EventHandle { return EventHandle {counter: 0, guid: Self.fresh_guid(move(counter), move(sender))}; } // Use sender's EventHandleGenerator to generate a unique event handle that one can emit an event to. - public new_event_handle(): Self.EventHandle acquires T { + public new_event_handle(): Self.EventHandle acquires T { let sender_account_ref: &mut Self.T; let sender_bytes: vector; sender_account_ref = borrow_global_mut(get_txn_sender()); @@ -552,7 +552,7 @@ module LibraAccount { // Emit an event with payload `msg` by using handle's key and counter. Will change the payload from vector to a // generic type parameter once we have generics. - public emit_event(handle_ref: &mut Self.EventHandle, msg: T) { + public emit_event(handle_ref: &mut Self.EventHandle, msg: T) { let count: &mut u64; let guid: vector; @@ -566,10 +566,10 @@ module LibraAccount { // Native procedure that writes to the actual event stream in Event store // This will replace the "native" portion of EmitEvent bytecode - native write_to_event_store(guid: vector, count: u64, msg: T); + native write_to_event_store(guid: vector, count: u64, msg: T); // Destroy a unique handle. - public destroy_handle(handle: Self.EventHandle) { + public destroy_handle(handle: Self.EventHandle) { let guid: vector; let count: u64; EventHandle { count, guid } = move(handle); diff --git a/language/compiler/src/ir_stdlib/modules/vector.mvir b/language/compiler/src/ir_stdlib/modules/vector.mvir index 71dd21c26ce4..30599b21f02c 100644 --- a/language/compiler/src/ir_stdlib/modules/vector.mvir +++ b/language/compiler/src/ir_stdlib/modules/vector.mvir @@ -1,4 +1,4 @@ -// A variable-sized container that can hold both unrestricted types and resources. +// A variable-sized container that can hold both copyable types and resources. module Vector { native public empty(): vector; diff --git a/language/e2e-tests/src/tests/scripts.rs b/language/e2e-tests/src/tests/scripts.rs index 2cd5c63e0027..e516c8640d98 100644 --- a/language/e2e-tests/src/tests/scripts.rs +++ b/language/e2e-tests/src/tests/scripts.rs @@ -9,7 +9,7 @@ use libra_types::{ }; use vm::file_format::{ empty_script, AddressPoolIndex, Bytecode, FunctionHandle, FunctionHandleIndex, - FunctionSignatureIndex, IdentifierIndex, LocalsSignatureIndex, ModuleHandle, ModuleHandleIndex, + FunctionSignatureIndex, IdentifierIndex, ModuleHandle, ModuleHandleIndex, SignatureIndex, }; #[test] @@ -85,7 +85,7 @@ fn script_non_existing_module_dep() { script.main.code.code = vec![ Bytecode::Call( FunctionHandleIndex((script.function_handles.len() - 1) as u16), - LocalsSignatureIndex(0), + SignatureIndex(0), ), Bytecode::Ret, ]; @@ -151,7 +151,7 @@ fn script_non_existing_function_dep() { script.main.code.code = vec![ Bytecode::Call( FunctionHandleIndex((script.function_handles.len() - 1) as u16), - LocalsSignatureIndex(0), + SignatureIndex(0), ), Bytecode::Ret, ]; @@ -219,7 +219,7 @@ fn script_bad_sig_function_dep() { script.main.code.code = vec![ Bytecode::Call( FunctionHandleIndex((script.function_handles.len() - 1) as u16), - LocalsSignatureIndex(0), + SignatureIndex(0), ), Bytecode::Ret, ]; diff --git a/language/e2e-tests/src/tests/verify_txn.rs b/language/e2e-tests/src/tests/verify_txn.rs index 2b4f867bd28c..8f6dee3b8b61 100644 --- a/language/e2e-tests/src/tests/verify_txn.rs +++ b/language/e2e-tests/src/tests/verify_txn.rs @@ -325,7 +325,7 @@ fn verify_simple_payment() { executor.execute_transaction(txn).status(), &TransactionStatus::Keep( VMStatus::new(StatusCode::TYPE_MISMATCH) - .with_message("Actual Type Mismatch".to_string()) + .with_message("Argument Type Mismatch".to_string()) ) ); @@ -341,7 +341,7 @@ fn verify_simple_payment() { executor.execute_transaction(txn).status(), &TransactionStatus::Keep( VMStatus::new(StatusCode::TYPE_MISMATCH) - .with_message("Actual Type Mismatch".to_string()) + .with_message("Argument Type Mismatch".to_string()) ) ); }); diff --git a/language/ir-testsuite/tests/generics/function_def.mvir b/language/ir-testsuite/tests/generics/function_def.mvir index bf5cd7768059..3e522512be50 100644 --- a/language/ir-testsuite/tests/generics/function_def.mvir +++ b/language/ir-testsuite/tests/generics/function_def.mvir @@ -7,7 +7,7 @@ module M { return move(x); } - public foo(x1: T4, x2: T3) { + public foo(x1: T4, x2: T3) { let x3: T2; let x4: T1; abort 0; diff --git a/language/ir-testsuite/tests/generics/gen_move_to.mvir b/language/ir-testsuite/tests/generics/gen_move_to.mvir index 5794188ca31c..aebfa6970e0f 100644 --- a/language/ir-testsuite/tests/generics/gen_move_to.mvir +++ b/language/ir-testsuite/tests/generics/gen_move_to.mvir @@ -8,7 +8,7 @@ module M { // a resource resource Value { val: u64 } - // a generic type either unrestricted or resource + // a generic type either copyable or resource struct Container { elem: T } // Functions @@ -19,8 +19,8 @@ module M { return Container{ elem: move(t) }; } - // change the elem of a `Container` if T is unrestricted - public change_container(c: &mut Self.Container, t: T) { + // change the elem of a `Container` if T is copyable + public change_container(c: &mut Self.Container, t: T) { *&mut move(c).elem = move(t); return; } @@ -112,7 +112,7 @@ module M { } // publish a `Some` under sender account - public change_some(val: T) acquires Some { + public change_some(val: T) acquires Some { let some: &mut Self.Some; some = borrow_global_mut>(get_txn_sender()); *(&mut move(some).v) = move(val); diff --git a/language/ir-testsuite/tests/generics/import_function.mvir b/language/ir-testsuite/tests/generics/import_function.mvir index 5f6cfc4e16b0..9f81e52a1cbb 100644 --- a/language/ir-testsuite/tests/generics/import_function.mvir +++ b/language/ir-testsuite/tests/generics/import_function.mvir @@ -5,7 +5,7 @@ module M { abort 0; } - public bar(x: T3, y: T2, z: T1) { + public bar(x: T3, y: T2, z: T1) { abort 0; } diff --git a/language/ir-testsuite/tests/generics/import_struct.mvir b/language/ir-testsuite/tests/generics/import_struct.mvir index 5ef904eb9058..4fbee79e6f84 100644 --- a/language/ir-testsuite/tests/generics/import_struct.mvir +++ b/language/ir-testsuite/tests/generics/import_struct.mvir @@ -1,7 +1,7 @@ module M { resource Foo { x: T } - struct Bar { x: T3, y: T2, z: T1 } + struct Bar { x: T3, y: T2, z: T1 } } //! new-transaction diff --git a/language/ir-testsuite/tests/generics/option.mvir b/language/ir-testsuite/tests/generics/option.mvir index c4454507544c..48f297573d7b 100644 --- a/language/ir-testsuite/tests/generics/option.mvir +++ b/language/ir-testsuite/tests/generics/option.mvir @@ -16,7 +16,7 @@ module Option { return T { v: move(v) }; } - public unwrap_or(x: Self.T, e: E): E { + public unwrap_or(x: Self.T, e: E): E { let v: vector; T { v: v } = move(x); if (Vector.is_empty(&v)) { @@ -25,7 +25,7 @@ module Option { return Vector.pop_back(&mut v); } - public really_none(): Self.T { + public really_none(): Self.T { return Self.unwrap_or>(Self.none>(), Self.none()); } } diff --git a/language/ir-testsuite/tests/generics/resource_safety/borrow_global_mut.mvir b/language/ir-testsuite/tests/generics/resource_safety/borrow_global_mut.mvir index 3ea70255f191..d77f11d1fcc0 100644 --- a/language/ir-testsuite/tests/generics/resource_safety/borrow_global_mut.mvir +++ b/language/ir-testsuite/tests/generics/resource_safety/borrow_global_mut.mvir @@ -1,5 +1,5 @@ module M { - struct Foo { x: T } + struct Foo { x: T } f(): u64 acquires Foo { let foo_ref: &mut Self.Foo; diff --git a/language/ir-testsuite/tests/generics/signatures/all_as_unrestricted.mvir b/language/ir-testsuite/tests/generics/signatures/all_as_unrestricted.mvir index dbfb49a97e87..2cc2248b2006 100644 --- a/language/ir-testsuite/tests/generics/signatures/all_as_unrestricted.mvir +++ b/language/ir-testsuite/tests/generics/signatures/all_as_unrestricted.mvir @@ -1,5 +1,5 @@ module M { - struct S { b: bool } + struct S { b: bool } foo() { let x: Self.S; diff --git a/language/ir-testsuite/tests/generics/signatures/resource_as_unrestricted.mvir b/language/ir-testsuite/tests/generics/signatures/resource_as_unrestricted.mvir index 9c3a0f1de941..3e5f63f2c0ad 100644 --- a/language/ir-testsuite/tests/generics/signatures/resource_as_unrestricted.mvir +++ b/language/ir-testsuite/tests/generics/signatures/resource_as_unrestricted.mvir @@ -1,5 +1,5 @@ module M { - struct S { b: bool } + struct S { b: bool } resource R { b: bool } foo() { diff --git a/language/ir-testsuite/tests/generics/signatures/too_few_type_actuals.mvir b/language/ir-testsuite/tests/generics/signatures/too_few_type_actuals.mvir index ffb9a4573f07..d69da18869da 100644 --- a/language/ir-testsuite/tests/generics/signatures/too_few_type_actuals.mvir +++ b/language/ir-testsuite/tests/generics/signatures/too_few_type_actuals.mvir @@ -7,4 +7,4 @@ module M { } } -// check: NUMBER_OF_TYPE_ACTUALS_MISMATCH +// check: NUMBER_OF_TYPE_ARGUMENTS_MISMATCH diff --git a/language/ir-testsuite/tests/generics/signatures/too_many_type_actuals.mvir b/language/ir-testsuite/tests/generics/signatures/too_many_type_actuals.mvir index e3533d0366e4..a428a5c0d999 100644 --- a/language/ir-testsuite/tests/generics/signatures/too_many_type_actuals.mvir +++ b/language/ir-testsuite/tests/generics/signatures/too_many_type_actuals.mvir @@ -7,4 +7,4 @@ module M { } } -// check: NUMBER_OF_TYPE_ACTUALS_MISMATCH +// check: NUMBER_OF_TYPE_ARGUMENTS_MISMATCH diff --git a/language/ir-testsuite/tests/generics/signatures/two_type_actuals_ok.mvir b/language/ir-testsuite/tests/generics/signatures/two_type_actuals_ok.mvir index 9c91a55861f7..74b5e51c1093 100644 --- a/language/ir-testsuite/tests/generics/signatures/two_type_actuals_ok.mvir +++ b/language/ir-testsuite/tests/generics/signatures/two_type_actuals_ok.mvir @@ -1,6 +1,6 @@ module M { resource R { b: bool} - struct S { b: bool } + struct S { b: bool } foo() { let x: Self.S; diff --git a/language/ir-testsuite/tests/generics/signatures/two_type_actuals_reverse_order.mvir b/language/ir-testsuite/tests/generics/signatures/two_type_actuals_reverse_order.mvir index 4bfc5205f8c8..43417a950e72 100644 --- a/language/ir-testsuite/tests/generics/signatures/two_type_actuals_reverse_order.mvir +++ b/language/ir-testsuite/tests/generics/signatures/two_type_actuals_reverse_order.mvir @@ -1,6 +1,6 @@ module M { resource R { b: bool } - struct S { b: bool } + struct S { b: bool } foo() { let x: Self.S; diff --git a/language/ir-testsuite/tests/generics/struct_def.mvir b/language/ir-testsuite/tests/generics/struct_def.mvir index cdfc4362867e..ad8a82819ec0 100644 --- a/language/ir-testsuite/tests/generics/struct_def.mvir +++ b/language/ir-testsuite/tests/generics/struct_def.mvir @@ -4,5 +4,5 @@ module M { struct Foo { x: T } - struct Bar { x1: T2, x2: T3, x3: T4, x4: T1 } + struct Bar { x1: T2, x2: T3, x3: T4, x4: T1 } } diff --git a/language/ir-testsuite/tests/generics/unpack.mvir b/language/ir-testsuite/tests/generics/unpack.mvir index 7b09cc4dbc52..e4caa940ce4c 100644 --- a/language/ir-testsuite/tests/generics/unpack.mvir +++ b/language/ir-testsuite/tests/generics/unpack.mvir @@ -11,7 +11,7 @@ module M { //! new-transaction module N { - resource Foo { x: T1, y: T2 } + resource Foo { x: T1, y: T2 } foo() { let x: u64; diff --git a/language/ir-testsuite/tests/natives/event_emit_struct_with_type_params.mvir b/language/ir-testsuite/tests/natives/event_emit_struct_with_type_params.mvir index c535f68792a9..cd34cb3bfff5 100644 --- a/language/ir-testsuite/tests/natives/event_emit_struct_with_type_params.mvir +++ b/language/ir-testsuite/tests/natives/event_emit_struct_with_type_params.mvir @@ -3,7 +3,7 @@ module M { struct MyEvent { b: bool } - public emit_event() { + public emit_event() { let handle: LibraAccount.EventHandle>; handle = LibraAccount.new_event_handle>(); LibraAccount.emit_event>(&mut handle, MyEvent{ b: true }); diff --git a/language/move-ir/types/src/ast.rs b/language/move-ir/types/src/ast.rs index 0c56b2964edd..8aea90421aba 100644 --- a/language/move-ir/types/src/ast.rs +++ b/language/move-ir/types/src/ast.rs @@ -155,8 +155,8 @@ pub enum Kind { All, /// `Resource` types must follow move semantics and various resource safety rules. Resource, - /// `Unrestricted` types do not need to follow the `Resource` rules. - Unrestricted, + /// `Copyable` types do not need to follow the `Resource` rules. + Copyable, } //************************************************************************************************** @@ -225,7 +225,7 @@ pub struct StructDefinition_ { /// Human-readable name for the struct that also serves as a nominal type pub name: StructName, /// Kind constraints of the type parameters - pub type_formals: Vec<(TypeVar, Kind)>, + pub type_parameters: Vec<(TypeVar, Kind)>, /// the fields each instance has pub fields: StructDefinitionFields, /// the invariants for this struct @@ -260,7 +260,7 @@ pub struct FunctionSignature { /// Optional return types pub return_type: Vec, /// Possibly-empty list of (TypeVar, Kind) pairs.s. - pub type_formals: Vec<(TypeVar, Kind)>, + pub type_parameters: Vec<(TypeVar, Kind)>, } /// Public or internal modifier for a procedure @@ -787,14 +787,14 @@ impl StructDefinition_ { pub fn move_declared( is_nominal_resource: bool, name: impl Into>, - type_formals: Vec<(TypeVar, Kind)>, + type_parameters: Vec<(TypeVar, Kind)>, fields: Fields, invariants: Vec, ) -> Result { Ok(StructDefinition_ { is_nominal_resource, name: StructName::parse(name)?, - type_formals, + type_parameters, fields: StructDefinitionFields::Move { fields }, invariants, }) @@ -806,12 +806,12 @@ impl StructDefinition_ { pub fn native( is_nominal_resource: bool, name: impl Into>, - type_formals: Vec<(TypeVar, Kind)>, + type_parameters: Vec<(TypeVar, Kind)>, ) -> Result { Ok(StructDefinition_ { is_nominal_resource, name: StructName::parse(name)?, - type_formals, + type_parameters, fields: StructDefinitionFields::Native, invariants: vec![], }) @@ -845,12 +845,12 @@ impl FunctionSignature { pub fn new( formals: Vec<(Var, Type)>, return_type: Vec, - type_formals: Vec<(TypeVar, Kind)>, + type_parameters: Vec<(TypeVar, Kind)>, ) -> Self { FunctionSignature { formals, return_type, - type_formals, + type_parameters, } } } @@ -862,12 +862,12 @@ impl Function_ { visibility: FunctionVisibility, formals: Vec<(Var, Type)>, return_type: Vec, - type_formals: Vec<(TypeVar, Kind)>, + type_parameters: Vec<(TypeVar, Kind)>, acquires: Vec, specifications: Vec, body: FunctionBody, ) -> Self { - let signature = FunctionSignature::new(formals, return_type, type_formals); + let signature = FunctionSignature::new(formals, return_type, type_parameters); Function_ { visibility, signature, @@ -1161,7 +1161,7 @@ impl fmt::Display for Kind { match self { Kind::All => "all", Kind::Resource => "resource", - Kind::Unrestricted => "unrestricted", + Kind::Copyable => "copyable", } ) } @@ -1235,7 +1235,7 @@ impl fmt::Display for StructDefinition_ { f, "Struct({}{}, ", self.name, - format_type_formals(&self.type_formals) + format_type_parameters(&self.type_parameters) )?; match &self.fields { StructDefinitionFields::Move { fields } => writeln!(f, "{}", format_fields(fields))?, @@ -1296,7 +1296,7 @@ fn format_fields(fields: &[(Field, T)]) -> String { impl fmt::Display for FunctionSignature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", format_type_formals(&self.type_formals))?; + write!(f, "{}", format_type_parameters(&self.type_parameters))?; write!(f, "(")?; for (v, ty) in self.formals.iter() { write!(f, "{}: {}, ", v, ty)?; @@ -1320,7 +1320,7 @@ fn format_type_actuals(tys: &[Type]) -> String { } } -fn format_type_formals(formals: &[(TypeVar, Kind)]) -> String { +fn format_type_parameters(formals: &[(TypeVar, Kind)]) -> String { if formals.is_empty() { "".to_string() } else { diff --git a/language/move-lang/src/cfgir/ast.rs b/language/move-lang/src/cfgir/ast.rs index 6997dbed12f1..9fc3d94b83c2 100644 --- a/language/move-lang/src/cfgir/ast.rs +++ b/language/move-lang/src/cfgir/ast.rs @@ -302,7 +302,7 @@ impl BaseType_ { use BuiltinTypeName_::*; let kind = match b_ { - U8 | U64 | U128 | Bool | Address | Bytearray => sp(loc, Kind_::Unrestricted), + U8 | U64 | U128 | Bool | Address | Bytearray => sp(loc, Kind_::Copyable), Vector => { assert!( ty_args.len() == 1, @@ -358,7 +358,7 @@ impl SingleType_ { pub fn kind(&self, loc: Loc) -> Kind { match self { - SingleType_::Ref(_, _) => sp(loc, Kind_::Unrestricted), + SingleType_::Ref(_, _) => sp(loc, Kind_::Copyable), SingleType_::Base(b) => b.value.kind(), } } diff --git a/language/move-lang/src/hlir/ast.rs b/language/move-lang/src/hlir/ast.rs index 42845708d6b9..5b4e239171d1 100644 --- a/language/move-lang/src/hlir/ast.rs +++ b/language/move-lang/src/hlir/ast.rs @@ -238,7 +238,7 @@ impl BaseType_ { use BuiltinTypeName_::*; let kind = match b_ { - U8 | U64 | U128 | Bool | Address | Bytearray => sp(loc, Kind_::Unrestricted), + U8 | U64 | U128 | Bool | Address | Bytearray => sp(loc, Kind_::Copyable), Vector => { assert!( ty_args.len() == 1, diff --git a/language/move-lang/src/ir_translation.rs b/language/move-lang/src/ir_translation.rs index 1ecdd2123169..43d0c7b9e985 100644 --- a/language/move-lang/src/ir_translation.rs +++ b/language/move-lang/src/ir_translation.rs @@ -28,8 +28,8 @@ pub fn fix_syntax_and_write(out_path: &Path, contents: String) { let contents = replace!(contents, r"copy\((\w+)\)", "copy $1"); // resource StructName ~> resource struct StructName let contents = replace!(contents, r"resource\s+(\w)", "resource struct $1"); - // unrestricted ~> copyable - let contents = replace!(contents, r":\s*unrestricted", NoExpand(": copyable")); + // copyable ~> copyable + let contents = replace!(contents, r":\s*copyable", NoExpand(": copyable")); // import ~> use let contents = replace!(contents, r"import", NoExpand("use")); // Self. is unnecessary diff --git a/language/move-lang/src/naming/ast.rs b/language/move-lang/src/naming/ast.rs index fd8df9d15481..3a3ddf360d59 100644 --- a/language/move-lang/src/naming/ast.rs +++ b/language/move-lang/src/naming/ast.rs @@ -382,7 +382,7 @@ impl BaseType_ { use BuiltinTypeName_::*; let kind = match b_ { - U8 | U64 | U128 | Address | Bool | Bytearray => Some(sp(loc, Kind_::Unrestricted)), + U8 | U64 | U128 | Address | Bool | Bytearray => Some(sp(loc, Kind_::Copyable)), Vector => None, }; let n = sp(loc, TypeName_::Builtin(sp(loc, b_))); @@ -708,7 +708,7 @@ impl AstDebug for TParam { Kind_::Unknown => (), Kind_::Resource => w.write(": resource"), Kind_::Affine => w.write(": copyable"), - Kind_::Unrestricted => panic!("ICE 'unrestricted' kind constraint"), + Kind_::Copyable => panic!("ICE 'copyable' kind constraint"), } } } diff --git a/language/move-lang/src/parser/ast.rs b/language/move-lang/src/parser/ast.rs index e0e2c8fd210c..119bde043ebe 100644 --- a/language/move-lang/src/parser/ast.rs +++ b/language/move-lang/src/parser/ast.rs @@ -245,7 +245,7 @@ pub enum Kind_ { // Explicitly copyable types Affine, // Implicitly copyable types - Unrestricted, + Copyable, } pub type Kind = Spanned; @@ -516,7 +516,7 @@ impl Kind_ { pub fn is_resourceful(&self) -> bool { match self { - Kind_::Affine | Kind_::Unrestricted => false, + Kind_::Affine | Kind_::Copyable => false, Kind_::Resource | Kind_::Unknown => true, } } @@ -910,7 +910,7 @@ impl AstDebug for (Name, Kind) { w.write(": "); k.ast_debug(w) } - Kind_::Unrestricted => panic!("ICE 'unrestricted' kind constraint"), + Kind_::Copyable => panic!("ICE 'copyable' kind constraint"), } } } @@ -921,7 +921,7 @@ impl AstDebug for Kind_ { Kind_::Unknown => "unknown", Kind_::Resource => "resource", Kind_::Affine => "copyable", - Kind_::Unrestricted => "unrestricted", + Kind_::Copyable => "copyable", }) } } diff --git a/language/move-lang/src/to_bytecode/context.rs b/language/move-lang/src/to_bytecode/context.rs index b25d6f520c67..c9fdf38c1ba2 100644 --- a/language/move-lang/src/to_bytecode/context.rs +++ b/language/move-lang/src/to_bytecode/context.rs @@ -14,10 +14,9 @@ use libra_types::{ }; use move_vm::file_format::{ self as F, AddressPoolIndex, ByteArrayPoolIndex, FieldDefinitionIndex, FunctionHandle, - FunctionHandleIndex, FunctionSignature, FunctionSignatureIndex, IdentifierIndex, - LocalsSignature, LocalsSignatureIndex, ModuleHandle, ModuleHandleIndex, SignatureToken, - StructDefinitionIndex, StructHandle, StructHandleIndex, TableIndex, TypeSignature, - TypeSignatureIndex, + FunctionHandleIndex, FunctionSignature, FunctionSignatureIndex, IdentifierIndex, ModuleHandle, + ModuleHandleIndex, Signature, SignatureIndex, SignatureToken, StructDefinitionIndex, + StructHandle, StructHandleIndex, TableIndex, TypeSignature, TypeSignatureIndex, }; use std::{clone::Clone, collections::HashMap, hash::Hash}; @@ -78,7 +77,7 @@ pub struct MaterializedPools { /// Function signature pool pub function_signatures: Vec, /// Locals signatures pool - pub locals_signatures: Vec, + pub locals_signatures: Vec, /// Identifier pool pub identifiers: Vec, /// Byte array pool @@ -110,7 +109,7 @@ pub struct Context<'a> { struct_handles: HashMap, function_handles: HashMap, type_signatures: HashMap, - locals_signatures: HashMap, + locals_signatures: HashMap, identifiers: HashMap, byte_array_pool: HashMap, TableIndex>, address_pool: HashMap, @@ -233,7 +232,7 @@ impl<'a> Context<'a> { } /// Get the type formal index, fails if it is not bound. - pub fn type_formal_index(&mut self, t: TParamID) -> TableIndex { + pub fn type_parameter_index(&mut self, t: TParamID) -> TableIndex { match self.type_parameters.get(&t) { None => panic!("Unbound type parameter"), Some(idx) => *idx, @@ -303,9 +302,9 @@ impl<'a> Context<'a> { pub fn locals_signature_index( &mut self, loc: Loc, - locals: LocalsSignature, - ) -> Result { - Ok(LocalsSignatureIndex(get_or_add_item( + locals: Signature, + ) -> Result { + Ok(SignatureIndex(get_or_add_item( loc, &mut self.locals_signatures, locals, @@ -413,7 +412,7 @@ impl<'a> Context<'a> { mname: &ModuleIdent, sname: &StructName, is_nominal_resource: bool, - type_formals: Vec, + type_parameters: Vec, ) -> Result { let module = self.module_handle_index(mname)?; let name = self.identifier_index(sname)?; @@ -426,7 +425,7 @@ impl<'a> Context<'a> { module, name, is_nominal_resource, - type_formals, + type_parameters, }, ) .is_none()); diff --git a/language/move-lang/src/to_bytecode/translate.rs b/language/move-lang/src/to_bytecode/translate.rs index 033dceb5ac71..f0aebd6cf880 100644 --- a/language/move-lang/src/to_bytecode/translate.rs +++ b/language/move-lang/src/to_bytecode/translate.rs @@ -269,6 +269,10 @@ fn module( module_handles, struct_handles, function_handles, + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -317,6 +321,8 @@ fn main( module_handles, struct_handles, function_handles, + struct_instantiations: vec![], + function_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -469,17 +475,17 @@ fn function_signature( context: &mut Context, sig: G::FunctionSignature, ) -> Result { - let return_types = types(context, sig.return_type)?; - let arg_types = sig + let return_ = types(context, sig.return_type)?; + let parameters = sig .parameters .into_iter() .map(|(_, st)| single_type(context, st)) .collect::>()?; - let type_formals = kinds(sig.type_parameters.iter().map(|tp| &tp.kind)); + let type_parameters = kinds(sig.type_parameters.iter().map(|tp| &tp.kind)); Ok(F::FunctionSignature { - return_types, - arg_types, - type_formals, + return_, + parameters, + type_parameters, }) } @@ -503,7 +509,7 @@ fn function_body( let (local_vars, local_types): (Vec<_>, Vec<_>) = parameters.into_iter().unzip(); let mut ff = FunctionFrame::new(loc, local_vars.into_iter())?; - let locals_signature = F::LocalsSignature( + let locals_signature = F::Signature( local_types .into_iter() .map(|st| single_type(context, st)) @@ -553,7 +559,7 @@ fn kind(sp!(_, k_): &Kind) -> F::Kind { match k_ { GK::Unknown => FK::All, GK::Resource => FK::Resource, - GK::Affine | GK::Unrestricted => FK::Unrestricted, + GK::Affine | GK::Copyable => FK::Copyable, } } @@ -572,14 +578,14 @@ fn bind_type_parameters( fn struct_definition_indices_base( context: &mut Context, sp!(loc, b_): G::BaseType, -) -> Result<(F::StructDefinitionIndex, F::LocalsSignatureIndex)> { +) -> Result<(F::StructDefinitionIndex, F::SignatureIndex)> { use TypeName_ as TN; use G::BaseType_ as B; match b_ { B::Apply(_, sp!(_, TN::ModuleType(m, s)), tys) => { assert!(context.module_handle_index(&m).unwrap().0 == 0); let def_idx = context.struct_definition_index(&s); - let local_sig = F::LocalsSignature(base_types(context, tys)?); + let local_sig = F::Signature(base_types(context, tys)?); let tys_idx = context.locals_signature_index(loc, local_sig)?; Ok((def_idx, tys_idx)) } @@ -653,7 +659,7 @@ fn base_type(context: &mut Context, sp!(_, bt_): G::BaseType) -> Result ST::TypeParameter(context.type_formal_index(id)), + B::Param(TParam { id, .. }) => ST::TypeParameter(context.type_parameter_index(id)), }) } @@ -787,7 +793,7 @@ fn lvalue( // empty structs have a dummy field of type 'bool' added let def_idx = context.struct_definition_index(&s); - let local_sig = F::LocalsSignature(base_types(context, tys)?); + let local_sig = F::Signature(base_types(context, tys)?); let local_idx = context.locals_signature_index(loc, local_sig)?; function_frame.pop(); @@ -800,7 +806,7 @@ fn lvalue( L::Unpack(s, tys, field_ls) => { let def_idx = context.struct_definition_index(&s); - let local_sig = F::LocalsSignature(base_types(context, tys)?); + let local_sig = F::Signature(base_types(context, tys)?); let local_idx = context.locals_signature_index(loc, local_sig)?; function_frame.pop(); @@ -941,7 +947,7 @@ fn exp_( // empty structs have a dummy field of type 'bool' added let def_idx = context.struct_definition_index(&s); - let local_sig = F::LocalsSignature(base_types(context, tys)?); + let local_sig = F::Signature(base_types(context, tys)?); let local_idx = context.locals_signature_index(eloc, local_sig)?; // Push on fake field @@ -959,7 +965,7 @@ fn exp_( exp_(context, function_frame, code, earg)?; } let def_idx = context.struct_definition_index(&s); - let local_sig = F::LocalsSignature(base_types(context, tys)?); + let local_sig = F::Signature(base_types(context, tys)?); let local_idx = context.locals_signature_index(eloc, local_sig)?; function_frame.popn(num_args); @@ -1065,7 +1071,7 @@ fn module_call( context.declare_function(m, f, sig)? } }; - let tokens = F::LocalsSignature(base_types(context, tys)?); + let tokens = F::Signature(base_types(context, tys)?); let type_actuals_id = context.locals_signature_index(loc, tokens)?; code.push(B::Call(function_handle_index, type_actuals_id)); Ok(()) diff --git a/language/move-lang/src/typing/core.rs b/language/move-lang/src/typing/core.rs index 6bb18bf2f625..acd390c75b68 100644 --- a/language/move-lang/src/typing/core.rs +++ b/language/move-lang/src/typing/core.rs @@ -365,7 +365,7 @@ pub fn error_format(sp!(_, t_): &Type, subst: &Subst) -> String { pub fn infer_kind(context: &Context, subst: &Subst, s: SingleType) -> Option { use SingleType_ as S; match s.value { - S::Ref(_, _) => Some(sp(s.loc, Kind_::Unrestricted)), + S::Ref(_, _) => Some(sp(s.loc, Kind_::Copyable)), S::Base(b) => infer_kind_base(context, subst, b), } } @@ -399,7 +399,7 @@ pub fn infer_kind_base(context: &Context, subst: &Subst, b: BaseType) -> Option< infer_kind_base(context, subst, t).or(constraint_opt) }) .map(|k| match k { - sp!(loc, Kind_::Unrestricted) => sp(loc, Kind_::Affine), + sp!(loc, Kind_::Copyable) => sp(loc, Kind_::Affine), k => k, }) .max_by(most_general_kind) @@ -413,7 +413,7 @@ fn most_general_kind(k1: &Kind, k2: &Kind) -> std::cmp::Ordering { use std::cmp::Ordering as O; use Kind_ as K; match (&k1.value, &k2.value) { - (K::Unrestricted, _) | (_, K::Unrestricted) => panic!("ICE structs cannot be unrestricted"), + (K::Copyable, _) | (_, K::Copyable) => panic!("ICE structs cannot be copyable"), (K::Unknown, K::Unknown) => O::Equal, (K::Unknown, _) => O::Greater, @@ -658,21 +658,21 @@ fn solve_kind_constraint(context: &mut Context, loc: Loc, b: BaseType, k: Kind) Some(k) => k, }; match (b_kind.value, &k.value) { - (_, K::Unrestricted) => panic!("ICE tparams cannot have unrestricted constraints"), + (_, K::Copyable) => panic!("ICE tparams cannot have copyable constraints"), // _ <: all - // unrestricted <: affine + // copyable <: affine // affine <: affine // linear <: linear (_, K::Unknown) - | (K::Unrestricted, K::Affine) + | (K::Copyable, K::Affine) | (K::Affine, K::Affine) | (K::Resource, K::Resource) => (), - // unrestricted { + (K::Copyable, K::Resource) | (K::Affine, K::Resource) | (K::Unknown, K::Resource) => { let ty_str = error_format_base(&b, &context.subst); let cmsg = format!( "The {} type {} does not satisfy the constraint '{}'", @@ -698,7 +698,7 @@ fn solve_kind_constraint(context: &mut Context, loc: Loc, b: BaseType, k: Kind) // linear { let resource_msg = match bk { - K::Unrestricted | K::Affine => panic!("ICE covered above"), + K::Copyable | K::Affine => panic!("ICE covered above"), K::Resource => "resource ", K::Unknown => "", }; @@ -735,7 +735,7 @@ fn solve_copyable_constraint(context: &mut Context, loc: Loc, msg: String, s: Si Some(k) => k, }; match kind { - sp!(_, Kind_::Unrestricted) | sp!(_, Kind_::Affine) => (), + sp!(_, Kind_::Copyable) | sp!(_, Kind_::Affine) => (), sp!(rloc, Kind_::Unknown) | sp!(rloc, Kind_::Resource) => { let ty_str = error_format_single(&s, &context.subst); context.error(vec![ @@ -763,7 +763,7 @@ fn solve_implicitly_copyable_constraint( Some(k) => k, }; match kind { - sp!(_, Kind_::Unrestricted) => (), + sp!(_, Kind_::Copyable) => (), sp!(kloc, Kind_::Affine) => { let ty_str = error_format_base(&b, &context.subst); context.error(vec![ diff --git a/language/move-lang/src/typing/expand.rs b/language/move-lang/src/typing/expand.rs index f3c433cbf3b3..d0c6e2752594 100644 --- a/language/move-lang/src/typing/expand.rs +++ b/language/move-lang/src/typing/expand.rs @@ -133,7 +133,7 @@ pub fn base_type(context: &mut Context, bt: &mut BaseType) -> bool { fn get_kind(s: &SingleType) -> Kind { use SingleType_ as S; match &s.value { - S::Ref(_, _) => sp(s.loc, Kind_::Unrestricted), + S::Ref(_, _) => sp(s.loc, Kind_::Copyable), S::Base(b) => get_kind_base(b), } } @@ -142,7 +142,7 @@ fn get_kind_base(b: &BaseType) -> Kind { use BaseType_ as B; match b { sp!(_, B::Var(_)) => panic!("ICE unexpanded type"), - sp!(loc, B::Anything) => sp(*loc, Kind_::Unrestricted), + sp!(loc, B::Anything) => sp(*loc, Kind_::Copyable), sp!(_, B::Param(TParam { kind, .. })) => kind.clone(), sp!(_, B::Apply(Some(kind), _, _)) => kind.clone(), sp!(_, B::Apply(None, _, _)) => panic!("ICE unexpanded type"), @@ -198,7 +198,7 @@ fn exp(context: &mut Context, e: &mut T::Exp) { let from_user = false; let var = v.clone(); e.exp.value = match get_kind(st).value { - Kind_::Unrestricted => E::Copy { from_user, var }, + Kind_::Copyable => E::Copy { from_user, var }, Kind_::Unknown | Kind_::Affine | Kind_::Resource => E::Move { from_user, var }, } } diff --git a/language/move-prover/bytecode-to-boogie/src/boogie_wrapper.rs b/language/move-prover/bytecode-to-boogie/src/boogie_wrapper.rs index 07b04f9e3cc4..8d4cb2b75cab 100644 --- a/language/move-prover/bytecode-to-boogie/src/boogie_wrapper.rs +++ b/language/move-prover/bytecode-to-boogie/src/boogie_wrapper.rs @@ -405,7 +405,7 @@ impl<'env> BoogieWrapper<'env> { if idx < n { func_env.get_local_type(idx) } else { - func_env.get_return_types()[idx - n].clone() + func_env.get_return_()[idx - n].clone() } } diff --git a/language/move-prover/bytecode-to-boogie/src/bytecode_translator.rs b/language/move-prover/bytecode-to-boogie/src/bytecode_translator.rs index 07e63b595e4d..05cbd9967604 100644 --- a/language/move-prover/bytecode-to-boogie/src/bytecode_translator.rs +++ b/language/move-prover/bytecode-to-boogie/src/bytecode_translator.rs @@ -1093,7 +1093,7 @@ impl<'env> ModuleTranslator<'env> { ) .join(", "); let rets = func_env - .get_return_types() + .get_return_() .iter() .enumerate() .map(|(i, ref s)| format!("__ret{}: {}", i, boogie_local_type(s))) @@ -1319,7 +1319,7 @@ impl<'env> ModuleTranslator<'env> { self.writer.indent(); emitln!(self.writer, "__abort_flag := true;"); emitln!(self.writer, "__m := __saved_m;"); - for (i, sig) in func_env.get_return_types().iter().enumerate() { + for (i, sig) in func_env.get_return_().iter().enumerate() { let ret_str = format!("__ret{}", i); if sig.is_reference() { emitln!(self.writer, "{} := DefaultReference;", &ret_str); @@ -1389,7 +1389,7 @@ impl<'env> ModuleTranslator<'env> { let sig = if idx < func_env.get_local_count() { func_env.get_local_type(idx) } else { - func_env.get_return_types()[idx - func_env.get_local_count()].clone() + func_env.get_return_()[idx - func_env.get_local_count()].clone() }; if let GlobalType::Reference(bt) | GlobalType::MutableReference(bt) = sig { let deref = format!("Dereference(__m, {})", value); diff --git a/language/move-prover/bytecode-to-boogie/src/driver.rs b/language/move-prover/bytecode-to-boogie/src/driver.rs index 9f6ed53deac0..f9a64fe02055 100644 --- a/language/move-prover/bytecode-to-boogie/src/driver.rs +++ b/language/move-prover/bytecode-to-boogie/src/driver.rs @@ -173,7 +173,7 @@ impl Driver { let type_arg_names = def .value .signature - .type_formals + .type_parameters .iter() .map(|(v, _)| v.value.name().into()) .collect(); diff --git a/language/move-prover/bytecode-to-boogie/src/env.rs b/language/move-prover/bytecode-to-boogie/src/env.rs index b8dd347f84d8..d189bc636b5a 100644 --- a/language/move-prover/bytecode-to-boogie/src/env.rs +++ b/language/move-prover/bytecode-to-boogie/src/env.rs @@ -23,7 +23,7 @@ use vm::{ access::ModuleAccess, file_format::{ AddressPoolIndex, FieldDefinitionIndex, FunctionDefinitionIndex, FunctionHandleIndex, Kind, - LocalsSignatureIndex, SignatureToken, StructDefinitionIndex, StructFieldInformation, + SignatureIndex, SignatureToken, StructDefinitionIndex, StructFieldInformation, StructHandleIndex, TypeParameterIndex, }, views::{ @@ -611,7 +611,7 @@ impl<'env> ModuleEnv<'env> { } /// Gets a list of type actuals associated with the index in the bytecode. - pub fn get_type_actuals(&self, idx: LocalsSignatureIndex) -> Vec { + pub fn get_type_actuals(&self, idx: SignatureIndex) -> Vec { let actuals = &self.data.module.locals_signature_at(idx).0; self.globalize_signatures(actuals) } @@ -880,7 +880,7 @@ impl<'env> StructEnv<'env> { &self.module_env.data.module, self.module_env.data.module.struct_def_at(self.data.def_idx), ); - view.type_formals() + view.type_parameters() .iter() .enumerate() .map(|(i, k)| TypeParameter(new_identifier(&format!("tv{}", i)), *k)) @@ -1062,7 +1062,7 @@ impl<'env> FunctionEnv<'env> { // parameter names, so use indices instead. let view = self.definition_view(); view.signature() - .type_formals() + .type_parameters() .iter() .enumerate() .map(|(i, k)| TypeParameter(new_identifier(&format!("tv{}", i)), *k)) @@ -1083,7 +1083,7 @@ impl<'env> FunctionEnv<'env> { } /// Returns return types of this function. - pub fn get_return_types(&self) -> Vec { + pub fn get_return_(&self) -> Vec { let view = self.definition_view(); view.signature() .return_tokens() diff --git a/language/move-prover/bytecode-to-boogie/src/spec_translator.rs b/language/move-prover/bytecode-to-boogie/src/spec_translator.rs index 0c05234512e6..3072c09e9840 100644 --- a/language/move-prover/bytecode-to-boogie/src/spec_translator.rs +++ b/language/move-prover/bytecode-to-boogie/src/spec_translator.rs @@ -178,7 +178,7 @@ impl<'env> SpecTranslator<'env> { BoogieExpr(param.0.to_string(), param.1.clone()), ); } - for (i, ty) in func_env.get_return_types().iter().enumerate() { + for (i, ty) in func_env.get_return_().iter().enumerate() { let name = &format!("__ret{}", i); self.define_symbol(name, false, BoogieExpr(name.clone(), ty.clone())); } diff --git a/language/move-prover/bytecode-to-boogie/test_mvir/test-generics.mvir b/language/move-prover/bytecode-to-boogie/test_mvir/test-generics.mvir index cc9eb28750c3..7fc685eb6a91 100644 --- a/language/move-prover/bytecode-to-boogie/test_mvir/test-generics.mvir +++ b/language/move-prover/bytecode-to-boogie/test_mvir/test-generics.mvir @@ -5,7 +5,7 @@ module TestGenerics { v: vector } - struct T { + struct T { v: vector } @@ -20,14 +20,14 @@ module TestGenerics { return; } - public create(x: E): Self.T { + public create(x: E): Self.T { let v: vector; v = Vector.empty(); Vector.push_back(&mut v, move(x)); return T{ v: move(v) }; } - public overcomplicated_equals(x: E, y: E): bool { + public overcomplicated_equals(x: E, y: E): bool { let r: bool; let x1: Self.T; let y1: Self.T; diff --git a/language/move-prover/bytecode-to-boogie/test_mvir/vector.mvir b/language/move-prover/bytecode-to-boogie/test_mvir/vector.mvir index 521f5895453b..0e27acd81a25 100644 --- a/language/move-prover/bytecode-to-boogie/test_mvir/vector.mvir +++ b/language/move-prover/bytecode-to-boogie/test_mvir/vector.mvir @@ -16,7 +16,7 @@ module Option { return T { v: move(v) }; } - public unwrap_or(x: Self.T, e: E): E { + public unwrap_or(x: Self.T, e: E): E { let v: vector; T { v: v } = move(x); if (Vector.is_empty(&v)) { diff --git a/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/libra_account.mvir b/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/libra_account.mvir index a1988390fdaa..727e01c312c0 100644 --- a/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/libra_account.mvir +++ b/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/libra_account.mvir @@ -73,7 +73,7 @@ module LibraAccount { // A handle for a event such that: // 1. Other modules can emit event to this handle. // 2. Storage can use this handle to prove the total number of events that happened in the past. - resource EventHandle { + resource EventHandle { // Total number of events emitted to this event stream. counter: u64, // A globally unique ID for this event stream. @@ -743,14 +743,14 @@ module LibraAccount { } // Use EventHandleGenerator to generate a unique event handle that one can emit an event to. - new_event_handle_impl(counter: &mut Self.EventHandleGenerator, sender: address): Self.EventHandle + new_event_handle_impl(counter: &mut Self.EventHandleGenerator, sender: address): Self.EventHandle aborts_if counter.counter + 1 > max_u64() { return EventHandle {counter: 0, guid: Self.fresh_guid(move(counter), move(sender))}; } // Use sender's EventHandleGenerator to generate a unique event handle that one can emit an event to. - public new_event_handle(): Self.EventHandle acquires T + public new_event_handle(): Self.EventHandle acquires T aborts_if global(txn_sender).event_generator.counter + 1 > max_u64() { let sender_account_ref: &mut Self.T; @@ -761,7 +761,7 @@ module LibraAccount { // Emit an event with payload `msg` by using handle's key and counter. Will change the payload from vector to a // generic type parameter once we have generics. - public emit_event(handle_ref: &mut Self.EventHandle, msg: T) + public emit_event(handle_ref: &mut Self.EventHandle, msg: T) aborts_if handle_ref.counter + 1 > max_u64() { let count: &mut u64; @@ -777,11 +777,11 @@ module LibraAccount { // Native procedure that writes to the actual event stream in Event store // This will replace the "native" portion of EmitEvent bytecode - native write_to_event_store(guid: vector, count: u64, msg: T) + native write_to_event_store(guid: vector, count: u64, msg: T) aborts_if false; // Destroy a unique handle. - public destroy_handle(handle: Self.EventHandle) + public destroy_handle(handle: Self.EventHandle) aborts_if false { let guid: vector; diff --git a/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/vector.mvir b/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/vector.mvir index 64c56e9c516a..d13f444e20cf 100644 --- a/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/vector.mvir +++ b/language/move-prover/bytecode-to-boogie/test_mvir/verify-stdlib/vector.mvir @@ -1,4 +1,4 @@ -// A variable-sized container that can hold both unrestricted types and resources. +// A variable-sized container that can hold both copyable types and resources. // Except for this comment, this file is just a copy of language/stdlib/modules/vector.mvir // This hasn't been specified, yet. This is only needed for MVIR type checking, since the definitions @@ -76,15 +76,15 @@ module Vector { return Self.length(move(v)) == 0; } - // Return the `i`th element of the vector. Only available for vectors that contain unrestricted + // Return the `i`th element of the vector. Only available for vectors that contain copyable // values. - public get(v: &vector, i: u64): Element { + public get(v: &vector, i: u64): Element { return *Self.borrow(move(v), move(i)); } // Replace the `i`th element of the vector with the value `v`. Only available for vectors that - // contain unrestricted values. - public set(v: &mut vector, i: u64, e: Element) { + // contain copyable values. + public set(v: &mut vector, i: u64, e: Element) { *(Self.borrow_mut(move(v), move(i))) = move(e); return; } diff --git a/language/move-prover/bytecode-to-boogie/test_mvir/verify-vector.mvir b/language/move-prover/bytecode-to-boogie/test_mvir/verify-vector.mvir index 95f0e86a4aba..bd13344a9e36 100644 --- a/language/move-prover/bytecode-to-boogie/test_mvir/verify-vector.mvir +++ b/language/move-prover/bytecode-to-boogie/test_mvir/verify-vector.mvir @@ -358,7 +358,7 @@ module VerifyVector { } // succeeds. standard vector method. - public my_get4(v: &vector, i: u64): Element + public my_get4(v: &vector, i: u64): Element aborts_if i >= len(*v) //ensures RET(0) == vector_get(*v, i) ensures RET(0) == v[i] @@ -385,7 +385,7 @@ module VerifyVector { } // succeeds. standard vector method. - public my_set3(v: &mut vector, i: u64, e: Element) + public my_set3(v: &mut vector, i: u64, e: Element) aborts_if i >= len(*v) ensures *v == old(v[i:=e]) //ensures *v == old(*v)[i:=e] // mvir parsing errors: ParserError: Invalid token at 11189 @@ -512,7 +512,7 @@ module VerifyVector { } // succeeds. custom vector method. - public my_swap3(v: &mut vector, i: u64, j: u64) + public my_swap3(v: &mut vector, i: u64, j: u64) aborts_if i >= len(*v) aborts_if j >= len(*v) ensures *v == old(v[i:=v[j]][j:=v[i]]) diff --git a/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode.rs b/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode.rs index 7cfef6517cbe..dc6d5e7397cf 100644 --- a/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode.rs +++ b/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode.rs @@ -3,7 +3,7 @@ use vm::file_format::{ AddressPoolIndex, ByteArrayPoolIndex, CodeOffset, FieldDefinitionIndex, FunctionHandleIndex, - LocalIndex, LocalsSignatureIndex, StructDefinitionIndex, + LocalIndex, SignatureIndex, StructDefinitionIndex, }; type TempIndex = usize; @@ -22,7 +22,7 @@ pub enum StacklessBytecode { Call( Vec, FunctionHandleIndex, - LocalsSignatureIndex, + SignatureIndex, Vec, ), /* t1_vec = call(index) with * t2_vec as parameters */ @@ -31,36 +31,21 @@ pub enum StacklessBytecode { Pack( TempIndex, StructDefinitionIndex, - LocalsSignatureIndex, + SignatureIndex, Vec, ), /* t1 = struct(index) with t2_vec * as fields */ Unpack( Vec, StructDefinitionIndex, - LocalsSignatureIndex, + SignatureIndex, TempIndex, ), // t1_vec = t2's fields BorrowField(TempIndex, TempIndex, FieldDefinitionIndex), // t1 = t2.field - MoveToSender(TempIndex, StructDefinitionIndex, LocalsSignatureIndex), /* move_to_sender(t) */ - MoveFrom( - TempIndex, - TempIndex, - StructDefinitionIndex, - LocalsSignatureIndex, - ), /* t1 = move_from(t2) */ - BorrowGlobal( - TempIndex, - TempIndex, - StructDefinitionIndex, - LocalsSignatureIndex, - ), /* t1 = borrow_global(t2) */ - Exists( - TempIndex, - TempIndex, - StructDefinitionIndex, - LocalsSignatureIndex, - ), /* t1 = exists(t2) */ + MoveToSender(TempIndex, StructDefinitionIndex, SignatureIndex), /* move_to_sender(t) */ + MoveFrom(TempIndex, TempIndex, StructDefinitionIndex, SignatureIndex), /* t1 = move_from(t2) */ + BorrowGlobal(TempIndex, TempIndex, StructDefinitionIndex, SignatureIndex), /* t1 = borrow_global(t2) */ + Exists(TempIndex, TempIndex, StructDefinitionIndex, SignatureIndex), /* t1 = exists(t2) */ GetGasRemaining(TempIndex), GetTxnSequenceNumber(TempIndex), diff --git a/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode_generator.rs b/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode_generator.rs index f6b5cbd98c54..dda92601f015 100644 --- a/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode_generator.rs +++ b/language/move-prover/stackless-bytecode-generator/src/stackless_bytecode_generator.rs @@ -6,7 +6,7 @@ use vm::{ access::ModuleAccess, file_format::{ Bytecode, CompiledModule, CompiledProgram, FieldDefinitionIndex, FunctionDefinition, - LocalsSignatureIndex, SignatureToken, + SignatureIndex, SignatureToken, }, views::{ FieldDefinitionView, FunctionDefinitionView, FunctionSignatureView, StructDefinitionView, @@ -86,8 +86,8 @@ impl<'a> StacklessBytecodeGenerator<'a> { if !function_definition_view.is_native() { let locals_signature_view = function_definition_view.locals_signature(); temp_count = locals_signature_view.len(); - for (_, arg_type_view) in locals_signature_view.tokens().enumerate() { - local_types.push(arg_type_view.as_inner().clone()); + for (_, parameter_view) in locals_signature_view.tokens().enumerate() { + local_types.push(parameter_view.as_inner().clone()); } } StacklessBytecodeGenerator { @@ -122,7 +122,7 @@ impl<'a> StacklessBytecodeGenerator<'a> { .clone() } - fn get_type_params(&self, type_params_index: LocalsSignatureIndex) -> Vec { + fn get_type_params(&self, type_params_index: SignatureIndex) -> Vec { self.module.locals_signature_at(type_params_index).0.clone() } @@ -392,7 +392,7 @@ impl<'a> StacklessBytecodeGenerator<'a> { let mut arg_temp_indices = vec![]; let mut return_temp_indices = vec![]; - for _ in function_signature.arg_types.iter() { + for _ in function_signature.parameters.iter() { let arg_temp_index = self.temp_stack.pop().unwrap(); arg_temp_indices.push(arg_temp_index); } diff --git a/language/move-prover/stackless-bytecode-generator/tests/stack_elim_tests.rs b/language/move-prover/stackless-bytecode-generator/tests/stack_elim_tests.rs index a2887a43b100..d31e239aa584 100644 --- a/language/move-prover/stackless-bytecode-generator/tests/stack_elim_tests.rs +++ b/language/move-prover/stackless-bytecode-generator/tests/stack_elim_tests.rs @@ -10,7 +10,7 @@ use stackless_bytecode_generator::{ use stdlib::{stdlib_modules, StdLibOptions}; use vm::file_format::{ AddressPoolIndex, ByteArrayPoolIndex, FieldDefinitionIndex, FunctionHandleIndex, - LocalsSignatureIndex, SignatureToken, StructDefinitionIndex, StructHandleIndex, + SignatureIndex, SignatureToken, StructDefinitionIndex, StructHandleIndex, }; #[test] @@ -163,7 +163,7 @@ fn transform_code_with_pack_unpack() { Pack( 6, StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), + SignatureIndex::new(1), vec![4, 5], ), StLoc(1, 6), @@ -171,7 +171,7 @@ fn transform_code_with_pack_unpack() { Unpack( vec![8, 9], StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), + SignatureIndex::new(1), 7, ), StLoc(3, 9), @@ -409,7 +409,7 @@ fn transform_code_with_function_call() { Call( vec![11, 10, 9], FunctionHandleIndex::new(1), - LocalsSignatureIndex::new(1), + SignatureIndex::new(1), vec![6, 7, 8], ), StLoc(5, 11), @@ -461,35 +461,16 @@ fn transform_code_with_module_builtins() { let (actual_code, actual_types) = generate_code_from_string(code); let expected_code = vec![ CopyLoc(4, 0), - Exists( - 5, - 4, - StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), - ), + Exists(5, 4, StructDefinitionIndex::new(0), SignatureIndex::new(1)), StLoc(3, 5), CopyLoc(6, 0), - BorrowGlobal( - 7, - 6, - StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), - ), + BorrowGlobal(7, 6, StructDefinitionIndex::new(0), SignatureIndex::new(1)), StLoc(2, 7), CopyLoc(8, 0), - MoveFrom( - 9, - 8, - StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), - ), + MoveFrom(9, 8, StructDefinitionIndex::new(0), SignatureIndex::new(1)), StLoc(1, 9), MoveLoc(10, 1), - MoveToSender( - 10, - StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), - ), + MoveToSender(10, StructDefinitionIndex::new(0), SignatureIndex::new(1)), MoveLoc(11, 2), Ret(vec![11]), ]; @@ -538,7 +519,7 @@ fn transform_program_with_script() { Call( vec![], FunctionHandleIndex::new(1), - LocalsSignatureIndex::new(1), + SignatureIndex::new(1), vec![2, 3], ), Ret(vec![]), @@ -583,7 +564,7 @@ fn transform_program_with_generics() { Unpack( vec![8], StructDefinitionIndex::new(0), - LocalsSignatureIndex::new(1), + SignatureIndex::new(1), 7, ), StLoc(3, 8), diff --git a/language/move-vm/types/src/native_functions/dispatch.rs b/language/move-vm/types/src/native_functions/dispatch.rs index c9fa308865fd..7a4363f414ec 100644 --- a/language/move-vm/types/src/native_functions/dispatch.rs +++ b/language/move-vm/types/src/native_functions/dispatch.rs @@ -179,7 +179,7 @@ impl NativeFunction { None => return Ok(None), Some(res) => res, }; - if self.num_args() == res.arg_types.len() { + if self.num_args() == res.parameters.len() { Ok(Some(res)) } else { Err( @@ -200,9 +200,9 @@ impl NativeFunction { }}; ($kinds:expr, $args:expr, $ret:expr) => {{ FunctionSignature { - return_types: $ret, - arg_types: $args, - type_formals: $kinds, + return_: $ret, + parameters: $args, + type_parameters: $kinds, } }}; } @@ -282,19 +282,19 @@ impl NativeFunction { vec![] ), Self::AccountWriteEvent => simple!( - vec![Kind::Unrestricted], + vec![Kind::Copyable], vec![Vector(Box::new(U8)), U64, TypeParameter(0)], vec![] ), Self::AccountSaveAccount => { - let type_formals = vec![]; + let type_parameters = vec![]; let t_idx = struct_handle_idx(m?, "T")?; - let arg_types = vec![Address, Struct(t_idx, vec![])]; - let return_types = vec![]; + let parameters = vec![Address, Struct(t_idx, vec![])]; + let return_ = vec![]; FunctionSignature { - type_formals, - arg_types, - return_types, + type_parameters, + parameters, + return_, } } }) diff --git a/language/move-vm/types/src/native_structs/dispatch.rs b/language/move-vm/types/src/native_structs/dispatch.rs index 615a86a1dc91..0b91d7557f8d 100644 --- a/language/move-vm/types/src/native_structs/dispatch.rs +++ b/language/move-vm/types/src/native_structs/dispatch.rs @@ -10,7 +10,7 @@ pub struct NativeStruct { /// The expected boolean indicating if it is a nominal resource or not pub expected_nominal_resource: bool, /// The expected kind constraints of the type parameters. - pub expected_type_formals: Vec, + pub expected_type_parameters: Vec, /// The expected index for the struct /// Helpful for ensuring proper typing of native functions pub expected_index: StructHandleIndex, diff --git a/language/tools/cost-synthesis/src/main.rs b/language/tools/cost-synthesis/src/main.rs index 543c0ecbadf8..880da16152bf 100644 --- a/language/tools/cost-synthesis/src/main.rs +++ b/language/tools/cost-synthesis/src/main.rs @@ -30,7 +30,7 @@ use vm::{ access::ModuleAccess, file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, FieldDefinitionIndex, - FunctionDefinitionIndex, FunctionHandleIndex, StructDefinitionIndex, NO_TYPE_ACTUALS, + FunctionDefinitionIndex, FunctionHandleIndex, StructDefinitionIndex, NO_TYPE_ARGUMENTS, }, gas_schedule::{AbstractMemorySize, CostTable, GasAlgebra, GasCarrier, GasUnits}, transaction_metadata::TransactionMetadata, @@ -103,11 +103,11 @@ fn stack_instructions(options: &Opt) { ReadRef, WriteRef, FreezeRef, - MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - Exists(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + Exists(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), MutBorrowField(FieldDefinitionIndex::new(0)), ImmBorrowField(FieldDefinitionIndex::new(0)), CopyLoc(0), @@ -115,9 +115,9 @@ fn stack_instructions(options: &Opt) { MutBorrowLoc(0), ImmBorrowLoc(0), StLoc(0), - Unpack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - Pack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), - Call(FunctionHandleIndex::new(0), NO_TYPE_ACTUALS), + Unpack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + Pack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), + Call(FunctionHandleIndex::new(0), NO_TYPE_ARGUMENTS), Sub, Ret, Add, diff --git a/language/tools/cost-synthesis/src/stack_generator.rs b/language/tools/cost-synthesis/src/stack_generator.rs index 034e6b6182d8..99e80c0676bd 100644 --- a/language/tools/cost-synthesis/src/stack_generator.rs +++ b/language/tools/cost-synthesis/src/stack_generator.rs @@ -26,7 +26,7 @@ use vm::{ FunctionDefinition, FunctionDefinitionIndex, FunctionHandleIndex, FunctionSignature, LocalIndex, MemberCount, ModuleHandle, SignatureToken, StructDefinition, StructDefinitionIndex, StructFieldInformation, StructHandleIndex, TableIndex, - NO_TYPE_ACTUALS, + NO_TYPE_ARGUMENTS, }, gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier}, }; @@ -337,7 +337,7 @@ impl<'txn> RandomStackGenerator<'txn> { let type_tok = &type_sig[local_index]; let stack_local = self.resolve_to_value(type_tok, &[]); let mut stack = vec![stack_local]; - for type_tok in function_sig.arg_types.iter() { + for type_tok in function_sig.parameters.iter() { stack.push(self.resolve_to_value(type_tok, &[])) } (module, local_index as LocalIndex, function_def_idx, stack) @@ -570,7 +570,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - MoveToSender(struct_handle_idx, NO_TYPE_ACTUALS), + MoveToSender(struct_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -583,7 +583,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - MoveFrom(struct_handle_idx, NO_TYPE_ACTUALS), + MoveFrom(struct_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -596,7 +596,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - MutBorrowGlobal(struct_handle_idx, NO_TYPE_ACTUALS), + MutBorrowGlobal(struct_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -609,7 +609,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - ImmBorrowGlobal(struct_handle_idx, NO_TYPE_ACTUALS), + ImmBorrowGlobal(struct_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -627,7 +627,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - Exists(next_struct_handle_idx, NO_TYPE_ACTUALS), + Exists(next_struct_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -639,7 +639,7 @@ impl<'txn> RandomStackGenerator<'txn> { .root_module .function_signature_at(function_handle.signature); let stack = function_sig - .arg_types + .parameters .iter() .fold(Vec::new(), |mut acc, sig_tok| { acc.push(self.resolve_to_value(sig_tok, &acc)); @@ -651,7 +651,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - Call(function_handle_idx, NO_TYPE_ACTUALS), + Call(function_handle_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -690,7 +690,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(stack), - Pack(random_struct_idx, NO_TYPE_ACTUALS), + Pack(random_struct_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) @@ -709,7 +709,7 @@ impl<'txn> RandomStackGenerator<'txn> { StackState::new( (self.root_module, None), self.random_pad(vec![struct_stack]), - Unpack(random_struct_idx, NO_TYPE_ACTUALS), + Unpack(random_struct_idx, NO_TYPE_ARGUMENTS), size, HashMap::new(), ) diff --git a/language/tools/disassembler/src/disassembler.rs b/language/tools/disassembler/src/disassembler.rs index d79793807e14..2151f9a0684b 100644 --- a/language/tools/disassembler/src/disassembler.rs +++ b/language/tools/disassembler/src/disassembler.rs @@ -12,8 +12,8 @@ use vm::{ access::ModuleAccess, file_format::{ Bytecode, FieldDefinitionIndex, FunctionDefinition, FunctionDefinitionIndex, - FunctionSignature, Kind, LocalsSignature, LocalsSignatureIndex, SignatureToken, - StructDefinition, StructDefinitionIndex, StructFieldInformation, TableIndex, TypeSignature, + FunctionSignature, Kind, Signature, SignatureIndex, SignatureToken, StructDefinition, + StructDefinitionIndex, StructFieldInformation, TableIndex, TypeSignature, }, }; @@ -150,7 +150,7 @@ impl Disassembler { fn struct_type_info( &self, struct_idx: StructDefinitionIndex, - types_idx: LocalsSignatureIndex, + types_idx: SignatureIndex, ) -> Result<(String, String)> { let struct_definition = self.get_struct_def(struct_idx)?; let struct_source_map = self @@ -197,7 +197,7 @@ impl Disassembler { fn type_for_local( &self, local_idx: u64, - locals_sigs: &LocalsSignature, + locals_sigs: &Signature, function_source_map: &FunctionSourceMap, ) -> Result { let sig_tok = locals_sigs @@ -301,7 +301,7 @@ impl Disassembler { fn disassemble_instruction( &self, instruction: &Bytecode, - locals_sigs: &LocalsSignature, + locals_sigs: &Signature, function_source_map: &FunctionSourceMap, ) -> Result { match instruction { @@ -422,13 +422,13 @@ impl Disassembler { }) .collect::>>()?; let type_arguments = function_signature - .arg_types + .parameters .iter() .map(|sig_tok| Ok(self.disassemble_sig_tok(sig_tok.clone(), &ty_params)?)) .collect::>>()? .join(", "); let type_rets = function_signature - .return_types + .return_ .iter() .map(|sig_tok| Ok(self.disassemble_sig_tok(sig_tok.clone(), &ty_params)?)) .collect::>>()?; @@ -497,7 +497,7 @@ impl Disassembler { Ok(instrs) } - fn disassemble_type_formals( + fn disassemble_type_parameters( source_map_ty_params: &[SourceName], kinds: &[Kind], ) -> String { @@ -529,7 +529,7 @@ impl Disassembler { Ok(format!("{}: {}", name.to_string(), ty)) }) .collect::>>()?; - let mut locals = locals_names_tys.split_off(function_signature.arg_types.len()); + let mut locals = locals_names_tys.split_off(function_signature.parameters.len()); let args = locals_names_tys; if !self.options.print_locals { locals = vec![]; @@ -568,9 +568,9 @@ impl Disassembler { "" }; - let ty_params = Self::disassemble_type_formals( + let ty_params = Self::disassemble_type_parameters( &function_source_map.type_parameters, - &function_signature.type_formals, + &function_signature.type_parameters, ); let name = self .source_mapper @@ -578,7 +578,7 @@ impl Disassembler { .identifier_at(function_handle.name) .to_string(); let ret_type: Vec = function_signature - .return_types + .return_ .iter() .cloned() .map(|sig_token| { @@ -655,9 +655,9 @@ impl Disassembler { .identifier_at(struct_handle.name) .to_string(); - let ty_params = Self::disassemble_type_formals( + let ty_params = Self::disassemble_type_parameters( &struct_source_map.type_parameters, - &struct_handle.type_formals, + &struct_handle.type_parameters, ); let mut fields = match field_info { None => vec![], diff --git a/language/tools/test-generation/src/abstract_state.rs b/language/tools/test-generation/src/abstract_state.rs index 02c0519989d8..1d7847e2e018 100644 --- a/language/tools/test-generation/src/abstract_state.rs +++ b/language/tools/test-generation/src/abstract_state.rs @@ -9,8 +9,8 @@ use std::{ use vm::{ access::ModuleAccess, file_format::{ - empty_module, CompiledModule, CompiledModuleMut, FunctionHandleIndex, Kind, - LocalsSignature, LocalsSignatureIndex, SignatureToken, StructDefinitionIndex, TableIndex, + empty_module, CompiledModule, CompiledModuleMut, FunctionHandleIndex, Kind, Signature, + SignatureIndex, SignatureToken, StructDefinitionIndex, TableIndex, }, }; @@ -47,7 +47,7 @@ pub enum Mutability { } impl AbstractValue { - /// Create a new primitive `AbstractValue` given its type; the kind will be `Unrestricted` + /// Create a new primitive `AbstractValue` given its type; the kind will be `Copyable` pub fn new_primitive(token: SignatureToken) -> AbstractValue { checked_precondition!( match token { @@ -60,7 +60,7 @@ impl AbstractValue { ); AbstractValue { token, - kind: Kind::Unrestricted, + kind: Kind::Copyable, } } @@ -195,12 +195,12 @@ impl CallGraph { /// type instantiations, and at the end materialize this updated signature pool into a module. We /// also need the ability to quickly determine if an instantiation has already been created, and if /// so, at which index. So this also keeps a reverse lookup table of instantiation to -/// LocalsSignatureIndex. +/// SignatureIndex. #[derive(Debug, Clone)] pub struct InstantiableModule { // A reverse lookup table for instantiations. instance_for_offset: Vec>, - instantiations: HashMap, LocalsSignatureIndex>, + instantiations: HashMap, SignatureIndex>, pub module: CompiledModule, } @@ -211,7 +211,7 @@ impl InstantiableModule { .locals_signatures() .iter() .enumerate() - .map(|(index, sig)| (sig.0.clone(), LocalsSignatureIndex(index as TableIndex))) + .map(|(index, sig)| (sig.0.clone(), SignatureIndex(index as TableIndex))) .collect::>(), instance_for_offset: module .locals_signatures() @@ -224,13 +224,12 @@ impl InstantiableModule { /// If the `instantiant` is not in the `instantiations` table, this adds the instantiant to the /// `instance_for_offset` for table, and adds the index to the reverse lookup table. Returns - /// the LocalsSignatureIndex for the `instantiant`. - pub fn add_instantiation(&mut self, instantiant: Vec) -> LocalsSignatureIndex { + /// the SignatureIndex for the `instantiant`. + pub fn add_instantiation(&mut self, instantiant: Vec) -> SignatureIndex { match self.instantiations.get(&instantiant) { Some(index) => *index, None => { - let current_index = - LocalsSignatureIndex(self.instance_for_offset.len() as TableIndex); + let current_index = SignatureIndex(self.instance_for_offset.len() as TableIndex); self.instantiations .insert(instantiant.clone(), current_index); self.instance_for_offset.push(instantiant); @@ -240,7 +239,7 @@ impl InstantiableModule { } /// Returns the type instantiation at `index`. Errors if the instantiation does not exist. - pub fn instantiantiation_at(&self, index: LocalsSignatureIndex) -> &Vec { + pub fn instantiantiation_at(&self, index: SignatureIndex) -> &Vec { match self.instance_for_offset.get(index.0 as usize) { Some(vec) => vec, None => { @@ -256,7 +255,7 @@ impl InstantiableModule { module.locals_signatures = self .instance_for_offset .into_iter() - .map(LocalsSignature) + .map(Signature) .collect(); module } diff --git a/language/tools/test-generation/src/bytecode_generator.rs b/language/tools/test-generation/src/bytecode_generator.rs index 681cdab67317..6dbf48aeb6af 100644 --- a/language/tools/test-generation/src/bytecode_generator.rs +++ b/language/tools/test-generation/src/bytecode_generator.rs @@ -16,9 +16,8 @@ use vm::{ access::ModuleAccess, file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, CodeOffset, CompiledModuleMut, - FieldDefinitionIndex, FunctionHandleIndex, FunctionSignature, LocalIndex, - LocalsSignatureIndex, SignatureToken, StructDefinitionIndex, StructFieldInformation, - TableIndex, + FieldDefinitionIndex, FunctionHandleIndex, FunctionSignature, LocalIndex, SignatureIndex, + SignatureToken, StructDefinitionIndex, StructFieldInformation, TableIndex, }, }; @@ -44,15 +43,15 @@ type AddressPoolIndexToBytecode = fn(AddressPoolIndex) -> Bytecode; type ByteArrayPoolIndexToBytecode = fn(ByteArrayPoolIndex) -> Bytecode; /// This type represents bytecode instructions that take a `StructDefinitionIndex` -/// and a `LocalsSignatureIndex` -type StructAndLocalIndexToBytecode = fn(StructDefinitionIndex, LocalsSignatureIndex) -> Bytecode; +/// and a `SignatureIndex` +type StructAndLocalIndexToBytecode = fn(StructDefinitionIndex, SignatureIndex) -> Bytecode; /// This type represents bytecode instructions that take a `FieldDefinitionIndex`` type FieldDefinitionIndexToBytecode = fn(FieldDefinitionIndex) -> Bytecode; /// This type represents bytecode instructions that take a `FunctionHandleIndex` -/// and a `LocalsSignatureIndex` -type FunctionAndLocalIndexToBytecode = fn(FunctionHandleIndex, LocalsSignatureIndex) -> Bytecode; +/// and a `SignatureIndex` +type FunctionAndLocalIndexToBytecode = fn(FunctionHandleIndex, SignatureIndex) -> Bytecode; /// There are six types of bytecode instructions #[derive(Debug, Clone)] @@ -81,13 +80,13 @@ enum BytecodeType { /// Instructions that take a `ByteArrayPoolIndex` ByteArrayPoolIndex(ByteArrayPoolIndexToBytecode), - /// Instructions that take a `StructDefinitionIndex` and a `LocalsSignatureIndex` + /// Instructions that take a `StructDefinitionIndex` and a `SignatureIndex` StructAndLocalIndex(StructAndLocalIndexToBytecode), /// Instructions that take a `FieldDefinitionIndex` FieldDefinitionIndex(FieldDefinitionIndexToBytecode), - /// Instructions that take a `FunctionHandleIndex` and a `LocalsSignatureIndex` + /// Instructions that take a `FunctionHandleIndex` and a `SignatureIndex` FunctionAndLocalIndex(FunctionAndLocalIndexToBytecode), } @@ -377,7 +376,7 @@ impl<'a> BytecodeGenerator<'a> { instruction( StructDefinitionIndex::new(x), // Set 0 as the index. This will be filled in/changed later on. - LocalsSignatureIndex::new(0), + SignatureIndex::new(0), ) }) } @@ -401,7 +400,7 @@ impl<'a> BytecodeGenerator<'a> { instruction( handle, // Set 0 as the signature index. This index will be filled in/changed later - LocalsSignatureIndex::new(0), + SignatureIndex::new(0), ) }) } @@ -698,14 +697,14 @@ impl<'a> BytecodeGenerator<'a> { let state1 = AbstractState::from_locals( module.clone(), block.get_locals_in().clone(), - signature.type_formals.clone(), + signature.type_parameters.clone(), acquires_global_resources.to_vec(), call_graph.clone(), ); let state2 = AbstractState::from_locals( module.clone(), block.get_locals_out().clone(), - signature.type_formals.clone(), + signature.type_parameters.clone(), acquires_global_resources.to_vec(), call_graph.clone(), ); @@ -750,7 +749,7 @@ impl<'a> BytecodeGenerator<'a> { )? } else if cfg_copy.num_children(*block_id) == 0 { // Return: Add return types to last block - for token_type in signature.return_types.iter() { + for token_type in signature.return_.iter() { let next_instructions = Self::inhabit_with_bytecode_seq(&mut state_f.module, &token_type); debug!( diff --git a/language/tools/test-generation/src/control_flow_graph.rs b/language/tools/test-generation/src/control_flow_graph.rs index c2a6ebe03b27..299e93969e28 100644 --- a/language/tools/test-generation/src/control_flow_graph.rs +++ b/language/tools/test-generation/src/control_flow_graph.rs @@ -135,7 +135,7 @@ impl CFG { }; // Assign locals to basic blocks assume!(target_blocks == 0 || !cfg.basic_blocks.is_empty()); - CFG::add_locals(&mut cfg, rng, locals, signature.arg_types.len()); + CFG::add_locals(&mut cfg, rng, locals, signature.parameters.len()); cfg } @@ -263,7 +263,7 @@ impl CFG { ( i, ( - AbstractValue::new_value(token.clone(), Kind::Unrestricted), + AbstractValue::new_value(token.clone(), Kind::Copyable), borrow_state, ), ) diff --git a/language/tools/test-generation/src/lib.rs b/language/tools/test-generation/src/lib.rs index e2c4cac5063f..4edc8247467b 100644 --- a/language/tools/test-generation/src/lib.rs +++ b/language/tools/test-generation/src/lib.rs @@ -57,7 +57,7 @@ fn run_vm(module: VerifiedModule) -> VMResult<()> { module.function_signature_at(sig_idx).clone() }; let main_args: Vec = function_signature - .arg_types + .parameters .iter() .map(|sig_tok| match sig_tok { SignatureToken::Address => Value::address(AccountAddress::new([0; 32])), diff --git a/language/tools/test-generation/src/summaries.rs b/language/tools/test-generation/src/summaries.rs index 8cf476ddd410..51148575f01c 100644 --- a/language/tools/test-generation/src/summaries.rs +++ b/language/tools/test-generation/src/summaries.rs @@ -19,17 +19,17 @@ use crate::{ transitions::*, unpack_instantiation_for_state, with_ty_param, }; -use vm::file_format::{Bytecode, Kind, LocalsSignatureIndex, SignatureToken}; +use vm::file_format::{Bytecode, Kind, SignatureIndex, SignatureToken}; /// A `Precondition` is a boolean predicate on an `AbstractState`. pub type Precondition = dyn Fn(&AbstractState) -> bool; /// A `Effect` is a function that transforms on `AbstractState` to another pub type NonInstantiableEffect = dyn Fn(&AbstractState) -> Result; -pub type InstantiableEffect = dyn Fn(LocalsSignatureIndex) -> Vec>; +pub type InstantiableEffect = dyn Fn(SignatureIndex) -> Vec>; type Instantiation = dyn Fn(&AbstractState) -> Vec; -type InstantiableInstruction = dyn Fn(LocalsSignatureIndex) -> Bytecode; +type InstantiableInstruction = dyn Fn(SignatureIndex) -> Bytecode; pub enum Effects { NoTyParams(Vec>), @@ -53,7 +53,7 @@ pub fn instruction_summary(instruction: Bytecode, exact: bool) -> Summary { Bytecode::Pop => Summary { preconditions: vec![ state_stack_has!(0, None), - state_stack_kind_is!(0, Kind::Unrestricted), + state_stack_kind_is!(0, Kind::Copyable), state_memory_safe!(Some(0)), ], effects: Effects::NoTyParams(vec![state_stack_pop!()]), @@ -124,7 +124,7 @@ pub fn instruction_summary(instruction: Bytecode, exact: bool) -> Summary { Bytecode::CopyLoc(i) => Summary { preconditions: vec![ state_local_exists!(i), - state_local_kind_is!(i, Kind::Unrestricted), + state_local_kind_is!(i, Kind::Copyable), state_local_availability_is!(i, BorrowState::Available), state_memory_safe!(None), ], @@ -148,8 +148,8 @@ pub fn instruction_summary(instruction: Bytecode, exact: bool) -> Summary { preconditions: vec![ state_stack_has!(0, None), state_local_exists!(i), - // TODO: This covers storing on an unrestricted local only - state_local_kind_is!(i, Kind::Unrestricted), + // TODO: This covers storing on an copyable local only + state_local_kind_is!(i, Kind::Copyable), state_stack_local_polymorphic_eq!(0, i as usize), state_memory_safe!(Some(0)), ], @@ -259,7 +259,7 @@ pub fn instruction_summary(instruction: Bytecode, exact: bool) -> Summary { preconditions: vec![ state_stack_has!(0, None), state_stack_has!(1, None), - state_stack_kind_is!(0, Kind::Unrestricted), + state_stack_kind_is!(0, Kind::Copyable), state_stack_has_polymorphic_eq!(0, 1), state_memory_safe!(Some(0)), state_memory_safe!(Some(1)), diff --git a/language/tools/test-generation/src/transitions.rs b/language/tools/test-generation/src/transitions.rs index 6f59faed52d2..00ce4df09ebe 100644 --- a/language/tools/test-generation/src/transitions.rs +++ b/language/tools/test-generation/src/transitions.rs @@ -9,7 +9,7 @@ use crate::{ use vm::{ access::*, file_format::{ - FieldDefinitionIndex, FunctionHandleIndex, Kind, LocalsSignatureIndex, SignatureToken, + FieldDefinitionIndex, FunctionHandleIndex, Kind, SignatureIndex, SignatureToken, StructDefinitionIndex, }, views::{FunctionHandleView, SignatureTokenView, StructDefinitionView, ViewInternals}, @@ -163,7 +163,7 @@ pub fn stack_kind_is(state: &AbstractState, index: usize, kind: Kind) -> bool { /// Determine if the abstract value at `index` has a kind that is a subkind of the kind for the /// instruction kind. e.g. if the instruction takes a type of kind `All` then it is OK to fit in a -/// value with a type of kind `Unrestricted`. +/// value with a type of kind `Copyable`. pub fn stack_kind_is_subkind(state: &AbstractState, index: usize, instruction_kind: Kind) -> bool { if !stack_has(state, index, None) { return false; @@ -353,13 +353,13 @@ pub fn local_place(state: &AbstractState, index: u8) -> Result, + instantiation: Option, ) -> (bool, Subst) { let instantiation = instantiation.map(|index| state.module.instantiantiation_at(index)); let struct_def = state.module.module.struct_def_at(struct_index); let struct_def = StructDefinitionView::new(&state.module.module, struct_def); // Get the type formals for the struct, and the kinds that they expect. - let type_formals = struct_def.type_formals(); + let type_parameters = struct_def.type_parameters(); let field_token_views = struct_def .fields() .into_iter() @@ -374,7 +374,7 @@ pub fn stack_satisfies_struct_signature( token_view.as_inner().clone() }; let has = if let SignatureToken::TypeParameter(idx) = &ty { - if stack_kind_is_subkind(state, i, type_formals[*idx as usize]) { + if stack_kind_is_subkind(state, i, type_parameters[*idx as usize]) { let stack_tok = state.stack_peek(i).unwrap(); substitution.check_and_add(state, stack_tok.token, ty) } else { @@ -383,7 +383,7 @@ pub fn stack_satisfies_struct_signature( } else { let abstract_value = AbstractValue { token: ty, - kind: token_view.kind(type_formals), + kind: token_view.kind(type_parameters), }; stack_has(state, i, Some(abstract_value)) }; @@ -398,7 +398,7 @@ pub fn stack_satisfies_struct_signature( pub fn get_struct_instantiation_for_state( state: &AbstractState, struct_index: StructDefinitionIndex, - instantiation: Option, + instantiation: Option, ) -> Vec { if let Some(index) = instantiation { return state.module.instantiantiation_at(index).clone(); @@ -407,11 +407,11 @@ pub fn get_struct_instantiation_for_state( stack_satisfies_struct_signature(state, struct_index, instantiation).1; let struct_def = state.module.module.struct_def_at(struct_index); let struct_def = StructDefinitionView::new(&state.module.module, struct_def); - let typs = struct_def.type_formals(); + let typs = struct_def.type_parameters(); for (index, kind) in typs.iter().enumerate() { if !partial_instantiation.subst.contains_key(&index) { match kind { - Kind::All | Kind::Unrestricted => { + Kind::All | Kind::Copyable => { partial_instantiation .subst .insert(index, SignatureToken::U64); @@ -513,7 +513,7 @@ pub fn stack_struct_popn( pub fn create_struct( state: &AbstractState, struct_index: StructDefinitionIndex, - instantiation: LocalsSignatureIndex, + instantiation: SignatureIndex, ) -> Result { let state_copy = state.clone(); let mut state = state.clone(); @@ -542,7 +542,7 @@ pub fn stack_unpack_struct_instantiation(state: &AbstractState) -> Vec Result { let state_copy = state.clone(); let mut state = state.clone(); @@ -676,21 +676,22 @@ pub fn stack_satisfies_function_signature( .module .module .function_signature_at(function_handle.signature); - let type_formals = &function_signature.type_formals; + let type_parameters = &function_signature.type_parameters; let mut satisfied = true; let mut substitution = Subst::new(); - for (i, arg_type) in function_signature.arg_types.iter().rev().enumerate() { - let has = if let SignatureToken::TypeParameter(idx) = arg_type { - if stack_kind_is_subkind(state, i, type_formals[*idx as usize]) { + for (i, parameter) in function_signature.parameters.iter().rev().enumerate() { + let has = if let SignatureToken::TypeParameter(idx) = parameter { + if stack_kind_is_subkind(state, i, type_parameters[*idx as usize]) { let stack_tok = state.stack_peek(i).unwrap(); - substitution.check_and_add(state, stack_tok.token, arg_type.clone()) + substitution.check_and_add(state, stack_tok.token, parameter.clone()) } else { false } } else { - let kind = SignatureTokenView::new(&state.module.module, arg_type).kind(type_formals); + let kind = + SignatureTokenView::new(&state.module.module, parameter).kind(type_parameters); let abstract_value = AbstractValue { - token: arg_type.clone(), + token: parameter.clone(), kind, }; stack_has(&state, i, Some(abstract_value)) @@ -711,7 +712,7 @@ pub fn function_can_acquire_resource(state: &AbstractState) -> bool { pub fn stack_function_call( state: &AbstractState, function_index: FunctionHandleIndex, - instantiation: LocalsSignatureIndex, + instantiation: SignatureIndex, ) -> Result { let state_copy = state.clone(); let mut state = state.clone(); @@ -722,7 +723,7 @@ pub fn stack_function_call( .function_signature_at(function_handle.signature); let ty_instantiation = state_copy.module.instantiantiation_at(instantiation); let kinds = kinds_for_instantiation(&state_copy, &ty_instantiation); - for return_type in function_signature.return_types.iter() { + for return_type in function_signature.return_.iter() { let abstract_value = AbstractValue { token: return_type.substitute(&ty_instantiation), kind: kind_for_token(&state, return_type, &kinds), @@ -740,11 +741,11 @@ pub fn get_function_instantiation_for_state( let function_handle = state.module.module.function_handle_at(function_index); let function_handle = FunctionHandleView::new(&state.module.module, function_handle); let signature = function_handle.signature(); - let typs = signature.type_formals(); + let typs = signature.type_parameters(); for (index, kind) in typs.iter().enumerate() { if !partial_instantiation.subst.contains_key(&index) { match kind { - Kind::All | Kind::Unrestricted => { + Kind::All | Kind::Copyable => { partial_instantiation .subst .insert(index, SignatureToken::U64); @@ -771,7 +772,7 @@ pub fn stack_function_popn( .module .module .function_signature_at(function_handle.signature); - let number_of_pops = function_signature.arg_types.iter().len(); + let number_of_pops = function_signature.parameters.iter().len(); for _ in 0..number_of_pops { state.stack_pop()?; } diff --git a/language/tools/test-generation/tests/control_flow_instructions.rs b/language/tools/test-generation/tests/control_flow_instructions.rs index 3dbbbec872b5..2f88d1b109c3 100644 --- a/language/tools/test-generation/tests/control_flow_instructions.rs +++ b/language/tools/test-generation/tests/control_flow_instructions.rs @@ -7,8 +7,8 @@ use std::collections::HashMap; use test_generation::abstract_state::{AbstractState, AbstractValue, CallGraph}; use vm::file_format::{ empty_module, Bytecode, CompiledModuleMut, FunctionHandle, FunctionHandleIndex, - FunctionSignature, FunctionSignatureIndex, IdentifierIndex, LocalsSignature, - LocalsSignatureIndex, ModuleHandleIndex, SignatureToken, + FunctionSignature, FunctionSignatureIndex, IdentifierIndex, ModuleHandleIndex, Signature, + SignatureIndex, SignatureToken, }; mod common; @@ -22,9 +22,9 @@ fn generate_module_with_function() -> CompiledModuleMut { let sigs = vec![( vec![], FunctionSignature { - arg_types: vec![SignatureToken::U64, SignatureToken::Bool], - return_types: vec![SignatureToken::Address], - type_formals: vec![], + parameters: vec![SignatureToken::U64, SignatureToken::Bool], + return_: vec![SignatureToken::Address], + type_parameters: vec![], }, )]; @@ -41,7 +41,7 @@ fn generate_module_with_function() -> CompiledModuleMut { module.function_signatures.append(&mut function_sigs); module .locals_signatures - .append(&mut local_sigs.into_iter().map(LocalsSignature).collect()); + .append(&mut local_sigs.into_iter().map(Signature).collect()); module } @@ -53,7 +53,7 @@ fn bytecode_call() { state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool)); let (state2, _) = common::run_instruction( - Bytecode::Call(FunctionHandleIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Call(FunctionHandleIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!( @@ -70,7 +70,7 @@ fn bytecode_call_function_signature_not_satisfied() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::Call(FunctionHandleIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Call(FunctionHandleIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -84,7 +84,7 @@ fn bytecode_call_return_not_pushed() { state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool)); let (state2, _) = common::run_instruction( - Bytecode::Call(FunctionHandleIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Call(FunctionHandleIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!(state2.stack_len(), 0,); diff --git a/language/tools/test-generation/tests/local_instructions.rs b/language/tools/test-generation/tests/local_instructions.rs index d8a26a9042cf..a381aaea28d0 100644 --- a/language/tools/test-generation/tests/local_instructions.rs +++ b/language/tools/test-generation/tests/local_instructions.rs @@ -106,7 +106,7 @@ fn bytecode_mutborrowloc() { state2.stack_peek(0), Some(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted + Kind::Copyable )), "stack type postcondition not met" ); @@ -133,7 +133,7 @@ fn bytecode_immborrowloc() { state2.stack_peek(0), Some(AbstractValue::new_reference( SignatureToken::Reference(Box::new(SignatureToken::U64),), - Kind::Unrestricted + Kind::Copyable )), "stack type postcondition not met" ); diff --git a/language/tools/test-generation/tests/reference_instructions.rs b/language/tools/test-generation/tests/reference_instructions.rs index 6758f5dcde2c..b3316f34c932 100644 --- a/language/tools/test-generation/tests/reference_instructions.rs +++ b/language/tools/test-generation/tests/reference_instructions.rs @@ -12,7 +12,7 @@ fn bytecode_readref() { let mut state1 = AbstractState::new(); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); let (state2, _) = common::run_instruction(Bytecode::ReadRef, state1); assert_eq!( @@ -35,7 +35,7 @@ fn bytecode_readref_wrong_dereference() { let mut state1 = AbstractState::new(); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); let (state2, _) = common::run_instruction(Bytecode::ReadRef, state1); assert!( @@ -50,7 +50,7 @@ fn bytecode_writeref() { state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64)); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); let (state2, _) = common::run_instruction(Bytecode::WriteRef, state1); assert_eq!(state2.stack_len(), 0, "stack type postcondition not met"); @@ -63,7 +63,7 @@ fn bytecode_writeref_type_mismatch() { state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool)); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); common::run_instruction(Bytecode::WriteRef, state1); } @@ -75,7 +75,7 @@ fn bytecode_writeref_stack_len_mismatch() { state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64)); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); let (state2, _) = common::run_instruction(Bytecode::WriteRef, state1); assert!(state2.stack_len() != 0, "stack type postcondition not met"); @@ -86,7 +86,7 @@ fn bytecode_feezeref() { let mut state1 = AbstractState::new(); state1.stack_push(AbstractValue::new_reference( SignatureToken::MutableReference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); let (state2, _) = common::run_instruction(Bytecode::FreezeRef, state1); assert_eq!(state2.stack_len(), 1, "stack len postcondition not met"); @@ -94,7 +94,7 @@ fn bytecode_feezeref() { state2.stack_peek(0), Some(AbstractValue::new_reference( SignatureToken::Reference(Box::new(SignatureToken::U64)), - Kind::Unrestricted + Kind::Copyable )), "stack type postcondition not met" ); @@ -113,7 +113,7 @@ fn bytecode_feezeref_already_immutable() { let mut state1 = AbstractState::new(); state1.stack_push(AbstractValue::new_reference( SignatureToken::Reference(Box::new(SignatureToken::U64)), - Kind::Unrestricted, + Kind::Copyable, )); common::run_instruction(Bytecode::FreezeRef, state1); } diff --git a/language/tools/test-generation/tests/struct_instructions.rs b/language/tools/test-generation/tests/struct_instructions.rs index 2977fcd8baaa..826388c76548 100644 --- a/language/tools/test-generation/tests/struct_instructions.rs +++ b/language/tools/test-generation/tests/struct_instructions.rs @@ -9,8 +9,8 @@ use vm::{ access::ModuleAccess, file_format::{ empty_module, Bytecode, CompiledModule, CompiledModuleMut, FieldDefinition, - FieldDefinitionIndex, IdentifierIndex, Kind, LocalsSignatureIndex, MemberCount, - ModuleHandleIndex, SignatureToken, StructDefinition, StructDefinitionIndex, + FieldDefinitionIndex, IdentifierIndex, Kind, MemberCount, ModuleHandleIndex, + SignatureIndex, SignatureToken, StructDefinition, StructDefinitionIndex, StructFieldInformation, StructHandle, StructHandleIndex, TableIndex, TypeSignature, TypeSignatureIndex, }, @@ -64,7 +64,7 @@ fn generate_module_with_struct(resource: bool) -> CompiledModuleMut { module: ModuleHandleIndex::new(0), name: IdentifierIndex::new((struct_index + offset) as TableIndex), is_nominal_resource: resource, - type_formals: vec![], + type_parameters: vec![], }]; module } @@ -84,11 +84,11 @@ fn create_struct_value(module: &CompiledModule) -> (AbstractValue, Vec Kind::All, (Kind::Resource, _) | (_, Kind::Resource) => Kind::Resource, - (Kind::Unrestricted, Kind::Unrestricted) => Kind::Unrestricted, + (Kind::Copyable, Kind::Copyable) => Kind::Copyable, } }) }; @@ -108,7 +108,7 @@ fn bytecode_pack_signature_not_satisfied() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::Pack(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Pack(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -127,7 +127,7 @@ fn bytecode_pack() { state1.stack_push(abstract_value); } let (state2, _) = common::run_instruction( - Bytecode::Pack(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Pack(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); let struct_value2 = state2.stack_peek(0).expect("struct not added to stack"); @@ -144,7 +144,7 @@ fn bytecode_unpack_signature_not_satisfied() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::Unpack(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Unpack(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -157,7 +157,7 @@ fn bytecode_unpack() { let (struct_value, tokens) = create_struct_value(&state1.module.module); state1.stack_push(struct_value); let (state2, _) = common::run_instruction( - Bytecode::Unpack(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Unpack(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!( @@ -174,7 +174,7 @@ fn bytecode_exists() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); let (state2, _) = common::run_instruction( - Bytecode::Exists(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Exists(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!( @@ -192,7 +192,7 @@ fn bytecode_exists_struct_is_not_resource() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); common::run_instruction( - Bytecode::Exists(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Exists(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -204,7 +204,7 @@ fn bytecode_exists_no_address_on_stack() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::Exists(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::Exists(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -226,7 +226,7 @@ fn bytecode_movefrom() { .struct_def_at(StructDefinitionIndex::new(0)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); let (state2, _) = common::run_instruction( - Bytecode::MoveFrom(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveFrom(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); let struct_value = state2.stack_peek(0).expect("struct not added to stack"); @@ -247,7 +247,7 @@ fn bytecode_movefrom_struct_is_not_resource() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); common::run_instruction( - Bytecode::MoveFrom(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveFrom(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -259,7 +259,7 @@ fn bytecode_movefrom_no_address_on_stack() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::MoveFrom(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveFrom(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -271,7 +271,7 @@ fn bytecode_movetosender() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(create_struct_value(&state1.module.module).0); let (state2, _) = common::run_instruction( - Bytecode::MoveToSender(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveToSender(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!(state2.stack_len(), 0, "stack type postcondition not met"); @@ -285,7 +285,7 @@ fn bytecode_movetosender_struct_is_not_resource() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(create_struct_value(&state1.module.module).0); common::run_instruction( - Bytecode::MoveToSender(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveToSender(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -297,7 +297,7 @@ fn bytecode_movetosender_no_struct_on_stack() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::MoveToSender(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MoveToSender(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -416,7 +416,7 @@ fn bytecode_borrowglobal() { let struct_value = create_struct_value(&state1.module.module).0; state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); let (state2, _) = common::run_instruction( - Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); assert_eq!( @@ -437,7 +437,7 @@ fn bytecode_borrowglobal_struct_is_not_resource() { AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); state1.stack_push(AbstractValue::new_primitive(SignatureToken::Address)); common::run_instruction( - Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } @@ -449,7 +449,7 @@ fn bytecode_borrowglobal_no_address_on_stack() { let state1 = AbstractState::from_locals(module, HashMap::new(), vec![], vec![], CallGraph::new(0)); common::run_instruction( - Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), LocalsSignatureIndex::new(0)), + Bytecode::MutBorrowGlobal(StructDefinitionIndex::new(0), SignatureIndex::new(0)), state1, ); } diff --git a/language/tools/utils/src/module_generation/generator.rs b/language/tools/utils/src/module_generation/generator.rs index cfda9496f15e..38fa5ddfe4c1 100644 --- a/language/tools/utils/src/module_generation/generator.rs +++ b/language/tools/utils/src/module_generation/generator.rs @@ -126,7 +126,7 @@ impl<'a> ModuleGenerator<'a> { let index = self.index(structs.len()); let struct_def = structs[index].value.clone(); let ty_instants = { - let num_typ_params = struct_def.type_formals.len(); + let num_typ_params = struct_def.type_parameters.len(); // NB: Relying on randomness for termination here init!(num_typ_params, self.base_type(ty_param_context)) }; @@ -158,7 +158,7 @@ impl<'a> ModuleGenerator<'a> { } } - fn type_formals(&mut self) -> Vec<(TypeVar, Kind)> { + fn type_parameters(&mut self) -> Vec<(TypeVar, Kind)> { // Don't generate type parameters if we're generating simple types only if self.options.simple_types_only { vec![] @@ -168,7 +168,7 @@ impl<'a> ModuleGenerator<'a> { num_ty_params, ( Spanned::no_loc(TypeVar_::new(self.identifier())), - Kind::Unrestricted, + Kind::Copyable, ) ) } @@ -177,7 +177,7 @@ impl<'a> ModuleGenerator<'a> { // All functions will have unit return type, and an empty body with the exception of a return. // We'll scoop this out and replace it later on in the compiled module that we generate. fn function_signature(&mut self) -> FunctionSignature { - let ty_params = self.type_formals(); + let ty_params = self.type_parameters(); let number_of_args = self.index(self.options.max_function_call_size); let mut formals: Vec<(Var, Type)> = init!(number_of_args, { let param_name = Spanned::no_loc(Var_::new(self.identifier())); @@ -221,7 +221,7 @@ impl<'a> ModuleGenerator<'a> { let locals = init!(num_locals, { ( Spanned::no_loc(Var_::new(self.identifier())), - self.typ(&signature.type_formals), + self.typ(&signature.type_parameters), ) }); let fun = Function_ { @@ -246,12 +246,12 @@ impl<'a> ModuleGenerator<'a> { fn struct_def(&mut self, is_nominal_resource: bool) { let name = StructName::new(self.identifier()); - let type_formals = self.type_formals(); - let fields = self.struct_fields(&type_formals); + let type_parameters = self.type_parameters(); + let fields = self.struct_fields(&type_parameters); let strct = StructDefinition_ { is_nominal_resource, name, - type_formals, + type_parameters, fields, invariants: vec![], }; diff --git a/language/tools/utils/src/module_generation/padding.rs b/language/tools/utils/src/module_generation/padding.rs index 59d381653702..e6bd9e4cca45 100644 --- a/language/tools/utils/src/module_generation/padding.rs +++ b/language/tools/utils/src/module_generation/padding.rs @@ -4,7 +4,7 @@ use crate::module_generation::{options::ModuleGeneratorOptions, utils::random_string}; use libra_types::{account_address::AccountAddress, byte_array::ByteArray, identifier::Identifier}; use rand::{rngs::StdRng, Rng, SeedableRng}; -use vm::file_format::{Bytecode, CompiledModuleMut, LocalsSignature}; +use vm::file_format::{Bytecode, CompiledModuleMut, Signature}; /////////////////////////////////////////////////////////////////////////// // Padding of tables in compiled modules @@ -71,7 +71,7 @@ impl Pad { // Ensure that locals signatures always contain an empty signature fn pad_locals_signatures(&mut self, module: &mut CompiledModuleMut) { if module.locals_signatures.iter().all(|v| !v.is_empty()) { - module.locals_signatures.push(LocalsSignature(Vec::new())); + module.locals_signatures.push(Signature(Vec::new())); } } } diff --git a/language/tools/vm-genesis/src/genesis_gas_schedule.rs b/language/tools/vm-genesis/src/genesis_gas_schedule.rs index 8ca178a868e5..ba5d69fb56ea 100644 --- a/language/tools/vm-genesis/src/genesis_gas_schedule.rs +++ b/language/tools/vm-genesis/src/genesis_gas_schedule.rs @@ -8,7 +8,7 @@ use once_cell::sync::Lazy; use vm::{ file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, FieldDefinitionIndex, FunctionHandleIndex, - StructDefinitionIndex, NO_TYPE_ACTUALS, NUMBER_OF_NATIVE_FUNCTIONS, + StructDefinitionIndex, NO_TYPE_ARGUMENTS, NUMBER_OF_NATIVE_FUNCTIONS, }, gas_schedule::{CostTable, GasCost, GAS_SCHEDULE_NAME, MAXIMUM_NUMBER_OF_GAS_UNITS}, }; @@ -21,12 +21,12 @@ static INITIAL_GAS_SCHEDULE: Lazy> = Lazy::new(|| { use Bytecode::*; let instrs = vec![ ( - MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(774, 1), ), (GetTxnSenderAddress, GasCost::new(30, 1)), ( - MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(917, 1), ), (BrTrue(0), GasCost::new(31, 1)), @@ -69,13 +69,13 @@ static INITIAL_GAS_SCHEDULE: Lazy> = Lazy::new(|| { (Neq, GasCost::new(51, 1)), (Not, GasCost::new(35, 1)), ( - Call(FunctionHandleIndex::new(0), NO_TYPE_ACTUALS), + Call(FunctionHandleIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(197, 1), ), (Le, GasCost::new(47, 1)), (Branch(0), GasCost::new(10, 1)), ( - Unpack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Unpack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(94, 1), ), (Or, GasCost::new(43, 1)), @@ -85,7 +85,7 @@ static INITIAL_GAS_SCHEDULE: Lazy> = Lazy::new(|| { (Mod, GasCost::new(42, 1)), (BrFalse(0), GasCost::new(29, 1)), ( - Exists(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Exists(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(856, 1), ), (GetGasRemaining, GasCost::new(32, 1)), @@ -94,11 +94,11 @@ static INITIAL_GAS_SCHEDULE: Lazy> = Lazy::new(|| { (GetTxnSequenceNumber, GasCost::new(29, 1)), (FreezeRef, GasCost::new(10, 1)), ( - MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(929, 1), ), ( - ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(929, 1), ), (Div, GasCost::new(41, 1)), @@ -106,7 +106,7 @@ static INITIAL_GAS_SCHEDULE: Lazy> = Lazy::new(|| { (LdByteArray(ByteArrayPoolIndex::new(0)), GasCost::new(56, 1)), (Gt, GasCost::new(46, 1)), ( - Pack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Pack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(73, 1), ), ]; diff --git a/language/vm/src/access.rs b/language/vm/src/access.rs index ecf4142c549d..6a870f5b47c9 100644 --- a/language/vm/src/access.rs +++ b/language/vm/src/access.rs @@ -8,9 +8,9 @@ use crate::{ AddressPoolIndex, ByteArrayPoolIndex, CompiledModule, CompiledModuleMut, CompiledScript, FieldDefinition, FieldDefinitionIndex, FunctionDefinition, FunctionDefinitionIndex, FunctionHandle, FunctionHandleIndex, FunctionSignature, FunctionSignatureIndex, - IdentifierIndex, LocalsSignature, LocalsSignatureIndex, MemberCount, ModuleHandle, - ModuleHandleIndex, StructDefinition, StructDefinitionIndex, StructHandle, - StructHandleIndex, TypeSignature, TypeSignatureIndex, + IdentifierIndex, MemberCount, ModuleHandle, ModuleHandleIndex, Signature, SignatureIndex, + StructDefinition, StructDefinitionIndex, StructHandle, StructHandleIndex, TypeSignature, + TypeSignatureIndex, }, internals::ModuleIndex, }; @@ -66,7 +66,7 @@ pub trait ModuleAccess: Sync { &self.as_module().as_inner().function_signatures[idx.into_index()] } - fn locals_signature_at(&self, idx: LocalsSignatureIndex) -> &LocalsSignature { + fn locals_signature_at(&self, idx: SignatureIndex) -> &Signature { &self.as_module().as_inner().locals_signatures[idx.into_index()] } @@ -120,7 +120,7 @@ pub trait ModuleAccess: Sync { &self.as_module().as_inner().function_signatures } - fn locals_signatures(&self) -> &[LocalsSignature] { + fn locals_signatures(&self) -> &[Signature] { &self.as_module().as_inner().locals_signatures } @@ -213,7 +213,7 @@ pub trait ScriptAccess: Sync { &self.as_script().as_inner().function_signatures[idx.into_index()] } - fn locals_signature_at(&self, idx: LocalsSignatureIndex) -> &LocalsSignature { + fn locals_signature_at(&self, idx: SignatureIndex) -> &Signature { &self.as_script().as_inner().locals_signatures[idx.into_index()] } @@ -249,7 +249,7 @@ pub trait ScriptAccess: Sync { &self.as_script().as_inner().function_signatures } - fn locals_signatures(&self) -> &[LocalsSignature] { + fn locals_signatures(&self) -> &[Signature] { &self.as_script().as_inner().locals_signatures } diff --git a/language/vm/src/check_bounds.rs b/language/vm/src/check_bounds.rs index 3aded8993119..680a6ebe78f5 100644 --- a/language/vm/src/check_bounds.rs +++ b/language/vm/src/check_bounds.rs @@ -5,8 +5,8 @@ use crate::{ errors::{append_err_info, bounds_error, bytecode_offset_err, verification_error}, file_format::{ Bytecode, CodeUnit, CompiledModuleMut, FieldDefinition, FunctionDefinition, FunctionHandle, - FunctionSignature, Kind, LocalsSignature, LocalsSignatureIndex, ModuleHandle, - SignatureToken, StructDefinition, StructFieldInformation, StructHandle, TypeSignature, + FunctionSignature, Kind, ModuleHandle, Signature, SignatureIndex, SignatureToken, + StructDefinition, StructFieldInformation, StructHandle, TypeSignature, }, internals::ModuleIndex, IndexKind, @@ -81,7 +81,7 @@ impl<'a> BoundsChecker<'a> { locals .check_struct_handles(&self.module.struct_handles) .into_iter() - .map(move |err| append_err_info(err, IndexKind::LocalsSignature, idx)) + .map(move |err| append_err_info(err, IndexKind::Signature, idx)) }) .collect(), ); @@ -110,7 +110,7 @@ impl<'a> BoundsChecker<'a> { let sh = &self.module.struct_handles[field_def.struct_.0 as usize]; let sig = &self.module.type_signatures[field_def.signature.0 as usize]; - sig.check_type_parameters(sh.type_formals.len()) + sig.check_type_parameters(sh.type_parameters.len()) }); let errors_code_units = self.module.function_defs.iter().flat_map(|function_def| { @@ -297,19 +297,19 @@ impl TypeSignature { self.0.check_struct_handles(struct_handles) } - fn check_type_parameters(&self, type_formals_len: usize) -> Vec { - self.0.check_type_parameters(type_formals_len) + fn check_type_parameters(&self, type_parameters_len: usize) -> Vec { + self.0.check_type_parameters(type_parameters_len) } } impl BoundsCheck<&CompiledModuleMut> for FunctionSignature { #[inline] fn check_bounds(&self, module: &CompiledModuleMut) -> Vec { - self.return_types + self.return_ .iter() .map(|token| token.check_bounds((module, self))) .chain( - self.arg_types + self.parameters .iter() .map(|token| token.check_bounds((module, self))), ) @@ -318,11 +318,11 @@ impl BoundsCheck<&CompiledModuleMut> for FunctionSignature { } } -impl LocalsSignature { - fn check_type_parameters(&self, type_formals_len: usize) -> Vec { +impl Signature { + fn check_type_parameters(&self, type_parameters_len: usize) -> Vec { self.0 .iter() - .flat_map(|ty| ty.check_type_parameters(type_formals_len)) + .flat_map(|ty| ty.check_type_parameters(type_parameters_len)) .collect() } @@ -344,22 +344,22 @@ impl BoundsCheck<(&[StructHandle], usize)> for SignatureToken { } impl SignatureToken { - pub fn check_type_parameters(&self, type_formals_len: usize) -> Vec { + pub fn check_type_parameters(&self, type_parameters_len: usize) -> Vec { match self { SignatureToken::Struct(_, type_actuals) => type_actuals .iter() - .flat_map(|ty| ty.check_type_parameters(type_formals_len)) + .flat_map(|ty| ty.check_type_parameters(type_parameters_len)) .collect(), SignatureToken::Reference(ty) | SignatureToken::MutableReference(ty) => { - ty.check_type_parameters(type_formals_len) + ty.check_type_parameters(type_parameters_len) } SignatureToken::TypeParameter(idx) => { let idx = *idx as usize; - if idx >= type_formals_len { + if idx >= type_parameters_len { vec![bounds_error( IndexKind::TypeParameter, idx, - type_formals_len, + type_parameters_len, StatusCode::INDEX_OUT_OF_BOUNDS, )] } else { @@ -400,7 +400,7 @@ impl BoundsCheck<(&CompiledModuleMut, &FunctionSignature)> for SignatureToken { fn check_bounds(&self, context: (&CompiledModuleMut, &FunctionSignature)) -> Vec { self.check_bounds(( context.0.struct_handles.as_slice(), - context.1.type_formals.as_slice(), + context.1.type_parameters.as_slice(), )) } } @@ -409,7 +409,7 @@ impl BoundsCheck<(&CompiledModuleMut, &StructHandle)> for SignatureToken { fn check_bounds(&self, context: (&CompiledModuleMut, &StructHandle)) -> Vec { self.check_bounds(( context.0.struct_handles.as_slice(), - context.1.type_formals.as_slice(), + context.1.type_parameters.as_slice(), )) } } @@ -417,14 +417,15 @@ impl BoundsCheck<(&CompiledModuleMut, &StructHandle)> for SignatureToken { fn check_type_actuals_bounds( context: (&CompiledModuleMut, &FunctionSignature), bytecode_offset: usize, - idx: LocalsSignatureIndex, + idx: SignatureIndex, ) -> Vec { let (module, function_sig) = context; let errs = check_code_unit_bounds_impl(&module.locals_signatures, bytecode_offset, idx); if !errs.is_empty() { return errs; } - module.locals_signatures[idx.0 as usize].check_type_parameters(function_sig.type_formals.len()) + module.locals_signatures[idx.0 as usize] + .check_type_parameters(function_sig.type_parameters.len()) } impl BoundsCheck<(&CompiledModuleMut, &FunctionSignature)> for CodeUnit { diff --git a/language/vm/src/deserializer.rs b/language/vm/src/deserializer.rs index 769e7eb321fa..a9863097fbde 100644 --- a/language/vm/src/deserializer.rs +++ b/language/vm/src/deserializer.rs @@ -199,7 +199,7 @@ trait CommonTables { fn get_type_signatures(&mut self) -> &mut TypeSignaturePool; fn get_function_signatures(&mut self) -> &mut FunctionSignaturePool; - fn get_locals_signatures(&mut self) -> &mut LocalsSignaturePool; + fn get_locals_signatures(&mut self) -> &mut SignaturePool; fn get_identifiers(&mut self) -> &mut IdentifierPool; fn get_byte_array_pool(&mut self) -> &mut ByteArrayPool; @@ -227,7 +227,7 @@ impl CommonTables for CompiledScriptMut { &mut self.function_signatures } - fn get_locals_signatures(&mut self) -> &mut LocalsSignaturePool { + fn get_locals_signatures(&mut self) -> &mut SignaturePool { &mut self.locals_signatures } @@ -265,7 +265,7 @@ impl CommonTables for CompiledModuleMut { &mut self.function_signatures } - fn get_locals_signatures(&mut self) -> &mut LocalsSignaturePool { + fn get_locals_signatures(&mut self) -> &mut SignaturePool { &mut self.locals_signatures } @@ -451,12 +451,12 @@ fn load_struct_handles( let module_handle = read_uleb_u16_internal(&mut cursor)?; let name = read_uleb_u16_internal(&mut cursor)?; let is_nominal_resource = load_nominal_resource_flag(&mut cursor)?; - let type_formals = load_kinds(&mut cursor)?; + let type_parameters = load_kinds(&mut cursor)?; struct_handles.push(StructHandle { module: ModuleHandleIndex(module_handle), name: IdentifierIndex(name), is_nominal_resource, - type_formals, + type_parameters, }); } Ok(()) @@ -620,11 +620,11 @@ fn load_function_signatures( let token = load_signature_token(&mut cursor)?; args_signature.push(token); } - let type_formals = load_kinds(&mut cursor)?; + let type_parameters = load_kinds(&mut cursor)?; function_signatures.push(FunctionSignature { - return_types: returns_signature, - arg_types: args_signature, - type_formals, + return_: returns_signature, + parameters: args_signature, + type_parameters, }); } Ok(()) @@ -634,7 +634,7 @@ fn load_function_signatures( fn load_locals_signatures( binary: &[u8], table: &Table, - locals_signatures: &mut LocalsSignaturePool, + locals_signatures: &mut SignaturePool, ) -> BinaryLoaderResult<()> { let start = table.offset as usize; let end = start + table.count as usize; @@ -655,7 +655,7 @@ fn load_locals_signatures( local_signature.push(token); } - locals_signatures.push(LocalsSignature(local_signature)); + locals_signatures.push(Signature(local_signature)); } Ok(()) } @@ -721,7 +721,7 @@ fn load_kind(cursor: &mut Cursor<&[u8]>) -> BinaryLoaderResult { if let Ok(byte) = cursor.read_u8() { Ok(match SerializedKind::from_u8(byte)? { SerializedKind::ALL => Kind::All, - SerializedKind::UNRESTRICTED => Kind::Unrestricted, + SerializedKind::COPYABLE => Kind::Copyable, SerializedKind::RESOURCE => Kind::Resource, }) } else { @@ -859,7 +859,7 @@ fn load_code_unit(cursor: &mut Cursor<&[u8]>) -> BinaryLoaderResult { let mut code_unit = CodeUnit { max_stack_size, - locals: LocalsSignatureIndex(locals), + locals: SignatureIndex(locals), code: vec![], }; @@ -957,17 +957,17 @@ fn load_code(cursor: &mut Cursor<&[u8]>, code: &mut Vec) -> BinaryLoad Opcodes::CALL => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::Call(FunctionHandleIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::Call(FunctionHandleIndex(idx), SignatureIndex(types_idx)) } Opcodes::PACK => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::Pack(StructDefinitionIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::Pack(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::UNPACK => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::Unpack(StructDefinitionIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::Unpack(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::READ_REF => Bytecode::ReadRef, Opcodes::WRITE_REF => Bytecode::WriteRef, @@ -998,33 +998,27 @@ fn load_code(cursor: &mut Cursor<&[u8]>, code: &mut Vec) -> BinaryLoad Opcodes::EXISTS => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::Exists(StructDefinitionIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::Exists(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::MUT_BORROW_GLOBAL => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::MutBorrowGlobal( - StructDefinitionIndex(idx), - LocalsSignatureIndex(types_idx), - ) + Bytecode::MutBorrowGlobal(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::IMM_BORROW_GLOBAL => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::ImmBorrowGlobal( - StructDefinitionIndex(idx), - LocalsSignatureIndex(types_idx), - ) + Bytecode::ImmBorrowGlobal(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::MOVE_FROM => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::MoveFrom(StructDefinitionIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::MoveFrom(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::MOVE_TO => { let idx = read_uleb_u16_internal(cursor)?; let types_idx = read_uleb_u16_internal(cursor)?; - Bytecode::MoveToSender(StructDefinitionIndex(idx), LocalsSignatureIndex(types_idx)) + Bytecode::MoveToSender(StructDefinitionIndex(idx), SignatureIndex(types_idx)) } Opcodes::GET_TXN_SEQUENCE_NUMBER => Bytecode::GetTxnSequenceNumber, Opcodes::GET_TXN_PUBLIC_KEY => Bytecode::GetTxnPublicKey, @@ -1137,7 +1131,7 @@ impl SerializedKind { fn from_u8(value: u8) -> BinaryLoaderResult { match value { 0x1 => Ok(SerializedKind::ALL), - 0x2 => Ok(SerializedKind::UNRESTRICTED), + 0x2 => Ok(SerializedKind::COPYABLE), 0x3 => Ok(SerializedKind::RESOURCE), _ => Err(VMStatus::new(StatusCode::UNKNOWN_SERIALIZED_TYPE)), } diff --git a/language/vm/src/file_format.rs b/language/vm/src/file_format.rs index 735d1b83b025..e3e866735f37 100644 --- a/language/vm/src/file_format.rs +++ b/language/vm/src/file_format.rs @@ -105,6 +105,26 @@ define_index! { kind: FunctionHandle, doc: "Index into the `FunctionHandle` table.", } +define_index! { + name: FieldHandleIndex, + kind: FieldHandle, + doc: "Index into the `FieldHandle` table.", +} +define_index! { + name: StructInstantiationIndex, + kind: StructInstantiation, + doc: "Index into the `StructInstantiation` table.", +} +define_index! { + name: FunctionInstantiationIndex, + kind: FunctionInstantiation, + doc: "Index into the `FunctionInstantiation` table.", +} +define_index! { + name: FieldInstantiationIndex, + kind: FieldInstantiation, + doc: "Index into the `FieldInstantiation` table.", +} define_index! { name: IdentifierIndex, kind: Identifier, @@ -131,9 +151,9 @@ define_index! { doc: "Index into the `FunctionSignature` table.", } define_index! { - name: LocalsSignatureIndex, - kind: LocalsSignature, - doc: "Index into the `LocalsSignature` table.", + name: SignatureIndex, + kind: Signature, + doc: "Index into the `Signature` table.", } define_index! { name: StructDefinitionIndex, @@ -160,6 +180,8 @@ pub type MemberCount = u16; /// Index into the code stream for a jump. The offset is relative to the beginning of /// the instruction stream. pub type CodeOffset = u16; +/// Index of a field into the vector of fields of a `Struct`. +pub type FieldOffset = u8; /// The pool of identifiers. pub type IdentifierPool = Vec; @@ -175,9 +197,9 @@ pub type AddressPool = Vec; pub type TypeSignaturePool = Vec; /// The pool of `FunctionSignature` instances. pub type FunctionSignaturePool = Vec; -/// The pool of `LocalsSignature` instances. Every function definition must define the set of +/// The pool of `Signature` instances. Every function definition must define the set of /// locals used and their types. -pub type LocalsSignaturePool = Vec; +pub type SignaturePool = Vec; // TODO: "" only passes the validator for identifiers because it is special cased. Whenever // "" is removed, so should the special case in identifier.rs. @@ -186,9 +208,9 @@ pub fn self_module_name() -> &'static IdentStr { } /// Index 0 into the LocalsSignaturePool, which is guaranteed to be an empty list. -/// Used to represent function/struct instantiation with no type actuals -- effectively +/// Used to represent function/struct instantiation with no type arguments -- effectively /// non-generic functions and structs. -pub const NO_TYPE_ACTUALS: LocalsSignatureIndex = LocalsSignatureIndex(0); +pub const NO_TYPE_ARGUMENTS: SignatureIndex = SignatureIndex(0); // HANDLES: // Handles are structs that accompany opcodes that need references: a type reference, @@ -248,7 +270,7 @@ pub struct StructHandle { /// If `is_nominal_resource` is true, it is a *nominal resource* pub is_nominal_resource: bool, /// The type formals (identified by their index into the vec) and their kind constraints - pub type_formals: Vec, + pub type_parameters: Vec, } /// A `FunctionHandle` is a reference to a function. It is composed by a @@ -270,6 +292,15 @@ pub struct FunctionHandle { pub signature: FunctionSignatureIndex, } +/// A field access info (owner type and offset) +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] +#[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))] +pub struct FieldHandle { + owner: StructDefinitionIndex, + field: FieldOffset, +} + // DEFINITIONS: // Definitions are the module code. So the set of types and functions in the module. @@ -288,6 +319,46 @@ pub enum StructFieldInformation { }, } +// +// Instantiations +// +// Instantiations point to a generic handle and its instantiation. +// The instantiation can be partial. +// So, for example, `S`, `S`, `S`, `S, address>` are all +// `StructInstantiation`s + +/// A complete or partial instantiation of a generic struct +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] +#[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))] +pub struct StructInstantiation { + pub handle: StructHandleIndex, + pub type_arguments: SignatureIndex, +} + +/// A complete or partial instantiation of a function +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] +#[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))] +pub struct FunctionInstantiation { + pub handle: FunctionHandleIndex, + pub type_arguments: SignatureIndex, +} + +/// A complete or partial instantiation of a field (or the type of it). +/// +/// A `FieldInstantiation` points to a generic `FieldHandle` and the instantiation +/// of the owner type. +/// E.g. for `S.f` where `f` is a field of any type, `instantiation` +/// would be `[u8, boo]` +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] +#[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))] +pub struct FieldInstantiation { + pub handle: FieldHandleIndex, + pub type_arguments: SignatureIndex, +} + /// A `StructDefinition` is a type definition. It either indicates it is native or // defines all the user-specified fields declared on the type. #[derive(Clone, Debug, Eq, PartialEq)] @@ -318,7 +389,7 @@ impl StructDefinition { #[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] #[cfg_attr(any(test, feature = "fuzzing"), proptest(no_params))] pub struct FieldDefinition { - /// The type (resource or unrestricted) the field is defined on. + /// The type (resource or copyable) the field is defined on. pub struct_: StructHandleIndex, /// The name of the field. pub name: IdentifierIndex, @@ -343,7 +414,7 @@ pub struct FunctionDefinition { /// /// Not in the signature as it is not needed outside of the declaring module /// - /// Note, there is no LocalsSignatureIndex with each struct definition index, as global + /// Note, there is no SignatureIndex with each struct definition index, as global /// resources cannot currently take type arguments pub acquires_global_resources: Vec, /// Code for this function. @@ -391,25 +462,25 @@ pub struct FunctionSignature { any(test, feature = "fuzzing"), proptest(strategy = "vec(any::(), 0..=params)") )] - pub return_types: Vec, + pub return_: Vec, /// The list of arguments to the function. #[cfg_attr( any(test, feature = "fuzzing"), proptest(strategy = "vec(any::(), 0..=params)") )] - pub arg_types: Vec, + pub parameters: Vec, /// The type formals (identified by their index into the vec) and their kind constraints - pub type_formals: Vec, + pub type_parameters: Vec, } -/// A `LocalsSignature` is the list of locals used by a function. +/// A `Signature` is the list of locals used by a function. /// /// Locals include the arguments to the function from position `0` to argument `count - 1`. /// The remaining elements are the type of each local. #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] #[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] #[cfg_attr(any(test, feature = "fuzzing"), proptest(params = "usize"))] -pub struct LocalsSignature( +pub struct Signature( #[cfg_attr( any(test, feature = "fuzzing"), proptest(strategy = "vec(any::(), 0..=params)") @@ -417,8 +488,8 @@ pub struct LocalsSignature( pub Vec, ); -impl LocalsSignature { - /// Length of the `LocalsSignature`. +impl Signature { + /// Length of the `Signature`. #[inline] pub fn len(&self) -> usize { self.0.len() @@ -437,23 +508,23 @@ pub type TypeParameterIndex = u16; /// A `Kind` classifies types into sets with rules each set must follow. /// -/// Currently there are three kinds in Move: `All`, `Resource` and `Unrestricted`. +/// Currently there are three kinds in Move: `All`, `Resource` and `Copyable`. #[derive(Debug, Clone, Eq, Copy, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(any(test, feature = "fuzzing"), derive(Arbitrary))] pub enum Kind { /// Represents the super set of all types. The type might actually be a `Resource` or - /// `Unrestricted` A type might be in this set if it is not known to be a `Resource` or - /// `Unrestricted` + /// `Copyable` A type might be in this set if it is not known to be a `Resource` or + /// `Copyable` /// - This occurs when there is a type parameter with this kind as a constraint All, /// `Resource` types must follow move semantics and various resource safety rules, namely: /// - `Resource` values cannot be copied /// - `Resource` values cannot be popped, i.e. they must be used Resource, - /// `Unrestricted` types do not need to follow the `Resource` rules. - /// - `Unrestricted` values can be copied - /// - `Unrestricted` values can be popped - Unrestricted, + /// `Copyable` types do not need to follow the `Resource` rules. + /// - `Copyable` values can be copied + /// - `Copyable` values can be popped + Copyable, } impl Kind { @@ -463,18 +534,18 @@ impl Kind { use Kind::*; match (self, k) { - (_, All) | (Resource, Resource) | (Unrestricted, Unrestricted) => true, + (_, All) | (Resource, Resource) | (Copyable, Copyable) => true, _ => false, } } /// Helper function to determine the kind of a struct instance by taking the kind of a type - /// actual and join it with the existing partial result. + /// argument and join it with the existing partial result. pub fn join(self, other: Kind) -> Kind { match (self, other) { (Kind::All, _) | (_, Kind::All) => Kind::All, (Kind::Resource, _) | (_, Kind::Resource) => Kind::Resource, - (Kind::Unrestricted, Kind::Unrestricted) => Kind::Unrestricted, + (Kind::Copyable, Kind::Copyable) => Kind::Copyable, } } } @@ -502,7 +573,7 @@ pub enum SignatureToken { Address, /// Vector Vector(Box), - /// MOVE user type, resource or unrestricted + /// MOVE user type, resource or copyable Struct(StructHandleIndex, Vec), /// Reference to a type. Reference(Box), @@ -526,7 +597,7 @@ impl Arbitrary for SignatureToken { Just(U64), Just(ByteArray), Just(Address), - // TODO: generate type actuals when generics is implemented + // TODO: generate type arguments when generics is implemented any::().prop_map(|sh_idx| Struct(sh_idx, vec![])), any::().prop_map(TypeParameter), ]; @@ -583,7 +654,7 @@ impl SignatureToken { } } - /// Returns the type actuals if the signature token is a reference to a struct instance. + /// Returns the type arguments if the signature token is a reference to a struct instance. pub fn get_type_actuals_from_reference(&self) -> Option<&[SignatureToken]> { use SignatureToken::*; @@ -616,7 +687,7 @@ impl SignatureToken { } /// Returns the `StructHandleIndex` for a `SignatureToken` that contains a reference to a user - /// defined type (a resource or unrestricted type). + /// defined type (a resource or copyable type). #[inline] pub fn struct_index(&self) -> Option { use SignatureToken::*; @@ -707,7 +778,7 @@ impl SignatureToken { } } - /// Creating a new type by Substituting the type variables with type actuals. + /// Creating a new type by Substituting the type variables with type arguments. pub fn substitute(&self, tys: &[SignatureToken]) -> SignatureToken { use SignatureToken::*; @@ -719,9 +790,9 @@ impl SignatureToken { ByteArray => ByteArray, Address => Address, Vector(ty) => Vector(Box::new(ty.substitute(tys))), - Struct(idx, actuals) => Struct( + Struct(idx, arguments) => Struct( *idx, - actuals + arguments .iter() .map(|ty| ty.substitute(tys)) .collect::>(), @@ -740,21 +811,21 @@ impl SignatureToken { /// Returns the kind of the signature token in the given context (module, function/struct). /// The context is needed to determine the kinds of structs & type variables. pub fn kind( - (struct_handles, type_formals): (&[StructHandle], &[Kind]), + (struct_handles, type_parameters): (&[StructHandle], &[Kind]), ty: &SignatureToken, ) -> Kind { use SignatureToken::*; match ty { - // The primitive types & references have kind unrestricted. + // The primitive types & references have kind copyable. Bool | U8 | U64 | U128 | ByteArray | Address | Reference(_) | MutableReference(_) => { - Kind::Unrestricted + Kind::Copyable } // To get the kind of a type parameter, we lookup its constraint in the formals. - TypeParameter(idx) => type_formals[*idx as usize], + TypeParameter(idx) => type_parameters[*idx as usize], - Vector(ty) => Self::kind((struct_handles, type_formals), ty), + Vector(ty) => Self::kind((struct_handles, type_parameters), ty), Struct(idx, tys) => { // Get the struct handle at idx. Note the index could be out of bounds. @@ -764,21 +835,21 @@ impl SignatureToken { return Kind::Resource; } - // Gather the kinds of the type actuals. + // Gather the kinds of the type arguments. let kinds = tys .iter() - .map(|ty| Self::kind((struct_handles, type_formals), ty)) + .map(|ty| Self::kind((struct_handles, type_parameters), ty)) .collect::>(); // Derive the kind of the struct. - // - If any of the type actuals is `all`, then the struct is `all`. + // - If any of the type arguments is `all`, then the struct is `all`. // - `all` means some part of the type can be either `resource` or - // `unrestricted`. + // `copyable`. // - Therefore it is also impossible to determine the kind of the type as a // whole, and thus `all`. - // - If none of the type actuals is `all`, then the struct is a resource if - // and only if one of the type actuals is `resource`. - kinds.iter().cloned().fold(Kind::Unrestricted, Kind::join) + // - If none of the type arguments is `all`, then the struct is a resource if + // and only if one of the type arguments is `resource`. + kinds.iter().cloned().fold(Kind::Copyable, Kind::join) } } } @@ -792,7 +863,7 @@ pub struct CodeUnit { /// Max stack size for the function - currently unused. pub max_stack_size: u16, /// List of locals type. All locals are typed. - pub locals: LocalsSignatureIndex, + pub locals: SignatureIndex, /// Code stream, function body. #[cfg_attr( any(test, feature = "fuzzing"), @@ -820,7 +891,7 @@ impl CodeUnit { #[num_variants = "NUM_INSTRUCTIONS"] pub enum Bytecode { /// Pop and discard the value at the top of the stack. - /// The value on the stack must be an unrestricted type. + /// The value on the stack must be an copyable type. /// /// Stack transition: /// @@ -946,7 +1017,7 @@ pub enum Bytecode { /// /// ```..., arg(1), arg(2), ..., arg(n) -> ..., return_value(1), return_value(2), ..., /// return_value(k)``` - Call(FunctionHandleIndex, LocalsSignatureIndex), + Call(FunctionHandleIndex, SignatureIndex), /// Create an instance of the type specified via `StructHandleIndex` and push it on the stack. /// The values of the fields of the struct, in the order they appear in the struct declaration, /// must be pushed on the stack. All fields must be provided. @@ -956,7 +1027,7 @@ pub enum Bytecode { /// Stack transition: /// /// ```..., field(1)_value, field(2)_value, ..., field(n)_value -> ..., instance_value``` - Pack(StructDefinitionIndex, LocalsSignatureIndex), + Pack(StructDefinitionIndex, SignatureIndex), /// Destroy an instance of a type and push the values bound to each field on the /// stack. /// @@ -969,7 +1040,7 @@ pub enum Bytecode { /// Stack transition: /// /// ```..., instance_value -> ..., field(1)_value, field(2)_value, ..., field(n)_value``` - Unpack(StructDefinitionIndex, LocalsSignatureIndex), + Unpack(StructDefinitionIndex, SignatureIndex), /// Read a reference. The reference is on the stack, it is consumed and the value read is /// pushed on the stack. /// @@ -983,7 +1054,7 @@ pub enum Bytecode { /// Write to a reference. The reference and the value are on the stack and are consumed. /// /// - /// The reference must be to an unrestricted type because Resources cannot be overwritten. + /// The reference must be to an copyable type because Resources cannot be overwritten. /// /// Stack transition: /// @@ -1033,7 +1104,7 @@ pub enum Bytecode { /// Stack transition: /// /// ```..., address_value -> ..., reference_value``` - MutBorrowGlobal(StructDefinitionIndex, LocalsSignatureIndex), + MutBorrowGlobal(StructDefinitionIndex, SignatureIndex), /// Return an immutable reference to an instance of type `StructDefinitionIndex` published at /// the address passed as argument. Abort execution if such an object does not exist or if a /// reference has already been handed out. @@ -1041,7 +1112,7 @@ pub enum Bytecode { /// Stack transition: /// /// ```..., address_value -> ..., reference_value``` - ImmBorrowGlobal(StructDefinitionIndex, LocalsSignatureIndex), + ImmBorrowGlobal(StructDefinitionIndex, SignatureIndex), /// Add the 2 u64 at the top of the stack and pushes the result on the stack. /// The operation aborts the transaction in case of overflow. /// @@ -1195,21 +1266,21 @@ pub enum Bytecode { /// Stack transition: /// /// ```..., address_value -> ..., bool_value``` - Exists(StructDefinitionIndex, LocalsSignatureIndex), + Exists(StructDefinitionIndex, SignatureIndex), /// Move the instance of type StructDefinitionIndex, at the address at the top of the stack. /// Abort execution if such an object does not exist. /// /// Stack transition: /// /// ```..., address_value -> ..., value``` - MoveFrom(StructDefinitionIndex, LocalsSignatureIndex), + MoveFrom(StructDefinitionIndex, SignatureIndex), /// Move the instance at the top of the stack to the address of the sender. /// Abort execution if an object of type StructDefinitionIndex already exists in address. /// /// Stack transition: /// /// ```..., value -> ...``` - MoveToSender(StructDefinitionIndex, LocalsSignatureIndex), + MoveToSender(StructDefinitionIndex, SignatureIndex), /// Get the sequence number submitted with the transaction and pushes it on the stack. /// /// Stack transition: @@ -1410,12 +1481,17 @@ pub struct CompiledScriptMut { /// Handles to external/imported functions. pub function_handles: Vec, + /// Struct instantiations. + pub struct_instantiations: Vec, + /// Function instantiations. + pub function_instantiations: Vec, + /// Type pool. All external types referenced by the transaction. pub type_signatures: TypeSignaturePool, /// Function signature pool. The signatures of the function referenced by the transaction. pub function_signatures: FunctionSignaturePool, /// Locals signature pool. The signature of the locals in `main`. - pub locals_signatures: LocalsSignaturePool, + pub locals_signatures: SignaturePool, /// All identifiers used in this transaction. pub identifiers: IdentifierPool, @@ -1469,6 +1545,11 @@ impl CompiledScriptMut { module_handles: self.module_handles, struct_handles: self.struct_handles, function_handles: self.function_handles, + field_handles: vec![], + + struct_instantiations: self.struct_instantiations, + function_instantiations: self.function_instantiations, + field_instantiations: vec![], type_signatures: self.type_signatures, function_signatures: self.function_signatures, @@ -1504,6 +1585,15 @@ pub struct CompiledModuleMut { pub struct_handles: Vec, /// Handles to external and internal functions. pub function_handles: Vec, + /// Handles to fields. + pub field_handles: Vec, + + /// Struct instantiations. + pub struct_instantiations: Vec, + /// Function instantiations. + pub function_instantiations: Vec, + /// Field instantiations. + pub field_instantiations: Vec, /// Type pool. A definition for all types used in the module. pub type_signatures: TypeSignaturePool, @@ -1512,7 +1602,7 @@ pub struct CompiledModuleMut { pub function_signatures: FunctionSignaturePool, /// Locals signature pool. The signature for all locals of the functions defined in /// the module. - pub locals_signatures: LocalsSignaturePool, + pub locals_signatures: SignaturePool, /// All identifiers used in this module. pub identifiers: IdentifierPool, @@ -1548,7 +1638,7 @@ impl Arbitrary for CompiledScriptMut { ( vec(any::(), 0..=size), vec(any_with::(size), 0..=size), - vec(any_with::(size), 0..=size), + vec(any_with::(size), 0..=size), ), ( vec(any::(), 0..=size), @@ -1568,6 +1658,8 @@ impl Arbitrary for CompiledScriptMut { module_handles, struct_handles, function_handles, + struct_instantiations: vec![], + function_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -1598,7 +1690,7 @@ impl Arbitrary for CompiledModuleMut { ( vec(any::(), 0..=size), vec(any_with::(size), 0..=size), - vec(any_with::(size), 0..=size), + vec(any_with::(size), 0..=size), ), ( vec(any::(), 0..=size), @@ -1622,6 +1714,10 @@ impl Arbitrary for CompiledModuleMut { module_handles, struct_handles, function_handles, + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures, function_signatures, locals_signatures, @@ -1645,21 +1741,24 @@ impl CompiledModuleMut { IndexKind::ModuleHandle => self.module_handles.len(), IndexKind::StructHandle => self.struct_handles.len(), IndexKind::FunctionHandle => self.function_handles.len(), + IndexKind::FieldHandle => self.field_handles.len(), + IndexKind::StructInstantiation => self.struct_instantiations.len(), + IndexKind::FunctionInstantiation => self.function_instantiations.len(), + IndexKind::FieldInstantiation => self.field_instantiations.len(), IndexKind::StructDefinition => self.struct_defs.len(), IndexKind::FieldDefinition => self.field_defs.len(), IndexKind::FunctionDefinition => self.function_defs.len(), IndexKind::TypeSignature => self.type_signatures.len(), IndexKind::FunctionSignature => self.function_signatures.len(), - IndexKind::LocalsSignature => self.locals_signatures.len(), + IndexKind::Signature => self.locals_signatures.len(), IndexKind::Identifier => self.identifiers.len(), IndexKind::ByteArrayPool => self.byte_array_pool.len(), IndexKind::AddressPool => self.address_pool.len(), // XXX these two don't seem to belong here other @ IndexKind::LocalPool | other @ IndexKind::CodeDefinition - | other @ IndexKind::TypeParameter => { - unreachable!("invalid kind for count: {:?}", other) - } + | other @ IndexKind::TypeParameter + | other @ IndexKind::FieldOffset => unreachable!("invalid kind for count: {:?}", other), } } @@ -1724,6 +1823,9 @@ impl CompiledModule { struct_handles: inner.struct_handles, function_handles: inner.function_handles, + struct_instantiations: inner.struct_instantiations, + function_instantiations: inner.function_instantiations, + type_signatures: inner.type_signatures, function_signatures: inner.function_signatures, locals_signatures: inner.locals_signatures, @@ -1751,9 +1853,13 @@ pub fn empty_module() -> CompiledModuleMut { field_defs: vec![], struct_handles: vec![], function_handles: vec![], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], type_signatures: vec![], function_signatures: vec![], - locals_signatures: vec![LocalsSignature(vec![])], + locals_signatures: vec![Signature(vec![])], byte_array_pool: vec![], } } @@ -1769,9 +1875,9 @@ pub fn basic_test_module() -> CompiledModuleMut { let mut m = empty_module(); m.function_signatures.push(FunctionSignature { - return_types: vec![], - arg_types: vec![], - type_formals: vec![], + return_: vec![], + parameters: vec![], + type_parameters: vec![], }); m.function_handles.push(FunctionHandle { @@ -1788,7 +1894,7 @@ pub fn basic_test_module() -> CompiledModuleMut { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 0, - locals: LocalsSignatureIndex::new(0), + locals: SignatureIndex::new(0), code: vec![], }, }); @@ -1797,7 +1903,7 @@ pub fn basic_test_module() -> CompiledModuleMut { module: ModuleHandleIndex::new(0), name: IdentifierIndex::new(m.identifiers.len() as u16), is_nominal_resource: false, - type_formals: vec![], + type_parameters: vec![], }); m.identifiers .push(Identifier::new("Bar".to_string()).unwrap()); @@ -1832,9 +1938,9 @@ pub fn dummy_procedure_module(code: Vec) -> CompiledModule { fun_def.code = code_unit; module.function_signatures.push(FunctionSignature { - arg_types: vec![], - return_types: vec![], - type_formals: vec![], + parameters: vec![], + return_: vec![], + type_parameters: vec![], }); let fun_handle = FunctionHandle { module: ModuleHandleIndex(0), @@ -1853,11 +1959,11 @@ pub fn empty_script() -> CompiledScriptMut { let self_module_name = self_module_name().to_owned(); let main_name = Identifier::new("main").unwrap(); let void_void_sig = FunctionSignature { - arg_types: vec![], - return_types: vec![], - type_formals: vec![], + parameters: vec![], + return_: vec![], + type_parameters: vec![], }; - let no_args_no_locals = LocalsSignature(vec![]); + let no_args_no_locals = Signature(vec![]); let self_module_handle = ModuleHandle { address: AddressPoolIndex(0), name: IdentifierIndex(0), @@ -1869,7 +1975,7 @@ pub fn empty_script() -> CompiledScriptMut { }; let code = CodeUnit { max_stack_size: 1, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Bytecode::Ret], }; let main_def = FunctionDefinition { @@ -1883,6 +1989,9 @@ pub fn empty_script() -> CompiledScriptMut { struct_handles: vec![], function_handles: vec![main], + struct_instantiations: vec![], + function_instantiations: vec![], + type_signatures: vec![], function_signatures: vec![void_void_sig], locals_signatures: vec![no_args_no_locals], diff --git a/language/vm/src/file_format_common.rs b/language/vm/src/file_format_common.rs index 4e5d60632842..51a70c22d561 100644 --- a/language/vm/src/file_format_common.rs +++ b/language/vm/src/file_format_common.rs @@ -99,7 +99,7 @@ pub enum SerializedNominalResourceFlag { #[derive(Clone, Copy, Debug)] pub enum SerializedKind { ALL = 0x1, - UNRESTRICTED = 0x2, + COPYABLE = 0x2, RESOURCE = 0x3, } diff --git a/language/vm/src/gas_schedule.rs b/language/vm/src/gas_schedule.rs index a221b27551ab..6394badedd59 100644 --- a/language/vm/src/gas_schedule.rs +++ b/language/vm/src/gas_schedule.rs @@ -8,7 +8,7 @@ //! native function itself. use crate::file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, FieldDefinitionIndex, FunctionHandleIndex, - StructDefinitionIndex, NO_TYPE_ACTUALS, NUMBER_OF_NATIVE_FUNCTIONS, + StructDefinitionIndex, NO_TYPE_ARGUMENTS, NUMBER_OF_NATIVE_FUNCTIONS, }; pub use crate::file_format_common::Opcodes; use libra_types::{identifier::Identifier, transaction::MAX_TRANSACTION_SIZE_IN_BYTES}; @@ -331,12 +331,12 @@ impl CostTable { // in the gas schedule for each instruction. let instrs = vec![ ( - MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MoveToSender(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (GetTxnSenderAddress, GasCost::new(0, 0)), ( - MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MoveFrom(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (BrTrue(0), GasCost::new(0, 0)), @@ -379,13 +379,13 @@ impl CostTable { (Neq, GasCost::new(0, 0)), (Not, GasCost::new(0, 0)), ( - Call(FunctionHandleIndex::new(0), NO_TYPE_ACTUALS), + Call(FunctionHandleIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (Le, GasCost::new(0, 0)), (Branch(0), GasCost::new(0, 0)), ( - Unpack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Unpack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (Or, GasCost::new(0, 0)), @@ -395,7 +395,7 @@ impl CostTable { (Mod, GasCost::new(0, 0)), (BrFalse(0), GasCost::new(0, 0)), ( - Exists(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Exists(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (GetGasRemaining, GasCost::new(0, 0)), @@ -404,11 +404,11 @@ impl CostTable { (GetTxnSequenceNumber, GasCost::new(0, 0)), (FreezeRef, GasCost::new(0, 0)), ( - MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + MutBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), ( - ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + ImmBorrowGlobal(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), (Div, GasCost::new(0, 0)), @@ -416,7 +416,7 @@ impl CostTable { (LdByteArray(ByteArrayPoolIndex::new(0)), GasCost::new(0, 0)), (Gt, GasCost::new(0, 0)), ( - Pack(StructDefinitionIndex::new(0), NO_TYPE_ACTUALS), + Pack(StructDefinitionIndex::new(0), NO_TYPE_ARGUMENTS), GasCost::new(0, 0), ), ]; diff --git a/language/vm/src/lib.rs b/language/vm/src/lib.rs index 05af972080f9..a3df734a5846 100644 --- a/language/vm/src/lib.rs +++ b/language/vm/src/lib.rs @@ -39,18 +39,23 @@ pub enum IndexKind { ModuleHandle, StructHandle, FunctionHandle, + FieldHandle, + StructInstantiation, + FunctionInstantiation, + FieldInstantiation, StructDefinition, FieldDefinition, FunctionDefinition, TypeSignature, FunctionSignature, - LocalsSignature, + Signature, Identifier, ByteArrayPool, AddressPool, LocalPool, CodeDefinition, TypeParameter, + FieldOffset, } impl IndexKind { @@ -63,17 +68,22 @@ impl IndexKind { ModuleHandle, StructHandle, FunctionHandle, + FieldHandle, + StructInstantiation, + FunctionInstantiation, + FieldInstantiation, StructDefinition, FieldDefinition, FunctionDefinition, TypeSignature, FunctionSignature, - LocalsSignature, + Signature, Identifier, AddressPool, LocalPool, CodeDefinition, TypeParameter, + FieldOffset, ] } } @@ -86,18 +96,23 @@ impl fmt::Display for IndexKind { ModuleHandle => "module handle", StructHandle => "struct handle", FunctionHandle => "function handle", + FieldHandle => "field handle", + StructInstantiation => "struct instantiation", + FunctionInstantiation => "function instantiation", + FieldInstantiation => "field instantiation", StructDefinition => "struct definition", FieldDefinition => "field definition", FunctionDefinition => "function definition", TypeSignature => "type signature", FunctionSignature => "function signature", - LocalsSignature => "locals signature", + Signature => "signature", Identifier => "identifier", ByteArrayPool => "byte_array pool", AddressPool => "address pool", LocalPool => "local pool", CodeDefinition => "code definition pool", TypeParameter => "type parameter", + FieldOffset => "field offset", }; f.write_str(desc) diff --git a/language/vm/src/printers.rs b/language/vm/src/printers.rs index 3ee54f54cb34..52471a40219d 100644 --- a/language/vm/src/printers.rs +++ b/language/vm/src/printers.rs @@ -78,7 +78,7 @@ pub trait TableAccess { fn get_address_at(&self, idx: AddressPoolIndex) -> Result<&AccountAddress>; fn get_type_signature_at(&self, idx: TypeSignatureIndex) -> Result<&TypeSignature>; fn get_function_signature_at(&self, idx: FunctionSignatureIndex) -> Result<&FunctionSignature>; - fn get_locals_signature_at(&self, idx: LocalsSignatureIndex) -> Result<&LocalsSignature>; + fn get_locals_signature_at(&self, idx: SignatureIndex) -> Result<&Signature>; } impl TableAccess for CompiledScriptMut { @@ -129,7 +129,7 @@ impl TableAccess for CompiledScriptMut { .ok_or_else(|| format_err!("bad signature index {}", idx)) } - fn get_locals_signature_at(&self, idx: LocalsSignatureIndex) -> Result<&LocalsSignature> { + fn get_locals_signature_at(&self, idx: SignatureIndex) -> Result<&Signature> { self.locals_signatures .get(idx.0 as usize) .ok_or_else(|| format_err!("bad signature index {}", idx)) @@ -186,7 +186,7 @@ impl TableAccess for CompiledModuleMut { .ok_or_else(|| format_err!("bad signature index {}", idx)) } - fn get_locals_signature_at(&self, idx: LocalsSignatureIndex) -> Result<&LocalsSignature> { + fn get_locals_signature_at(&self, idx: SignatureIndex) -> Result<&Signature> { self.locals_signatures .get(idx.0 as usize) .ok_or_else(|| format_err!("bad signature index {}", idx)) @@ -516,7 +516,7 @@ fn display_function_signature( tables: &T, f: &mut fmt::Formatter, ) -> fmt::Result { - let mut iter = sig.arg_types.iter().peekable(); + let mut iter = sig.parameters.iter().peekable(); write!(f, "(")?; while let Some(token) = iter.next() { display_signature_token(token, tables, f)?; @@ -526,7 +526,7 @@ fn display_function_signature( } write!(f, "): ")?; - let mut iter = sig.return_types.iter().peekable(); + let mut iter = sig.return_.iter().peekable(); write!(f, "(")?; while let Some(token) = iter.next() { display_signature_token(token, tables, f)?; @@ -539,7 +539,7 @@ fn display_function_signature( } fn display_locals_signature( - sig: &LocalsSignature, + sig: &Signature, tables: &T, f: &mut fmt::Formatter, ) -> fmt::Result { diff --git a/language/vm/src/proptest_types.rs b/language/vm/src/proptest_types.rs index 6b99c45df7e0..bc83ec504817 100644 --- a/language/vm/src/proptest_types.rs +++ b/language/vm/src/proptest_types.rs @@ -5,8 +5,8 @@ use crate::file_format::{ AddressPoolIndex, CompiledModule, CompiledModuleMut, FieldDefinition, FieldDefinitionIndex, - FunctionHandle, FunctionSignatureIndex, IdentifierIndex, Kind, LocalsSignature, MemberCount, - ModuleHandle, ModuleHandleIndex, SignatureToken, StructDefinition, StructFieldInformation, + FunctionHandle, FunctionSignatureIndex, IdentifierIndex, Kind, MemberCount, ModuleHandle, + ModuleHandleIndex, Signature, SignatureToken, StructDefinition, StructFieldInformation, StructHandle, StructHandleIndex, TableIndex, TypeSignature, TypeSignatureIndex, }; use libra_proptest_helpers::GrowingSubset; @@ -237,7 +237,7 @@ impl CompiledModuleStrategyGen { let struct_handles: Vec<_> = struct_handles .into_iter() .map( - |(module_idx, name_idx, is_nominal_resource, _type_formals)| { + |(module_idx, name_idx, is_nominal_resource, _type_parameters)| { StructHandle { module: ModuleHandleIndex::new( module_idx.index(module_handles_len) as TableIndex, @@ -248,7 +248,7 @@ impl CompiledModuleStrategyGen { is_nominal_resource, // TODO: re-enable type formals gen when we rework prop tests // for generics - type_formals: vec![], + type_parameters: vec![], } }, ) @@ -305,7 +305,7 @@ impl CompiledModuleStrategyGen { function_defs_len: function_defs.len(), function_signatures, // locals will be filled out by FunctionDefinitionGen::materialize - locals_signatures: vec![LocalsSignature(vec![])], + locals_signatures: vec![Signature(vec![])], function_handles, }; @@ -327,6 +327,11 @@ impl CompiledModuleStrategyGen { module_handles, struct_handles, function_handles, + field_handles: vec![], + + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], struct_defs, field_defs, @@ -406,7 +411,7 @@ struct StructDefinitionGen { // the is_nominal_resource field of generated struct handle is set to true if // either any of the fields contains a resource or self.is_nominal_resource is true is_nominal_resource: bool, - type_formals: Vec, + type_parameters: Vec, is_public: bool, field_defs: Option>, } @@ -424,11 +429,11 @@ impl StructDefinitionGen { option::of(vec(FieldDefinitionGen::strategy(), member_count)), ) .prop_map( - |(name_idx, is_nominal_resource, _type_formals, is_public, field_defs)| Self { + |(name_idx, is_nominal_resource, _type_parameters, is_public, field_defs)| Self { name_idx, is_nominal_resource, // TODO: re-enable type formals gen once we rework prop tests for generics - type_formals: vec![], + type_parameters: vec![], is_public, field_defs, }, @@ -450,8 +455,8 @@ impl StructDefinitionGen { self.name_idx.index(state.identifiers_len) as TableIndex ), is_nominal_resource, - type_formals: self - .type_formals + type_parameters: self + .type_parameters .into_iter() .map(|kind| kind.materialize()) .collect(), @@ -484,8 +489,8 @@ impl StructDefinitionGen { self.name_idx.index(state.identifiers_len) as TableIndex ), is_nominal_resource, - type_formals: self - .type_formals + type_parameters: self + .type_parameters .into_iter() .map(|kind| kind.materialize()) .collect(), diff --git a/language/vm/src/proptest_types/functions.rs b/language/vm/src/proptest_types/functions.rs index d9d6e8ebc9a5..74ef1080edc8 100644 --- a/language/vm/src/proptest_types/functions.rs +++ b/language/vm/src/proptest_types/functions.rs @@ -5,8 +5,8 @@ use crate::{ file_format::{ AddressPoolIndex, ByteArrayPoolIndex, Bytecode, CodeOffset, CodeUnit, FieldDefinitionIndex, FunctionDefinition, FunctionHandle, FunctionHandleIndex, FunctionSignature, - FunctionSignatureIndex, IdentifierIndex, LocalIndex, LocalsSignature, LocalsSignatureIndex, - ModuleHandleIndex, StructDefinitionIndex, TableIndex, NO_TYPE_ACTUALS, + FunctionSignatureIndex, IdentifierIndex, LocalIndex, ModuleHandleIndex, Signature, + SignatureIndex, StructDefinitionIndex, TableIndex, NO_TYPE_ARGUMENTS, }, proptest_types::{ signature::{FunctionSignatureGen, SignatureTokenGen}, @@ -35,7 +35,7 @@ pub struct FnDefnMaterializeState { pub function_handles_len: usize, // These get mutated by `FunctionDefinitionGen`. pub function_signatures: Vec, - pub locals_signatures: Vec, + pub locals_signatures: Vec, pub function_handles: Vec, } @@ -48,10 +48,10 @@ impl FnDefnMaterializeState { } #[inline] - fn add_locals_signature(&mut self, sig: LocalsSignature) -> LocalsSignatureIndex { + fn add_locals_signature(&mut self, sig: Signature) -> SignatureIndex { precondition!(self.locals_signatures.len() < TableSize::max_value() as usize); self.locals_signatures.push(sig); - LocalsSignatureIndex::new((self.locals_signatures.len() - 1) as TableIndex) + SignatureIndex::new((self.locals_signatures.len() - 1) as TableIndex) } #[inline] @@ -158,7 +158,7 @@ impl CodeUnitGen { fn materialize(self, state: &mut FnDefnMaterializeState) -> CodeUnit { precondition!(state.locals_signatures.len() < TableSize::max_value() as usize); - let locals_signature = LocalsSignature( + let locals_signature = Signature( self.locals_signature .into_iter() .map(|sig| sig.materialize(state.struct_handles_len)) @@ -252,7 +252,7 @@ impl BytecodeGen { fn will_materialize( &self, state: &FnDefnMaterializeState, - locals_signature: &LocalsSignature, + locals_signature: &Signature, ) -> bool { // This method should remain in sync with the `None` below. use BytecodeGen::*; @@ -270,7 +270,7 @@ impl BytecodeGen { self, state: &FnDefnMaterializeState, code_len: usize, - locals_signature: &LocalsSignature, + locals_signature: &Signature, ) -> Option { // This method returns an Option because some bytecodes cannot be represented if // some tables are empty. @@ -308,43 +308,43 @@ impl BytecodeGen { } BytecodeGen::Call(idx, _types_idx) => Bytecode::Call( FunctionHandleIndex::new(idx.index(state.function_handles_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::Pack(idx, _types_idx) => Bytecode::Pack( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::Unpack(idx, _types_idx) => Bytecode::Unpack( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::Exists(idx, _types_idx) => Bytecode::Exists( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::ImmBorrowGlobal(idx, _types_idx) => Bytecode::ImmBorrowGlobal( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::MutBorrowGlobal(idx, _types_idx) => Bytecode::MutBorrowGlobal( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::MoveFrom(idx, _types_idx) => Bytecode::MoveFrom( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::MoveToSender(idx, _types_idx) => Bytecode::MoveToSender( StructDefinitionIndex::new(idx.index(state.struct_defs_len) as TableIndex), - // TODO: generate random index to type actuals once generics is fully implemented - NO_TYPE_ACTUALS, + // TODO: generate random index to type arguments once generics is fully implemented + NO_TYPE_ARGUMENTS, ), BytecodeGen::BrTrue(idx) => Bytecode::BrTrue(idx.index(code_len) as CodeOffset), BytecodeGen::BrFalse(idx) => Bytecode::BrFalse(idx.index(code_len) as CodeOffset), diff --git a/language/vm/src/proptest_types/signature.rs b/language/vm/src/proptest_types/signature.rs index d15fe3f189bd..0fb7e76a11ce 100644 --- a/language/vm/src/proptest_types/signature.rs +++ b/language/vm/src/proptest_types/signature.rs @@ -13,14 +13,14 @@ use proptest::{ #[derive(Clone, Debug)] pub enum KindGen { Resource, - Unrestricted, + Copyable, } impl KindGen { pub fn strategy() -> impl Strategy { use KindGen::*; - static KINDS: &[KindGen] = &[Resource, Unrestricted]; + static KINDS: &[KindGen] = &[Resource, Copyable]; select(KINDS) } @@ -28,16 +28,16 @@ impl KindGen { pub fn materialize(self) -> Kind { match self { KindGen::Resource => Kind::Resource, - KindGen::Unrestricted => Kind::Unrestricted, + KindGen::Copyable => Kind::Copyable, } } } #[derive(Clone, Debug)] pub struct FunctionSignatureGen { - return_types: Vec, - arg_types: Vec, - type_formals: Vec, + return_: Vec, + parameters: Vec, + type_parameters: Vec, } impl FunctionSignatureGen { @@ -52,21 +52,20 @@ impl FunctionSignatureGen { // TODO: re-enable type formals once we rework prop tests for generics vec(KindGen::strategy(), 0), ) - .prop_map(|(return_types, arg_types, type_formals)| Self { - return_types, - arg_types, - type_formals, + .prop_map(|(return_, parameters, type_parameters)| Self { + return_, + parameters, + type_parameters, }) } pub fn materialize(self, struct_handles_len: usize) -> FunctionSignature { FunctionSignature { - return_types: SignatureTokenGen::map_materialize(self.return_types, struct_handles_len) + return_: SignatureTokenGen::map_materialize(self.return_, struct_handles_len).collect(), + parameters: SignatureTokenGen::map_materialize(self.parameters, struct_handles_len) .collect(), - arg_types: SignatureTokenGen::map_materialize(self.arg_types, struct_handles_len) - .collect(), - type_formals: self - .type_formals + type_parameters: self + .type_parameters .into_iter() .map(KindGen::materialize) .collect(), @@ -133,7 +132,7 @@ impl SignatureTokenGen { pub fn struct_strategy() -> impl Strategy { use SignatureTokenGen::*; - // TODO: generate type actuals + // TODO: generate type arguments any::().prop_map(|idx| Struct(idx, vec![])) } diff --git a/language/vm/src/resolver.rs b/language/vm/src/resolver.rs index a2ebbc83027c..3f5486242235 100644 --- a/language/vm/src/resolver.rs +++ b/language/vm/src/resolver.rs @@ -96,7 +96,7 @@ impl Resolver { .get(struct_name) .ok_or_else(|| VMStatus::new(StatusCode::TYPE_RESOLUTION_FAILURE))?, is_nominal_resource: struct_handle.is_nominal_resource, - type_formals: struct_handle.type_formals.clone(), + type_parameters: struct_handle.type_parameters.clone(), }; Ok(SignatureToken::Struct( *self @@ -127,18 +127,18 @@ impl Resolver { dependency: &impl ModuleAccess, func_sig: &FunctionSignature, ) -> Result { - let mut return_types = Vec::::new(); - let mut arg_types = Vec::::new(); - for e in &func_sig.return_types { - return_types.push(self.import_signature_token(dependency, e)?); + let mut return_ = Vec::::new(); + let mut parameters = Vec::::new(); + for e in &func_sig.return_ { + return_.push(self.import_signature_token(dependency, e)?); } - for e in &func_sig.arg_types { - arg_types.push(self.import_signature_token(dependency, e)?); + for e in &func_sig.parameters { + parameters.push(self.import_signature_token(dependency, e)?); } Ok(FunctionSignature { - return_types, - arg_types, - type_formals: func_sig.type_formals.clone(), + return_, + parameters, + type_parameters: func_sig.type_parameters.clone(), }) } } diff --git a/language/vm/src/serializer.rs b/language/vm/src/serializer.rs index 8ca9101e821a..b60f99b01557 100644 --- a/language/vm/src/serializer.rs +++ b/language/vm/src/serializer.rs @@ -165,7 +165,7 @@ trait CommonTables { fn get_byte_array_pool(&self) -> &[ByteArray]; fn get_type_signatures(&self) -> &[TypeSignature]; fn get_function_signatures(&self) -> &[FunctionSignature]; - fn get_locals_signatures(&self) -> &[LocalsSignature]; + fn get_locals_signatures(&self) -> &[Signature]; } impl CommonTables for CompiledScriptMut { @@ -201,7 +201,7 @@ impl CommonTables for CompiledScriptMut { &self.function_signatures } - fn get_locals_signatures(&self) -> &[LocalsSignature] { + fn get_locals_signatures(&self) -> &[Signature] { &self.locals_signatures } } @@ -239,7 +239,7 @@ impl CommonTables for CompiledModuleMut { &self.function_signatures } - fn get_locals_signatures(&self) -> &[LocalsSignature] { + fn get_locals_signatures(&self) -> &[Signature] { &self.locals_signatures } } @@ -265,7 +265,7 @@ fn serialize_struct_handle(binary: &mut BinaryData, struct_handle: &StructHandle write_u16_as_uleb128(binary, struct_handle.module.0)?; write_u16_as_uleb128(binary, struct_handle.name.0)?; serialize_nominal_resource_flag(binary, struct_handle.is_nominal_resource)?; - serialize_kinds(binary, &struct_handle.type_formals) + serialize_kinds(binary, &struct_handle.type_parameters) } /// Serializes a `FunctionHandle`. @@ -437,17 +437,17 @@ fn serialize_function_signature( signature: &FunctionSignature, ) -> Result<()> { binary.push(SignatureType::FUNCTION_SIGNATURE as u8)?; - serialize_signature_tokens(binary, &signature.return_types)?; - serialize_signature_tokens(binary, &signature.arg_types)?; - serialize_kinds(binary, &signature.type_formals) + serialize_signature_tokens(binary, &signature.return_)?; + serialize_signature_tokens(binary, &signature.parameters)?; + serialize_kinds(binary, &signature.type_parameters) } -/// Serializes a `LocalsSignature`. +/// Serializes a `Signature`. /// -/// A `LocalsSignature` gets serialized as follows: +/// A `Signature` gets serialized as follows: /// - `SignatureType::LOCAL_SIGNATURE` as 1 byte /// - The vector of `SignatureToken`s for locals -fn serialize_locals_signature(binary: &mut BinaryData, signature: &LocalsSignature) -> Result<()> { +fn serialize_locals_signature(binary: &mut BinaryData, signature: &Signature) -> Result<()> { binary.push(SignatureType::LOCAL_SIGNATURE as u8)?; serialize_signature_tokens(binary, &signature.0) } @@ -522,7 +522,7 @@ fn serialize_kind(binary: &mut BinaryData, kind: Kind) -> Result<()> { binary.push(match kind { Kind::All => SerializedKind::ALL, Kind::Resource => SerializedKind::RESOURCE, - Kind::Unrestricted => SerializedKind::UNRESTRICTED, + Kind::Copyable => SerializedKind::COPYABLE, } as u8)?; Ok(()) } @@ -993,7 +993,7 @@ impl CommonSerializer { fn serialize_locals_signatures( &mut self, binary: &mut BinaryData, - signatures: &[LocalsSignature], + signatures: &[Signature], ) -> Result<()> { if !signatures.is_empty() { self.table_count += 1; diff --git a/language/vm/src/views.rs b/language/vm/src/views.rs index 71e89b12e996..2b144801c170 100644 --- a/language/vm/src/views.rs +++ b/language/vm/src/views.rs @@ -17,7 +17,7 @@ use crate::{ access::ModuleAccess, file_format::{ CodeUnit, CompiledModule, FieldDefinition, FunctionDefinition, FunctionHandle, - FunctionSignature, Kind, LocalIndex, LocalsSignature, ModuleHandle, SignatureToken, + FunctionSignature, Kind, LocalIndex, ModuleHandle, Signature, SignatureToken, StructDefinition, StructDefinitionIndex, StructFieldInformation, StructHandle, StructHandleIndex, TypeSignature, }, @@ -230,8 +230,8 @@ impl<'a, T: ModuleAccess> StructHandleView<'a, T> { self.struct_handle.is_nominal_resource } - pub fn type_formals(&self) -> &Vec { - &self.struct_handle.type_formals + pub fn type_parameters(&self) -> &Vec { + &self.struct_handle.type_parameters } pub fn module_handle(&self) -> &ModuleHandle { @@ -330,8 +330,8 @@ impl<'a, T: ModuleAccess> StructDefinitionView<'a, T> { } } - pub fn type_formals(&self) -> &Vec { - self.struct_handle_view.type_formals() + pub fn type_parameters(&self) -> &Vec { + self.struct_handle_view.type_parameters() } pub fn fields( @@ -469,13 +469,13 @@ impl<'a, T: ModuleAccess> TypeSignatureView<'a, T> { } #[inline] - pub fn kind(&self, type_formals: &[Kind]) -> Kind { - self.token().kind(type_formals) + pub fn kind(&self, type_parameters: &[Kind]) -> Kind { + self.token().kind(type_parameters) } #[inline] - pub fn contains_nominal_resource(&self, type_formals: &[Kind]) -> bool { - self.token().contains_nominal_resource(type_formals) + pub fn contains_nominal_resource(&self, type_parameters: &[Kind]) -> bool { + self.token().contains_nominal_resource(type_parameters) } } @@ -497,7 +497,7 @@ impl<'a, T: ModuleAccess> FunctionSignatureView<'a, T> { pub fn return_tokens(&self) -> impl DoubleEndedIterator> + 'a { let module = self.module; self.function_signature - .return_types + .return_ .iter() .map(move |token| SignatureTokenView::new(module, token)) } @@ -506,33 +506,33 @@ impl<'a, T: ModuleAccess> FunctionSignatureView<'a, T> { pub fn arg_tokens(&self) -> impl DoubleEndedIterator> + 'a { let module = self.module; self.function_signature - .arg_types + .parameters .iter() .map(move |token| SignatureTokenView::new(module, token)) } #[inline] - pub fn type_formals(&self) -> &Vec { - &self.function_signature.type_formals + pub fn type_parameters(&self) -> &Vec { + &self.function_signature.type_parameters } pub fn return_count(&self) -> usize { - self.function_signature.return_types.len() + self.function_signature.return_.len() } pub fn arg_count(&self) -> usize { - self.function_signature.arg_types.len() + self.function_signature.parameters.len() } } pub struct LocalsSignatureView<'a, T> { module: &'a T, - locals_signature: &'a LocalsSignature, + locals_signature: &'a Signature, } impl<'a, T: ModuleAccess> LocalsSignatureView<'a, T> { #[inline] - pub fn new(module: &'a T, locals_signature: &'a LocalsSignature) -> Self { + pub fn new(module: &'a T, locals_signature: &'a Signature) -> Self { Self { module, locals_signature, @@ -591,8 +591,8 @@ impl<'a, T: ModuleAccess> SignatureTokenView<'a, T> { } // TODO: rework views to make the interfaces here cleaner. - pub fn kind(&self, type_formals: &[Kind]) -> Kind { - SignatureToken::kind((self.module.struct_handles(), type_formals), self.token) + pub fn kind(&self, type_parameters: &[Kind]) -> Kind { + SignatureToken::kind((self.module.struct_handles(), type_parameters), self.token) } /// Determines if the given signature token contains a nominal resource. @@ -600,22 +600,22 @@ impl<'a, T: ModuleAccess> SignatureTokenView<'a, T> { /// 1) it is a type variable explicitly marked as resource kind. /// 2) it is a struct that /// a) is marked as resource. - /// b) has a type actual which is a nominal resource. + /// b) has a type argument which is a nominal resource. /// /// Similar to `SignatureTokenView::kind`, the context is used for looking up struct /// definitions & type formals. // TODO: refactor views so that we get the type formals from self. - pub fn contains_nominal_resource(&self, type_formals: &[Kind]) -> bool { + pub fn contains_nominal_resource(&self, type_parameters: &[Kind]) -> bool { match self.token { SignatureToken::Struct(sh_idx, type_arguments) => { StructHandleView::new(self.module, self.module.struct_handle_at(*sh_idx)) .is_nominal_resource() || type_arguments.iter().any(|token| { - Self::new(self.module, token).contains_nominal_resource(type_formals) + Self::new(self.module, token).contains_nominal_resource(type_parameters) }) } SignatureToken::Vector(ty) => { - SignatureTokenView::new(self.module, ty).contains_nominal_resource(type_formals) + SignatureTokenView::new(self.module, ty).contains_nominal_resource(type_parameters) } SignatureToken::Reference(_) | SignatureToken::MutableReference(_) @@ -656,11 +656,11 @@ impl<'a, T: ModuleAccess> SignatureTokenView<'a, T> { // Token contains a struct handle from `self.module`. Need to resolve inside // `other_module`. We do this by normalizing the struct in `self.token`, then // searching for the normalized representation inside `other_module` - // TODO: do we need to resolve `self.token`'s type actuals? - let type_actuals = Vec::new(); + // TODO: do we need to resolve `self.token`'s type arguments? + let type_arguments = Vec::new(); ModuleView::new(other_module) .resolve_struct(&struct_handle.normalize_struct()) - .map(|handle_idx| SignatureToken::Struct(handle_idx, type_actuals)) + .map(|handle_idx| SignatureToken::Struct(handle_idx, type_arguments)) } else { Some(self.token.clone()) } @@ -728,5 +728,5 @@ impl_view_internals!(FunctionDefinitionView, FunctionDefinition, function_def); impl_view_internals!(FieldDefinitionView, FieldDefinition, field_def); impl_view_internals!(TypeSignatureView, TypeSignature, type_signature); impl_view_internals!(FunctionSignatureView, FunctionSignature, function_signature); -impl_view_internals!(LocalsSignatureView, LocalsSignature, locals_signature); +impl_view_internals!(LocalsSignatureView, Signature, locals_signature); impl_view_internals!(SignatureTokenView, SignatureToken, token); diff --git a/language/vm/vm-runtime/src/code_cache/module_cache.rs b/language/vm/vm-runtime/src/code_cache/module_cache.rs index 8ae5666cf132..089c0d8c21ad 100644 --- a/language/vm/vm-runtime/src/code_cache/module_cache.rs +++ b/language/vm/vm-runtime/src/code_cache/module_cache.rs @@ -101,7 +101,7 @@ impl<'alloc> VMModuleCache<'alloc> { let struct_def = module.struct_def_at(idx); let struct_handle = module.struct_handle_at(struct_def.struct_handle); let type_context = - TypeContext::identity_mapping(struct_handle.type_formals.len() as u16); + TypeContext::identity_mapping(struct_handle.type_parameters.len() as u16); match &struct_def.field_information { // TODO we might want a more informative error here StructFieldInformation::Native => { diff --git a/language/vm/vm-runtime/src/interpreter.rs b/language/vm/vm-runtime/src/interpreter.rs index 13e776d4d4ac..9a75f81fc4e0 100644 --- a/language/vm/vm-runtime/src/interpreter.rs +++ b/language/vm/vm-runtime/src/interpreter.rs @@ -39,7 +39,7 @@ use vm::{ access::ModuleAccess, errors::*, file_format::{ - Bytecode, FunctionHandleIndex, LocalIndex, LocalsSignatureIndex, SignatureToken, + Bytecode, FunctionHandleIndex, LocalIndex, SignatureIndex, SignatureToken, StructDefinitionIndex, }, gas_schedule::{ @@ -842,7 +842,7 @@ impl<'txn> Interpreter<'txn> { context: &mut dyn InterpreterContext, address: AccountAddress, idx: StructDefinitionIndex, - type_actuals_idx: LocalsSignatureIndex, + type_actuals_idx: SignatureIndex, frame: &Frame<'txn, FunctionRef<'txn>>, op: F, ) -> VMResult> @@ -1139,7 +1139,7 @@ enum ExitCode { /// A `Return` opcode was found. Return, /// A `Call` opcode was found. - Call(FunctionHandleIndex, LocalsSignatureIndex), + Call(FunctionHandleIndex, SignatureIndex), } impl<'txn, F> Frame<'txn, F> diff --git a/language/vm/vm-runtime/src/loaded_data/function.rs b/language/vm/vm-runtime/src/loaded_data/function.rs index 1b8da9f0548d..1d072416142a 100644 --- a/language/vm/vm-runtime/src/loaded_data/function.rs +++ b/language/vm/vm-runtime/src/loaded_data/function.rs @@ -101,8 +101,8 @@ impl<'txn> FunctionRef<'txn> { "{}::{}({:?}){:?}", self.module().name(), self.name().as_str(), - signature.arg_types, - signature.return_types + signature.parameters, + signature.return_ ) } } @@ -128,8 +128,8 @@ impl FunctionDef { FunctionDef { code, flags, - arg_count: function_sig.arg_types.len(), - return_count: function_sig.return_types.len(), + arg_count: function_sig.parameters.len(), + return_count: function_sig.return_.len(), // Local count for native function is omitted local_count: if (flags & CodeUnit::NATIVE) == CodeUnit::NATIVE { 0 diff --git a/language/vm/vm-runtime/src/runtime.rs b/language/vm/vm-runtime/src/runtime.rs index 995fe4d77319..3ed4969f5ce9 100644 --- a/language/vm/vm-runtime/src/runtime.rs +++ b/language/vm/vm-runtime/src/runtime.rs @@ -119,7 +119,7 @@ impl<'alloc> VMRuntime<'alloc> { if !verify_actuals(main.signature(), &args) { return Err(VMStatus::new(StatusCode::TYPE_MISMATCH) - .with_message("Actual Type Mismatch".to_string())); + .with_message("Argument Type Mismatch".to_string())); } Interpreter::entrypoint(context, self, txn_data, gas_schedule, main, args) @@ -225,17 +225,17 @@ impl<'alloc> VMRuntime<'alloc> { } } -/// Verify if the transaction arguments match the type signature of the main function. +/// Verify if the transaction actuals match the type signature of the main function. fn verify_actuals(signature: &FunctionSignature, args: &[Value]) -> bool { - if signature.arg_types.len() != args.len() { + if signature.parameters.len() != args.len() { warn!( "[VM] different argument length: actuals {}, formals {}", args.len(), - signature.arg_types.len() + signature.parameters.len() ); return false; } - for (ty, arg) in signature.arg_types.iter().zip(args.iter()) { + for (ty, arg) in signature.parameters.iter().zip(args.iter()) { if !arg.is_valid_script_arg(ty) { warn!( "[VM] different argument type: formal {:?}, actual {:?}", diff --git a/language/vm/vm-runtime/src/unit_tests/module_cache_tests.rs b/language/vm/vm-runtime/src/unit_tests/module_cache_tests.rs index d42421d45948..9275efd5d398 100644 --- a/language/vm/vm-runtime/src/unit_tests/module_cache_tests.rs +++ b/language/vm/vm-runtime/src/unit_tests/module_cache_tests.rs @@ -90,6 +90,10 @@ fn test_module(name: &'static str) -> VerifiedModule { signature: FunctionSignatureIndex::new(1), }, ], + field_handles: vec![], + struct_instantiations: vec![], + function_instantiations: vec![], + field_instantiations: vec![], struct_defs: vec![], field_defs: vec![], @@ -100,7 +104,7 @@ fn test_module(name: &'static str) -> VerifiedModule { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 10, - locals: LocalsSignatureIndex::new(0), + locals: SignatureIndex::new(0), code: vec![Bytecode::LdTrue, Bytecode::Pop, Bytecode::Ret], }, }, @@ -110,7 +114,7 @@ fn test_module(name: &'static str) -> VerifiedModule { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 10, - locals: LocalsSignatureIndex::new(1), + locals: SignatureIndex::new(1), code: vec![Bytecode::Ret], }, }, @@ -118,20 +122,17 @@ fn test_module(name: &'static str) -> VerifiedModule { type_signatures: vec![], function_signatures: vec![ FunctionSignature { - return_types: vec![], - arg_types: vec![], - type_formals: vec![], + return_: vec![], + parameters: vec![], + type_parameters: vec![], }, FunctionSignature { - return_types: vec![], - arg_types: vec![SignatureToken::U64], - type_formals: vec![], + return_: vec![], + parameters: vec![SignatureToken::U64], + type_parameters: vec![], }, ], - locals_signatures: vec![ - LocalsSignature(vec![]), - LocalsSignature(vec![SignatureToken::U64]), - ], + locals_signatures: vec![Signature(vec![]), Signature(vec![SignatureToken::U64])], identifiers: idents(vec![name, "func1", "func2"]), byte_array_pool: vec![], address_pool: vec![AccountAddress::default()], @@ -149,7 +150,7 @@ fn test_script() -> VerifiedScript { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 10, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Bytecode::Ret], }, }, @@ -181,20 +182,22 @@ fn test_script() -> VerifiedScript { module: ModuleHandleIndex::new(1), }, ], + struct_instantiations: vec![], + function_instantiations: vec![], type_signatures: vec![], function_signatures: vec![ FunctionSignature { - return_types: vec![], - arg_types: vec![], - type_formals: vec![], + return_: vec![], + parameters: vec![], + type_parameters: vec![], }, FunctionSignature { - return_types: vec![], - arg_types: vec![SignatureToken::U64], - type_formals: vec![], + return_: vec![], + parameters: vec![SignatureToken::U64], + type_parameters: vec![], }, ], - locals_signatures: vec![LocalsSignature(vec![])], + locals_signatures: vec![Signature(vec![])], identifiers: idents(vec!["hello", "module", "func1", "func2", "main"]), byte_array_pool: vec![], address_pool: vec![AccountAddress::default()], @@ -379,7 +382,7 @@ fn test_multi_level_cache_write_back() { acquires_global_resources: vec![], code: CodeUnit { max_stack_size: 10, - locals: LocalsSignatureIndex(0), + locals: SignatureIndex(0), code: vec![Bytecode::Ret], }, }, @@ -421,20 +424,22 @@ fn test_multi_level_cache_write_back() { module: ModuleHandleIndex::new(2), }, ], + struct_instantiations: vec![], + function_instantiations: vec![], type_signatures: vec![], function_signatures: vec![ FunctionSignature { - return_types: vec![], - arg_types: vec![], - type_formals: vec![], + return_: vec![], + parameters: vec![], + type_parameters: vec![], }, FunctionSignature { - return_types: vec![], - arg_types: vec![SignatureToken::U64], - type_formals: vec![], + return_: vec![], + parameters: vec![SignatureToken::U64], + type_parameters: vec![], }, ], - locals_signatures: vec![LocalsSignature(vec![])], + locals_signatures: vec![Signature(vec![])], identifiers: idents(vec![ "hello", "module", diff --git a/types/src/vm_error.rs b/types/src/vm_error.rs index 1b101514fa1f..2e4d6603c964 100644 --- a/types/src/vm_error.rs +++ b/types/src/vm_error.rs @@ -378,7 +378,7 @@ pub enum StatusCode { INVALID_ACQUIRES_RESOURCE_ANNOTATION_ERROR = 1073, GLOBAL_REFERENCE_ERROR = 1074, CONTRAINT_KIND_MISMATCH = 1075, - NUMBER_OF_TYPE_ACTUALS_MISMATCH = 1076, + NUMBER_OF_TYPE_ARGUMENTS_MISMATCH = 1076, LOOP_IN_INSTANTIATION_GRAPH = 1077, UNUSED_LOCALS_SIGNATURE = 1078, UNUSED_TYPE_SIGNATURE = 1079, @@ -591,7 +591,7 @@ impl TryFrom for StatusCode { 1073 => Ok(StatusCode::INVALID_ACQUIRES_RESOURCE_ANNOTATION_ERROR), 1074 => Ok(StatusCode::GLOBAL_REFERENCE_ERROR), 1075 => Ok(StatusCode::CONTRAINT_KIND_MISMATCH), - 1076 => Ok(StatusCode::NUMBER_OF_TYPE_ACTUALS_MISMATCH), + 1076 => Ok(StatusCode::NUMBER_OF_TYPE_ARGUMENTS_MISMATCH), 1077 => Ok(StatusCode::LOOP_IN_INSTANTIATION_GRAPH), 1078 => Ok(StatusCode::UNUSED_LOCALS_SIGNATURE), 1079 => Ok(StatusCode::UNUSED_TYPE_SIGNATURE),