use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::hash_map::Entry;
use std::fmt::{self, Debug};
use std::hash::Hash;
use std::mem;
use super::{
CalleeName, ConformanceWitness, InterfaceRequirement, NativeOperation, NativeTypeKind,
ReceiverCoercion,
};
use crate::EcoString;
use crate::ast::{Expression, ExpressionId, Span};
use crate::types::{IterableKind, RangeKind, SubstitutionMap, Symbol, Type, substitute};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ValueUseKey {
expression: ExpressionId,
role: ValueUseRole,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum ValueUseRole {
Value,
PropagatedError,
CastOperand,
}
impl ValueUseKey {
pub fn value(expression: &Expression) -> Self {
Self::value_id(expression.id())
}
pub fn value_id(expression: ExpressionId) -> Self {
Self {
expression,
role: ValueUseRole::Value,
}
}
pub fn propagated_error(operand: &Expression) -> Self {
Self {
expression: operand.id(),
role: ValueUseRole::PropagatedError,
}
}
pub fn expression(&self) -> ExpressionId {
self.expression
}
pub fn cast_operand(cast: ExpressionId) -> Self {
Self {
expression: cast,
role: ValueUseRole::CastOperand,
}
}
}
#[derive(Debug, Clone)]
pub enum Adaptation {
Identity,
Delegated {
converts: bool,
},
Interface(Box<InterfaceConversion>),
ImplicitSome {
payload: Box<Adaptation>,
},
Newtype,
Tuple(Vec<Adaptation>),
Array(Box<Adaptation>),
Receiver(ReceiverCoercion),
}
impl Adaptation {
pub fn converts(&self) -> bool {
match self {
Self::Identity => false,
Self::Delegated { converts } => *converts,
Self::Interface(_)
| Self::Newtype
| Self::ImplicitSome { .. }
| Self::Tuple(_)
| Self::Array(_)
| Self::Receiver(_) => true,
}
}
}
#[derive(Debug, Clone)]
pub struct InterfaceConversion {
pub source: Type,
pub target: Type,
pub source_shape: Type,
pub target_interface: Option<Type>,
pub witness: Option<ConformanceWitness>,
}
#[derive(Debug, Clone)]
pub struct CheckedValueUse {
pub slot: Type,
pub adaptation: Adaptation,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CheckedCallee {
pub operation: CallOperation,
pub name: Option<CalleeName>,
pub type_arguments: SubstitutionMap,
pub copies_storage: bool,
pub binds_receiver: bool,
pub interface_method: Option<Box<InterfaceRequirement>>,
pub span: Span,
}
impl CheckedCallee {
pub fn definition(&self) -> Option<&str> {
self.name
.as_ref()
.and_then(CalleeName::definition)
.map(Symbol::as_str)
}
pub fn method(&self) -> Option<&super::MethodName> {
self.name.as_ref().and_then(CalleeName::method)
}
pub fn interface_requirement(&self) -> Option<&InterfaceRequirement> {
match &self.operation {
CallOperation::BoundMethod { requirement, .. } => Some(requirement),
_ => self.interface_method.as_deref(),
}
}
pub fn native(&self) -> Option<NativeOperation<'_>> {
match &self.operation {
CallOperation::Native { kind, method } => Some(NativeOperation::new(*kind, method)),
_ => None,
}
}
pub fn receiver_offset(&self) -> usize {
usize::from(self.binds_receiver)
}
pub fn first_type_argument(&self) -> &Type {
self.type_arguments
.types()
.next()
.expect("internal error: the checker records the type argument of this callee")
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum CallOperation {
Function,
UfcsFunction,
ReceiverMethod {
is_public: bool,
},
BoundMethod {
bound: Type,
requirement: Box<InterfaceRequirement>,
},
Native {
kind: NativeTypeKind,
method: EcoString,
},
NativeConstructor {
kind: NativeTypeKind,
method: EcoString,
},
TupleStructConstructor {
owner: Symbol,
is_newtype: bool,
},
AssertType,
Zero,
TypeConversion,
Unavailable,
}
#[derive(Debug, Clone, PartialEq)]
pub enum EqualityRecipe {
Operator,
Method { owner: Option<Symbol> },
Slice(Option<Box<ElementEquality>>),
Map(Option<Box<ElementEquality>>),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ElementEquality {
pub ty: Type,
pub recipe: EqualityRecipe,
}
impl EqualityRecipe {
pub fn owners(&self) -> Vec<&Symbol> {
match self {
Self::Operator | Self::Method { owner: None } => Vec::new(),
Self::Method { owner: Some(owner) } => vec![owner],
Self::Slice(element) | Self::Map(element) => element
.as_ref()
.map(|element| element.recipe.owners())
.unwrap_or_default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FieldKey {
Access(ExpressionId),
Literal(ExpressionId, EcoString),
Pattern(Span),
Positional(ExpressionId, usize),
PatternPosition(Span, usize),
}
impl FieldKey {
fn file_id(&self) -> u32 {
match self {
Self::Access(expression)
| Self::Literal(expression, _)
| Self::Positional(expression, _) => expression.file_id(),
Self::Pattern(span) | Self::PatternPosition(span, _) => span.file_id,
}
}
}
pub enum PatternPosition<'a> {
Interface(&'a Type),
Value,
}
#[derive(Debug, Clone, Default)]
pub struct PatternPositions {
interfaces: FxHashMap<Span, Type>,
}
impl PatternPositions {
pub fn insert_interface(&mut self, pattern: Span, interface: Type) {
self.interfaces.insert(pattern, interface);
}
pub fn merge(&mut self, other: Self) {
self.interfaces.extend(other.interfaces);
}
pub fn interfaces(&self) -> impl Iterator<Item = (&Span, &Type)> {
self.interfaces.iter()
}
pub fn position(&self, pattern: Span) -> PatternPosition<'_> {
match self.interfaces.get(&pattern) {
Some(interface) => PatternPosition::Interface(interface),
None => PatternPosition::Value,
}
}
}
#[derive(Debug, Clone)]
pub struct FieldSelection {
pub owner: Symbol,
pub declared_ty: Type,
pub substitutions: SubstitutionMap,
}
impl FieldSelection {
pub fn field_ty(&self) -> Type {
substitute(&self.declared_ty, &self.substitutions)
}
}
#[derive(Debug, Clone)]
pub struct CheckedStructLiteral {
pub unset_fields: Vec<(EcoString, Type)>,
pub via_alias: bool,
}
#[derive(Debug, Clone, Default)]
pub struct CheckedBodies {
files: FxHashMap<u32, FileBodies>,
}
#[derive(Debug, Clone, Default)]
struct FileBodies {
uses: FxHashMap<ValueUseKey, CheckedValueUse>,
callees: FxHashMap<ValueUseKey, CheckedCallee>,
equalities: FxHashMap<ExpressionId, EqualityRecipe>,
implicit_units: FxHashMap<ExpressionId, ExpressionId>,
struct_literals: FxHashMap<ExpressionId, CheckedStructLiteral>,
field_selections: FxHashMap<FieldKey, FieldSelection>,
iterable_kinds: FxHashMap<ExpressionId, IterableKind>,
range_kinds: FxHashMap<ExpressionId, RangeKind>,
forwarded_failures: FxHashSet<ExpressionId>,
receiver_generics: FxHashMap<ExpressionId, Vec<(EcoString, Vec<Type>)>>,
}
impl CheckedBodies {
fn file(&self, file_id: u32) -> Option<&FileBodies> {
self.files.get(&file_id)
}
fn file_mut(&mut self, file_id: u32) -> &mut FileBodies {
self.files.entry(file_id).or_default()
}
pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
self.file(key.expression().file_id())?.uses.get(key)
}
pub fn callee(&self, key: &ValueUseKey) -> Option<&CheckedCallee> {
self.file(key.expression().file_id())?.callees.get(key)
}
pub fn equality(&self, expression: ExpressionId) -> Option<&EqualityRecipe> {
self.file(expression.file_id())?.equalities.get(&expression)
}
pub fn callees(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedCallee)> {
self.files.values().flat_map(|file| file.callees.iter())
}
pub fn uses(&self) -> impl Iterator<Item = (&ValueUseKey, &CheckedValueUse)> {
self.files.values().flat_map(|file| file.uses.iter())
}
fn field_selection(&self, key: &FieldKey) -> Option<&FieldSelection> {
self.file(key.file_id())?.field_selections.get(key)
}
pub fn pattern_field(&self, name_span: Span) -> &FieldSelection {
self.field_selection(&FieldKey::Pattern(name_span))
.unwrap_or_else(|| {
panic!("internal error: no checked field selection for the pattern field at {name_span:?}")
})
}
pub fn variant_pattern_fields(&self, pattern_span: Span) -> Vec<&FieldSelection> {
(0..)
.map_while(|index| {
self.field_selection(&FieldKey::PatternPosition(pattern_span, index))
})
.collect()
}
pub fn occurrence<'e>(&self, expression: &'e Expression) -> CheckedExpression<'e, '_> {
CheckedExpression {
expression,
bodies: self,
}
}
pub fn debug_lines(&self) -> Vec<String> {
fn push<K: Debug, V: Debug>(
lines: &mut Vec<String>,
label: &str,
entries: impl IntoIterator<Item = (K, V)>,
) {
lines.extend(
entries
.into_iter()
.map(|(key, value)| format!("{label} {key:?} {value:?}")),
);
}
let mut lines = Vec::new();
for file in self.files.values() {
push(&mut lines, "use", &file.uses);
push(&mut lines, "callee", &file.callees);
push(&mut lines, "equality", &file.equalities);
push(&mut lines, "implicit_unit", &file.implicit_units);
push(&mut lines, "struct_literal", &file.struct_literals);
push(&mut lines, "field_selection", &file.field_selections);
push(&mut lines, "iterable_kind", &file.iterable_kinds);
push(&mut lines, "range_kind", &file.range_kinds);
push(
&mut lines,
"forwarded_failure",
file.forwarded_failures.iter().map(|id| (id, ())),
);
push(&mut lines, "receiver_generics", &file.receiver_generics);
}
lines
}
}
#[derive(Debug, Clone, Default)]
pub struct CheckedBodiesBuilder {
records: CheckedBodies,
}
impl CheckedBodiesBuilder {
pub fn value_use(&self, key: &ValueUseKey) -> Option<&CheckedValueUse> {
self.records.value_use(key)
}
pub fn insert_use(&mut self, key: ValueUseKey, value_use: CheckedValueUse) {
insert_unique(
&mut self.records.file_mut(key.expression().file_id()).uses,
key,
value_use,
);
}
pub fn insert_callee(&mut self, key: ValueUseKey, callee: CheckedCallee) {
insert_unique(
&mut self.records.file_mut(key.expression().file_id()).callees,
key,
callee,
);
}
pub fn insert_equality(&mut self, expression: ExpressionId, recipe: EqualityRecipe) {
insert_unique(
&mut self.records.file_mut(expression.file_id()).equalities,
expression,
recipe,
);
}
pub fn insert_implicit_unit(&mut self, if_let: ExpressionId, unit: ExpressionId) {
insert_unique(
&mut self.records.file_mut(if_let.file_id()).implicit_units,
if_let,
unit,
);
}
pub fn insert_struct_literal(&mut self, literal: ExpressionId, record: CheckedStructLiteral) {
insert_unique(
&mut self.records.file_mut(literal.file_id()).struct_literals,
literal,
record,
);
}
pub fn insert_field_selection(&mut self, key: FieldKey, selection: FieldSelection) {
insert_unique(
&mut self.records.file_mut(key.file_id()).field_selections,
key,
selection,
);
}
pub fn insert_iterable_kind(&mut self, for_loop: ExpressionId, kind: IterableKind) {
insert_unique(
&mut self.records.file_mut(for_loop.file_id()).iterable_kinds,
for_loop,
kind,
);
}
pub fn insert_range_kind(&mut self, range: ExpressionId, kind: RangeKind) {
insert_unique(
&mut self.records.file_mut(range.file_id()).range_kinds,
range,
kind,
);
}
pub fn insert_forwarded_failure_id(&mut self, operand: ExpressionId) {
let inserted = self
.records
.file_mut(operand.file_id())
.forwarded_failures
.insert(operand);
assert!(
inserted,
"internal error: two forwarded failures share the key {operand:?}"
);
}
pub fn insert_receiver_generics(
&mut self,
impl_block: ExpressionId,
generics: Vec<(EcoString, Vec<Type>)>,
) {
insert_unique(
&mut self
.records
.file_mut(impl_block.file_id())
.receiver_generics,
impl_block,
generics,
);
}
pub fn merge(&mut self, other: Self) {
for (file_id, file) in other.records.files {
match self.records.files.entry(file_id) {
Entry::Vacant(entry) => {
entry.insert(file);
}
Entry::Occupied(mut entry) => {
let existing = mem::replace(entry.get_mut(), file);
self.merge_file(existing);
}
}
}
}
fn merge_file(&mut self, other: FileBodies) {
let FileBodies {
uses,
callees,
equalities,
implicit_units,
struct_literals,
field_selections,
iterable_kinds,
range_kinds,
forwarded_failures,
receiver_generics,
} = other;
for (key, value_use) in uses {
self.insert_use(key, value_use);
}
for (key, callee) in callees {
self.insert_callee(key, callee);
}
for (expression, recipe) in equalities {
self.insert_equality(expression, recipe);
}
for (if_let, unit) in implicit_units {
self.insert_implicit_unit(if_let, unit);
}
for (literal, record) in struct_literals {
self.insert_struct_literal(literal, record);
}
for (key, selection) in field_selections {
self.insert_field_selection(key, selection);
}
for (for_loop, kind) in iterable_kinds {
self.insert_iterable_kind(for_loop, kind);
}
for (range, kind) in range_kinds {
self.insert_range_kind(range, kind);
}
for operand in forwarded_failures {
self.insert_forwarded_failure_id(operand);
}
for (impl_block, generics) in receiver_generics {
self.insert_receiver_generics(impl_block, generics);
}
}
pub fn records(&self) -> &CheckedBodies {
&self.records
}
pub fn publish(self) -> CheckedBodies {
self.records
}
}
fn insert_unique<K: Eq + Hash + Debug, V>(map: &mut FxHashMap<K, V>, key: K, value: V) {
match map.entry(key) {
Entry::Occupied(entry) => {
panic!(
"internal error: two records share the key {:?}",
entry.key()
)
}
Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
#[derive(Clone, Copy)]
pub struct CheckedExpression<'e, 'a> {
expression: &'e Expression,
bodies: &'a CheckedBodies,
}
impl<'a> CheckedExpression<'_, 'a> {
pub fn value_use(&self) -> &'a CheckedValueUse {
self.record(ValueUseKey::value(self.expression))
}
pub fn cast_operand(&self) -> &'a CheckedValueUse {
self.record(ValueUseKey::cast_operand(self.expression.id()))
}
pub fn propagated_error(&self) -> Option<&'a CheckedValueUse> {
self.bodies
.value_use(&ValueUseKey::propagated_error(self.expression))
}
pub fn receiver_change(&self) -> Option<ReceiverCoercion> {
match self.value_use().adaptation {
Adaptation::Receiver(change) => Some(change),
_ => None,
}
}
pub fn callee(&self) -> &'a CheckedCallee {
self.expect(self.function_value(), format_args!("selected callee"))
}
pub fn function_value(&self) -> Option<&'a CheckedCallee> {
self.bodies.callee(&ValueUseKey::value(self.expression))
}
pub fn equality(&self) -> Option<&'a EqualityRecipe> {
self.bodies.equality(self.expression.id())
}
pub fn implicit_unit(&self) -> Option<ExpressionId> {
self.table()?
.implicit_units
.get(&self.expression.id())
.copied()
}
pub fn receiver_generics(&self) -> &'a [(EcoString, Vec<Type>)] {
self.expect(
self.table()
.and_then(|table| table.receiver_generics.get(&self.expression.id()))
.map(Vec::as_slice),
format_args!("checked receiver generics"),
)
}
pub fn range_kind(&self) -> Option<RangeKind> {
self.table()?
.range_kinds
.get(&self.expression.id())
.copied()
}
pub fn forwards_failure(&self) -> bool {
self.table()
.is_some_and(|table| table.forwarded_failures.contains(&self.expression.id()))
}
pub fn iterable_kind(&self) -> IterableKind {
*self.expect(
self.table()
.and_then(|table| table.iterable_kinds.get(&self.expression.id())),
format_args!("checked iterable kind"),
)
}
pub fn field_selection(&self) -> Option<&'a FieldSelection> {
self.bodies
.field_selection(&FieldKey::Access(self.expression.id()))
}
pub fn positional_field(&self, index: usize) -> &'a FieldSelection {
self.expect(
self.bodies
.field_selection(&FieldKey::Positional(self.expression.id(), index)),
format_args!("checked field selection for field {index}"),
)
}
pub fn literal_field(&self, name: &str) -> &'a FieldSelection {
self.expect(
self.bodies
.field_selection(&FieldKey::Literal(self.expression.id(), name.into())),
format_args!("checked field selection for `{name}`"),
)
}
pub fn struct_literal(&self) -> &'a CheckedStructLiteral {
self.expect(
self.table()
.and_then(|table| table.struct_literals.get(&self.expression.id())),
format_args!("checked struct literal"),
)
}
fn table(&self) -> Option<&'a FileBodies> {
self.bodies.file(self.expression.id().file_id())
}
fn record(&self, key: ValueUseKey) -> &'a CheckedValueUse {
self.expect(
self.bodies.value_use(&key),
format_args!("checked value use"),
)
}
fn expect<V>(&self, found: Option<V>, what: fmt::Arguments<'_>) -> V {
found.unwrap_or_else(|| {
panic!(
"internal error: no {what} at {:?}",
self.expression.get_span()
)
})
}
}