use alloc::{string::String, vec::Vec};
use core::fmt::Write as _;
use hir_lang::{BinderId, Def, ExprId, ItemId, PatId, PathId, Prim, Symbol, TyId, VariantId};
use intern_lang::Lookup;
use crate::{
diag::{Diagnostic, DiagnosticKind, Severity},
mono::{Dispatch, Instantiation, MonoPlan},
profile::Profile,
types::{TypeDisplay, TypeId, Types},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Coercion {
Widen,
ToAny,
WrapNullable,
Null,
Subclass,
RecordWidth,
Unsize,
Reborrow,
AutoRef,
AutoDeref,
ToUnion,
FromIntersection,
ToDyn,
ErrorConvert,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OpClass {
Int(Prim),
Float(Prim),
Bool,
Char,
Str,
NullCheck,
Dynamic,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Stats {
pub steps: u64,
pub type_nodes: usize,
}
pub(crate) const NONE: u32 = u32::MAX;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct WNode {
pub(crate) kind: WKind,
pub(crate) arity: u32,
pub(crate) names: (u32, u32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WKind {
Wild,
Null,
Value,
Member(TypeId),
Variant(VariantId),
Item(ItemId),
Tuple,
Ref,
Bool(bool),
Int(i128, i128),
Char(char, char),
Slice(u32),
SliceRest(u32, u32),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Typed {
pub(crate) types: Types,
pub(crate) exprs: Vec<u32>,
pub(crate) pats: Vec<u32>,
pub(crate) binders: Vec<u32>,
pub(crate) path_defs: Vec<(PathId, Def)>,
pub(crate) methods: Vec<(ExprId, ItemId)>,
pub(crate) coercions: Vec<(ExprId, Coercion, TypeId)>,
pub(crate) op_classes: Vec<(ExprId, OpClass)>,
pub(crate) insts: Vec<(ExprId, ItemId, u32, u32, Dispatch)>,
pub(crate) inst_args: Vec<TypeId>,
pub(crate) mono: MonoPlan,
pub(crate) opaque: Vec<(TyId, TypeId)>,
pub(crate) witnesses: Vec<(ExprId, u32, u32)>,
pub(crate) wnodes: Vec<WNode>,
pub(crate) wsyms: Vec<Symbol>,
pub(crate) wnames: Vec<(u32, Symbol)>,
pub(crate) witems: Vec<(u32, Symbol)>,
pub(crate) diagnostics: Vec<Diagnostic>,
pub(crate) profile: Profile,
pub(crate) stats: Stats,
}
fn lookup<K: Ord + Copy, V: Copy>(table: &[(K, V)], key: K) -> Option<V> {
table
.binary_search_by(|(k, _)| k.cmp(&key))
.ok()
.and_then(|i| table.get(i))
.map(|&(_, v)| v)
}
fn dense(table: &[u32], index: usize) -> Option<TypeId> {
table
.get(index)
.copied()
.filter(|&raw| raw != NONE)
.map(TypeId::from_raw)
}
impl Typed {
#[must_use]
pub fn expr(&self, id: ExprId) -> Option<TypeId> {
dense(&self.exprs, id.index())
}
#[must_use]
pub fn pat(&self, id: PatId) -> Option<TypeId> {
dense(&self.pats, id.index())
}
#[must_use]
pub fn binder(&self, id: BinderId) -> Option<TypeId> {
dense(&self.binders, id.index())
}
#[must_use]
pub fn types(&self) -> &Types {
&self.types
}
#[must_use]
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
#[must_use]
pub fn is_ok(&self) -> bool {
self.diagnostics
.iter()
.all(|d| d.severity != Severity::Error)
}
#[must_use]
pub fn path_def(&self, path: PathId) -> Option<Def> {
lookup(&self.path_defs, path)
}
#[must_use]
pub fn method(&self, call: ExprId) -> Option<ItemId> {
lookup(&self.methods, call)
}
#[must_use]
pub fn coercion(&self, expr: ExprId) -> Option<(Coercion, TypeId)> {
self.coercions
.binary_search_by(|(e, _, _)| e.cmp(&expr))
.ok()
.and_then(|i| self.coercions.get(i))
.map(|&(_, c, t)| (c, t))
}
#[must_use]
pub fn op_class(&self, op: ExprId) -> Option<OpClass> {
lookup(&self.op_classes, op)
}
#[must_use]
pub fn witnesses<L: Lookup>(&self, match_expr: ExprId, names: &L) -> Vec<String> {
let lo = self.witnesses.partition_point(|&(e, _, _)| e < match_expr);
self.witnesses
.get(lo..)
.unwrap_or(&[])
.iter()
.take_while(|&&(e, _, _)| e == match_expr)
.map(|&(_, start, len)| {
let nodes = self
.wnodes
.get(start as usize..(start as usize).saturating_add(len as usize))
.unwrap_or(&[]);
let mut out = String::new();
self.render_witness(nodes, names, &mut out);
out
})
.collect()
}
#[must_use]
pub fn instantiation(&self, expr: ExprId) -> Option<Instantiation<'_>> {
let i = self.insts.binary_search_by(|&(e, ..)| e.cmp(&expr)).ok()?;
let &(_, item, start, len, dispatch) = self.insts.get(i)?;
Some(Instantiation {
item,
args: self
.inst_args
.get(start as usize..(start as usize).saturating_add(len as usize))
.unwrap_or(&[]),
dispatch,
})
}
#[must_use]
pub fn mono_plan(&self) -> &MonoPlan {
&self.mono
}
#[must_use]
pub fn opaque_type(&self, origin: TyId) -> Option<TypeId> {
lookup(&self.opaque, origin)
}
#[must_use]
pub fn profile(&self) -> &Profile {
&self.profile
}
#[must_use]
pub fn stats(&self) -> Stats {
self.stats
}
#[must_use]
pub fn display<'a, L: Lookup>(&'a self, ty: TypeId, names: &'a L) -> TypeDisplay<'a, L> {
self.types.display(ty, names)
}
#[must_use]
pub fn message<L: Lookup>(&self, diagnostic: &Diagnostic, names: &L) -> String {
let mut out = String::new();
diagnostic.kind.render(&self.types, names, &mut out);
if let (DiagnosticKind::NonExhaustive { .. }, hir_lang::NodeRef::Expr(m)) =
(diagnostic.kind, diagnostic.node)
{
let ws = self.witnesses(m, names);
if let Some((first, rest)) = ws.split_first() {
let _ = write!(out, ": `{first}`");
match rest.len() {
0 => out.push_str(" not covered"),
1 => {
let _ = write!(
out,
" and `{}` not covered",
rest.first().map_or("", |s| s.as_str())
);
}
n => {
let _ = write!(out, " and {n} more not covered");
}
}
}
}
out
}
fn name_of(&self, key: u32) -> Option<Symbol> {
lookup(&self.wnames, key)
}
fn render_witness<L: Lookup>(&self, nodes: &[WNode], names: &L, out: &mut String) {
enum Piece {
Node(usize),
Text(&'static str),
Field(Symbol),
}
let push_sym = |s: Symbol, out: &mut String| {
if names.resolve_with(s, |t| out.push_str(t)).is_none() {
out.push('?');
}
};
let mut size = alloc::vec![1usize; nodes.len()];
for i in (0..nodes.len()).rev() {
let arity = nodes.get(i).map_or(0, |n| n.arity as usize);
let mut child = i + 1;
let mut total = 1;
for _ in 0..arity {
let s = size.get(child).copied().unwrap_or(1);
total += s;
child += s;
}
if let Some(slot) = size.get_mut(i) {
*slot = total;
}
}
let mut stack = alloc::vec![Piece::Node(0)];
while let Some(piece) = stack.pop() {
if out.len() > 200 {
out.push('…');
return;
}
let i = match piece {
Piece::Text(t) => {
out.push_str(t);
continue;
}
Piece::Field(s) => {
push_sym(s, out);
out.push_str(": ");
continue;
}
Piece::Node(i) => i,
};
let Some(n) = nodes.get(i).copied() else {
continue;
};
let mut kids = Vec::with_capacity(n.arity as usize);
let mut child = i + 1;
for _ in 0..n.arity {
kids.push(child);
child += size.get(child).copied().unwrap_or(1);
}
let fields: &[Symbol] = self
.wsyms
.get(n.names.0 as usize..(n.names.0 as usize).saturating_add(n.names.1 as usize))
.unwrap_or(&[]);
let named = !fields.is_empty() && fields.len() == kids.len();
let push_fields = |stack: &mut Vec<Piece>, open: &'static str, close: &'static str| {
stack.push(Piece::Text(close));
for (k, &c) in kids.iter().enumerate().rev() {
stack.push(Piece::Node(c));
if named {
if let Some(&f) = fields.get(k) {
stack.push(Piece::Field(f));
}
}
if k > 0 {
stack.push(Piece::Text(", "));
}
}
stack.push(Piece::Text(open));
};
match n.kind {
WKind::Wild => out.push('_'),
WKind::Null => out.push_str("null"),
WKind::Value => {
if let Some(&c) = kids.first() {
stack.push(Piece::Node(c));
}
}
WKind::Member(t) => {
out.push_str("is ");
self.types.render(t, names, out);
if let Some(&c) = kids.first() {
if nodes.get(c).is_some_and(|x| x.kind != WKind::Wild) {
stack.push(Piece::Node(c));
out.push(' ');
}
}
}
WKind::Variant(v) => {
let key = u32::try_from(v.index()).unwrap_or(NONE);
match self.name_of(key) {
Some(s) => push_sym(s, out),
None => {
let _ = write!(out, "#{}", v.index());
}
}
if !kids.is_empty() {
if named {
push_fields(&mut stack, " { ", " }");
} else {
push_fields(&mut stack, "(", ")");
}
}
}
WKind::Item(item) => {
let key = u32::try_from(item.index()).unwrap_or(NONE);
if let Some(s) = lookup(&self.witems, key) {
push_sym(s, out);
}
if named {
push_fields(&mut stack, " { ", " }");
} else {
push_fields(&mut stack, "(", ")");
}
}
WKind::Tuple => {
if named {
push_fields(&mut stack, "{ ", " }");
} else if kids.len() == 1 {
push_fields(&mut stack, "(", ",)");
} else {
push_fields(&mut stack, "(", ")");
}
}
WKind::Ref => {
out.push('&');
if let Some(&c) = kids.first() {
stack.push(Piece::Node(c));
}
}
WKind::Bool(b) => out.push_str(if b { "true" } else { "false" }),
WKind::Int(lo, hi) => {
if lo == hi {
let _ = write!(out, "{lo}");
} else {
let _ = write!(out, "{lo}..={hi}");
}
}
WKind::Char(lo, hi) => {
if lo == hi {
let _ = write!(out, "{lo:?}");
} else {
let _ = write!(out, "{lo:?}..={hi:?}");
}
}
WKind::Slice(_) => push_fields(&mut stack, "[", "]"),
WKind::SliceRest(prefix, _) => {
let mut seq: Vec<Piece> = alloc::vec![Piece::Text("[")];
let total = kids.len() + 1;
let mut k = 0usize;
for pos in 0..total {
if pos > 0 {
seq.push(Piece::Text(", "));
}
if pos == prefix as usize {
seq.push(Piece::Text(".."));
} else if let Some(&c) = kids.get(k) {
seq.push(Piece::Node(c));
k += 1;
}
}
seq.push(Piece::Text("]"));
stack.extend(seq.into_iter().rev());
}
}
}
}
}