use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
use std::borrow::Borrow;
use std::sync::Arc;
use ecow::EcoString;
use crate::ast::Generic;
use crate::program::{Definition, DefinitionBody};
use fmt::Formatter;
use std::fmt;
use std::fmt::Display;
use std::ops::Deref;
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Symbol(EcoString);
impl Symbol {
pub fn from_parts(package: &str, local: &str) -> Self {
let mut s = EcoString::with_capacity(package.len() + 1 + local.len());
s.push_str(package);
s.push('.');
s.push_str(local);
Self(s)
}
pub fn with_segment(&self, segment: &str) -> Self {
let mut s = EcoString::with_capacity(self.0.len() + 1 + segment.len());
s.push_str(&self.0);
s.push('.');
s.push_str(segment);
Self(s)
}
pub fn from_raw(qualified: impl Into<EcoString>) -> Self {
Self(qualified.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_eco(&self) -> &EcoString {
&self.0
}
pub fn last_segment(&self) -> &str {
self.0.rsplit('.').next().unwrap_or(&self.0)
}
pub fn without_last_segment(&self) -> Option<&str> {
self.0.rsplit_once('.').map(|(rest, _)| rest)
}
}
impl Borrow<str> for Symbol {
fn borrow(&self) -> &str {
&self.0
}
}
impl AsRef<str> for Symbol {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Deref for Symbol {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl From<&Symbol> for EcoString {
fn from(s: &Symbol) -> Self {
s.0.clone()
}
}
impl Display for Symbol {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl From<EcoString> for Symbol {
fn from(s: EcoString) -> Self {
Self(s)
}
}
impl From<Symbol> for EcoString {
fn from(s: Symbol) -> Self {
s.0
}
}
impl From<&str> for Symbol {
fn from(s: &str) -> Self {
Self(EcoString::from(s))
}
}
impl From<String> for Symbol {
fn from(s: String) -> Self {
Self(EcoString::from(s))
}
}
impl PartialEq<str> for Symbol {
fn eq(&self, other: &str) -> bool {
self.0.as_str() == other
}
}
impl PartialEq<&str> for Symbol {
fn eq(&self, other: &&str) -> bool {
self.0.as_str() == *other
}
}
pub fn unqualified_name(id: &str) -> &str {
id.rsplit('.').next().unwrap_or(id)
}
pub const GO_IMPORT_PREFIX: &str = "go:";
pub fn package_for_qualified_name<'a, I>(id: &'a str, package_ids: I) -> Option<&'a str>
where
I: IntoIterator<Item = &'a str>,
{
if !id.starts_with(GO_IMPORT_PREFIX) || !id.contains('/') {
return id.split_once('.').map(|(m, _)| m);
}
let mut best: Option<&str> = None;
for package_id in package_ids {
if id.starts_with(package_id)
&& id.as_bytes().get(package_id.len()) == Some(&b'.')
&& best.is_none_or(|prev| package_id.len() > prev.len())
{
best = Some(package_id);
}
}
best
}
fn is_range_type_name(name: &str) -> bool {
matches!(
name,
"Range" | "RangeInclusive" | "RangeFrom" | "RangeTo" | "RangeToInclusive"
)
}
pub fn peel_to_range_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let peeled = peel_alias(ty, lookup);
peeled
.get_name()
.is_some_and(is_range_type_name)
.then_some(peeled)
}
pub type SubstitutionMap = HashMap<EcoString, Type>;
pub fn build_substitution_map(generics: &[Generic], type_args: &[Type]) -> SubstitutionMap {
generics
.iter()
.zip(type_args.iter())
.map(|(g, t)| (g.name.clone(), t.clone()))
.collect()
}
pub fn build_named_substitution_map<'a>(
names: &[EcoString],
type_args: impl IntoIterator<Item = &'a Type>,
) -> SubstitutionMap {
names
.iter()
.zip(type_args)
.map(|(name, ty)| (name.clone(), ty.clone()))
.collect()
}
pub fn type_args_match_params<'a>(
args: &[Type],
params: impl ExactSizeIterator<Item = &'a EcoString>,
) -> bool {
args.len() == params.len()
&& args
.iter()
.zip(params)
.all(|(arg, param)| matches!(arg, Type::Parameter(name) if name == param))
}
pub fn substitute(ty: &Type, map: &HashMap<EcoString, Type>) -> Type {
if map.is_empty() {
return ty.clone();
}
match ty {
Type::Parameter(name) => map.get(name).cloned().unwrap_or_else(|| ty.clone()),
Type::Nominal {
id,
params,
writable,
} => Type::Nominal {
id: id.clone(),
params: params.iter().map(|p| substitute(p, map)).collect(),
writable: *writable,
},
Type::Function(f) => f.rebuild(
f.params
.iter()
.map(|param| param.with_type(substitute(¶m.ty, map)))
.collect(),
f.bounds
.iter()
.map(|b| Bound {
param_name: b.param_name.clone(),
generic: substitute(&b.generic, map),
ty: substitute(&b.ty, map),
})
.collect(),
Box::new(substitute(&f.return_type, map)),
),
Type::Var { .. } | Type::Uninferred | Type::Ignored | Type::Error => ty.clone(),
Type::Forall { vars, body } => {
let has_overlap = map.keys().any(|k| vars.contains(k));
let substituted_body = if has_overlap {
let filtered_map: HashMap<EcoString, Type> = map
.iter()
.filter(|(k, _)| !vars.contains(*k))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
substitute(body, &filtered_map)
} else {
substitute(body, map)
};
Type::Forall {
vars: vars.clone(),
body: Box::new(substituted_body),
}
}
Type::Tuple(elements) => Type::Tuple(elements.iter().map(|e| substitute(e, map)).collect()),
Type::Array { length, element } => Type::Array {
length: *length,
element: Box::new(substitute(element, map)),
},
Type::Compound {
kind,
args,
writable,
} => Type::qualified_compound(
*kind,
args.iter().map(|a| substitute(a, map)).collect(),
*writable,
),
Type::Simple(_) | Type::Never | Type::ImportNamespace(_) | Type::ReceiverPlaceholder => {
ty.clone()
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Bound {
pub param_name: EcoString,
pub generic: Type,
pub ty: Type,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionParameter {
pub ty: Type,
pub name: Option<EcoString>,
pub mutable: bool,
}
impl FunctionParameter {
pub fn new(ty: Type, mutable: bool) -> Self {
Self {
ty,
name: None,
mutable,
}
}
pub fn named(ty: Type, name: Option<EcoString>, mutable: bool) -> Self {
Self { ty, name, mutable }
}
pub fn with_type(&self, ty: Type) -> Self {
Self {
ty,
name: self.name.clone(),
mutable: self.mutable,
}
}
}
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionType {
pub params: Vec<FunctionParameter>,
pub bounds: Vec<Bound>,
pub return_type: Box<Type>,
}
impl PartialEq for FunctionType {
fn eq(&self, other: &Self) -> bool {
self.params.len() == other.params.len()
&& self
.params
.iter()
.zip(&other.params)
.all(|(left, right)| left.ty == right.ty && left.mutable == right.mutable)
&& self.bounds == other.bounds
&& self.return_type == other.return_type
}
}
impl FunctionType {
pub fn remove_receiver(&mut self) -> Type {
self.params.remove(0).ty
}
pub fn without_receiver(&self) -> Type {
let mut stripped = self.clone();
if !stripped.params.is_empty() {
stripped.remove_receiver();
}
Type::Function(Arc::new(stripped))
}
pub fn rebuild(
&self,
params: Vec<FunctionParameter>,
bounds: Vec<Bound>,
return_type: Box<Type>,
) -> Type {
Type::function(params, bounds, return_type)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TypeVarId(u32);
impl TypeVarId {
pub const fn new(index: u32) -> Self {
Self(index)
}
pub const fn index(self) -> u32 {
self.0
}
}
impl fmt::Debug for TypeVarId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Type {
Simple(SimpleKind),
Compound {
kind: CompoundKind,
args: Vec<Type>,
writable: bool,
},
Nominal {
id: Symbol,
params: Vec<Type>,
writable: bool,
},
ImportNamespace(EcoString),
Function(Arc<FunctionType>),
Var {
id: TypeVarId,
hint: Option<EcoString>,
},
Uninferred,
Ignored,
Forall {
vars: Vec<EcoString>,
body: Box<Type>,
},
Parameter(EcoString),
Never,
Tuple(Vec<Type>),
Array {
length: u64,
element: Box<Type>,
},
Error,
ReceiverPlaceholder,
}
struct TypePlaceholder(&'static str);
impl fmt::Debug for TypePlaceholder {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl fmt::Debug for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Type::Nominal {
id,
params,
writable,
} => {
let mut s = f.debug_struct("Nominal");
s.field("id", id).field("params", params);
if *writable {
s.field("writable", writable);
}
s.finish()
}
Type::Function(f_ty) => {
let mut s = f.debug_struct("Function");
s.field("params", &f_ty.params)
.field("bounds", &f_ty.bounds)
.field("return_type", &f_ty.return_type)
.finish()
}
Type::Var { id, hint } => {
let mut s = f.debug_struct("Var");
s.field("id", id);
if let Some(h) = hint {
s.field("hint", h);
}
s.finish()
}
Type::Uninferred => f
.debug_struct("Var")
.field("id", &TypePlaceholder("uninferred"))
.finish(),
Type::Ignored => f
.debug_struct("Var")
.field("id", &TypePlaceholder("ignored"))
.finish(),
Type::Forall { vars, body } => f
.debug_struct("Forall")
.field("vars", vars)
.field("body", body)
.finish(),
Type::Parameter(name) => f.debug_tuple("Parameter").field(name).finish(),
Type::Never => write!(f, "Never"),
Type::Tuple(elements) => f.debug_tuple("Tuple").field(elements).finish(),
Type::Array { length, element } => f
.debug_struct("Array")
.field("length", length)
.field("element", element)
.finish(),
Type::Error => write!(f, "Error"),
Type::ImportNamespace(package_id) => {
f.debug_tuple("ImportNamespace").field(package_id).finish()
}
Type::ReceiverPlaceholder => write!(f, "ReceiverPlaceholder"),
Type::Simple(kind) => f.debug_tuple("Simple").field(kind).finish(),
Type::Compound {
kind,
args,
writable,
} => {
let mut s = f.debug_struct("Compound");
s.field("kind", kind).field("args", args);
if *writable {
s.field("writable", writable);
}
s.finish()
}
}
}
}
impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
Type::Nominal {
id: id1,
params: params1,
writable: w1,
},
Type::Nominal {
id: id2,
params: params2,
writable: w2,
},
) => id1 == id2 && params1 == params2 && w1 == w2,
(Type::Function(f1), Type::Function(f2)) => f1 == f2,
(Type::Var { id: id1, .. }, Type::Var { id: id2, .. }) => id1 == id2,
(Type::Uninferred, Type::Uninferred) | (Type::Ignored, Type::Ignored) => true,
(
Type::Forall {
vars: vars1,
body: body1,
},
Type::Forall {
vars: vars2,
body: body2,
},
) => vars1 == vars2 && body1 == body2,
(Type::Parameter(name1), Type::Parameter(name2)) => name1 == name2,
(Type::Never, Type::Never) => true,
(Type::Tuple(elems1), Type::Tuple(elems2)) => elems1 == elems2,
(
Type::Array {
length: length1,
element: element1,
},
Type::Array {
length: length2,
element: element2,
},
) => length1 == length2 && element1 == element2,
(Type::ImportNamespace(m1), Type::ImportNamespace(m2)) => m1 == m2,
(Type::ReceiverPlaceholder, Type::ReceiverPlaceholder) => true,
(Type::Simple(k1), Type::Simple(k2)) => k1 == k2,
(
Type::Compound {
kind: k1,
args: a1,
writable: w1,
},
Type::Compound {
kind: k2,
args: a2,
writable: w2,
},
) => k1 == k2 && a1 == a2 && w1 == w2,
_ => false,
}
}
}
impl Type {
fn simple(kind: SimpleKind) -> Type {
Self::Simple(kind)
}
pub fn compound(kind: CompoundKind, args: Vec<Type>) -> Type {
Self::qualified_compound(kind, args, false)
}
pub fn qualified_compound(kind: CompoundKind, args: Vec<Type>, writable: bool) -> Type {
debug_assert!(
!writable || kind.carries_write_permission(),
"writable flag is restricted to Slice, Map, and Ref"
);
let args = if kind.carries_write_permission()
&& !writable
&& args.iter().any(Type::contains_write_permission)
{
args.iter().map(Type::demoted).collect()
} else {
args
};
Self::Compound {
kind,
args,
writable,
}
}
fn contains_write_permission(&self) -> bool {
match self {
Type::Compound { args, writable, .. } => {
*writable || args.iter().any(Type::contains_write_permission)
}
Type::Nominal {
params, writable, ..
} => *writable || params.iter().any(Type::contains_write_permission),
Type::Tuple(elements) => elements.iter().any(Type::contains_write_permission),
Type::Array { element, .. } => element.contains_write_permission(),
_ => false,
}
}
pub fn is_writable(&self) -> bool {
matches!(
self,
Type::Compound { writable: true, .. } | Type::Nominal { writable: true, .. }
)
}
pub fn make_writable(self) -> Type {
match self {
Type::Compound { kind, args, .. } if kind.carries_write_permission() => {
Type::qualified_compound(kind, args, true)
}
Type::Nominal { id, params, .. } => Type::Nominal {
id,
params,
writable: true,
},
other => other,
}
}
pub fn demoted(&self) -> Type {
match self {
Type::Compound {
kind,
args,
writable: _,
} => Type::Compound {
kind: *kind,
args: args.iter().map(Type::demoted).collect(),
writable: false,
},
Type::Nominal {
id,
params,
writable: _,
} => Type::Nominal {
id: id.clone(),
params: params.iter().map(Type::demoted).collect(),
writable: false,
},
Type::Tuple(elements) => Type::Tuple(elements.iter().map(Type::demoted).collect()),
Type::Array { length, element } => Type::Array {
length: *length,
element: Box::new(element.demoted()),
},
_ => self.clone(),
}
}
pub fn function(
params: Vec<FunctionParameter>,
bounds: Vec<Bound>,
return_type: Box<Type>,
) -> Type {
Type::Function(Arc::new(FunctionType {
params,
bounds,
return_type,
}))
}
pub fn int() -> Type {
Self::simple(SimpleKind::Int)
}
pub fn string() -> Type {
Self::simple(SimpleKind::String)
}
pub fn bool() -> Type {
Self::simple(SimpleKind::Bool)
}
pub fn unit() -> Type {
Self::simple(SimpleKind::Unit)
}
}
impl Type {
pub fn uninferred() -> Self {
Self::Uninferred
}
pub fn is_uninferred(&self) -> bool {
matches!(self, Self::Uninferred)
}
pub fn ignored() -> Self {
Self::Ignored
}
pub fn get_type_params(&self) -> Option<&[Type]> {
match self {
Type::Nominal { params, .. } => Some(params),
Type::Compound { args, .. } => Some(args),
_ => None,
}
}
pub fn children(&self) -> Vec<&Type> {
match self {
Type::Nominal { params, .. } => params.iter().collect(),
Type::Compound { args, .. } => args.iter().collect(),
Type::Function(f) => {
let mut c: Vec<&Type> = f.params.iter().map(|param| ¶m.ty).collect();
c.push(&f.return_type);
c
}
Type::Tuple(elements) => elements.iter().collect(),
Type::Array { element, .. } => vec![element],
Type::Forall { body, .. } => vec![body],
_ => vec![],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericFamily {
SignedInt,
UnsignedInt,
Float,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CompoundKind {
Ref,
Slice,
EnumeratedSlice,
Map,
Channel,
Sender,
Receiver,
VarArgs,
}
impl CompoundKind {
pub fn carries_write_permission(self) -> bool {
matches!(
self,
CompoundKind::Slice | CompoundKind::Map | CompoundKind::Ref
)
}
pub fn leaf_name(self) -> &'static str {
match self {
CompoundKind::Ref => "Ref",
CompoundKind::Slice => "Slice",
CompoundKind::EnumeratedSlice => "EnumeratedSlice",
CompoundKind::Map => "Map",
CompoundKind::Channel => "Channel",
CompoundKind::Sender => "Sender",
CompoundKind::Receiver => "Receiver",
CompoundKind::VarArgs => "VarArgs",
}
}
pub fn from_name(name: &str) -> Option<CompoundKind> {
Some(match name {
"Ref" => CompoundKind::Ref,
"Slice" => CompoundKind::Slice,
"EnumeratedSlice" => CompoundKind::EnumeratedSlice,
"Map" => CompoundKind::Map,
"Channel" => CompoundKind::Channel,
"Sender" => CompoundKind::Sender,
"Receiver" => CompoundKind::Receiver,
"VarArgs" => CompoundKind::VarArgs,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SimpleKind {
Int,
Int8,
Int16,
Int32,
Int64,
Uint,
Uint8,
Uint16,
Uint32,
Uint64,
Uintptr,
Byte,
Float32,
Float64,
Complex64,
Complex128,
Rune,
Bool,
String,
Unit,
}
impl SimpleKind {
pub fn leaf_name(self) -> &'static str {
match self {
SimpleKind::Int => "int",
SimpleKind::Int8 => "int8",
SimpleKind::Int16 => "int16",
SimpleKind::Int32 => "int32",
SimpleKind::Int64 => "int64",
SimpleKind::Uint => "uint",
SimpleKind::Uint8 => "uint8",
SimpleKind::Uint16 => "uint16",
SimpleKind::Uint32 => "uint32",
SimpleKind::Uint64 => "uint64",
SimpleKind::Uintptr => "uintptr",
SimpleKind::Byte => "byte",
SimpleKind::Float32 => "float32",
SimpleKind::Float64 => "float64",
SimpleKind::Complex64 => "complex64",
SimpleKind::Complex128 => "complex128",
SimpleKind::Rune => "rune",
SimpleKind::Bool => "bool",
SimpleKind::String => "string",
SimpleKind::Unit => "Unit",
}
}
pub fn from_name(name: &str) -> Option<SimpleKind> {
Some(match name {
"int" => SimpleKind::Int,
"int8" => SimpleKind::Int8,
"int16" => SimpleKind::Int16,
"int32" => SimpleKind::Int32,
"int64" => SimpleKind::Int64,
"uint" => SimpleKind::Uint,
"uint8" => SimpleKind::Uint8,
"uint16" => SimpleKind::Uint16,
"uint32" => SimpleKind::Uint32,
"uint64" => SimpleKind::Uint64,
"uintptr" => SimpleKind::Uintptr,
"byte" => SimpleKind::Byte,
"float32" => SimpleKind::Float32,
"float64" => SimpleKind::Float64,
"complex64" => SimpleKind::Complex64,
"complex128" => SimpleKind::Complex128,
"rune" => SimpleKind::Rune,
"bool" => SimpleKind::Bool,
"string" => SimpleKind::String,
"Unit" => SimpleKind::Unit,
_ => return None,
})
}
pub fn is_arithmetic(self) -> bool {
!matches!(
self,
SimpleKind::Bool | SimpleKind::String | SimpleKind::Unit | SimpleKind::Uintptr
)
}
pub fn is_ordered(self) -> bool {
self.is_arithmetic() && !matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
}
pub fn integer_range(self) -> Option<(i128, i128)> {
use SimpleKind::*;
Some(match self {
Int8 => (i8::MIN as i128, i8::MAX as i128),
Int16 => (i16::MIN as i128, i16::MAX as i128),
Int32 | Rune => (i32::MIN as i128, i32::MAX as i128),
Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
Uint8 | Byte => (0, u8::MAX as i128),
Uint16 => (0, u16::MAX as i128),
Uint32 => (0, u32::MAX as i128),
Uint | Uint64 | Uintptr => (0, u64::MAX as i128),
_ => return None,
})
}
pub fn is_unsigned_int(self) -> bool {
matches!(
self,
SimpleKind::Byte
| SimpleKind::Uint
| SimpleKind::Uint8
| SimpleKind::Uint16
| SimpleKind::Uint32
| SimpleKind::Uint64
)
}
pub fn is_signed_int(self) -> bool {
matches!(
self,
SimpleKind::Int
| SimpleKind::Int8
| SimpleKind::Int16
| SimpleKind::Int32
| SimpleKind::Int64
| SimpleKind::Rune
)
}
pub fn is_float(self) -> bool {
matches!(self, SimpleKind::Float32 | SimpleKind::Float64)
}
fn is_complex(self) -> bool {
matches!(self, SimpleKind::Complex64 | SimpleKind::Complex128)
}
fn numeric_family(self) -> Option<NumericFamily> {
if self.is_signed_int() {
Some(NumericFamily::SignedInt)
} else if self.is_unsigned_int() {
Some(NumericFamily::UnsignedInt)
} else if self.is_float() {
Some(NumericFamily::Float)
} else {
None
}
}
}
impl Type {
pub fn get_function_ret(&self) -> Option<&Type> {
match self {
Type::Function(f) => Some(&f.return_type),
_ => None,
}
}
pub fn is_stringer_signature(&self) -> bool {
let func = match self {
Type::Forall { body, .. } => body.as_ref(),
other => other,
};
matches!(
func,
Type::Function(f)
if f.params.len() == 1
&& matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::String))
)
}
pub fn is_equals_signature(&self) -> bool {
let func = match self {
Type::Forall { body, .. } => body.as_ref(),
other => other,
};
matches!(
func,
Type::Function(f)
if f.params.len() == 2
&& matches!(f.return_type.as_ref(), Type::Simple(SimpleKind::Bool))
&& f.params[0].ty == f.params[1].ty
&& !f.params[0].ty.is_ref()
)
}
pub fn is_equals_bound_signature(&self, param_name: &str) -> bool {
let func = match self {
Type::Forall { body, .. } => body.as_ref(),
other => other,
};
matches!(
func,
Type::Function(f)
if f.params.len() == 1
&& f.return_type.is_boolean()
&& matches!(&f.params[0].ty, Type::Parameter(name) if name.as_str() == param_name)
)
}
pub fn equals_receiver_vars(&self, owner_id: &str, arity: usize) -> Option<Vec<EcoString>> {
if !self.is_equals_signature() {
return None;
}
let (quantified, func): (&[EcoString], &Type) = match self {
Type::Forall { vars, body } => (vars, body.as_ref()),
other => (&[], other),
};
if quantified.len() != arity {
return None;
}
let Type::Function(f) = func else {
return None;
};
let Type::Nominal { id, params, .. } = &f.params[0].ty else {
return None;
};
if id.as_str() != owner_id || params.len() != arity {
return None;
}
let mut vars = Vec::with_capacity(arity);
for param in params {
let Type::Parameter(name) = param else {
return None;
};
if vars.contains(name) {
return None;
}
vars.push(name.clone());
}
if !quantified.iter().all(|v| vars.contains(v)) {
return None;
}
Some(vars)
}
pub fn has_name(&self, name: &str) -> bool {
match self {
Type::Nominal { id, .. } => id.last_segment() == name,
Type::Simple(kind) => kind.leaf_name() == name,
Type::Compound { kind, .. } => kind.leaf_name() == name,
_ => false,
}
}
pub fn get_qualified_id(&self) -> Option<&str> {
match self {
Type::Nominal { id, .. } => Some(id.as_str()),
_ => None,
}
}
pub fn is_result(&self) -> bool {
self.has_qualified_id("prelude.Result")
}
pub fn is_option(&self) -> bool {
self.has_qualified_id("prelude.Option")
}
pub fn is_partial(&self) -> bool {
self.has_qualified_id("prelude.Partial")
}
fn has_qualified_id(&self, qualified_id: &str) -> bool {
matches!(self, Type::Nominal { id, .. } if id.as_str() == qualified_id)
}
pub fn is_unit(&self) -> bool {
self.is_simple(SimpleKind::Unit)
}
pub fn tuple_arity(&self) -> Option<usize> {
match self {
Type::Tuple(elements) => Some(elements.len()),
_ => None,
}
}
pub fn is_tuple(&self) -> bool {
matches!(self, Type::Tuple(_))
}
pub fn array_len(&self) -> Option<u64> {
match self {
Type::Array { length, .. } => Some(*length),
_ => None,
}
}
pub fn as_import_namespace(&self) -> Option<&str> {
match self {
Type::ImportNamespace(package_id) => Some(package_id),
_ => None,
}
}
pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
match self {
Type::Compound { kind, args, .. } => Some((*kind, args.as_slice())),
_ => None,
}
}
pub fn is_native(&self, kind: CompoundKind) -> bool {
self.as_compound().is_some_and(|(k, _)| k == kind)
}
pub fn is_ref(&self) -> bool {
self.is_native(CompoundKind::Ref)
}
pub fn is_slice(&self) -> bool {
self.is_native(CompoundKind::Slice)
}
pub fn is_map(&self) -> bool {
self.is_native(CompoundKind::Map)
}
pub fn is_channel(&self) -> bool {
self.is_native(CompoundKind::Channel)
}
pub fn is_receiver_placeholder(&self) -> bool {
matches!(self, Type::ReceiverPlaceholder)
}
pub fn is_unknown(&self) -> bool {
self.has_name("Unknown")
}
pub fn is_receiver(&self) -> bool {
self.is_native(CompoundKind::Receiver)
}
pub fn is_ignored(&self) -> bool {
matches!(self, Type::Ignored)
}
pub fn is_placeholder(&self) -> bool {
matches!(self, Type::Uninferred | Type::Ignored)
}
pub fn is_variadic(&self) -> Option<Type> {
let last = self.get_function_params()?.last()?;
match last.ty.as_compound()? {
(CompoundKind::VarArgs, _) => last.ty.inner(),
_ => None,
}
}
pub fn is_string(&self) -> bool {
self.is_simple(SimpleKind::String)
}
fn is_slice_of_simple(&self, element: SimpleKind) -> bool {
match self.as_compound() {
Some((CompoundKind::Slice, [elem])) => elem.is_simple(element),
_ => false,
}
}
pub fn is_byte_slice(&self) -> bool {
self.is_slice_of_simple(SimpleKind::Byte) || self.is_slice_of_simple(SimpleKind::Uint8)
}
fn is_rune_slice(&self) -> bool {
self.is_slice_of_simple(SimpleKind::Rune)
}
fn is_byte_or_rune_slice(&self) -> bool {
self.is_byte_slice() || self.is_rune_slice()
}
pub fn as_simple(&self) -> Option<SimpleKind> {
match self {
Type::Simple(kind) => Some(*kind),
_ => None,
}
}
pub fn is_simple(&self, kind: SimpleKind) -> bool {
self.as_simple() == Some(kind)
}
pub fn is_boolean(&self) -> bool {
self.is_simple(SimpleKind::Bool)
}
pub fn is_rune(&self) -> bool {
self.is_simple(SimpleKind::Rune)
}
pub fn is_float(&self) -> bool {
self.as_simple().is_some_and(SimpleKind::is_float)
}
pub fn is_variable(&self) -> bool {
matches!(self, Type::Var { .. })
}
pub fn is_structural_alias_body(&self) -> bool {
matches!(
self,
Type::Simple(_) | Type::Compound { .. } | Type::Array { .. } | Type::Tuple(_)
)
}
pub fn is_numeric(&self) -> bool {
self.as_simple().is_some_and(SimpleKind::is_arithmetic)
}
pub fn is_complex(&self) -> bool {
self.as_simple().is_some_and(SimpleKind::is_complex)
}
pub fn is_unsigned_int(&self) -> bool {
self.as_simple().is_some_and(SimpleKind::is_unsigned_int)
}
pub fn is_never(&self) -> bool {
matches!(self, Type::Never)
}
pub fn is_error(&self) -> bool {
matches!(self, Type::Error)
}
pub fn contains_error(&self) -> bool {
match self {
Type::Error => true,
Type::Nominal { params, .. } => params.iter().any(Type::contains_error),
Type::Compound { args, .. } => args.iter().any(Type::contains_error),
Type::Function(f) => {
f.params.iter().any(|param| param.ty.contains_error())
|| f.return_type.contains_error()
}
Type::Tuple(elements) => elements.iter().any(Type::contains_error),
Type::Array { element, .. } => element.contains_error(),
Type::Forall { body, .. } => body.contains_error(),
_ => false,
}
}
pub fn has_unbound_variables(&self) -> bool {
match self {
Type::Var { hint, .. } => hint.is_some(),
Type::Nominal { params, .. } => params.iter().any(|p| p.has_unbound_variables()),
Type::Function(f) => {
f.params.iter().any(|p| p.ty.has_unbound_variables())
|| f.return_type.has_unbound_variables()
}
Type::Forall { body, .. } => body.has_unbound_variables(),
Type::Tuple(elements) => elements.iter().any(|e| e.has_unbound_variables()),
Type::Array { element, .. } => element.has_unbound_variables(),
Type::Compound { args, .. } => args.iter().any(|a| a.has_unbound_variables()),
Type::Simple(_)
| Type::Parameter(_)
| Type::Never
| Type::Uninferred
| Type::Ignored
| Type::Error
| Type::ImportNamespace(_)
| Type::ReceiverPlaceholder => false,
}
}
pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
match self {
Type::Var { id, hint } => {
if hint.is_some() {
out.push(*id);
}
}
Type::Nominal { params, .. } => {
for p in params {
p.collect_unbound_variables(out);
}
}
Type::Function(f) => {
for p in &f.params {
p.ty.collect_unbound_variables(out);
}
f.return_type.collect_unbound_variables(out);
}
Type::Forall { body, .. } => body.collect_unbound_variables(out),
Type::Tuple(elements) => {
for e in elements {
e.collect_unbound_variables(out);
}
}
Type::Array { element, .. } => element.collect_unbound_variables(out),
Type::Compound { args, .. } => {
for a in args {
a.collect_unbound_variables(out);
}
}
Type::Simple(_)
| Type::Parameter(_)
| Type::Never
| Type::Uninferred
| Type::Ignored
| Type::Error
| Type::ImportNamespace(_)
| Type::ReceiverPlaceholder => {}
}
}
pub fn remove_found_type_names(&self, names: &mut HashSet<EcoString>) {
if names.is_empty() {
return;
}
match self {
Type::Nominal { id, params, .. } => {
names.remove(id.last_segment());
for param in params {
param.remove_found_type_names(names);
}
}
Type::Function(f) => {
for param in &f.params {
param.ty.remove_found_type_names(names);
}
f.return_type.remove_found_type_names(names);
for bound in &f.bounds {
bound.generic.remove_found_type_names(names);
bound.ty.remove_found_type_names(names);
}
}
Type::Forall { body, .. } => {
body.remove_found_type_names(names);
}
Type::Var { .. } => {}
Type::Parameter(name) => {
names.remove(name);
}
Type::Tuple(elements) => {
for element in elements {
element.remove_found_type_names(names);
}
}
Type::Compound { kind, args, .. } => {
names.remove(kind.leaf_name());
for arg in args {
arg.remove_found_type_names(names);
}
}
Type::Array { element, .. } => {
names.remove("Array");
element.remove_found_type_names(names);
}
Type::Simple(kind) => {
names.remove(kind.leaf_name());
}
Type::Never
| Type::Uninferred
| Type::Ignored
| Type::Error
| Type::ImportNamespace(_)
| Type::ReceiverPlaceholder => {}
}
}
}
impl Type {
pub fn get_name(&self) -> Option<&str> {
match self {
Type::Simple(kind) => Some(kind.leaf_name()),
Type::Compound { kind, args, .. } => match kind {
CompoundKind::Ref => args.first().and_then(|inner| inner.get_name()),
_ => Some(kind.leaf_name()),
},
Type::Nominal { id, .. } => Some(id.last_segment()),
Type::ImportNamespace(package_id) => {
let path = package_id.strip_prefix("go:").unwrap_or(package_id);
path.rsplit('/').next()
}
Type::Array { .. } => Some("Array"),
_ => None,
}
}
pub fn wraps(&self, name: &str, inner: &Type) -> bool {
self.get_name().is_some_and(|n| n == name)
&& self
.get_type_params()
.and_then(|p| p.first())
.is_some_and(|first| *first == *inner)
}
pub fn get_function_params(&self) -> Option<&[FunctionParameter]> {
match self {
Type::Function(f) => Some(&f.params),
_ => None,
}
}
pub fn param_count(&self) -> usize {
match self {
Type::Function(f) => f.params.len(),
_ => 0,
}
}
pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
match self {
Type::Function(f) => {
if f.params.is_empty() {
return self.clone();
}
let mut new_params = f.params.clone();
new_params[0] = new_params[0].with_type(new_first.clone());
f.rebuild(new_params, f.bounds.clone(), f.return_type.clone())
}
Type::Forall { vars, body } => Type::Forall {
vars: vars.clone(),
body: Box::new(body.with_replaced_first_param(new_first)),
},
_ => self.clone(),
}
}
pub fn get_bounds(&self) -> &[Bound] {
match self {
Type::Function(f) => &f.bounds,
Type::Forall { body, .. } => body.get_bounds(),
_ => &[],
}
}
pub fn get_qualified_name(&self) -> Option<Symbol> {
let mut current = self;
while current.is_ref() {
current = current.get_type_params()?.first()?;
}
match current {
Type::Nominal { id, .. } => Some(id.clone()),
Type::Simple(kind) => Some(Symbol::from_parts("prelude", kind.leaf_name())),
Type::Compound { kind, .. } => Some(Symbol::from_parts("prelude", kind.leaf_name())),
_ => None,
}
}
pub fn inner(&self) -> Option<Type> {
self.get_type_params()
.and_then(|args| args.first().cloned())
}
pub fn ok_type(&self) -> Type {
debug_assert!(
self.is_result() || self.is_option() || self.is_partial(),
"ok_type called on non-Result/Option/Partial type"
);
self.inner()
.expect("Result/Option/Partial should have inner type")
}
pub fn err_type(&self) -> Type {
debug_assert!(
self.is_result() || self.is_partial(),
"err_type called on non-Result/Partial type"
);
self.get_type_params()
.and_then(|args| args.get(1).cloned())
.expect("Result/Partial should have error type")
}
}
pub fn peel_alias<'d, F>(ty: &Type, lookup: F) -> Type
where
F: Fn(&str) -> Option<&'d Definition>,
{
let mut current = ty.unwrap_forall().clone();
let mut seen: HashSet<Symbol> = HashSet::default();
while let Type::Nominal {
id,
params,
writable,
} = ¤t
{
let writable = *writable;
if !seen.insert(id.clone()) {
break;
}
let Some(target) = lookup(id.as_str())
.and_then(|definition| definition.instantiate_alias_target(params, writable))
else {
break;
};
current = target.unwrap_forall().clone();
}
current
}
pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let Type::Nominal {
id,
params,
writable,
} = ty.unwrap_forall()
else {
return None;
};
lookup(id.as_str())?.instantiate_underlying(params, *writable)
}
pub fn peel_underlying<'d, F>(ty: &Type, lookup: F) -> Type
where
F: Fn(&str) -> Option<&'d Definition>,
{
let mut current = ty.unwrap_forall().clone();
let mut seen: HashSet<Symbol> = HashSet::default();
while let Type::Nominal {
id,
params,
writable,
} = ¤t
{
let writable = *writable;
if !seen.insert(id.clone()) {
break;
}
let Some(underlying) = lookup(id.as_str())
.and_then(|definition| definition.instantiate_underlying(params, writable))
else {
break;
};
current = underlying.unwrap_forall().clone();
}
current
}
pub fn resolves_to_unknown<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
peel_alias(ty, lookup).is_unknown()
}
pub fn contains_unknown<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
fn contains<'d, F>(ty: &Type, lookup: &F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
let peeled = peel_alias(ty, lookup);
peeled.is_unknown()
|| peeled
.children()
.into_iter()
.any(|child| contains(child, lookup))
}
contains(ty, &lookup)
}
pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
where
F: Fn(&str) -> Option<&'d Definition>,
{
peel_underlying(ty, lookup).as_simple()
}
pub fn underlying_numeric_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let underlying = peel_underlying(ty, lookup);
underlying.is_numeric().then_some(underlying)
}
pub fn literal_adaptation_target<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
underlying_numeric_type(ty, &lookup).or_else(|| {
(matches!(ty.unwrap_forall(), Type::Nominal { .. })
&& underlying_simple_kind(ty, &lookup) == Some(SimpleKind::Uintptr))
.then_some(Type::Simple(SimpleKind::Uintptr))
})
}
pub fn is_numeric_compatible_with<'d, F>(left: &Type, right: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
match (
underlying_numeric_type(left, &lookup),
underlying_numeric_type(right, &lookup),
) {
(Some(left), Some(right)) => left.numeric_family() == right.numeric_family(),
_ => false,
}
}
pub fn is_aliased_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
matches!(ty.unwrap_forall(), Type::Nominal { .. })
&& underlying_type(ty, &lookup).is_some()
&& !ty.is_numeric()
&& underlying_numeric_type(ty, lookup).is_some()
}
pub fn has_byte_or_rune_slice_underlying<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
peel_underlying(ty, lookup).is_byte_or_rune_slice()
}
pub fn is_orderable<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
matches!(
underlying_simple_kind(ty, lookup),
Some(kind) if kind.is_ordered() || kind == SimpleKind::String
) || ty.is_boolean()
}
pub fn satisfies_ordered_constraint<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
let Some(kind) = underlying_simple_kind(ty, lookup) else {
return matches!(ty.unwrap_forall(), Type::Parameter(_));
};
matches!(
kind,
SimpleKind::Int
| SimpleKind::Int8
| SimpleKind::Int16
| SimpleKind::Int32
| SimpleKind::Int64
| SimpleKind::Uint
| SimpleKind::Uint8
| SimpleKind::Uint16
| SimpleKind::Uint32
| SimpleKind::Uint64
| SimpleKind::Uintptr
| SimpleKind::Byte
| SimpleKind::Rune
| SimpleKind::Float32
| SimpleKind::Float64
| SimpleKind::String
)
}
pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
let core = peel_underlying(ty, &lookup);
if let Type::Nominal { id, .. } = &core {
return matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }));
}
core.is_ref()
|| matches!(core, Type::Function(_))
|| core.is_map()
|| core.is_channel()
|| core.is_native(CompoundKind::Sender)
|| core.is_receiver()
}
pub fn peel_alias_id<F>(id: &str, next_alias: F) -> String
where
F: Fn(&str) -> Option<String>,
{
let mut current = id.to_string();
let mut seen: Vec<String> = Vec::new();
loop {
if seen.iter().any(|s| s == ¤t) {
return current;
}
let Some(next) = next_alias(¤t) else {
return current;
};
seen.push(current);
current = next;
}
}
impl Type {
pub fn unwrap_forall(&self) -> &Type {
match self {
Type::Forall { body, .. } => body.as_ref(),
other => other,
}
}
pub fn as_function_type(&self) -> Option<&FunctionType> {
match self.unwrap_forall() {
Type::Function(f) => Some(f),
_ => None,
}
}
pub fn strip_refs(&self) -> Type {
if self.is_ref() {
return self.inner().expect("ref type must have inner").strip_refs();
}
self.clone()
}
pub fn with_receiver_placeholder(self) -> Type {
match self {
Type::Function(f) => {
let f = Arc::try_unwrap(f).unwrap_or_else(|arc| (*arc).clone());
let mut new_params = vec![FunctionParameter::new(Type::ReceiverPlaceholder, false)];
new_params.extend(f.params);
Type::function(new_params, f.bounds, f.return_type)
}
_ => unreachable!(
"with_receiver_placeholder called on non-function type: {:?}",
self
),
}
}
pub fn remove_vars(types: &[&Type]) -> (Vec<Type>, Vec<EcoString>) {
let mut vars = HashMap::default();
let types = types
.iter()
.map(|v| Self::remove_vars_impl(v, &mut vars))
.collect();
(types, vars.into_values().collect())
}
fn remove_vars_impl(ty: &Type, vars: &mut HashMap<u32, EcoString>) -> Type {
match ty {
Type::Nominal {
id: name,
params: args,
writable,
} => Type::Nominal {
id: name.clone(),
params: args
.iter()
.map(|a| Self::remove_vars_impl(a, vars))
.collect(),
writable: *writable,
},
Type::Function(f) => Type::function(
f.params
.iter()
.map(|param| param.with_type(Self::remove_vars_impl(¶m.ty, vars)))
.collect(),
f.bounds
.iter()
.map(|b| Bound {
param_name: b.param_name.clone(),
generic: Self::remove_vars_impl(&b.generic, vars),
ty: Self::remove_vars_impl(&b.ty, vars),
})
.collect(),
Self::remove_vars_impl(&f.return_type, vars).into(),
),
Type::Var { id, hint } => match vars.get(&id.index()) {
Some(g) => Type::Parameter(g.clone()),
None => {
let name: EcoString = hint
.clone()
.unwrap_or_else(|| alpha_index(vars.len()).into());
vars.insert(id.index(), name.clone());
Type::Parameter(name)
}
},
Type::Forall { body, .. } => Self::remove_vars_impl(body, vars),
Type::Tuple(elements) => Type::Tuple(
elements
.iter()
.map(|e| Self::remove_vars_impl(e, vars))
.collect(),
),
Type::Compound {
kind,
args,
writable,
} => Type::Compound {
kind: *kind,
writable: *writable,
args: args
.iter()
.map(|a| Self::remove_vars_impl(a, vars))
.collect(),
},
Type::Array { length, element } => Type::Array {
length: *length,
element: Box::new(Self::remove_vars_impl(element, vars)),
},
Type::Simple(_) | Type::Parameter(_) => ty.clone(),
Type::Never
| Type::Uninferred
| Type::Ignored
| Type::Error
| Type::ImportNamespace(_)
| Type::ReceiverPlaceholder => ty.clone(),
}
}
pub fn contains_type(&self, target: &Type) -> bool {
if *self == *target {
return true;
}
match self {
Type::Nominal { params, .. } => params.iter().any(|p| p.contains_type(target)),
Type::Function(f) => {
f.params.iter().any(|p| p.ty.contains_type(target))
|| f.return_type.contains_type(target)
}
Type::Var { .. } => false,
Type::Forall { body, .. } => body.contains_type(target),
Type::Tuple(elements) => elements.iter().any(|e| e.contains_type(target)),
Type::Array { element, .. } => element.contains_type(target),
Type::Compound { args, .. } => args.iter().any(|a| a.contains_type(target)),
Type::Simple(_)
| Type::Parameter(_)
| Type::Never
| Type::Uninferred
| Type::Ignored
| Type::Error
| Type::ImportNamespace(_)
| Type::ReceiverPlaceholder => false,
}
}
}
impl Type {
pub fn numeric_family(&self) -> Option<NumericFamily> {
self.as_simple()?.numeric_family()
}
}
fn alpha_index(idx: usize) -> String {
let mut s = String::new();
let mut n = idx + 1;
while n > 0 {
n -= 1;
s.insert(0, (b'A' + (n % 26) as u8) as char);
n /= 26;
}
s
}
#[cfg(test)]
mod tests {
use super::*;
use std::iter;
#[test]
fn function_equality_ignores_param_names() {
let named = Type::function(
vec![FunctionParameter::named(
Type::int(),
Some("width".into()),
false,
)],
vec![],
Box::new(Type::bool()),
);
let differently_named = Type::function(
vec![FunctionParameter::named(
Type::int(),
Some("height".into()),
false,
)],
vec![],
Box::new(Type::bool()),
);
let unnamed = Type::function(
vec![FunctionParameter::new(Type::int(), false)],
vec![],
Box::new(Type::bool()),
);
assert_eq!(named, differently_named);
assert_eq!(named, unnamed);
}
#[test]
fn alpha_index_single() {
assert_eq!(alpha_index(0), "A");
assert_eq!(alpha_index(5), "F");
assert_eq!(alpha_index(25), "Z");
}
#[test]
fn alpha_index_double() {
assert_eq!(alpha_index(26), "AA");
assert_eq!(alpha_index(27), "AB");
assert_eq!(alpha_index(51), "AZ");
assert_eq!(alpha_index(52), "BA");
assert_eq!(alpha_index(701), "ZZ");
}
#[test]
fn alpha_index_triple() {
assert_eq!(alpha_index(702), "AAA");
}
fn unhinted_var(id: u32) -> Type {
Type::Var {
id: TypeVarId::new(id),
hint: None,
}
}
#[test]
fn remove_vars_handles_more_than_six_unhinted_vars() {
let func = Type::function(
(0..6)
.map(unhinted_var)
.map(|ty| FunctionParameter::new(ty, false))
.collect(),
vec![],
Box::new(unhinted_var(6)),
);
let (resolved, generics) = Type::remove_vars(&[&func]);
assert_eq!(generics.len(), 7);
let Type::Function(f) = &resolved[0] else {
panic!("expected function type");
};
let names: Vec<_> = f
.params
.iter()
.map(|param| ¶m.ty)
.chain(iter::once(f.return_type.as_ref()))
.map(|p| match p {
Type::Parameter(name) => name.to_string(),
other => panic!("expected parameter, got {:?}", other),
})
.collect();
assert_eq!(names, vec!["A", "B", "C", "D", "E", "F", "G"]);
}
#[test]
fn remove_vars_handles_dozens_of_unhinted_vars() {
let params: Vec<Type> = (0..30).map(unhinted_var).collect();
let func = Type::function(
params
.iter()
.cloned()
.map(|ty| FunctionParameter::new(ty, false))
.collect(),
vec![],
Box::new(Type::Simple(SimpleKind::Unit)),
);
let (_, generics) = Type::remove_vars(&[&func]);
assert_eq!(generics.len(), 30);
}
}