diff --git a/language/benchmarks/src/move_vm.rs b/language/benchmarks/src/move_vm.rs index 590996edbb..1b07b7580b 100644 --- a/language/benchmarks/src/move_vm.rs +++ b/language/benchmarks/src/move_vm.rs @@ -3,7 +3,7 @@ use criterion::{measurement::Measurement, Criterion}; use move_binary_format::CompiledModule; -use move_compiler::{compiled_unit::AnnotatedCompiledUnit, Compiler, Flags}; +use move_compiler::{compiled_unit::AnnotatedCompiledUnit, Compiler}; use move_core_types::{ account_address::AccountAddress, identifier::{IdentStr, Identifier}, @@ -39,7 +39,6 @@ fn compile_modules() -> Vec { vec![(src_files, move_stdlib::move_stdlib_named_addresses())], vec![], ) - .set_flags(Flags::empty().set_sources_shadow_deps(false)) .build_and_report() .expect("Error compiling..."); compiled_units diff --git a/language/evm/move-to-yul/src/lib.rs b/language/evm/move-to-yul/src/lib.rs index 1cb35152bf..0d40d32cfb 100644 --- a/language/evm/move-to-yul/src/lib.rs +++ b/language/evm/move-to-yul/src/lib.rs @@ -37,11 +37,11 @@ pub fn run_to_yul_errors_to_stderr(options: Options) -> anyhow::Result<()> { /// Run move-to-yul compiler and print errors to given writer. pub fn run_to_yul(error_writer: &mut W, options: Options) -> anyhow::Result<()> { // Run the model builder. + let addrs = parse_addresses_from_options(options.named_address_mapping.clone())?; let env = run_model_builder_with_options( - &options.sources, - &options.dependencies, + vec![(options.sources.clone(), addrs.clone())], + vec![(options.dependencies.clone(), addrs)], ModelBuilderOptions::default(), - parse_addresses_from_options(options.named_address_mapping.clone())?, )?; // If the model contains any errors, report them now and exit. check_errors( diff --git a/language/evm/move-to-yul/tests/dispatcher_testsuite.rs b/language/evm/move-to-yul/tests/dispatcher_testsuite.rs index 31d44442c5..1298e8005b 100644 --- a/language/evm/move-to-yul/tests/dispatcher_testsuite.rs +++ b/language/evm/move-to-yul/tests/dispatcher_testsuite.rs @@ -56,10 +56,12 @@ fn compile_yul_to_bytecode_bytes(filename: &str) -> Result> { NumericalAddress::parse_str("0x2").unwrap(), ); let env = run_model_builder_with_options( - &[contract_path(filename).to_string_lossy().to_string()], - &deps, + vec![( + vec![contract_path(filename).to_string_lossy().to_string()], + named_address_mapping.clone(), + )], + vec![(deps, named_address_mapping)], ModelBuilderOptions::default(), - named_address_mapping, )?; let options = Options::default(); let (_, out) = Generator::run(&options, &env); diff --git a/language/evm/move-to-yul/tests/testsuite.rs b/language/evm/move-to-yul/tests/testsuite.rs index 94df99485f..2d874dce9f 100644 --- a/language/evm/move-to-yul/tests/testsuite.rs +++ b/language/evm/move-to-yul/tests/testsuite.rs @@ -10,7 +10,7 @@ use move_compiler::shared::NumericalAddress; use move_model::{ model::{FunId, GlobalEnv, QualifiedId}, options::ModelBuilderOptions, - run_model_builder_with_options, + run_model_builder_with_options_and_compilation_flags, }; use move_prover_test_utils::{baseline_test::verify_or_update_baseline, extract_test_directives}; use move_stdlib::move_stdlib_named_addresses; @@ -39,11 +39,11 @@ fn test_runner(path: &Path) -> datatest_stable::Result<()> { "Evm".to_string(), NumericalAddress::parse_str("0x2").unwrap(), ); - let env = run_model_builder_with_options( - &sources, - &deps, + let env = run_model_builder_with_options_and_compilation_flags( + vec![(sources, named_address_mapping.clone())], + vec![(deps, named_address_mapping)], ModelBuilderOptions::default(), - named_address_mapping, + move_compiler::Flags::empty().set_sources_shadow_deps(true), )?; for exp in std::iter::once(String::new()).chain(experiments.into_iter()) { let mut options = Options { diff --git a/language/move-compiler/src/command_line/compiler.rs b/language/move-compiler/src/command_line/compiler.rs index 494f44c28d..c5981d4cd2 100644 --- a/language/move-compiler/src/command_line/compiler.rs +++ b/language/move-compiler/src/command_line/compiler.rs @@ -88,26 +88,29 @@ pub struct FullyCompiledProgram { //************************************************************************************************** impl<'a> Compiler<'a> { - pub fn new(targets: Vec, deps: Vec) -> Self { - fn rc_scopes( + pub fn new, NamedAddress: Into>( + targets: Vec>, + deps: Vec>, + ) -> Self { + fn indexed_scopes( maps: &mut NamedAddressMaps, - all_paths: Vec, + all_paths: Vec, impl Into>>, ) -> Vec { let mut idx_paths = vec![]; for (paths, mapping) in all_paths { let idx = maps.insert( mapping .into_iter() - .map(|(k, v)| (Symbol::from(k), v)) + .map(|(k, v)| (k.into(), v)) .collect::(), ); - idx_paths.extend(paths.into_iter().map(|p| (p, idx))); + idx_paths.extend(paths.into_iter().map(|p| (p.into(), idx))); } idx_paths } let mut maps = NamedAddressMaps::new(); - let targets = rc_scopes(&mut maps, targets); - let deps = rc_scopes(&mut maps, deps); + let targets = indexed_scopes(&mut maps, targets); + let deps = indexed_scopes(&mut maps, deps); Self { maps, @@ -383,15 +386,16 @@ impl<'a> SteppedCompiler<'a, PASS_COMPILATION> { /// Given a set of dependencies, precompile them and save the ASTs so that they can be used again /// to compile against without having to recompile these dependencies -pub fn construct_pre_compiled_lib( - deps: Vec, +pub fn construct_pre_compiled_lib, NamedAddress: Into>( + deps: Vec>, interface_files_dir_opt: Option, flags: Flags, ) -> anyhow::Result> { - let (files, pprog_and_comments_res) = Compiler::new(vec![], deps) - .set_interface_files_dir_opt(interface_files_dir_opt) - .set_flags(flags) - .run::()?; + let (files, pprog_and_comments_res) = + Compiler::new(Vec::>::new(), deps) + .set_interface_files_dir_opt(interface_files_dir_opt) + .set_flags(flags) + .run::()?; let (_comments, stepped) = match pprog_and_comments_res { Err(errors) => return Ok(Err((files, errors))), @@ -585,18 +589,18 @@ pub fn generate_interface_files( ) -> anyhow::Result> { let mv_files = { let mut v = vec![]; - let (mv_magic_files, other_file_locations): (Vec<_>, Vec<_>) = mv_file_locations - .iter() - .cloned() - .partition(|s| Path::new(&s.0).is_file() && has_compiled_module_magic_number(&s.0)); + let (mv_magic_files, other_file_locations): (Vec<_>, Vec<_>) = + mv_file_locations.iter().cloned().partition(|s| { + Path::new(s.0.as_str()).is_file() && has_compiled_module_magic_number(&s.0) + }); v.extend(mv_magic_files); for (file, address_mapping) in other_file_locations { v.extend( - find_filenames(&[file], |path| { + find_filenames(&[file.as_str()], |path| { extension_equals(path, MOVE_COMPILED_EXTENSION) })? .into_iter() - .map(|f| (f, address_mapping)), + .map(|f| (Symbol::from(f), address_mapping)), ); } v @@ -619,7 +623,7 @@ pub fn generate_interface_files( mv_files.len().hash(&mut hasher); HASH_DELIM.hash(&mut hasher); for (mv_file, _) in &mv_files { - std::fs::read(mv_file)?.hash(&mut hasher); + std::fs::read(mv_file.as_str())?.hash(&mut hasher); HASH_DELIM.hash(&mut hasher); } @@ -637,7 +641,7 @@ pub fn generate_interface_files( let addr_dir = dir_path!(all_addr_dir.clone(), format!("{}", id.address())); let file_path = file_path!(addr_dir.clone(), format!("{}", id.name()), MOVE_EXTENSION); result.push(( - file_path.clone().into_os_string().into_string().unwrap(), + Symbol::from(file_path.clone().into_os_string().into_string().unwrap()), idx, )); // it's possible some files exist but not others due to multithreaded environments @@ -712,7 +716,6 @@ fn run( match cur { PassResult::Parser(prog) => { - let prog = parser::sources_shadow_deps::program(compilation_env, prog); let prog = parser::merge_spec_modules::program(compilation_env, prog); let prog = unit_test::filter_test_members::program(compilation_env, prog); let eprog = expansion::translate::program(compilation_env, pre_compiled_lib, prog); diff --git a/language/move-compiler/src/command_line/mod.rs b/language/move-compiler/src/command_line/mod.rs index b1f997691a..ddfc716ff7 100644 --- a/language/move-compiler/src/command_line/mod.rs +++ b/language/move-compiler/src/command_line/mod.rs @@ -13,8 +13,8 @@ pub const OUT_DIR: &str = "out-dir"; pub const OUT_DIR_SHORT: char = 'o'; pub const DEFAULT_OUTPUT_DIR: &str = "build"; -pub const NO_SHADOW: &str = "no-shadow"; -pub const NO_SHADOW_SHORT: char = 'S'; +pub const SHADOW: &str = "shadow"; +pub const SHADOW_SHORT: char = 'S'; pub const SOURCE_MAP: &str = "source-map"; pub const SOURCE_MAP_SHORT: char = 'm'; diff --git a/language/move-compiler/src/compiled_unit.rs b/language/move-compiler/src/compiled_unit.rs index 79f0dcc7e8..bf19b9445f 100644 --- a/language/move-compiler/src/compiled_unit.rs +++ b/language/move-compiler/src/compiled_unit.rs @@ -92,10 +92,8 @@ pub type AnnotatedCompiledUnit = CompiledUnitEnum ModuleIdent { use crate::expansion::ast::Address; - let address = match self.address_name { - None => Address::Anonymous(sp(self.loc, self.named_module.address)), - Some(n) => Address::Named(n, Some(self.named_module.address)), - }; + let address = + Address::Numerical(self.address_name, sp(self.loc, self.named_module.address)); sp( self.loc, ModuleIdent_::new( diff --git a/language/move-compiler/src/expansion/ast.rs b/language/move-compiler/src/expansion/ast.rs index b324e1556d..dce3f1d5a1 100644 --- a/language/move-compiler/src/expansion/ast.rs +++ b/language/move-compiler/src/expansion/ast.rs @@ -90,8 +90,8 @@ pub struct Script { #[derive(Clone, Copy)] pub enum Address { - Anonymous(Spanned), - Named(Name, Option), + Numerical(Option, Spanned), + NamedUnassigned(Name), } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ModuleIdent_ { @@ -494,8 +494,8 @@ impl fmt::Debug for Address { impl PartialEq for Address { fn eq(&self, other: &Self) -> bool { match (self, other) { - (Self::Anonymous(l), Self::Anonymous(r)) => l == r, - (Self::Named(l, _), Self::Named(r, _)) => l == r, + (Self::Numerical(_, l), Self::Numerical(_, r)) => l == r, + (Self::NamedUnassigned(l), Self::NamedUnassigned(r)) => l == r, _ => false, } } @@ -514,11 +514,11 @@ impl Ord for Address { use std::cmp::Ordering; match (self, other) { - (Self::Anonymous(_), Self::Named(_, _)) => Ordering::Less, - (Self::Named(_, _), Self::Anonymous(_)) => Ordering::Greater, + (Self::Numerical(_, _), Self::NamedUnassigned(_)) => Ordering::Less, + (Self::NamedUnassigned(_), Self::Numerical(_, _)) => Ordering::Greater, - (Self::Anonymous(l), Self::Anonymous(r)) => l.cmp(r), - (Self::Named(l, _), Self::Named(r, _)) => l.cmp(r), + (Self::Numerical(_, l), Self::Numerical(_, r)) => l.cmp(r), + (Self::NamedUnassigned(l), Self::NamedUnassigned(r)) => l.cmp(r), } } } @@ -526,12 +526,8 @@ impl Ord for Address { impl Hash for Address { fn hash(&self, state: &mut H) { match self { - Self::Anonymous(sp!(_, bytes)) => bytes.hash(state), - Self::Named(n, None) => n.hash(state), - Self::Named(n, Some(bytes)) => { - n.hash(state); - bytes.hash(state) - } + Self::Numerical(_, sp!(_, bytes)) => bytes.hash(state), + Self::NamedUnassigned(name) => name.hash(state), } } } @@ -542,14 +538,13 @@ impl Hash for Address { impl Address { pub const fn anonymous(loc: Loc, address: NumericalAddress) -> Self { - Self::Anonymous(sp(loc, address)) + Self::Numerical(None, sp(loc, address)) } pub fn into_addr_bytes(self) -> NumericalAddress { match self { - Self::Anonymous(sp!(_, bytes)) => bytes, - Self::Named(_, Some(bytes)) => bytes, - Self::Named(_, None) => NumericalAddress::DEFAULT_ERROR_ADDRESS, + Self::Numerical(_, sp!(_, bytes)) => bytes, + Self::NamedUnassigned(_) => NumericalAddress::DEFAULT_ERROR_ADDRESS, } } } @@ -720,8 +715,9 @@ impl<'a> IntoIterator for AbilitySet { impl fmt::Display for Address { fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result { match self { - Self::Anonymous(sp!(_, bytes)) => write!(f, "{}", bytes), - Self::Named(n, _) => write!(f, "{}", n), + Self::Numerical(None, sp!(_, bytes)) => write!(f, "{}", bytes), + Self::Numerical(Some(name), sp!(_, bytes)) => write!(f, "({}={})", name, bytes), + Self::NamedUnassigned(name) => write!(f, "{}", name), } } } diff --git a/language/move-compiler/src/expansion/mod.rs b/language/move-compiler/src/expansion/mod.rs index 9490c7664f..4613175c18 100644 --- a/language/move-compiler/src/expansion/mod.rs +++ b/language/move-compiler/src/expansion/mod.rs @@ -7,4 +7,3 @@ mod byte_string; mod dependency_ordering; mod hex_string; pub(crate) mod translate; -mod unique_modules_after_mapping; diff --git a/language/move-compiler/src/expansion/translate.rs b/language/move-compiler/src/expansion/translate.rs index fe54f4a678..dde419d149 100644 --- a/language/move-compiler/src/expansion/translate.rs +++ b/language/move-compiler/src/expansion/translate.rs @@ -128,7 +128,8 @@ pub fn program( let mut context = Context::new(compilation_env, module_members); - let mut module_map = UniqueMap::new(); + let mut source_module_map = UniqueMap::new(); + let mut lib_module_map = UniqueMap::new(); let mut scripts = vec![]; let P::Program { named_address_maps, @@ -139,15 +140,24 @@ pub fn program( context.is_source_definition = true; for (named_addr_map_idx, def) in source_definitions { context.named_address_mapping = Some(named_address_maps.get(named_addr_map_idx)); - definition(&mut context, &mut module_map, &mut scripts, def) + definition(&mut context, &mut source_module_map, &mut scripts, def) } context.is_source_definition = false; for (named_addr_map_idx, def) in lib_definitions { context.named_address_mapping = Some(named_address_maps.get(named_addr_map_idx)); - definition(&mut context, &mut module_map, &mut scripts, def) + definition(&mut context, &mut lib_module_map, &mut scripts, def) } + for (mident, module) in lib_module_map { + if let Err((mident, old_loc)) = source_module_map.add(mident, module) { + if !context.env.flags().sources_shadow_deps() { + duplicate_module(&mut context, &source_module_map, mident, old_loc) + } + } + } + let mut module_map = source_module_map; + let mut scripts = { let mut collected: BTreeMap> = BTreeMap::new(); for s in scripts { @@ -178,7 +188,6 @@ pub fn program( keyed }; - super::unique_modules_after_mapping::verify(context.env, &module_map); super::dependency_ordering::verify(context.env, &mut module_map, &mut scripts); E::Program { modules: module_map, @@ -244,16 +253,21 @@ fn address_( match ln_ { P::LeadingNameAccess_::AnonymousAddress(bytes) => { debug_assert!(name_res.is_ok()); // - Address::Anonymous(sp(loc, bytes)) + Address::Numerical(None, sp(loc, bytes)) } - P::LeadingNameAccess_::Name(n) => { - let addr = named_address_mapping.get(&n.value); - if name_res.is_ok() && addr.is_none() { - compilation_env.add_diag(address_without_value_error(suggest_declaration, loc, &n)); + P::LeadingNameAccess_::Name(n) => match named_address_mapping.get(&n.value).copied() { + Some(addr) => Address::Numerical(Some(n), sp(loc, addr)), + None => { + if name_res.is_ok() { + compilation_env.add_diag(address_without_value_error( + suggest_declaration, + loc, + &n, + )); + } + Address::NamedUnassigned(n) } - - Address::Named(n, addr.copied()) - } + }, } } @@ -293,6 +307,22 @@ fn check_module_address( } } +fn duplicate_module( + context: &mut Context, + module_map: &UniqueMap, + mident: ModuleIdent, + old_loc: Loc, +) { + let old_mident = module_map.get_key(&mident).unwrap(); + let dup_msg = format!("Duplicate definition for module '{}'", mident); + let prev_msg = format!("Module previously defined here, with '{}'", old_mident); + context.env.add_diag(diag!( + Declarations::DuplicateItem, + (mident.loc, dup_msg), + (old_loc, prev_msg), + )) +} + fn module( context: &mut Context, module_map: &mut UniqueMap, @@ -302,12 +332,7 @@ fn module( assert!(context.address == None); let (mident, mod_) = module_(context, module_address, module_def); if let Err((mident, old_loc)) = module_map.add(mident, mod_) { - let mmsg = format!("Duplicate definition for module '{}'", mident); - context.env.add_diag(diag!( - Declarations::DuplicateItem, - (mident.loc, mmsg), - (old_loc, "Module previously defined here"), - )); + duplicate_module(context, module_map, mident, old_loc) } context.address = None } @@ -330,7 +355,7 @@ fn set_sender_address( context .env .add_diag(diag!(Declarations::InvalidModule, (loc, msg))); - Address::Anonymous(sp(loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)) + Address::Numerical(None, sp(loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)) } }) } @@ -631,7 +656,9 @@ fn all_module_members<'a>( ) } // Error will be handled when the module is compiled - None => Address::Anonymous(sp(m.loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)), + None => { + Address::Numerical(None, sp(m.loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)) + } }; module_members(members, always_add, addr, m) } diff --git a/language/move-compiler/src/expansion/unique_modules_after_mapping.rs b/language/move-compiler/src/expansion/unique_modules_after_mapping.rs deleted file mode 100644 index 54b6290bd4..0000000000 --- a/language/move-compiler/src/expansion/unique_modules_after_mapping.rs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) The Diem Core Contributors -// SPDX-License-Identifier: Apache-2.0 - -use crate::{ - diag, - expansion::ast::{self as E, Address, ModuleIdent, ModuleIdent_}, - parser::ast::ModuleName, - shared::{unique_map::UniqueMap, *}, -}; -use move_ir_types::location::*; -use move_symbol_pool::Symbol; -use std::collections::BTreeMap; - -//************************************************************************************************** -// Entry -//************************************************************************************************** - -type RefinedModuleIdent = (Loc, Option, NumericalAddress, ModuleName); - -/// Verifies that modules remain unique, even after substituting named addresses for their values -pub fn verify( - compilation_env: &mut CompilationEnv, - modules: &UniqueMap, -) { - let mut decl_locs: BTreeMap<(NumericalAddress, Symbol), RefinedModuleIdent> = BTreeMap::new(); - for (sp!(loc, ModuleIdent_ { address, module }), _mdef) in modules.key_cloned_iter() { - let sp!(nloc, n_) = module.0; - let addr_name = match &address { - Address::Anonymous(_) => None, - Address::Named(n, _) => Some(*n), - }; - let addr_bytes = match &address { - Address::Anonymous(sp!(_, addr_bytes)) => *addr_bytes, - Address::Named(_, Some(addr_bytes)) => *addr_bytes, - // No mapping given, already an error - Address::Named(_, None) => continue, - }; - let mident_ = (addr_bytes, n_); - let compiled_mident = (loc, addr_name, addr_bytes, ModuleName(sp(nloc, n_))); - if let Some(prev) = decl_locs.insert(mident_, compiled_mident) { - let cur = &decl_locs[&mident_]; - let (orig, duplicate) = - if cur.0.file_hash() == prev.0.file_hash() && cur.0.start() > prev.0.start() { - (&prev, cur) - } else { - (cur, &prev) - }; - - // Formatting here is a bit weird, but it is guaranteed that at least one of the - // declarations (prev or cur) will have an address_name of Some(_) - let format_name = |m: &RefinedModuleIdent| match &m.1 { - None => format!("'{}::{}'", &m.2, &m.3), - Some(aname) => format!( - "'{aname}::{mname}', with '{aname}' = {abytes}", - aname = aname, - abytes = &m.2, - mname = &m.3 - ), - }; - let msg = format!("Duplicate definition of {}", format_name(duplicate)); - let prev_msg = format!("Module previously defined here as {}", format_name(orig)); - compilation_env.add_diag(diag!( - Declarations::DuplicateItem, - (duplicate.0, msg), - (orig.0, prev_msg) - )) - } - } -} diff --git a/language/move-compiler/src/hlir/ast.rs b/language/move-compiler/src/hlir/ast.rs index 40615a27e3..b2a05f52af 100644 --- a/language/move-compiler/src/hlir/ast.rs +++ b/language/move-compiler/src/hlir/ast.rs @@ -119,6 +119,7 @@ pub struct Function { //************************************************************************************************** #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] +#[allow(clippy::large_enum_variant)] pub enum TypeName_ { Builtin(BuiltinTypeName), ModuleType(ModuleIdent, StructName), diff --git a/language/move-compiler/src/naming/ast.rs b/language/move-compiler/src/naming/ast.rs index d75a4b2171..15a681057d 100644 --- a/language/move-compiler/src/naming/ast.rs +++ b/language/move-compiler/src/naming/ast.rs @@ -144,6 +144,7 @@ pub enum BuiltinTypeName_ { pub type BuiltinTypeName = Spanned; #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] +#[allow(clippy::large_enum_variant)] pub enum TypeName_ { // exp-list/tuple type Multiple(usize), diff --git a/language/move-compiler/src/parser/ast.rs b/language/move-compiler/src/parser/ast.rs index 661d49e293..a794fe02a7 100644 --- a/language/move-compiler/src/parser/ast.rs +++ b/language/move-compiler/src/parser/ast.rs @@ -967,13 +967,13 @@ impl AstDebug for Program { source_definitions, lib_definitions, } = self; - w.write("------ Lib Defs: ------"); + w.writeln("------ Lib Defs: ------"); for (idx, src) in lib_definitions { named_address_maps.get(*idx).ast_debug(w); src.ast_debug(w); } w.new_line(); - w.write("------ Source Defs: ------"); + w.writeln("------ Source Defs: ------"); for (idx, src) in source_definitions { named_address_maps.get(*idx).ast_debug(w); src.ast_debug(w); @@ -984,7 +984,8 @@ impl AstDebug for Program { impl AstDebug for NamedAddressMap { fn ast_debug(&self, w: &mut AstWriter) { for (sym, addr) in self { - w.writeln(&format!("{} => {}", sym, addr)) + w.write(&format!("{} => {}", sym, addr)); + w.new_line() } } } diff --git a/language/move-compiler/src/parser/mod.rs b/language/move-compiler/src/parser/mod.rs index 90e7c80de8..1721c74f45 100644 --- a/language/move-compiler/src/parser/mod.rs +++ b/language/move-compiler/src/parser/mod.rs @@ -8,7 +8,6 @@ pub mod ast; pub mod comments; pub mod keywords; pub(crate) mod merge_spec_modules; -pub(crate) mod sources_shadow_deps; use crate::{ diagnostics::{codes::Severity, Diagnostics, FilesSourceText}, @@ -41,11 +40,14 @@ pub(crate) fn parse_program( let mut res = vec![]; for (paths, idx) in paths_with_mapping { res.extend( - find_move_filenames(&[paths], true)? + find_move_filenames(&[paths.as_str()], true)? .into_iter() .map(|s| (Symbol::from(s), idx)), ); } + // sort the filenames so errors about redefinitions, or other inter-file conflicts, are + // deterministic + res.sort_by(|(fname1, _), (fname2, _)| fname1.cmp(fname2)); Ok(res) } diff --git a/language/move-compiler/src/parser/sources_shadow_deps.rs b/language/move-compiler/src/parser/sources_shadow_deps.rs deleted file mode 100644 index 35b4be3b27..0000000000 --- a/language/move-compiler/src/parser/sources_shadow_deps.rs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) The Diem Core Contributors -// SPDX-License-Identifier: Apache-2.0 - -use crate::{ - parser::ast::{Definition, Program}, - shared::*, -}; -use std::collections::BTreeSet; - -use super::ast::LeadingNameAccess_; - -/// Given a parsed program, if a module id is found in both the source and lib definitions, filter -/// out the lib definition and re-construct a new parsed program -pub fn program(compilation_env: &CompilationEnv, prog: Program) -> Program { - if !compilation_env.flags().sources_shadow_deps() { - return prog; - } - - let Program { - named_address_maps, - source_definitions, - lib_definitions, - } = prog; - let mut modules_defined_in_src = BTreeSet::new(); - for (_, def) in &source_definitions { - match def { - Definition::Address(a) => { - let addr = a.addr.value; - for module in &a.modules { - modules_defined_in_src.insert((addr, module.name)); - } - } - Definition::Module(module) => { - modules_defined_in_src.insert(( - module.address.map(|a| a.value).unwrap_or_else(|| { - LeadingNameAccess_::AnonymousAddress( - NumericalAddress::DEFAULT_ERROR_ADDRESS, - ) - }), - module.name, - )); - } - Definition::Script(_) => (), - } - } - - // Shadow (i.e., filter out) library definitions with the following criteria - // 1. this library definition is an Address space AST and any module in the address space is - // already defined in the source. - // 2. this library definition is a Module AST and the module is already defined in the source. - let lib_definitions = lib_definitions - .into_iter() - .map(|(address_map, def)| match def { - Definition::Address(mut a) => { - let addr = a.addr.value; - let modules = std::mem::take(&mut a.modules); - a.modules = modules - .into_iter() - .filter(|module| !modules_defined_in_src.contains(&(addr, module.name))) - .collect(); - (address_map, Definition::Address(a)) - } - def => (address_map, def), - }) - .filter(|(_, def)| match def { - Definition::Address(_) => true, - Definition::Module(module) => !modules_defined_in_src.contains(&( - module.address.map(|a| a.value).unwrap_or_else(|| { - LeadingNameAccess_::AnonymousAddress(NumericalAddress::DEFAULT_ERROR_ADDRESS) - }), - module.name, - )), - Definition::Script(_) => false, - }) - .collect(); - - Program { - named_address_maps, - source_definitions, - lib_definitions, - } -} diff --git a/language/move-compiler/src/shared/mod.rs b/language/move-compiler/src/shared/mod.rs index 9ef3d17f7b..78f318cf09 100644 --- a/language/move-compiler/src/shared/mod.rs +++ b/language/move-compiler/src/shared/mod.rs @@ -314,14 +314,14 @@ pub fn shortest_cycle<'a, T: Ord + Hash>( // Compilation Env //************************************************************************************************** -pub type AddressScopedFiles = (Vec, BTreeMap); +pub type AddressScopedFiles = + (Vec, BTreeMap); pub type NamedAddressMap = BTreeMap; -pub(crate) type AddressScopedFileIndexed = (String, NamedAddressMapIndex); - -pub type AttributeDeriver = dyn Fn(&mut CompilationEnv, &mut ModuleDefinition); +pub(crate) type AddressScopedFileIndexed = (Symbol, NamedAddressMapIndex); #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct NamedAddressMapIndex(usize); + #[derive(Clone, Debug, Eq, PartialEq)] pub struct NamedAddressMaps(Vec); @@ -341,6 +341,8 @@ impl NamedAddressMaps { } } +pub type AttributeDeriver = dyn Fn(&mut CompilationEnv, &mut ModuleDefinition); + #[derive(Clone, Debug, Eq, PartialEq)] pub struct CompilationEnv { flags: Flags, @@ -448,21 +450,21 @@ pub struct Flags { )] flavor: String, - /// If set, do not allow modules defined in source_files to shadow modules of the same id that - /// exist in dependencies. Checking will fail in this case. + /// If set, source files will not shadow dependency files. If the same file is passed to both, + /// an error will be raised #[clap( - name = "SOURCES_DO_NOT_SHADOW_DEPS", - short = cli::NO_SHADOW_SHORT, - long = cli::NO_SHADOW, + name = "SOURCES_SHADOW_DEPS", + short = cli::SHADOW_SHORT, + long = cli::SHADOW, )] - no_shadow: bool, + shadow: bool, } impl Flags { pub fn empty() -> Self { Self { test: false, - no_shadow: false, + shadow: false, flavor: "".to_string(), } } @@ -470,7 +472,7 @@ impl Flags { pub fn testing() -> Self { Self { test: true, - no_shadow: false, + shadow: false, flavor: "".to_string(), } } @@ -484,7 +486,7 @@ impl Flags { pub fn set_sources_shadow_deps(self, sources_shadow_deps: bool) -> Self { Self { - no_shadow: !sources_shadow_deps, + shadow: sources_shadow_deps, ..self } } @@ -498,7 +500,7 @@ impl Flags { } pub fn sources_shadow_deps(&self) -> bool { - !self.no_shadow + self.shadow } pub fn get_flavor(&self) -> &str { diff --git a/language/move-compiler/src/shared/unique_map.rs b/language/move-compiler/src/shared/unique_map.rs index ede989afc6..e1a2bec9e7 100644 --- a/language/move-compiler/src/shared/unique_map.rs +++ b/language/move-compiler/src/shared/unique_map.rs @@ -67,6 +67,10 @@ impl UniqueMap { self.0.get(key_).map(|loc_value| &loc_value.0) } + pub fn get_key(&self, key: &K) -> Option<&K::Key> { + self.0.get_key_value(key.borrow().1).map(|(k, _v)| k) + } + pub fn remove(&mut self, key: &K) -> Option { self.remove_(key.borrow().1) } diff --git a/language/move-compiler/src/to_bytecode/context.rs b/language/move-compiler/src/to_bytecode/context.rs index e531992512..33d5180c02 100644 --- a/language/move-compiler/src/to_bytecode/context.rs +++ b/language/move-compiler/src/to_bytecode/context.rs @@ -207,8 +207,8 @@ impl<'a> Context<'a> { fn ir_module_alias(sp!(_, ModuleIdent_ { address, module }): &ModuleIdent) -> IR::ModuleName { let s = match address { - Address::Anonymous(sp!(_, a_)) => format!("{:X}::{}", a_, module), - Address::Named(n, _) => format!("{}::{}", n, module), + Address::Numerical(_, sp!(_, a_)) => format!("{:X}::{}", a_, module), + Address::NamedUnassigned(name) => format!("{}::{}", name, module), }; IR::ModuleName(s.into()) } diff --git a/language/move-compiler/src/to_bytecode/translate.rs b/language/move-compiler/src/to_bytecode/translate.rs index e844b6703c..480b296f70 100644 --- a/language/move-compiler/src/to_bytecode/translate.rs +++ b/language/move-compiler/src/to_bytecode/translate.rs @@ -192,8 +192,8 @@ fn module( .collect(); let addr_name = match &ident.value.address { - Address::Anonymous(_) => None, - Address::Named(n, _) => Some(*n), + Address::Numerical(None, _) => None, + Address::Numerical(Some(name), _) | Address::NamedUnassigned(name) => Some(*name), }; let addr_bytes = context.resolve_address(ident.value.address); let (imports, explicit_dependency_declarations) = context.materialize( diff --git a/language/move-compiler/tests/move_check/expansion/duplicate_module.exp b/language/move-compiler/tests/move_check/expansion/duplicate_module.exp index 1e4126ccb3..9f47b19f5b 100644 --- a/language/move-compiler/tests/move_check/expansion/duplicate_module.exp +++ b/language/move-compiler/tests/move_check/expansion/duplicate_module.exp @@ -2,7 +2,7 @@ error[E02001]: duplicate declaration, item, or annotation ┌─ tests/move_check/expansion/duplicate_module.move:2:19 │ 1 │ module 0x8675309::M {} - │ - Module previously defined here + │ - Module previously defined here, with '0x8675309::M' 2 │ module 0x8675309::M {} │ ^ Duplicate definition for module '0x8675309::M' diff --git a/language/move-compiler/tests/move_check/expansion/duplicate_module_after_mapping.exp b/language/move-compiler/tests/move_check/expansion/duplicate_module_after_mapping.exp index 7cd2105e8b..6cef28fd73 100644 --- a/language/move-compiler/tests/move_check/expansion/duplicate_module_after_mapping.exp +++ b/language/move-compiler/tests/move_check/expansion/duplicate_module_after_mapping.exp @@ -2,23 +2,23 @@ error[E02001]: duplicate declaration, item, or annotation ┌─ tests/move_check/expansion/duplicate_module_after_mapping.move:5:11 │ 4 │ module A::M {} - │ - Module previously defined here as 'A::M', with 'A' = 0x42 + │ - Module previously defined here, with '(A=0x42)::M' 5 │ module B::M {} - │ ^ Duplicate definition of 'B::M', with 'B' = 0x42 + │ ^ Duplicate definition for module '(B=0x42)::M' error[E02001]: duplicate declaration, item, or annotation ┌─ tests/move_check/expansion/duplicate_module_after_mapping.move:9:11 │ 8 │ module 0x1::M {} - │ - Module previously defined here as '0x1::M' + │ - Module previously defined here, with '0x1::M' 9 │ module M::M {} - │ ^ Duplicate definition of 'M::M', with 'M' = 0x1 + │ ^ Duplicate definition for module '(M=0x1)::M' error[E02001]: duplicate declaration, item, or annotation ┌─ tests/move_check/expansion/duplicate_module_after_mapping.move:13:14 │ 12 │ module K::M {} - │ - Module previously defined here as 'K::M', with 'K' = 0x19 + │ - Module previously defined here, with '(K=0x19)::M' 13 │ module 0x19::M {} - │ ^ Duplicate definition of '0x19::M' + │ ^ Duplicate definition for module '0x19::M' diff --git a/language/move-compiler/tests/move_check/expansion/unbound_named_address.exp b/language/move-compiler/tests/move_check/expansion/unbound_named_address.exp index 67c176b161..128b76145b 100644 --- a/language/move-compiler/tests/move_check/expansion/unbound_named_address.exp +++ b/language/move-compiler/tests/move_check/expansion/unbound_named_address.exp @@ -1,8 +1,8 @@ error[E03002]: unbound module ┌─ tests/move_check/expansion/unbound_named_address.move:3:9 │ -3 │ use B::M; - │ ^^^^ Invalid 'use'. Unbound module: 'B::M' +3 │ use B::X; + │ ^^^^ Invalid 'use'. Unbound module: '(B=0x42)::X' error[E02011]: invalid 'friend' declaration ┌─ tests/move_check/expansion/unbound_named_address.move:5:5 diff --git a/language/move-compiler/tests/move_check/expansion/unbound_named_address.move b/language/move-compiler/tests/move_check/expansion/unbound_named_address.move index 0aec019d91..934fb5a113 100644 --- a/language/move-compiler/tests/move_check/expansion/unbound_named_address.move +++ b/language/move-compiler/tests/move_check/expansion/unbound_named_address.move @@ -1,6 +1,6 @@ // Unbound address in all cases module A::M { // suggests declaration - use B::M; + use B::X; friend C::M; friend D::M::foo; diff --git a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.exp b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.exp deleted file mode 100644 index 2a2148c8e5..0000000000 --- a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.exp +++ /dev/null @@ -1,33 +0,0 @@ -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_each_other.move:11:9 - │ -11 │ use B::M; - │ ^^^^ Invalid 'use'. Unbound module: 'B::M' - -error[E02011]: invalid 'friend' declaration - ┌─ tests/move_check/naming/named_address_distinct_from_each_other.move:12:5 - │ -12 │ friend B::M; - │ ^^^^^^^^^^^^ - │ │ │ - │ │ Cannot declare modules out of the current address as a friend - │ Invalid friend declaration - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_each_other.move:13:22 - │ -13 │ public fun ex(): B::M::S { - │ ^^^^ Unbound module 'B::M' - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_each_other.move:14:9 - │ -14 │ B::M::C; - │ ^^^^ Unbound module 'B::M' - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_each_other.move:15:9 - │ -15 │ B::M::s() - │ ^^^^ Unbound module 'B::M' - diff --git a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.exp b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.exp new file mode 100644 index 0000000000..362a2aa9c6 --- /dev/null +++ b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.exp @@ -0,0 +1,9 @@ +error[E04001]: restricted visibility + ┌─ tests/move_check/naming/named_address_distinct_from_each_others_value.move:18:9 + │ + 6 │ const C: u64 = 0; + │ - Constants are internal to their module, and cannot can be accessed outside of their module + · +18 │ B::M::C; + │ ^^^^^^^ Invalid access of '(B=0x42)::M::C' + diff --git a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.move b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.move similarity index 50% rename from language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.move rename to language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.move index 06983db820..64909f4088 100644 --- a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_other.move +++ b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_each_others_value.move @@ -1,5 +1,6 @@ // These checks straddle a few different passes but -// Named addresses are distinct from each other, even if the value is the same +// Named addresses are no longer distinct from their value, even with a different name +// This is due to the package system mostly maintaining the value module A::M { const C: u64 = 0; @@ -7,11 +8,18 @@ module A::M { public fun s(): S { S{} } } -module A::Ex { - use B::M; +module A::Ex0 { friend B::M; +} + +module A::Ex1 { + use B::M; public fun ex(): B::M::S { B::M::C; B::M::s() } + + public fun ex2(): M::S { + ex() + } } diff --git a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.exp b/language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.exp deleted file mode 100644 index 2ffade7a03..0000000000 --- a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.exp +++ /dev/null @@ -1,33 +0,0 @@ -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_value.move:11:9 - │ -11 │ use 0x42::M; - │ ^^^^^^^ Invalid 'use'. Unbound module: '0x42::M' - -error[E02011]: invalid 'friend' declaration - ┌─ tests/move_check/naming/named_address_distinct_from_value.move:12:5 - │ -12 │ friend 0x42::M; - │ ^^^^^^^^^^^^^^^ - │ │ │ - │ │ Cannot declare modules out of the current address as a friend - │ Invalid friend declaration - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_value.move:13:22 - │ -13 │ public fun ex(): 0x42::M::S { - │ ^^^^^^^ Unbound module '0x42::M' - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_value.move:14:9 - │ -14 │ 0x42::M::C; - │ ^^^^^^^ Unbound module '0x42::M' - -error[E03002]: unbound module - ┌─ tests/move_check/naming/named_address_distinct_from_value.move:15:9 - │ -15 │ 0x42::M::s() - │ ^^^^^^^ Unbound module '0x42::M' - diff --git a/language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.exp b/language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.exp new file mode 100644 index 0000000000..5877ae2b22 --- /dev/null +++ b/language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.exp @@ -0,0 +1,9 @@ +error[E04001]: restricted visibility + ┌─ tests/move_check/naming/named_address_not_distinct_from_value.move:18:9 + │ + 6 │ const C: u64 = 0; + │ - Constants are internal to their module, and cannot can be accessed outside of their module + · +18 │ 0x42::M::C; + │ ^^^^^^^^^^ Invalid access of '0x42::M::C' + diff --git a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.move b/language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.move similarity index 55% rename from language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.move rename to language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.move index 664fd4f119..50dca40915 100644 --- a/language/move-compiler/tests/move_check/naming/named_address_distinct_from_value.move +++ b/language/move-compiler/tests/move_check/naming/named_address_not_distinct_from_value.move @@ -1,5 +1,6 @@ // These checks straddle a few different passes but -// Named addresses are distinct from their value +// Named addresses are no longer distinct from their value +// This is due to the package system mostly maintaining the value module A::M { const C: u64 = 0; @@ -7,11 +8,18 @@ module A::M { public fun s(): S { S{} } } -module A::Ex { - use 0x42::M; +module A::Ex0 { friend 0x42::M; +} + +module A::Ex1 { + use 0x42::M; public fun ex(): 0x42::M::S { 0x42::M::C; 0x42::M::s() } + + public fun ex2(): M::S { + ex() + } } diff --git a/language/move-model/src/builder/model_builder.rs b/language/move-model/src/builder/model_builder.rs index 8fa990570b..301f649b65 100644 --- a/language/move-model/src/builder/model_builder.rs +++ b/language/move-model/src/builder/model_builder.rs @@ -291,10 +291,9 @@ impl<'env> ModelBuilder<'env> { pub fn resolve_address(&self, loc: &Loc, addr: &EA::Address) -> NumericalAddress { match addr { - EA::Address::Anonymous(bytes) => bytes.value, - EA::Address::Named(_n, Some(bytes)) => *bytes, - EA::Address::Named(n, None) => { - self.error(loc, &format!("Undeclared address `{}`", n)); + EA::Address::Numerical(_, bytes) => bytes.value, + EA::Address::NamedUnassigned(name) => { + self.error(loc, &format!("Undeclared address `{}`", name)); NumericalAddress::DEFAULT_ERROR_ADDRESS } } diff --git a/language/move-model/src/lib.rs b/language/move-model/src/lib.rs index ad099705b8..d06d8116b5 100644 --- a/language/move-model/src/lib.rs +++ b/language/move-model/src/lib.rs @@ -8,6 +8,7 @@ use codespan_reporting::diagnostic::{Diagnostic, Label, LabelStyle}; use itertools::Itertools; #[allow(unused_imports)] use log::warn; +use move_symbol_pool::Symbol as MoveSymbol; use std::collections::{BTreeMap, BTreeSet}; use builder::module_builder::ModuleBuilder; @@ -27,7 +28,7 @@ use move_compiler::{ diagnostics::Diagnostics, expansion::ast::{self as E, Address, ModuleDefinition, ModuleIdent, ModuleIdent_}, parser::ast::{self as P, ModuleName as ParserModuleName}, - shared::{parse_named_address, unique_map::UniqueMap, NumericalAddress}, + shared::{parse_named_address, unique_map::UniqueMap, AddressScopedFiles, NumericalAddress}, Compiler, Flags, PASS_COMPILATION, PASS_EXPANSION, PASS_PARSER, }; use move_core_types::{account_address::AccountAddress, identifier::Identifier}; @@ -61,55 +62,47 @@ pub mod ty; /// Build the move model with default compilation flags and default options and no named addresses. /// This collects transitive dependencies for move sources from the provided directory list. -pub fn run_model_builder( - move_sources: &[String], - deps_dir: &[String], +pub fn run_model_builder, NamedAddress: Into>( + move_sources: Vec>, + deps: Vec>, ) -> anyhow::Result { - run_model_builder_with_options( - move_sources, - deps_dir, - ModelBuilderOptions::default(), - BTreeMap::new(), - ) + run_model_builder_with_options(move_sources, deps, ModelBuilderOptions::default()) } /// Build the move model with default compilation flags and custom options and a set of provided /// named addreses. /// This collects transitive dependencies for move sources from the provided directory list. -pub fn run_model_builder_with_options( - move_sources: &[String], - deps_dir: &[String], +pub fn run_model_builder_with_options, NamedAddress: Into>( + move_sources: Vec>, + deps: Vec>, options: ModelBuilderOptions, - named_address_mapping: BTreeMap, ) -> anyhow::Result { run_model_builder_with_options_and_compilation_flags( move_sources, - deps_dir, + deps, options, Flags::empty(), - named_address_mapping, ) } /// Build the move model with custom compilation flags and custom options /// This collects transitive dependencies for move sources from the provided directory list. -pub fn run_model_builder_with_options_and_compilation_flags( - move_sources: &[String], - deps_dir: &[String], +pub fn run_model_builder_with_options_and_compilation_flags< + Paths: Into, + NamedAddress: Into, +>( + move_sources: Vec>, + deps: Vec>, options: ModelBuilderOptions, flags: Flags, - named_address_mapping: BTreeMap, ) -> anyhow::Result { let mut env = GlobalEnv::new(); env.set_extension(options); // Step 1: parse the program to get comments and a separation of targets and dependencies. - let (files, comments_and_compiler_res) = Compiler::new( - vec![(move_sources.to_vec(), named_address_mapping.clone())], - vec![(deps_dir.to_vec(), named_address_mapping)], - ) - .set_flags(flags) - .run::()?; + let (files, comments_and_compiler_res) = Compiler::new(move_sources, deps) + .set_flags(flags) + .run::()?; let (comment_map, compiler) = match comments_and_compiler_res { Err(diags) => { // Add source files so that the env knows how to translate locations of parse errors @@ -167,17 +160,11 @@ pub fn run_model_builder_with_options_and_compilation_flags( Ok(compiler) => compiler.into_ast(), }; // Extract the module/script closure - let mut visited_addresses = BTreeSet::new(); let mut visited_modules = BTreeSet::new(); for (_, mident, mdef) in &expansion_ast.modules { let src_file_hash = mdef.loc.file_hash(); if !dep_files.contains(&src_file_hash) { - collect_related_modules_recursive( - mident, - &expansion_ast.modules, - &mut visited_addresses, - &mut visited_modules, - ); + collect_related_modules_recursive(mident, &expansion_ast.modules, &mut visited_modules); } } for sdef in expansion_ast.scripts.values() { @@ -187,15 +174,9 @@ pub fn run_model_builder_with_options_and_compilation_flags( collect_related_modules_recursive( mident, &expansion_ast.modules, - &mut visited_addresses, &mut visited_modules, ); } - for addr in &sdef.used_addresses { - if let Address::Named(n, _) = &addr { - visited_addresses.insert(&n.value); - } - } } } @@ -243,34 +224,18 @@ pub fn run_model_builder_with_options_and_compilation_flags( Ok(env) } -fn collect_used_addresses<'a>( - used_addresses: &'a BTreeSet
, - visited_addresses: &mut BTreeSet<&'a str>, -) { - for addr in used_addresses { - if let Address::Named(n, _) = &addr { - visited_addresses.insert(&n.value); - } - } -} - fn collect_related_modules_recursive<'a>( mident: &'a ModuleIdent_, modules: &'a UniqueMap, - visited_addresses: &mut BTreeSet<&'a str>, visited_modules: &mut BTreeSet, ) { if visited_modules.contains(mident) { return; } let mdef = modules.get_(mident).unwrap(); - if let Address::Named(n, _) = &mident.address { - visited_addresses.insert(&n.value); - } - collect_used_addresses(&mdef.used_addresses, visited_addresses); visited_modules.insert(*mident); for (_, next_mident, _) in &mdef.immediate_neighbors { - collect_related_modules_recursive(next_mident, modules, visited_addresses, visited_modules); + collect_related_modules_recursive(next_mident, modules, visited_modules); } } @@ -512,7 +477,7 @@ fn run_spec_checker(env: &mut GlobalEnv, units: Vec, mut }; // Convert the script into a module. let address = - Address::Anonymous(sp(loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)); + Address::Numerical(None, sp(loc, NumericalAddress::DEFAULT_ERROR_ADDRESS)); let ident = sp( loc, ModuleIdent_::new(address, ParserModuleName(function_name.0)), diff --git a/language/move-model/tests/testsuite.rs b/language/move-model/tests/testsuite.rs index a84e65653d..60020391e5 100644 --- a/language/move-model/tests/testsuite.rs +++ b/language/move-model/tests/testsuite.rs @@ -12,8 +12,11 @@ use move_prover_test_utils::baseline_test::verify_or_update_baseline; use std::path::Path; fn test_runner(path: &Path) -> datatest_stable::Result<()> { - let targets = vec![path.to_str().unwrap().to_string()]; - let env = run_model_builder(&targets, &[])?; + let targets = vec![( + vec![path.to_str().unwrap().to_string()], + std::collections::BTreeMap::::new(), + )]; + let env = run_model_builder(targets, vec![])?; let diags = if env.diag_count(Severity::Warning) > 0 { let mut writer = Buffer::no_color(); env.report_diag(&mut writer, Severity::Warning); diff --git a/language/move-prover/bytecode/tests/testsuite.rs b/language/move-prover/bytecode/tests/testsuite.rs index 064fee1ec8..a247bb3785 100644 --- a/language/move-prover/bytecode/tests/testsuite.rs +++ b/language/move-prover/bytecode/tests/testsuite.rs @@ -214,10 +214,9 @@ fn test_runner(path: &Path) -> datatest_stable::Result<()> { let mut sources = extract_test_directives(path, "// dep:")?; sources.push(path.to_string_lossy().to_string()); let env: GlobalEnv = run_model_builder_with_options( - &sources, - &[], + vec![(sources, move_stdlib::move_stdlib_named_addresses())], + vec![], ModelBuilderOptions::default(), - move_stdlib::move_stdlib_named_addresses(), )?; let out = if env.has_errors() { let mut error_writer = Buffer::no_color(); diff --git a/language/move-prover/lab/src/benchmark.rs b/language/move-prover/lab/src/benchmark.rs index deab0cdc68..e1c925b7a6 100644 --- a/language/move-prover/lab/src/benchmark.rs +++ b/language/move-prover/lab/src/benchmark.rs @@ -127,11 +127,11 @@ fn run_benchmark( } else { Options::default() }; + let addrs = parse_addresses_from_options(options.move_named_address_values.clone())?; let env = run_model_builder_with_options( - modules, - dep_dirs, + vec![(modules.to_vec(), addrs.clone())], + vec![(dep_dirs.to_vec(), addrs)], options.model_builder.clone(), - parse_addresses_from_options(options.move_named_address_values.clone())?, )?; let mut error_writer = StandardStream::stderr(ColorChoice::Auto); diff --git a/language/move-prover/mutation/src/mutator.rs b/language/move-prover/mutation/src/mutator.rs index 50fc9ccb8c..c7cff84373 100644 --- a/language/move-prover/mutation/src/mutator.rs +++ b/language/move-prover/mutation/src/mutator.rs @@ -121,11 +121,11 @@ fn apply_mutation( dep_dirs: &[String], ) -> anyhow::Result<()> { println!("building model"); + let addrs = parse_addresses_from_options(addresses.to_owned())?; let env = run_model_builder_with_options( - modules, - dep_dirs, + vec![(modules.to_vec(), addrs.clone())], + vec![(dep_dirs.to_vec(), addrs)], ModelBuilderOptions::default(), - parse_addresses_from_options(addresses.to_owned())?, )?; let mut error_writer = StandardStream::stderr(ColorChoice::Auto); let mut options = if let Some(config_file) = config_file_opt { diff --git a/language/move-prover/src/lib.rs b/language/move-prover/src/lib.rs index 4c26c94c94..22399bf59f 100644 --- a/language/move-prover/src/lib.rs +++ b/language/move-prover/src/lib.rs @@ -51,11 +51,11 @@ pub fn run_move_prover( ) -> anyhow::Result<()> { let now = Instant::now(); // Run the model builder. + let addrs = parse_addresses_from_options(options.move_named_address_values.clone())?; let env = run_model_builder_with_options( - &options.move_sources, - &options.move_deps, + vec![(options.move_sources.clone(), addrs.clone())], + vec![(options.move_deps.clone(), addrs)], options.model_builder.clone(), - parse_addresses_from_options(options.move_named_address_values.clone())?, )?; run_move_prover_with_model(&env, error_writer, options, Some(now)) } diff --git a/language/move-prover/tools/spec-flatten/src/workflow.rs b/language/move-prover/tools/spec-flatten/src/workflow.rs index 57e53d2c22..f31839d45b 100644 --- a/language/move-prover/tools/spec-flatten/src/workflow.rs +++ b/language/move-prover/tools/spec-flatten/src/workflow.rs @@ -97,10 +97,9 @@ pub(crate) fn prepare_with_override( // run move model builder let mut env = run_model_builder_with_options( - &options.srcs, - &options.deps, + vec![(options.srcs.clone(), named_addresses.clone())], + vec![(options.deps.clone(), named_addresses.clone())], get_model_options(options), - named_addresses, )?; if env.has_errors() { return Err(anyhow!("Error in model building")); diff --git a/language/move-vm/integration-tests/src/compiler.rs b/language/move-vm/integration-tests/src/compiler.rs index 2727b02b14..3deca39f15 100644 --- a/language/move-vm/integration-tests/src/compiler.rs +++ b/language/move-vm/integration-tests/src/compiler.rs @@ -3,7 +3,7 @@ use anyhow::{bail, Result}; use move_binary_format::file_format::{CompiledModule, CompiledScript}; -use move_compiler::{compiled_unit::AnnotatedCompiledUnit, Compiler as MoveCompiler, Flags}; +use move_compiler::{compiled_unit::AnnotatedCompiledUnit, Compiler as MoveCompiler}; use std::{fs::File, io::Write, path::Path}; use tempfile::tempdir; @@ -23,7 +23,6 @@ pub fn compile_units(s: &str) -> Result> { )], vec![], ) - .set_flags(Flags::empty().set_sources_shadow_deps(false)) .build_and_report()?; dir.close()?; @@ -44,11 +43,10 @@ pub fn compile_modules_in_file(path: &Path) -> Result> { let (_, units) = MoveCompiler::new( vec![( vec![path.to_str().unwrap().to_string()], - std::collections::BTreeMap::new(), + std::collections::BTreeMap::::new(), )], vec![], ) - .set_flags(Flags::empty().set_sources_shadow_deps(false)) .build_and_report()?; expect_modules(units).collect() diff --git a/language/testing-infra/transactional-test-runner/src/framework.rs b/language/testing-infra/transactional-test-runner/src/framework.rs index cda5310548..642ff4490a 100644 --- a/language/testing-infra/transactional-test-runner/src/framework.rs +++ b/language/testing-infra/transactional-test-runner/src/framework.rs @@ -432,6 +432,7 @@ fn compile_source_unit( vec![(deps.to_vec(), named_address_mapping)], ) .set_pre_compiled_lib_opt(pre_compiled_deps) + .set_flags(move_compiler::Flags::empty().set_sources_shadow_deps(true)) .run::()?; let units_or_diags = comments_and_compiler_res .map(|(_comments, move_compiler)| move_compiler.into_compiled_units()); diff --git a/language/testing-infra/transactional-test-runner/src/vm_test_harness.rs b/language/testing-infra/transactional-test-runner/src/vm_test_harness.rs index 4ae5ba5b7f..e139aaffc3 100644 --- a/language/testing-infra/transactional-test-runner/src/vm_test_harness.rs +++ b/language/testing-infra/transactional-test-runner/src/vm_test_harness.rs @@ -291,7 +291,7 @@ static PRECOMPILED_MOVE_STDLIB: Lazy = Lazy::new(|| { move_stdlib::move_stdlib_named_addresses(), )], None, - move_compiler::Flags::empty().set_sources_shadow_deps(false), + move_compiler::Flags::empty(), ) .unwrap(); match program_res { diff --git a/language/tools/move-cli/src/base/commands/check.rs b/language/tools/move-cli/src/base/commands/check.rs index 8a4878a7d7..9fbcc4870f 100644 --- a/language/tools/move-cli/src/base/commands/check.rs +++ b/language/tools/move-cli/src/base/commands/check.rs @@ -4,11 +4,7 @@ use std::collections::BTreeMap; use anyhow::Result; -use move_compiler::{ - self, - shared::{Flags, NumericalAddress}, - Compiler, -}; +use move_compiler::{self, shared::NumericalAddress, Compiler, Flags}; /// Type-check the user modules in `files` and the dependencies in `interface_files` pub fn check( diff --git a/language/tools/move-cli/src/base/commands/compile.rs b/language/tools/move-cli/src/base/commands/compile.rs index ea29070e50..e299547476 100644 --- a/language/tools/move-cli/src/base/commands/compile.rs +++ b/language/tools/move-cli/src/base/commands/compile.rs @@ -4,11 +4,7 @@ use std::collections::BTreeMap; use anyhow::Result; -use move_compiler::{ - self, - shared::{Flags, NumericalAddress}, - Compiler, -}; +use move_compiler::{self, shared::NumericalAddress, Compiler, Flags}; /// Compile the user modules in `sources` against the dependencies in `interface_files`, placing /// the resulting binaries in `output_dir`. diff --git a/language/tools/move-cli/tests/testsuite/build_include_exclude_stdlib/args.exp b/language/tools/move-cli/tests/testsuite/build_include_exclude_stdlib/args.exp index 5c05869593..6f988d4a2d 100644 --- a/language/tools/move-cli/tests/testsuite/build_include_exclude_stdlib/args.exp +++ b/language/tools/move-cli/tests/testsuite/build_include_exclude_stdlib/args.exp @@ -4,7 +4,7 @@ error[E03002]: unbound module ┌─ ./sources/UseSigner.move:2:7 │ 2 │ use Std::Signer; - │ ^^^^^^^^^^^ Invalid 'use'. Unbound module: 'Std::Signer' + │ ^^^^^^^^^^^ Invalid 'use'. Unbound module: '(Std=0x1)::Signer' error[E03002]: unbound module ┌─ ./sources/UseSigner.move:5:5 diff --git a/language/tools/move-cli/tests/testsuite/use_named_address/args.exp b/language/tools/move-cli/tests/testsuite/use_named_address/args.exp index bf06b0579f..fd9fe26181 100644 --- a/language/tools/move-cli/tests/testsuite/use_named_address/args.exp +++ b/language/tools/move-cli/tests/testsuite/use_named_address/args.exp @@ -3,10 +3,10 @@ error[E02001]: duplicate declaration, item, or annotation ┌─ ./sources/M_no_named.move:1:14 │ 1 │ module 0x42::M { - │ ^ Duplicate definition of '0x42::M' + │ ^ Duplicate definition for module '0x42::M' │ ┌─ ./sources/M.move:1:11 │ 1 │ module A::M { - │ - Module previously defined here as 'A::M', with 'A' = 0x42 + │ - Module previously defined here, with '(A=0x42)::M' diff --git a/language/tools/move-package/src/compilation/compiled_package.rs b/language/tools/move-package/src/compilation/compiled_package.rs index fdfdc7b92c..b8f3eb1381 100644 --- a/language/tools/move-package/src/compilation/compiled_package.rs +++ b/language/tools/move-package/src/compilation/compiled_package.rs @@ -24,15 +24,16 @@ use move_compiler::{ AnnotatedCompiledUnit, CompiledUnit, NamedCompiledModule, NamedCompiledScript, }, diagnostics::FilesSourceText, - shared::{Flags, NumericalAddress}, + shared::{AddressScopedFiles, Flags, NamedAddressMap, NumericalAddress}, Compiler, }; use move_core_types::language_storage::ModuleId; use move_docgen::{Docgen, DocgenOptions}; use move_model::{model::GlobalEnv, options::ModelBuilderOptions, run_model_builder_with_options}; +use move_symbol_pool::Symbol; use serde::{Deserialize, Serialize}; use std::{ - collections::BTreeMap, + collections::{BTreeMap, BTreeSet}, io::Write, path::{Path, PathBuf}, }; @@ -463,7 +464,7 @@ impl CompiledPackage { w: &mut W, project_root: &Path, resolved_package: ResolvedPackage, - dependencies: Vec<(CompiledPackage, CompilationCachingStatus)>, + dependencies_with_status: Vec<(CompiledPackage, CompilationCachingStatus)>, resolution_graph: &ResolvedGraph, is_root_package: bool, mut compiler_driver: impl FnMut( @@ -472,25 +473,16 @@ impl CompiledPackage { ) -> Result<(FilesSourceText, Vec)>, ) -> Result<(CompiledPackage, CompilationCachingStatus)> { - let mut module_resolution_metadata = BTreeMap::new(); - - // NB: This renaming needs to be applied in the topological order of dependencies - for package in &dependencies { - package - .0 - .apply_renaming(&mut module_resolution_metadata, &resolved_package.renaming) - } - let build_root_path = project_root.join(CompiledPackageLayout::Root.path()); let path = build_root_path .join(resolved_package.source_package.package.name.as_str()) .join(CompiledPackageLayout::BuildInfo.path()); - // Compare the digest of the package being compiled against the digest of the package at the time - // of the last compilation to determine if we can reuse the already-compiled package or + // Compare the digest of the package being compiled against the digest of the package at the + // time of the last compilation to determine if we can reuse the already-compiled package or // not. If any dependency has changed we need to recompile. if let Ok(package) = OnDiskCompiledPackage::from_path(&path) { - if dependencies + if dependencies_with_status .iter() .all(|(_, cache_status)| cache_status.is_cached()) && Self::can_load_cached( @@ -517,60 +509,44 @@ impl CompiledPackage { "BUILDING".bold().green(), resolved_package.source_package.package.name, )?; - let dependencies: Vec<_> = dependencies.into_iter().map(|x| x.0).collect(); - let dep_paths = dependencies - .iter() - .map(|compiled_package| { - build_root_path - .join( - compiled_package - .compiled_package_info - .package_name - .to_string(), - ) - .join(CompiledPackageLayout::CompiledModules.path()) - .to_string_lossy() - .to_string() - }) + let dependencies = dependencies_with_status + .into_iter() + .map(|(package, _status)| package) .collect::>(); - let tmp_interface_dir = tempfile::tempdir()?; - let in_scope_named_addrs = resolved_package - .resolution_table + // gather dep source info + let deps_source_info = dependencies .iter() - .map(|(ident, addr)| { - let parsed_addr = NumericalAddress::new( - addr.into_bytes(), - move_compiler::shared::NumberFormat::Hex, - ); - (ident.to_string(), parsed_addr) + .map(|dep_package| { + let dep_source_paths = dep_package + .compiled_units + .iter() + .map(|unit| Symbol::from(unit.source_path.to_string_lossy().to_string())) + .collect::>(); + Ok(( + dep_source_paths, + &dep_package + .compiled_package_info + .address_alias_instantiation, + )) }) - .collect::>(); - let sources: Vec<_> = resolved_package - .get_sources(&resolution_graph.build_options)? - .into_iter() - .map(|symbol| symbol.as_str().to_string()) - .collect(); + .collect::>>()?; + + // gather source/dep files with their address mappings + let (sources_with_addrs, deps_with_addrs) = make_source_and_deps_for_compiler( + resolution_graph, + &resolved_package, + deps_source_info, + )?; let flags = if resolution_graph.build_options.test_mode { Flags::testing() } else { Flags::empty() }; - - let compiler = Compiler::new( - vec![(sources.clone(), in_scope_named_addrs.clone())], - vec![(dep_paths, in_scope_named_addrs.clone())], - ) - .set_compiled_module_named_address_mapping( - module_resolution_metadata - .clone() - .into_iter() - .map(|(x, ident)| (x, ident.to_string())) - .collect::>(), - ) - .set_interface_files_dir(tmp_interface_dir.path().to_string_lossy().to_string()) - .set_flags(flags); + // invoke the compiler + let compiler = Compiler::new(vec![sources_with_addrs.clone()], deps_with_addrs.clone()) + .set_flags(flags); let (file_map, compiled_units) = compiler_driver(compiler, is_root_package)?; let (compiled_units, resolutions): (Vec<_>, Vec<_>) = compiled_units @@ -604,8 +580,18 @@ impl CompiledPackage { }) .unzip(); + // gather module resolution data from deps + let mut module_resolution_metadata = BTreeMap::new(); + for dep_package in &dependencies { + dep_package.gather_module_resolution_metadata( + &resolved_package.renaming, + &mut module_resolution_metadata, + ) + } + // gather from compiled units (which do not include deps) for (mod_id, name) in resolutions.into_iter().flatten() { - module_resolution_metadata.insert(mod_id, name); + let _old_value = module_resolution_metadata.insert(mod_id, name); + debug_assert!(_old_value.is_none()); } let mut compiled_docs = None; @@ -614,10 +600,9 @@ impl CompiledPackage { || resolution_graph.build_options.generate_abis { let model = run_model_builder_with_options( - &sources, - &[tmp_interface_dir.path().to_string_lossy().to_string()], + vec![sources_with_addrs], + deps_with_addrs, ModelBuilderOptions::default(), - in_scope_named_addrs, )?; if resolution_graph.build_options.generate_docs { @@ -807,10 +792,10 @@ impl CompiledPackage { Ok(on_disk_package) } - fn apply_renaming( + fn gather_module_resolution_metadata( &self, - module_resolution: &mut ModuleResolutionMetadata, renaming: &Renaming, + module_resolution: &mut ModuleResolutionMetadata, ) { let package_renamings = renaming .iter() @@ -910,3 +895,74 @@ impl CompiledPackage { docgen.gen() } } + +pub(crate) fn named_address_mapping_for_compiler( + resolution_table: &ResolvedTable, +) -> BTreeMap { + resolution_table + .iter() + .map(|(ident, addr)| { + let parsed_addr = + NumericalAddress::new(addr.into_bytes(), move_compiler::shared::NumberFormat::Hex); + (*ident, parsed_addr) + }) + .collect::>() +} + +pub(crate) fn apply_named_address_renaming( + current_package_name: Symbol, + address_resolution: BTreeMap, + renaming: &Renaming, +) -> NamedAddressMap { + let package_renamings = renaming + .iter() + .filter_map(|(rename_to, (package_name, from_name))| { + if package_name == ¤t_package_name { + Some((from_name, *rename_to)) + } else { + None + } + }) + .collect::>(); + + address_resolution + .into_iter() + .map(|(name, value)| { + let new_name = package_renamings.get(&name).copied(); + (new_name.unwrap_or(name), value) + }) + .collect() +} + +pub(crate) fn make_source_and_deps_for_compiler( + resolution_graph: &ResolvedGraph, + root: &ResolvedPackage, + deps: Vec<( + /* source paths */ Vec, + /* address mapping */ &ResolvedTable, + )>, +) -> Result<( + /* sources */ AddressScopedFiles, + /* deps */ Vec>, +)> { + let deps_with_addrs = deps + .into_iter() + .map(|(source_paths, resolved_table)| { + let source_paths = source_paths + .into_iter() + .collect::>() + .into_iter() + .collect::>(); + let named_addr_map = named_address_mapping_for_compiler(resolved_table); + Ok((source_paths, named_addr_map)) + }) + .collect::>>()?; + let root_named_addrs = apply_named_address_renaming( + root.source_package.package.name, + named_address_mapping_for_compiler(&root.resolution_table), + &root.renaming, + ); + let sources = root.get_sources(&resolution_graph.build_options)?; + let sources_with_addrs = (sources, root_named_addrs); + Ok((sources_with_addrs, deps_with_addrs)) +} diff --git a/language/tools/move-package/src/compilation/model_builder.rs b/language/tools/move-package/src/compilation/model_builder.rs index 71bb5f3eca..c63f4ab8b6 100644 --- a/language/tools/move-package/src/compilation/model_builder.rs +++ b/language/tools/move-package/src/compilation/model_builder.rs @@ -1,9 +1,11 @@ // Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 -use crate::{resolution::resolution_graph::ResolvedGraph, ModelConfig}; +use crate::{ + compilation::compiled_package::make_source_and_deps_for_compiler, + resolution::resolution_graph::ResolvedGraph, ModelConfig, +}; use anyhow::Result; -use move_compiler::shared::NumericalAddress; use move_model::{model::GlobalEnv, options::ModelBuilderOptions, run_model_builder_with_options}; #[derive(Debug, Clone)] @@ -40,54 +42,52 @@ impl ModelBuilder { // Targets are all files in the root package let root_name = &self.resolution_graph.root_package.package.name; let root_package = self.resolution_graph.get_package(root_name).clone(); - let mut targets: Vec<_> = root_package - .get_sources(&self.resolution_graph.build_options)? - .into_iter() - .map(|symbol| symbol.to_string()) - .collect(); - // Dependencies are all files in non-root package - let deps = self + let deps_source_info = self .resolution_graph .package_table .iter() - .flat_map(|(nm, pkg)| { + .filter_map(|(nm, pkg)| { if nm == root_name { - vec![] - } else { - pkg.get_sources(&self.resolution_graph.build_options) - .unwrap() + return None; } + let dep_source_paths = pkg + .get_sources(&self.resolution_graph.build_options) + .unwrap(); + Some(Ok((dep_source_paths, &pkg.resolution_table))) }) - .map(|symbol| symbol.to_string()) - .collect::>(); + .collect::>>()?; - let (mut targets, mut deps) = if self.model_config.all_files_as_targets { + let (target, deps) = make_source_and_deps_for_compiler( + &self.resolution_graph, + &root_package, + deps_source_info, + )?; + let (all_targets, all_deps) = if self.model_config.all_files_as_targets { + let mut targets = vec![target]; targets.extend(deps.into_iter()); (targets, vec![]) } else { - (targets, deps) + (vec![target], deps) + }; + let (all_targets, all_deps) = match &self.model_config.target_filter { + Some(filter) => { + let mut new_targets = vec![]; + let mut new_deps = all_deps; + for (targets, mapping) in all_targets { + let (true_targets, false_targets): (Vec<_>, Vec<_>) = + targets.into_iter().partition(|t| t.contains(filter)); + if !true_targets.is_empty() { + new_targets.push((true_targets, mapping.clone())) + } + if !false_targets.is_empty() { + new_deps.push((false_targets, mapping)) + } + } + (new_targets, new_deps) + } + None => (all_targets, all_deps), }; - if let Some(filter) = &self.model_config.target_filter { - // Filtering targets moves them into the deps - deps.extend(targets.iter().filter(|t| !t.contains(filter)).cloned()); - targets = targets.into_iter().filter(|t| t.contains(filter)).collect(); - } - run_model_builder_with_options( - &targets, - &deps, - ModelBuilderOptions::default(), - root_package - .resolution_table - .into_iter() - .map(|(ident, addr)| { - let addr = NumericalAddress::new( - addr.into_bytes(), - move_compiler::shared::NumberFormat::Hex, - ); - (ident.to_string(), addr) - }) - .collect(), - ) + run_model_builder_with_options(all_targets, all_deps, ModelBuilderOptions::default()) } } diff --git a/language/tools/move-package/src/resolution/resolution_graph.rs b/language/tools/move-package/src/resolution/resolution_graph.rs index ba56f31797..eb6b0bfa85 100644 --- a/language/tools/move-package/src/resolution/resolution_graph.rs +++ b/language/tools/move-package/src/resolution/resolution_graph.rs @@ -670,6 +670,7 @@ impl ResolvedPackage { .map(Symbol::from) .collect()) } + /// Returns the transitive dependencies of this package in dependency order pub fn transitive_dependencies(&self, resolved_graph: &ResolvedGraph) -> Vec { let mut seen = BTreeSet::new(); diff --git a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.exp b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.exp index 4af08d40a6..e056431e79 100644 --- a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.exp +++ b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.exp @@ -2,6 +2,7 @@ CompiledPackageInfo { package_name: "test", address_alias_instantiation: { "A": 00000000000000000000000000000001, + "C": 00000000000000000000000000000003, "DA": 00000000000000000000000000000002, }, module_resolution_metadata: { @@ -17,6 +18,12 @@ CompiledPackageInfo { "A", ), }: "DA", + ModuleId { + address: 00000000000000000000000000000003, + name: Identifier( + "A", + ), + }: "C", }, source_digest: Some( "ELIDED_FOR_TEST", diff --git a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.toml b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.toml index dc685c37f0..423f3f880f 100644 --- a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.toml +++ b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/Move.toml @@ -4,6 +4,9 @@ name = "test" version = "0.0.0" +[addresses] +A = "0x1" + [dependencies] C = { local = "./deps_only/C" } D = { local = "./deps_only/D" , addr_subst = {"DA" = "A" } } diff --git a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/Move.toml b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/Move.toml index a5bcadbfb6..d8942384fb 100644 --- a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/Move.toml +++ b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/Move.toml @@ -3,4 +3,4 @@ name = "C" version = "0.0.0" [addresses] -A = "0x1" +C = "0x3" diff --git a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/sources/A.move b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/sources/A.move index 9d42ff170f..d66d01a882 100644 --- a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/sources/A.move +++ b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/deps_only/C/sources/A.move @@ -1,3 +1,3 @@ -module A::A { +module C::A { public fun foo() { } } diff --git a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/sources/Root.move b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/sources/Root.move index d5c334283f..aaa8560f6c 100644 --- a/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/sources/Root.move +++ b/language/tools/move-package/tests/test_sources/compilation/multiple_deps_rename_one/sources/Root.move @@ -1,9 +1,9 @@ module A::A { use DA::A as DAA; - use A::A as CAA; + use C::A as CA; public fun foo() { DAA::foo(); - CAA::foo() + CA::foo() } } diff --git a/language/tools/move-unit-test/src/test_runner.rs b/language/tools/move-unit-test/src/test_runner.rs index 2d633d54c4..e78f0bd0a9 100644 --- a/language/tools/move-unit-test/src/test_runner.rs +++ b/language/tools/move-unit-test/src/test_runner.rs @@ -346,11 +346,10 @@ impl SharedTestingConfig { let stackless_model = if self.check_stackless_vm { let model = run_model_builder_with_options_and_compilation_flags( - &filtered_sources, - &[], + vec![(filtered_sources, self.named_address_values.clone())], + vec![], ModelBuilderOptions::default(), Flags::testing(), - self.named_address_values.clone(), ) .unwrap_or_else(|e| panic!("Unable to build stackless bytecode: {}", e)); @@ -571,11 +570,10 @@ impl SharedTestingConfig { .collect::>(); let model = run_model_builder_with_options_and_compilation_flags( - &filtered_sources, - &[], + vec![(filtered_sources, self.named_address_values.clone())], + vec![], ModelBuilderOptions::default(), Flags::testing(), - self.named_address_values.clone(), ) .unwrap_or_else(|e| panic!("Unable to build move model: {}", e));