Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes find_method_for_type bail out with 1st match #6606

Merged
merged 8 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,12 @@ impl ty::TyFunctionDecl {
} = ty_fn_decl;

// Insert the previously type checked type parameters into the current namespace.
// We insert all type parameter before the constraints because some constraints may depend on the parameters.
for p in type_parameters.iter() {
p.insert_into_namespace_self(handler, ctx.by_ref())?;
}
for p in type_parameters {
p.insert_into_namespace(handler, ctx.by_ref())?;
p.insert_into_namespace_constraints(handler, ctx.by_ref())?;
}

// Insert the previously type checked function parameters into the current namespace.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ impl ty::TyExpression {
arguments: Vec<ty::TyExpression>,
span: Span,
) -> Result<ty::TyExpression, ErrorEmitted> {
let engines = ctx.engines;
let ctx = ctx.with_type_annotation(engines.te().insert(
engines,
TypeInfo::Boolean,
span.source_id(),
));
Self::core_ops(handler, ctx, OpVariant::Equals, arguments, span)
}

Expand All @@ -67,6 +73,12 @@ impl ty::TyExpression {
arguments: Vec<ty::TyExpression>,
span: Span,
) -> Result<ty::TyExpression, ErrorEmitted> {
let engines = ctx.engines;
let ctx = ctx.with_type_annotation(engines.te().insert(
engines,
TypeInfo::Boolean,
span.source_id(),
));
Self::core_ops(handler, ctx, OpVariant::NotEquals, arguments, span)
}

