diff --git a/forc-pkg/src/pkg.rs b/forc-pkg/src/pkg.rs index 9857562d689..55acf0b3af5 100644 --- a/forc-pkg/src/pkg.rs +++ b/forc-pkg/src/pkg.rs @@ -29,7 +29,7 @@ use std::{ use sway_core::{ abi_generation::{evm_json_abi, fuel_json_abi}, asm_generation::ProgramABI, - decl_engine::{DeclEngine, DeclId}, + decl_engine::{DeclEngine, DeclRef}, fuel_prelude::{ fuel_crypto, fuel_tx::{self, Contract, ContractId, StorageSlot}, @@ -2696,9 +2696,9 @@ impl PkgEntry { finalized_entry: &FinalizedEntry, decl_engine: &DeclEngine, ) -> Result { - let pkg_entry_kind = match &finalized_entry.test_decl_id { - Some(test_decl_id) => { - let pkg_test_entry = PkgTestEntry::from_decl(test_decl_id.clone(), decl_engine)?; + let pkg_entry_kind = match &finalized_entry.test_decl_ref { + Some(test_decl_ref) => { + let pkg_test_entry = PkgTestEntry::from_decl(test_decl_ref.clone(), decl_engine)?; PkgEntryKind::Test(pkg_test_entry) } None => PkgEntryKind::Main, @@ -2722,9 +2722,9 @@ impl PkgEntryKind { } impl PkgTestEntry { - fn from_decl(decl_id: DeclId, decl_engine: &DeclEngine) -> Result { - let span = decl_id.span(); - let test_function_decl = decl_engine.get_function(decl_id, &span)?; + fn from_decl(decl_ref: DeclRef, decl_engine: &DeclEngine) -> Result { + let span = decl_ref.span(); + let test_function_decl = decl_engine.get_function(&decl_ref, &span)?; let test_args: HashSet = test_function_decl .attributes diff --git a/forc-plugins/forc-doc/src/descriptor.rs b/forc-plugins/forc-doc/src/descriptor.rs index 232d224ce5f..09065eb49f0 100644 --- a/forc-plugins/forc-doc/src/descriptor.rs +++ b/forc-plugins/forc-doc/src/descriptor.rs @@ -8,17 +8,16 @@ use sway_core::{ decl_engine::*, language::ty::{TyDeclaration, TyTraitFn}, }; -use sway_types::Spanned; trait RequiredMethods { fn to_methods(&self, decl_engine: &DeclEngine) -> Result>; } -impl RequiredMethods for Vec { +impl RequiredMethods for Vec { fn to_methods(&self, decl_engine: &DeclEngine) -> Result> { self.iter() - .map(|decl_id| { + .map(|DeclRef { id, decl_span, .. }| { decl_engine - .get_trait_fn(decl_id.clone(), &decl_id.span()) + .get_trait_fn(id, decl_span) .map_err(|e| anyhow::anyhow!("{}", e)) }) .collect::>() @@ -44,8 +43,10 @@ impl Descriptor { use swayfmt::parse; use TyDeclaration::*; match ty_decl { - StructDeclaration(ref decl_id) => { - let struct_decl = decl_engine.get_struct(decl_id.clone(), &decl_id.span())?; + StructDeclaration { + decl_id, decl_span, .. + } => { + let struct_decl = decl_engine.get_struct(decl_id, decl_span)?; if !document_private_items && struct_decl.visibility.is_private() { Ok(Descriptor::NonDocumentable) } else { @@ -76,8 +77,10 @@ impl Descriptor { })) } } - EnumDeclaration(ref decl_id) => { - let enum_decl = decl_engine.get_enum(decl_id.clone(), &decl_id.span())?; + EnumDeclaration { + decl_id, decl_span, .. + } => { + let enum_decl = decl_engine.get_enum(decl_id, decl_span)?; if !document_private_items && enum_decl.visibility.is_private() { Ok(Descriptor::NonDocumentable) } else { @@ -108,8 +111,10 @@ impl Descriptor { })) } } - TraitDeclaration(ref decl_id) => { - let trait_decl = decl_engine.get_trait(decl_id.clone(), &decl_id.span())?; + TraitDeclaration { + decl_id, decl_span, .. + } => { + let trait_decl = decl_engine.get_trait(decl_id, decl_span)?; if !document_private_items && trait_decl.visibility.is_private() { Ok(Descriptor::NonDocumentable) } else { @@ -143,8 +148,10 @@ impl Descriptor { })) } } - AbiDeclaration(ref decl_id) => { - let abi_decl = decl_engine.get_abi(decl_id.clone(), &decl_id.span())?; + AbiDeclaration { + decl_id, decl_span, .. + } => { + let abi_decl = decl_engine.get_abi(decl_id, decl_span)?; let item_name = abi_decl.name; let attrs_opt = (!abi_decl.attributes.is_empty()).then(|| abi_decl.attributes.to_html_string()); @@ -172,8 +179,10 @@ impl Descriptor { raw_attributes: attrs_opt, })) } - StorageDeclaration(ref decl_id) => { - let storage_decl = decl_engine.get_storage(decl_id.clone(), &decl_id.span())?; + StorageDeclaration { + decl_id, decl_span, .. + } => { + let storage_decl = decl_engine.get_storage(decl_id, decl_span)?; let item_name = sway_types::BaseIdent::new_no_trim( sway_types::span::Span::from_string(CONTRACT_STORAGE.to_string()), ); @@ -203,12 +212,12 @@ impl Descriptor { })) } // Uncomment this when we decide how to handle ImplTraits - // ImplTrait(ref decl_id) => { + // ImplTrait { decl_id, decl_span, .. } => { // TODO: figure out how to use this, likely we don't want to document this directly. // // This declaration type may make more sense to document as part of another declaration // much like how we document method functions for traits or fields on structs. - // let impl_trait = decl_engine.get_impl_trait(decl_id.clone(), &decl_id.span())?; + // let impl_trait = decl_engine.get_impl_trait(&decl_ref, decl_span)?; // let item_name = impl_trait.trait_name.suffix; // Ok(Descriptor::Documentable(Document { // module_info: module_info.clone(), @@ -230,8 +239,10 @@ impl Descriptor { // raw_attributes: None, // })) // } - FunctionDeclaration(ref decl_id) => { - let fn_decl = decl_engine.get_function(decl_id.clone(), &decl_id.span())?; + FunctionDeclaration { + decl_id, decl_span, .. + } => { + let fn_decl = decl_engine.get_function(decl_id, decl_span)?; if !document_private_items && fn_decl.visibility.is_private() { Ok(Descriptor::NonDocumentable) } else { @@ -260,8 +271,10 @@ impl Descriptor { })) } } - ConstantDeclaration(ref decl_id) => { - let const_decl = decl_engine.get_constant(decl_id.clone(), &decl_id.span())?; + ConstantDeclaration { + decl_id, decl_span, .. + } => { + let const_decl = decl_engine.get_constant(decl_id, decl_span)?; if !document_private_items && const_decl.visibility.is_private() { Ok(Descriptor::NonDocumentable) } else { diff --git a/forc-plugins/forc-doc/src/doc.rs b/forc-plugins/forc-doc/src/doc.rs index 9a05c752af0..0972e8459a6 100644 --- a/forc-plugins/forc-doc/src/doc.rs +++ b/forc-plugins/forc-doc/src/doc.rs @@ -26,7 +26,7 @@ impl Document { pub(crate) fn html_filename(&self) -> String { use sway_core::language::ty::TyDeclaration::StorageDeclaration; let name = match &self.item_body.ty_decl { - StorageDeclaration(_) => None, + StorageDeclaration { .. } => None, _ => Some(self.item_header.item_name.as_str()), }; diff --git a/forc-plugins/forc-doc/src/render.rs b/forc-plugins/forc-doc/src/render.rs index c03b4ab43f8..a7791035436 100644 --- a/forc-plugins/forc-doc/src/render.rs +++ b/forc-plugins/forc-doc/src/render.rs @@ -52,31 +52,31 @@ impl RenderedDocumentation { match module_map.get_mut(&location) { Some(doc_links) => { match doc.item_body.ty_decl { - StructDeclaration(_) => match doc_links.get_mut(&BlockTitle::Structs) { + StructDeclaration { .. } => match doc_links.get_mut(&BlockTitle::Structs) { Some(links) => links.push(doc.link()), None => { doc_links.insert(BlockTitle::Structs, vec![doc.link()]); } }, - EnumDeclaration(_) => match doc_links.get_mut(&BlockTitle::Enums) { + EnumDeclaration { .. } => match doc_links.get_mut(&BlockTitle::Enums) { Some(links) => links.push(doc.link()), None => { doc_links.insert(BlockTitle::Enums, vec![doc.link()]); } }, - TraitDeclaration(_) => match doc_links.get_mut(&BlockTitle::Traits) { + TraitDeclaration { .. } => match doc_links.get_mut(&BlockTitle::Traits) { Some(links) => links.push(doc.link()), None => { doc_links.insert(BlockTitle::Traits, vec![doc.link()]); } }, - AbiDeclaration(_) => match doc_links.get_mut(&BlockTitle::Abi) { + AbiDeclaration { .. } => match doc_links.get_mut(&BlockTitle::Abi) { Some(links) => links.push(doc.link()), None => { doc_links.insert(BlockTitle::Abi, vec![doc.link()]); } }, - StorageDeclaration(_) => { + StorageDeclaration { .. } => { match doc_links.get_mut(&BlockTitle::ContractStorage) { Some(links) => links.push(doc.link()), None => { @@ -84,43 +84,47 @@ impl RenderedDocumentation { } } } - FunctionDeclaration(_) => match doc_links.get_mut(&BlockTitle::Functions) { - Some(links) => links.push(doc.link()), - None => { - doc_links.insert(BlockTitle::Functions, vec![doc.link()]); + FunctionDeclaration { .. } => { + match doc_links.get_mut(&BlockTitle::Functions) { + Some(links) => links.push(doc.link()), + None => { + doc_links.insert(BlockTitle::Functions, vec![doc.link()]); + } } - }, - ConstantDeclaration(_) => match doc_links.get_mut(&BlockTitle::Constants) { - Some(links) => links.push(doc.link()), - None => { - doc_links.insert(BlockTitle::Constants, vec![doc.link()]); + } + ConstantDeclaration { .. } => { + match doc_links.get_mut(&BlockTitle::Constants) { + Some(links) => links.push(doc.link()), + None => { + doc_links.insert(BlockTitle::Constants, vec![doc.link()]); + } } - }, + } _ => {} // TODO: ImplTraitDeclaration } } None => { let mut doc_links: BTreeMap> = BTreeMap::new(); match doc.item_body.ty_decl { - StructDeclaration(_) => { + StructDeclaration { .. } => { doc_links.insert(BlockTitle::Structs, vec![doc.link()]); } - EnumDeclaration(_) => { + EnumDeclaration { .. } => { doc_links.insert(BlockTitle::Enums, vec![doc.link()]); } - TraitDeclaration(_) => { + TraitDeclaration { .. } => { doc_links.insert(BlockTitle::Traits, vec![doc.link()]); } - AbiDeclaration(_) => { + AbiDeclaration { .. } => { doc_links.insert(BlockTitle::Abi, vec![doc.link()]); } - StorageDeclaration(_) => { + StorageDeclaration { .. } => { doc_links.insert(BlockTitle::ContractStorage, vec![doc.link()]); } - FunctionDeclaration(_) => { + FunctionDeclaration { .. } => { doc_links.insert(BlockTitle::Functions, vec![doc.link()]); } - ConstantDeclaration(_) => { + ConstantDeclaration { .. } => { doc_links.insert(BlockTitle::Constants, vec![doc.link()]); } _ => {} // TODO: ImplTraitDeclaration @@ -156,55 +160,60 @@ impl RenderedDocumentation { } // Above we check for the module a link belongs to, here we want _all_ links so the check is much more shallow. match doc.item_body.ty_decl { - StructDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Structs) { + StructDeclaration { .. } => match all_docs.links.get_mut(&BlockTitle::Structs) { Some(links) => links.push(doc.link()), None => { all_docs.links.insert(BlockTitle::Structs, vec![doc.link()]); } }, - EnumDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Enums) { + EnumDeclaration { .. } => match all_docs.links.get_mut(&BlockTitle::Enums) { Some(links) => links.push(doc.link()), None => { all_docs.links.insert(BlockTitle::Enums, vec![doc.link()]); } }, - TraitDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Traits) { + TraitDeclaration { .. } => match all_docs.links.get_mut(&BlockTitle::Traits) { Some(links) => links.push(doc.link()), None => { all_docs.links.insert(BlockTitle::Traits, vec![doc.link()]); } }, - AbiDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Abi) { + AbiDeclaration { .. } => match all_docs.links.get_mut(&BlockTitle::Abi) { Some(links) => links.push(doc.link()), None => { all_docs.links.insert(BlockTitle::Abi, vec![doc.link()]); } }, - StorageDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::ContractStorage) - { - Some(links) => links.push(doc.link()), - None => { - all_docs - .links - .insert(BlockTitle::ContractStorage, vec![doc.link()]); + StorageDeclaration { .. } => { + match all_docs.links.get_mut(&BlockTitle::ContractStorage) { + Some(links) => links.push(doc.link()), + None => { + all_docs + .links + .insert(BlockTitle::ContractStorage, vec![doc.link()]); + } } - }, - FunctionDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Functions) { - Some(links) => links.push(doc.link()), - None => { - all_docs - .links - .insert(BlockTitle::Functions, vec![doc.link()]); + } + FunctionDeclaration { .. } => { + match all_docs.links.get_mut(&BlockTitle::Functions) { + Some(links) => links.push(doc.link()), + None => { + all_docs + .links + .insert(BlockTitle::Functions, vec![doc.link()]); + } } - }, - ConstantDeclaration(_) => match all_docs.links.get_mut(&BlockTitle::Constants) { - Some(links) => links.push(doc.link()), - None => { - all_docs - .links - .insert(BlockTitle::Constants, vec![doc.link()]); + } + ConstantDeclaration { .. } => { + match all_docs.links.get_mut(&BlockTitle::Constants) { + Some(links) => links.push(doc.link()), + None => { + all_docs + .links + .insert(BlockTitle::Constants, vec![doc.link()]); + } } - }, + } _ => {} // TODO: ImplTraitDeclaration } } @@ -661,13 +670,13 @@ impl Renderable for TyTraitFn { write!(fn_sig, ") -> {}", self.return_type_span.as_str())?; let multiline = fn_sig.chars().count() >= 60; - let method_id = format!("tymethod.{}", self.name.as_str()); + let method_ref = format!("tymethod.{}", self.name.as_str()); Ok(box_html! { div(class="methods") { - div(id=&method_id, class="method has-srclink") { + div(id=&method_ref, class="method has-srclink") { h4(class="code-header") { : "fn "; - a(class="fnname", href=format!("{IDENTITY}{method_id}")) { + a(class="fnname", href=format!("{IDENTITY}{method_ref}")) { : self.name.as_str(); } : "("; diff --git a/sway-core/src/asm_generation/finalized_asm.rs b/sway-core/src/asm_generation/finalized_asm.rs index e6c14eead3c..ff12f21e911 100644 --- a/sway-core/src/asm_generation/finalized_asm.rs +++ b/sway-core/src/asm_generation/finalized_asm.rs @@ -4,7 +4,7 @@ use super::{ ProgramABI, ProgramKind, }; use crate::asm_lang::allocated_ops::{AllocatedOp, AllocatedOpcode}; -use crate::decl_engine::DeclId; +use crate::decl_engine::DeclRef; use crate::error::*; use crate::source_map::SourceMap; @@ -36,7 +36,7 @@ pub struct FinalizedEntry { pub selector: Option<[u8; 4]>, /// If this entry is constructed from a test function contains the declaration id for that /// function, otherwise contains `None`. - pub test_decl_id: Option, + pub test_decl_ref: Option, } /// The bytecode for a sway program as well as the byte offsets of configuration-time constants in diff --git a/sway-core/src/asm_generation/from_ir.rs b/sway-core/src/asm_generation/from_ir.rs index 5d8ee1ffe90..c03ebecd312 100644 --- a/sway-core/src/asm_generation/from_ir.rs +++ b/sway-core/src/asm_generation/from_ir.rs @@ -109,11 +109,11 @@ fn compile_module_to_asm( let (data_section, reg_seqr, entries, non_entries) = result; let entries = entries .into_iter() - .map(|(func, label, ops, test_decl_id)| { + .map(|(func, label, ops, test_decl_ref)| { let selector = func.get_selector(context); let name = func.get_name(context).to_string(); AbstractEntry { - test_decl_id, + test_decl_ref, selector, label, ops, diff --git a/sway-core/src/asm_generation/fuel/fuel_asm_builder.rs b/sway-core/src/asm_generation/fuel/fuel_asm_builder.rs index 96d9df5e750..52f700eaf64 100644 --- a/sway-core/src/asm_generation/fuel/fuel_asm_builder.rs +++ b/sway-core/src/asm_generation/fuel/fuel_asm_builder.rs @@ -13,7 +13,7 @@ use crate::{ ProgramKind, }, asm_lang::{virtual_register::*, Label, Op, VirtualImmediate12, VirtualImmediate18, VirtualOp}, - decl_engine::DeclId, + decl_engine::DeclRef, error::*, fuel_prelude::fuel_crypto::Hasher, metadata::MetadataManager, @@ -63,7 +63,7 @@ pub struct FuelAsmBuilder<'ir> { // Final resulting VM bytecode ops; entry functions with their function and label, and regular // non-entry functions. - pub(super) entries: Vec<(Function, Label, Vec, Option)>, + pub(super) entries: Vec<(Function, Label, Vec, Option)>, pub(super) non_entries: Vec>, // In progress VM bytecode ops. @@ -73,7 +73,7 @@ pub struct FuelAsmBuilder<'ir> { pub type FuelAsmBuilderResult = ( DataSection, RegisterSequencer, - Vec<(Function, Label, AbstractInstructionSet, Option)>, + Vec<(Function, Label, AbstractInstructionSet, Option)>, Vec, ); @@ -140,8 +140,8 @@ impl<'ir> FuelAsmBuilder<'ir> { self.entries .clone() .into_iter() - .map(|(f, l, ops, test_decl_id)| { - (f, l, AbstractInstructionSet { ops }, test_decl_id) + .map(|(f, l, ops, test_decl_ref)| { + (f, l, AbstractInstructionSet { ops }, test_decl_ref) }) .collect(), self.non_entries diff --git a/sway-core/src/asm_generation/fuel/functions.rs b/sway-core/src/asm_generation/fuel/functions.rs index c82a92a4524..40b5de09f9f 100644 --- a/sway-core/src/asm_generation/fuel/functions.rs +++ b/sway-core/src/asm_generation/fuel/functions.rs @@ -8,7 +8,7 @@ use crate::{ virtual_register::*, Op, OrganizationalOp, VirtualImmediate12, VirtualImmediate18, VirtualImmediate24, VirtualOp, }, - decl_engine::DeclId, + decl_engine::DeclRef, error::*, fuel_prelude::fuel_asm::GTFArgs, size_bytes_in_words, size_bytes_round_up_to_word_alignment, @@ -150,8 +150,8 @@ impl<'ir> FuelAsmBuilder<'ir> { let md = function.get_metadata(self.context); let span = self.md_mgr.md_to_span(self.context, md); let test_decl_index = self.md_mgr.md_to_test_decl_index(self.context, md); - let test_decl_id = match (&span, &test_decl_index) { - (Some(span), Some(decl_index)) => Some(DeclId::new( + let test_decl_ref = match (&span, &test_decl_index) { + (Some(span), Some(decl_index)) => Some(DeclRef::new( Ident::new(span.clone()), *decl_index, span.clone(), @@ -265,7 +265,7 @@ impl<'ir> FuelAsmBuilder<'ir> { ops.append(&mut self.cur_bytecode); if func_is_entry { self.entries - .push((function, start_label, ops, test_decl_id)); + .push((function, start_label, ops, test_decl_ref)); } else { self.non_entries.push(ops); } diff --git a/sway-core/src/asm_generation/programs.rs b/sway-core/src/asm_generation/programs.rs index 5b38f937b77..0084e2f0beb 100644 --- a/sway-core/src/asm_generation/programs.rs +++ b/sway-core/src/asm_generation/programs.rs @@ -10,7 +10,7 @@ use super::fuel::{ use crate::{ asm_lang::{allocated_ops::AllocatedOp, Label}, - decl_engine::DeclId, + decl_engine::DeclRef, }; type SelectorOpt = Option<[u8; 4]>; @@ -44,7 +44,7 @@ pub(super) struct AbstractEntry { pub(super) label: Label, pub(super) ops: AbstractInstructionSet, pub(super) name: FnName, - pub(super) test_decl_id: Option, + pub(super) test_decl_ref: Option, } /// An AllocatedProgram represents code which has allocated registers but still has abstract @@ -54,7 +54,7 @@ pub(super) struct AllocatedProgram { data_section: DataSection, prologue: AllocatedAbstractInstructionSet, functions: Vec, - entries: Vec<(SelectorOpt, Label, FnName, Option)>, + entries: Vec<(SelectorOpt, Label, FnName, Option)>, } /// A FinalProgram represents code which may be serialized to VM bytecode. @@ -63,7 +63,7 @@ pub(super) enum FinalProgram { kind: ProgramKind, data_section: DataSection, ops: Vec, - entries: Vec<(SelectorOpt, ImmOffset, FnName, Option)>, + entries: Vec<(SelectorOpt, ImmOffset, FnName, Option)>, }, Evm { ops: Vec, diff --git a/sway-core/src/asm_generation/programs/abstract.rs b/sway-core/src/asm_generation/programs/abstract.rs index 7d4a1bc2975..d3ef4291da7 100644 --- a/sway-core/src/asm_generation/programs/abstract.rs +++ b/sway-core/src/asm_generation/programs/abstract.rs @@ -54,7 +54,7 @@ impl AbstractProgram { entry.selector, entry.label, entry.name.clone(), - entry.test_decl_id.clone(), + entry.test_decl_ref.clone(), ) }) .collect(); diff --git a/sway-core/src/asm_generation/programs/allocated.rs b/sway-core/src/asm_generation/programs/allocated.rs index b8938def270..ef3f6acd9ce 100644 --- a/sway-core/src/asm_generation/programs/allocated.rs +++ b/sway-core/src/asm_generation/programs/allocated.rs @@ -21,12 +21,12 @@ impl AllocatedProgram { let entries = self .entries .into_iter() - .map(|(selector, label, name, test_decl_id)| { + .map(|(selector, label, name, test_decl_ref)| { let offset = label_offsets .remove(&label) .expect("no offset for entry") .offs; - (selector, offset, name, test_decl_id) + (selector, offset, name, test_decl_ref) }) .collect(); diff --git a/sway-core/src/asm_generation/programs/final.rs b/sway-core/src/asm_generation/programs/final.rs index 4326b6704ae..9e8a670aa9f 100644 --- a/sway-core/src/asm_generation/programs/final.rs +++ b/sway-core/src/asm_generation/programs/final.rs @@ -21,11 +21,11 @@ impl FinalProgram { program_kind: kind, entries: entries .into_iter() - .map(|(selector, imm, fn_name, test_decl_id)| FinalizedEntry { + .map(|(selector, imm, fn_name, test_decl_ref)| FinalizedEntry { imm, fn_name, selector, - test_decl_id, + test_decl_ref, }) .collect(), abi: None, diff --git a/sway-core/src/control_flow_analysis/analyze_return_paths.rs b/sway-core/src/control_flow_analysis/analyze_return_paths.rs index f2ab5f1c025..a87e1d27b46 100644 --- a/sway-core/src/control_flow_analysis/analyze_return_paths.rs +++ b/sway-core/src/control_flow_analysis/analyze_return_paths.rs @@ -3,7 +3,7 @@ use crate::{ control_flow_analysis::*, - decl_engine::DeclId, + decl_engine::DeclRef, language::{ty, CallPath}, type_system::*, Engines, @@ -182,21 +182,21 @@ fn connect_declaration<'eng: 'cfg, 'cfg>( use ty::TyDeclaration::*; let decl_engine = engines.de(); match decl { - TraitDeclaration(_) - | AbiDeclaration(_) - | StructDeclaration(_) - | EnumDeclaration(_) - | StorageDeclaration(_) + TraitDeclaration { .. } + | AbiDeclaration { .. } + | StructDeclaration { .. } + | EnumDeclaration { .. } + | StorageDeclaration { .. } | GenericTypeForFunctionScope { .. } => Ok(leaves.to_vec()), - VariableDeclaration(_) | ConstantDeclaration(_) => { + VariableDeclaration(_) | ConstantDeclaration { .. } => { let entry_node = graph.add_node(node.into()); for leaf in leaves { graph.add_edge(*leaf, entry_node, "".into()); } Ok(vec![entry_node]) } - FunctionDeclaration(decl_id) => { - let fn_decl = decl_engine.get_function(decl_id.clone(), &decl.span())?; + FunctionDeclaration { decl_id, .. } => { + let fn_decl = decl_engine.get_function(decl_id, &decl.span())?; let entry_node = graph.add_node(node.into()); for leaf in leaves { graph.add_edge(*leaf, entry_node, "".into()); @@ -204,12 +204,12 @@ fn connect_declaration<'eng: 'cfg, 'cfg>( connect_typed_fn_decl(engines, &fn_decl, graph, entry_node, span)?; Ok(leaves.to_vec()) } - ImplTrait(decl_id) => { + ImplTrait { decl_id, .. } => { let ty::TyImplTrait { trait_name, methods, .. - } = decl_engine.get_impl_trait(decl_id.clone(), &span)?; + } = decl_engine.get_impl_trait(decl_id, &span)?; let entry_node = graph.add_node(node.into()); for leaf in leaves { graph.add_edge(*leaf, entry_node, "".into()); @@ -231,18 +231,18 @@ fn connect_impl_trait<'eng: 'cfg, 'cfg>( engines: Engines<'eng>, trait_name: &CallPath, graph: &mut ControlFlowGraph<'cfg>, - methods: &[DeclId], + methods: &[DeclRef], entry_node: NodeIndex, ) -> Result<(), CompileError> { let decl_engine = engines.de(); let mut methods_and_indexes = vec![]; // insert method declarations into the graph - for method_decl_id in methods { - let fn_decl = decl_engine.get_function(method_decl_id.clone(), &trait_name.span())?; + for method_decl_ref in methods { + let fn_decl = decl_engine.get_function(method_decl_ref, &trait_name.span())?; let fn_decl_entry_node = graph.add_node(ControlFlowGraphNode::MethodDeclaration { span: fn_decl.span.clone(), method_name: fn_decl.name.clone(), - method_decl_id: method_decl_id.clone(), + method_decl_ref: method_decl_ref.clone(), engines, }); graph.add_edge(entry_node, fn_decl_entry_node, "".into()); diff --git a/sway-core/src/control_flow_analysis/dead_code_analysis.rs b/sway-core/src/control_flow_analysis/dead_code_analysis.rs index dd483f12543..906c3d8a82f 100644 --- a/sway-core/src/control_flow_analysis/dead_code_analysis.rs +++ b/sway-core/src/control_flow_analysis/dead_code_analysis.rs @@ -35,7 +35,9 @@ impl<'cfg> ControlFlowGraph<'cfg> { if let ControlFlowGraphNode::ProgramNode(ty::TyAstNode { span: function_span, content: - ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(_)), + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration { + .. + }), }) = &self.graph[*x] { function_span.end() >= span.end() && function_span.start() <= span.start() @@ -311,9 +313,9 @@ fn connect_declaration<'eng: 'cfg, 'cfg>( options, ) } - ConstantDeclaration(decl_id) => { + ConstantDeclaration { decl_id, .. } => { let ty::TyConstantDeclaration { name, value, .. } = - decl_engine.get_constant(decl_id.clone(), &span)?; + decl_engine.get_constant(decl_id, &span)?; graph.namespace.insert_constant(name, entry_node); connect_expression( engines, @@ -327,39 +329,39 @@ fn connect_declaration<'eng: 'cfg, 'cfg>( options, ) } - FunctionDeclaration(decl_id) => { - let fn_decl = decl_engine.get_function(decl_id.clone(), &decl.span())?; + FunctionDeclaration { decl_id, .. } => { + let fn_decl = decl_engine.get_function(decl_id, &decl.span())?; connect_typed_fn_decl( engines, &fn_decl, graph, entry_node, span, exit_node, tree_type, options, )?; Ok(leaves.to_vec()) } - TraitDeclaration(decl_id) => { - let trait_decl = decl_engine.get_trait(decl_id.clone(), &span)?; + TraitDeclaration { decl_id, .. } => { + let trait_decl = decl_engine.get_trait(decl_id, &span)?; connect_trait_declaration(&trait_decl, graph, entry_node); Ok(leaves.to_vec()) } - AbiDeclaration(decl_id) => { - let abi_decl = decl_engine.get_abi(decl_id.clone(), &span)?; + AbiDeclaration { decl_id, .. } => { + let abi_decl = decl_engine.get_abi(decl_id, &span)?; connect_abi_declaration(engines, &abi_decl, graph, entry_node)?; Ok(leaves.to_vec()) } - StructDeclaration(decl_id) => { - let struct_decl = decl_engine.get_struct(decl_id.clone(), &span)?; + StructDeclaration { decl_id, .. } => { + let struct_decl = decl_engine.get_struct(decl_id, &span)?; connect_struct_declaration(&struct_decl, graph, entry_node, tree_type); Ok(leaves.to_vec()) } - EnumDeclaration(decl_id) => { - let enum_decl = decl_engine.get_enum(decl_id.clone(), &span)?; + EnumDeclaration { decl_id, .. } => { + let enum_decl = decl_engine.get_enum(decl_id, &span)?; connect_enum_declaration(&enum_decl, graph, entry_node); Ok(leaves.to_vec()) } - ImplTrait(decl_id) => { + ImplTrait { decl_id, .. } => { let ty::TyImplTrait { trait_name, methods, .. - } = decl_engine.get_impl_trait(decl_id.clone(), &span)?; + } = decl_engine.get_impl_trait(decl_id, &span)?; connect_impl_trait( engines, @@ -372,8 +374,8 @@ fn connect_declaration<'eng: 'cfg, 'cfg>( )?; Ok(leaves.to_vec()) } - StorageDeclaration(decl_id) => { - let storage = decl_engine.get_storage(decl_id.clone(), &span)?; + StorageDeclaration { decl_id, .. } => { + let storage = decl_engine.get_storage(decl_id, &span)?; connect_storage_declaration(&storage, graph, entry_node, tree_type); Ok(leaves.to_vec()) } @@ -430,7 +432,7 @@ fn connect_impl_trait<'eng: 'cfg, 'cfg>( engines: Engines<'eng>, trait_name: &CallPath, graph: &mut ControlFlowGraph<'cfg>, - methods: &[DeclId], + methods: &[DeclRef], entry_node: NodeIndex, tree_type: &TreeType, options: NodeConnectionOptions, @@ -449,12 +451,12 @@ fn connect_impl_trait<'eng: 'cfg, 'cfg>( }; let mut methods_and_indexes = vec![]; // insert method declarations into the graph - for method_decl_id in methods { - let fn_decl = decl_engine.get_function(method_decl_id.clone(), &trait_name.span())?; + for method_decl_ref in methods { + let fn_decl = decl_engine.get_function(method_decl_ref, &trait_name.span())?; let fn_decl_entry_node = graph.add_node(ControlFlowGraphNode::MethodDeclaration { span: fn_decl.span.clone(), method_name: fn_decl.name.clone(), - method_decl_id: method_decl_id.clone(), + method_decl_ref: method_decl_ref.clone(), engines, }); if matches!(tree_type, TreeType::Library { .. } | TreeType::Contract) { @@ -534,8 +536,8 @@ fn connect_abi_declaration( // If a struct type is used as a return type in the interface surface // of the contract, then assume that any fields inside the struct can // be used outside of the contract. - for fn_decl_id in decl.interface_surface.iter() { - let fn_decl = decl_engine.get_trait_fn(fn_decl_id.clone(), &decl.span)?; + for fn_decl_ref in decl.interface_surface.iter() { + let fn_decl = decl_engine.get_trait_fn(fn_decl_ref, &decl.span)?; if let Some(TypeInfo::Struct { call_path, .. }) = get_struct_type_info_from_type_id(type_engine, fn_decl.return_type)? { @@ -741,34 +743,34 @@ fn depth_first_insertion_code_block<'eng: 'cfg, 'cfg>( fn get_trait_fn_node_index<'a>( engines: Engines<'_>, - function_decl_id: DeclId, + function_decl_ref: DeclRef, expression_span: Span, graph: &'a ControlFlowGraph, ) -> Result, CompileError> { let decl_engine = engines.de(); - let fn_decl = decl_engine.get_function(function_decl_id, &expression_span)?; + let fn_decl = decl_engine.get_function(&function_decl_ref, &expression_span)?; if let Some(implementing_type) = fn_decl.implementing_type { match implementing_type { - ty::TyDeclaration::TraitDeclaration(decl) => { - let trait_decl = decl_engine.get_trait(decl, &expression_span)?; + ty::TyDeclaration::TraitDeclaration { decl_id, .. } => { + let trait_decl = decl_engine.get_trait(&decl_id, &expression_span)?; Ok(graph .namespace .find_trait_method(&trait_decl.name.into(), &fn_decl.name)) } - ty::TyDeclaration::StructDeclaration(decl) => { - let struct_decl = decl_engine.get_struct(decl, &expression_span)?; + ty::TyDeclaration::StructDeclaration { decl_id, .. } => { + let struct_decl = decl_engine.get_struct(&decl_id, &expression_span)?; Ok(graph .namespace .find_trait_method(&struct_decl.call_path.suffix.into(), &fn_decl.name)) } - ty::TyDeclaration::ImplTrait(decl) => { - let impl_trait = decl_engine.get_impl_trait(decl, &expression_span)?; + ty::TyDeclaration::ImplTrait { decl_id, .. } => { + let impl_trait = decl_engine.get_impl_trait(&decl_id, &expression_span)?; Ok(graph .namespace .find_trait_method(&impl_trait.trait_name, &fn_decl.name)) } - ty::TyDeclaration::AbiDeclaration(decl) => { - let abi_decl = decl_engine.get_abi(decl, &expression_span)?; + ty::TyDeclaration::AbiDeclaration { decl_id, .. } => { + let abi_decl = decl_engine.get_abi(&decl_id, &expression_span)?; Ok(graph .namespace .find_trait_method(&abi_decl.name.into(), &fn_decl.name)) @@ -804,19 +806,19 @@ fn connect_expression<'eng: 'cfg, 'cfg>( FunctionApplication { call_path: name, arguments, - function_decl_id, + function_decl_ref, .. } => { - let fn_decl = decl_engine.get_function(function_decl_id.clone(), &expression_span)?; + let fn_decl = decl_engine.get_function(function_decl_ref, &expression_span)?; let mut is_external = false; // in the case of monomorphized functions, first check if we already have a node for // it in the namespace. if not then we need to check to see if the namespace contains // the decl id parents (the original generic non monomorphized decl id). let mut exists = false; - let parents = decl_engine.find_all_parents(engines, function_decl_id.clone()); - for parent in parents { - if let Ok(parent) = decl_engine.get_function(parent.clone(), &expression_span) { + let parents = decl_engine.find_all_parents(engines, function_decl_ref); + for parent in parents.iter() { + if let Ok(parent) = decl_engine.get_function(parent, &expression_span) { exists |= graph.namespace.get_function(&parent).is_some(); } } @@ -833,7 +835,11 @@ fn connect_expression<'eng: 'cfg, 'cfg>( engines, &ty::TyAstNode { content: ty::TyAstNodeContent::Declaration( - ty::TyDeclaration::FunctionDeclaration(function_decl_id.clone()), + ty::TyDeclaration::FunctionDeclaration { + name: function_decl_ref.name.clone(), + decl_id: function_decl_ref.id, + decl_span: function_decl_ref.decl_span.clone(), + }, ), span: expression_span.clone(), }, @@ -865,8 +871,12 @@ fn connect_expression<'eng: 'cfg, 'cfg>( ) }); - let trait_fn_node_idx = - get_trait_fn_node_index(engines, function_decl_id.clone(), expression_span, graph)?; + let trait_fn_node_idx = get_trait_fn_node_index( + engines, + function_decl_ref.clone(), + expression_span, + graph, + )?; if let Some(trait_fn_node_idx) = trait_fn_node_idx { if fn_entrypoint != *trait_fn_node_idx { graph.add_edge(fn_entrypoint, *trait_fn_node_idx, "".into()); @@ -1584,40 +1594,46 @@ fn construct_dead_code_warning_from_node( // code. ty::TyAstNode { content: - ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(decl_id)), + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration { + name, .. + }), .. } => CompileWarning { - span: decl_id.name.span(), + span: name.span(), warning_content: Warning::DeadFunctionDeclaration, }, ty::TyAstNode { content: - ty::TyAstNodeContent::Declaration(ty::TyDeclaration::StructDeclaration(decl_id)), + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::StructDeclaration { name, .. }), .. } => CompileWarning { - span: decl_id.name.span(), + span: name.span(), warning_content: Warning::DeadStructDeclaration, }, ty::TyAstNode { - content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::EnumDeclaration(decl_id)), + content: + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::EnumDeclaration { name, .. }), .. } => CompileWarning { - span: decl_id.name.span(), + span: name.span(), warning_content: Warning::DeadEnumDeclaration, }, ty::TyAstNode { - content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::TraitDeclaration(decl_id)), + content: + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::TraitDeclaration { name, .. }), .. } => CompileWarning { - span: decl_id.name.span(), + span: name.span(), warning_content: Warning::DeadTrait, }, ty::TyAstNode { content: - ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ConstantDeclaration(decl_id)), + ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ConstantDeclaration { + name, .. + }), .. } => CompileWarning { - span: decl_id.name.span(), + span: name.span(), warning_content: Warning::DeadDeclaration, }, ty::TyAstNode { @@ -1640,9 +1656,9 @@ fn construct_dead_code_warning_from_node( } } ty::TyAstNode { - content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ImplTrait(decl_id)), + content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ImplTrait { decl_id, .. }), span, - } => match decl_engine.get_impl_trait(decl_id.clone(), span) { + } => match decl_engine.get_impl_trait(decl_id, span) { Ok(ty::TyImplTrait { methods, .. }) if methods.is_empty() => return None, _ => CompileWarning { span: span.clone(), diff --git a/sway-core/src/control_flow_analysis/flow_graph/mod.rs b/sway-core/src/control_flow_analysis/flow_graph/mod.rs index 32f6d96c1a1..79b4c55cd51 100644 --- a/sway-core/src/control_flow_analysis/flow_graph/mod.rs +++ b/sway-core/src/control_flow_analysis/flow_graph/mod.rs @@ -62,7 +62,7 @@ pub enum ControlFlowGraphNode<'cfg> { MethodDeclaration { span: Span, method_name: Ident, - method_decl_id: DeclId, + method_decl_ref: DeclRef, engines: Engines<'cfg>, }, StructField { @@ -135,13 +135,13 @@ impl<'cfg> std::fmt::Debug for ControlFlowGraphNode<'cfg> { } ControlFlowGraphNode::MethodDeclaration { method_name, - method_decl_id, + method_decl_ref, engines, .. } => { let decl_engines = engines.de(); let method = decl_engines - .get_function(method_decl_id.clone(), &Span::dummy()) + .get_function(method_decl_ref, &Span::dummy()) .unwrap(); if let Some(implementing_type) = method.implementing_type { format!( diff --git a/sway-core/src/decl_engine/engine.rs b/sway-core/src/decl_engine/engine.rs index 4b0417be1c0..335402ea6e8 100644 --- a/sway-core/src/decl_engine/engine.rs +++ b/sway-core/src/decl_engine/engine.rs @@ -18,7 +18,7 @@ use crate::{ #[derive(Debug, Default)] pub struct DeclEngine { slab: ConcurrentSlab, - parents: RwLock>>, + parents: RwLock>>, } impl fmt::Display for DeclEngine { @@ -31,20 +31,33 @@ impl fmt::Display for DeclEngine { } impl DeclEngine { - pub(crate) fn get(&self, index: DeclId) -> DeclWrapper { + pub(crate) fn get<'a, T>(&self, index: &'a T) -> DeclWrapper + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)) + } + + /// This method was added as a weird workaround for a potential Rust + /// compiler bug where it is unable to resolve the trait constraints on the + /// `get` method above (???) + fn get_from_decl_id(&self, index: DeclId) -> DeclWrapper { self.slab.get(*index) } - pub(super) fn replace(&self, index: DeclId, wrapper: DeclWrapper) { - self.slab.replace(index, wrapper); + pub(super) fn replace<'a, T>(&self, index: &'a T, wrapper: DeclWrapper) + where + DeclId: From<&'a T>, + { + self.slab.replace(DeclId::from(index), wrapper); } - pub(crate) fn insert(&self, decl: T) -> DeclId + pub(crate) fn insert(&self, decl: T) -> DeclRef where T: Into<(Ident, DeclWrapper, Span)>, { let (ident, decl_wrapper, span) = decl.into(); - DeclId::new(ident, self.slab.insert(decl_wrapper), span) + DeclRef::new(ident, self.slab.insert(decl_wrapper), span) } pub(crate) fn insert_wrapper( @@ -52,31 +65,38 @@ impl DeclEngine { ident: Ident, decl_wrapper: DeclWrapper, span: Span, - ) -> DeclId { - DeclId::new(ident, self.slab.insert(decl_wrapper), span) + ) -> DeclRef { + DeclRef::new(ident, self.slab.insert(decl_wrapper), span) } - /// Given a [DeclId] `index`, finds all the parents of `index` and all the + /// Given a [DeclRef] `index`, finds all the parents of `index` and all the /// recursive parents of those parents, and so on. Does not perform - /// duplicated computation---if the parents of a [DeclId] have already been + /// duplicated computation---if the parents of a [DeclRef] have already been /// found, we do not find them again. #[allow(clippy::map_entry)] - pub(crate) fn find_all_parents(&self, engines: Engines<'_>, index: DeclId) -> Vec { + pub(crate) fn find_all_parents<'a, T>(&self, engines: Engines<'_>, index: &'a T) -> Vec + where + DeclId: From<&'a T>, + { + let index: DeclId = DeclId::from(index); let parents = self.parents.read().unwrap(); - let mut acc_parents: HashMap = HashMap::new(); - let mut already_checked: HashSet = HashSet::new(); + let mut acc_parents: HashMap = HashMap::new(); + let mut already_checked: HashSet = HashSet::new(); let mut left_to_check: VecDeque = VecDeque::from([index]); while let Some(curr) = left_to_check.pop_front() { - if !already_checked.insert(*curr) { + if !already_checked.insert(curr) { continue; } - if let Some(curr_parents) = parents.get(&*curr) { + if let Some(curr_parents) = parents.get(&curr) { for curr_parent in curr_parents.iter() { - if !acc_parents.contains_key(&**curr_parent) { - acc_parents.insert(**curr_parent, curr_parent.clone()); + if !acc_parents.contains_key(curr_parent) { + acc_parents.insert(*curr_parent, *curr_parent); } - if !left_to_check.iter().any(|x| x.eq(curr_parent, engines)) { - left_to_check.push_back(curr_parent.clone()); + if !left_to_check.iter().any(|x| { + self.get_from_decl_id(*x) + .eq(&self.get_from_decl_id(*curr_parent), engines) + }) { + left_to_check.push_back(*curr_parent); } } } @@ -84,79 +104,115 @@ impl DeclEngine { acc_parents.values().cloned().collect() } - pub(crate) fn register_parent(&self, index: &DeclId, parent: DeclId) { + pub(crate) fn register_parent<'a, T>(&self, index: &DeclRef, parent: &'a T) + where + DeclId: From<&'a T>, + { + let index: DeclId = index.into(); + let parent: DeclId = DeclId::from(parent); let mut parents = self.parents.write().unwrap(); parents - .entry(**index) - .and_modify(|e| e.push(parent.clone())) + .entry(index) + .and_modify(|e| e.push(parent)) .or_insert_with(|| vec![parent]); } - pub fn get_function( + pub fn get_function<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_function(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_function(span) } - pub fn get_trait( + pub fn get_trait<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_trait(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_trait(span) } - pub fn get_trait_fn(&self, index: DeclId, span: &Span) -> Result { - self.slab.get(*index).expect_trait_fn(span) + pub fn get_trait_fn<'a, T>( + &self, + index: &'a T, + span: &Span, + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_trait_fn(span) } - pub fn get_impl_trait( + pub fn get_impl_trait<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_impl_trait(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_impl_trait(span) } - pub fn get_struct( + pub fn get_struct<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_struct(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_struct(span) } - pub fn get_storage( + pub fn get_storage<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_storage(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_storage(span) } - pub fn get_abi( + pub fn get_abi<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_abi(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_abi(span) } - pub fn get_constant( + pub fn get_constant<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_constant(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_constant(span) } - pub fn get_enum( + pub fn get_enum<'a, T>( &self, - index: DeclId, + index: &'a T, span: &Span, - ) -> Result { - self.slab.get(*index).expect_enum(span) + ) -> Result + where + DeclId: From<&'a T>, + { + self.slab.get(*DeclId::from(index)).expect_enum(span) } } diff --git a/sway-core/src/decl_engine/id.rs b/sway-core/src/decl_engine/id.rs index 7e9ea197fde..13681975625 100644 --- a/sway-core/src/decl_engine/id.rs +++ b/sway-core/src/decl_engine/id.rs @@ -1,175 +1,71 @@ -use std::hash::Hasher; - -use sway_types::{Ident, Span, Spanned}; - -use crate::{engine_threading::*, language::ty, type_system::*}; - -use super::{DeclEngine, DeclMapping, ReplaceDecls, ReplaceFunctionImplementingType}; +use crate::{decl_engine::*, engine_threading::*, type_system::*}; /// An ID used to refer to an item in the [DeclEngine](super::decl_engine::DeclEngine) -#[derive(Debug)] -pub struct DeclId { - /// The name of the declaration. - // NOTE: In the case of storage, the name is "storage". - pub name: Ident, - - /// The low-level index into the [DeclEngine]. - id: usize, - - /// The [Span] of the entire declaration. - decl_span: Span, -} +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] +pub struct DeclId(usize); -impl Clone for DeclId { - fn clone(&self) -> DeclId { - DeclId { - name: self.name.clone(), - id: self.id, - decl_span: self.decl_span.clone(), - } +impl DeclId { + pub(crate) fn new(id: usize) -> DeclId { + DeclId(id) } -} -impl EqWithEngines for DeclId {} -impl PartialEqWithEngines for DeclId { - fn eq(&self, other: &Self, engines: Engines<'_>) -> bool { - let decl_engine = engines.de(); - let left = decl_engine.get(self.clone()); - let right = decl_engine.get(other.clone()); - left.eq(&right, engines) - } -} - -impl HashWithEngines for DeclId { - fn hash(&self, state: &mut H, engines: Engines<'_>) { - let decl_engine = engines.de(); - let decl = decl_engine.get(self.clone()); - decl.hash(state, engines); + pub(crate) fn replace_id(&mut self, index: DeclId) { + self.0 = index.0; } } impl std::ops::Deref for DeclId { type Target = usize; fn deref(&self) -> &Self::Target { - &self.id + &self.0 } } #[allow(clippy::from_over_into)] impl Into for DeclId { fn into(self) -> usize { - self.id + self.0 } } -impl Spanned for DeclId { - fn span(&self) -> Span { - self.decl_span.clone() +impl From<&DeclId> for DeclId { + fn from(value: &DeclId) -> Self { + DeclId::new(value.0) } } -impl SubstTypes for DeclId { - fn subst_inner(&mut self, type_mapping: &TypeSubstMap, engines: Engines<'_>) { - let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); - decl.subst(type_mapping, engines); - decl_engine.replace(self.clone(), decl); +impl From<&mut DeclId> for DeclId { + fn from(value: &mut DeclId) -> Self { + DeclId::new(value.0) } } -impl ReplaceSelfType for DeclId { - fn replace_self_type(&mut self, engines: Engines<'_>, self_type: TypeId) { - let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); - decl.replace_self_type(engines, self_type); - decl_engine.replace(self.clone(), decl); +impl From<&DeclRef> for DeclId { + fn from(value: &DeclRef) -> Self { + value.id } } -impl ReplaceDecls for DeclId { - fn replace_decls_inner(&mut self, decl_mapping: &DeclMapping, engines: Engines<'_>) { - let decl_engine = engines.de(); - if let Some(new_decl_id) = decl_mapping.find_match(self) { - self.id = *new_decl_id; - return; - } - let all_parents = decl_engine.find_all_parents(engines, self.clone()); - for parent in all_parents.into_iter() { - if let Some(new_decl_id) = decl_mapping.find_match(&parent) { - self.id = *new_decl_id; - return; - } - } - } -} - -impl ReplaceFunctionImplementingType for DeclId { - fn replace_implementing_type( - &mut self, - engines: Engines<'_>, - implementing_type: ty::TyDeclaration, - ) { - let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); - decl.replace_implementing_type(engines, implementing_type); - decl_engine.replace(self.clone(), decl); +impl From<&mut DeclRef> for DeclId { + fn from(value: &mut DeclRef) -> Self { + value.id } } -impl DeclId { - pub(crate) fn new(name: Ident, id: usize, decl_span: Span) -> DeclId { - DeclId { - name, - id, - decl_span, - } - } - - pub(crate) fn with_parent(self, decl_engine: &DeclEngine, parent: DeclId) -> DeclId { - decl_engine.register_parent(&self, parent); - self - } - - pub(crate) fn replace_id(&mut self, index: usize) { - self.id = index; - } - - pub(crate) fn subst_types_and_insert_new( - &self, - type_mapping: &TypeSubstMap, - engines: Engines<'_>, - ) -> DeclId { +impl SubstTypes for DeclId { + fn subst_inner(&mut self, type_mapping: &TypeSubstMap, engines: Engines<'_>) { let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); + let mut decl = decl_engine.get(self); decl.subst(type_mapping, engines); - decl_engine - .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) - .with_parent(decl_engine, self.clone()) + decl_engine.replace(self, decl); } +} - pub(crate) fn replace_self_type_and_insert_new( - &self, - engines: Engines<'_>, - self_type: TypeId, - ) -> DeclId { +impl ReplaceSelfType for DeclId { + fn replace_self_type(&mut self, engines: Engines<'_>, self_type: TypeId) { let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); + let mut decl = decl_engine.get(self); decl.replace_self_type(engines, self_type); - decl_engine - .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) - .with_parent(decl_engine, self.clone()) - } - - pub(crate) fn replace_decls_and_insert_new( - &self, - decl_mapping: &DeclMapping, - engines: Engines<'_>, - ) -> DeclId { - let decl_engine = engines.de(); - let mut decl = decl_engine.get(self.clone()); - decl.replace_decls(decl_mapping, engines); - decl_engine - .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) - .with_parent(decl_engine, self.clone()) + decl_engine.replace(self, decl); } } diff --git a/sway-core/src/decl_engine/mapping.rs b/sway-core/src/decl_engine/mapping.rs index e82ab4adc54..faffd240324 100644 --- a/sway-core/src/decl_engine/mapping.rs +++ b/sway-core/src/decl_engine/mapping.rs @@ -18,7 +18,9 @@ impl fmt::Display for DeclMapping { "DeclMapping {{ {} }}", self.mapping .iter() - .map(|(source_type, dest_type)| { format!("{} -> {}", **source_type, **dest_type) }) + .map(|(source_type, dest_type)| { + format!("{} -> {}", **source_type, **dest_type,) + }) .collect::>() .join(", ") ) @@ -44,23 +46,27 @@ impl DeclMapping { self.mapping.is_empty() } - pub(crate) fn from_stub_and_impld_decl_ids( - stub_decl_ids: MethodMap, - impld_decl_ids: MethodMap, + pub(crate) fn from_stub_and_impld_decl_refs( + stub_decl_refs: MethodMap, + impld_decl_refs: MethodMap, ) -> DeclMapping { let mut mapping = vec![]; - for (stub_decl_name, stub_decl_id) in stub_decl_ids.into_iter() { - if let Some(new_decl_id) = impld_decl_ids.get(&stub_decl_name) { - mapping.push((stub_decl_id, new_decl_id.clone())); + for (stub_decl_name, stub_decl_ref) in stub_decl_refs.into_iter() { + if let Some(new_decl_ref) = impld_decl_refs.get(&stub_decl_name) { + mapping.push(((&stub_decl_ref).into(), new_decl_ref.into())); } } DeclMapping { mapping } } - pub(crate) fn find_match(&self, decl_id: &SourceDecl) -> Option { - for (source_decl_id, dest_decl_id) in self.mapping.iter() { - if **source_decl_id == **decl_id { - return Some(dest_decl_id.clone()); + pub(crate) fn find_match<'a, T>(&self, decl_ref: &'a T) -> Option + where + SourceDecl: From<&'a T>, + { + let decl_ref = SourceDecl::from(decl_ref); + for (source_decl_ref, dest_decl_ref) in self.mapping.iter() { + if **source_decl_ref == *decl_ref { + return Some(*dest_decl_ref); } } None diff --git a/sway-core/src/decl_engine/mod.rs b/sway-core/src/decl_engine/mod.rs index aa670ec91e2..e7f881cd083 100644 --- a/sway-core/src/decl_engine/mod.rs +++ b/sway-core/src/decl_engine/mod.rs @@ -12,16 +12,18 @@ pub(crate) mod engine; pub(crate) mod id; pub(crate) mod mapping; -pub(crate) mod replace_decl_id; +pub(crate) mod r#ref; +pub(crate) mod replace_decls; pub(crate) mod wrapper; use std::collections::BTreeMap; pub use engine::*; -pub use id::*; +pub(crate) use id::*; pub(crate) use mapping::*; -pub(crate) use replace_decl_id::*; +pub use r#ref::*; +pub(crate) use replace_decls::*; use sway_types::Ident; pub(crate) use wrapper::*; -pub(crate) type MethodMap = BTreeMap; +pub(crate) type MethodMap = BTreeMap; diff --git a/sway-core/src/decl_engine/ref.rs b/sway-core/src/decl_engine/ref.rs new file mode 100644 index 00000000000..f48e9eee832 --- /dev/null +++ b/sway-core/src/decl_engine/ref.rs @@ -0,0 +1,153 @@ +use std::hash::Hasher; + +use sway_types::{Ident, Span, Spanned}; + +use crate::{decl_engine::*, engine_threading::*, language::ty, type_system::*}; + +/// A reference to the use of a declaration. A smart-wrapper around a [DeclId], +/// containing additional information about a declaration. +#[derive(Debug, Clone)] +pub struct DeclRef { + /// The name of the declaration. + // NOTE: In the case of storage, the name is "storage". + pub name: Ident, + + /// The index into the [DeclEngine]. + pub id: DeclId, + + /// The [Span] of the entire declaration. + pub decl_span: Span, +} + +impl DeclRef { + pub(crate) fn new(name: Ident, id: usize, decl_span: Span) -> DeclRef { + DeclRef { + name, + id: DeclId::new(id), + decl_span, + } + } + + pub(crate) fn with_parent<'a, T>(self, decl_engine: &DeclEngine, parent: &'a T) -> DeclRef + where + DeclId: From<&'a T>, + { + decl_engine.register_parent::(&self, parent); + self + } + + pub(crate) fn replace_id(&mut self, index: DeclId) { + self.id.replace_id(index); + } + + pub(crate) fn subst_types_and_insert_new( + &self, + type_mapping: &TypeSubstMap, + engines: Engines<'_>, + ) -> DeclRef { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(self); + decl.subst(type_mapping, engines); + decl_engine + .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) + .with_parent(decl_engine, self) + } + + pub(crate) fn replace_self_type_and_insert_new( + &self, + engines: Engines<'_>, + self_type: TypeId, + ) -> DeclRef { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(self); + decl.replace_self_type(engines, self_type); + decl_engine + .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) + .with_parent(decl_engine, self) + } + + pub(crate) fn replace_decls_and_insert_new( + &self, + decl_mapping: &DeclMapping, + engines: Engines<'_>, + ) -> DeclRef { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(&self.clone()); + decl.replace_decls(decl_mapping, engines); + decl_engine + .insert_wrapper(self.name.clone(), decl, self.decl_span.clone()) + .with_parent(decl_engine, self) + } +} + +impl EqWithEngines for DeclRef {} +impl PartialEqWithEngines for DeclRef { + fn eq(&self, other: &Self, engines: Engines<'_>) -> bool { + let decl_engine = engines.de(); + let left = decl_engine.get(self); + let right = decl_engine.get(other); + self.name == other.name && left.eq(&right, engines) + } +} + +impl HashWithEngines for DeclRef { + fn hash(&self, state: &mut H, engines: Engines<'_>) { + let decl_engine = engines.de(); + let decl = decl_engine.get(self); + decl.hash(state, engines); + } +} + +impl Spanned for DeclRef { + fn span(&self) -> Span { + self.decl_span.clone() + } +} + +impl SubstTypes for DeclRef { + fn subst_inner(&mut self, type_mapping: &TypeSubstMap, engines: Engines<'_>) { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(self); + decl.subst(type_mapping, engines); + decl_engine.replace(self, decl); + } +} + +impl ReplaceSelfType for DeclRef { + fn replace_self_type(&mut self, engines: Engines<'_>, self_type: TypeId) { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(self); + decl.replace_self_type(engines, self_type); + decl_engine.replace(self, decl); + } +} + +impl ReplaceDecls for DeclRef { + fn replace_decls_inner(&mut self, decl_mapping: &DeclMapping, engines: Engines<'_>) { + let decl_engine = engines.de(); + if let Some(new_decl_ref) = decl_mapping.find_match(self) { + self.id = new_decl_ref; + return; + } + let all_parents = decl_engine.find_all_parents(engines, self); + for parent in all_parents.iter() { + if let Some(new_decl_ref) = decl_mapping.find_match(parent) { + self.id = new_decl_ref; + return; + } + } + } +} + +impl ReplaceFunctionImplementingType for DeclRef { + fn replace_implementing_type( + &mut self, + engines: Engines<'_>, + implementing_type: ty::TyDeclaration, + ) { + let decl_engine = engines.de(); + let mut decl = decl_engine.get(self); + decl.replace_implementing_type(engines, implementing_type); + decl_engine.replace(self, decl); + } +} diff --git a/sway-core/src/decl_engine/replace_decl_id.rs b/sway-core/src/decl_engine/replace_decls.rs similarity index 100% rename from sway-core/src/decl_engine/replace_decl_id.rs rename to sway-core/src/decl_engine/replace_decls.rs diff --git a/sway-core/src/ir_generation/compile.rs b/sway-core/src/ir_generation/compile.rs index ba707bf19c0..d179bf8a1de 100644 --- a/sway-core/src/ir_generation/compile.rs +++ b/sway-core/src/ir_generation/compile.rs @@ -1,5 +1,5 @@ use crate::{ - decl_engine::DeclId, + decl_engine::{DeclId, DeclRef}, language::{ty, Visibility}, metadata::MetadataManager, semantic_analysis::namespace, @@ -28,7 +28,7 @@ pub(super) fn compile_script( declarations: &[ty::TyDeclaration], logged_types_map: &HashMap, messages_types_map: &HashMap, - test_fns: &[(ty::TyFunctionDeclaration, DeclId)], + test_fns: &[(ty::TyFunctionDeclaration, DeclRef)], ) -> Result { let module = Module::new(context, Kind::Script); let mut md_mgr = MetadataManager::default(); @@ -74,7 +74,7 @@ pub(super) fn compile_predicate( declarations: &[ty::TyDeclaration], logged_types: &HashMap, messages_types: &HashMap, - test_fns: &[(ty::TyFunctionDeclaration, DeclId)], + test_fns: &[(ty::TyFunctionDeclaration, DeclRef)], ) -> Result { let module = Module::new(context, Kind::Predicate); let mut md_mgr = MetadataManager::default(); @@ -119,7 +119,7 @@ pub(super) fn compile_contract( declarations: &[ty::TyDeclaration], logged_types_map: &HashMap, messages_types_map: &HashMap, - test_fns: &[(ty::TyFunctionDeclaration, DeclId)], + test_fns: &[(ty::TyFunctionDeclaration, DeclRef)], engines: Engines<'_>, ) -> Result { let module = Module::new(context, Kind::Contract); @@ -165,7 +165,7 @@ pub(super) fn compile_library( declarations: &[ty::TyDeclaration], logged_types_map: &HashMap, messages_types_map: &HashMap, - test_fns: &[(ty::TyFunctionDeclaration, DeclId)], + test_fns: &[(ty::TyFunctionDeclaration, DeclRef)], ) -> Result { let module = Module::new(context, Kind::Library); let mut md_mgr = MetadataManager::default(); @@ -243,8 +243,10 @@ fn compile_declarations( let (type_engine, decl_engine) = engines.unwrap(); for declaration in declarations { match declaration { - ty::TyDeclaration::ConstantDeclaration(ref decl_id) => { - let decl = decl_engine.get_constant(decl_id.clone(), &declaration.span())?; + ty::TyDeclaration::ConstantDeclaration { + decl_id, decl_span, .. + } => { + let decl = decl_engine.get_constant(decl_id, decl_span)?; compile_const_decl( &mut LookupEnv { type_engine, @@ -260,14 +262,14 @@ fn compile_declarations( )?; } - ty::TyDeclaration::FunctionDeclaration(_decl) => { + ty::TyDeclaration::FunctionDeclaration { .. } => { // We no longer compile functions other than `main()` until we can improve the name // resolution. Currently there isn't enough information in the AST to fully // distinguish similarly named functions and especially trait methods. // //compile_function(context, module, decl).map(|_| ())? } - ty::TyDeclaration::ImplTrait(_) => { + ty::TyDeclaration::ImplTrait { .. } => { // And for the same reason we don't need to compile impls at all. // // compile_impl( @@ -278,13 +280,13 @@ fn compile_declarations( //)?, } - ty::TyDeclaration::StructDeclaration(_) - | ty::TyDeclaration::EnumDeclaration(_) - | ty::TyDeclaration::TraitDeclaration(_) + ty::TyDeclaration::StructDeclaration { .. } + | ty::TyDeclaration::EnumDeclaration { .. } + | ty::TyDeclaration::TraitDeclaration { .. } | ty::TyDeclaration::VariableDeclaration(_) - | ty::TyDeclaration::AbiDeclaration(_) + | ty::TyDeclaration::AbiDeclaration { .. } | ty::TyDeclaration::GenericTypeForFunctionScope { .. } - | ty::TyDeclaration::StorageDeclaration(_) + | ty::TyDeclaration::StorageDeclaration { .. } | ty::TyDeclaration::ErrorRecovery(_) => (), } } @@ -301,7 +303,7 @@ pub(super) fn compile_function( logged_types_map: &HashMap, messages_types_map: &HashMap, is_entry: bool, - test_decl_id: Option, + test_decl_ref: Option, ) -> Result, CompileError> { let type_engine = engines.te(); // Currently monomorphization of generics is inlined into main() and the functions with generic @@ -326,7 +328,7 @@ pub(super) fn compile_function( None, logged_types_map, messages_types_map, - test_decl_id, + test_decl_ref, ) .map(Some) } @@ -341,7 +343,7 @@ pub(super) fn compile_entry_function( ast_fn_decl: &ty::TyFunctionDeclaration, logged_types_map: &HashMap, messages_types_map: &HashMap, - test_decl_id: Option, + test_decl_ref: Option, ) -> Result { let is_entry = true; compile_function( @@ -353,7 +355,7 @@ pub(super) fn compile_entry_function( logged_types_map, messages_types_map, is_entry, - test_decl_id, + test_decl_ref, ) .map(|f| f.expect("entry point should never contain generics")) } @@ -365,11 +367,11 @@ pub(super) fn compile_tests( module: Module, logged_types_map: &HashMap, messages_types_map: &HashMap, - test_fns: &[(ty::TyFunctionDeclaration, DeclId)], + test_fns: &[(ty::TyFunctionDeclaration, DeclRef)], ) -> Result, CompileError> { test_fns .iter() - .map(|(ast_fn_decl, decl_id)| { + .map(|(ast_fn_decl, decl_ref)| { compile_entry_function( engines, context, @@ -378,7 +380,7 @@ pub(super) fn compile_tests( ast_fn_decl, logged_types_map, messages_types_map, - Some(decl_id.clone()), + Some(decl_ref.clone()), ) }) .collect() @@ -414,7 +416,7 @@ fn compile_fn_with_args( selector: Option<[u8; 4]>, logged_types_map: &HashMap, messages_types_map: &HashMap, - test_decl_id: Option, + test_decl_ref: Option, ) -> Result { let type_engine = engines.te(); @@ -456,7 +458,7 @@ fn compile_fn_with_args( let storage_md_idx = md_mgr.purity_to_md(context, *purity); let mut metadata = md_combine(context, &span_md_idx, &storage_md_idx); - let decl_index = test_decl_id.map(|decl_id| *decl_id); + let decl_index = test_decl_ref.map(|decl_ref| *DeclId::from(&decl_ref)); if let Some(decl_index) = decl_index { let test_decl_index_md_idx = md_mgr.test_decl_index_to_md(context, decl_index); metadata = md_combine(context, &metadata, &test_decl_index_md_idx); diff --git a/sway-core/src/ir_generation/const_eval.rs b/sway-core/src/ir_generation/const_eval.rs index 9b1d24a5788..8707835900e 100644 --- a/sway-core/src/ir_generation/const_eval.rs +++ b/sway-core/src/ir_generation/const_eval.rs @@ -91,15 +91,13 @@ pub(crate) fn compile_const_decl( // See if we it's a global const and whether we can compile it *now*. let decl = module_ns.check_symbol(name)?; let decl_name_value = match decl { - ty::TyDeclaration::ConstantDeclaration(decl_id) => { + ty::TyDeclaration::ConstantDeclaration { decl_id, .. } => { let ty::TyConstantDeclaration { name, value, is_configurable, .. - } = env - .decl_engine - .get_constant(decl_id.clone(), &name.span())?; + } = env.decl_engine.get_constant(decl_id, &name.span())?; Some((name, value, is_configurable)) } _otherwise => None, @@ -221,7 +219,7 @@ fn const_eval_typed_expr( ty::TyExpressionVariant::Literal(l) => Some(convert_literal_to_constant(lookup.context, l)), ty::TyExpressionVariant::FunctionApplication { arguments, - function_decl_id, + function_decl_ref, .. } => { let mut actuals_const: Vec<_> = vec![]; @@ -245,7 +243,7 @@ fn const_eval_typed_expr( // TODO: Handle more than one statement in the block. let function_decl = lookup .decl_engine - .get_function(function_decl_id.clone(), &expr.span)?; + .get_function(function_decl_ref, &expr.span)?; if function_decl.body.contents.len() > 1 { return Ok(None); } diff --git a/sway-core/src/ir_generation/function.rs b/sway-core/src/ir_generation/function.rs index e1e2967e3bc..69b42c76f28 100644 --- a/sway-core/src/ir_generation/function.rs +++ b/sway-core/src/ir_generation/function.rs @@ -139,37 +139,35 @@ impl<'eng> FnCompiler<'eng> { ty::TyDeclaration::VariableDeclaration(tvd) => { self.compile_var_decl(context, md_mgr, tvd, span_md_idx) } - ty::TyDeclaration::ConstantDeclaration(decl_id) => { - let tcd = self - .decl_engine - .get_constant(decl_id.clone(), &ast_node.span)?; + ty::TyDeclaration::ConstantDeclaration { decl_id, .. } => { + let tcd = self.decl_engine.get_constant(decl_id, &ast_node.span)?; self.compile_const_decl(context, md_mgr, tcd, span_md_idx)?; Ok(None) } - ty::TyDeclaration::FunctionDeclaration(_) => { + ty::TyDeclaration::FunctionDeclaration { .. } => { Err(CompileError::UnexpectedDeclaration { decl_type: "function", span: ast_node.span.clone(), }) } - ty::TyDeclaration::TraitDeclaration(_) => { + ty::TyDeclaration::TraitDeclaration { .. } => { Err(CompileError::UnexpectedDeclaration { decl_type: "trait", span: ast_node.span.clone(), }) } - ty::TyDeclaration::StructDeclaration(_) => { + ty::TyDeclaration::StructDeclaration { .. } => { Err(CompileError::UnexpectedDeclaration { decl_type: "struct", span: ast_node.span.clone(), }) } - ty::TyDeclaration::EnumDeclaration(decl_id) => { - let ted = self.decl_engine.get_enum(decl_id.clone(), &ast_node.span)?; + ty::TyDeclaration::EnumDeclaration { decl_id, .. } => { + let ted = self.decl_engine.get_enum(decl_id, &ast_node.span)?; create_enum_aggregate(self.type_engine, context, &ted.variants).map(|_| ())?; Ok(None) } - ty::TyDeclaration::ImplTrait(_) => { + ty::TyDeclaration::ImplTrait { .. } => { // XXX What if we ignore the trait implementation??? Potentially since // we currently inline everything and below we 'recreate' the functions // lazily as they are called, nothing needs to be done here. BUT! @@ -177,10 +175,12 @@ impl<'eng> FnCompiler<'eng> { // compile and then call these properly. Ok(None) } - ty::TyDeclaration::AbiDeclaration(_) => Err(CompileError::UnexpectedDeclaration { - decl_type: "abi", - span: ast_node.span.clone(), - }), + ty::TyDeclaration::AbiDeclaration { .. } => { + Err(CompileError::UnexpectedDeclaration { + decl_type: "abi", + span: ast_node.span.clone(), + }) + } ty::TyDeclaration::GenericTypeForFunctionScope { .. } => { Err(CompileError::UnexpectedDeclaration { decl_type: "abi", @@ -193,7 +193,7 @@ impl<'eng> FnCompiler<'eng> { span: ast_node.span.clone(), }) } - ty::TyDeclaration::StorageDeclaration(_) => { + ty::TyDeclaration::StorageDeclaration { .. } => { Err(CompileError::UnexpectedDeclaration { decl_type: "storage", span: ast_node.span.clone(), @@ -233,7 +233,7 @@ impl<'eng> FnCompiler<'eng> { call_path: name, contract_call_params, arguments, - function_decl_id, + function_decl_ref, self_state_idx, selector, type_binding: _, @@ -252,7 +252,7 @@ impl<'eng> FnCompiler<'eng> { } else { let function_decl = self .decl_engine - .get_function(function_decl_id.clone(), &ast_expr.span)?; + .get_function(function_decl_ref, &ast_expr.span)?; self.compile_fn_call( context, md_mgr, diff --git a/sway-core/src/language/parsed/declaration/trait.rs b/sway-core/src/language/parsed/declaration/trait.rs index f3261695abd..601fabf1332 100644 --- a/sway-core/src/language/parsed/declaration/trait.rs +++ b/sway-core/src/language/parsed/declaration/trait.rs @@ -2,7 +2,7 @@ use std::hash::{Hash, Hasher}; use super::{FunctionDeclaration, FunctionParameter}; -use crate::{decl_engine::DeclId, engine_threading::*, language::*, transform, type_system::*}; +use crate::{decl_engine::DeclRef, engine_threading::*, language::*, transform, type_system::*}; use sway_types::{ident::Ident, span::Span, Spanned}; #[derive(Debug, Clone)] @@ -20,7 +20,7 @@ pub struct TraitDeclaration { #[derive(Debug, Clone)] pub struct Supertrait { pub name: CallPath, - pub decl_id: Option, + pub decl_ref: Option, } impl Spanned for Supertrait { @@ -32,15 +32,15 @@ impl Spanned for Supertrait { impl EqWithEngines for Supertrait {} impl PartialEqWithEngines for Supertrait { fn eq(&self, other: &Self, engines: Engines<'_>) -> bool { - self.name == other.name && self.decl_id.eq(&other.decl_id, engines) + self.name == other.name && self.decl_ref.eq(&other.decl_ref, engines) } } impl HashWithEngines for Supertrait { fn hash(&self, state: &mut H, engines: Engines<'_>) { - let Supertrait { name, decl_id } = self; + let Supertrait { name, decl_ref } = self; name.hash(state); - decl_id.hash(state, engines); + decl_ref.hash(state, engines); } } diff --git a/sway-core/src/language/ty/ast_node.rs b/sway-core/src/language/ty/ast_node.rs index 80e60c47031..96259625243 100644 --- a/sway-core/src/language/ty/ast_node.rs +++ b/sway-core/src/language/ty/ast_node.rs @@ -4,7 +4,7 @@ use std::{ }; use sway_error::error::CompileError; -use sway_types::{Ident, Span, Spanned}; +use sway_types::{Ident, Span}; use crate::{ decl_engine::*, @@ -20,8 +20,8 @@ pub trait GetDeclIdent { fn get_decl_ident(&self) -> Option; } -pub trait GetDeclId { - fn get_decl_id(&self) -> Option; +pub trait GetDeclRef { + fn get_decl_ref(&self) -> Option; } #[derive(Clone, Debug)] @@ -177,13 +177,16 @@ impl TyAstNode { match &self { TyAstNode { span, - content: TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(decl_id)), + content: + TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + decl_id, .. + }), .. } => { let TyFunctionDeclaration { type_parameters, .. } = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), span)), + CompileResult::from(decl_engine.get_function(decl_id, span)), return err(warnings, errors), warnings, errors @@ -201,11 +204,14 @@ impl TyAstNode { match &self { TyAstNode { span, - content: TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(decl_id)), + content: + TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + decl_id, .. + }), .. } => { let TyFunctionDeclaration { attributes, .. } = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), span)), + CompileResult::from(decl_engine.get_function(decl_id, span)), return err(warnings, errors), warnings, errors @@ -232,10 +238,13 @@ impl TyAstNode { TyAstNode { span, content: - TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(decl_id)), + TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + decl_id, + .. + }), .. } => { - let decl = decl_engine.get_function(decl_id.clone(), span)?; + let decl = decl_engine.get_function(decl_id, span)?; Ok(decl.is_entry()) } _ => Ok(false), @@ -244,25 +253,38 @@ impl TyAstNode { TreeType::Contract | TreeType::Library { .. } => match self { TyAstNode { content: - TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(decl_id)), + TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + decl_id, + decl_span, + .. + }), .. } => { - let decl = decl_engine.get_function(decl_id.clone(), &decl_id.span())?; + let decl = decl_engine.get_function(decl_id, decl_span)?; Ok(decl.visibility == Visibility::Public || decl.is_test()) } TyAstNode { - content: TyAstNodeContent::Declaration(TyDeclaration::TraitDeclaration(decl_id)), + content: + TyAstNodeContent::Declaration(TyDeclaration::TraitDeclaration { + decl_id, + decl_span, + .. + }), .. } => Ok(decl_engine - .get_trait(decl_id.clone(), &decl_id.span())? + .get_trait(decl_id, decl_span)? .visibility .is_public()), TyAstNode { content: - TyAstNodeContent::Declaration(TyDeclaration::StructDeclaration(decl_id)), + TyAstNodeContent::Declaration(TyDeclaration::StructDeclaration { + decl_id, + decl_span, + .. + }), .. } => { - let struct_decl = decl_engine.get_struct(decl_id.clone(), &decl_id.span())?; + let struct_decl = decl_engine.get_struct(decl_id, decl_span)?; Ok(struct_decl.visibility == Visibility::Public) } TyAstNode { @@ -271,10 +293,14 @@ impl TyAstNode { } => Ok(true), TyAstNode { content: - TyAstNodeContent::Declaration(TyDeclaration::ConstantDeclaration(decl_id)), + TyAstNodeContent::Declaration(TyDeclaration::ConstantDeclaration { + decl_id, + decl_span, + .. + }), .. } => { - let decl = decl_engine.get_constant(decl_id.clone(), &decl_id.span())?; + let decl = decl_engine.get_constant(decl_id, decl_span)?; Ok(decl.visibility.is_public()) } _ => Ok(false), diff --git a/sway-core/src/language/ty/declaration/abi.rs b/sway-core/src/language/ty/declaration/abi.rs index a634e47e7b2..ef19a4dde06 100644 --- a/sway-core/src/language/ty/declaration/abi.rs +++ b/sway-core/src/language/ty/declaration/abi.rs @@ -2,7 +2,7 @@ use std::hash::{Hash, Hasher}; use sway_types::{Ident, Span}; -use crate::{decl_engine::DeclId, engine_threading::*, transform, type_system::*}; +use crate::{decl_engine::DeclRef, engine_threading::*, transform, type_system::*}; /// A [TyAbiDeclaration] contains the type-checked version of the parse tree's `AbiDeclaration`. #[derive(Clone, Debug)] @@ -10,8 +10,8 @@ pub struct TyAbiDeclaration { /// The name of the abi trait (also known as a "contract trait") pub name: Ident, /// The methods a contract is required to implement in order opt in to this interface - pub interface_surface: Vec, - pub methods: Vec, + pub interface_surface: Vec, + pub methods: Vec, pub span: Span, pub attributes: transform::AttributesMap, } diff --git a/sway-core/src/language/ty/declaration/declaration.rs b/sway-core/src/language/ty/declaration/declaration.rs index cdcf706c540..2935a653908 100644 --- a/sway-core/src/language/ty/declaration/declaration.rs +++ b/sway-core/src/language/ty/declaration/declaration.rs @@ -17,34 +17,149 @@ use crate::{ #[derive(Clone, Debug)] pub enum TyDeclaration { VariableDeclaration(Box), - ConstantDeclaration(DeclId), - FunctionDeclaration(DeclId), - TraitDeclaration(DeclId), - StructDeclaration(DeclId), - EnumDeclaration(DeclId), - ImplTrait(DeclId), - AbiDeclaration(DeclId), + ConstantDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + FunctionDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + TraitDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + StructDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + EnumDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + ImplTrait { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, + AbiDeclaration { + name: Ident, + decl_id: DeclId, + decl_span: Span, + }, // If type parameters are defined for a function, they are put in the namespace just for // the body of that function. - GenericTypeForFunctionScope { name: Ident, type_id: TypeId }, + GenericTypeForFunctionScope { + name: Ident, + type_id: TypeId, + }, ErrorRecovery(Span), - StorageDeclaration(DeclId), + StorageDeclaration { + decl_id: DeclId, + decl_span: Span, + }, } impl EqWithEngines for TyDeclaration {} impl PartialEqWithEngines for TyDeclaration { fn eq(&self, other: &Self, engines: Engines<'_>) -> bool { + let decl_engine = engines.de(); let type_engine = engines.te(); match (self, other) { (Self::VariableDeclaration(x), Self::VariableDeclaration(y)) => x.eq(y, engines), - (Self::ConstantDeclaration(x), Self::ConstantDeclaration(y)) => x.eq(y, engines), - (Self::FunctionDeclaration(x), Self::FunctionDeclaration(y)) => x.eq(y, engines), - (Self::TraitDeclaration(x), Self::TraitDeclaration(y)) => x.eq(y, engines), - (Self::StructDeclaration(x), Self::StructDeclaration(y)) => x.eq(y, engines), - (Self::EnumDeclaration(x), Self::EnumDeclaration(y)) => x.eq(y, engines), - (Self::ImplTrait(x), Self::ImplTrait(y)) => x.eq(y, engines), - (Self::AbiDeclaration(x), Self::AbiDeclaration(y)) => x.eq(y, engines), - (Self::StorageDeclaration(x), Self::StorageDeclaration(y)) => x.eq(y, engines), + ( + Self::ConstantDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::ConstantDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::FunctionDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::FunctionDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::TraitDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::TraitDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::StructDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::StructDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::EnumDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::EnumDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::ImplTrait { + name: ln, + decl_id: lid, + .. + }, + Self::ImplTrait { + name: rn, + decl_id: rid, + .. + }, + ) + | ( + Self::AbiDeclaration { + name: ln, + decl_id: lid, + .. + }, + Self::AbiDeclaration { + name: rn, + decl_id: rid, + .. + }, + ) => ln == rn && decl_engine.get(lid).eq(&decl_engine.get(rid), engines), + ( + Self::StorageDeclaration { decl_id: lid, .. }, + Self::StorageDeclaration { decl_id: rid, .. }, + ) => decl_engine.get(lid).eq(&decl_engine.get(rid), engines), ( Self::GenericTypeForFunctionScope { name: xn, @@ -64,21 +179,22 @@ impl PartialEqWithEngines for TyDeclaration { impl HashWithEngines for TyDeclaration { fn hash(&self, state: &mut H, engines: Engines<'_>) { use TyDeclaration::*; + let decl_engine = engines.de(); let type_engine = engines.te(); std::mem::discriminant(self).hash(state); match self { VariableDeclaration(decl) => { decl.hash(state, engines); } - ConstantDeclaration(decl_id) - | FunctionDeclaration(decl_id) - | TraitDeclaration(decl_id) - | StructDeclaration(decl_id) - | EnumDeclaration(decl_id) - | ImplTrait(decl_id) - | AbiDeclaration(decl_id) - | StorageDeclaration(decl_id) => { - decl_id.hash(state, engines); + ConstantDeclaration { decl_id, .. } + | FunctionDeclaration { decl_id, .. } + | TraitDeclaration { decl_id, .. } + | StructDeclaration { decl_id, .. } + | EnumDeclaration { decl_id, .. } + | ImplTrait { decl_id, .. } + | AbiDeclaration { decl_id, .. } + | StorageDeclaration { decl_id, .. } => { + decl_engine.get(decl_id).hash(state, engines); } GenericTypeForFunctionScope { name, type_id } => { name.hash(state); @@ -94,15 +210,25 @@ impl SubstTypes for TyDeclaration { use TyDeclaration::*; match self { VariableDeclaration(ref mut var_decl) => var_decl.subst(type_mapping, engines), - FunctionDeclaration(ref mut decl_id) => decl_id.subst(type_mapping, engines), - TraitDeclaration(ref mut decl_id) => decl_id.subst(type_mapping, engines), - StructDeclaration(ref mut decl_id) => decl_id.subst(type_mapping, engines), - EnumDeclaration(ref mut decl_id) => decl_id.subst(type_mapping, engines), - ImplTrait(decl_id) => decl_id.subst(type_mapping, engines), + FunctionDeclaration { + ref mut decl_id, .. + } + | TraitDeclaration { + ref mut decl_id, .. + } + | StructDeclaration { + ref mut decl_id, .. + } + | EnumDeclaration { + ref mut decl_id, .. + } + | ImplTrait { + ref mut decl_id, .. + } => decl_id.subst(type_mapping, engines), // generics in an ABI is unsupported by design - AbiDeclaration(..) - | ConstantDeclaration(_) - | StorageDeclaration(..) + AbiDeclaration { .. } + | ConstantDeclaration { .. } + | StorageDeclaration { .. } | GenericTypeForFunctionScope { .. } | ErrorRecovery(_) => (), } @@ -114,15 +240,25 @@ impl ReplaceSelfType for TyDeclaration { use TyDeclaration::*; match self { VariableDeclaration(ref mut var_decl) => var_decl.replace_self_type(engines, self_type), - FunctionDeclaration(ref mut decl_id) => decl_id.replace_self_type(engines, self_type), - TraitDeclaration(ref mut decl_id) => decl_id.replace_self_type(engines, self_type), - StructDeclaration(ref mut decl_id) => decl_id.replace_self_type(engines, self_type), - EnumDeclaration(ref mut decl_id) => decl_id.replace_self_type(engines, self_type), - ImplTrait(decl_id) => decl_id.replace_self_type(engines, self_type), + FunctionDeclaration { + ref mut decl_id, .. + } + | TraitDeclaration { + ref mut decl_id, .. + } + | StructDeclaration { + ref mut decl_id, .. + } + | EnumDeclaration { + ref mut decl_id, .. + } + | ImplTrait { + ref mut decl_id, .. + } => decl_id.replace_self_type(engines, self_type), // generics in an ABI is unsupported by design - AbiDeclaration(..) - | ConstantDeclaration(_) - | StorageDeclaration(..) + AbiDeclaration { .. } + | ConstantDeclaration { .. } + | StorageDeclaration { .. } | GenericTypeForFunctionScope { .. } | ErrorRecovery(_) => (), } @@ -134,14 +270,14 @@ impl Spanned for TyDeclaration { use TyDeclaration::*; match self { VariableDeclaration(decl) => decl.name.span(), - ConstantDeclaration(decl_id) => decl_id.span(), - FunctionDeclaration(decl_id) => decl_id.span(), - TraitDeclaration(decl_id) => decl_id.span(), - StructDeclaration(decl_id) => decl_id.span(), - EnumDeclaration(decl_id) => decl_id.span(), - AbiDeclaration(decl_id) => decl_id.span(), - ImplTrait(decl_id) => decl_id.span(), - StorageDeclaration(decl) => decl.span(), + FunctionDeclaration { decl_span, .. } + | TraitDeclaration { decl_span, .. } + | StructDeclaration { decl_span, .. } + | EnumDeclaration { decl_span, .. } + | ImplTrait { decl_span, .. } + | ConstantDeclaration { decl_span, .. } + | StorageDeclaration { decl_span, .. } + | AbiDeclaration { decl_span, .. } => decl_span.clone(), GenericTypeForFunctionScope { name, .. } => name.span(), ErrorRecovery(span) => span.clone(), } @@ -181,10 +317,10 @@ impl DisplayWithEngines for TyDeclaration { builder.push_str(&engines.help_out(body).to_string()); builder } - TyDeclaration::FunctionDeclaration(decl_id) => decl_id.name.as_str().into(), - TyDeclaration::TraitDeclaration(decl_id) => decl_id.name.as_str().into(), - TyDeclaration::StructDeclaration(decl_id) => decl_id.name.as_str().into(), - TyDeclaration::EnumDeclaration(decl_id) => decl_id.name.as_str().into(), + TyDeclaration::FunctionDeclaration { name, .. } + | TyDeclaration::TraitDeclaration { name, .. } + | TyDeclaration::StructDeclaration { name, .. } + | TyDeclaration::EnumDeclaration { name, .. } => name.as_str().into(), _ => String::new(), } ) @@ -217,45 +353,45 @@ impl CollectTypesMetadata for TyDeclaration { )); body } - FunctionDeclaration(decl_id) => { - match decl_engine.get_function(decl_id.clone(), &decl_id.span()) { - Ok(decl) => { - check!( - decl.collect_types_metadata(ctx), - return err(warnings, errors), - warnings, - errors - ) - } - Err(e) => { - errors.push(e); - return err(warnings, errors); - } + FunctionDeclaration { + decl_id, decl_span, .. + } => match decl_engine.get_function(decl_id, decl_span) { + Ok(decl) => { + check!( + decl.collect_types_metadata(ctx), + return err(warnings, errors), + warnings, + errors + ) } - } - ConstantDeclaration(decl_id) => { - match decl_engine.get_constant(decl_id.clone(), &decl_id.span()) { - Ok(TyConstantDeclaration { value, .. }) => { - check!( - value.collect_types_metadata(ctx), - return err(warnings, errors), - warnings, - errors - ) - } - Err(e) => { - errors.push(e); - return err(warnings, errors); - } + Err(e) => { + errors.push(e); + return err(warnings, errors); } - } + }, + ConstantDeclaration { + decl_id, decl_span, .. + } => match decl_engine.get_constant(decl_id, decl_span) { + Ok(TyConstantDeclaration { value, .. }) => { + check!( + value.collect_types_metadata(ctx), + return err(warnings, errors), + warnings, + errors + ) + } + Err(e) => { + errors.push(e); + return err(warnings, errors); + } + }, ErrorRecovery(_) - | StorageDeclaration(_) - | TraitDeclaration(_) - | StructDeclaration(_) - | EnumDeclaration(_) + | StorageDeclaration { .. } + | TraitDeclaration { .. } + | StructDeclaration { .. } + | EnumDeclaration { .. } | ImplTrait { .. } - | AbiDeclaration(_) + | AbiDeclaration { .. } | GenericTypeForFunctionScope { .. } => vec![], }; if errors.is_empty() { @@ -270,34 +406,62 @@ impl GetDeclIdent for TyDeclaration { fn get_decl_ident(&self) -> Option { match self { TyDeclaration::VariableDeclaration(decl) => Some(decl.name.clone()), - TyDeclaration::ConstantDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::FunctionDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::TraitDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::StructDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::EnumDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::ImplTrait(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::AbiDeclaration(decl_id) => Some(decl_id.name.clone()), - TyDeclaration::GenericTypeForFunctionScope { name, .. } => Some(name.clone()), + TyDeclaration::FunctionDeclaration { name, .. } + | TyDeclaration::TraitDeclaration { name, .. } + | TyDeclaration::StructDeclaration { name, .. } + | TyDeclaration::EnumDeclaration { name, .. } + | TyDeclaration::ConstantDeclaration { name, .. } + | TyDeclaration::ImplTrait { name, .. } + | TyDeclaration::AbiDeclaration { name, .. } + | TyDeclaration::GenericTypeForFunctionScope { name, .. } => Some(name.clone()), TyDeclaration::ErrorRecovery(_) => None, - TyDeclaration::StorageDeclaration(_decl) => None, + TyDeclaration::StorageDeclaration { .. } => None, } } } -impl GetDeclId for TyDeclaration { - fn get_decl_id(&self) -> Option { +impl GetDeclRef for TyDeclaration { + fn get_decl_ref(&self) -> Option { match self { TyDeclaration::VariableDeclaration(_) => todo!("not a declaration id yet"), - TyDeclaration::ConstantDeclaration(decl) => Some(decl.clone()), - TyDeclaration::FunctionDeclaration(decl) => Some(decl.clone()), - TyDeclaration::TraitDeclaration(decl) => Some(decl.clone()), - TyDeclaration::StructDeclaration(decl) => Some(decl.clone()), - TyDeclaration::EnumDeclaration(decl) => Some(decl.clone()), - TyDeclaration::ImplTrait(decl) => Some(decl.clone()), - TyDeclaration::AbiDeclaration(decl) => Some(decl.clone()), + TyDeclaration::FunctionDeclaration { + name, + decl_id, + decl_span, + } + | TyDeclaration::ConstantDeclaration { + name, + decl_id, + decl_span, + } + | TyDeclaration::TraitDeclaration { + name, + decl_id, + decl_span, + } + | TyDeclaration::StructDeclaration { + name, + decl_id, + decl_span, + } + | TyDeclaration::EnumDeclaration { + name, + decl_id, + decl_span, + } + | TyDeclaration::ImplTrait { + name, + decl_id, + decl_span, + } + | TyDeclaration::AbiDeclaration { + name, + decl_id, + decl_span, + } => Some(DeclRef::new(name.clone(), **decl_id, decl_span.clone())), TyDeclaration::GenericTypeForFunctionScope { .. } => None, TyDeclaration::ErrorRecovery(_) => None, - TyDeclaration::StorageDeclaration(_decl) => None, + TyDeclaration::StorageDeclaration { .. } => None, } } } @@ -312,8 +476,8 @@ impl TyDeclaration { access_span: &Span, ) -> CompileResult { match self { - TyDeclaration::EnumDeclaration(decl_id) => { - CompileResult::from(decl_engine.get_enum(decl_id.clone(), access_span)) + TyDeclaration::EnumDeclaration { decl_id, .. } => { + CompileResult::from(decl_engine.get_enum(decl_id, access_span)) } TyDeclaration::ErrorRecovery(_) => err(vec![], vec![]), decl => err( @@ -337,9 +501,9 @@ impl TyDeclaration { let mut warnings = vec![]; let mut errors = vec![]; match self { - TyDeclaration::StructDeclaration(decl_id) => { + TyDeclaration::StructDeclaration { decl_id, .. } => { let decl = check!( - CompileResult::from(decl_engine.get_struct(decl_id.clone(), access_span)), + CompileResult::from(decl_engine.get_struct(decl_id, access_span)), return err(warnings, errors), warnings, errors @@ -368,9 +532,9 @@ impl TyDeclaration { let mut warnings = vec![]; let mut errors = vec![]; match self { - TyDeclaration::FunctionDeclaration(decl_id) => { + TyDeclaration::FunctionDeclaration { decl_id, .. } => { let decl = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), access_span)), + CompileResult::from(decl_engine.get_function(decl_id, access_span)), return err(warnings, errors), warnings, errors, @@ -416,8 +580,8 @@ impl TyDeclaration { access_span: &Span, ) -> CompileResult { match self { - TyDeclaration::AbiDeclaration(decl_id) => { - CompileResult::from(decl_engine.get_abi(decl_id.clone(), access_span)) + TyDeclaration::AbiDeclaration { decl_id, .. } => { + CompileResult::from(decl_engine.get_abi(decl_id, access_span)) } TyDeclaration::ErrorRecovery(_) => err(vec![], vec![]), decl => err( @@ -439,8 +603,8 @@ impl TyDeclaration { access_span: &Span, ) -> CompileResult { match self { - TyDeclaration::ConstantDeclaration(decl) => { - CompileResult::from(decl_engine.get_constant(decl.clone(), access_span)) + TyDeclaration::ConstantDeclaration { decl_id, .. } => { + CompileResult::from(decl_engine.get_constant(decl_id, access_span)) } TyDeclaration::ErrorRecovery(_) => err(vec![], vec![]), decl => { @@ -462,10 +626,8 @@ impl TyDeclaration { let decl_engine = engines.de(); let type_engine = engines.te(); match self { - ImplTrait(decl_id) => { - let decl = decl_engine - .get_impl_trait(decl_id.clone(), &Span::dummy()) - .unwrap(); + ImplTrait { decl_id, .. } => { + let decl = decl_engine.get_impl_trait(decl_id, &Span::dummy()).unwrap(); let implementing_for_type_id = type_engine.get(decl.implementing_for_type_id); format!( "{} for {}", @@ -486,16 +648,16 @@ impl TyDeclaration { use TyDeclaration::*; match self { VariableDeclaration(_) => "variable", - ConstantDeclaration(_) => "constant", - FunctionDeclaration(_) => "function", - TraitDeclaration(_) => "trait", - StructDeclaration(_) => "struct", - EnumDeclaration(_) => "enum", + ConstantDeclaration { .. } => "constant", + FunctionDeclaration { .. } => "function", + TraitDeclaration { .. } => "trait", + StructDeclaration { .. } => "struct", + EnumDeclaration { .. } => "enum", ImplTrait { .. } => "impl trait", - AbiDeclaration(..) => "abi", + AbiDeclaration { .. } => "abi", GenericTypeForFunctionScope { .. } => "generic type parameter", ErrorRecovery(_) => "error", - StorageDeclaration(_) => "contract storage declaration", + StorageDeclaration { .. } => "contract storage declaration", } } @@ -503,14 +665,14 @@ impl TyDeclaration { pub fn doc_name(&self) -> &'static str { use TyDeclaration::*; match self { - StructDeclaration(_) => "struct", - EnumDeclaration(_) => "enum", - TraitDeclaration(_) => "trait", - AbiDeclaration(_) => "abi", - StorageDeclaration(_) => "contract_storage", - ImplTrait(_) => "impl_trait", - FunctionDeclaration(_) => "fn", - ConstantDeclaration(_) => "constant", + StructDeclaration { .. } => "struct", + EnumDeclaration { .. } => "enum", + TraitDeclaration { .. } => "trait", + AbiDeclaration { .. } => "abi", + StorageDeclaration { .. } => "contract_storage", + ImplTrait { .. } => "impl_trait", + FunctionDeclaration { .. } => "fn", + ConstantDeclaration { .. } => "constant", _ => unreachable!("these items are non-documentable"), } } @@ -526,36 +688,36 @@ impl TyDeclaration { let decl_engine = engines.de(); let type_id = match self { TyDeclaration::VariableDeclaration(decl) => decl.body.return_type, - TyDeclaration::FunctionDeclaration(decl_id) => { + TyDeclaration::FunctionDeclaration { decl_id, .. } => { let decl = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &self.span())), + CompileResult::from(decl_engine.get_function(decl_id, &self.span())), return err(warnings, errors), warnings, errors ); decl.return_type.type_id } - TyDeclaration::StructDeclaration(decl_id) => { + TyDeclaration::StructDeclaration { decl_id, .. } => { let decl = check!( - CompileResult::from(decl_engine.get_struct(decl_id.clone(), &self.span())), + CompileResult::from(decl_engine.get_struct(decl_id, &self.span())), return err(warnings, errors), warnings, errors ); decl.create_type_id(engines) } - TyDeclaration::EnumDeclaration(decl_id) => { + TyDeclaration::EnumDeclaration { decl_id, .. } => { let decl = check!( - CompileResult::from(decl_engine.get_enum(decl_id.clone(), access_span)), + CompileResult::from(decl_engine.get_enum(decl_id, access_span)), return err(warnings, errors), warnings, errors ); decl.create_type_id(engines) } - TyDeclaration::StorageDeclaration(decl_id) => { + TyDeclaration::StorageDeclaration { decl_id, .. } => { let storage_decl = check!( - CompileResult::from(decl_engine.get_storage(decl_id.clone(), &self.span())), + CompileResult::from(decl_engine.get_storage(decl_id, &self.span())), return err(warnings, errors), warnings, errors @@ -585,45 +747,55 @@ impl TyDeclaration { let mut warnings = vec![]; let mut errors = vec![]; let visibility = match self { - TraitDeclaration(decl_id) => { + TraitDeclaration { + decl_id, decl_span, .. + } => { let TyTraitDeclaration { visibility, .. } = check!( - CompileResult::from(decl_engine.get_trait(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_trait(decl_id, decl_span)), return err(warnings, errors), warnings, errors ); visibility } - ConstantDeclaration(decl_id) => { + ConstantDeclaration { + decl_id, decl_span, .. + } => { let TyConstantDeclaration { visibility, .. } = check!( - CompileResult::from(decl_engine.get_constant(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_constant(decl_id, decl_span)), return err(warnings, errors), warnings, errors ); visibility } - StructDeclaration(decl_id) => { + StructDeclaration { + decl_id, decl_span, .. + } => { let TyStructDeclaration { visibility, .. } = check!( - CompileResult::from(decl_engine.get_struct(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_struct(decl_id, decl_span)), return err(warnings, errors), warnings, errors ); visibility } - EnumDeclaration(decl_id) => { + EnumDeclaration { + decl_id, decl_span, .. + } => { let TyEnumDeclaration { visibility, .. } = check!( - CompileResult::from(decl_engine.get_enum(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_enum(decl_id, decl_span)), return err(warnings, errors), warnings, errors ); visibility } - FunctionDeclaration(decl_id) => { + FunctionDeclaration { + decl_id, decl_span, .. + } => { let TyFunctionDeclaration { visibility, .. } = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_function(decl_id, decl_span)), return err(warnings, errors), warnings, errors @@ -633,7 +805,7 @@ impl TyDeclaration { GenericTypeForFunctionScope { .. } | ImplTrait { .. } | StorageDeclaration { .. } - | AbiDeclaration(..) + | AbiDeclaration { .. } | ErrorRecovery(_) => Visibility::Public, VariableDeclaration(decl) => decl.mutability.visibility(), }; diff --git a/sway-core/src/language/ty/declaration/impl_trait.rs b/sway-core/src/language/ty/declaration/impl_trait.rs index edacd08575a..6a598589ae8 100644 --- a/sway-core/src/language/ty/declaration/impl_trait.rs +++ b/sway-core/src/language/ty/declaration/impl_trait.rs @@ -2,16 +2,16 @@ use std::hash::{Hash, Hasher}; use sway_types::Span; -use crate::{decl_engine::DeclId, engine_threading::*, language::CallPath, type_system::*}; +use crate::{decl_engine::DeclRef, engine_threading::*, language::CallPath, type_system::*}; #[derive(Clone, Debug)] pub struct TyImplTrait { pub impl_type_parameters: Vec, pub trait_name: CallPath, pub trait_type_arguments: Vec, - pub methods: Vec, + pub methods: Vec, pub implementing_for_type_id: TypeId, - pub trait_decl_id: Option, + pub trait_decl_ref: Option, pub type_implementing_for_span: Span, pub span: Span, } @@ -30,7 +30,7 @@ impl PartialEqWithEngines for TyImplTrait { && type_engine .get(self.implementing_for_type_id) .eq(&type_engine.get(other.implementing_for_type_id), engines) - && self.trait_decl_id.eq(&other.trait_decl_id, engines) + && self.trait_decl_ref.eq(&other.trait_decl_ref, engines) } } @@ -42,7 +42,7 @@ impl HashWithEngines for TyImplTrait { trait_type_arguments, methods, implementing_for_type_id, - trait_decl_id, + trait_decl_ref, // these fields are not hashed because they aren't relevant/a // reliable source of obj v. obj distinction type_implementing_for_span: _, @@ -56,7 +56,7 @@ impl HashWithEngines for TyImplTrait { type_engine .get(*implementing_for_type_id) .hash(state, engines); - trait_decl_id.hash(state, engines); + trait_decl_ref.hash(state, engines); } } diff --git a/sway-core/src/language/ty/declaration/trait.rs b/sway-core/src/language/ty/declaration/trait.rs index 8be960a1ff6..31eb106017b 100644 --- a/sway-core/src/language/ty/declaration/trait.rs +++ b/sway-core/src/language/ty/declaration/trait.rs @@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher}; use sway_types::{Ident, Span}; use crate::{ - decl_engine::DeclId, + decl_engine::DeclRef, engine_threading::*, language::{parsed, Visibility}, transform, @@ -14,8 +14,8 @@ use crate::{ pub struct TyTraitDeclaration { pub name: Ident, pub type_parameters: Vec, - pub interface_surface: Vec, - pub methods: Vec, + pub interface_surface: Vec, + pub methods: Vec, pub supertraits: Vec, pub visibility: Visibility, pub attributes: transform::AttributesMap, @@ -64,11 +64,11 @@ impl SubstTypes for TyTraitDeclaration { .for_each(|x| x.subst(type_mapping, engines)); self.interface_surface .iter_mut() - .for_each(|function_decl_id| { - let new_decl_id = function_decl_id + .for_each(|function_decl_ref| { + let new_decl_ref = function_decl_ref .clone() .subst_types_and_insert_new(type_mapping, engines); - function_decl_id.replace_id(*new_decl_id); + function_decl_ref.replace_id((&new_decl_ref).into()); }); // we don't have to type check the methods because it hasn't been type checked yet } @@ -81,11 +81,11 @@ impl ReplaceSelfType for TyTraitDeclaration { .for_each(|x| x.replace_self_type(engines, self_type)); self.interface_surface .iter_mut() - .for_each(|function_decl_id| { - let new_decl_id = function_decl_id + .for_each(|function_decl_ref| { + let new_decl_ref = function_decl_ref .clone() .replace_self_type_and_insert_new(engines, self_type); - function_decl_id.replace_id(*new_decl_id); + function_decl_ref.replace_id((&new_decl_ref).into()); }); // we don't have to type check the methods because it hasn't been type checked yet } diff --git a/sway-core/src/language/ty/expression/expression.rs b/sway-core/src/language/ty/expression/expression.rs index 2353e446a50..0299a77352b 100644 --- a/sway-core/src/language/ty/expression/expression.rs +++ b/sway-core/src/language/ty/expression/expression.rs @@ -93,7 +93,7 @@ impl CollectTypesMetadata for TyExpression { match &self.expression { FunctionApplication { arguments, - function_decl_id, + function_decl_ref, call_path, .. } => { @@ -105,11 +105,10 @@ impl CollectTypesMetadata for TyExpression { errors )); } - let function_decl = - match decl_engine.get_function(function_decl_id.clone(), &self.span) { - Ok(decl) => decl, - Err(e) => return err(vec![], vec![e]), - }; + let function_decl = match decl_engine.get_function(function_decl_ref, &self.span) { + Ok(decl) => decl, + Err(e) => return err(vec![], vec![e]), + }; ctx.call_site_push(); for type_parameter in function_decl.type_parameters { @@ -420,18 +419,17 @@ impl DeterministicallyAborts for TyExpression { use TyExpressionVariant::*; match &self.expression { FunctionApplication { - function_decl_id, + function_decl_ref, arguments, .. } => { if !check_call_body { return false; } - let function_decl = - match decl_engine.get_function(function_decl_id.clone(), &self.span) { - Ok(decl) => decl, - Err(_e) => panic!("failed to get function"), - }; + let function_decl = match decl_engine.get_function(function_decl_ref, &self.span) { + Ok(decl) => decl, + Err(_e) => panic!("failed to get function"), + }; function_decl .body .deterministically_aborts(decl_engine, check_call_body) diff --git a/sway-core/src/language/ty/expression/expression_variant.rs b/sway-core/src/language/ty/expression/expression_variant.rs index 80c32803d11..bb9b20620e7 100644 --- a/sway-core/src/language/ty/expression/expression_variant.rs +++ b/sway-core/src/language/ty/expression/expression_variant.rs @@ -20,7 +20,7 @@ pub enum TyExpressionVariant { call_path: CallPath, contract_call_params: HashMap, arguments: Vec<(Ident, TyExpression)>, - function_decl_id: DeclId, + function_decl_ref: DeclRef, /// If this is `Some(val)` then `val` is the metadata. If this is `None`, then /// there is no selector. self_state_idx: Option, @@ -142,21 +142,21 @@ impl PartialEqWithEngines for TyExpressionVariant { Self::FunctionApplication { call_path: l_name, arguments: l_arguments, - function_decl_id: l_function_decl_id, + function_decl_ref: l_function_decl_ref, .. }, Self::FunctionApplication { call_path: r_name, arguments: r_arguments, - function_decl_id: r_function_decl_id, + function_decl_ref: r_function_decl_ref, .. }, ) => { let l_function_decl = decl_engine - .get_function(l_function_decl_id.clone(), &Span::dummy()) + .get_function(l_function_decl_ref, &Span::dummy()) .unwrap(); let r_function_decl = decl_engine - .get_function(r_function_decl_id.clone(), &Span::dummy()) + .get_function(r_function_decl_ref, &Span::dummy()) .unwrap(); l_name == r_name && l_arguments.len() == r_arguments.len() @@ -392,7 +392,7 @@ impl HashWithEngines for TyExpressionVariant { Self::FunctionApplication { call_path, arguments, - function_decl_id, + function_decl_ref, // these fields are not hashed because they aren't relevant/a // reliable source of obj v. obj distinction contract_call_params: _, @@ -401,7 +401,7 @@ impl HashWithEngines for TyExpressionVariant { type_binding: _, } => { call_path.hash(state); - function_decl_id.hash(state, engines); + function_decl_ref.hash(state, engines); arguments.iter().for_each(|(name, arg)| { name.hash(state); arg.hash(state, engines); @@ -574,16 +574,16 @@ impl SubstTypes for TyExpressionVariant { Literal(..) => (), FunctionApplication { arguments, - ref mut function_decl_id, + ref mut function_decl_ref, .. } => { arguments .iter_mut() .for_each(|(_ident, expr)| expr.subst(type_mapping, engines)); - let new_decl_id = function_decl_id + let new_decl_ref = function_decl_ref .clone() .subst_types_and_insert_new(type_mapping, engines); - function_decl_id.replace_id(*new_decl_id); + function_decl_ref.replace_id((&new_decl_ref).into()); } LazyOperator { lhs, rhs, .. } => { (*lhs).subst(type_mapping, engines); @@ -694,16 +694,16 @@ impl ReplaceSelfType for TyExpressionVariant { Literal(..) => (), FunctionApplication { arguments, - ref mut function_decl_id, + ref mut function_decl_ref, .. } => { arguments .iter_mut() .for_each(|(_ident, expr)| expr.replace_self_type(engines, self_type)); - let new_decl_id = function_decl_id + let new_decl_ref = function_decl_ref .clone() .replace_self_type_and_insert_new(engines, self_type); - function_decl_id.replace_id(*new_decl_id); + function_decl_ref.replace_id((&new_decl_ref).into()); } LazyOperator { lhs, rhs, .. } => { (*lhs).replace_self_type(engines, self_type); @@ -807,15 +807,15 @@ impl ReplaceDecls for TyExpressionVariant { match self { Literal(..) => (), FunctionApplication { - ref mut function_decl_id, + ref mut function_decl_ref, ref mut arguments, .. } => { - function_decl_id.replace_decls(decl_mapping, engines); - let new_decl_id = function_decl_id + function_decl_ref.replace_decls(decl_mapping, engines); + let new_decl_ref = function_decl_ref .clone() .replace_decls_and_insert_new(decl_mapping, engines); - function_decl_id.replace_id(*new_decl_id); + function_decl_ref.replace_id((&new_decl_ref).into()); for (_, arg) in arguments.iter_mut() { arg.replace_decls(decl_mapping, engines); } diff --git a/sway-core/src/language/ty/module.rs b/sway-core/src/language/ty/module.rs index 281314e8ca8..76098648d96 100644 --- a/sway-core/src/language/ty/module.rs +++ b/sway-core/src/language/ty/module.rs @@ -1,7 +1,7 @@ use sway_types::{Ident, Span}; use crate::{ - decl_engine::{DeclEngine, DeclId}, + decl_engine::{DeclEngine, DeclRef}, language::ty::*, language::DepName, semantic_analysis::namespace, @@ -45,16 +45,22 @@ impl TyModule { pub fn test_fns<'a: 'b, 'b>( &'b self, decl_engine: &'a DeclEngine, - ) -> impl '_ + Iterator { + ) -> impl '_ + Iterator { self.all_nodes.iter().filter_map(|node| { - if let TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(ref decl_id)) = - node.content + if let TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + decl_id, + name, + decl_span, + }) = &node.content { let fn_decl = decl_engine - .get_function(decl_id.clone(), &node.span) + .get_function(decl_id, &node.span) .expect("no function declaration for ID"); if fn_decl.is_test() { - return Some((fn_decl, decl_id.clone())); + return Some(( + fn_decl, + DeclRef::new(name.clone(), **decl_id, decl_span.clone()), + )); } } None diff --git a/sway-core/src/language/ty/program.rs b/sway-core/src/language/ty/program.rs index e9eb6be431e..da5fd73796a 100644 --- a/sway-core/src/language/ty/program.rs +++ b/sway-core/src/language/ty/program.rs @@ -65,9 +65,13 @@ impl TyProgram { let mut fn_declarations = std::collections::HashSet::new(); for node in &root.all_nodes { match &node.content { - TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration(decl_id)) => { + TyAstNodeContent::Declaration(TyDeclaration::FunctionDeclaration { + name, + decl_id, + decl_span, + }) => { let func = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &node.span)), + CompileResult::from(decl_engine.get_function(decl_id, &node.span)), return err(warnings, errors), warnings, errors @@ -84,35 +88,38 @@ impl TyProgram { }); } - declarations.push(TyDeclaration::FunctionDeclaration(decl_id.clone())); + declarations.push(TyDeclaration::FunctionDeclaration { + name: name.clone(), + decl_id: *decl_id, + decl_span: decl_span.clone(), + }); } - TyAstNodeContent::Declaration(TyDeclaration::ConstantDeclaration(decl_id)) => { - match decl_engine.get_constant(decl_id.clone(), &node.span) { - Ok(config_decl) if config_decl.is_configurable => { - configurables.push(config_decl) - } - _ => {} + TyAstNodeContent::Declaration(TyDeclaration::ConstantDeclaration { + decl_id, + .. + }) => match decl_engine.get_constant(decl_id, &node.span) { + Ok(config_decl) if config_decl.is_configurable => { + configurables.push(config_decl) } - } + _ => {} + }, // ABI entries are all functions declared in impl_traits on the contract type // itself. - TyAstNodeContent::Declaration(TyDeclaration::ImplTrait(decl_id)) => { + TyAstNodeContent::Declaration(TyDeclaration::ImplTrait { decl_id, .. }) => { let TyImplTrait { methods, implementing_for_type_id, span, .. } = check!( - CompileResult::from( - decl_engine.get_impl_trait(decl_id.clone(), &node.span) - ), + CompileResult::from(decl_engine.get_impl_trait(decl_id, &node.span)), return err(warnings, errors), warnings, errors ); if matches!(ty_engine.get(implementing_for_type_id), TypeInfo::Contract) { - for method_id in methods { - match decl_engine.get_function(method_id, &span) { + for method_ref in methods { + match decl_engine.get_function(&method_ref, &span) { Ok(method) => abi_entries.push(method), Err(err) => errors.push(err), } @@ -153,12 +160,12 @@ impl TyProgram { // `storage` declarations are not allowed in non-contracts let storage_decl = declarations .iter() - .find(|decl| matches!(decl, TyDeclaration::StorageDeclaration(_))); + .find(|decl| matches!(decl, TyDeclaration::StorageDeclaration { .. })); - if let Some(TyDeclaration::StorageDeclaration(decl_id)) = storage_decl { + if let Some(TyDeclaration::StorageDeclaration { decl_span, .. }) = storage_decl { errors.push(CompileError::StorageDeclarationInNonContract { program_kind: format!("{kind}"), - span: decl_id.span(), + span: decl_span.clone(), }); } } @@ -168,10 +175,8 @@ impl TyProgram { parsed::TreeType::Contract => { // Types containing raw_ptr are not allowed in storage (e.g Vec) for decl in declarations.iter() { - if let TyDeclaration::StorageDeclaration(decl_id) = decl { - if let Ok(storage_decl) = - decl_engine.get_storage(decl_id.clone(), &decl_id.span()) - { + if let TyDeclaration::StorageDeclaration { decl_id, decl_span } = decl { + if let Ok(storage_decl) = decl_engine.get_storage(decl_id, decl_span) { for field in storage_decl.fields.iter() { let type_info = ty_engine.get(field.type_argument.type_id); let type_info_str = engines.help_out(&type_info).to_string(); @@ -300,7 +305,7 @@ impl TyProgram { pub fn test_fns<'a: 'b, 'b>( &'b self, decl_engine: &'a DeclEngine, - ) -> impl '_ + Iterator { + ) -> impl '_ + Iterator { self.root .submodules_recursive() .flat_map(|(_, submod)| submod.module.test_fns(decl_engine)) @@ -463,8 +468,8 @@ fn disallow_impure_functions( let fn_decls = declarations .iter() .filter_map(|decl| match decl { - TyDeclaration::FunctionDeclaration(decl_id) => { - match decl_engine.get_function(decl_id.clone(), &decl.span()) { + TyDeclaration::FunctionDeclaration { decl_id, .. } => { + match decl_engine.get_function(decl_id, &decl.span()) { Ok(fn_decl) => Some(fn_decl), Err(err) => { errs.push(err); diff --git a/sway-core/src/semantic_analysis/ast_node/code_block.rs b/sway-core/src/semantic_analysis/ast_node/code_block.rs index aa712803ec4..80c6cb45767 100644 --- a/sway-core/src/semantic_analysis/ast_node/code_block.rs +++ b/sway-core/src/semantic_analysis/ast_node/code_block.rs @@ -68,9 +68,12 @@ impl ty::TyCodeBlock { .resolve_symbol(&never_mod_path, &never_ident) .value; - if let Some(ty::TyDeclaration::EnumDeclaration(never_decl_id)) = never_decl_opt + if let Some(ty::TyDeclaration::EnumDeclaration { + decl_id: never_decl_id, + .. + }) = never_decl_opt { - if let Ok(never_decl) = decl_engine.get_enum(never_decl_id.clone(), &span) { + if let Ok(never_decl) = decl_engine.get_enum(never_decl_id, &span) { return never_decl.create_type_id(ctx.engines()); } } diff --git a/sway-core/src/semantic_analysis/ast_node/declaration/declaration.rs b/sway-core/src/semantic_analysis/ast_node/declaration/declaration.rs index c94d2ce0174..d97a9d5a156 100644 --- a/sway-core/src/semantic_analysis/ast_node/declaration/declaration.rs +++ b/sway-core/src/semantic_analysis/ast_node/declaration/declaration.rs @@ -2,7 +2,7 @@ use sway_error::warning::{CompileWarning, Warning}; use sway_types::{style::is_screaming_snake_case, Spanned}; use crate::{ - decl_engine::ReplaceFunctionImplementingType, + decl_engine::{DeclRef, ReplaceFunctionImplementingType}, error::*, language::{parsed, ty}, semantic_analysis::TypeCheckContext, @@ -140,8 +140,12 @@ impl ty::TyDeclaration { is_configurable, span, }; - let typed_const_decl = - ty::TyDeclaration::ConstantDeclaration(decl_engine.insert(decl)); + let decl_ref = decl_engine.insert(decl); + let typed_const_decl = ty::TyDeclaration::ConstantDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; check!( ctx.namespace.insert_symbol(name, typed_const_decl.clone()), return err(warnings, errors), @@ -159,7 +163,12 @@ impl ty::TyDeclaration { errors ); let call_path = enum_decl.call_path.clone(); - let decl = ty::TyDeclaration::EnumDeclaration(decl_engine.insert(enum_decl)); + let decl_ref = decl_engine.insert(enum_decl); + let decl = ty::TyDeclaration::EnumDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; check!( ctx.namespace.insert_symbol(call_path.suffix, decl.clone()), return err(warnings, errors), @@ -179,7 +188,12 @@ impl ty::TyDeclaration { errors ); let name = fn_decl.name.clone(); - let decl = ty::TyDeclaration::FunctionDeclaration(decl_engine.insert(fn_decl)); + let decl_ref = decl_engine.insert(fn_decl); + let decl = ty::TyDeclaration::FunctionDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; ctx.namespace.insert_symbol(name, decl.clone()); decl } @@ -193,22 +207,33 @@ impl ty::TyDeclaration { ); let name = trait_decl.name.clone(); - // save decl_ids for the LSP + // save decl_refs for the LSP for supertrait in trait_decl.supertraits.iter_mut() { ctx.namespace .resolve_call_path(&supertrait.name) .cloned() .map(|supertrait_decl| { - if let ty::TyDeclaration::TraitDeclaration(supertrait_decl_id) = - supertrait_decl + if let ty::TyDeclaration::TraitDeclaration { + name: supertrait_name, + decl_id: supertrait_decl_id, + decl_span: supertrait_decl_span, + } = supertrait_decl { - supertrait.decl_id = Some(supertrait_decl_id); + supertrait.decl_ref = Some(DeclRef::new( + supertrait_name, + *supertrait_decl_id, + supertrait_decl_span, + )); } }); } - let decl_id = decl_engine.insert(trait_decl.clone()); - let decl = ty::TyDeclaration::TraitDeclaration(decl_id); + let decl_ref = decl_engine.insert(trait_decl.clone()); + let decl = ty::TyDeclaration::TraitDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; trait_decl .methods @@ -244,8 +269,12 @@ impl ty::TyDeclaration { warnings, errors ); - let impl_trait_decl = - ty::TyDeclaration::ImplTrait(decl_engine.insert(impl_trait.clone())); + let decl_ref = decl_engine.insert(impl_trait.clone()); + let impl_trait_decl = ty::TyDeclaration::ImplTrait { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; impl_trait.methods.iter_mut().for_each(|method| { method.replace_implementing_type(engines, impl_trait_decl.clone()) }); @@ -273,8 +302,12 @@ impl ty::TyDeclaration { warnings, errors ); - let impl_trait_decl = - ty::TyDeclaration::ImplTrait(decl_engine.insert(impl_trait.clone())); + let decl_ref = decl_engine.insert(impl_trait.clone()); + let impl_trait_decl = ty::TyDeclaration::ImplTrait { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; impl_trait.methods.iter_mut().for_each(|method| { method.replace_implementing_type(engines, impl_trait_decl.clone()) }); @@ -289,8 +322,12 @@ impl ty::TyDeclaration { errors ); let call_path = decl.call_path.clone(); - let decl_id = decl_engine.insert(decl); - let decl = ty::TyDeclaration::StructDeclaration(decl_id); + let decl_ref = decl_engine.insert(decl); + let decl = ty::TyDeclaration::StructDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; // insert the struct decl into namespace check!( ctx.namespace.insert_symbol(call_path.suffix, decl.clone()), @@ -309,7 +346,12 @@ impl ty::TyDeclaration { errors ); let name = abi_decl.name.clone(); - let decl = ty::TyDeclaration::AbiDeclaration(decl_engine.insert(abi_decl.clone())); + let decl_ref = decl_engine.insert(abi_decl.clone()); + let decl = ty::TyDeclaration::AbiDeclaration { + name: decl_ref.name, + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + }; abi_decl .methods .iter_mut() @@ -362,18 +404,21 @@ impl ty::TyDeclaration { }); } let decl = ty::TyStorageDeclaration::new(fields_buf, span, attributes); - let decl_id = decl_engine.insert(decl); + let decl_ref = decl_engine.insert(decl); // insert the storage declaration into the symbols // if there already was one, return an error that duplicate storage // declarations are not allowed check!( - ctx.namespace.set_storage_declaration(decl_id.clone()), + ctx.namespace.set_storage_declaration(decl_ref.clone()), return err(warnings, errors), warnings, errors ); - ty::TyDeclaration::StorageDeclaration(decl_id) + ty::TyDeclaration::StorageDeclaration { + decl_id: decl_ref.id, + decl_span: decl_ref.decl_span, + } } }; diff --git a/sway-core/src/semantic_analysis/ast_node/declaration/impl_trait.rs b/sway-core/src/semantic_analysis/ast_node/declaration/impl_trait.rs index 002081bfb84..ac0c9f3dd2a 100644 --- a/sway-core/src/semantic_analysis/ast_node/declaration/impl_trait.rs +++ b/sway-core/src/semantic_analysis/ast_node/declaration/impl_trait.rs @@ -113,9 +113,9 @@ impl ty::TyImplTrait { .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::TraitDeclaration(decl_id)) => { + Some(ty::TyDeclaration::TraitDeclaration { decl_id, .. }) => { let mut trait_decl = check!( - CompileResult::from(decl_engine.get_trait(decl_id.clone(), &trait_name.span())), + CompileResult::from(decl_engine.get_trait(&decl_id, &trait_name.span())), return err(warnings, errors), warnings, errors @@ -156,21 +156,25 @@ impl ty::TyImplTrait { impl_type_parameters: new_impl_type_parameters, trait_name: trait_name.clone(), trait_type_arguments, - trait_decl_id: Some(decl_id), + trait_decl_ref: Some(DeclRef::new( + trait_decl.name.clone(), + *decl_id, + trait_decl.span.clone(), + )), span: block_span, methods: new_methods, implementing_for_type_id, type_implementing_for_span: type_implementing_for_span.clone(), } } - Some(ty::TyDeclaration::AbiDeclaration(decl_id)) => { + Some(ty::TyDeclaration::AbiDeclaration { decl_id, .. }) => { // if you are comparing this with the `impl_trait` branch above, note that // there are no type arguments here because we don't support generic types // in contract ABIs yet (or ever?) due to the complexity of communicating // the ABI layout in the descriptor file. let abi = check!( - CompileResult::from(decl_engine.get_abi(decl_id.clone(), &trait_name.span())), + CompileResult::from(decl_engine.get_abi(&decl_id, &trait_name.span())), return err(warnings, errors), warnings, errors @@ -210,7 +214,7 @@ impl ty::TyImplTrait { impl_type_parameters: vec![], // this is empty because abi definitions don't support generics trait_name, trait_type_arguments: vec![], // this is empty because abi definitions don't support generics - trait_decl_id: Some(decl_id), + trait_decl_ref: Some(DeclRef::new(abi.name.clone(), *decl_id, abi.span)), span: block_span, methods: new_methods, implementing_for_type_id, @@ -374,22 +378,22 @@ impl ty::TyImplTrait { ty::TyDeclaration::VariableDeclaration(decl) => { expr_contains_get_storage_index(decl_engine, &decl.body, access_span) } - ty::TyDeclaration::ConstantDeclaration(decl_id) => { + ty::TyDeclaration::ConstantDeclaration { decl_id, .. } => { let ty::TyConstantDeclaration { value: expr, .. } = - decl_engine.get_constant(decl_id.clone(), access_span)?; + decl_engine.get_constant(decl_id, access_span)?; expr_contains_get_storage_index(decl_engine, &expr, access_span) } // We're already inside a type's impl. So we can't have these // nested functions etc. We just ignore them. - ty::TyDeclaration::FunctionDeclaration(_) - | ty::TyDeclaration::TraitDeclaration(_) - | ty::TyDeclaration::StructDeclaration(_) - | ty::TyDeclaration::EnumDeclaration(_) - | ty::TyDeclaration::ImplTrait(_) - | ty::TyDeclaration::AbiDeclaration(_) + ty::TyDeclaration::FunctionDeclaration { .. } + | ty::TyDeclaration::TraitDeclaration { .. } + | ty::TyDeclaration::StructDeclaration { .. } + | ty::TyDeclaration::EnumDeclaration { .. } + | ty::TyDeclaration::ImplTrait { .. } + | ty::TyDeclaration::AbiDeclaration { .. } | ty::TyDeclaration::GenericTypeForFunctionScope { .. } | ty::TyDeclaration::ErrorRecovery(_) - | ty::TyDeclaration::StorageDeclaration(_) => Ok(false), + | ty::TyDeclaration::StorageDeclaration { .. } => Ok(false), } } @@ -555,7 +559,7 @@ impl ty::TyImplTrait { impl_type_parameters: new_impl_type_parameters, trait_name, trait_type_arguments: vec![], // this is empty because impl selfs don't support generics on the "Self" trait, - trait_decl_id: None, + trait_decl_ref: None, span: block_span, methods: methods_ids, implementing_for_type_id, @@ -572,13 +576,13 @@ fn type_check_trait_implementation( trait_type_parameters: &[TypeParameter], trait_type_arguments: &[TypeArgument], trait_supertraits: &[Supertrait], - trait_interface_surface: &[DeclId], - trait_methods: &[DeclId], + trait_interface_surface: &[DeclRef], + trait_methods: &[DeclRef], impl_methods: &[FunctionDeclaration], trait_name: &CallPath, block_span: &Span, is_contract: bool, -) -> CompileResult> { +) -> CompileResult> { let mut errors = vec![]; let mut warnings = vec![]; @@ -605,8 +609,8 @@ fn type_check_trait_implementation( errors ); - // Gather the supertrait "stub_method_ids" and "impld_method_ids". - let (supertrait_stub_method_ids, supertrait_impld_method_ids) = check!( + // Gather the supertrait "stub_method_refs" and "impld_method_refs". + let (supertrait_stub_method_refs, supertrait_impld_method_refs) = check!( handle_supertraits(ctx.by_ref(), trait_supertraits), return err(warnings, errors), warnings, @@ -622,7 +626,7 @@ fn type_check_trait_implementation( trait_name.clone(), trait_type_arguments.to_vec(), self_type, - &supertrait_impld_method_ids + &supertrait_impld_method_refs .values() .cloned() .collect::>(), @@ -637,15 +641,15 @@ fn type_check_trait_implementation( // This map keeps track of the stub declaration id's of the trait // definition. - let mut stub_method_ids: MethodMap = BTreeMap::new(); + let mut stub_method_refs: MethodMap = BTreeMap::new(); // This map keeps track of the new declaration ids of the implemented // interface surface. - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); - for decl_id in trait_interface_surface.iter() { + for decl_ref in trait_interface_surface.iter() { let method = check!( - CompileResult::from(decl_engine.get_trait_fn(decl_id.clone(), block_span)), + CompileResult::from(decl_engine.get_trait_fn(decl_ref, block_span)), return err(warnings, errors), warnings, errors @@ -656,7 +660,7 @@ fn type_check_trait_implementation( method_checklist.insert(name.clone(), method); // Add this method to the "stub methods". - stub_method_ids.insert(name, decl_id.clone()); + stub_method_refs.insert(name, decl_ref.clone()); } for impl_method in impl_methods { @@ -667,7 +671,7 @@ fn type_check_trait_implementation( impl_method, trait_name, is_contract, - &impld_method_ids, + &impld_method_refs, &method_checklist ), ty::TyFunctionDeclaration::error(impl_method.clone()), @@ -675,16 +679,16 @@ fn type_check_trait_implementation( errors ); let name = impl_method.name.clone(); - let decl_id = decl_engine.insert(impl_method); + let decl_ref = decl_engine.insert(impl_method); // Remove this method from the checklist. method_checklist.remove(&name); // Add this method to the "impld methods". - impld_method_ids.insert(name, decl_id); + impld_method_refs.insert(name, decl_ref); } - let mut all_method_ids: Vec = impld_method_ids.values().cloned().collect(); + let mut all_method_refs: Vec = impld_method_refs.values().cloned().collect(); // Retrieve the methods defined on the trait declaration and transform // them into the correct typing for this impl block by using the type @@ -702,12 +706,13 @@ fn type_check_trait_implementation( .map(|type_arg| type_arg.type_id) .collect(), ); - stub_method_ids.extend(supertrait_stub_method_ids); - impld_method_ids.extend(supertrait_impld_method_ids); - let decl_mapping = DeclMapping::from_stub_and_impld_decl_ids(stub_method_ids, impld_method_ids); - for decl_id in trait_methods.iter() { + stub_method_refs.extend(supertrait_stub_method_refs); + impld_method_refs.extend(supertrait_impld_method_refs); + let decl_mapping = + DeclMapping::from_stub_and_impld_decl_refs(stub_method_refs, impld_method_refs); + for decl_ref in trait_methods.iter() { let mut method = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), block_span)), + CompileResult::from(decl_engine.get_function(decl_ref, block_span)), return err(warnings, errors), warnings, errors @@ -715,10 +720,10 @@ fn type_check_trait_implementation( method.replace_decls(&decl_mapping, engines); method.subst(&type_mapping, engines); method.replace_self_type(engines, ctx.self_type()); - all_method_ids.push( + all_method_refs.push( decl_engine .insert(method) - .with_parent(decl_engine, decl_id.clone()), + .with_parent(decl_engine, decl_ref), ); } @@ -735,7 +740,7 @@ fn type_check_trait_implementation( } if errors.is_empty() { - ok(all_method_ids, warnings, errors) + ok(all_method_refs, warnings, errors) } else { err(warnings, errors) } @@ -747,7 +752,7 @@ fn type_check_impl_method( impl_method: &FunctionDeclaration, trait_name: &CallPath, is_contract: bool, - impld_method_ids: &MethodMap, + impld_method_refs: &MethodMap, method_checklist: &BTreeMap, ) -> CompileResult { let mut warnings = vec![]; @@ -780,7 +785,7 @@ fn type_check_impl_method( ); // Ensure that there aren't multiple definitions of this function impl'd - if impld_method_ids.contains_key(&impl_method.name.clone()) { + if impld_method_refs.contains_key(&impl_method.name.clone()) { errors.push(CompileError::MultipleDefinitionsOfFunction { name: impl_method.name.clone(), span: impl_method.name.span(), @@ -1083,7 +1088,7 @@ fn handle_supertraits( let decl_engine = ctx.decl_engine; let mut interface_surface_methods_ids: MethodMap = BTreeMap::new(); - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); let self_type = ctx.self_type(); for supertrait in supertraits.iter() { @@ -1105,9 +1110,9 @@ fn handle_supertraits( .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::TraitDeclaration(decl_id)) => { + Some(ty::TyDeclaration::TraitDeclaration { decl_id, .. }) => { let trait_decl = check!( - CompileResult::from(decl_engine.get_trait(decl_id.clone(), &supertrait.span())), + CompileResult::from(decl_engine.get_trait(&decl_id, &supertrait.span())), return err(warnings, errors), warnings, errors @@ -1125,27 +1130,27 @@ fn handle_supertraits( // Retrieve the interface surface and implemented method ids for // this trait. - let (trait_interface_surface_methods_ids, trait_impld_method_ids) = trait_decl + let (trait_interface_surface_methods_ids, trait_impld_method_refs) = trait_decl .retrieve_interface_surface_and_implemented_methods_for_type( ctx.by_ref(), self_type, &supertrait.name, ); interface_surface_methods_ids.extend(trait_interface_surface_methods_ids); - impld_method_ids.extend(trait_impld_method_ids); + impld_method_refs.extend(trait_impld_method_refs); // Retrieve the interface surfaces and implemented methods for // the supertraits of this type. - let (next_stub_supertrait_decl_ids, next_these_supertrait_decl_ids) = check!( + let (next_stub_supertrait_decl_refs, next_these_supertrait_decl_refs) = check!( handle_supertraits(ctx.by_ref(), &trait_decl.supertraits), continue, warnings, errors ); - interface_surface_methods_ids.extend(next_stub_supertrait_decl_ids); - impld_method_ids.extend(next_these_supertrait_decl_ids); + interface_surface_methods_ids.extend(next_stub_supertrait_decl_refs); + impld_method_refs.extend(next_these_supertrait_decl_refs); } - Some(ty::TyDeclaration::AbiDeclaration(_)) => { + Some(ty::TyDeclaration::AbiDeclaration { .. }) => { errors.push(CompileError::AbiAsSupertrait { span: supertrait.name.span().clone(), }) @@ -1159,7 +1164,7 @@ fn handle_supertraits( if errors.is_empty() { ok( - (interface_surface_methods_ids, impld_method_ids), + (interface_surface_methods_ids, impld_method_refs), warnings, errors, ) diff --git a/sway-core/src/semantic_analysis/ast_node/declaration/supertrait.rs b/sway-core/src/semantic_analysis/ast_node/declaration/supertrait.rs index fa4ac288da1..da8dd473780 100644 --- a/sway-core/src/semantic_analysis/ast_node/declaration/supertrait.rs +++ b/sway-core/src/semantic_analysis/ast_node/declaration/supertrait.rs @@ -39,9 +39,9 @@ pub(crate) fn insert_supertraits_into_namespace( .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::TraitDeclaration(decl_id)) => { + Some(ty::TyDeclaration::TraitDeclaration { decl_id, .. }) => { let mut trait_decl = check!( - CompileResult::from(decl_engine.get_trait(decl_id.clone(), &supertrait.span())), + CompileResult::from(decl_engine.get_trait(&decl_id, &supertrait.span())), break, warnings, errors @@ -100,7 +100,7 @@ pub(crate) fn insert_supertraits_into_namespace( errors ); } - Some(ty::TyDeclaration::AbiDeclaration(_)) => { + Some(ty::TyDeclaration::AbiDeclaration { .. }) => { errors.push(CompileError::AbiAsSupertrait { span: supertrait.name.span().clone(), }) diff --git a/sway-core/src/semantic_analysis/ast_node/declaration/trait.rs b/sway-core/src/semantic_analysis/ast_node/declaration/trait.rs index e0e320e0cee..ddcf344975f 100644 --- a/sway-core/src/semantic_analysis/ast_node/declaration/trait.rs +++ b/sway-core/src/semantic_analysis/ast_node/declaration/trait.rs @@ -76,13 +76,13 @@ impl ty::TyTraitDeclaration { warnings, errors ); - let decl_id = decl_engine.insert(method.clone()); - new_interface_surface.push(decl_id.clone()); + let decl_ref = decl_engine.insert(method.clone()); dummy_interface_surface.push( decl_engine .insert(method.to_dummy_func(Mode::NonAbi)) - .with_parent(decl_engine, decl_id), + .with_parent(decl_engine, &decl_ref), ); + new_interface_surface.push(decl_ref); } // insert placeholder functions representing the interface surface @@ -138,8 +138,8 @@ impl ty::TyTraitDeclaration { type_id: TypeId, call_path: &CallPath, ) -> (MethodMap, MethodMap) { - let mut interface_surface_method_ids: MethodMap = BTreeMap::new(); - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut interface_surface_method_refs: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); let ty::TyTraitDeclaration { interface_surface, .. @@ -148,20 +148,20 @@ impl ty::TyTraitDeclaration { let engines = ctx.engines(); // Retrieve the interface surface for this trait. - for decl_id in interface_surface.iter() { - interface_surface_method_ids.insert(decl_id.name.clone(), decl_id.clone()); + for decl_ref in interface_surface.iter() { + interface_surface_method_refs.insert(decl_ref.name.clone(), decl_ref.clone()); } // Retrieve the implemented methods for this type. - for decl_id in ctx + for decl_ref in ctx .namespace .get_methods_for_type_and_trait_name(engines, type_id, call_path) .into_iter() { - impld_method_ids.insert(decl_id.name.clone(), decl_id); + impld_method_refs.insert(decl_ref.name.clone(), decl_ref); } - (interface_surface_method_ids, impld_method_ids) + (interface_surface_method_refs, impld_method_refs) } /// Retrieves the interface surface, methods, and implemented methods for @@ -176,9 +176,9 @@ impl ty::TyTraitDeclaration { let mut warnings = vec![]; let mut errors = vec![]; - let mut interface_surface_method_ids: MethodMap = BTreeMap::new(); - let mut method_ids: MethodMap = BTreeMap::new(); - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut interface_surface_method_refs: MethodMap = BTreeMap::new(); + let mut method_refs: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); let ty::TyTraitDeclaration { interface_surface, @@ -191,13 +191,13 @@ impl ty::TyTraitDeclaration { let engines = ctx.engines(); // Retrieve the interface surface for this trait. - for decl_id in interface_surface.iter() { - interface_surface_method_ids.insert(decl_id.name.clone(), decl_id.clone()); + for decl_ref in interface_surface.iter() { + interface_surface_method_refs.insert(decl_ref.name.clone(), decl_ref.clone()); } // Retrieve the trait methods for this trait. - for decl_id in methods.iter() { - method_ids.insert(decl_id.name.clone(), decl_id.clone()); + for decl_ref in methods.iter() { + method_refs.insert(decl_ref.name.clone(), decl_ref.clone()); } // Retrieve the implemented methods for this type. @@ -211,26 +211,32 @@ impl ty::TyTraitDeclaration { .map(|type_arg| type_arg.type_id) .collect(), ); - for decl_id in ctx + for decl_ref in ctx .namespace .get_methods_for_type_and_trait_name(engines, type_id, call_path) .into_iter() { let mut method = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &call_path.span())), + CompileResult::from(decl_engine.get_function(&decl_ref, &call_path.span())), return err(warnings, errors), warnings, errors ); method.subst(&type_mapping, engines); - impld_method_ids.insert( + impld_method_refs.insert( method.name.clone(), - decl_engine.insert(method).with_parent(decl_engine, decl_id), + decl_engine + .insert(method) + .with_parent(decl_engine, &decl_ref), ); } ok( - (interface_surface_method_ids, method_ids, impld_method_ids), + ( + interface_surface_method_refs, + method_refs, + impld_method_refs, + ), warnings, errors, ) @@ -271,9 +277,9 @@ impl ty::TyTraitDeclaration { .map(|type_arg| type_arg.type_id) .collect(), ); - for decl_id in interface_surface.iter() { + for decl_ref in interface_surface.iter() { let mut method = check!( - CompileResult::from(decl_engine.get_trait_fn(decl_id.clone(), &trait_name.span())), + CompileResult::from(decl_engine.get_trait_fn(decl_ref, &trait_name.span())), continue, warnings, errors @@ -283,12 +289,12 @@ impl ty::TyTraitDeclaration { all_methods.push( ctx.decl_engine .insert(method.to_dummy_func(Mode::NonAbi)) - .with_parent(ctx.decl_engine, decl_id.clone()), + .with_parent(ctx.decl_engine, decl_ref), ); } - for decl_id in methods.iter() { + for decl_ref in methods.iter() { let mut method = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &trait_name.span())), + CompileResult::from(decl_engine.get_function(decl_ref, &trait_name.span())), continue, warnings, errors @@ -298,7 +304,7 @@ impl ty::TyTraitDeclaration { all_methods.push( ctx.decl_engine .insert(method) - .with_parent(ctx.decl_engine, decl_id.clone()), + .with_parent(ctx.decl_engine, decl_ref), ); } diff --git a/sway-core/src/semantic_analysis/ast_node/expression/match_expression/typed/typed_scrutinee.rs b/sway-core/src/semantic_analysis/ast_node/expression/match_expression/typed/typed_scrutinee.rs index 0f8311ded66..5fd29563a7b 100644 --- a/sway-core/src/semantic_analysis/ast_node/expression/match_expression/typed/typed_scrutinee.rs +++ b/sway-core/src/semantic_analysis/ast_node/expression/match_expression/typed/typed_scrutinee.rs @@ -70,9 +70,9 @@ fn type_check_variable( let typed_scrutinee = match ctx.namespace.resolve_symbol(&name).value { // If this variable is a constant, then we turn it into a [TyScrutinee::Constant](ty::TyScrutinee::Constant). - Some(ty::TyDeclaration::ConstantDeclaration(decl_id)) => { + Some(ty::TyDeclaration::ConstantDeclaration { decl_id, .. }) => { let constant_decl = check!( - CompileResult::from(decl_engine.get_constant(decl_id.clone(), &span)), + CompileResult::from(decl_engine.get_constant(decl_id, &span)), return err(warnings, errors), warnings, errors diff --git a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression.rs b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression.rs index 2809618be03..15159019190 100644 --- a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression.rs +++ b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression.rs @@ -21,7 +21,7 @@ use crate::{ error::*, language::{ parsed::*, - ty::{self, GetDeclId}, + ty::{self, GetDeclRef}, *, }, semantic_analysis::*, @@ -74,16 +74,14 @@ impl ty::TyExpression { span: call_path.span(), }; let arguments = VecDeque::from(arguments); - let decl_id = check!( + let decl_ref = check!( resolve_method_name(ctx, &mut method_name_binding, arguments.clone()), return err(warnings, errors), warnings, errors ); let method = check!( - CompileResult::from( - decl_engine.get_function(decl_id.clone(), &method_name_binding.span()) - ), + CompileResult::from(decl_engine.get_function(&decl_ref, &method_name_binding.span())), return err(warnings, errors), warnings, errors @@ -107,7 +105,7 @@ impl ty::TyExpression { call_path, contract_call_params: HashMap::new(), arguments: args_and_names, - function_decl_id: decl_id, + function_decl_ref: decl_ref, self_state_idx: None, selector: None, type_binding: None, @@ -412,13 +410,13 @@ impl ty::TyExpression { span, } } - Some(ty::TyDeclaration::ConstantDeclaration(decl_id)) => { + Some(ty::TyDeclaration::ConstantDeclaration { decl_id, .. }) => { let ty::TyConstantDeclaration { name: decl_name, type_ascription, .. } = check!( - CompileResult::from(decl_engine.get_constant(decl_id.clone(), &span)), + CompileResult::from(decl_engine.get_constant(decl_id, &span)), return err(warnings, errors), warnings, errors @@ -436,9 +434,9 @@ impl ty::TyExpression { span, } } - Some(ty::TyDeclaration::AbiDeclaration(decl_id)) => { + Some(ty::TyDeclaration::AbiDeclaration { decl_id, .. }) => { let decl = check!( - CompileResult::from(decl_engine.get_abi(decl_id.clone(), &span)), + CompileResult::from(decl_engine.get_abi(decl_id, &span)), return err(warnings, errors), warnings, errors @@ -497,7 +495,7 @@ impl ty::TyExpression { instantiate_function_application( ctx, - unknown_decl.get_decl_id().unwrap(), + unknown_decl.get_decl_ref().unwrap(), call_path_binding, Some(arguments), span, @@ -1119,7 +1117,7 @@ impl ty::TyExpression { .and_then(|decl| { decl.expect_function(decl_engine, &span) .ok(&mut function_probe_warnings, &mut function_probe_errors) - .map(|_s| (decl.get_decl_id().unwrap(), call_path_binding)) + .map(|_s| (decl.get_decl_ref().unwrap(), call_path_binding)) }) }; @@ -1169,7 +1167,7 @@ impl ty::TyExpression { errors ) } - (false, Some((decl_id, call_path_binding)), None, None) => { + (false, Some((decl_ref, call_path_binding)), None, None) => { warnings.append(&mut function_probe_warnings); errors.append(&mut function_probe_errors); // In case `foo::bar::::baz(...)` throw an error. @@ -1182,7 +1180,7 @@ impl ty::TyExpression { ); } check!( - instantiate_function_application(ctx, decl_id, call_path_binding, args, span), + instantiate_function_application(ctx, decl_ref, call_path_binding, args, span), return err(warnings, errors), warnings, errors @@ -1275,9 +1273,9 @@ impl ty::TyExpression { span, .. } = match abi { - ty::TyDeclaration::AbiDeclaration(decl_id) => { + ty::TyDeclaration::AbiDeclaration { decl_id, .. } => { check!( - CompileResult::from(decl_engine.get_abi(decl_id, &span)), + CompileResult::from(decl_engine.get_abi(&decl_id, &span)), return err(warnings, errors), warnings, errors @@ -1350,9 +1348,9 @@ impl ty::TyExpression { // Retrieve the interface surface for this abi. let mut abi_methods = vec![]; - for decl_id in interface_surface.into_iter() { + for decl_ref in interface_surface.into_iter() { let method = check!( - CompileResult::from(decl_engine.get_trait_fn(decl_id.clone(), &name.span())), + CompileResult::from(decl_engine.get_trait_fn(&decl_ref, &name.span())), return err(warnings, errors), warnings, errors @@ -1360,7 +1358,7 @@ impl ty::TyExpression { abi_methods.push( decl_engine .insert(method.to_dummy_func(Mode::ImplAbiFn)) - .with_parent(decl_engine, decl_id), + .with_parent(decl_engine, &decl_ref), ); } diff --git a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/function_application.rs b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/function_application.rs index 3a197a874c4..4ef85f9a7bb 100644 --- a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/function_application.rs +++ b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/function_application.rs @@ -1,5 +1,5 @@ use crate::{ - decl_engine::{DeclId, ReplaceDecls}, + decl_engine::{DeclRef, ReplaceDecls}, error::*, language::{ty, *}, semantic_analysis::{ast_node::*, TypeCheckContext}, @@ -11,7 +11,7 @@ use sway_types::Spanned; #[allow(clippy::too_many_arguments)] pub(crate) fn instantiate_function_application( mut ctx: TypeCheckContext, - function_decl_id: DeclId, + function_decl_ref: DeclRef, call_path_binding: TypeBinding, arguments: Option>, span: Span, @@ -22,9 +22,7 @@ pub(crate) fn instantiate_function_application( let decl_engine = ctx.decl_engine; let engines = ctx.engines(); - let mut function_decl = decl_engine - .get_function(function_decl_id.clone(), &span) - .unwrap(); + let mut function_decl = decl_engine.get_function(&function_decl_ref, &span).unwrap(); if arguments.is_none() { errors.push(CompileError::MissingParenthesesForFunction { @@ -90,16 +88,16 @@ pub(crate) fn instantiate_function_application( ); function_decl.replace_decls(&decl_mapping, engines); let return_type = function_decl.return_type.clone(); - let new_decl_id = decl_engine + let new_decl_ref = decl_engine .insert(function_decl) - .with_parent(decl_engine, function_decl_id); + .with_parent(decl_engine, &function_decl_ref); let exp = ty::TyExpression { expression: ty::TyExpressionVariant::FunctionApplication { call_path: call_path_binding.inner.clone(), contract_call_params: HashMap::new(), arguments: typed_arguments_with_names, - function_decl_id: new_decl_id, + function_decl_ref: new_decl_ref, self_state_idx: None, selector: None, type_binding: Some(call_path_binding.strip_inner()), diff --git a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/method_application.rs b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/method_application.rs index e4e26c265d6..35b2b705d41 100644 --- a/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/method_application.rs +++ b/sway-core/src/semantic_analysis/ast_node/expression/typed_expression/method_application.rs @@ -1,5 +1,5 @@ use crate::{ - decl_engine::DeclId, + decl_engine::DeclRef, error::*, language::{parsed::*, ty, *}, semantic_analysis::*, @@ -43,14 +43,14 @@ pub(crate) fn type_check_method_application( } // resolve the method name to a typed function declaration and type_check - let decl_id = check!( + let decl_ref = check!( resolve_method_name(ctx.by_ref(), &mut method_name_binding, args_buf.clone()), return err(warnings, errors), warnings, errors ); let method = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &method_name_binding.span())), + CompileResult::from(decl_engine.get_function(&decl_ref, &method_name_binding.span())), return err(warnings, errors), warnings, errors @@ -237,7 +237,7 @@ pub(crate) fn type_check_method_application( ); let is_decl_mutable = match unknown_decl { - ty::TyDeclaration::ConstantDeclaration(_) => false, + ty::TyDeclaration::ConstantDeclaration { .. } => false, _ => { let variable_decl = check!( unknown_decl.expect_variable().cloned(), @@ -352,7 +352,7 @@ pub(crate) fn type_check_method_application( call_path, contract_call_params: contract_call_params_map, arguments: typed_arguments_with_names, - function_decl_id: decl_id, + function_decl_ref: decl_ref, self_state_idx, selector, type_binding: Some(method_name_binding.strip_inner()), @@ -414,7 +414,7 @@ pub(crate) fn resolve_method_name( mut ctx: TypeCheckContext, method_name: &mut TypeBinding, arguments: VecDeque, -) -> CompileResult { +) -> CompileResult { let mut warnings = vec![]; let mut errors = vec![]; @@ -423,7 +423,7 @@ pub(crate) fn resolve_method_name( let engines = ctx.engines(); // retrieve the function declaration using the components of the method name - let decl_id = match &method_name.inner { + let decl_ref = match &method_name.inner { MethodName::FromType { call_path_binding, method_name, @@ -515,7 +515,7 @@ pub(crate) fn resolve_method_name( }; let mut func_decl = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_function(&decl_ref, &decl_ref.span())), return err(warnings, errors), warnings, errors @@ -535,10 +535,10 @@ pub(crate) fn resolve_method_name( errors ); - let decl_id = ctx + let decl_ref = ctx .decl_engine .insert(func_decl) - .with_parent(ctx.decl_engine, decl_id); + .with_parent(ctx.decl_engine, &decl_ref); - ok(decl_id, warnings, errors) + ok(decl_ref, warnings, errors) } diff --git a/sway-core/src/semantic_analysis/cei_pattern_analysis.rs b/sway-core/src/semantic_analysis/cei_pattern_analysis.rs index 0e74c4002f1..989c1ebbdad 100644 --- a/sway-core/src/semantic_analysis/cei_pattern_analysis.rs +++ b/sway-core/src/semantic_analysis/cei_pattern_analysis.rs @@ -98,10 +98,10 @@ fn contract_entry_points( ast_nodes .iter() .flat_map(|ast_node| match &ast_node.content { - Declaration(ty::TyDeclaration::FunctionDeclaration(decl_id)) => { + Declaration(ty::TyDeclaration::FunctionDeclaration { decl_id, .. }) => { decl_id_to_fn_decls(decl_engine, decl_id, &ast_node.span) } - Declaration(ty::TyDeclaration::ImplTrait(decl_id)) => { + Declaration(ty::TyDeclaration::ImplTrait { decl_id, .. }) => { impl_trait_methods(decl_engine, decl_id, &ast_node.span) } _ => vec![], @@ -115,20 +115,20 @@ fn decl_id_to_fn_decls( span: &Span, ) -> Vec { decl_engine - .get_function(decl_id.clone(), span) + .get_function(decl_id, span) .map_or(vec![], |fn_decl| vec![fn_decl]) } -fn impl_trait_methods<'a>( +fn impl_trait_methods( decl_engine: &DeclEngine, - impl_trait_decl_id: &'a DeclId, - span: &'a Span, + impl_trait_decl_id: &DeclId, + span: &Span, ) -> Vec { - match decl_engine.get_impl_trait(impl_trait_decl_id.clone(), span) { + match decl_engine.get_impl_trait(impl_trait_decl_id, span) { Ok(impl_trait) => impl_trait .methods .iter() - .flat_map(|fn_decl| decl_id_to_fn_decls(decl_engine, fn_decl, span)) + .flat_map(|fn_decl| decl_id_to_fn_decls(decl_engine, &fn_decl.id, span)) .collect(), Err(_) => vec![], } @@ -247,13 +247,13 @@ fn analyze_expression( } => analyze_two_expressions(engines, left, right, block_name, warnings), FunctionApplication { arguments, - function_decl_id, + function_decl_ref, selector, call_path, .. } => { let func = decl_engine - .get_function(function_decl_id.clone(), &expr.span) + .get_function(function_decl_ref, &expr.span) .unwrap(); // we don't need to run full analysis on the function body as it will be covered // as a separate step of the whole contract analysis @@ -581,13 +581,13 @@ fn effects_of_expression(engines: Engines<'_>, expr: &ty::TyExpression) -> HashS .cloned() .collect(), FunctionApplication { - function_decl_id, + function_decl_ref, arguments, selector, .. } => { let fn_body = decl_engine - .get_function(function_decl_id.clone(), &expr.span) + .get_function(function_decl_ref, &expr.span) .unwrap() .body; let mut effs = effects_of_codeblock(engines, &fn_body); diff --git a/sway-core/src/semantic_analysis/coins_analysis.rs b/sway-core/src/semantic_analysis/coins_analysis.rs index 00a020b2339..2eff419795e 100644 --- a/sway-core/src/semantic_analysis/coins_analysis.rs +++ b/sway-core/src/semantic_analysis/coins_analysis.rs @@ -21,8 +21,8 @@ pub fn possibly_nonzero_u64_expression( ty::TyDeclaration::VariableDeclaration(var_decl) => { possibly_nonzero_u64_expression(namespace, decl_engine, &var_decl.body) } - ty::TyDeclaration::ConstantDeclaration(decl_id) => { - match decl_engine.get_constant(decl_id.clone(), &expr.span) { + ty::TyDeclaration::ConstantDeclaration { decl_id, .. } => { + match decl_engine.get_constant(decl_id, &expr.span) { Ok(const_decl) => possibly_nonzero_u64_expression( namespace, decl_engine, diff --git a/sway-core/src/semantic_analysis/namespace/items.rs b/sway-core/src/semantic_analysis/namespace/items.rs index 8f0600ba972..cbbe9bcafd6 100644 --- a/sway-core/src/semantic_analysis/namespace/items.rs +++ b/sway-core/src/semantic_analysis/namespace/items.rs @@ -37,7 +37,7 @@ pub struct Items { /// alias for `bar`. pub(crate) use_aliases: UseAliases, /// If there is a storage declaration (which are only valid in contracts), store it here. - pub(crate) declared_storage: Option, + pub(crate) declared_storage: Option, } impl Items { @@ -58,9 +58,9 @@ impl Items { let type_engine = engines.te(); let decl_engine = engines.de(); match self.declared_storage { - Some(ref decl_id) => { + Some(ref decl_ref) => { let storage = check!( - CompileResult::from(decl_engine.get_storage(decl_id.clone(), access_span)), + CompileResult::from(decl_engine.get_storage(decl_ref, access_span)), return err(warnings, errors), warnings, errors @@ -76,16 +76,16 @@ impl Items { } } - pub fn set_storage_declaration(&mut self, decl_id: DeclId) -> CompileResult<()> { + pub fn set_storage_declaration(&mut self, decl_ref: DeclRef) -> CompileResult<()> { if self.declared_storage.is_some() { return err( vec![], vec![CompileError::MultipleStorageDeclarations { - span: decl_id.span(), + span: decl_ref.span(), }], ); } - self.declared_storage = Some(decl_id); + self.declared_storage = Some(decl_ref); ok((), vec![], vec![]) } @@ -166,7 +166,7 @@ impl Items { &self, engines: Engines<'_>, type_id: TypeId, - ) -> Vec { + ) -> Vec { self.implemented_traits .get_methods_for_type(engines, type_id) } @@ -183,9 +183,9 @@ impl Items { let mut warnings = vec![]; let mut errors = vec![]; match self.declared_storage { - Some(ref decl_id) => { + Some(ref decl_ref) => { let storage = check!( - CompileResult::from(decl_engine.get_storage(decl_id.clone(), access_span)), + CompileResult::from(decl_engine.get_storage(decl_ref, access_span)), return err(warnings, errors), warnings, errors diff --git a/sway-core/src/semantic_analysis/namespace/namespace.rs b/sway-core/src/semantic_analysis/namespace/namespace.rs index c66cd329eea..17517bd77ba 100644 --- a/sway-core/src/semantic_analysis/namespace/namespace.rs +++ b/sway-core/src/semantic_analysis/namespace/namespace.rs @@ -1,5 +1,5 @@ use crate::{ - decl_engine::DeclId, + decl_engine::DeclRef, engine_threading::*, error::*, language::{ty, CallPath}, @@ -163,7 +163,7 @@ impl Namespace { self_type: TypeId, args_buf: &VecDeque, engines: Engines<'_>, - ) -> CompileResult { + ) -> CompileResult { let mut warnings = vec![]; let mut errors = vec![]; @@ -220,26 +220,24 @@ impl Namespace { let mut methods = local_methods; methods.append(&mut type_methods); - let mut matching_method_decl_ids: Vec = vec![]; + let mut matching_method_decl_refs: Vec = vec![]; - for decl_id in methods.into_iter() { - if &decl_id.name == method_name { - matching_method_decl_ids.push(decl_id); + for decl_ref in methods.into_iter() { + if &decl_ref.name == method_name { + matching_method_decl_refs.push(decl_ref); } } - let matching_method_decl_id = match matching_method_decl_ids.len().cmp(&1) { - Ordering::Equal => matching_method_decl_ids.get(0).cloned(), + let matching_method_decl_ref = match matching_method_decl_refs.len().cmp(&1) { + Ordering::Equal => matching_method_decl_refs.get(0).cloned(), Ordering::Greater => { // Case where multiple methods exist with the same name // This is the case of https://github.com/FuelLabs/sway/issues/3633 // where multiple generic trait impls use the same method name but with different parameter types - let mut maybe_method_decl_id: Option = Option::None; - for decl_id in matching_method_decl_ids.clone().into_iter() { + let mut maybe_method_decl_ref: Option = Option::None; + for decl_ref in matching_method_decl_refs.clone().into_iter() { let method = check!( - CompileResult::from( - decl_engine.get_function(decl_id.clone(), &decl_id.span()) - ), + CompileResult::from(decl_engine.get_function(&decl_ref, &decl_ref.span())), return err(warnings, errors), warnings, errors @@ -253,24 +251,24 @@ impl Namespace { ) }) { - maybe_method_decl_id = Some(decl_id); + maybe_method_decl_ref = Some(decl_ref); break; } } - if let Some(matching_method_decl_id) = maybe_method_decl_id { + if let Some(matching_method_decl_ref) = maybe_method_decl_ref { // In case one or more methods match the parameter types we return the first match. - Some(matching_method_decl_id) + Some(matching_method_decl_ref) } else { // When we can't match any method with parameter types we still return the first method found // This was the behavior before introducing the parameter type matching - matching_method_decl_ids.get(0).cloned() + matching_method_decl_refs.get(0).cloned() } } Ordering::Less => None, }; - if let Some(method_decl_id) = matching_method_decl_id { - return ok(method_decl_id, warnings, errors); + if let Some(method_decl_ref) = matching_method_decl_ref { + return ok(method_decl_ref, warnings, errors); } if !args_buf @@ -343,7 +341,7 @@ impl Namespace { trait_name: CallPath, trait_type_args: Vec, type_id: TypeId, - methods: &[DeclId], + methods: &[DeclRef], impl_span: &Span, is_impl_self: bool, engines: Engines<'_>, @@ -368,7 +366,7 @@ impl Namespace { engines: Engines<'_>, type_id: TypeId, trait_name: &CallPath, - ) -> Vec { + ) -> Vec { // Use trait name with full path, improves consistency between // this get and inserting in `insert_trait_implementation`. let trait_name = trait_name.to_fullpath(self); diff --git a/sway-core/src/semantic_analysis/namespace/trait_map.rs b/sway-core/src/semantic_analysis/namespace/trait_map.rs index a22a40b189e..295ff9273c7 100644 --- a/sway-core/src/semantic_analysis/namespace/trait_map.rs +++ b/sway-core/src/semantic_analysis/namespace/trait_map.rs @@ -4,7 +4,7 @@ use sway_error::error::CompileError; use sway_types::{Ident, Span, Spanned}; use crate::{ - decl_engine::DeclId, + decl_engine::DeclRef, engine_threading::*, error::*, language::CallPath, @@ -63,7 +63,7 @@ impl OrdWithEngines for TraitKey { } /// Map of function name to [TyFunctionDeclaration](ty::TyFunctionDeclaration) -type TraitMethods = im::HashMap; +type TraitMethods = im::HashMap; #[derive(Clone, Debug)] struct TraitEntry { @@ -98,7 +98,7 @@ impl TraitMap { trait_name: CallPath, trait_type_args: Vec, type_id: TypeId, - methods: &[DeclId], + methods: &[DeclRef], impl_span: &Span, is_impl_self: bool, engines: Engines<'_>, @@ -110,8 +110,8 @@ impl TraitMap { let decl_engine = engines.de(); let mut trait_methods: TraitMethods = im::HashMap::new(); - for decl_id in methods.iter() { - trait_methods.insert(decl_id.name.to_string(), decl_id.clone()); + for decl_ref in methods.iter() { + trait_methods.insert(decl_ref.name.to_string(), decl_ref.clone()); } // check to see if adding this trait will produce a conflicting definition @@ -185,12 +185,12 @@ impl TraitMap { second_impl_span: impl_span.clone(), }); } else if types_are_subset && (traits_are_subset || is_impl_self) { - for (name, decl_id) in trait_methods.iter() { + for (name, decl_ref) in trait_methods.iter() { if map_trait_methods.get(name).is_some() { errors.push(CompileError::DuplicateMethodsDefinedForType { - func_name: decl_id.name.to_string(), + func_name: decl_ref.name.to_string(), type_implementing_for: engines.help_out(type_id).to_string(), - span: decl_id.name.span(), + span: decl_ref.name.span(), }); } } @@ -581,15 +581,15 @@ impl TraitMap { let trait_methods: TraitMethods = map_trait_methods .clone() .into_iter() - .map(|(name, decl_id)| { - let mut decl = decl_engine.get(decl_id.clone()); + .map(|(name, decl_ref)| { + let mut decl = decl_engine.get(&decl_ref); decl.subst(&type_mapping, engines); decl.replace_self_type(engines, new_self_type); ( name, decl_engine - .insert_wrapper(decl_id.name.clone(), decl, decl_id.span()) - .with_parent(decl_engine, decl_id), + .insert_wrapper(decl_ref.name.clone(), decl, decl_ref.span()) + .with_parent(decl_engine, &decl_ref), ) }) .collect(); @@ -618,7 +618,7 @@ impl TraitMap { &self, engines: Engines<'_>, type_id: TypeId, - ) -> Vec { + ) -> Vec { let type_engine = engines.te(); let mut methods = vec![]; // small performance gain in bad case @@ -657,7 +657,7 @@ impl TraitMap { engines: Engines<'_>, type_id: TypeId, trait_name: &CallPath, - ) -> Vec { + ) -> Vec { let type_engine = engines.te(); let mut methods = vec![]; // small performance gain in bad case diff --git a/sway-core/src/semantic_analysis/program.rs b/sway-core/src/semantic_analysis/program.rs index dbfbd8aefcf..c3d88337f3a 100644 --- a/sway-core/src/semantic_analysis/program.rs +++ b/sway-core/src/semantic_analysis/program.rs @@ -9,7 +9,6 @@ use crate::{ Engines, }; use sway_ir::{Context, Module}; -use sway_types::Spanned; impl ty::TyProgram { /// Type-check the given parsed program to produce a typed program. @@ -56,15 +55,15 @@ impl ty::TyProgram { let storage_decl = self .declarations .iter() - .find(|decl| matches!(decl, ty::TyDeclaration::StorageDeclaration(_))); + .find(|decl| matches!(decl, ty::TyDeclaration::StorageDeclaration { .. })); // Expecting at most a single storage declaration match storage_decl { - Some(ty::TyDeclaration::StorageDeclaration(decl_id)) => { + Some(ty::TyDeclaration::StorageDeclaration { + decl_id, decl_span, .. + }) => { let decl = check!( - CompileResult::from( - decl_engine.get_storage(decl_id.clone(), &decl_id.span()) - ), + CompileResult::from(decl_engine.get_storage(decl_id, decl_span)), return err(warnings, errors), warnings, errors diff --git a/sway-core/src/semantic_analysis/storage_only_types.rs b/sway-core/src/semantic_analysis/storage_only_types.rs index 1024d00dbb0..e45544999ca 100644 --- a/sway-core/src/semantic_analysis/storage_only_types.rs +++ b/sway-core/src/semantic_analysis/storage_only_types.rs @@ -184,11 +184,13 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul ); check!(expr_validate(engines, &decl.body), (), warnings, errors) } - ty::TyDeclaration::ConstantDeclaration(decl_id) => { + ty::TyDeclaration::ConstantDeclaration { + decl_id, decl_span, .. + } => { let ty::TyConstantDeclaration { value: expr, name, .. } = check!( - CompileResult::from(decl_engine.get_constant(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_constant(decl_id, decl_span)), return err(warnings, errors), warnings, errors @@ -201,14 +203,16 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul ); check!(expr_validate(engines, &expr), (), warnings, errors) } - ty::TyDeclaration::FunctionDeclaration(decl_id) => { + ty::TyDeclaration::FunctionDeclaration { + decl_id, decl_span, .. + } => { let ty::TyFunctionDeclaration { body, parameters, return_type, .. } = check!( - CompileResult::from(decl_engine.get_function(decl_id.clone(), &decl.span())), + CompileResult::from(decl_engine.get_function(decl_id, decl_span)), return err(warnings, errors), warnings, errors @@ -239,18 +243,20 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul errors ); } - ty::TyDeclaration::AbiDeclaration(_) | ty::TyDeclaration::TraitDeclaration(_) => { + ty::TyDeclaration::AbiDeclaration { .. } | ty::TyDeclaration::TraitDeclaration { .. } => { // These methods are not typed. They are however handled from ImplTrait. } - ty::TyDeclaration::ImplTrait(decl_id) => { + ty::TyDeclaration::ImplTrait { + decl_id, decl_span, .. + } => { let ty::TyImplTrait { methods, span, .. } = check!( - CompileResult::from(decl_engine.get_impl_trait(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_impl_trait(decl_id, decl_span)), return err(warnings, errors), warnings, errors ); - for method_id in methods { - match decl_engine.get_function(method_id, &span) { + for method_ref in methods { + match decl_engine.get_function(&method_ref, &span) { Ok(method) => { check!( validate_decls_for_storage_only_types_in_codeblock( @@ -277,9 +283,11 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul }; } } - ty::TyDeclaration::StructDeclaration(decl_id) => { + ty::TyDeclaration::StructDeclaration { + decl_id, decl_span, .. + } => { let ty::TyStructDeclaration { fields, .. } = check!( - CompileResult::from(decl_engine.get_struct(decl_id.clone(), &decl_id.span())), + CompileResult::from(decl_engine.get_struct(decl_id, decl_span)), return err(warnings, errors), warnings, errors, @@ -298,9 +306,11 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul ); } } - ty::TyDeclaration::EnumDeclaration(decl_id) => { + ty::TyDeclaration::EnumDeclaration { + decl_id, decl_span, .. + } => { let ty::TyEnumDeclaration { variants, .. } = check!( - CompileResult::from(decl_engine.get_enum(decl_id.clone(), &decl.span())), + CompileResult::from(decl_engine.get_enum(decl_id, decl_span)), return err(warnings, errors), warnings, errors @@ -319,9 +329,9 @@ fn decl_validate(engines: Engines<'_>, decl: &ty::TyDeclaration) -> CompileResul ); } } - ty::TyDeclaration::StorageDeclaration(decl_id) => { + ty::TyDeclaration::StorageDeclaration { decl_id, decl_span } => { let ty::TyStorageDeclaration { fields, .. } = check!( - CompileResult::from(decl_engine.get_storage(decl_id.clone(), &decl.span())), + CompileResult::from(decl_engine.get_storage(decl_id, decl_span)), return err(warnings, errors), warnings, errors diff --git a/sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs b/sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs index c503fbd5a9d..d662195215f 100644 --- a/sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs +++ b/sway-core/src/transform/to_parsed_lang/convert_parse_tree.rs @@ -2251,7 +2251,7 @@ fn path_type_to_supertrait( */ let supertrait = Supertrait { name, - decl_id: None, + decl_ref: None, //type_parameters, }; Ok(supertrait) diff --git a/sway-core/src/type_system/binding.rs b/sway-core/src/type_system/binding.rs index db94045a76f..efc0b746ad4 100644 --- a/sway-core/src/type_system/binding.rs +++ b/sway-core/src/type_system/binding.rs @@ -1,17 +1,15 @@ use sway_types::{Span, Spanned}; use crate::{ + decl_engine::*, engine_threading::*, error::*, language::{ty, CallPath}, semantic_analysis::TypeCheckContext, - type_system::EnforceTypeArguments, type_system::*, - CreateTypeId, Ident, TypeInfo, + CreateTypeId, Ident, }; -use super::{TypeArgument, TypeId}; - /// A `TypeBinding` is the result of using turbofish to bind types to /// generic parameters. /// @@ -250,12 +248,14 @@ impl TypeBinding { // monomorphize the declaration, if needed let new_decl = match unknown_decl { - ty::TyDeclaration::FunctionDeclaration(original_id) => { + ty::TyDeclaration::FunctionDeclaration { + decl_id: original_id, + name, + decl_span, + } => { // get the copy from the declaration engine let mut new_copy = check!( - CompileResult::from( - decl_engine.get_function(original_id.clone(), &self.span()) - ), + CompileResult::from(decl_engine.get_function(&original_id, &self.span())), return err(warnings, errors), warnings, errors @@ -277,17 +277,27 @@ impl TypeBinding { } // insert the new copy into the declaration engine - let new_id = ctx + let DeclRef { + id: new_decl_id, .. + } = ctx .decl_engine .insert(new_copy) - .with_parent(ctx.decl_engine, original_id); + .with_parent(ctx.decl_engine, &original_id); - ty::TyDeclaration::FunctionDeclaration(new_id) + ty::TyDeclaration::FunctionDeclaration { + name, + decl_id: new_decl_id, + decl_span, + } } - ty::TyDeclaration::EnumDeclaration(original_id) => { + ty::TyDeclaration::EnumDeclaration { + decl_id: original_id, + name, + decl_span, + } => { // get the copy from the declaration engine let mut new_copy = check!( - CompileResult::from(decl_engine.get_enum(original_id, &self.span())), + CompileResult::from(decl_engine.get_enum(&original_id, &self.span())), return err(warnings, errors), warnings, errors @@ -313,14 +323,24 @@ impl TypeBinding { ); // insert the new copy into the declaration engine - let new_id = ctx.decl_engine.insert(new_copy); - - ty::TyDeclaration::EnumDeclaration(new_id) + let DeclRef { + id: new_decl_id, .. + } = ctx.decl_engine.insert(new_copy); + + ty::TyDeclaration::EnumDeclaration { + name, + decl_id: new_decl_id, + decl_span, + } } - ty::TyDeclaration::StructDeclaration(original_id) => { + ty::TyDeclaration::StructDeclaration { + decl_id: original_id, + name, + decl_span, + } => { // get the copy from the declaration engine let mut new_copy = check!( - CompileResult::from(decl_engine.get_struct(original_id, &self.span())), + CompileResult::from(decl_engine.get_struct(&original_id, &self.span())), return err(warnings, errors), warnings, errors @@ -346,9 +366,15 @@ impl TypeBinding { ); // insert the new copy into the declaration engine - let new_id = ctx.decl_engine.insert(new_copy); - - ty::TyDeclaration::StructDeclaration(new_id) + let DeclRef { + id: new_decl_id, .. + } = ctx.decl_engine.insert(new_copy); + + ty::TyDeclaration::StructDeclaration { + name, + decl_id: new_decl_id, + decl_span, + } } _ => unknown_decl, }; diff --git a/sway-core/src/type_system/engine.rs b/sway-core/src/type_system/engine.rs index f504351d6b1..80de2119cf2 100644 --- a/sway-core/src/type_system/engine.rs +++ b/sway-core/src/type_system/engine.rs @@ -411,11 +411,14 @@ impl TypeEngine { .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::StructDeclaration(original_id)) => { + Some(ty::TyDeclaration::StructDeclaration { + decl_id: original_id, + .. + }) => { // get the copy from the declaration engine let mut new_copy = check!( CompileResult::from( - decl_engine.get_struct(original_id, &call_path.span()) + decl_engine.get_struct(&original_id, &call_path.span()) ), return err(warnings, errors), warnings, @@ -447,11 +450,14 @@ impl TypeEngine { // return the id type_id } - Some(ty::TyDeclaration::EnumDeclaration(original_id)) => { + Some(ty::TyDeclaration::EnumDeclaration { + decl_id: original_id, + .. + }) => { // get the copy from the declaration engine let mut new_copy = check!( CompileResult::from( - decl_engine.get_enum(original_id, &call_path.span()) + decl_engine.get_enum(&original_id, &call_path.span()) ), return err(warnings, errors), warnings, diff --git a/sway-core/src/type_system/trait_constraint.rs b/sway-core/src/type_system/trait_constraint.rs index 82d90f72f8b..3bd7c8c6bb6 100644 --- a/sway-core/src/type_system/trait_constraint.rs +++ b/sway-core/src/type_system/trait_constraint.rs @@ -170,9 +170,9 @@ impl TraitConstraint { .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::TraitDeclaration(decl_id)) => { + Some(ty::TyDeclaration::TraitDeclaration { decl_id, .. }) => { let mut trait_decl = check!( - CompileResult::from(decl_engine.get_trait(decl_id, &trait_name.span())), + CompileResult::from(decl_engine.get_trait(&decl_id, &trait_name.span())), return err(warnings, errors), warnings, errors @@ -218,7 +218,7 @@ impl TraitConstraint { errors ); } - Some(ty::TyDeclaration::AbiDeclaration(_)) => { + Some(ty::TyDeclaration::AbiDeclaration { .. }) => { errors.push(CompileError::AbiAsSupertrait { span: trait_name.span(), }) diff --git a/sway-core/src/type_system/type_parameter.rs b/sway-core/src/type_system/type_parameter.rs index 67e8f96aadf..ab5b3b058db 100644 --- a/sway-core/src/type_system/type_parameter.rs +++ b/sway-core/src/type_system/type_parameter.rs @@ -169,8 +169,8 @@ impl TypeParameter { let mut warnings = vec![]; let mut errors = vec![]; - let mut original_method_ids: MethodMap = BTreeMap::new(); - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut original_method_refs: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); for type_param in type_parameters.iter() { let TypeParameter { @@ -200,20 +200,20 @@ impl TypeParameter { type_arguments: trait_type_arguments, } = trait_constraint; - let (trait_original_method_ids, trait_impld_method_ids) = check!( + let (trait_original_method_refs, trait_impld_method_refs) = check!( handle_trait(ctx.by_ref(), *type_id, trait_name, trait_type_arguments), continue, warnings, errors ); - original_method_ids.extend(trait_original_method_ids); - impld_method_ids.extend(trait_impld_method_ids); + original_method_refs.extend(trait_original_method_refs); + impld_method_refs.extend(trait_impld_method_refs); } } if errors.is_empty() { let decl_mapping = - DeclMapping::from_stub_and_impld_decl_ids(original_method_ids, impld_method_ids); + DeclMapping::from_stub_and_impld_decl_refs(original_method_refs, impld_method_refs); ok(decl_mapping, warnings, errors) } else { err(warnings, errors) @@ -232,8 +232,8 @@ fn handle_trait( let decl_engine = ctx.decl_engine; - let mut original_method_ids: MethodMap = BTreeMap::new(); - let mut impld_method_ids: MethodMap = BTreeMap::new(); + let mut original_method_refs: MethodMap = BTreeMap::new(); + let mut impld_method_refs: MethodMap = BTreeMap::new(); match ctx .namespace @@ -241,15 +241,15 @@ fn handle_trait( .ok(&mut warnings, &mut errors) .cloned() { - Some(ty::TyDeclaration::TraitDeclaration(decl_id)) => { + Some(ty::TyDeclaration::TraitDeclaration { decl_id, .. }) => { let trait_decl = check!( - CompileResult::from(decl_engine.get_trait(decl_id, &trait_name.suffix.span())), + CompileResult::from(decl_engine.get_trait(&decl_id, &trait_name.suffix.span())), return err(warnings, errors), warnings, errors ); - let (trait_original_method_ids, trait_method_ids, trait_impld_method_ids) = check!( + let (trait_original_method_refs, trait_method_refs, trait_impld_method_refs) = check!( trait_decl.retrieve_interface_surface_and_methods_and_implemented_methods_for_type( ctx.by_ref(), type_id, @@ -260,19 +260,19 @@ fn handle_trait( warnings, errors ); - original_method_ids.extend(trait_original_method_ids); - original_method_ids.extend(trait_method_ids); - impld_method_ids.extend(trait_impld_method_ids); + original_method_refs.extend(trait_original_method_refs); + original_method_refs.extend(trait_method_refs); + impld_method_refs.extend(trait_impld_method_refs); for supertrait in trait_decl.supertraits.iter() { - let (supertrait_original_method_ids, supertrait_impld_method_ids) = check!( + let (supertrait_original_method_refs, supertrait_impld_method_refs) = check!( handle_trait(ctx.by_ref(), type_id, &supertrait.name, &[]), continue, warnings, errors ); - original_method_ids.extend(supertrait_original_method_ids); - impld_method_ids.extend(supertrait_impld_method_ids); + original_method_refs.extend(supertrait_original_method_refs); + impld_method_refs.extend(supertrait_impld_method_refs); } } _ => errors.push(CompileError::TraitNotFound { @@ -282,7 +282,7 @@ fn handle_trait( } if errors.is_empty() { - ok((original_method_ids, impld_method_ids), warnings, errors) + ok((original_method_refs, impld_method_refs), warnings, errors) } else { err(warnings, errors) } diff --git a/sway-lsp/src/capabilities/code_actions.rs b/sway-lsp/src/capabilities/code_actions.rs index caf5d78f111..ee6cc5492de 100644 --- a/sway-lsp/src/capabilities/code_actions.rs +++ b/sway-lsp/src/capabilities/code_actions.rs @@ -5,7 +5,6 @@ pub use crate::error::DocumentError; use abi_impl::abi_impl_code_action; use std::sync::Arc; use sway_core::{language::ty::TyDeclaration, Engines}; -use sway_types::Spanned; use tower_lsp::lsp_types::{CodeActionResponse, Range, TextDocumentIdentifier, Url}; pub(crate) fn code_actions( @@ -25,12 +24,9 @@ pub(crate) fn code_actions( maybe_decl .and_then(|decl| match decl { - TyDeclaration::AbiDeclaration(ref decl_id) => Some( - session - .decl_engine - .read() - .get_abi(decl_id.clone(), &decl_id.span()), - ), + TyDeclaration::AbiDeclaration { + decl_id, decl_span, .. + } => Some(session.decl_engine.read().get_abi(&decl_id, &decl_span)), // Add code actions for other declaration types here _ => None, }) diff --git a/sway-lsp/src/capabilities/code_actions/abi_impl.rs b/sway-lsp/src/capabilities/code_actions/abi_impl.rs index d87ada61d78..aadb0f1758b 100644 --- a/sway-lsp/src/capabilities/code_actions/abi_impl.rs +++ b/sway-lsp/src/capabilities/code_actions/abi_impl.rs @@ -64,9 +64,9 @@ fn get_function_signatures(engines: Engines<'_>, abi_decl: TyAbiDeclaration) -> abi_decl .interface_surface .iter() - .filter_map(|function_decl_id| { + .filter_map(|function_decl_ref| { decl_engine - .get_trait_fn(function_decl_id.clone(), &function_decl_id.span()) + .get_trait_fn(function_decl_ref, &function_decl_ref.span()) .ok() .map(|function_decl| { let param_string: String = function_decl diff --git a/sway-lsp/src/capabilities/hover.rs b/sway-lsp/src/capabilities/hover.rs index 7d3348ca3ae..92759223bf3 100644 --- a/sway-lsp/src/capabilities/hover.rs +++ b/sway-lsp/src/capabilities/hover.rs @@ -139,8 +139,8 @@ fn hover_format(engines: Engines<'_>, token: &Token, ident: &Ident) -> lsp_types &token_name, )) } - ty::TyDeclaration::StructDeclaration(decl_id) => decl_engine - .get_struct(decl_id.clone(), &decl.span()) + ty::TyDeclaration::StructDeclaration { decl_id, .. } => decl_engine + .get_struct(decl_id, &decl.span()) .map(|struct_decl| { format_visibility_hover( struct_decl.visibility, @@ -149,8 +149,8 @@ fn hover_format(engines: Engines<'_>, token: &Token, ident: &Ident) -> lsp_types ) }) .ok(), - ty::TyDeclaration::TraitDeclaration(ref decl_id) => decl_engine - .get_trait(decl_id.clone(), &decl.span()) + ty::TyDeclaration::TraitDeclaration { decl_id, .. } => decl_engine + .get_trait(decl_id, &decl.span()) .map(|trait_decl| { format_visibility_hover( trait_decl.visibility, @@ -159,8 +159,8 @@ fn hover_format(engines: Engines<'_>, token: &Token, ident: &Ident) -> lsp_types ) }) .ok(), - ty::TyDeclaration::EnumDeclaration(decl_id) => decl_engine - .get_enum(decl_id.clone(), &decl.span()) + ty::TyDeclaration::EnumDeclaration { decl_id, .. } => decl_engine + .get_enum(decl_id, &decl.span()) .map(|enum_decl| { format_visibility_hover( enum_decl.visibility, diff --git a/sway-lsp/src/core/token_map.rs b/sway-lsp/src/core/token_map.rs index 56300e384be..e0dd23baa6b 100644 --- a/sway-lsp/src/core/token_map.rs +++ b/sway-lsp/src/core/token_map.rs @@ -113,9 +113,9 @@ impl TokenMap { let decl_engine = engines.de(); self.declaration_of_type_id(type_engine, type_id) .and_then(|decl| match decl { - ty::TyDeclaration::StructDeclaration(ref decl_id) => decl_engine - .get_struct(decl_id.clone(), &decl_id.span()) - .ok(), + ty::TyDeclaration::StructDeclaration { + decl_id, decl_span, .. + } => decl_engine.get_struct(&decl_id, &decl_span).ok(), _ => None, }) } diff --git a/sway-lsp/src/traverse/dependency.rs b/sway-lsp/src/traverse/dependency.rs index d310cc97148..ad163bb845b 100644 --- a/sway-lsp/src/traverse/dependency.rs +++ b/sway-lsp/src/traverse/dependency.rs @@ -46,11 +46,11 @@ impl<'a> Dependency<'a> { let ident = match declaration { ty::TyDeclaration::VariableDeclaration(variable) => variable.name.clone(), - ty::TyDeclaration::StructDeclaration(decl_id) - | ty::TyDeclaration::TraitDeclaration(decl_id) - | ty::TyDeclaration::FunctionDeclaration(decl_id) - | ty::TyDeclaration::ConstantDeclaration(decl_id) - | ty::TyDeclaration::EnumDeclaration(decl_id) => decl_id.name.clone(), + ty::TyDeclaration::StructDeclaration { name, .. } + | ty::TyDeclaration::TraitDeclaration { name, .. } + | ty::TyDeclaration::FunctionDeclaration { name, .. } + | ty::TyDeclaration::ConstantDeclaration { name, .. } + | ty::TyDeclaration::EnumDeclaration { name, .. } => name.clone(), _ => return, }; let ident = token::to_ident_key(&ident); diff --git a/sway-lsp/src/traverse/typed_tree.rs b/sway-lsp/src/traverse/typed_tree.rs index bee8d2af001..10ca8778b83 100644 --- a/sway-lsp/src/traverse/typed_tree.rs +++ b/sway-lsp/src/traverse/typed_tree.rs @@ -111,8 +111,10 @@ impl<'a> TypedTree<'a> { self.handle_expression(&variable.body, namespace); } - ty::TyDeclaration::ConstantDeclaration(decl_id) => { - if let Ok(const_decl) = decl_engine.get_constant(decl_id.clone(), &decl_id.span()) { + ty::TyDeclaration::ConstantDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(const_decl) = decl_engine.get_constant(decl_id, decl_span) { if let Some(mut token) = self .tokens .try_get_mut(&to_ident_key(&const_decl.name)) @@ -126,13 +128,17 @@ impl<'a> TypedTree<'a> { self.handle_expression(&const_decl.value, namespace); } } - ty::TyDeclaration::FunctionDeclaration(decl_id) => { - if let Ok(func_decl) = decl_engine.get_function(decl_id.clone(), &decl_id.span()) { + ty::TyDeclaration::FunctionDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(func_decl) = decl_engine.get_function(decl_id, decl_span) { self.collect_typed_fn_decl(&func_decl, namespace); } } - ty::TyDeclaration::TraitDeclaration(decl_id) => { - if let Ok(trait_decl) = decl_engine.get_trait(decl_id.clone(), &decl_id.span()) { + ty::TyDeclaration::TraitDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(trait_decl) = decl_engine.get_trait(decl_id, decl_span) { if let Some(mut token) = self .tokens .try_get_mut(&to_ident_key(&trait_decl.name)) @@ -142,9 +148,9 @@ impl<'a> TypedTree<'a> { token.type_def = Some(TypeDefinition::Ident(trait_decl.name.clone())); } - for trait_fn_decl_id in &trait_decl.interface_surface { - if let Ok(trait_fn) = decl_engine - .get_trait_fn(trait_fn_decl_id.clone(), &trait_fn_decl_id.span()) + for trait_fn_decl_ref in &trait_decl.interface_surface { + if let Ok(trait_fn) = + decl_engine.get_trait_fn(trait_fn_decl_ref, &trait_fn_decl_ref.span()) { self.collect_typed_trait_fn_token(&trait_fn); } @@ -154,10 +160,8 @@ impl<'a> TypedTree<'a> { } } } - ty::TyDeclaration::StructDeclaration(decl_id) => { - if let Ok(struct_decl) = - decl_engine.get_struct(decl_id.clone(), &declaration.span()) - { + ty::TyDeclaration::StructDeclaration { decl_id, .. } => { + if let Ok(struct_decl) = decl_engine.get_struct(decl_id, &declaration.span()) { if let Some(mut token) = self .tokens .try_get_mut(&to_ident_key(&struct_decl.call_path.suffix)) @@ -184,8 +188,10 @@ impl<'a> TypedTree<'a> { } } } - ty::TyDeclaration::EnumDeclaration(decl_id) => { - if let Ok(enum_decl) = decl_engine.get_enum(decl_id.clone(), &decl_id.span()) { + ty::TyDeclaration::EnumDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(enum_decl) = decl_engine.get_enum(decl_id, decl_span) { if let Some(mut token) = self .tokens .try_get_mut(&to_ident_key(&enum_decl.call_path.suffix)) @@ -213,17 +219,19 @@ impl<'a> TypedTree<'a> { } } } - ty::TyDeclaration::ImplTrait(decl_id) => { + ty::TyDeclaration::ImplTrait { + decl_id, decl_span, .. + } => { if let Ok(ty::TyImplTrait { impl_type_parameters, trait_name, trait_type_arguments, - trait_decl_id, + trait_decl_ref, methods, implementing_for_type_id, type_implementing_for_span, .. - }) = decl_engine.get_impl_trait(decl_id.clone(), &decl_id.span()) + }) = decl_engine.get_impl_trait(decl_id, decl_span) { for param in impl_type_parameters { self.collect_type_id( @@ -248,10 +256,8 @@ impl<'a> TypedTree<'a> { .try_unwrap() { token.typed = Some(TypedAstToken::TypedDeclaration(declaration.clone())); - token.type_def = if let Some(decl_id) = &trait_decl_id { - if let Ok(trait_decl) = - decl_engine.get_trait(decl_id.clone(), &decl_id.span()) - { + token.type_def = if let Some(decl_ref) = &trait_decl_ref { + if let Ok(trait_decl) = decl_engine.get_trait(decl_ref, decl_span) { Some(TypeDefinition::Ident(trait_decl.name)) } else { Some(TypeDefinition::TypeId(implementing_for_type_id)) @@ -269,10 +275,8 @@ impl<'a> TypedTree<'a> { ); } - for method_id in methods { - if let Ok(method) = - decl_engine.get_function(method_id.clone(), &decl_id.span()) - { + for method_ref in methods { + if let Ok(method) = decl_engine.get_function(&method_ref, decl_span) { self.collect_typed_fn_decl(&method, namespace); } } @@ -284,8 +288,10 @@ impl<'a> TypedTree<'a> { ); } } - ty::TyDeclaration::AbiDeclaration(decl_id) => { - if let Ok(abi_decl) = decl_engine.get_abi(decl_id.clone(), &decl_id.span()) { + ty::TyDeclaration::AbiDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(abi_decl) = decl_engine.get_abi(decl_id, decl_span) { if let Some(mut token) = self .tokens .try_get_mut(&to_ident_key(&abi_decl.name)) @@ -295,9 +301,9 @@ impl<'a> TypedTree<'a> { token.type_def = Some(TypeDefinition::Ident(abi_decl.name.clone())); } - for trait_fn_decl_id in &abi_decl.interface_surface { - if let Ok(trait_fn) = decl_engine - .get_trait_fn(trait_fn_decl_id.clone(), &trait_fn_decl_id.span()) + for trait_fn_decl_ref in &abi_decl.interface_surface { + if let Ok(trait_fn) = + decl_engine.get_trait_fn(trait_fn_decl_ref, &trait_fn_decl_ref.span()) { self.collect_typed_trait_fn_token(&trait_fn); } @@ -310,9 +316,10 @@ impl<'a> TypedTree<'a> { } } ty::TyDeclaration::ErrorRecovery(_) => {} - ty::TyDeclaration::StorageDeclaration(decl_id) => { - if let Ok(storage_decl) = decl_engine.get_storage(decl_id.clone(), &decl_id.span()) - { + ty::TyDeclaration::StorageDeclaration { + decl_id, decl_span, .. + } => { + if let Ok(storage_decl) = decl_engine.get_storage(decl_id, decl_span) { for field in &storage_decl.fields { if let Some(mut token) = self .tokens @@ -425,7 +432,7 @@ impl<'a> TypedTree<'a> { call_path, contract_call_params, arguments, - function_decl_id, + function_decl_ref, type_binding, .. } => { @@ -436,7 +443,7 @@ impl<'a> TypedTree<'a> { } let implementing_type_name = decl_engine - .get_function(function_decl_id.clone(), &call_path.span()) + .get_function(function_decl_ref, &call_path.span()) .ok() .and_then(|function_decl| function_decl.implementing_type) .and_then(|impl_type| impl_type.get_decl_ident()); @@ -470,7 +477,7 @@ impl<'a> TypedTree<'a> { { token.typed = Some(TypedAstToken::TypedExpression(expression.clone())); if let Ok(function_decl) = - decl_engine.get_function(function_decl_id.clone(), &call_path.span()) + decl_engine.get_function(function_decl_ref, &call_path.span()) { token.type_def = Some(TypeDefinition::Ident(function_decl.name)); } @@ -490,7 +497,7 @@ impl<'a> TypedTree<'a> { } if let Ok(function_decl) = - decl_engine.get_function(function_decl_id.clone(), &call_path.span()) + decl_engine.get_function(function_decl_ref, &call_path.span()) { for node in &function_decl.body.contents { self.traverse_node(node, namespace); @@ -946,9 +953,9 @@ impl<'a> TypedTree<'a> { .try_unwrap() { token.typed = Some(TypedAstToken::TypedSupertrait(supertrait.clone())); - token.type_def = if let Some(decl_id) = &supertrait.decl_id { + token.type_def = if let Some(decl_ref) = &supertrait.decl_ref { let decl_engine = self.engines.de(); - if let Ok(trait_decl) = decl_engine.get_trait(decl_id.clone(), &decl_id.span()) { + if let Ok(trait_decl) = decl_engine.get_trait(decl_ref, &decl_ref.span()) { Some(TypeDefinition::Ident(trait_decl.name)) } else { Some(TypeDefinition::Ident(supertrait.name.suffix.clone())) diff --git a/sway-lsp/src/utils/debug.rs b/sway-lsp/src/utils/debug.rs index 8119ac54b28..6c4e07cacfc 100644 --- a/sway-lsp/src/utils/debug.rs +++ b/sway-lsp/src/utils/debug.rs @@ -69,46 +69,46 @@ pub(crate) fn print_decl_engine_types( .iter() .map(|n| match &n.content { ty::TyAstNodeContent::Declaration(declaration) => match declaration { - ty::TyDeclaration::ConstantDeclaration(decl_id) => { - let const_decl = decl_engine - .get_constant(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::ConstantDeclaration { + decl_id, decl_span, .. + } => { + let const_decl = decl_engine.get_constant(decl_id, decl_span).unwrap(); format!("{const_decl:#?}") } - ty::TyDeclaration::FunctionDeclaration(decl_id) => { - let func_decl = decl_engine - .get_function(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::FunctionDeclaration { + decl_id, decl_span, .. + } => { + let func_decl = decl_engine.get_function(decl_id, decl_span).unwrap(); format!("{func_decl:#?}") } - ty::TyDeclaration::TraitDeclaration(decl_id) => { - let trait_decl = decl_engine - .get_trait(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::TraitDeclaration { + decl_id, decl_span, .. + } => { + let trait_decl = decl_engine.get_trait(decl_id, decl_span).unwrap(); format!("{trait_decl:#?}") } - ty::TyDeclaration::StructDeclaration(decl_id) => { - let struct_decl = decl_engine - .get_struct(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::StructDeclaration { + decl_id, decl_span, .. + } => { + let struct_decl = decl_engine.get_struct(decl_id, decl_span).unwrap(); format!("{struct_decl:#?}") } - ty::TyDeclaration::EnumDeclaration(decl_id) => { - let enum_decl = decl_engine - .get_enum(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::EnumDeclaration { + decl_id, decl_span, .. + } => { + let enum_decl = decl_engine.get_enum(decl_id, decl_span).unwrap(); format!("{enum_decl:#?}") } - ty::TyDeclaration::AbiDeclaration(decl_id) => { - let abi_decl = decl_engine - .get_abi(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::AbiDeclaration { + decl_id, decl_span, .. + } => { + let abi_decl = decl_engine.get_abi(decl_id, decl_span).unwrap(); format!("{abi_decl:#?}") } - ty::TyDeclaration::StorageDeclaration(decl_id) => { - let storage_decl = decl_engine - .get_storage(decl_id.clone(), &decl_id.span()) - .unwrap(); + ty::TyDeclaration::StorageDeclaration { + decl_id, decl_span, .. + } => { + let storage_decl = decl_engine.get_storage(decl_id, decl_span).unwrap(); format!("{storage_decl:#?}") } _ => format!("{declaration:#?}"),