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
use std::{
    fmt::{self, Debug},
    iter::zip,
    rc::Rc,
};

use debris_common::{Span, SpecialIdent};
use debris_error::{LangResult, SingleCompileError};

use crate::{
    block_id::BlockId,
    function_interface::DebrisFunctionInterface,
    impl_class,
    item_id::{ItemId, ItemIdAllocator},
    llir_function_builder::{FunctionBuilderRuntime, LlirFunctionBuilder},
    llir_nodes::Node,
    memory::MemoryLayout,
    type_context::TypeContext,
    NativeFunctionId, ObjectPayload, ObjectRef, Type,
};

/// A function object
///
/// Has a map of available signatures.
/// The call parameters are unique identifiers for every signature
#[derive(Clone)]
pub struct ObjFunction {
    pub name: &'static str,
    pub callback_function: Rc<DebrisFunctionInterface>,
}

impl_class! {ObjFunction, Type::Function, {}}

impl ObjFunction {
    pub fn new(name: &'static str, callback_function: Rc<DebrisFunctionInterface>) -> Self {
        ObjFunction {
            name,
            callback_function,
        }
    }
}

impl ObjectPayload for ObjFunction {
    fn memory_layout(&self) -> &MemoryLayout {
        &MemoryLayout::Unsized
    }
}

impl PartialEq for ObjFunction {
    fn eq(&self, other: &ObjFunction) -> bool {
        Rc::ptr_eq(&self.callback_function, &other.callback_function)
    }
}

impl Eq for ObjFunction {}

impl Debug for ObjFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ObjectFunction")
            .field(&self.name)
            .field(&Rc::as_ptr(&self.callback_function))
            .finish()
    }
}

impl fmt::Display for ObjFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Builtin '{}'", self.name)
    }
}

pub type FunctionClassRef = Rc<FunctionClass>;

#[derive(Debug, PartialEq, Eq)]
pub struct FunctionClass {
    pub parameters: Vec<ObjectRef>,
    pub return_class: ObjectRef,
}

impl FunctionClass {
    /// Here a concept of 'variance' is required: normal matches on return types,
    /// however function parameters have to be matched the other way around:
    /// if a: b, then fn(b): fn(a), but not fn(a): fn(b)
    pub fn matches(&self, other: &FunctionClass) -> bool {
        self.return_class
            .downcast_class()
            .unwrap()
            .matches(&other.return_class.downcast_class().unwrap())
            && self.parameters.len() == other.parameters.len()
            && zip(&self.parameters, &other.parameters).all(|(own, other)| {
                other
                    .downcast_class()
                    .unwrap()
                    .matches(&own.downcast_class().unwrap())
            })
    }

    pub fn diverges(&self) -> bool {
        self.return_class.downcast_class().unwrap().diverges()
            || self
                .parameters
                .iter()
                .any(|param| param.downcast_class().unwrap().diverges())
    }
}

impl fmt::Display for FunctionClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "fn(")?;
        let mut iter = self.parameters.iter();
        if let Some(first) = iter.next() {
            write!(f, "{first}")?;
        }
        for rest in iter {
            write!(f, ", {rest}")?;
        }
        write!(f, ")")?;

        if self
            .return_class
            .downcast_class()
            .map_or(true, |class| class.kind.typ() != Type::Null)
        {
            write!(f, " -> {}", self.return_class)?;
        }
        Ok(())
    }
}

/// The context which gets passed to a function
pub struct FunctionContext<'llir_builder, 'ctx, 'params> {
    /// The id of the returned value
    pub item_id: ItemId,
    /// The parameters for this function call, excluding the self value
    pub parameters: &'params [ObjectRef],
    /// The self value
    pub self_val: Option<ObjectRef>,
    /// The nodes that are emitted by this function
    pub nodes: Vec<Node>,
    pub span: Span,
    pub(crate) llir_function_builder: &'params mut LlirFunctionBuilder<'llir_builder, 'ctx>,
}

impl<'llir_builder, 'ctx, 'params> FunctionContext<'llir_builder, 'ctx, 'params> {
    /// Adds a node to the previously emitted nodes
    pub fn emit(&mut self, node: Node) {
        self.nodes.push(node);
    }

    /// Returns `self_val` downcasted to the desired type or None
    pub fn self_value_as<T: ObjectPayload>(&self) -> Option<&T> {
        self.self_val
            .as_ref()
            .and_then(|self_val| self_val.downcast_payload::<T>())
    }

    /// Generates a new function context which can be used for calling another function.
    pub fn with_new_function_context<'a, T>(
        &'a mut self,
        parameters: &'a [ObjectRef],
        self_value: Option<ObjectRef>,
        f: impl FnOnce(&mut FunctionContext<'llir_builder, 'ctx, 'a>) -> T,
    ) -> (T, Vec<Node>) {
        let mut inner_ctx = FunctionContext {
            item_id: self.item_id_allocator().next_id(),
            parameters,
            self_val: self_value,
            nodes: Vec::new(),
            span: self.span,
            llir_function_builder: self.llir_function_builder,
        };
        let result = f(&mut inner_ctx);

        (result, inner_ctx.nodes)
    }

    pub fn item_id_allocator(&self) -> &ItemIdAllocator {
        &self.llir_function_builder.builder.item_id_allocator
    }

    pub fn type_ctx(&self) -> &TypeContext {
        &self.llir_function_builder.builder.type_context
    }

    pub fn runtime_mut(&mut self) -> &mut FunctionBuilderRuntime {
        &mut self.llir_function_builder.pending_runtime_functions
    }

    // TODO: Turn into proper result
    pub fn compile_native_function(
        &mut self,
        function_id: NativeFunctionId,
    ) -> LangResult<BlockId> {
        match self
            .llir_function_builder
            .compile_null_function(function_id, self.span)
        {
            Ok(result) => Ok(result),
            Err(err) => match err {
                SingleCompileError::LangError(lang_error) => Err(lang_error.kind),
                SingleCompileError::ParseError(_) => unreachable!("(I hope)"),
            },
        }
    }

    pub fn call_function<'a>(
        &'a mut self,
        function: &ObjFunction,
        parameters: &'a [ObjectRef],
        self_value: Option<ObjectRef>,
    ) -> LangResult<ObjectRef> {
        let raw_result = self.call_function_raw(function, parameters, self_value);
        function
            .callback_function
            .handle_raw_result(self, raw_result)
    }

    pub fn call_function_raw<'a>(
        &'a mut self,
        function: &ObjFunction,
        parameters: &'a [ObjectRef],
        self_value: Option<ObjectRef>,
    ) -> Option<LangResult<ObjectRef>> {
        let (result, nodes) = self.with_new_function_context(parameters, self_value, |ctx| {
            function.callback_function.call_raw(ctx)
        });
        if let Some(Ok(_)) = result {
            self.nodes.extend(nodes);
        }
        result
    }

    pub fn promote_obj(
        &mut self,
        value: ObjectRef,
        target: ObjectRef,
    ) -> Option<LangResult<ObjectRef>> {
        let obj_fn = value.get_property(self.type_ctx(), &SpecialIdent::Promote.into())?;
        let promote_fn = obj_fn.downcast_payload()?;
        self.call_function_raw(promote_fn, &[value, target], None)
    }
}