From e30b347a0e26ee3de89307392caed01d601427be Mon Sep 17 00:00:00 2001 From: jfecher Date: Tue, 16 Jul 2024 12:22:56 -0500 Subject: [PATCH] chore: Remove `--use-legacy` and resolution code (#5248) # Description ## Problem\* ## Summary\* Made this PR as an experiment to see how much legacy code we can remove today. It looks like we can remove the majority of resolution code at the `dc_crate` level, but we can't remove the NameResolver or TypeChecker since these are used by the aztec macros crate. This is something we'll have to watch out for when the elaborator is used by default - that code injected by macros will still use the old resolution & type checking code. I'm not aware of any compatibility errors when running both but it is something to keep in mind. Edit: Removed the NameResolver and TypeChecker in a separate PR: https://github.com/noir-lang/noir/pull/5525 ## Additional Context ## Documentation\* Check one: - [x] No documentation needed. - [ ] Documentation included in this PR. - [ ] **[For Experimental Features]** Documentation to be submitted in a separate PR. # PR Checklist\* - [x] I have tested the changes locally. - [x] I have formatted the changes with [Prettier](https://prettier.io/) and/or `cargo fmt` on default settings. --- compiler/noirc_driver/src/lib.rs | 10 +- .../noirc_driver/tests/stdlib_warnings.rs | 2 +- .../src/hir/def_collector/dc_crate.rs | 255 +-------- .../noirc_frontend/src/hir/def_map/mod.rs | 2 - .../src/hir/resolution/functions.rs | 84 --- .../src/hir/resolution/globals.rs | 46 -- .../src/hir/resolution/impls.rs | 145 ----- .../noirc_frontend/src/hir/resolution/mod.rs | 47 -- .../src/hir/resolution/resolver.rs | 7 - .../src/hir/resolution/structs.rs | 83 --- .../src/hir/resolution/traits.rs | 506 ------------------ .../src/hir/resolution/type_aliases.rs | 33 -- compiler/noirc_frontend/src/tests.rs | 12 +- tooling/lsp/src/lib.rs | 3 +- tooling/lsp/src/notifications/mod.rs | 11 +- tooling/lsp/src/requests/code_lens_request.rs | 2 +- tooling/lsp/src/requests/mod.rs | 2 +- tooling/lsp/src/requests/test_run.rs | 2 +- tooling/lsp/src/requests/tests.rs | 2 +- tooling/nargo_cli/build.rs | 115 ---- tooling/nargo_cli/src/cli/check_cmd.rs | 12 +- tooling/nargo_cli/src/cli/export_cmd.rs | 1 - tooling/nargo_cli/src/cli/test_cmd.rs | 2 - tooling/nargo_cli/tests/stdlib-tests.rs | 2 +- 24 files changed, 27 insertions(+), 1359 deletions(-) delete mode 100644 compiler/noirc_frontend/src/hir/resolution/functions.rs delete mode 100644 compiler/noirc_frontend/src/hir/resolution/globals.rs delete mode 100644 compiler/noirc_frontend/src/hir/resolution/impls.rs delete mode 100644 compiler/noirc_frontend/src/hir/resolution/structs.rs delete mode 100644 compiler/noirc_frontend/src/hir/resolution/traits.rs delete mode 100644 compiler/noirc_frontend/src/hir/resolution/type_aliases.rs diff --git a/compiler/noirc_driver/src/lib.rs b/compiler/noirc_driver/src/lib.rs index 3ec8c102aec..dd774a1eeec 100644 --- a/compiler/noirc_driver/src/lib.rs +++ b/compiler/noirc_driver/src/lib.rs @@ -99,10 +99,6 @@ pub struct CompileOptions { #[arg(long, hide = true)] pub force_brillig: bool, - /// Use the deprecated name resolution & type checking passes instead of the elaborator - #[arg(long, hide = true)] - pub use_legacy: bool, - /// Enable printing results of comptime evaluation: provide a path suffix /// for the module to debug, e.g. "package_name/src/main.nr" #[arg(long)] @@ -262,15 +258,13 @@ pub fn check_crate( crate_id: CrateId, deny_warnings: bool, disable_macros: bool, - use_legacy: bool, debug_comptime_in_file: Option<&str>, ) -> CompilationResult<()> { let macros: &[&dyn MacroProcessor] = if disable_macros { &[] } else { &[&aztec_macros::AztecMacro as &dyn MacroProcessor] }; let mut errors = vec![]; - let diagnostics = - CrateDefMap::collect_defs(crate_id, context, use_legacy, debug_comptime_in_file, macros); + let diagnostics = CrateDefMap::collect_defs(crate_id, context, debug_comptime_in_file, macros); errors.extend(diagnostics.into_iter().map(|(error, file_id)| { let diagnostic = CustomDiagnostic::from(&error); diagnostic.in_file(file_id) @@ -307,7 +301,6 @@ pub fn compile_main( crate_id, options.deny_warnings, options.disable_macros, - options.use_legacy, options.debug_comptime_in_file.as_deref(), )?; @@ -349,7 +342,6 @@ pub fn compile_contract( crate_id, options.deny_warnings, options.disable_macros, - options.use_legacy, options.debug_comptime_in_file.as_deref(), )?; diff --git a/compiler/noirc_driver/tests/stdlib_warnings.rs b/compiler/noirc_driver/tests/stdlib_warnings.rs index 0e098d0d087..d2474444d13 100644 --- a/compiler/noirc_driver/tests/stdlib_warnings.rs +++ b/compiler/noirc_driver/tests/stdlib_warnings.rs @@ -25,7 +25,7 @@ fn stdlib_does_not_produce_constant_warnings() -> Result<(), ErrorsAndWarnings> let root_crate_id = prepare_crate(&mut context, file_name); let ((), warnings) = - noirc_driver::check_crate(&mut context, root_crate_id, false, false, false, None)?; + noirc_driver::check_crate(&mut context, root_crate_id, false, false, None)?; assert_eq!(warnings, Vec::new(), "stdlib is producing {} warnings", warnings.len()); diff --git a/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs b/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs index f42819dab1f..199c5626546 100644 --- a/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs +++ b/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs @@ -2,20 +2,14 @@ use super::dc_mod::collect_defs; use super::errors::{DefCollectorErrorKind, DuplicateType}; use crate::elaborator::Elaborator; use crate::graph::CrateId; -use crate::hir::comptime::{Interpreter, InterpreterError}; +use crate::hir::comptime::InterpreterError; use crate::hir::def_map::{CrateDefMap, LocalModuleId, ModuleId}; use crate::hir::resolution::errors::ResolverError; +use crate::hir::resolution::path_resolver; +use crate::hir::type_check::TypeCheckError; use crate::{ResolvedGeneric, Type}; use crate::hir::resolution::import::{resolve_import, ImportDirective, PathResolution}; -use crate::hir::resolution::{ - collect_impls, collect_trait_impls, path_resolver, resolve_free_functions, resolve_globals, - resolve_impls, resolve_structs, resolve_trait_by_path, resolve_trait_impls, resolve_traits, - resolve_type_aliases, -}; -use crate::hir::type_check::{ - check_trait_impl_method_matches_declaration, type_check_func, TypeCheckError, TypeChecker, -}; use crate::hir::Context; use crate::macros_api::{MacroError, MacroProcessor}; @@ -39,16 +33,6 @@ use std::fmt::Write; use std::path::PathBuf; use std::vec; -#[derive(Default)] -pub struct ResolvedModule { - pub globals: Vec<(FileId, GlobalId)>, - pub functions: Vec<(FileId, FuncId)>, - pub trait_impl_functions: Vec<(FileId, FuncId)>, - pub debug_comptime_in_file: Option, - - pub errors: Vec<(CompilationError, FileId)>, -} - /// Stores all of the unresolved functions in a particular file/mod #[derive(Clone)] pub struct UnresolvedFunctions { @@ -68,35 +52,6 @@ impl UnresolvedFunctions { pub fn function_ids(&self) -> Vec { vecmap(&self.functions, |(_, id, _)| *id) } - - pub fn resolve_trait_bounds_trait_ids( - &mut self, - def_maps: &BTreeMap, - crate_id: CrateId, - ) -> Vec { - let mut errors = Vec::new(); - - for (local_id, _, func) in &mut self.functions { - let module = ModuleId { krate: crate_id, local_id: *local_id }; - - for bound in &mut func.def.where_clause { - match resolve_trait_by_path(def_maps, module, bound.trait_bound.trait_path.clone()) - { - Ok((trait_id, warning)) => { - bound.trait_bound.trait_id = Some(trait_id); - if let Some(warning) = warning { - errors.push(DefCollectorErrorKind::PathResolutionError(warning)); - } - } - Err(err) => { - errors.push(err); - } - } - } - } - - errors - } } pub struct UnresolvedStruct { @@ -201,13 +156,6 @@ pub enum CompilationError { DebugComptimeScopeNotFound(Vec), } -impl CompilationError { - pub fn is_error(&self) -> bool { - let diagnostic = CustomDiagnostic::from(self); - diagnostic.is_error() - } -} - impl<'a> From<&'a CompilationError> for CustomDiagnostic { fn from(value: &'a CompilationError) -> Self { match value { @@ -284,7 +232,6 @@ impl DefCollector { context: &mut Context, ast: SortedModule, root_file_id: FileId, - use_legacy: bool, debug_comptime_in_file: Option<&str>, macro_processors: &[&dyn MacroProcessor], ) -> Vec<(CompilationError, FileId)> { @@ -302,7 +249,6 @@ impl DefCollector { errors.extend(CrateDefMap::collect_defs( dep.crate_id, context, - use_legacy, debug_comptime_in_file, macro_processors, )); @@ -425,121 +371,19 @@ impl DefCollector { }) }); - if !use_legacy { - let mut more_errors = Elaborator::elaborate( - context, - crate_id, - def_collector.items, - debug_comptime_in_file, - ); - errors.append(&mut more_errors); - - for macro_processor in macro_processors { - macro_processor.process_typed_ast(&crate_id, context).unwrap_or_else( - |(macro_err, file_id)| { - errors.push((macro_err.into(), file_id)); - }, - ); - } - return errors; - } - - let mut resolved_module = - ResolvedModule { errors, debug_comptime_in_file, ..Default::default() }; - - // We must first resolve and intern the globals before we can resolve any stmts inside each function. - // Each function uses its own resolver with a newly created ScopeForest, and must be resolved again to be within a function's scope - // - // Additionally, we must resolve integer globals before structs since structs may refer to - // the values of integer globals as numeric generics. - let (literal_globals, other_globals) = filter_literal_globals(def_collector.items.globals); - - resolved_module.resolve_globals(context, literal_globals, crate_id); - - resolved_module.errors.extend(resolve_type_aliases( - context, - def_collector.items.type_aliases, - crate_id, - )); - - resolved_module.errors.extend(resolve_traits( - context, - def_collector.items.traits, - crate_id, - )); - - // Must resolve structs before we resolve globals. - resolved_module.errors.extend(resolve_structs( - context, - def_collector.items.types, - crate_id, - )); - - // Bind trait impls to their trait. Collect trait functions, that have a - // default implementation, which hasn't been overridden. - resolved_module.errors.extend(collect_trait_impls( - context, - crate_id, - &mut def_collector.items.trait_impls, - )); - - // Before we resolve any function symbols we must go through our impls and - // re-collect the methods within into their proper module. This cannot be - // done before resolution since we need to be able to resolve the type of the - // impl since that determines the module we should collect into. - // - // These are resolved after trait impls so that struct methods are chosen - // over trait methods if there are name conflicts. - resolved_module.errors.extend(collect_impls(context, crate_id, &def_collector.items.impls)); - - // We must wait to resolve non-integer globals until after we resolve structs since struct - // globals will need to reference the struct type they're initialized to ensure they are valid. - resolved_module.resolve_globals(context, other_globals, crate_id); - - // Resolve each function in the crate. This is now possible since imports have been resolved - resolved_module.functions = resolve_free_functions( - &mut context.def_interner, - crate_id, - &context.def_maps, - def_collector.items.functions, - None, - &mut resolved_module.errors, - ); - - resolved_module.functions.extend(resolve_impls( - &mut context.def_interner, - crate_id, - &context.def_maps, - def_collector.items.impls, - &mut resolved_module.errors, - )); - - resolved_module.trait_impl_functions = resolve_trait_impls( - context, - def_collector.items.trait_impls, - crate_id, - &mut resolved_module.errors, - ); + let mut more_errors = + Elaborator::elaborate(context, crate_id, def_collector.items, debug_comptime_in_file); + errors.append(&mut more_errors); for macro_processor in macro_processors { macro_processor.process_typed_ast(&crate_id, context).unwrap_or_else( |(macro_err, file_id)| { - resolved_module.errors.push((macro_err.into(), file_id)); + errors.push((macro_err.into(), file_id)); }, ); } - let cycle_errors = context.def_interner.check_for_dependency_cycles(); - let cycles_present = !cycle_errors.is_empty(); - resolved_module.errors.extend(cycle_errors); - - resolved_module.type_check(context); - - if !cycles_present { - resolved_module.evaluate_comptime(&mut context.def_interner, crate_id); - } - - resolved_module.errors + errors } } @@ -615,86 +459,3 @@ pub fn filter_literal_globals( _ => false, }) } - -impl ResolvedModule { - fn type_check(&mut self, context: &mut Context) { - self.type_check_globals(&mut context.def_interner); - self.type_check_functions(&mut context.def_interner); - self.type_check_trait_impl_function(&mut context.def_interner); - } - - fn type_check_globals(&mut self, interner: &mut NodeInterner) { - for (file_id, global_id) in self.globals.iter() { - for error in TypeChecker::check_global(*global_id, interner) { - self.errors.push((error.into(), *file_id)); - } - } - } - - fn type_check_functions(&mut self, interner: &mut NodeInterner) { - for (file, func) in self.functions.iter() { - for error in type_check_func(interner, *func) { - self.errors.push((error.into(), *file)); - } - } - } - - fn type_check_trait_impl_function(&mut self, interner: &mut NodeInterner) { - for (file, func) in self.trait_impl_functions.iter() { - for error in check_trait_impl_method_matches_declaration(interner, *func) { - self.errors.push((error.into(), *file)); - } - for error in type_check_func(interner, *func) { - self.errors.push((error.into(), *file)); - } - } - } - - /// Evaluate all `comptime` expressions in this module - fn evaluate_comptime(&mut self, interner: &mut NodeInterner, crate_id: CrateId) { - if self.count_errors() == 0 { - let mut scopes = vec![HashMap::default()]; - let mut interpreter_errors = vec![]; - let mut interpreter = Interpreter::new( - interner, - &mut scopes, - crate_id, - self.debug_comptime_in_file, - &mut interpreter_errors, - ); - - for (_file, global) in &self.globals { - if let Err(error) = interpreter.scan_global(*global) { - self.errors.push(error.into_compilation_error_pair()); - } - } - - for (_file, function) in &self.functions { - // The file returned by the error may be different than the file the - // function is in so only use the error's file id. - if let Err(error) = interpreter.scan_function(*function) { - self.errors.push(error.into_compilation_error_pair()); - } - } - self.errors.extend( - interpreter_errors.into_iter().map(InterpreterError::into_compilation_error_pair), - ); - } - } - - fn resolve_globals( - &mut self, - context: &mut Context, - literal_globals: Vec, - crate_id: CrateId, - ) { - let globals = resolve_globals(context, literal_globals, crate_id); - self.globals.extend(globals.globals); - self.errors.extend(globals.errors); - } - - /// Counts the number of errors (minus warnings) this program currently has - fn count_errors(&self) -> usize { - self.errors.iter().filter(|(error, _)| error.is_error()).count() - } -} diff --git a/compiler/noirc_frontend/src/hir/def_map/mod.rs b/compiler/noirc_frontend/src/hir/def_map/mod.rs index 43d1548dc29..143d29971bf 100644 --- a/compiler/noirc_frontend/src/hir/def_map/mod.rs +++ b/compiler/noirc_frontend/src/hir/def_map/mod.rs @@ -73,7 +73,6 @@ impl CrateDefMap { pub fn collect_defs( crate_id: CrateId, context: &mut Context, - use_legacy: bool, debug_comptime_in_file: Option<&str>, macro_processors: &[&dyn MacroProcessor], ) -> Vec<(CompilationError, FileId)> { @@ -123,7 +122,6 @@ impl CrateDefMap { context, ast, root_file_id, - use_legacy, debug_comptime_in_file, macro_processors, )); diff --git a/compiler/noirc_frontend/src/hir/resolution/functions.rs b/compiler/noirc_frontend/src/hir/resolution/functions.rs deleted file mode 100644 index fe46796ed24..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/functions.rs +++ /dev/null @@ -1,84 +0,0 @@ -use std::collections::BTreeMap; - -use fm::FileId; -use iter_extended::vecmap; - -use crate::{ - graph::CrateId, - hir::{ - def_collector::dc_crate::{CompilationError, UnresolvedFunctions}, - def_map::{CrateDefMap, ModuleId}, - }, - node_interner::{FuncId, NodeInterner, TraitImplId}, - ResolvedGeneric, Type, -}; - -use super::{path_resolver::StandardPathResolver, Resolver}; - -#[allow(clippy::too_many_arguments)] -pub(crate) fn resolve_function_set( - interner: &mut NodeInterner, - crate_id: CrateId, - def_maps: &BTreeMap, - mut unresolved_functions: UnresolvedFunctions, - self_type: Option, - trait_impl_id: Option, - impl_generics: Vec, - errors: &mut Vec<(CompilationError, FileId)>, -) -> Vec<(FileId, FuncId)> { - let file_id = unresolved_functions.file_id; - - let where_clause_errors = - unresolved_functions.resolve_trait_bounds_trait_ids(def_maps, crate_id); - errors.extend(where_clause_errors.iter().cloned().map(|e| (e.into(), file_id))); - - vecmap(unresolved_functions.functions, |(mod_id, func_id, func)| { - let module_id = ModuleId { krate: crate_id, local_id: mod_id }; - let path_resolver = StandardPathResolver::new(module_id); - - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file_id); - // Must use set_generics here to ensure we re-use the same generics from when - // the impl was originally collected. Otherwise the function will be using different - // TypeVariables for the same generic, causing it to instantiate incorrectly. - resolver.set_generics(impl_generics.clone()); - resolver.set_self_type(self_type.clone()); - resolver.set_trait_id(unresolved_functions.trait_id); - resolver.set_trait_impl_id(trait_impl_id); - - // Without this, impl methods can accidentally be placed in contracts. See #3254 - if self_type.is_some() { - resolver.set_in_contract(false); - } - - let (hir_func, func_meta, errs) = resolver.resolve_function(func, func_id); - interner.push_fn_meta(func_meta, func_id); - interner.update_fn(func_id, hir_func); - errors.extend(errs.iter().cloned().map(|e| (e.into(), file_id))); - (file_id, func_id) - }) -} - -pub(crate) fn resolve_free_functions( - interner: &mut NodeInterner, - crate_id: CrateId, - def_maps: &BTreeMap, - collected_functions: Vec, - self_type: Option, - errors: &mut Vec<(CompilationError, FileId)>, -) -> Vec<(FileId, FuncId)> { - collected_functions - .into_iter() - .flat_map(|unresolved_functions| { - resolve_function_set( - interner, - crate_id, - def_maps, - unresolved_functions, - self_type.clone(), - None, - vec![], // no impl generics - errors, - ) - }) - .collect() -} diff --git a/compiler/noirc_frontend/src/hir/resolution/globals.rs b/compiler/noirc_frontend/src/hir/resolution/globals.rs deleted file mode 100644 index bcda4e75d3d..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/globals.rs +++ /dev/null @@ -1,46 +0,0 @@ -use super::{path_resolver::StandardPathResolver, resolver::Resolver, take_errors}; -use crate::{ - graph::CrateId, - hir::{ - def_collector::dc_crate::{CompilationError, UnresolvedGlobal}, - def_map::ModuleId, - Context, - }, - node_interner::GlobalId, -}; -use fm::FileId; -use iter_extended::vecmap; - -#[derive(Default)] -pub(crate) struct ResolvedGlobals { - pub(crate) globals: Vec<(FileId, GlobalId)>, - pub(crate) errors: Vec<(CompilationError, FileId)>, -} - -pub(crate) fn resolve_globals( - context: &mut Context, - globals: Vec, - crate_id: CrateId, -) -> ResolvedGlobals { - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - let globals = vecmap(globals, |global| { - let module_id = ModuleId { local_id: global.module_id, krate: crate_id }; - let path_resolver = StandardPathResolver::new(module_id); - - let mut resolver = Resolver::new( - &mut context.def_interner, - &path_resolver, - &context.def_maps, - global.file_id, - ); - - let hir_stmt = resolver.resolve_global_let(global.stmt_def, global.global_id); - errors.extend(take_errors(global.file_id, resolver)); - - let statement_id = context.def_interner.get_global(global.global_id).let_statement; - context.def_interner.replace_statement(statement_id, hir_stmt); - - (global.file_id, global.global_id) - }); - ResolvedGlobals { globals, errors } -} diff --git a/compiler/noirc_frontend/src/hir/resolution/impls.rs b/compiler/noirc_frontend/src/hir/resolution/impls.rs deleted file mode 100644 index 7efd1eed86e..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/impls.rs +++ /dev/null @@ -1,145 +0,0 @@ -use std::collections::BTreeMap; - -use fm::FileId; - -use crate::ast::ItemVisibility; -use crate::{ - graph::CrateId, - hir::{ - def_collector::{ - dc_crate::{CompilationError, ImplMap}, - errors::DefCollectorErrorKind, - }, - def_map::{CrateDefMap, ModuleId}, - Context, - }, - node_interner::{FuncId, NodeInterner}, - Type, -}; - -use super::{ - errors::ResolverError, functions, get_module_mut, get_struct_type, - path_resolver::StandardPathResolver, resolver::Resolver, take_errors, -}; - -/// Go through the list of impls and add each function within to the scope -/// of the module defined by its type. -pub(crate) fn collect_impls( - context: &mut Context, - crate_id: CrateId, - collected_impls: &ImplMap, -) -> Vec<(CompilationError, FileId)> { - let interner = &mut context.def_interner; - let def_maps = &mut context.def_maps; - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - - for ((unresolved_type, module_id), methods) in collected_impls { - let path_resolver = - StandardPathResolver::new(ModuleId { local_id: *module_id, krate: crate_id }); - - let file = def_maps[&crate_id].file_id(*module_id); - - for (generics, span, unresolved) in methods { - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - resolver.add_generics(generics); - let typ = resolver.resolve_type(unresolved_type.clone()); - - errors.extend(take_errors(unresolved.file_id, resolver)); - - if let Some(struct_type) = get_struct_type(&typ) { - let struct_type = struct_type.borrow(); - - // `impl`s are only allowed on types defined within the current crate - if struct_type.id.krate() != crate_id { - let span = *span; - let type_name = struct_type.name.to_string(); - let error = DefCollectorErrorKind::ForeignImpl { span, type_name }; - errors.push((error.into(), unresolved.file_id)); - continue; - } - - // Grab the module defined by the struct type. Note that impls are a case - // where the module the methods are added to is not the same as the module - // they are resolved in. - let module = get_module_mut(def_maps, struct_type.id.module_id()); - - for (_, method_id, method) in &unresolved.functions { - // If this method was already declared, remove it from the module so it cannot - // be accessed with the `TypeName::method` syntax. We'll check later whether the - // object types in each method overlap or not. If they do, we issue an error. - // If not, that is specialization which is allowed. - if module - .declare_function( - method.name_ident().clone(), - ItemVisibility::Public, - *method_id, - ) - .is_err() - { - module.remove_function(method.name_ident()); - } - } - // Prohibit defining impls for primitive types if we're not in the stdlib - } else if typ != Type::Error && !crate_id.is_stdlib() { - let span = *span; - let error = DefCollectorErrorKind::NonStructTypeInImpl { span }; - errors.push((error.into(), unresolved.file_id)); - } - } - } - errors -} - -pub(crate) fn resolve_impls( - interner: &mut NodeInterner, - crate_id: CrateId, - def_maps: &BTreeMap, - collected_impls: ImplMap, - errors: &mut Vec<(CompilationError, FileId)>, -) -> Vec<(FileId, FuncId)> { - let mut file_method_ids = Vec::new(); - - for ((unresolved_type, module_id), methods) in collected_impls { - let path_resolver = - StandardPathResolver::new(ModuleId { local_id: module_id, krate: crate_id }); - - let file = def_maps[&crate_id].file_id(module_id); - - for (generics, _, functions) in methods { - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - resolver.add_generics(&generics); - let generics = resolver.get_generics().to_vec(); - let self_type = resolver.resolve_type(unresolved_type.clone()); - - let mut file_func_ids = functions::resolve_function_set( - interner, - crate_id, - def_maps, - functions, - Some(self_type.clone()), - None, - generics, - errors, - ); - if self_type != Type::Error { - for (file_id, method_id) in &file_func_ids { - let method_name = interner.function_name(method_id).to_owned(); - - if let Some(first_fn) = - interner.add_method(&self_type, method_name.clone(), *method_id, false) - { - let error = ResolverError::DuplicateDefinition { - name: method_name, - first_span: interner.function_ident(&first_fn).span(), - second_span: interner.function_ident(method_id).span(), - }; - errors.push((error.into(), *file_id)); - } - } - } - file_method_ids.append(&mut file_func_ids); - } - } - - file_method_ids -} diff --git a/compiler/noirc_frontend/src/hir/resolution/mod.rs b/compiler/noirc_frontend/src/hir/resolution/mod.rs index 8c16a9cca80..601e78015ca 100644 --- a/compiler/noirc_frontend/src/hir/resolution/mod.rs +++ b/compiler/noirc_frontend/src/hir/resolution/mod.rs @@ -9,50 +9,3 @@ pub mod errors; pub mod import; pub mod path_resolver; pub mod resolver; - -mod functions; -mod globals; -mod impls; -mod structs; -mod traits; -mod type_aliases; - -pub(crate) use functions::resolve_free_functions; -pub(crate) use globals::resolve_globals; -pub(crate) use impls::{collect_impls, resolve_impls}; -pub(crate) use structs::resolve_structs; -pub(crate) use traits::{ - collect_trait_impls, resolve_trait_by_path, resolve_trait_impls, resolve_traits, -}; -pub(crate) use type_aliases::resolve_type_aliases; - -use crate::{ - graph::CrateId, - hir::{ - def_collector::dc_crate::CompilationError, - def_map::{CrateDefMap, ModuleData, ModuleId}, - }, - Shared, StructType, Type, -}; -use fm::FileId; -use iter_extended::vecmap; -use resolver::Resolver; -use std::collections::BTreeMap; - -fn take_errors(file_id: FileId, resolver: Resolver<'_>) -> Vec<(CompilationError, FileId)> { - vecmap(resolver.take_errors(), |e| (e.into(), file_id)) -} - -fn get_module_mut( - def_maps: &mut BTreeMap, - module: ModuleId, -) -> &mut ModuleData { - &mut def_maps.get_mut(&module.krate).unwrap().modules[module.local_id.0] -} - -fn get_struct_type(typ: &Type) -> Option<&Shared> { - match typ { - Type::Struct(definition, _) => Some(definition), - _ => None, - } -} diff --git a/compiler/noirc_frontend/src/hir/resolution/resolver.rs b/compiler/noirc_frontend/src/hir/resolution/resolver.rs index 55cb2145ba8..de953946004 100644 --- a/compiler/noirc_frontend/src/hir/resolution/resolver.rs +++ b/compiler/noirc_frontend/src/hir/resolution/resolver.rs @@ -1124,13 +1124,6 @@ impl<'a> Resolver<'a> { } } - /// Override whether this name resolver is within a contract or not. - /// This will affect which types are allowed as parameters to methods as well - /// as which modifiers are allowed on a function. - pub(crate) fn set_in_contract(&mut self, in_contract: bool) { - self.in_contract = in_contract; - } - /// True if the 'pub' keyword is allowed on parameters in this function /// 'pub' on function parameters is only allowed for entry point functions fn pub_allowed(&self, func: &NoirFunction) -> bool { diff --git a/compiler/noirc_frontend/src/hir/resolution/structs.rs b/compiler/noirc_frontend/src/hir/resolution/structs.rs deleted file mode 100644 index f62e5589d74..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/structs.rs +++ /dev/null @@ -1,83 +0,0 @@ -use std::collections::BTreeMap; - -use fm::FileId; -use iter_extended::vecmap; - -use crate::ast::Ident; -use crate::{ - graph::CrateId, - hir::{ - def_collector::dc_crate::{CompilationError, UnresolvedStruct}, - def_map::ModuleId, - Context, - }, - node_interner::StructId, - Generics, Type, -}; - -use super::{errors::ResolverError, path_resolver::StandardPathResolver, resolver::Resolver}; - -/// Create the mappings from TypeId -> StructType -/// so that expressions can access the fields of structs -pub(crate) fn resolve_structs( - context: &mut Context, - structs: BTreeMap, - crate_id: CrateId, -) -> Vec<(CompilationError, FileId)> { - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - // This is necessary to avoid cloning the entire struct map - // when adding checks after each struct field is resolved. - let struct_ids = structs.keys().copied().collect::>(); - - // Resolve each field in each struct. - // Each struct should already be present in the NodeInterner after def collection. - for (type_id, typ) in structs { - let file_id = typ.file_id; - let (generics, fields, resolver_errors) = - resolve_struct_fields(context, crate_id, type_id, typ); - errors.extend(vecmap(resolver_errors, |err| (err.into(), file_id))); - context.def_interner.update_struct(type_id, |struct_def| { - struct_def.set_fields(fields); - struct_def.generics = generics; - }); - } - - // Check whether the struct fields have nested slices - // We need to check after all structs are resolved to - // make sure every struct's fields is accurately set. - for id in struct_ids { - let struct_type = context.def_interner.get_struct(id); - // Only handle structs without generics as any generics args will be checked - // after monomorphization when performing SSA codegen - if struct_type.borrow().generics.is_empty() { - let fields = struct_type.borrow().get_fields(&[]); - for field in fields.iter() { - if field.1.is_nested_slice() { - errors.push(( - ResolverError::NestedSlices { span: struct_type.borrow().location.span } - .into(), - struct_type.borrow().location.file, - )); - } - } - } - } - - errors -} - -fn resolve_struct_fields( - context: &mut Context, - krate: CrateId, - type_id: StructId, - unresolved: UnresolvedStruct, -) -> (Generics, Vec<(Ident, Type)>, Vec) { - let path_resolver = - StandardPathResolver::new(ModuleId { local_id: unresolved.module_id, krate }); - let file_id = unresolved.file_id; - let (generics, fields, errors) = - Resolver::new(&mut context.def_interner, &path_resolver, &context.def_maps, file_id) - .resolve_struct_fields(unresolved.struct_def, type_id); - - (generics, fields, errors) -} diff --git a/compiler/noirc_frontend/src/hir/resolution/traits.rs b/compiler/noirc_frontend/src/hir/resolution/traits.rs deleted file mode 100644 index 28ee70393cd..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/traits.rs +++ /dev/null @@ -1,506 +0,0 @@ -use std::collections::{BTreeMap, HashSet}; - -use fm::FileId; -use iter_extended::vecmap; -use noirc_errors::Location; - -use crate::ast::{Ident, ItemVisibility, Path, TraitItem, UnresolvedGeneric}; -use crate::{ - graph::CrateId, - hir::{ - def_collector::{ - dc_crate::{CompilationError, UnresolvedTrait, UnresolvedTraitImpl}, - errors::{DefCollectorErrorKind, DuplicateType}, - }, - def_map::{CrateDefMap, ModuleDefId, ModuleId}, - Context, - }, - hir_def::traits::{TraitConstant, TraitFunction, TraitImpl, TraitType}, - node_interner::{FuncId, NodeInterner, TraitId}, - GenericTypeVars, Shared, Type, TypeVariableKind, -}; - -use super::{ - functions, get_module_mut, get_struct_type, - import::{PathResolution, PathResolutionError}, - path_resolver::{PathResolver, StandardPathResolver}, - resolver::Resolver, - take_errors, -}; - -/// Create the mappings from TypeId -> TraitType -/// so that expressions can access the elements of traits -pub(crate) fn resolve_traits( - context: &mut Context, - traits: BTreeMap, - crate_id: CrateId, -) -> Vec<(CompilationError, FileId)> { - let mut all_errors = Vec::new(); - - for (trait_id, unresolved_trait) in traits { - let file_id = context.def_maps[&crate_id].file_id(unresolved_trait.module_id); - let generics = context.resolve_generics( - &unresolved_trait.trait_def.generics, - &mut all_errors, - file_id, - ); - let generic_type_vars = generics.iter().map(|generic| generic.type_var.clone()).collect(); - - context.def_interner.push_empty_trait(trait_id, &unresolved_trait, generics); - - // Resolve order - // 1. Trait Types ( Trait constants can have a trait type, therefore types before constants) - let _ = resolve_trait_types(context, crate_id, &unresolved_trait); - // 2. Trait Constants ( Trait's methods can use trait types & constants, therefore they should be after) - let _ = resolve_trait_constants(context, crate_id, &unresolved_trait); - // 3. Trait Methods - let (methods, errors) = resolve_trait_methods( - context, - trait_id, - crate_id, - &unresolved_trait, - &generic_type_vars, - ); - - all_errors.extend(errors); - - context.def_interner.update_trait(trait_id, |trait_def| { - trait_def.set_methods(methods); - }); - - // This check needs to be after the trait's methods are set since - // the interner may set `interner.ordering_type` based on the result type - // of the Cmp trait, if this is it. - if crate_id.is_stdlib() { - context.def_interner.try_add_infix_operator_trait(trait_id); - context.def_interner.try_add_prefix_operator_trait(trait_id); - } - } - all_errors -} - -fn resolve_trait_types( - _context: &mut Context, - _crate_id: CrateId, - _unresolved_trait: &UnresolvedTrait, -) -> (Vec, Vec<(CompilationError, FileId)>) { - // TODO - (vec![], vec![]) -} -fn resolve_trait_constants( - _context: &mut Context, - _crate_id: CrateId, - _unresolved_trait: &UnresolvedTrait, -) -> (Vec, Vec<(CompilationError, FileId)>) { - // TODO - (vec![], vec![]) -} - -fn resolve_trait_methods( - context: &mut Context, - trait_id: TraitId, - crate_id: CrateId, - unresolved_trait: &UnresolvedTrait, - trait_generics: &GenericTypeVars, -) -> (Vec, Vec<(CompilationError, FileId)>) { - let interner = &mut context.def_interner; - let def_maps = &mut context.def_maps; - - let path_resolver = StandardPathResolver::new(ModuleId { - local_id: unresolved_trait.module_id, - krate: crate_id, - }); - let file = def_maps[&crate_id].file_id(unresolved_trait.module_id); - - let mut functions = vec![]; - let mut resolver_errors = vec![]; - - for item in &unresolved_trait.trait_def.items { - if let TraitItem::Function { - name, - generics, - parameters, - return_type, - where_clause, - body: _, - } = item - { - let the_trait = interner.get_trait(trait_id); - let self_typevar = the_trait.self_type_typevar.clone(); - let self_type = Type::TypeVariable(self_typevar.clone(), TypeVariableKind::Normal); - let name_span = the_trait.name.span(); - - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - resolver.add_generics(generics); - - resolver.add_existing_generics(&unresolved_trait.trait_def.generics, trait_generics); - resolver.add_existing_generic( - &UnresolvedGeneric::Variable(Ident::from("Self")), - name_span, - self_typevar, - ); - resolver.set_self_type(Some(self_type.clone())); - - let func_id = unresolved_trait.method_ids[&name.0.contents]; - let (_, func_meta) = resolver.resolve_trait_function( - name, - generics, - parameters, - return_type, - where_clause, - func_id, - ); - resolver.interner.push_fn_meta(func_meta, func_id); - - let arguments = vecmap(parameters, |param| resolver.resolve_type(param.1.clone())); - let return_type = resolver.resolve_type(return_type.get_type().into_owned()); - - let generics = vecmap(resolver.get_generics(), |generic| generic.type_var.clone()); - - let default_impl_list: Vec<_> = unresolved_trait - .fns_with_default_impl - .functions - .iter() - .filter(|(_, _, q)| q.name() == name.0.contents) - .collect(); - - let default_impl = if default_impl_list.len() == 1 { - Some(Box::new(default_impl_list[0].2.clone())) - } else { - None - }; - - let no_environment = Box::new(Type::Unit); - let function_type = Type::Function(arguments, Box::new(return_type), no_environment); - - functions.push(TraitFunction { - name: name.clone(), - typ: Type::Forall(generics, Box::new(function_type)), - location: Location::new(name.span(), unresolved_trait.file_id), - default_impl, - default_impl_module_id: unresolved_trait.module_id, - }); - - let errors = resolver.take_errors().into_iter(); - resolver_errors.extend(errors.map(|resolution_error| (resolution_error.into(), file))); - } - } - (functions, resolver_errors) -} - -fn collect_trait_impl_methods( - interner: &mut NodeInterner, - def_maps: &BTreeMap, - crate_id: CrateId, - trait_id: TraitId, - trait_impl: &mut UnresolvedTraitImpl, -) -> Vec<(CompilationError, FileId)> { - // In this Vec methods[i] corresponds to trait.methods[i]. If the impl has no implementation - // for a particular method, the default implementation will be added at that slot. - let mut ordered_methods = Vec::new(); - - // check whether the trait implementation is in the same crate as either the trait or the type - let mut errors = - check_trait_impl_crate_coherence(interner, trait_id, trait_impl, crate_id, def_maps); - // set of function ids that have a corresponding method in the trait - let mut func_ids_in_trait = HashSet::new(); - - // Temporarily take ownership of the trait's methods so we can iterate over them - // while also mutating the interner - let the_trait = interner.get_trait_mut(trait_id); - let methods = std::mem::take(&mut the_trait.methods); - - for method in &methods { - let overrides: Vec<_> = trait_impl - .methods - .functions - .iter() - .filter(|(_, _, f)| f.name() == method.name.0.contents) - .collect(); - - if overrides.is_empty() { - if let Some(default_impl) = &method.default_impl { - // copy 'where' clause from unresolved trait impl - let mut default_impl_clone = default_impl.clone(); - default_impl_clone.def.where_clause.extend(trait_impl.where_clause.clone()); - - let func_id = interner.push_empty_fn(); - let module = ModuleId { local_id: trait_impl.module_id, krate: crate_id }; - let location = Location::new(default_impl.def.span, trait_impl.file_id); - interner.push_function(func_id, &default_impl.def, module, location); - func_ids_in_trait.insert(func_id); - ordered_methods.push((method.default_impl_module_id, func_id, *default_impl_clone)); - } else { - let error = DefCollectorErrorKind::TraitMissingMethod { - trait_name: interner.get_trait(trait_id).name.clone(), - method_name: method.name.clone(), - trait_impl_span: trait_impl.object_type.span.expect("type must have a span"), - }; - errors.push((error.into(), trait_impl.file_id)); - } - } else { - for (_, func_id, _) in &overrides { - func_ids_in_trait.insert(*func_id); - } - - if overrides.len() > 1 { - let error = DefCollectorErrorKind::Duplicate { - typ: DuplicateType::TraitAssociatedFunction, - first_def: overrides[0].2.name_ident().clone(), - second_def: overrides[1].2.name_ident().clone(), - }; - errors.push((error.into(), trait_impl.file_id)); - } - - ordered_methods.push(overrides[0].clone()); - } - } - - // Restore the methods that were taken before the for loop - let the_trait = interner.get_trait_mut(trait_id); - the_trait.set_methods(methods); - - // Emit MethodNotInTrait error for methods in the impl block that - // don't have a corresponding method signature defined in the trait - for (_, func_id, func) in &trait_impl.methods.functions { - if !func_ids_in_trait.contains(func_id) { - let error = DefCollectorErrorKind::MethodNotInTrait { - trait_name: the_trait.name.clone(), - impl_method: func.name_ident().clone(), - }; - errors.push((error.into(), trait_impl.file_id)); - } - } - - trait_impl.methods.functions = ordered_methods; - trait_impl.methods.trait_id = Some(trait_id); - errors -} - -fn collect_trait_impl( - context: &mut Context, - crate_id: CrateId, - trait_impl: &mut UnresolvedTraitImpl, -) -> Vec<(CompilationError, FileId)> { - let interner = &mut context.def_interner; - let def_maps = &mut context.def_maps; - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - let unresolved_type = trait_impl.object_type.clone(); - let module = ModuleId { local_id: trait_impl.module_id, krate: crate_id }; - trait_impl.trait_id = - match resolve_trait_by_path(def_maps, module, trait_impl.trait_path.clone()) { - Ok((trait_id, warning)) => { - if let Some(warning) = warning { - errors.push(( - DefCollectorErrorKind::PathResolutionError(warning).into(), - trait_impl.file_id, - )); - } - Some(trait_id) - } - Err(error) => { - errors.push((error.into(), trait_impl.file_id)); - None - } - }; - - if let Some(trait_id) = trait_impl.trait_id { - errors - .extend(collect_trait_impl_methods(interner, def_maps, crate_id, trait_id, trait_impl)); - - let path_resolver = StandardPathResolver::new(module); - let file = def_maps[&crate_id].file_id(trait_impl.module_id); - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - resolver.add_generics(&trait_impl.generics); - - let typ = resolver.resolve_type(unresolved_type); - errors.extend(take_errors(trait_impl.file_id, resolver)); - - if let Some(struct_type) = get_struct_type(&typ) { - let struct_type = struct_type.borrow(); - let module = get_module_mut(def_maps, struct_type.id.module_id()); - - for (_, method_id, method) in &trait_impl.methods.functions { - // If this method was already declared, remove it from the module so it cannot - // be accessed with the `TypeName::method` syntax. We'll check later whether the - // object types in each method overlap or not. If they do, we issue an error. - // If not, that is specialization which is allowed. - if module - .declare_function( - method.name_ident().clone(), - ItemVisibility::Public, - *method_id, - ) - .is_err() - { - module.remove_function(method.name_ident()); - } - } - } - } - errors -} - -pub(crate) fn collect_trait_impls( - context: &mut Context, - crate_id: CrateId, - collected_impls: &mut [UnresolvedTraitImpl], -) -> Vec<(CompilationError, FileId)> { - collected_impls - .iter_mut() - .flat_map(|trait_impl| collect_trait_impl(context, crate_id, trait_impl)) - .collect() -} - -fn check_trait_impl_crate_coherence( - interner: &mut NodeInterner, - trait_id: TraitId, - trait_impl: &UnresolvedTraitImpl, - current_crate: CrateId, - def_maps: &BTreeMap, -) -> Vec<(CompilationError, FileId)> { - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - - let module = ModuleId { krate: current_crate, local_id: trait_impl.module_id }; - let file = def_maps[¤t_crate].file_id(trait_impl.module_id); - let path_resolver = StandardPathResolver::new(module); - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - - let object_crate = match resolver.resolve_type(trait_impl.object_type.clone()) { - Type::Struct(struct_type, _) => struct_type.borrow().id.krate(), - _ => CrateId::Dummy, - }; - - let the_trait = interner.get_trait(trait_id); - if current_crate != the_trait.crate_id && current_crate != object_crate { - let error = DefCollectorErrorKind::TraitImplOrphaned { - span: trait_impl.object_type.span.expect("object type must have a span"), - }; - errors.push((error.into(), trait_impl.file_id)); - } - - errors -} - -pub(crate) fn resolve_trait_by_path( - def_maps: &BTreeMap, - module: ModuleId, - path: Path, -) -> Result<(TraitId, Option), DefCollectorErrorKind> { - let path_resolver = StandardPathResolver::new(module); - - match path_resolver.resolve(def_maps, path.clone(), &mut None) { - Ok(PathResolution { module_def_id: ModuleDefId::TraitId(trait_id), error }) => { - Ok((trait_id, error)) - } - Ok(_) => Err(DefCollectorErrorKind::NotATrait { not_a_trait_name: path }), - Err(_) => Err(DefCollectorErrorKind::TraitNotFound { trait_path: path }), - } -} - -pub(crate) fn resolve_trait_impls( - context: &mut Context, - traits: Vec, - crate_id: CrateId, - errors: &mut Vec<(CompilationError, FileId)>, -) -> Vec<(FileId, FuncId)> { - let interner = &mut context.def_interner; - let mut methods = Vec::<(FileId, FuncId)>::new(); - - for trait_impl in traits { - let unresolved_type = trait_impl.object_type; - let local_mod_id = trait_impl.module_id; - let module_id = ModuleId { krate: crate_id, local_id: local_mod_id }; - let path_resolver = StandardPathResolver::new(module_id); - - let self_type_span = unresolved_type.span; - - let mut resolver = - Resolver::new(interner, &path_resolver, &context.def_maps, trait_impl.file_id); - resolver.add_generics(&trait_impl.generics); - - let trait_generics = - vecmap(&trait_impl.trait_generics, |generic| resolver.resolve_type(generic.clone())); - - let self_type = resolver.resolve_type(unresolved_type.clone()); - let impl_generics = resolver.get_generics().to_vec(); - let impl_id = interner.next_trait_impl_id(); - - let mut impl_methods = functions::resolve_function_set( - interner, - crate_id, - &context.def_maps, - trait_impl.methods.clone(), - Some(self_type.clone()), - Some(impl_id), - impl_generics.clone(), - errors, - ); - - let maybe_trait_id = trait_impl.trait_id; - if let Some(trait_id) = maybe_trait_id { - for (_, func) in &impl_methods { - interner.set_function_trait(*func, self_type.clone(), trait_id); - } - } - - if matches!(self_type, Type::MutableReference(_)) { - let span = self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()); - let error = DefCollectorErrorKind::MutableReferenceInTraitImpl { span }; - errors.push((error.into(), trait_impl.file_id)); - } - - let mut new_resolver = - Resolver::new(interner, &path_resolver, &context.def_maps, trait_impl.file_id); - - new_resolver.set_generics(impl_generics.clone()); - new_resolver.set_self_type(Some(self_type.clone())); - - if let Some(trait_id) = maybe_trait_id { - let where_clause = trait_impl - .where_clause - .into_iter() - .flat_map(|item| new_resolver.resolve_trait_constraint(item)) - .collect(); - - let resolver_errors = new_resolver.take_errors().into_iter(); - errors.extend(resolver_errors.map(|error| (error.into(), trait_impl.file_id))); - - let resolved_trait_impl = Shared::new(TraitImpl { - ident: trait_impl.trait_path.last_segment().clone(), - typ: self_type.clone(), - trait_id, - trait_generics: trait_generics.clone(), - file: trait_impl.file_id, - where_clause, - methods: vecmap(&impl_methods, |(_, func_id)| *func_id), - }); - - let impl_generics = vecmap(impl_generics, |generic| generic.type_var); - - if let Err((prev_span, prev_file)) = interner.add_trait_implementation( - self_type.clone(), - trait_id, - trait_generics, - impl_id, - impl_generics, - resolved_trait_impl, - ) { - let error = DefCollectorErrorKind::OverlappingImpl { - typ: self_type.clone(), - span: self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()), - }; - errors.push((error.into(), trait_impl.file_id)); - - // The 'previous impl defined here' note must be a separate error currently - // since it may be in a different file and all errors have the same file id. - let error = DefCollectorErrorKind::OverlappingImplNote { span: prev_span }; - errors.push((error.into(), prev_file)); - } - - methods.append(&mut impl_methods); - } - } - - methods -} diff --git a/compiler/noirc_frontend/src/hir/resolution/type_aliases.rs b/compiler/noirc_frontend/src/hir/resolution/type_aliases.rs deleted file mode 100644 index 2e5ce611a7f..00000000000 --- a/compiler/noirc_frontend/src/hir/resolution/type_aliases.rs +++ /dev/null @@ -1,33 +0,0 @@ -use super::{path_resolver::StandardPathResolver, resolver::Resolver}; -use crate::{ - graph::CrateId, - hir::{ - def_collector::dc_crate::{CompilationError, UnresolvedTypeAlias}, - def_map::ModuleId, - Context, - }, - node_interner::TypeAliasId, -}; -use fm::FileId; -use std::collections::BTreeMap; - -pub(crate) fn resolve_type_aliases( - context: &mut Context, - type_aliases: BTreeMap, - crate_id: CrateId, -) -> Vec<(CompilationError, FileId)> { - let mut errors: Vec<(CompilationError, FileId)> = vec![]; - for (alias_id, unresolved_typ) in type_aliases { - let path_resolver = StandardPathResolver::new(ModuleId { - local_id: unresolved_typ.module_id, - krate: crate_id, - }); - let file = unresolved_typ.file_id; - let (typ, generics, resolver_errors) = - Resolver::new(&mut context.def_interner, &path_resolver, &context.def_maps, file) - .resolve_type_alias(unresolved_typ.type_alias_def, alias_id); - errors.extend(resolver_errors.iter().cloned().map(|e| (e.into(), file))); - context.def_interner.set_type_alias(alias_id, typ, generics); - } - errors -} diff --git a/compiler/noirc_frontend/src/tests.rs b/compiler/noirc_frontend/src/tests.rs index 321ac3f549d..956b1c57de7 100644 --- a/compiler/noirc_frontend/src/tests.rs +++ b/compiler/noirc_frontend/src/tests.rs @@ -50,10 +50,7 @@ pub(crate) fn remove_experimental_warnings(errors: &mut Vec<(CompilationError, F }); } -pub(crate) fn get_program( - src: &str, - use_legacy: bool, -) -> (ParsedModule, Context, Vec<(CompilationError, FileId)>) { +pub(crate) fn get_program(src: &str) -> (ParsedModule, Context, Vec<(CompilationError, FileId)>) { let root = std::path::Path::new("/"); let fm = FileManager::new(root); @@ -85,7 +82,6 @@ pub(crate) fn get_program( &mut context, program.clone().into_sorted(), root_file_id, - use_legacy, None, // No debug_comptime_in_file &[], // No macro processors )); @@ -94,7 +90,7 @@ pub(crate) fn get_program( } pub(crate) fn get_program_errors(src: &str) -> Vec<(CompilationError, FileId)> { - get_program(src, false).2 + get_program(src).2 } fn assert_no_errors(src: &str) { @@ -833,7 +829,7 @@ fn check_trait_as_type_as_two_fn_parameters() { } fn get_program_captures(src: &str) -> Vec> { - let (program, context, _errors) = get_program(src, false); + let (program, context, _errors) = get_program(src); let interner = context.def_interner; let mut all_captures: Vec> = Vec::new(); for func in program.into_sorted().functions { @@ -1195,7 +1191,7 @@ fn resolve_fmt_strings() { } fn check_rewrite(src: &str, expected: &str) { - let (_program, mut context, _errors) = get_program(src, false); + let (_program, mut context, _errors) = get_program(src); let main_func_id = context.def_interner.find_function("main").unwrap(); let program = monomorphize(main_func_id, &mut context.def_interner).unwrap(); assert!(format!("{}", program) == expected); diff --git a/tooling/lsp/src/lib.rs b/tooling/lsp/src/lib.rs index 542876d6319..bdc59500fbd 100644 --- a/tooling/lsp/src/lib.rs +++ b/tooling/lsp/src/lib.rs @@ -406,8 +406,7 @@ fn prepare_package_from_source_string() { let mut state = LspState::new(&client, acvm::blackbox_solver::StubbedBlackBoxSolver); let (mut context, crate_id) = crate::prepare_source(source.to_string(), &mut state); - let _check_result = - noirc_driver::check_crate(&mut context, crate_id, false, false, false, None); + let _check_result = noirc_driver::check_crate(&mut context, crate_id, false, false, None); let main_func_id = context.get_main_function(&crate_id); assert!(main_func_id.is_some()); } diff --git a/tooling/lsp/src/notifications/mod.rs b/tooling/lsp/src/notifications/mod.rs index a5ded236514..b6c28d37b91 100644 --- a/tooling/lsp/src/notifications/mod.rs +++ b/tooling/lsp/src/notifications/mod.rs @@ -58,7 +58,7 @@ pub(super) fn on_did_change_text_document( let file_path = params.text_document.uri.to_file_path().unwrap(); let (mut context, crate_id) = prepare_source(text, state); - let _ = check_crate(&mut context, crate_id, false, false, false, None); + let _ = check_crate(&mut context, crate_id, false, false, None); let workspace = match resolve_workspace_for_source_path( params.text_document.uri.to_file_path().unwrap().as_path(), @@ -147,11 +147,10 @@ pub(crate) fn process_workspace_for_noir_document( let (mut context, crate_id) = crate::prepare_package(&workspace_file_manager, &parsed_files, package); - let file_diagnostics = - match check_crate(&mut context, crate_id, false, false, false, None) { - Ok(((), warnings)) => warnings, - Err(errors_and_warnings) => errors_and_warnings, - }; + let file_diagnostics = match check_crate(&mut context, crate_id, false, false, None) { + Ok(((), warnings)) => warnings, + Err(errors_and_warnings) => errors_and_warnings, + }; let package_root_dir: String = package.root_dir.as_os_str().to_string_lossy().into(); diff --git a/tooling/lsp/src/requests/code_lens_request.rs b/tooling/lsp/src/requests/code_lens_request.rs index 9f621a489c3..51336a324da 100644 --- a/tooling/lsp/src/requests/code_lens_request.rs +++ b/tooling/lsp/src/requests/code_lens_request.rs @@ -73,7 +73,7 @@ fn on_code_lens_request_inner( let (mut context, crate_id) = prepare_source(source_string, state); // We ignore the warnings and errors produced by compilation for producing code lenses // because we can still get the test functions even if compilation fails - let _ = check_crate(&mut context, crate_id, false, false, false, None); + let _ = check_crate(&mut context, crate_id, false, false, None); let collected_lenses = collect_lenses_for_package(&context, crate_id, &workspace, package, None); diff --git a/tooling/lsp/src/requests/mod.rs b/tooling/lsp/src/requests/mod.rs index e029750e589..55b74725e5e 100644 --- a/tooling/lsp/src/requests/mod.rs +++ b/tooling/lsp/src/requests/mod.rs @@ -313,7 +313,7 @@ where interner = def_interner; } else { // We ignore the warnings and errors produced by compilation while resolving the definition - let _ = noirc_driver::check_crate(&mut context, crate_id, false, false, false, None); + let _ = noirc_driver::check_crate(&mut context, crate_id, false, false, None); interner = &context.def_interner; } diff --git a/tooling/lsp/src/requests/test_run.rs b/tooling/lsp/src/requests/test_run.rs index b4b9b62d6b6..a4d507161c2 100644 --- a/tooling/lsp/src/requests/test_run.rs +++ b/tooling/lsp/src/requests/test_run.rs @@ -59,7 +59,7 @@ fn on_test_run_request_inner( Some(package) => { let (mut context, crate_id) = crate::prepare_package(&workspace_file_manager, &parsed_files, package); - if check_crate(&mut context, crate_id, false, false, false, None).is_err() { + if check_crate(&mut context, crate_id, false, false, None).is_err() { let result = NargoTestRunResult { id: params.id.clone(), result: "error".to_string(), diff --git a/tooling/lsp/src/requests/tests.rs b/tooling/lsp/src/requests/tests.rs index fb8b845df04..f0d2388504c 100644 --- a/tooling/lsp/src/requests/tests.rs +++ b/tooling/lsp/src/requests/tests.rs @@ -61,7 +61,7 @@ fn on_tests_request_inner( crate::prepare_package(&workspace_file_manager, &parsed_files, package); // We ignore the warnings and errors produced by compilation for producing tests // because we can still get the test functions even if compilation fails - let _ = check_crate(&mut context, crate_id, false, false, false, None); + let _ = check_crate(&mut context, crate_id, false, false, None); // We don't add test headings for a package if it contains no `#[test]` functions get_package_tests_in_crate(&context, &crate_id, &package.name) diff --git a/tooling/nargo_cli/build.rs b/tooling/nargo_cli/build.rs index 2756b58bf81..74e07efb5c1 100644 --- a/tooling/nargo_cli/build.rs +++ b/tooling/nargo_cli/build.rs @@ -59,25 +59,6 @@ const IGNORED_BRILLIG_TESTS: [&str; 11] = [ "is_unconstrained", ]; -/// Certain features are only available in the elaborator. -/// We skip these tests for non-elaborator code since they are not -/// expected to work there. This can be removed once the old code is removed. -const IGNORED_NEW_FEATURE_TESTS: [&str; 13] = [ - "macros", - "wildcard_type", - "type_definition_annotation", - "numeric_generics_explicit", - "derive_impl", - "comptime_traits", - "comptime_slice_methods", - "unary_operator_overloading", - "unquote_multiple_items_from_annotation", - "function_attribute", - "trait_attribute", - "regression_5428", - "unquote", -]; - fn read_test_cases( test_data_dir: &Path, test_sub_dir: &str, @@ -138,19 +119,6 @@ fn generate_execution_success_tests(test_file: &mut File, test_data_dir: &Path) nargo.assert().success();"#, ); - if !IGNORED_NEW_FEATURE_TESTS.contains(&test_name.as_str()) { - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("execute").arg("--force").arg("--use-legacy"); - - nargo.assert().success();"#, - ); - } - if !IGNORED_BRILLIG_TESTS.contains(&test_name.as_str()) { generate_test_case( test_file, @@ -182,17 +150,6 @@ fn generate_execution_failure_tests(test_file: &mut File, test_data_dir: &Path) nargo.assert().failure().stderr(predicate::str::contains("The application panicked (crashed).").not());"#, ); - - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("execute").arg("--force").arg("--use-legacy"); - - nargo.assert().failure().stderr(predicate::str::contains("The application panicked (crashed).").not());"#, - ); } } @@ -212,17 +169,6 @@ fn generate_noir_test_success_tests(test_file: &mut File, test_data_dir: &Path) nargo.assert().success();"#, ); - - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("test").arg("--use-legacy"); - - nargo.assert().success();"#, - ); } } @@ -241,17 +187,6 @@ fn generate_noir_test_failure_tests(test_file: &mut File, test_data_dir: &Path) nargo.assert().failure();"#, ); - - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("test").arg("--use-legacy"); - - nargo.assert().failure();"#, - ); } } @@ -288,21 +223,6 @@ fn generate_compile_success_empty_tests(test_file: &mut File, test_data_dir: &Pa {assert_zero_opcodes}"#, ), ); - - if !IGNORED_NEW_FEATURE_TESTS.contains(&test_name.as_str()) { - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - &format!( - r#" - nargo.arg("info").arg("--json").arg("--force").arg("--use-legacy"); - - {assert_zero_opcodes}"#, - ), - ); - } } } @@ -321,17 +241,6 @@ fn generate_compile_success_contract_tests(test_file: &mut File, test_data_dir: nargo.arg("compile").arg("--force"); nargo.assert().success();"#, ); - - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("compile").arg("--force").arg("--use-legacy"); - - nargo.assert().success();"#, - ); } } @@ -351,17 +260,6 @@ fn generate_compile_success_no_bug_tests(test_file: &mut File, test_data_dir: &P nargo.arg("compile").arg("--force"); nargo.assert().success().stderr(predicate::str::contains("bug:").not());"#, ); - - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("compile").arg("--force").arg("--use-legacy"); - - nargo.assert().success().stderr(predicate::str::contains("bug:").not());"#, - ); } } @@ -380,18 +278,5 @@ fn generate_compile_failure_tests(test_file: &mut File, test_data_dir: &Path) { nargo.assert().failure().stderr(predicate::str::contains("The application panicked (crashed).").not());"#, ); - - if !IGNORED_NEW_FEATURE_TESTS.contains(&test_name.as_str()) { - generate_test_case( - test_file, - test_type, - &format!("legacy_{test_name}"), - &test_dir, - r#" - nargo.arg("compile").arg("--force").arg("--use-legacy"); - - nargo.assert().failure().stderr(predicate::str::contains("The application panicked (crashed).").not());"#, - ); - } } } diff --git a/tooling/nargo_cli/src/cli/check_cmd.rs b/tooling/nargo_cli/src/cli/check_cmd.rs index 95726492418..d40bae1ecfd 100644 --- a/tooling/nargo_cli/src/cli/check_cmd.rs +++ b/tooling/nargo_cli/src/cli/check_cmd.rs @@ -87,7 +87,6 @@ fn check_package( compile_options.deny_warnings, compile_options.disable_macros, compile_options.silence_warnings, - compile_options.use_legacy, compile_options.debug_comptime_in_file.as_deref(), )?; @@ -161,17 +160,10 @@ pub(crate) fn check_crate_and_report_errors( deny_warnings: bool, disable_macros: bool, silence_warnings: bool, - use_legacy: bool, debug_comptime_in_file: Option<&str>, ) -> Result<(), CompileError> { - let result = check_crate( - context, - crate_id, - deny_warnings, - disable_macros, - use_legacy, - debug_comptime_in_file, - ); + let result = + check_crate(context, crate_id, deny_warnings, disable_macros, debug_comptime_in_file); report_errors(result, &context.file_manager, deny_warnings, silence_warnings) } diff --git a/tooling/nargo_cli/src/cli/export_cmd.rs b/tooling/nargo_cli/src/cli/export_cmd.rs index 105190c653f..1b7ba97d68d 100644 --- a/tooling/nargo_cli/src/cli/export_cmd.rs +++ b/tooling/nargo_cli/src/cli/export_cmd.rs @@ -89,7 +89,6 @@ fn compile_exported_functions( compile_options.deny_warnings, compile_options.disable_macros, compile_options.silence_warnings, - compile_options.use_legacy, compile_options.debug_comptime_in_file.as_deref(), )?; diff --git a/tooling/nargo_cli/src/cli/test_cmd.rs b/tooling/nargo_cli/src/cli/test_cmd.rs index 27c66c956d9..c8848e2e304 100644 --- a/tooling/nargo_cli/src/cli/test_cmd.rs +++ b/tooling/nargo_cli/src/cli/test_cmd.rs @@ -176,7 +176,6 @@ fn run_test + Default>( crate_id, compile_options.deny_warnings, compile_options.disable_macros, - compile_options.use_legacy, compile_options.debug_comptime_in_file.as_deref(), ) .expect("Any errors should have occurred when collecting test functions"); @@ -244,7 +243,6 @@ fn get_tests_in_package( compile_options.deny_warnings, compile_options.disable_macros, compile_options.silence_warnings, - compile_options.use_legacy, compile_options.debug_comptime_in_file.as_deref(), )?; diff --git a/tooling/nargo_cli/tests/stdlib-tests.rs b/tooling/nargo_cli/tests/stdlib-tests.rs index cc44b269c6a..c4cc792438e 100644 --- a/tooling/nargo_cli/tests/stdlib-tests.rs +++ b/tooling/nargo_cli/tests/stdlib-tests.rs @@ -33,7 +33,7 @@ fn run_stdlib_tests() { let (mut context, dummy_crate_id) = prepare_package(&file_manager, &parsed_files, &dummy_package); - let result = check_crate(&mut context, dummy_crate_id, false, false, false, None); + let result = check_crate(&mut context, dummy_crate_id, false, false, None); report_errors(result, &context.file_manager, true, false) .expect("Error encountered while compiling standard library");