sway_core/language/ty/declaration/
impl_trait.rs

1use super::{TyAbiDecl, TyDeclParsedType, TyTraitDecl, TyTraitItem};
2use crate::{
3    decl_engine::{DeclId, DeclRefMixedInterface, InterfaceDeclId},
4    engine_threading::*,
5    has_changes,
6    language::{parsed::ImplSelfOrTrait, CallPath},
7    type_system::*,
8};
9use serde::{Deserialize, Serialize};
10use std::{
11    fmt::Formatter,
12    hash::{Hash, Hasher},
13};
14use sway_types::{Ident, Named, Span, Spanned};
15
16pub type TyImplItem = TyTraitItem;
17
18/// Self impl, e.g.: `impl<A> Type<A>`,
19/// or trait impl, e.g.: `impl<A, B, C> Trait<A, B> for Type<C>`.
20#[derive(Clone, Debug, Serialize, Deserialize)]
21pub struct TyImplSelfOrTrait {
22    pub impl_type_parameters: Vec<TypeParameter>,
23    pub trait_name: CallPath,
24    pub trait_type_arguments: Vec<GenericArgument>,
25    pub items: Vec<TyImplItem>,
26    pub supertrait_items: Vec<TyImplItem>,
27    pub trait_decl_ref: Option<DeclRefMixedInterface>,
28    pub implementing_for: GenericTypeArgument,
29    pub span: Span,
30}
31
32impl TyImplSelfOrTrait {
33    pub fn is_impl_contract(&self, te: &TypeEngine) -> bool {
34        matches!(&*te.get(self.implementing_for.type_id), TypeInfo::Contract)
35    }
36
37    pub fn is_impl_self(&self) -> bool {
38        self.trait_decl_ref.is_none()
39    }
40
41    pub fn is_impl_trait(&self) -> bool {
42        match &self.trait_decl_ref {
43            Some(decl_ref) => matches!(decl_ref.id(), InterfaceDeclId::Trait(_)),
44            _ => false,
45        }
46    }
47
48    pub fn is_impl_abi(&self) -> bool {
49        match &self.trait_decl_ref {
50            Some(decl_ref) => matches!(decl_ref.id(), InterfaceDeclId::Abi(_)),
51            _ => false,
52        }
53    }
54
55    /// Returns [DeclId] of the trait implemented by `self`, if `self` implements a trait.
56    pub fn implemented_trait_decl_id(&self) -> Option<DeclId<TyTraitDecl>> {
57        match &self.trait_decl_ref {
58            Some(decl_ref) => match &decl_ref.id() {
59                InterfaceDeclId::Trait(decl_id) => Some(*decl_id),
60                InterfaceDeclId::Abi(_) => None,
61            },
62            _ => None,
63        }
64    }
65
66    /// Returns [DeclId] of the ABI implemented by `self`, if `self` implements an ABI for a contract.
67    pub fn implemented_abi_decl_id(&self) -> Option<DeclId<TyAbiDecl>> {
68        match &self.trait_decl_ref {
69            Some(decl_ref) => match &decl_ref.id() {
70                InterfaceDeclId::Abi(decl_id) => Some(*decl_id),
71                InterfaceDeclId::Trait(_) => None,
72            },
73            _ => None,
74        }
75    }
76}
77
78impl TyDeclParsedType for TyImplSelfOrTrait {
79    type ParsedType = ImplSelfOrTrait;
80}
81
82impl Named for TyImplSelfOrTrait {
83    fn name(&self) -> &Ident {
84        &self.trait_name.suffix
85    }
86}
87
88impl Spanned for TyImplSelfOrTrait {
89    fn span(&self) -> Span {
90        self.span.clone()
91    }
92}
93
94impl EqWithEngines for TyImplSelfOrTrait {}
95impl PartialEqWithEngines for TyImplSelfOrTrait {
96    fn eq(&self, other: &Self, ctx: &PartialEqWithEnginesContext) -> bool {
97        self.impl_type_parameters
98            .eq(&other.impl_type_parameters, ctx)
99            && self.trait_name == other.trait_name
100            && self
101                .trait_type_arguments
102                .eq(&other.trait_type_arguments, ctx)
103            && self.items.eq(&other.items, ctx)
104            && self.implementing_for.eq(&other.implementing_for, ctx)
105            && self.trait_decl_ref.eq(&other.trait_decl_ref, ctx)
106    }
107}
108
109impl HashWithEngines for TyImplSelfOrTrait {
110    fn hash<H: Hasher>(&self, state: &mut H, engines: &Engines) {
111        let TyImplSelfOrTrait {
112            impl_type_parameters,
113            trait_name,
114            trait_type_arguments,
115            items,
116            implementing_for,
117            trait_decl_ref,
118            // these fields are not hashed because they aren't relevant/a
119            // reliable source of obj v. obj distinction
120            span: _,
121            supertrait_items: _,
122        } = self;
123        trait_name.hash(state);
124        impl_type_parameters.hash(state, engines);
125        trait_type_arguments.hash(state, engines);
126        items.hash(state, engines);
127        implementing_for.hash(state, engines);
128        trait_decl_ref.hash(state, engines);
129    }
130}
131
132impl SubstTypes for TyImplSelfOrTrait {
133    fn subst_inner(&mut self, ctx: &SubstTypesContext) -> HasChanges {
134        has_changes! {
135            self.impl_type_parameters.subst(ctx);
136            self.implementing_for.subst_inner(ctx);
137            self.items.subst(ctx);
138        }
139    }
140}
141
142impl DebugWithEngines for TyImplSelfOrTrait {
143    fn fmt(&self, f: &mut Formatter<'_>, engines: &Engines) -> std::fmt::Result {
144        if let Some(t) = self.trait_decl_ref.as_ref() {
145            write!(
146                f,
147                "impl<> {:?} for {:?} -> {:?}",
148                t.name().as_str(),
149                engines.help_out(self.implementing_for.initial_type_id),
150                engines.help_out(self.implementing_for.type_id),
151            )
152        } else {
153            write!(
154                f,
155                "impl<> {:?} -> {:?}",
156                engines.help_out(self.implementing_for.initial_type_id),
157                engines.help_out(self.implementing_for.type_id),
158            )
159        }
160    }
161}