use xur_ast::{FieldDef, FnRetTy, PatKind, Ty, TyKind};
use xur_resolve::{DefId, DefKind, Namespace, PrimTy, Program, Res, Resolutions};
use xur_span::Symbol;
use crate::ItemIndex;
use crate::ir::RtType;
use crate::types::prim_rt_type;
#[derive(Debug, Clone, PartialEq)]
pub struct FnSig {
pub params: Vec<ParamSig>,
pub ret: TypeSig,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ParamSig {
pub name: String,
pub ty: TypeSig,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TypeSig {
Unit,
Bool,
Str,
Bytes,
Map,
Int {
name: &'static str,
min: i128,
max: i128,
},
Float {
name: &'static str,
},
List(Box<TypeSig>),
Tuple(Vec<TypeSig>),
Struct {
def: DefId,
name: String,
fields: Vec<FieldSig>,
},
Enum {
def: DefId,
name: String,
variants: Vec<VariantSig>,
},
Native {
def: DefId,
name: String,
args: Vec<TypeSig>,
},
Recursive {
def: DefId,
name: String,
},
Any,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FieldSig {
pub name: String,
pub ty: TypeSig,
}
#[derive(Debug, Clone, PartialEq)]
pub struct VariantSig {
pub def: DefId,
pub name: String,
pub unit: bool,
}
pub fn fn_signature(program: &Program, index: &ItemIndex, name: &str) -> Option<FnSig> {
let resolutions = program.resolutions();
let root = resolutions.module_defs[program.krate.root.0];
let Some(Res::Def(DefKind::Fn, def)) =
resolutions.lookup(root, Namespace::Value, Symbol::intern(name))
else {
return None;
};
let crate::ItemRef::Fn { item, .. } = index.get(def)? else {
return None;
};
let sigs = Sigs {
resolutions,
index,
seen: Vec::new(),
};
let mut sigs = sigs;
let params = item
.decl
.inputs
.iter()
.map(|param| ParamSig {
name: match ¶m.pat.kind {
PatKind::Ident(ident) => ident.name.to_string(),
_ => "_".to_owned(),
},
ty: sigs.ty(¶m.ty),
})
.collect();
let ret = match &item.decl.output {
FnRetTy::Default(_) => TypeSig::Unit,
FnRetTy::Ty(ty) => sigs.ty(ty),
};
Some(FnSig { params, ret })
}
struct Sigs<'a> {
resolutions: &'a Resolutions,
index: &'a ItemIndex,
seen: Vec<DefId>,
}
impl Sigs<'_> {
fn ty(&mut self, ty: &Ty) -> TypeSig {
match &ty.kind {
TyKind::Path(path) => {
let args = || {
path.segments
.last()
.and_then(|segment| segment.args.as_ref())
.map(|args| args.args.as_slice())
.unwrap_or_default()
};
match self.resolutions.res.get(&path.id) {
Some(Res::PrimTy(prim)) => prim_sig(*prim),
Some(&Res::Def(DefKind::Struct, def)) => self.strukt(def),
Some(&Res::Def(DefKind::Enum, def)) => self.enum_sig(def),
Some(&Res::Def(DefKind::NativeType(_), def)) => TypeSig::Native {
def,
name: self.resolutions.def_path(def),
args: args().iter().map(|ty| self.ty(ty)).collect(),
},
_ => TypeSig::Any,
}
}
TyKind::Tuple(tys) if tys.is_empty() => TypeSig::Unit,
TyKind::Tuple(tys) => TypeSig::Tuple(tys.iter().map(|ty| self.ty(ty)).collect()),
TyKind::Paren(ty) => self.ty(ty),
TyKind::List(ty) => TypeSig::List(Box::new(self.ty(ty))),
TyKind::Ptr(_)
| TyKind::Fn { .. }
| TyKind::Record
| TyKind::Infer
| TyKind::ImplicitSelf
| TyKind::Err => TypeSig::Any,
}
}
fn strukt(&mut self, def: DefId) -> TypeSig {
let name = self.resolutions.def_path(def);
if self.seen.contains(&def) {
return TypeSig::Recursive { def, name };
}
self.seen.push(def);
let fields = self
.index
.fields(def)
.unwrap_or_default()
.iter()
.enumerate()
.map(|(i, field)| self.field(i, field))
.collect();
self.seen.pop();
TypeSig::Struct { def, name, fields }
}
fn field(&mut self, i: usize, field: &FieldDef) -> FieldSig {
FieldSig {
name: field
.ident
.map(|ident| ident.name.to_string())
.unwrap_or_else(|| i.to_string()),
ty: self.ty(&field.ty),
}
}
fn enum_sig(&self, def: DefId) -> TypeSig {
let variants = self
.resolutions
.defs
.iter()
.filter(|(_, data)| data.kind == DefKind::Variant && data.parent == Some(def))
.map(|(variant, data)| VariantSig {
def: variant,
name: data.name.to_string(),
unit: self.index.fields(variant).is_none_or(<[_]>::is_empty),
})
.collect();
TypeSig::Enum {
def,
name: self.resolutions.def_path(def),
variants,
}
}
}
fn prim_sig(prim: PrimTy) -> TypeSig {
match prim_rt_type(prim) {
RtType::Bool => TypeSig::Bool,
RtType::Str => TypeSig::Str,
RtType::Bytes => TypeSig::Bytes,
RtType::Map => TypeSig::Map,
RtType::Int { name, min, max } => TypeSig::Int { name, min, max },
RtType::Float { name } => TypeSig::Float { name },
_ => TypeSig::Any,
}
}