1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! This module defines classes.
//! The concept of a class should be similar to the equivalent concept
//! in other languages.
//! Every value (`object`) has a class.
//! Builtin values have a class with an associated type, while
//! user defined classes, like structs, carry a reference to the concrete struct.

use std::cell::OnceCell;
use std::{fmt, rc::Rc};

use debris_common::Ident;
use rustc_hash::FxHashMap;

use crate::{
    item_id::ItemIdAllocator,
    objects::{
        obj_bool::ObjBool,
        obj_function::FunctionClassRef,
        obj_int::ObjInt,
        obj_never::ObjNever,
        obj_null::ObjNull,
        obj_struct::StructRef,
        obj_struct_object::ObjStructObject,
        obj_tuple_object::{ObjTupleObject, TupleRef},
    },
    ObjectProperties, ObjectRef, Type, ValidPayload,
};

use super::type_context::TypeContext;

pub type ClassRef = Rc<Class>;

/// An enum over every type that exists in debris.
/// Either a simple [`Type`] or a complex type with additional data.
///
/// Most complex types come in two variants: As a pattern and as a value.
/// A pattern could be e.g. a struct which may be required in a function definition as parameter.
/// The value would then be the struct object that can actually be passed to that function.
#[derive(Debug, PartialEq, Eq)]
pub enum ClassKind {
    Type(Type),
    Struct(StructRef),
    StructValue(StructRef),
    Tuple(TupleRef),
    TupleValue(TupleRef),
    Function(FunctionClassRef),
}

impl ClassKind {
    /// Changes all types to their respective objects, e.g. `Struct` => `StructObject`.
    /// This can be used to figure out the [`ClassKind`] that matches on this kind
    ///
    /// Returns [`None`] if this is already an object variant
    pub fn as_value(&self) -> Option<ClassKind> {
        let value = match self {
            ClassKind::StructValue(_) | ClassKind::TupleValue(_) => return None,
            ClassKind::Type(typ) => ClassKind::Type(*typ),
            ClassKind::Struct(strukt) => ClassKind::StructValue(strukt.clone()),
            ClassKind::Tuple(tuple) => ClassKind::TupleValue(tuple.clone()),
            ClassKind::Function(function) => ClassKind::Function(function.clone()),
        };
        Some(value)
    }

    /// Returns whether the other class kind matches this class kind if this is interpreted as a pattern.
    /// For example, a struct object can match on a struct, if the underlying struct is equal.
    pub fn matches(&self, other: &ClassKind) -> bool {
        match (self, other) {
            (ClassKind::Type(typ), other) => typ.matches(other.typ()),
            // Cases when a specific struct is expected and other is an instance of that struct
            (ClassKind::Struct(strukt), ClassKind::StructValue(other_strukt)) => {
                strukt == other_strukt
            }
            (ClassKind::Tuple(tuple), ClassKind::TupleValue(other_tuple)) => {
                tuple.matches(other_tuple)
            }
            (ClassKind::Function(function), ClassKind::Function(other_function)) => {
                function.matches(other_function)
            }
            (ClassKind::Function(_) | ClassKind::Struct(_) | ClassKind::Tuple(_), _) => false,
            (ClassKind::StructValue(_) | ClassKind::TupleValue(_), _) => {
                panic!("Cannot match against concrete objects")
            }
        }
    }

    /// Returns whether this value diverges, aka is impossible to construct.
    /// A diverging class can match on any pattern.
    ///
    /// This is also used for some optimizations
    pub fn diverges(&self) -> bool {
        match self {
            ClassKind::Function(function) => function.diverges(),
            ClassKind::Struct(strukt) | ClassKind::StructValue(strukt) => strukt.diverges(),
            ClassKind::Tuple(tuple) | ClassKind::TupleValue(tuple) => tuple.diverges(),
            ClassKind::Type(typ) => typ.diverges(),
        }
    }

    /// Returns the simple [`Type`] of this [`ClassKind`]
    pub fn typ(&self) -> Type {
        match self {
            ClassKind::Type(typ) => *typ,
            ClassKind::Struct(_) => Type::Struct,
            ClassKind::StructValue(_) => Type::StructObject,
            ClassKind::Tuple(_) => Type::Tuple,
            ClassKind::TupleValue(_) => Type::TupleObject,
            ClassKind::Function(_) => Type::Function,
        }
    }

    /// Returns whether this type can be fully encoded at runtime.
    pub fn runtime_encodable(&self) -> bool {
        match self {
            ClassKind::Type(typ) => typ.runtime_encodable(),
            ClassKind::Struct(_) => Type::Struct.runtime_encodable(),
            ClassKind::StructValue(strukt) => strukt.runtime_encodable(),
            ClassKind::Tuple(_) => Type::Tuple.runtime_encodable(),
            ClassKind::TupleValue(tuple) => tuple.runtime_encodable(),
            ClassKind::Function(_) => Type::Function.runtime_encodable(),
        }
    }