Expand Down
18 changes: 10 additions & 8 deletions sway-core/src/semantic_analysis/namespace/trait_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,7 @@ impl TraitMap {
type_id: TypeId,
) -> Vec<(ResolvedTraitImplItem, TraitKey)> {
let type_engine = engines.te();
let unify_check = UnifyCheck::non_dynamic_equality(engines);
let unify_check = UnifyCheck::non_dynamic_equality(engines).with_unify_ref_mut(false);

let mut items = vec![];
// small performance gain in bad case
Expand Down Expand Up @@ -1298,16 +1298,18 @@ impl TraitMap {
CompileError::MultipleApplicableItemsInScope {
item_name: symbol.as_str().to_string(),
item_kind: "item".to_string(),
type_name: engines.help_out(type_id).to_string(),
as_traits: candidates
.keys()
.map(|k| {
k.clone()
.split("::")
.collect::<Vec<_>>()
.last()
.unwrap()
.to_string()
(
k.clone()
.split("::")
.collect::<Vec<_>>()
.last()
.unwrap()
.to_string(),
engines.help_out(type_id).to_string(),
)
})
.collect::<Vec<_>>(),
span: symbol.span(),
Expand Down
172 changes: 143 additions & 29 deletions sway-core/src/semantic_analysis/type_check_context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#![allow(clippy::mutable_key_type)]
use std::collections::{HashMap, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};

use crate::{
decl_engine::{DeclEngineGet, DeclRefFunction},
Expand Down Expand Up @@ -825,17 +825,40 @@ impl<'a> TypeCheckContext<'a> {
// While collecting unification we don't decay numeric and will ignore this error.
if self.collecting_unifications {
return Err(handler.emit_err(CompileError::MethodNotFound {
method_name: method_name.clone(),
method: method_name.clone().as_str().to_string(),
type_name: self.engines.help_out(type_id).to_string(),
matching_method_strings: vec![],
span: method_name.span(),
}));
}
type_engine.decay_numeric(handler, self.engines, type_id, &method_name.span())?;
}

let matching_item_decl_refs =
let mut matching_item_decl_refs =
self.find_items_for_type(handler, type_id, method_prefix, method_name)?;

// This code path tries to get items of specific implementation of the annotation type that is a superset of type id.
// This allows the following associated method to be found:
// let _: Option<MyStruct<u64>> = MyStruct::try_from(my_u64);
if !matches!(&*type_engine.get(annotation_type), TypeInfo::Unknown)
&& !type_id.is_concrete(self.engines, crate::TreatNumericAs::Concrete)
{
let inner_types =
annotation_type.extract_inner_types(self.engines, crate::IncludeSelf::Yes);
for inner_type_id in inner_types {
if coercion_check.check(inner_type_id, type_id) {
matching_item_decl_refs.extend(self.find_items_for_type(
handler,
inner_type_id,
method_prefix,
method_name,
)?);
}
}
}

let mut matching_method_strings = HashSet::<String>::new();

let matching_method_decl_refs = matching_item_decl_refs
.into_iter()
.flat_map(|item| match item {
Expand All @@ -853,22 +876,40 @@ impl<'a> TypeCheckContext<'a> {
let mut maybe_method_decl_refs: Vec<DeclRefFunction> = vec![];
for decl_ref in matching_method_decl_refs.clone().into_iter() {
let method = decl_engine.get_function(&decl_ref);
if method.parameters.len() == arguments_types.len()
// Contract call methods don't have self parameter.
let args_len_diff = if method.is_contract_call && !arguments_types.is_empty() {
1
} else {
0
};
if method.parameters.len() == arguments_types.len() - args_len_diff
&& method
.parameters
.iter()
.zip(arguments_types.iter())
.all(|(p, a)| coercion_check.check(p.type_argument.type_id, *a))
.zip(arguments_types.iter().skip(args_len_diff))
.all(|(p, a)| coercion_check.check(*a, p.type_argument.type_id))
&& (matches!(&*type_engine.get(annotation_type), TypeInfo::Unknown)
|| coercion_check.check(annotation_type, method.return_type.type_id))
|| matches!(
&*type_engine.get(method.return_type.type_id),
TypeInfo::Never
)
esdrubal marked this conversation as resolved.
Show resolved Hide resolved
|| coercion_check
.with_ignore_generic_names(true)
.check(annotation_type, method.return_type.type_id))
{
maybe_method_decl_refs.push(decl_ref);
}
}

if !maybe_method_decl_refs.is_empty() {
let mut trait_methods =
HashMap::<(CallPath, Vec<WithEngines<TypeArgument>>), DeclRefFunction>::new();
let mut trait_methods = HashMap::<
(
CallPath,
Vec<WithEngines<TypeArgument>>,
Option<WithEngines<TypeInfo>>,
),
DeclRefFunction,
>::new();
let mut impl_self_method = None;
for method_ref in maybe_method_decl_refs.clone() {
let method = decl_engine.get_function(&method_ref);
Expand Down Expand Up @@ -929,6 +970,11 @@ impl<'a> TypeCheckContext<'a> {
.cloned()
.map(|a| self.engines.help_out(a))
.collect::<Vec<_>>(),
method.implementing_for_typeid.map(|t| {
self.engines.help_out(
(*self.engines.te().get(t)).clone(),
)
}),
),
method_ref.clone(),
);
Expand All @@ -938,19 +984,38 @@ impl<'a> TypeCheckContext<'a> {
}
}

let trait_methods_key = (
trait_decl.trait_name.clone(),
trait_decl
.trait_type_arguments
.iter()
.cloned()
.map(|a| self.engines.help_out(a))
.collect::<Vec<_>>(),
method.implementing_for_typeid.map(|t| {
self.engines.help_out((*self.engines.te().get(t)).clone())
}),
);

// If we have: impl<T> FromBytes for T
// and: impl FromBytes for DataPoint
// We pick the second implementation.
if let Some(existing_value) = trait_methods.get(&trait_methods_key) {
let existing_method = decl_engine.get_function(existing_value);
if let Some(ty::TyDecl::ImplSelfOrTrait(existing_impl_trait)) =
existing_method.implementing_type.clone()
{
let existing_trait_decl = decl_engine
.get_impl_self_or_trait(&existing_impl_trait.decl_id);
if existing_trait_decl.impl_type_parameters.is_empty() {
// We already have an impl without type parameters so we skip the others.
skip_insert = true;
}
}
}

if !skip_insert {
trait_methods.insert(
(
trait_decl.trait_name.clone(),
trait_decl
.trait_type_arguments
.iter()
.cloned()
.map(|a| self.engines.help_out(a))
.collect::<Vec<_>>(),
),
method_ref.clone(),
);
trait_methods.insert(trait_methods_key, method_ref.clone());
}
if trait_decl.trait_decl_ref.is_none() {
impl_self_method = Some(method_ref);
Expand Down Expand Up @@ -983,20 +1048,29 @@ impl<'a> TypeCheckContext<'a> {
.collect::<Vec<_>>()
.join(", ")
)
}
},
)
}
let mut trait_strings = trait_methods
.keys()
.map(|t| to_string(t.0.clone(), t.1.clone()))
.collect::<Vec<String>>();
.map(|t| {
(
to_string(t.0.clone(), t.1.clone()),
t.2.clone()
.map(|t| t.to_string())
.or_else(|| {
Some(self.engines().help_out(type_id).to_string())
})
.unwrap(),
)
})
.collect::<Vec<(String, String)>>();
// Sort so the output of the error is always the same.
trait_strings.sort();
return Err(handler.emit_err(
CompileError::MultipleApplicableItemsInScope {
item_name: method_name.as_str().to_string(),
item_kind: "function".to_string(),
type_name: self.engines.help_out(type_id).to_string(),
as_traits: trait_strings,
span: method_name.span(),
},
Expand All @@ -1009,9 +1083,28 @@ impl<'a> TypeCheckContext<'a> {
maybe_method_decl_refs.first().cloned()
}
} 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_refs.first().cloned()
for decl_ref in matching_method_decl_refs.clone().into_iter() {
let method = decl_engine.get_function(&decl_ref);
matching_method_strings.insert(format!(
"{}({}) -> {}{}",
method.name.as_str(),
method
.parameters
.iter()
.map(|p| self.engines.help_out(p.type_argument.type_id).to_string())
.collect::<Vec<_>>()
.join(", "),
self.engines.help_out(method.return_type.type_id),
if let Some(implementing_for_type_id) = method.implementing_for_typeid {
format!(" in {}", self.engines.help_out(implementing_for_type_id))
} else {
"".to_string()
}
));
}

// When we can't match any method with parameter types we will throw an error.
None
}
};

Expand Down Expand Up @@ -1054,9 +1147,30 @@ impl<'a> TypeCheckContext<'a> {
} else {
self.engines.help_out(type_id).to_string()
};

Err(handler.emit_err(CompileError::MethodNotFound {
method_name: method_name.clone(),
method: format!(
"{}({}){}",
method_name.clone(),
arguments_types
.iter()
.map(|a| self.engines.help_out(a).to_string())
.collect::<Vec<_>>()
.join(", "),
if matches!(
*self.engines.te().get(self.type_annotation),
TypeInfo::Unknown
) {
"".to_string()
} else {
format!(" -> {}", self.engines.help_out(self.type_annotation))
}
),
type_name,
matching_method_strings: matching_method_strings
.iter()
.cloned()
.collect::<Vec<_>>(),
span: method_name.span(),
}))
}
Expand Down
14 changes: 1 addition & 13 deletions sway-core/src/type_system/ast_elements/type_parameter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -378,19 +378,7 @@ impl TypeParameter {
Ok(())
}

pub fn insert_into_namespace(
&self,
handler: &Handler,
mut ctx: TypeCheckContext,
) -> Result<(), ErrorEmitted> {
self.insert_into_namespace_constraints(handler, ctx.by_ref())?;

self.insert_into_namespace_self(handler, ctx.by_ref())?;

Ok(())
}

fn insert_into_namespace_constraints(
pub(crate) fn insert_into_namespace_constraints(
&self,
handler: &Handler,
mut ctx: TypeCheckContext,
Expand Down
Loading
Loading