use crate::collections::SharedMap;
use crate::constant;
use crate::program::PRELUDE_PACKAGE_ID;
use rustc_hash::{FxHashMap, FxHashSet};
use std::fmt;
use std::ops::Deref;
use std::slice;
use ecow::EcoString;
use crate::ast::{
Annotation, EnumVariant, Generic, Literal, Span, StructFieldDefinition, StructFields,
Visibility,
};
use crate::types::{
FunctionParameter, Symbol, Type, TypeKind, TypeList, TypeScheme, build_substitution_map,
substitute, type_args_match_params, unqualified_name,
};
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Definition {
pub visibility: Visibility,
pub ty: TypeScheme,
pub name_span: Option<Span>,
pub doc: Option<String>,
pub body: DefinitionBody,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TypeAttribute {
Display,
ClosedDomain,
AnonStruct,
HiddenEmbed,
Serialized,
ZeroSafe,
ZeroUnsafe,
HiddenFields,
Incomparable,
Constraint,
}
impl TypeAttribute {
const fn mask(self) -> u16 {
match self {
Self::Display => 1 << 0,
Self::ClosedDomain => 1 << 1,
Self::AnonStruct => 1 << 2,
Self::HiddenEmbed => 1 << 3,
Self::Serialized => 1 << 4,
Self::ZeroSafe => 1 << 5,
Self::ZeroUnsafe => 1 << 6,
Self::HiddenFields => 1 << 7,
Self::Incomparable => 1 << 8,
Self::Constraint => 1 << 9,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Attributes {
flags: u16,
comparable_arguments: Vec<usize>,
}
impl Attributes {
pub fn insert(&mut self, attribute: TypeAttribute) -> bool {
let mask = attribute.mask();
let was_absent = self.flags & mask == 0;
self.flags |= mask;
was_absent
}
pub fn contains(&self, attribute: &TypeAttribute) -> bool {
self.flags & attribute.mask() != 0
}
pub fn require_comparable_argument(&mut self, position: usize) {
if !self.comparable_arguments.contains(&position) {
self.comparable_arguments.push(position);
}
}
pub fn requires_comparable_argument(&self, position: usize) -> bool {
self.comparable_arguments.contains(&position)
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ValueKind {
Runtime,
Variable,
ConstantDeclaration,
Constant(ConstantValue),
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ConstantValue {
Integer { value: u64, text: Option<String> },
Float { value: f64, text: Option<String> },
Boolean(bool),
String(String),
Char(String),
Evaluated(constant::Value),
}
impl ConstantValue {
pub fn value(&self) -> Option<constant::Value> {
match self {
Self::Evaluated(value) => Some(value.clone()),
literal => constant::literal_value(&literal.to_literal()?),
}
}
pub fn to_literal(&self) -> Option<Literal> {
Some(match self {
Self::Integer { value, text } => Literal::Integer {
value: *value,
text: text.clone(),
},
Self::Float { value, text } => Literal::Float {
value: *value,
text: text.clone(),
},
Self::Boolean(value) => Literal::Boolean(*value),
Self::String(value) => Literal::String {
value: value.clone(),
raw: false,
},
Self::Char(value) => Literal::Char(value.clone()),
Self::Evaluated(_) => return None,
})
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DefinitionBody {
TypeAlias {
generics: Vec<Generic>,
alias: AliasKind,
methods: Methods,
attributes: Attributes,
},
Enum {
generics: Vec<Generic>,
variants: EnumVariants,
methods: Methods,
attributes: Attributes,
default_variant: Option<usize>,
},
Struct {
generics: Vec<Generic>,
fields: StructFields,
methods: Methods,
attributes: Attributes,
},
Interface {
definition: Interface,
},
Value {
kind: ValueKind,
allowed_lints: Vec<String>,
go_hints: Vec<super::GoHint>,
go_name: Option<String>,
go_type_param_recipe: Option<Vec<super::GoTypeRecipe>>,
go_type_terms: Vec<super::GoTypeTerms>,
superseded_by: Option<String>,
impl_receiver: Option<Type>,
},
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AliasKind {
Opaque(Annotation),
Transparent {
annotation: Annotation,
target: Type,
},
}
impl AliasKind {
pub fn annotation(&self) -> &Annotation {
match self {
Self::Opaque(annotation) | Self::Transparent { annotation, .. } => annotation,
}
}
}
impl DefinitionBody {
pub fn value(kind: ValueKind) -> Self {
Self::Value {
kind,
allowed_lints: vec![],
go_hints: vec![],
go_name: None,
go_type_param_recipe: None,
go_type_terms: vec![],
superseded_by: None,
impl_receiver: None,
}
}
pub fn generics(&self) -> Option<&[Generic]> {
match self {
Self::TypeAlias { generics, .. }
| Self::Enum { generics, .. }
| Self::Struct { generics, .. } => Some(generics),
Self::Interface { definition } => Some(&definition.generics),
Self::Value { .. } => None,
}
}
}
impl Definition {
pub fn is_newtype(&self) -> bool {
matches!(
&self.body,
DefinitionBody::Struct {
fields: StructFields::Tuple(fields),
generics,
..
} if fields.len() == 1 && generics.is_empty()
)
}
pub fn newtype_field(&self) -> Option<&Type> {
match &self.body {
DefinitionBody::Struct {
fields: StructFields::Tuple(fields),
..
} if self.is_newtype() => Some(&fields[0].ty),
_ => None,
}
}
pub fn is_pointer_backed_newtype(&self) -> bool {
self.is_newtype()
&& matches!(
&self.body,
DefinitionBody::Struct {
fields: StructFields::Tuple(fields),
..
} if fields[0].ty.is_ref()
)
}
pub fn alias_target(&self) -> Option<&Type> {
match &self.body {
DefinitionBody::TypeAlias {
alias: AliasKind::Transparent { target, .. },
..
} => Some(target),
_ => None,
}
}
pub fn instantiate_alias_target(&self, params: &[Type], writable: bool) -> Option<Type> {
let DefinitionBody::TypeAlias {
generics,
alias: AliasKind::Transparent { target, .. },
..
} = &self.body
else {
return None;
};
let map = build_substitution_map(generics, params);
if writable {
Some(substitute(&target.clone().make_writable(), &map))
} else {
Some(substitute(target, &map))
}
}
pub fn newtype_underlying(&self, writable: bool) -> Option<Type> {
match &self.body {
DefinitionBody::Struct {
fields: StructFields::Tuple(fields),
..
} if self.is_newtype() => Some(if writable {
fields[0].ty.clone()
} else {
fields[0].ty.demoted()
}),
_ => None,
}
}
pub fn constructor_type(&self) -> Option<TypeScheme> {
let DefinitionBody::Struct {
fields: StructFields::Tuple(fields),
generics,
..
} = &self.body
else {
return None;
};
let function = Type::function(
fields
.iter()
.map(|field| FunctionParameter::new(field.ty.clone()))
.collect(),
Default::default(),
self.ty.body.clone().into(),
);
Some(TypeScheme {
vars: generics
.iter()
.map(|generic| generic.name.clone())
.collect(),
body: function,
})
}
pub fn allowed_lints(&self) -> &[String] {
match &self.body {
DefinitionBody::Value { allowed_lints, .. } => allowed_lints,
_ => &[],
}
}
pub fn go_hints(&self) -> &[super::GoHint] {
match &self.body {
DefinitionBody::Value { go_hints, .. } => go_hints,
_ => &[],
}
}
pub fn go_name(&self) -> Option<&str> {
match &self.body {
DefinitionBody::Value { go_name, .. } => go_name.as_deref(),
_ => None,
}
}
pub fn go_type_param_recipe(&self) -> Option<&[super::GoTypeRecipe]> {
match &self.body {
DefinitionBody::Value {
go_type_param_recipe,
..
} => go_type_param_recipe.as_deref(),
_ => None,
}
}
pub fn go_type_terms(&self) -> &[super::GoTypeTerms] {
match &self.body {
DefinitionBody::Value { go_type_terms, .. } => go_type_terms,
_ => &[],
}
}
pub fn impl_receiver(&self) -> Option<&Type> {
match &self.body {
DefinitionBody::Value { impl_receiver, .. } => impl_receiver.as_ref(),
_ => None,
}
}
pub fn superseded_by(&self) -> Option<&str> {
match &self.body {
DefinitionBody::Value { superseded_by, .. } => superseded_by.as_deref(),
_ => None,
}
}
pub fn const_value(&self) -> Option<&ConstantValue> {
match &self.body {
DefinitionBody::Value {
kind: ValueKind::Constant(value),
..
} => Some(value),
_ => None,
}
}
pub fn is_const(&self) -> bool {
matches!(
self.body,
DefinitionBody::Value {
kind: ValueKind::ConstantDeclaration | ValueKind::Constant(_),
..
}
)
}
pub fn is_read_only(&self) -> bool {
self.is_variable() && self.go_hints().contains(&super::GoHint::ReadOnly)
}
pub fn is_variable(&self) -> bool {
matches!(
self.body,
DefinitionBody::Value {
kind: ValueKind::Variable,
..
}
)
}
pub fn methods_mut(&mut self) -> Option<&mut Methods> {
match &mut self.body {
DefinitionBody::Struct { methods, .. } => Some(methods),
DefinitionBody::TypeAlias { methods, .. } => Some(methods),
DefinitionBody::Enum { methods, .. } => Some(methods),
DefinitionBody::Interface { definition } => Some(&mut definition.methods),
DefinitionBody::Value { .. } => None,
}
}
pub fn methods(&self) -> Option<&Methods> {
match &self.body {
DefinitionBody::Struct { methods, .. }
| DefinitionBody::TypeAlias { methods, .. }
| DefinitionBody::Enum { methods, .. } => Some(methods),
DefinitionBody::Interface { definition } => Some(&definition.methods),
DefinitionBody::Value { .. } => None,
}
}
pub fn fields(&self) -> Option<&[StructFieldDefinition]> {
match &self.body {
DefinitionBody::Struct { fields, .. } => Some(fields.as_slice()),
_ => None,
}
}
pub fn is_interface(&self) -> bool {
matches!(self.body, DefinitionBody::Interface { .. })
}
pub fn is_ufcs_method(&self, method: &str) -> bool {
let (methods, base_generics_count) = match &self.body {
DefinitionBody::Struct {
methods, generics, ..
}
| DefinitionBody::Enum {
methods, generics, ..
}
| DefinitionBody::TypeAlias {
methods, generics, ..
} => (methods, generics.len()),
DefinitionBody::Interface { .. } | DefinitionBody::Value { .. } => return false,
};
methods
.get(method)
.is_some_and(|method| is_ufcs_method_type(&method.ty, base_generics_count))
}
fn attributes(&self) -> Option<&Attributes> {
match &self.body {
DefinitionBody::Struct { attributes, .. }
| DefinitionBody::Enum { attributes, .. }
| DefinitionBody::TypeAlias { attributes, .. } => Some(attributes),
DefinitionBody::Interface { definition } => Some(&definition.attributes),
_ => None,
}
}
pub fn is_display(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::Display))
}
pub fn is_zero_safe(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::ZeroSafe))
}
pub fn is_zero_unsafe(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::ZeroUnsafe))
}
pub fn has_hidden_fields(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::HiddenFields))
}
pub fn is_closed_domain(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::ClosedDomain))
}
pub fn is_serialized(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::Serialized))
}
pub fn is_anon_struct(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::AnonStruct))
}
pub fn has_hidden_embed(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::HiddenEmbed))
}
pub fn is_incomparable(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::Incomparable))
}
pub fn requires_comparable_argument(&self, position: usize) -> bool {
self.attributes()
.is_some_and(|a| a.requires_comparable_argument(position))
}
pub fn is_constraint(&self) -> bool {
self.attributes()
.is_some_and(|a| a.contains(&TypeAttribute::Constraint))
}
pub fn is_type_definition(&self) -> bool {
matches!(
self.body,
DefinitionBody::Struct { .. }
| DefinitionBody::Enum { .. }
| DefinitionBody::TypeAlias { .. }
)
}
pub fn is_type_alias(&self) -> bool {
matches!(self.body, DefinitionBody::TypeAlias { .. })
}
pub fn is_value(&self, qualified_name: &str) -> bool {
matches!(self.body, DefinitionBody::Value { .. })
&& self.ty.body.get_qualified_id() != Some(qualified_name)
}
}
fn is_ufcs_method_type(method_ty: &TypeScheme, base_generics_count: usize) -> bool {
let TypeScheme { vars, body } = method_ty;
if vars.is_empty() {
return base_generics_count > 0;
}
if vars.len() > base_generics_count {
return true;
}
if let TypeKind::Function(function) = body.kind()
&& let Some(receiver) = function.params.first()
&& let TypeKind::Nominal {
params: receiver_params,
..
} = receiver.ty.strip_refs().kind()
&& !type_args_match_params(receiver_params, vars.iter())
{
return true;
}
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum MethodOrigin {
Declared,
Synthesized,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Method {
pub source_name: EcoString,
pub ty: TypeScheme,
pub visibility: Visibility,
pub origin: MethodOrigin,
pub name_span: Option<Span>,
pub doc: Option<String>,
pub allowed_lints: Vec<String>,
pub go_hints: Vec<super::GoHint>,
pub superseded_by: Option<String>,
}
impl Method {
pub fn with_type(&self, ty: TypeScheme) -> Self {
Self { ty, ..self.clone() }
}
fn with_receiver_placeholder(mut self) -> Self {
self.ty.body = self.ty.body.with_receiver_placeholder();
self
}
}
pub type Methods = SharedMap<EcoString, Method>;
#[derive(Clone)]
pub struct EnumVariants {
variants: Vec<EnumVariant>,
indices: FxHashMap<EcoString, usize>,
}
impl EnumVariants {
pub fn by_name(&self, name: &str) -> Option<&EnumVariant> {
self.indices.get(name).map(|&index| &self.variants[index])
}
pub fn contains_name(&self, name: &str) -> bool {
self.indices.contains_key(name)
}
}
impl From<Vec<EnumVariant>> for EnumVariants {
fn from(variants: Vec<EnumVariant>) -> Self {
let mut indices = FxHashMap::default();
for (index, variant) in variants.iter().enumerate() {
indices.entry(variant.name.clone()).or_insert(index);
}
Self { variants, indices }
}
}
impl Deref for EnumVariants {
type Target = [EnumVariant];
fn deref(&self) -> &Self::Target {
&self.variants
}
}
impl<'a> IntoIterator for &'a EnumVariants {
type Item = &'a EnumVariant;
type IntoIter = slice::Iter<'a, EnumVariant>;
fn into_iter(self) -> Self::IntoIter {
self.variants.iter()
}
}
impl<'a> IntoIterator for &'a mut EnumVariants {
type Item = &'a mut EnumVariant;
type IntoIter = slice::IterMut<'a, EnumVariant>;
fn into_iter(self) -> Self::IntoIter {
self.variants.iter_mut()
}
}
impl PartialEq for EnumVariants {
fn eq(&self, other: &Self) -> bool {
self.variants == other.variants
}
}
impl fmt::Debug for EnumVariants {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.variants.fmt(f)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for EnumVariants {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.variants.serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for EnumVariants {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Vec::<EnumVariant>::deserialize(deserializer).map(Self::from)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceInstance {
pub ty: Type,
pub parent_of: Option<Symbol>,
}
pub fn interface_instances<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceInstance>
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
fn collect<'d, F>(
interface_ty: &Type,
parent_of: Option<&Symbol>,
lookup: F,
visited: &mut FxHashSet<Type>,
visiting: &mut FxHashSet<Symbol>,
instances: &mut Vec<InterfaceInstance>,
) where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
let resolved = interface_ty.without_spelling();
let TypeKind::Nominal { id, params, .. } = resolved.kind() else {
return;
};
if !visited.insert(resolved.clone()) || !visiting.insert(id.clone()) {
return;
}
let Some(Definition {
body: DefinitionBody::Interface { definition },
..
}) = lookup(id)
else {
visiting.remove(id);
return;
};
let map = build_substitution_map(&definition.generics, params);
instances.push(InterfaceInstance {
ty: resolved.clone(),
parent_of: parent_of.cloned(),
});
for parent in &definition.parents {
collect(
&substitute(parent, &map),
Some(id),
lookup,
visited,
visiting,
instances,
);
}
visiting.remove(id);
}
let mut instances = Vec::new();
collect(
interface_ty,
None,
lookup,
&mut FxHashSet::default(),
&mut FxHashSet::default(),
&mut instances,
);
instances
}
pub struct ConstructorField<'d> {
pub name: &'d EcoString,
pub name_span: Span,
pub declared_ty: &'d Type,
pub ty: Type,
}
pub struct ConstructorFields<'d> {
pub definition: &'d Definition,
pub generics: &'d [Generic],
pub type_args: Vec<Type>,
pub fields: Vec<ConstructorField<'d>>,
}
pub fn constructor_fields<'d, F>(
owner: &str,
variant: Option<&str>,
ty: &Type,
lookup: F,
) -> Option<ConstructorFields<'d>>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let definition = lookup(owner)?;
let type_args = match ty.without_spelling().into_kind() {
TypeKind::Nominal { params, .. } => params,
_ => TypeList::new(),
};
let (generics, declared): (&'d [Generic], Vec<(&'d EcoString, Span, &'d Type)>) =
match (&definition.body, variant) {
(
DefinitionBody::Struct {
generics, fields, ..
},
_,
) => (
generics,
fields
.iter()
.map(|field| (&field.name, field.name_span, &field.ty))
.collect(),
),
(
DefinitionBody::Enum {
generics, variants, ..
},
Some(variant),
) => {
let variant = variants.by_name(unqualified_name(variant))?;
(
generics,
variant
.fields
.iter()
.map(|field| (&field.name, field.name_span, &field.ty))
.collect(),
)
}
_ => return None,
};
let map = build_substitution_map(generics, &type_args);
let fields = declared
.into_iter()
.map(|(name, name_span, declared_ty)| ConstructorField {
name,
name_span,
declared_ty,
ty: substitute(declared_ty, &map),
})
.collect();
Some(ConstructorFields {
definition,
generics,
type_args: type_args.to_vec(),
fields,
})
}
#[derive(Debug, Clone, PartialEq)]
pub struct InterfaceRequirement {
pub declaring_interface: Symbol,
pub parent_of: Option<Symbol>,
pub name: EcoString,
pub method: Method,
pub ty: Type,
}
pub fn interface_requirements<'d, F>(interface_ty: &Type, lookup: F) -> Vec<InterfaceRequirement>
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
let mut requirements = Vec::new();
for instance in interface_instances(interface_ty, lookup) {
let TypeKind::Nominal { id, params, .. } = instance.ty.kind() else {
continue;
};
let Some(Definition {
body: DefinitionBody::Interface { definition },
..
}) = lookup(id)
else {
continue;
};
let map = build_substitution_map(&definition.generics, params);
requirements.extend(
definition
.methods
.iter()
.map(|(name, method)| InterfaceRequirement {
declaring_interface: id.clone(),
parent_of: instance.parent_of.clone(),
name: name.clone(),
method: method.clone(),
ty: substitute(&method.ty.body, &map),
}),
);
}
requirements
}
pub fn methods_for_type<'d, F>(
ty: &Type,
trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
lookup: F,
) -> Methods
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
fn collect<'d, F>(
ty: &Type,
trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
lookup: F,
visited: &mut FxHashSet<String>,
) -> Methods
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
let stripped = ty.strip_refs();
let Some(qualified_name) = method_lookup_key(&stripped) else {
return Methods::default();
};
if !visited.insert(qualified_name.as_str().to_string()) {
return Methods::default();
}
if lookup(&qualified_name)
.is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
{
return interface_requirements(&stripped, lookup)
.into_iter()
.map(|requirement| {
(
requirement.name,
requirement
.method
.with_type(TypeScheme::mono(requirement.ty))
.with_receiver_placeholder(),
)
})
.collect();
}
if let Some(bounds) = trait_bounds.get(&qualified_name) {
return bounds
.iter()
.flat_map(|bound| collect(bound, trait_bounds, lookup, visited))
.collect();
}
lookup(&qualified_name)
.and_then(Definition::methods)
.cloned()
.unwrap_or_default()
}
collect(ty, trait_bounds, lookup, &mut FxHashSet::default())
}
pub fn interface_declares_any_method<'d, F>(interface_ty: &Type, lookup: F) -> bool
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
interface_instances(interface_ty, lookup)
.into_iter()
.any(|instance| {
let TypeKind::Nominal { id, .. } = instance.ty.kind() else {
return false;
};
matches!(
lookup(id),
Some(Definition {
body: DefinitionBody::Interface { definition },
..
}) if !definition.methods.is_empty()
)
})
}
pub fn method_for_type<'d, F>(
ty: &Type,
trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
lookup: F,
wanted: &str,
) -> Option<Method>
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
fn collect<'d, F>(
ty: &Type,
trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
lookup: F,
visited: &mut FxHashSet<Symbol>,
wanted: &str,
) -> Option<Method>
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
let stripped = ty.strip_refs();
let qualified_name = method_lookup_key(&stripped)?;
if !visited.insert(qualified_name.clone()) {
return None;
}
if lookup(&qualified_name)
.is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
{
return interface_requirements(&stripped, lookup)
.into_iter()
.rfind(|requirement| requirement.name == wanted)
.map(|requirement| {
requirement
.method
.with_type(TypeScheme::mono(requirement.ty))
.with_receiver_placeholder()
});
}
if let Some(bounds) = trait_bounds.get(&qualified_name) {
let mut found = None;
for bound in bounds {
if let Some(method) = collect(bound, trait_bounds, lookup, visited, wanted) {
found = Some(method);
}
}
return found;
}
lookup(&qualified_name)
.and_then(Definition::methods)
.and_then(|methods| methods.get(wanted))
.cloned()
}
collect(ty, trait_bounds, lookup, &mut FxHashSet::default(), wanted)
}
pub fn type_has_any_method<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
fn collect<'d, F>(ty: &Type, lookup: F, visited: &mut FxHashSet<Symbol>) -> bool
where
F: Copy + Fn(&str) -> Option<&'d Definition>,
{
let stripped = ty.strip_refs();
let Some(qualified_name) = method_lookup_key(&stripped) else {
return false;
};
if !visited.insert(qualified_name.clone()) {
return false;
}
if lookup(&qualified_name)
.is_some_and(|definition| matches!(definition.body, DefinitionBody::Interface { .. }))
{
return interface_declares_any_method(&stripped, lookup);
}
if lookup(&qualified_name)
.and_then(Definition::methods)
.is_some_and(|methods| !methods.is_empty())
{
return true;
}
false
}
collect(ty, lookup, &mut FxHashSet::default())
}
pub fn method_lookup_key(ty: &Type) -> Option<Symbol> {
match ty.kind() {
TypeKind::Nominal { id, .. } => Some(id.clone()),
TypeKind::Compound { kind, .. } => {
Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name()))
}
TypeKind::Simple(kind) => Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name())),
TypeKind::Array { .. } => Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, "Array")),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Interface {
pub generics: Vec<Generic>,
pub parents: Vec<Type>,
pub methods: Methods,
pub attributes: Attributes,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Symbol;
#[test]
fn attributes_track_independent_flags() {
let mut attributes = Attributes::default();
attributes.insert(TypeAttribute::Display);
attributes.insert(TypeAttribute::Serialized);
assert_eq!(
[
attributes.contains(&TypeAttribute::Display),
attributes.contains(&TypeAttribute::Serialized),
attributes.contains(&TypeAttribute::HiddenFields),
],
[true, true, false]
);
}
#[test]
fn inserting_an_existing_attribute_reports_it_present() {
let mut attributes = Attributes::default();
assert!(attributes.insert(TypeAttribute::Display));
assert!(!attributes.insert(TypeAttribute::Display));
}
fn generic(name: &str) -> Generic {
Generic::new(name, vec![], Span::dummy())
}
fn receiver(params: Vec<Type>) -> Type {
TypeKind::Nominal {
id: Symbol::from_raw("m.Box"),
params: params.into(),
writable: false,
}
.into()
}
fn method(vars: &[&str], receiver: Type) -> TypeScheme {
TypeScheme {
vars: vars.iter().map(|name| EcoString::from(*name)).collect(),
body: Type::function(
vec![FunctionParameter::new(receiver)],
Default::default(),
Box::new(Type::unit()),
),
}
}
fn definition(method_ty: TypeScheme) -> Definition {
Definition {
visibility: Visibility::Public,
ty: TypeScheme {
vars: vec!["T".into()],
body: receiver(vec![Type::parameter("T".into())]),
},
name_span: None,
doc: None,
body: DefinitionBody::Struct {
generics: vec![generic("T")],
fields: StructFields::Record(vec![]),
methods: Methods::from_iter([(
"map".into(),
Method {
source_name: "map".into(),
ty: method_ty,
visibility: Visibility::Public,
origin: MethodOrigin::Declared,
name_span: None,
doc: None,
allowed_lints: vec![],
go_hints: vec![],
superseded_by: None,
},
)]),
attributes: Attributes::default(),
},
}
}
#[test]
fn full_generic_receiver_is_a_selector_method() {
let definition = definition(method(&["T"], receiver(vec![Type::parameter("T".into())])));
assert!(!definition.is_ufcs_method("map"));
}
#[test]
fn extra_method_generic_requires_ufcs() {
let definition = definition(method(
&["T", "U"],
receiver(vec![Type::parameter("T".into())]),
));
assert!(definition.is_ufcs_method("map"));
}
#[test]
fn specialized_receiver_requires_ufcs() {
let definition = definition(method(&["T"], receiver(vec![Type::int()])));
assert!(definition.is_ufcs_method("map"));
}
fn nominal(id: &str) -> Type {
TypeKind::Nominal {
id: Symbol::from_raw(id),
params: TypeList::new(),
writable: false,
}
.into()
}
fn named_method(name: &str, return_type: Type) -> (EcoString, Method) {
let ty = Type::function(
vec![FunctionParameter::new(nominal("m.Receiver"))],
Default::default(),
Box::new(return_type),
);
(
name.into(),
Method {
source_name: name.into(),
ty: TypeScheme::mono(ty),
visibility: Visibility::Public,
origin: MethodOrigin::Declared,
name_span: None,
doc: None,
allowed_lints: vec![],
go_hints: vec![],
superseded_by: None,
},
)
}
fn interface_definition(id: &str, parents: Vec<Type>, methods: Methods) -> Definition {
Definition {
visibility: Visibility::Public,
ty: TypeScheme::mono(nominal(id)),
name_span: None,
doc: None,
body: DefinitionBody::Interface {
definition: Interface {
generics: vec![],
parents,
methods,
attributes: Attributes::default(),
},
},
}
}
fn table(entries: Vec<(&str, Definition)>) -> FxHashMap<String, Definition> {
entries
.into_iter()
.map(|(id, definition)| (id.to_string(), definition))
.collect()
}
fn assert_narrow_matches_broad(
table: &FxHashMap<String, Definition>,
trait_bounds: &FxHashMap<Symbol, Vec<Type>>,
ty: &Type,
name: &str,
) {
let lookup = |id: &str| table.get(id);
let broad = methods_for_type(ty, trait_bounds, lookup)
.get(name)
.cloned();
let narrow = method_for_type(ty, trait_bounds, lookup, name);
assert_eq!(narrow, broad);
}
#[test]
fn a_parent_interface_method_shadows_the_child_declaration() {
let table = table(vec![
(
"m.Child",
interface_definition(
"m.Child",
vec![nominal("m.Parent")],
Methods::from_iter([named_method("run", Type::int())]),
),
),
(
"m.Parent",
interface_definition(
"m.Parent",
vec![],
Methods::from_iter([named_method("run", Type::string())]),
),
),
]);
assert_narrow_matches_broad(&table, &FxHashMap::default(), &nominal("m.Child"), "run");
}
#[test]
fn the_last_bound_that_declares_a_method_wins() {
let table = table(vec![
(
"m.First",
interface_definition(
"m.First",
vec![],
Methods::from_iter([named_method("run", Type::int())]),
),
),
(
"m.Second",
interface_definition(
"m.Second",
vec![],
Methods::from_iter([named_method("run", Type::string())]),
),
),
]);
let trait_bounds = FxHashMap::from_iter([(
Symbol::from_raw("m.T"),
vec![nominal("m.First"), nominal("m.Second")],
)]);
assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
}
fn generic_interface_definition(id: &str, methods: Methods) -> Definition {
Definition {
visibility: Visibility::Public,
ty: TypeScheme::mono(nominal(id)),
name_span: None,
doc: None,
body: DefinitionBody::Interface {
definition: Interface {
generics: vec![generic("T")],
parents: vec![],
methods,
attributes: Attributes::default(),
},
},
}
}
fn instantiated(id: &str, argument: Type) -> Type {
TypeKind::Nominal {
id: Symbol::from_raw(id),
params: vec![argument].into(),
writable: false,
}
.into()
}
#[test]
fn bounds_that_share_a_nominal_key_agree_with_the_whole_method_set() {
let table = table(vec![(
"m.Boxed",
generic_interface_definition(
"m.Boxed",
Methods::from_iter([named_method("run", Type::parameter("T".into()))]),
),
)]);
let trait_bounds = FxHashMap::from_iter([(
Symbol::from_raw("m.T"),
vec![
instantiated("m.Boxed", Type::int()),
instantiated("m.Boxed", Type::string()),
],
)]);
assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
}
#[test]
fn a_self_referential_bound_terminates() {
let table = table(vec![]);
let trait_bounds = FxHashMap::from_iter([(Symbol::from_raw("m.T"), vec![nominal("m.T")])]);
assert_narrow_matches_broad(&table, &trait_bounds, &nominal("m.T"), "run");
}
#[test]
fn an_interface_declares_a_method_through_its_parent() {
let table = table(vec![
(
"m.Child",
interface_definition("m.Child", vec![nominal("m.Parent")], Methods::default()),
),
(
"m.Parent",
interface_definition(
"m.Parent",
vec![],
Methods::from_iter([named_method("run", Type::int())]),
),
),
]);
let lookup = |id: &str| table.get(id);
assert!(interface_declares_any_method(&nominal("m.Child"), lookup));
assert!(type_has_any_method(&nominal("m.Child"), lookup));
}
#[test]
fn an_interface_without_any_declared_method_is_reported_empty() {
let table = table(vec![
(
"m.Child",
interface_definition("m.Child", vec![nominal("m.Parent")], Methods::default()),
),
(
"m.Parent",
interface_definition("m.Parent", vec![], Methods::default()),
),
]);
let lookup = |id: &str| table.get(id);
assert!(!interface_declares_any_method(&nominal("m.Child"), lookup));
assert!(!type_has_any_method(&nominal("m.Child"), lookup));
}
}