    /// Returns whether this type can be fully encoded at compile time.
    pub fn comptime_encodable(&self) -> bool {
        match self {
            ClassKind::Type(typ) => typ.comptime_encodable(),
            ClassKind::Struct(strukt) | ClassKind::StructValue(strukt) => {
                strukt.comptime_encodable()
            }
            ClassKind::Tuple(tuple) | ClassKind::TupleValue(tuple) => tuple.comptime_encodable(),
            ClassKind::Function(_) => Type::Function.comptime_encodable(),
        }
    }
}

/// A class combines [`ClassKind`] and corresponding properties (Mostly associated methods).
#[derive(PartialEq, Eq)]
pub struct Class {
    pub kind: ClassKind,
    pub properties: OnceCell<ObjectProperties>,
}

impl Class {
    /// Constructs a new class with an empty properties map
    pub fn new_empty(kind: ClassKind) -> Self {
        let cell = OnceCell::new();
        cell.set(ObjectProperties::default()).unwrap();
        Class {
            kind,
            properties: cell,
        }
    }

    /// Returns if the value class `other` matches this pattern
    pub fn matches(&self, other: &Class) -> bool {
        self.kind.matches(&other.kind)
    }

    /// Returns whether the other class has the same type as this class or diverges.
    pub fn matches_type(&self, other: &Class) -> bool {
        self.kind.typ().matches(other.kind.typ())
    }

    /// Whether it is impossible to construct a value of this class
    pub fn diverges(&self) -> bool {
        self.kind.diverges()
    }

    /// Returns a property of this class
    ///
    /// # Panics
    /// panics if this class is not initialized yet
    pub fn get_property(&self, ident: &Ident) -> Option<ObjectRef> {
        self.properties
            .get()
            .expect("Cannot get property on uninitialized class")
            .get(ident)
            .cloned()
    }

    /// Constructs a new runtime object that corresponds to this class, if possible
    pub fn new_obj_from_allocator(
        &self,
        ctx: &TypeContext,
        allocator: &ItemIdAllocator,
    ) -> Option<ObjectRef> {
        match &self.kind {
            ClassKind::Function(_) => None,
            ClassKind::Type(typ) => match typ {
                Type::Type
                | Type::Any
                | Type::ComptimeBool
                | Type::ComptimeInt
                | Type::FormatString
                | Type::Function
                | Type::FunctionRef
                | Type::Module
                | Type::String
                | Type::Struct
                | Type::StructObject
                | Type::Tuple
                | Type::TupleObject => None,
                Type::DynamicBool => Some(ObjBool::new(allocator.next_id()).into_object(ctx)),
                Type::DynamicInt => Some(ObjInt::new(allocator.next_id()).into_object(ctx)),
                Type::Never => Some(ObjNever.into_object(ctx)),
                Type::Null => Some(ObjNull.into_object(ctx)),
            },
            ClassKind::Tuple(tuple) | ClassKind::TupleValue(tuple) => {
                let values = tuple
                    .layout
                    .iter()
                    .map(|class| class.new_obj_from_allocator(ctx, allocator))
                    .collect::<Option<Vec<_>>>()?;
                let tuple = ObjTupleObject::new(values);
                Some(tuple.into_object(ctx))
            }
            ClassKind::Struct(strukt) | ClassKind::StructValue(strukt) => {
                let mut values = FxHashMap::default();
                values.reserve(strukt.fields.len());
                for (ident, class) in &strukt.fields {
                    let obj = class.new_obj_from_allocator(ctx, allocator)?;
                    values.insert(ident.clone(), obj);
                }
                let strukt_obj = ObjStructObject::new(strukt.clone(), values)
                    .expect("Autogenerated values must be valid");
                Some(strukt_obj.into_object(ctx))
            }
        }
    }
}

impl From<Type> for ClassKind {
    fn from(value: Type) -> Self {
        ClassKind::Type(value)
    }
}

impl fmt::Display for ClassKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ClassKind::Type(typ) => fmt::Display::fmt(typ, f),
            ClassKind::Struct(strukt) | ClassKind::StructValue(strukt) => {
                fmt::Display::fmt(strukt, f)
            }
            ClassKind::Tuple(tuple) | ClassKind::TupleValue(tuple) => fmt::Display::fmt(tuple, f),
            ClassKind::Function(func) => fmt::Display::fmt(func, f),
        }
    }
}

impl fmt::Display for Class {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = &self.kind;
        write!(f, "{kind}")
    }
}

impl fmt::Debug for Class {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Class")
            .field("kind", &self.kind)
            .finish_non_exhaustive()
    }
}