use rustc_hash::{FxHashMap, FxHashSet};
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use std::mem;
use std::slice;
use std::sync::Arc;
use ecow::EcoString;
use crate::ast::{Generic, VariantFields};
use crate::program::{
Definition, DefinitionBody, PRELUDE_PACKAGE_ID, is_go_import, strip_go_prefix,
};
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<Symbol> for EcoString {
fn from(s: Symbol) -> Self {
s.0
}
}
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 SELF_TYPE_NAME: &str = "Self";
pub fn package_for_qualified_name(
id: &str,
mut contains_package: impl FnMut(&str) -> bool,
) -> Option<&str> {
if !is_go_import(id) || !id.contains('/') {
return id.split_once('.').map(|(m, _)| m);
}
let mut end = id.len();
while let Some(separator) = id[..end].rfind('.') {
let candidate = &id[..separator];
if contains_package(candidate) {
return Some(candidate);
}
end = separator;
}
None
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RangeKind {
Range,
RangeInclusive,
RangeFrom,
RangeTo,
RangeToInclusive,
}
impl RangeKind {
pub fn of(ty: &Type) -> Option<Self> {
match ty.get_qualified_id()? {
"prelude.Range" => Some(Self::Range),
"prelude.RangeInclusive" => Some(Self::RangeInclusive),
"prelude.RangeFrom" => Some(Self::RangeFrom),
"prelude.RangeTo" => Some(Self::RangeTo),
"prelude.RangeToInclusive" => Some(Self::RangeToInclusive),
_ => None,
}
}
pub fn has_start(self) -> bool {
matches!(self, Self::Range | Self::RangeInclusive | Self::RangeFrom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IterableKind {
String,
Slice,
EnumeratedSlice,
Channel,
Array,
Map,
Seq,
Seq2,
Range(RangeKind),
NotIterable,
}
impl IterableKind {
pub fn of(ty: &Type) -> Option<Self> {
if let Some(range) = RangeKind::of(ty) {
return Some(Self::Range(range));
}
Some(match ty.kind() {
TypeKind::Simple(SimpleKind::String) => Self::String,
TypeKind::Array { .. } => Self::Array,
TypeKind::Compound { kind, .. } => match kind {
CompoundKind::Slice => Self::Slice,
CompoundKind::EnumeratedSlice => Self::EnumeratedSlice,
CompoundKind::Channel | CompoundKind::Receiver => Self::Channel,
CompoundKind::Map => Self::Map,
_ => Self::NotIterable,
},
TypeKind::Simple(_) | TypeKind::Nominal { .. } | TypeKind::ImportNamespace(_) => {
Self::NotIterable
}
_ => return None,
})
}
pub fn yields_key_value(self) -> bool {
matches!(self, Self::Map | Self::EnumeratedSlice | Self::Seq2)
}
}
#[derive(Debug, Clone, Copy)]
pub struct DisplayName<'a>(&'a str);
impl Display for DisplayName<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SubstitutionMap(Vec<(EcoString, Type)>);
impl SubstitutionMap {
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn get(&self, name: &str) -> Option<&Type> {
self.0
.iter()
.find_map(|(candidate, ty)| (candidate == name).then_some(ty))
}
pub fn insert(&mut self, name: EcoString, ty: Type) -> Option<Type> {
if let Some((_, existing)) = self.0.iter_mut().find(|(candidate, _)| candidate == &name) {
return Some(mem::replace(existing, ty));
}
self.0.push((name, ty));
None
}
pub fn iter(&self) -> impl Iterator<Item = (&EcoString, &Type)> {
self.0.iter().map(|(name, ty)| (name, ty))
}
pub fn types(&self) -> impl ExactSizeIterator<Item = &Type> + Clone {
self.0.iter().map(|(_, ty)| ty)
}
pub fn types_mut(&mut self) -> impl Iterator<Item = &mut Type> {
self.0.iter_mut().map(|(_, ty)| ty)
}
}
impl FromIterator<(EcoString, Type)> for SubstitutionMap {
fn from_iter<T: IntoIterator<Item = (EcoString, Type)>>(iter: T) -> Self {
let mut map = Self::default();
for (name, ty) in iter {
map.insert(name, ty);
}
map
}
}
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.kind(), TypeKind::Parameter(name) if name == param))
}
pub fn substitute(ty: &Type, map: &SubstitutionMap) -> Type {
if map.is_empty() {
return ty.clone();
}
if let TypeKind::Parameter(name) = ty.kind() {
return map.get(name).cloned().unwrap_or_else(|| ty.clone());
}
ty.carry_spelling(substitute_structure(ty, map), |argument| {
substitute(argument, map)
})
}
fn substitute_structure(ty: &Type, map: &SubstitutionMap) -> Type {
match ty.kind() {
TypeKind::Parameter(_) => ty.clone(),
TypeKind::Nominal {
id,
params,
writable,
} => TypeKind::Nominal {
id: id.clone(),
params: params.iter().map(|p| substitute(p, map)).collect(),
writable: *writable,
}
.into(),
TypeKind::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)),
),
TypeKind::Var { .. } | TypeKind::Uninferred | TypeKind::Error(_) => ty.clone(),
TypeKind::Tuple(elements) => {
Type::tuple(elements.iter().map(|e| substitute(e, map)).collect())
}
TypeKind::Array { length, element } => TypeKind::Array {
length: *length,
element: Box::new(substitute(element, map)),
}
.into(),
TypeKind::Compound {
kind,
args,
writable,
} => Type::qualified_compound(
*kind,
args.iter().map(|a| substitute(a, map)).collect(),
*writable,
),
TypeKind::Simple(_)
| TypeKind::Never
| TypeKind::ImportNamespace(_)
| TypeKind::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>,
}
impl FunctionParameter {
pub fn new(ty: Type) -> Self {
Self { ty, name: None }
}
pub fn named(ty: Type, name: Option<EcoString>) -> Self {
Self { ty, name }
}
pub fn with_type(&self, ty: Type) -> Self {
Self {
ty,
name: self.name.clone(),
}
}
}
#[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)
&& 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();
}
TypeKind::Function(Arc::new(stripped)).into()
}
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(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ErrorReported(());
impl ErrorReported {
#[doc(hidden)]
pub fn unchecked() -> Self {
Self(())
}
}
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Type {
kind: TypeKind,
spelling: Option<Arc<Spelling>>,
}
const RUNE_ALIAS: &str = "prelude.rune";
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Spelling {
pub alias: Symbol,
pub args: TypeList,
}
impl Type {
pub fn kind(&self) -> &TypeKind {
&self.kind
}
pub fn into_kind(self) -> TypeKind {
self.kind
}
pub fn kind_mut(&mut self) -> &mut TypeKind {
self.spelling = None;
&mut self.kind
}
pub fn spelling(&self) -> Option<&Spelling> {
self.spelling.as_deref()
}
pub fn spelled(kind: TypeKind, spelling: Spelling) -> Self {
Self {
kind,
spelling: Some(Arc::new(spelling)),
}
}
pub fn same_spelling_as(&self, other: &Type) -> bool {
self == other && self.spellings_match(other)
}
fn spellings_match(&self, other: &Type) -> bool {
match (self.spelling(), other.spelling()) {
(Some(left), Some(right)) => {
left.alias == right.alias
&& left.args.len() == right.args.len()
&& left
.args
.iter()
.zip(right.args.iter())
.all(|(left, right)| left.same_spelling_as(right))
}
(None, None) => self
.children()
.zip(other.children())
.all(|(left, right)| left.spellings_match(right)),
(Some(_), None) | (None, Some(_)) => false,
}
}
pub fn written_alias(&self) -> Option<Type> {
let spelling = self.spelling()?;
Some(
TypeKind::Nominal {
id: spelling.alias.clone(),
params: spelling.args.clone(),
writable: self.is_writable(),
}
.into(),
)
}
pub fn without_spelling(&self) -> Type {
self.kind.clone().into()
}
pub fn carry_spelling(&self, target: Type, map: impl FnMut(&Type) -> Type) -> Type {
match &self.spelling {
None => target,
Some(_) => self.rebuilt(target.kind, map),
}
}
pub fn edit_kind_keeping_spelling(mut self, edit: impl FnOnce(&mut TypeKind)) -> Type {
edit(&mut self.kind);
self
}
fn rebuilt(&self, kind: TypeKind, mut map: impl FnMut(&Type) -> Type) -> Type {
let spelling = self.spelling.as_ref().map(|spelling| {
Arc::new(Spelling {
alias: spelling.alias.clone(),
args: spelling.args.iter().map(&mut map).collect(),
})
});
Type { kind, spelling }
}
}
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TypeScheme {
pub vars: Vec<EcoString>,
pub body: Type,
}
impl TypeScheme {
pub fn mono(body: Type) -> Self {
Self {
vars: Vec::new(),
body,
}
}
pub fn is_generic(&self) -> bool {
!self.vars.is_empty()
}
pub fn equals_receiver_vars(
&self,
owner_id: &str,
arity: usize,
peel: impl Fn(&Type) -> Type,
) -> Option<Vec<EcoString>> {
if !self.body.is_equals_signature(&peel) || self.vars.len() != arity {
return None;
}
let TypeKind::Function(f) = self.body.kind() else {
return None;
};
let TypeKind::Nominal { id, params, .. } = peel(&f.params[0].ty).into_kind() 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.iter().cloned() {
let TypeKind::Parameter(name) = param.into_kind() else {
return None;
};
if vars.contains(&name) {
return None;
}
vars.push(name);
}
if !self.vars.iter().all(|v| vars.contains(v)) {
return None;
}
Some(vars)
}
}
impl From<TypeKind> for Type {
fn from(kind: TypeKind) -> Self {
Self {
kind,
spelling: None,
}
}
}
impl PartialEq for Type {
fn eq(&self, other: &Self) -> bool {
self.kind == other.kind
}
}
impl Eq for Type {}
impl Hash for Type {
fn hash<H: Hasher>(&self, state: &mut H) {
self.kind.hash(state);
}
}
impl fmt::Debug for Type {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.kind.fmt(f)
}
}
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TypeKind {
Simple(SimpleKind),
Compound {
kind: CompoundKind,
args: TypeList,
writable: bool,
},
Nominal {
id: Symbol,
params: TypeList,
writable: bool,
},
ImportNamespace(EcoString),
Function(Arc<FunctionType>),
Var {
id: TypeVarId,
hint: Option<EcoString>,
},
Uninferred,
Parameter(EcoString),
Never,
Tuple(Vec<Type>),
Array {
length: u64,
element: Box<Type>,
},
Error(ErrorReported),
ReceiverPlaceholder,
}
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct TypeList(Option<Arc<Box<[Type]>>>);
impl TypeList {
pub const fn new() -> Self {
Self(None)
}
pub fn as_slice(&self) -> &[Type] {
self.0.as_deref().map_or(&[], |items| items)
}
}
impl Deref for TypeList {
type Target = [Type];
fn deref(&self) -> &[Type] {
self.as_slice()
}
}
impl fmt::Debug for TypeList {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.as_slice().fmt(f)
}
}
impl From<Vec<Type>> for TypeList {
fn from(items: Vec<Type>) -> Self {
Self((!items.is_empty()).then(|| Arc::new(items.into_boxed_slice())))
}
}
impl From<&[Type]> for TypeList {
fn from(items: &[Type]) -> Self {
Self((!items.is_empty()).then(|| Arc::new(Box::from(items))))
}
}
impl FromIterator<Type> for TypeList {
fn from_iter<I: IntoIterator<Item = Type>>(iter: I) -> Self {
Self::from(iter.into_iter().collect::<Vec<_>>())
}
}
impl<'a> IntoIterator for &'a TypeList {
type Item = &'a Type;
type IntoIter = slice::Iter<'a, Type>;
fn into_iter(self) -> Self::IntoIter {
self.as_slice().iter()
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for TypeList {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.as_slice().serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for TypeList {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Vec::<Type>::deserialize(deserializer).map(Self::from)
}
}
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 TypeKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
TypeKind::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()
}
TypeKind::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()
}
TypeKind::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()
}
TypeKind::Uninferred => f
.debug_struct("Var")
.field("id", &TypePlaceholder("uninferred"))
.finish(),
TypeKind::Parameter(name) => f.debug_tuple("Parameter").field(name).finish(),
TypeKind::Never => write!(f, "Never"),
TypeKind::Tuple(elements) => f.debug_tuple("Tuple").field(elements).finish(),
TypeKind::Array { length, element } => f
.debug_struct("Array")
.field("length", length)
.field("element", element)
.finish(),
TypeKind::Error(_) => write!(f, "Error"),
TypeKind::ImportNamespace(package_id) => {
f.debug_tuple("ImportNamespace").field(package_id).finish()
}
TypeKind::ReceiverPlaceholder => write!(f, "ReceiverPlaceholder"),
TypeKind::Simple(kind) => f.debug_tuple("Simple").field(kind).finish(),
TypeKind::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 TypeKind {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
TypeKind::Nominal {
id: id1,
params: params1,
writable: w1,
},
TypeKind::Nominal {
id: id2,
params: params2,
writable: w2,
},
) => id1 == id2 && params1 == params2 && w1 == w2,
(TypeKind::Function(f1), TypeKind::Function(f2)) => f1 == f2,
(TypeKind::Var { id: id1, .. }, TypeKind::Var { id: id2, .. }) => id1 == id2,
(TypeKind::Uninferred, TypeKind::Uninferred)
| (TypeKind::Error(_), TypeKind::Error(_)) => true,
(TypeKind::Parameter(name1), TypeKind::Parameter(name2)) => name1 == name2,
(TypeKind::Never, TypeKind::Never) => true,
(TypeKind::Tuple(elems1), TypeKind::Tuple(elems2)) => elems1 == elems2,
(
TypeKind::Array {
length: length1,
element: element1,
},
TypeKind::Array {
length: length2,
element: element2,
},
) => length1 == length2 && element1 == element2,
(TypeKind::ImportNamespace(m1), TypeKind::ImportNamespace(m2)) => m1 == m2,
(TypeKind::ReceiverPlaceholder, TypeKind::ReceiverPlaceholder) => true,
(TypeKind::Simple(k1), TypeKind::Simple(k2)) => k1 == k2,
(
TypeKind::Compound {
kind: k1,
args: a1,
writable: w1,
},
TypeKind::Compound {
kind: k2,
args: a2,
writable: w2,
},
) => k1 == k2 && a1 == a2 && w1 == w2,
_ => false,
}
}
}
impl Eq for TypeKind {}
impl Hash for TypeKind {
fn hash<H: Hasher>(&self, state: &mut H) {
mem::discriminant(self).hash(state);
match self {
TypeKind::Simple(kind) => kind.hash(state),
TypeKind::Compound {
kind,
args,
writable,
} => {
kind.hash(state);
args.hash(state);
writable.hash(state);
}
TypeKind::Nominal {
id,
params,
writable,
} => {
id.hash(state);
params.hash(state);
writable.hash(state);
}
TypeKind::ImportNamespace(package_id) => package_id.hash(state),
TypeKind::Function(function) => {
function.params.len().hash(state);
for parameter in &function.params {
parameter.ty.hash(state);
}
function.bounds.len().hash(state);
for bound in &function.bounds {
bound.param_name.hash(state);
bound.generic.hash(state);
bound.ty.hash(state);
}
function.return_type.hash(state);
}
TypeKind::Var { id, .. } => id.hash(state),
TypeKind::Parameter(name) => name.hash(state),
TypeKind::Tuple(elements) => elements.hash(state),
TypeKind::Array { length, element } => {
length.hash(state);
element.hash(state);
}
TypeKind::Uninferred
| TypeKind::Never
| TypeKind::Error(_)
| TypeKind::ReceiverPlaceholder => {}
}
}
}
impl Type {
pub fn simple(kind: SimpleKind) -> Type {
TypeKind::Simple(kind).into()
}
pub fn never() -> Type {
TypeKind::Never.into()
}
pub fn error(reported: ErrorReported) -> Type {
TypeKind::Error(reported).into()
}
pub fn parameter(name: EcoString) -> Type {
TypeKind::Parameter(name).into()
}
pub fn tuple(elements: Vec<Type>) -> Type {
TypeKind::Tuple(elements).into()
}
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.accepts_write_qualifier(),
"writable flag is restricted to Slice, Map, Ref, and VarArgs"
);
let args = if kind.carries_write_permission()
&& !writable
&& args.iter().any(Type::demotion_changes)
{
args.iter().map(Type::demoted).collect()
} else {
args
};
TypeKind::Compound {
kind,
args: args.into(),
writable,
}
.into()
}
pub fn contains_write_permission(&self) -> bool {
match self.kind() {
TypeKind::Compound { args, writable, .. } => {
*writable || args.iter().any(Type::contains_write_permission)
}
TypeKind::Nominal {
params, writable, ..
} => *writable || params.iter().any(Type::contains_write_permission),
TypeKind::Tuple(elements) => elements.iter().any(Type::contains_write_permission),
TypeKind::Array { element, .. } => element.contains_write_permission(),
_ => false,
}
}
pub fn contains_type_parameter(&self) -> bool {
self.is_type_parameter()
|| self
.children()
.into_iter()
.any(Type::contains_type_parameter)
}
pub fn is_writable(&self) -> bool {
matches!(
self.kind(),
TypeKind::Compound { writable: true, .. } | TypeKind::Nominal { writable: true, .. }
)
}
pub fn make_writable(self) -> Type {
let spelling = self.spelling;
let kind = match self.kind {
TypeKind::Compound { kind, args, .. } if kind.accepts_write_qualifier() => {
Type::qualified_compound(kind, args.to_vec(), true).kind
}
TypeKind::Nominal { id, params, .. } => TypeKind::Nominal {
id,
params,
writable: true,
},
other => other,
};
Type { kind, spelling }
}
pub fn writable_clone_result(&self) -> Type {
match self.kind() {
TypeKind::Compound { kind, args, .. }
if matches!(kind, CompoundKind::Slice | CompoundKind::EnumeratedSlice) =>
{
let [element] = args.as_slice() else {
return self.clone();
};
let result =
Type::qualified_compound(*kind, vec![element.writable_clone_result()], true);
self.carry_spelling(result, Type::writable_clone_result)
}
TypeKind::Compound {
kind: CompoundKind::Map,
args,
..
} => {
let [key, value] = args.as_slice() else {
return self.clone();
};
Type::qualified_compound(
CompoundKind::Map,
vec![key.clone(), value.writable_clone_result()],
true,
)
}
TypeKind::Tuple(elements) => {
Type::tuple(elements.iter().map(Type::writable_clone_result).collect())
}
_ => self.clone(),
}
}
pub fn shallow_demoted(&self) -> Type {
let kind = match self.kind() {
TypeKind::Compound {
kind,
args,
writable: _,
} => TypeKind::Compound {
kind: *kind,
args: args.clone(),
writable: false,
},
TypeKind::Nominal {
id,
params,
writable: _,
} => TypeKind::Nominal {
id: id.clone(),
params: params.clone(),
writable: false,
},
_ => return self.clone(),
};
self.rebuilt(kind, Type::clone)
}
pub fn demotion_changes(&self) -> bool {
match self.kind() {
TypeKind::Compound { args, writable, .. } => {
*writable || args.iter().any(Type::demotion_changes)
}
TypeKind::Nominal {
params, writable, ..
} => *writable || params.iter().any(Type::demotion_changes),
TypeKind::Tuple(elements) => elements.iter().any(Type::demotion_changes),
TypeKind::Array { element, .. } => element.demotion_changes(),
TypeKind::Function(f) => f.return_type.demotion_changes(),
_ => false,
}
}
pub fn demoted(&self) -> Type {
let kind = match self.kind() {
TypeKind::Compound {
kind,
args,
writable: _,
} => TypeKind::Compound {
kind: *kind,
args: args.iter().map(Type::demoted).collect(),
writable: false,
},
TypeKind::Nominal {
id,
params,
writable: _,
} => TypeKind::Nominal {
id: id.clone(),
params: params.iter().map(Type::demoted).collect(),
writable: false,
},
TypeKind::Tuple(elements) => {
TypeKind::Tuple(elements.iter().map(Type::demoted).collect())
}
TypeKind::Array { length, element } => TypeKind::Array {
length: *length,
element: Box::new(element.demoted()),
},
TypeKind::Function(f) => {
f.rebuild(
f.params.clone(),
f.bounds.clone(),
Box::new(f.return_type.demoted()),
)
.kind
}
_ => return self.clone(),
};
self.rebuilt(kind, Type::demoted)
}
pub fn function(
params: Vec<FunctionParameter>,
bounds: Vec<Bound>,
return_type: Box<Type>,
) -> Type {
TypeKind::Function(Arc::new(FunctionType {
params,
bounds,
return_type,
}))
.into()
}
pub fn int() -> Type {
Self::simple(SimpleKind::Int)
}
pub fn rune() -> Type {
Self::spelled(
TypeKind::Simple(SimpleKind::Int32),
Spelling {
alias: Symbol::from_raw(RUNE_ALIAS),
args: TypeList::new(),
},
)
}
pub fn string() -> Type {
Self::simple(SimpleKind::String)
}
pub fn bool() -> Type {
Self::simple(SimpleKind::Bool)
}
pub fn unit() -> Type {
Self::simple(SimpleKind::Unit)
}
pub fn test_context() -> Type {
TypeKind::Nominal {
id: Symbol::from_raw(TEST_CONTEXT_ID),
params: TypeList::new(),
writable: false,
}
.into()
}
pub fn is_test_context(&self) -> bool {
self.strip_refs().get_qualified_id() == Some(TEST_CONTEXT_ID)
}
}
pub const TEST_CONTEXT_ID: &str = "**test_prelude.TestContext";
#[derive(Clone, Copy)]
pub enum ScaledImaginary {
FloatLeft(f64),
FloatRight(f64),
}
pub fn scaled_imaginary(
left_coefficient: Option<f64>,
left_is_float: bool,
right_coefficient: Option<f64>,
right_is_float: bool,
) -> Option<ScaledImaginary> {
if let Some(coefficient) = right_coefficient
&& left_is_float
{
Some(ScaledImaginary::FloatLeft(coefficient))
} else if let Some(coefficient) = left_coefficient
&& right_is_float
{
Some(ScaledImaginary::FloatRight(coefficient))
} else {
None
}
}
impl Type {
pub fn uninferred() -> Self {
TypeKind::Uninferred.into()
}
pub fn is_uninferred(&self) -> bool {
matches!(self.kind(), TypeKind::Uninferred)
}
pub fn get_type_params(&self) -> Option<&[Type]> {
match self.kind() {
TypeKind::Nominal { params, .. } => Some(params),
TypeKind::Compound { args, .. } => Some(args),
_ => None,
}
}
pub fn without_permissions(&self) -> Type {
self.map_children(Type::without_permissions)
.shallow_demoted()
}
pub fn map_children(&self, mut map: impl FnMut(&Type) -> Type) -> Type {
let kind = match self.kind() {
TypeKind::Nominal {
id,
params: parameters,
writable,
} => TypeKind::Nominal {
id: id.clone(),
params: parameters.iter().map(&mut map).collect(),
writable: *writable,
},
TypeKind::Compound {
kind,
args: arguments,
writable,
} => TypeKind::Compound {
kind: *kind,
args: arguments.iter().map(&mut map).collect(),
writable: *writable,
},
TypeKind::Function(function) => {
let parameters = function
.params
.iter()
.map(|parameter| parameter.with_type(map(¶meter.ty)))
.collect();
let bounds = function
.bounds
.iter()
.map(|bound| Bound {
param_name: bound.param_name.clone(),
generic: map(&bound.generic),
ty: map(&bound.ty),
})
.collect();
function
.rebuild(parameters, bounds, Box::new(map(&function.return_type)))
.kind
}
TypeKind::Tuple(elements) => TypeKind::Tuple(elements.iter().map(&mut map).collect()),
TypeKind::Array { element, length } => TypeKind::Array {
element: Box::new(map(element)),
length: *length,
},
TypeKind::Simple(_)
| TypeKind::ImportNamespace(_)
| TypeKind::Var { .. }
| TypeKind::Uninferred
| TypeKind::Parameter(_)
| TypeKind::Never
| TypeKind::Error(_)
| TypeKind::ReceiverPlaceholder => {
if self.spelling.is_none() {
return self.clone();
}
self.kind.clone()
}
};
self.rebuilt(kind, map)
}
pub fn children(&self) -> TypeChildren<'_> {
match self.kind() {
TypeKind::Nominal { params, .. } => TypeChildren::Types(params.iter()),
TypeKind::Compound { args, .. } => TypeChildren::Types(args.iter()),
TypeKind::Function(f) => {
TypeChildren::Function(f.params.iter(), Some(f.return_type.as_ref()))
}
TypeKind::Tuple(elements) => TypeChildren::Types(elements.iter()),
TypeKind::Array { element, .. } => TypeChildren::One(Some(element)),
_ => TypeChildren::One(None),
}
}
}
#[derive(Clone)]
pub enum TypeChildren<'a> {
Types(slice::Iter<'a, Type>),
Function(slice::Iter<'a, FunctionParameter>, Option<&'a Type>),
One(Option<&'a Type>),
}
impl<'a> Iterator for TypeChildren<'a> {
type Item = &'a Type;
fn next(&mut self) -> Option<&'a Type> {
match self {
TypeChildren::Types(types) => types.next(),
TypeChildren::Function(params, return_type) => params
.next()
.map(|param| ¶m.ty)
.or_else(|| return_type.take()),
TypeChildren::One(child) => child.take(),
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.len();
(len, Some(len))
}
}
impl ExactSizeIterator for TypeChildren<'_> {
fn len(&self) -> usize {
match self {
TypeChildren::Types(types) => types.len(),
TypeChildren::Function(params, return_type) => {
params.len() + usize::from(return_type.is_some())
}
TypeChildren::One(child) => usize::from(child.is_some()),
}
}
}
impl DoubleEndedIterator for TypeChildren<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
match self {
TypeChildren::Types(types) => types.next_back(),
TypeChildren::Function(params, return_type) => return_type
.take()
.or_else(|| params.next_back().map(|param| ¶m.ty)),
TypeChildren::One(child) => child.take(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericFamily {
SignedInt,
UnsignedInt,
Float,
Complex,
}
impl NumericFamily {
pub fn is_integer(self) -> bool {
matches!(self, Self::SignedInt | Self::UnsignedInt)
}
}
#[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::EnumeratedSlice
| CompoundKind::Map
| CompoundKind::Ref
)
}
pub fn accepts_write_qualifier(self) -> bool {
self.carries_write_permission() || matches!(self, CompoundKind::VarArgs)
}
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,
Float32,
Float64,
Complex64,
Complex128,
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::Float32 => "float32",
SimpleKind::Float64 => "float64",
SimpleKind::Complex64 => "complex64",
SimpleKind::Complex128 => "complex128",
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::Uint8,
"float32" => SimpleKind::Float32,
"float64" => SimpleKind::Float64,
"complex64" => SimpleKind::Complex64,
"complex128" => SimpleKind::Complex128,
"rune" => SimpleKind::Int32,
"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
)
}
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 => (i32::MIN as i128, i32::MAX as i128),
Int | Int64 => (i64::MIN as i128, i64::MAX as i128),
Uint8 => (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_integer(self) -> bool {
self.is_signed_int() || self.is_unsigned_int()
}
pub fn is_unsigned_int(self) -> bool {
matches!(
self,
SimpleKind::Uint
| SimpleKind::Uint8
| SimpleKind::Uint16
| SimpleKind::Uint32
| SimpleKind::Uint64
)
}
pub fn is_unsigned(self) -> bool {
self.is_unsigned_int() || self == SimpleKind::Uintptr
}
pub fn sized_name(self) -> &'static str {
match self {
SimpleKind::Int | SimpleKind::Int64 => "int64",
SimpleKind::Uint | SimpleKind::Uint64 | SimpleKind::Uintptr => "uint64",
kind => kind.leaf_name(),
}
}
pub fn is_signed_int(self) -> bool {
matches!(
self,
SimpleKind::Int
| SimpleKind::Int8
| SimpleKind::Int16
| SimpleKind::Int32
| SimpleKind::Int64
)
}
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() {
Some(NumericFamily::UnsignedInt)
} else if self.is_float() {
Some(NumericFamily::Float)
} else if self.is_complex() {
Some(NumericFamily::Complex)
} else {
None
}
}
}
impl Type {
pub fn get_function_ret(&self) -> Option<&Type> {
match self.kind() {
TypeKind::Function(f) => Some(&f.return_type),
_ => None,
}
}
pub fn is_stringer_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
matches!(
self.kind(),
TypeKind::Function(f)
if f.params.len() == 1
&& matches!(peel(&f.return_type).kind(), TypeKind::Simple(SimpleKind::String))
)
}
pub fn is_equals_signature(&self, peel: impl Fn(&Type) -> Type) -> bool {
matches!(
self.kind(),
TypeKind::Function(f)
if f.params.len() == 2
&& matches!(peel(&f.return_type).kind(), TypeKind::Simple(SimpleKind::Bool))
&& peel(&f.params[0].ty) == peel(&f.params[1].ty)
&& !peel(&f.params[0].ty).is_ref()
)
}
pub fn is_equals_bound_signature(
&self,
param_name: &str,
peel: impl Fn(&Type) -> Type,
) -> bool {
matches!(
self.kind(),
TypeKind::Function(f)
if f.params.len() == 1
&& peel(&f.return_type).is_boolean()
&& matches!(f.params[0].ty.kind(), TypeKind::Parameter(name) if name.as_str() == param_name)
)
}
pub fn has_name(&self, name: &str) -> bool {
match self.kind() {
TypeKind::Nominal { id, .. } => id.last_segment() == name,
TypeKind::Simple(kind) => kind.leaf_name() == name,
TypeKind::Compound { kind, .. } => kind.leaf_name() == name,
_ => false,
}
}
pub fn get_qualified_id(&self) -> Option<&str> {
self.nominal_id().map(Symbol::as_str)
}
pub fn nominal_id(&self) -> Option<&Symbol> {
match self.kind() {
TypeKind::Nominal { id, .. } => Some(id),
_ => 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")
}
pub fn is_value_and_bool(&self) -> bool {
matches!(self.kind(), TypeKind::Tuple(elements) if elements.len() == 2 && elements[1].is_boolean())
}
pub fn option_of(inner: Type) -> Type {
TypeKind::Nominal {
id: Symbol::from_parts(PRELUDE_PACKAGE_ID, "Option"),
params: vec![inner].into(),
writable: false,
}
.into()
}
fn has_qualified_id(&self, qualified_id: &str) -> bool {
matches!(self.kind(), TypeKind::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.kind() {
TypeKind::Tuple(elements) => Some(elements.len()),
_ => None,
}
}
pub fn is_tuple(&self) -> bool {
matches!(self.kind(), TypeKind::Tuple(_))
}
pub fn is_function(&self) -> bool {
matches!(self.kind(), TypeKind::Function(_))
}
pub fn is_nominal(&self) -> bool {
matches!(self.kind(), TypeKind::Nominal { .. })
}
pub fn is_type_parameter(&self) -> bool {
matches!(self.kind(), TypeKind::Parameter(_))
}
pub fn is_array(&self) -> bool {
matches!(self.kind(), TypeKind::Array { .. })
}
pub fn tuple_elements(&self) -> Option<&[Type]> {
match self.kind() {
TypeKind::Tuple(elements) => Some(elements),
_ => None,
}
}
pub fn array_parts(&self) -> Option<(u64, &Type)> {
match self.kind() {
TypeKind::Array { length, element } => Some((*length, element)),
_ => None,
}
}
pub fn array_len(&self) -> Option<u64> {
match self.kind() {
TypeKind::Array { length, .. } => Some(*length),
_ => None,
}
}
pub fn as_import_namespace(&self) -> Option<&str> {
match self.kind() {
TypeKind::ImportNamespace(package_id) => Some(package_id),
_ => None,
}
}
pub fn as_compound(&self) -> Option<(CompoundKind, &[Type])> {
match self.kind() {
TypeKind::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.kind(), TypeKind::ReceiverPlaceholder)
}
pub fn is_unknown(&self) -> bool {
self.has_qualified_id("prelude.Unknown")
}
pub fn is_receiver(&self) -> bool {
self.is_native(CompoundKind::Receiver)
}
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)
}
pub fn as_simple(&self) -> Option<SimpleKind> {
match self.kind() {
TypeKind::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_float(&self) -> bool {
self.as_simple().is_some_and(SimpleKind::is_float)
}
pub fn is_variable(&self) -> bool {
matches!(self.kind(), TypeKind::Var { .. })
}
pub fn is_structural_alias_body(&self) -> bool {
matches!(
self.kind(),
TypeKind::Simple(_)
| TypeKind::Compound { .. }
| TypeKind::Array { .. }
| TypeKind::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.kind(), TypeKind::Never)
}
pub fn is_error(&self) -> bool {
matches!(self.kind(), TypeKind::Error(_))
}
pub fn contains_error(&self) -> bool {
self.reported_error().is_some()
}
pub fn reported_error(&self) -> Option<ErrorReported> {
match self.kind() {
TypeKind::Error(reported) => Some(*reported),
_ => self.children().into_iter().find_map(Type::reported_error),
}
}
pub fn has_variables(&self) -> bool {
self.is_variable() || self.children().into_iter().any(Type::has_variables)
}
pub fn collect_variables(&self, out: &mut Vec<TypeVarId>) {
if let TypeKind::Var { id, .. } = self.kind() {
out.push(*id);
}
for child in self.children() {
child.collect_variables(out);
}
}
pub fn has_unbound_variables(&self) -> bool {
match self.kind() {
TypeKind::Var { hint, .. } => hint.is_some(),
_ => self.children().into_iter().any(Type::has_unbound_variables),
}
}
pub fn collect_unbound_variables(&self, out: &mut Vec<TypeVarId>) {
if let TypeKind::Var { id, hint: Some(_) } = self.kind() {
out.push(*id);
}
for child in self.children() {
child.collect_unbound_variables(out);
}
}
pub fn remove_found_type_names(&self, names: &mut FxHashSet<EcoString>) {
if names.is_empty() {
return;
}
match self.kind() {
TypeKind::Nominal { id, params, .. } => {
names.remove(id.last_segment());
for param in params {
param.remove_found_type_names(names);
}
}
TypeKind::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);
}
}
TypeKind::Var { .. } => {}
TypeKind::Parameter(name) => {
names.remove(name);
}
TypeKind::Tuple(elements) => {
for element in elements {
element.remove_found_type_names(names);
}
}
TypeKind::Compound { kind, args, .. } => {
names.remove(kind.leaf_name());
for arg in args {
arg.remove_found_type_names(names);
}
}
TypeKind::Array { element, .. } => {
names.remove("Array");
element.remove_found_type_names(names);
}
TypeKind::Simple(kind) => {
names.remove(kind.leaf_name());
}
TypeKind::Never
| TypeKind::Uninferred
| TypeKind::Error(_)
| TypeKind::ImportNamespace(_)
| TypeKind::ReceiverPlaceholder => {}
}
}
}
impl Type {
pub fn display_name(&self) -> Option<DisplayName<'_>> {
if let Some(spelling) = self.spelling() {
return Some(DisplayName(spelling.alias.last_segment()));
}
match self.kind() {
TypeKind::Simple(kind) => Some(DisplayName(kind.leaf_name())),
TypeKind::Compound { kind, args, .. } => match kind {
CompoundKind::Ref => args.first().and_then(|inner| inner.display_name()),
_ => Some(DisplayName(kind.leaf_name())),
},
TypeKind::Nominal { id, .. } => Some(DisplayName(id.last_segment())),
TypeKind::ImportNamespace(_) => self.namespace_name().map(DisplayName),
TypeKind::Array { .. } => Some(DisplayName("Array")),
_ => None,
}
}
pub fn namespace_name(&self) -> Option<&str> {
let TypeKind::ImportNamespace(package_id) = self.kind() else {
return None;
};
let path = strip_go_prefix(package_id).unwrap_or(package_id);
path.rsplit('/').next()
}
pub fn wraps(&self, is_wrapper: impl Fn(&Type) -> bool, inner: &Type) -> bool {
is_wrapper(self)
&& 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.kind() {
TypeKind::Function(f) => Some(&f.params),
_ => None,
}
}
pub fn param_count(&self) -> usize {
match self.kind() {
TypeKind::Function(f) => f.params.len(),
_ => 0,
}
}
pub fn with_replaced_first_param(&self, new_first: &Type) -> Type {
match self.kind() {
TypeKind::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())
}
_ => self.clone(),
}
}
pub fn get_bounds(&self) -> &[Bound] {
match self.kind() {
TypeKind::Function(f) => &f.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.kind() {
TypeKind::Nominal { id, .. } => Some(id.clone()),
TypeKind::Simple(kind) => {
Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, kind.leaf_name()))
}
TypeKind::Compound { kind, .. } => {
Some(Symbol::from_parts(PRELUDE_PACKAGE_ID, 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")
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum IterSeqKind {
Seq,
Seq2,
}
pub fn is_rune<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
let mut current = ty.clone();
let mut seen: Vec<Symbol> = Vec::new();
while current.is_simple(SimpleKind::Int32) {
let Some(spelling) = current.spelling() else {
return false;
};
if spelling.alias.as_str() == RUNE_ALIAS {
return true;
}
if seen.contains(&spelling.alias) {
return false;
}
seen.push(spelling.alias.clone());
let Some(next) = lookup(spelling.alias.as_str()).and_then(|alias| {
alias.instantiate_alias_target(&spelling.args, current.is_writable())
}) else {
return false;
};
current = next.clone();
}
false
}
pub fn peel_to_iter_seq<'d, F>(ty: &Type, lookup: F) -> Option<(IterSeqKind, Type)>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let mut current = ty.clone();
let mut seen: Vec<Symbol> = Vec::new();
loop {
let spelling = current.spelling()?;
match spelling.alias.as_str() {
"go:iter.Seq" => return Some((IterSeqKind::Seq, current)),
"go:iter.Seq2" => return Some((IterSeqKind::Seq2, current)),
_ => {}
}
if seen.contains(&spelling.alias) {
return None;
}
seen.push(spelling.alias.clone());
let next = lookup(spelling.alias.as_str())?
.instantiate_alias_target(&spelling.args, current.is_writable())?;
current = next.strip_refs();
}
}
pub fn newtype_underlying<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let TypeKind::Nominal { id, writable, .. } = ty.kind() else {
return None;
};
lookup(id.as_str())?.newtype_underlying(*writable)
}
pub fn underlying_type<'d, F>(ty: &Type, lookup: F) -> Type
where
F: Fn(&str) -> Option<&'d Definition>,
{
let mut current = ty.clone();
let mut seen: FxHashSet<Symbol> = FxHashSet::default();
while let TypeKind::Nominal { id, writable, .. } = current.kind() {
let writable = *writable;
if !seen.insert(id.clone()) {
break;
}
let Some(underlying) =
lookup(id.as_str()).and_then(|definition| definition.newtype_underlying(writable))
else {
break;
};
current = underlying.clone();
}
current
}
pub const PRELUDE_ERROR_ID: &str = "prelude.error";
pub fn as_interface<'d, F>(ty: &Type, lookup: F) -> Option<Symbol>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let TypeKind::Nominal { id, .. } = ty.without_spelling().into_kind() else {
return None;
};
matches!(
lookup(id.as_str()).map(|definition| &definition.body),
Some(DefinitionBody::Interface { .. })
)
.then_some(id)
}
pub fn is_lisette_enum<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
matches!(ty.without_spelling().kind(), TypeKind::Nominal { id, .. }
if !is_go_import(id)
&& matches!(
lookup(id.as_str()).map(|definition| &definition.body),
Some(DefinitionBody::Enum { .. })
))
}
pub fn resolve_to_function_type<'d, F>(ty: &Type, lookup: F) -> Option<Type>
where
F: Fn(&str) -> Option<&'d Definition>,
{
let resolved = ty.without_spelling();
if resolved.is_function() {
return Some(resolved);
}
newtype_underlying(&resolved, &lookup).filter(|underlying| underlying.is_function())
}
pub fn contains_unknown(ty: &Type) -> bool {
ty.is_unknown() || ty.children().into_iter().any(contains_unknown)
}
pub fn contains_write_permission(ty: &Type) -> bool {
ty.is_writable() || ty.children().into_iter().any(contains_write_permission)
}
pub fn parameter_grants_write(ty: &Type) -> bool {
match ty.kind() {
TypeKind::Compound { args, writable, .. } => {
*writable || args.iter().any(parameter_grants_write)
}
TypeKind::Nominal {
params, writable, ..
} => *writable || params.iter().any(parameter_grants_write),
TypeKind::Tuple(elements) => elements.iter().any(parameter_grants_write),
TypeKind::Array { element, .. } => parameter_grants_write(element),
_ => false,
}
}
pub fn declares_writable_components<'d, F>(id: &str, lookup: &F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
match lookup(id).map(|definition| &definition.body) {
Some(DefinitionBody::Struct { fields, .. }) => fields
.as_slice()
.iter()
.any(|field| field.ty.demotion_changes()),
Some(DefinitionBody::Enum { variants, .. }) => variants
.iter()
.flat_map(|variant| match &variant.fields {
VariantFields::Unit => [].as_slice(),
VariantFields::Tuple(fields) | VariantFields::Struct(fields) => fields,
})
.any(|field| field.ty.demotion_changes()),
_ => false,
}
}
pub fn writable_ref_pointee<'d, F>(pointee: &Type, lookup: &F) -> Type
where
F: Fn(&str) -> Option<&'d Definition>,
{
match pointee.without_spelling().kind() {
TypeKind::Nominal {
id,
writable: false,
..
} if declares_writable_components(id.as_str(), lookup) => pointee.clone().make_writable(),
_ => pointee.clone(),
}
}
pub fn underlying_simple_kind<'d, F>(ty: &Type, lookup: F) -> Option<SimpleKind>
where
F: Fn(&str) -> Option<&'d Definition>,
{
underlying_type(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 = underlying_type(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(|| {
(ty.is_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_named_numeric_type<'d, F>(ty: &Type, lookup: F) -> bool
where
F: Fn(&str) -> Option<&'d Definition>,
{
let ty = ty.without_spelling();
ty.is_nominal()
&& newtype_underlying(&ty, &lookup).is_some()
&& 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>,
{
let peeled = underlying_type(ty, &lookup);
let Some((CompoundKind::Slice, [element])) = peeled.as_compound() else {
return false;
};
matches!(
element.without_spelling().as_simple(),
Some(SimpleKind::Uint8 | SimpleKind::Int32)
)
}
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
)
}
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 ty.is_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::Float32
| SimpleKind::Float64
| SimpleKind::String
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoNilForm {
Never,
Pointer,
Interface,
}
pub fn go_nil_form<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> GoNilForm {
let core = underlying_type(ty, &lookup);
if let TypeKind::Nominal { id, .. } = core.kind() {
return if matches!(lookup(id.as_str()), Some(d) if matches!(d.body, DefinitionBody::Interface { .. }))
{
GoNilForm::Interface
} else {
GoNilForm::Never
};
}
let pointer = core.is_ref()
|| core.is_function()
|| core.is_map()
|| core.is_channel()
|| core.is_native(CompoundKind::Sender)
|| core.is_receiver();
if pointer {
GoNilForm::Pointer
} else {
GoNilForm::Never
}
}
pub fn is_nilable_go_type<'a>(ty: &Type, lookup: impl Fn(&str) -> Option<&'a Definition>) -> bool {
go_nil_form(ty, lookup) != GoNilForm::Never
}
pub fn partial_ok_is_nilable<'a>(
ty: &Type,
lookup: impl Fn(&str) -> Option<&'a Definition>,
) -> bool {
is_nilable_go_type(ty, &lookup) || ty.without_spelling().is_slice()
}
impl Type {
pub fn as_function_type(&self) -> Option<&FunctionType> {
match self.kind() {
TypeKind::Function(f) => Some(f),
_ => None,
}
}
pub fn ref_depth(&self) -> usize {
match self.is_ref().then(|| self.inner()).flatten() {
Some(inner) => 1 + inner.ref_depth(),
None => 0,
}
}
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 receiver_shape(&self) -> Type {
self.strip_refs().without_spelling()
}
pub fn points_to_ref(&self) -> bool {
self.is_ref() && self.inner().is_some_and(|inner| inner.is_ref())
}
pub fn is_option_or_result(&self) -> bool {
self.is_option() || self.is_result()
}
pub fn tuple_or_type_arguments(&self) -> Vec<Type> {
match self.kind() {
TypeKind::Tuple(elements) => elements.clone(),
TypeKind::Nominal { params, .. } => params.to_vec(),
_ => Vec::new(),
}
}
pub fn is_prelude_error(&self) -> bool {
matches!(self.kind(), TypeKind::Nominal { id, .. } if id.as_str() == PRELUDE_ERROR_ID)
}
pub fn range_type(&self) -> Option<Type> {
RangeKind::of(self)
.is_some()
.then(|| self.without_spelling())
}
pub fn with_receiver_placeholder(self) -> Type {
match self.kind() {
TypeKind::Function(f) => {
let f = FunctionType::clone(f);
let mut new_params =
vec![FunctionParameter::new(TypeKind::ReceiverPlaceholder.into())];
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 = FxHashMap::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 FxHashMap<u32, EcoString>) -> Type {
let structure = Self::remove_vars_structure(ty, vars);
ty.carry_spelling(structure, |argument| Self::remove_vars_impl(argument, vars))
}
fn remove_vars_structure(ty: &Type, vars: &mut FxHashMap<u32, EcoString>) -> Type {
match ty.kind() {
TypeKind::Nominal {
id: name,
params: args,
writable,
} => TypeKind::Nominal {
id: name.clone(),
params: args
.iter()
.map(|a| Self::remove_vars_impl(a, vars))
.collect(),
writable: *writable,
}
.into(),
TypeKind::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(),
),
TypeKind::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)
}
},
TypeKind::Tuple(elements) => Type::tuple(
elements
.iter()
.map(|e| Self::remove_vars_impl(e, vars))
.collect(),
),
TypeKind::Compound {
kind,
args,
writable,
} => TypeKind::Compound {
kind: *kind,
writable: *writable,
args: args
.iter()
.map(|a| Self::remove_vars_impl(a, vars))
.collect(),
}
.into(),
TypeKind::Array { length, element } => TypeKind::Array {
length: *length,
element: Box::new(Self::remove_vars_impl(element, vars)),
}
.into(),
TypeKind::Simple(_) | TypeKind::Parameter(_) => ty.clone(),
TypeKind::Never
| TypeKind::Uninferred
| TypeKind::Error(_)
| TypeKind::ImportNamespace(_)
| TypeKind::ReceiverPlaceholder => ty.clone(),
}
}
pub fn contains_type(&self, target: &Type) -> bool {
self == target
|| self
.children()
.into_iter()
.any(|child| child.contains_type(target))
}
}
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
}
pub fn method_receiver_substitution(
receiver_ty: &Type,
concrete_ty: &Type,
) -> Option<SubstitutionMap> {
let receiver = receiver_ty.strip_refs();
let concrete = concrete_ty.strip_refs();
let (
TypeKind::Nominal {
id: receiver_id,
params: receiver_params,
..
},
TypeKind::Nominal {
id: concrete_id,
params: concrete_params,
..
},
) = (receiver.kind(), concrete.kind())
else {
return None;
};
if receiver_id != concrete_id || receiver_params.len() != concrete_params.len() {
return None;
}
receiver_params
.iter()
.zip(concrete_params)
.map(|(receiver_param, concrete_param)| {
let TypeKind::Parameter(name) = receiver_param.kind() else {
return None;
};
Some((name.clone(), concrete_param.clone()))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::iter;
fn hash(ty: &Type) -> u64 {
let mut state = DefaultHasher::new();
ty.hash(&mut state);
state.finish()
}
#[test]
fn error_type_equals_itself() {
let nominal_over_error = || -> Type {
TypeKind::Nominal {
id: Symbol::from_parts(PRELUDE_PACKAGE_ID, "Option"),
params: vec![Type::error(ErrorReported::unchecked())].into(),
writable: false,
}
.into()
};
assert_eq!(
TypeKind::Error(ErrorReported::unchecked()),
TypeKind::Error(ErrorReported::unchecked())
);
assert_eq!(nominal_over_error(), nominal_over_error());
}
#[test]
fn function_equality_ignores_param_names() {
let named = Type::function(
vec![FunctionParameter::named(Type::int(), Some("width".into()))],
vec![],
Box::new(Type::bool()),
);
let differently_named = Type::function(
vec![FunctionParameter::named(Type::int(), Some("height".into()))],
vec![],
Box::new(Type::bool()),
);
let unnamed = Type::function(
vec![FunctionParameter::new(Type::int())],
vec![],
Box::new(Type::bool()),
);
assert_eq!(named, differently_named);
assert_eq!(named, unnamed);
}
#[test]
fn equal_function_types_have_equal_hashes() {
let named = Type::function(
vec![FunctionParameter::named(Type::int(), Some("width".into()))],
vec![],
Box::new(Type::bool()),
);
let unnamed = Type::function(
vec![FunctionParameter::new(Type::int())],
vec![],
Box::new(Type::bool()),
);
assert_eq!(hash(&named), hash(&unnamed));
}
#[test]
fn equal_type_variables_have_equal_hashes() {
let named: Type = TypeKind::Var {
id: TypeVarId::new(1),
hint: Some("value".into()),
}
.into();
let unnamed: Type = TypeKind::Var {
id: TypeVarId::new(1),
hint: None,
}
.into();
assert_eq!(hash(&named), hash(&unnamed));
}
#[test]
fn signature_queries_ignore_function_bound_types() {
let variable: Type = TypeKind::Var {
id: TypeVarId::new(1),
hint: Some("value".into()),
}
.into();
let signature = Type::function(
vec![FunctionParameter::new(Type::int())],
vec![Bound {
param_name: "T".into(),
generic: variable.clone(),
ty: TypeKind::Tuple(vec![
variable.clone(),
Type::error(ErrorReported::unchecked()),
])
.into(),
}],
Box::new(Type::bool()),
);
let mut variables = Vec::new();
signature.collect_unbound_variables(&mut variables);
assert!(!signature.contains_error());
assert!(!signature.has_unbound_variables());
assert!(!signature.contains_type(&variable));
assert!(!signature.contains_type(&Type::error(ErrorReported::unchecked())));
assert!(variables.is_empty());
}
#[test]
fn signature_queries_find_errors_in_nested_return_types() {
let signature = Type::function(
vec![FunctionParameter::new(Type::int())],
vec![],
Box::new(
TypeKind::Array {
length: 1,
element: Box::new(Type::error(ErrorReported::unchecked())),
}
.into(),
),
);
assert!(signature.contains_error());
assert!(signature.contains_type(&Type::error(ErrorReported::unchecked())));
}
#[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 {
TypeKind::Var {
id: TypeVarId::new(id),
hint: None,
}
.into()
}
#[test]
fn remove_vars_handles_more_than_six_unhinted_vars() {
let func = Type::function(
(0..6)
.map(unhinted_var)
.map(FunctionParameter::new)
.collect(),
vec![],
Box::new(unhinted_var(6)),
);
let (resolved, generics) = Type::remove_vars(&[&func]);
assert_eq!(generics.len(), 7);
let TypeKind::Function(f) = resolved[0].kind() 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.kind() {
TypeKind::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(FunctionParameter::new).collect(),
vec![],
Box::new(Type::simple(SimpleKind::Unit)),
);
let (_, generics) = Type::remove_vars(&[&func]);
assert_eq!(generics.len(), 30);
}
}