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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
use interpreter::ast::{Expr, MacroArgument, MacroDef};
use interpreter::Compiler;
use ::{AnyFunction, Arguments, GenType};
use std::fmt::{self, Debug, Display};
use IString;

use failure::Error;

#[derive(Debug, Clone, PartialEq)]
pub struct SourceRef {
    filename: IString,
    line: u32,
    column: u32,
}

pub type CreateFunctionResult = Result<AnyFunction, Error>;

pub trait FunProto {
    fn get_name(&self) -> &str;
    fn arg_count(&self) -> usize;
    fn get_arg(&self, index: usize) -> (&str, GenType);
    fn get_description(&self) -> &str;
}

#[derive(Debug, Clone, PartialEq)]
pub struct InterpretedFunctionPrototype {
    function_name: IString,
    arguments: Vec<MacroArgument>,
    doc_comments: String, // no point in interning these
    body: Expr,
}

impl FunProto for InterpretedFunctionPrototype {
    fn get_name(&self) -> &str {
        &*self.function_name
    }
    fn arg_count(&self) -> usize {
        self.arguments.len()
    }
    fn get_arg(&self, index: usize) -> (&str, GenType) {
        let MacroArgument {
            ref name,
            ref arg_type,
        } = self.arguments[index];
        (name, (*arg_type).into())
    }
    fn get_description(&self) -> &str {
        self.doc_comments.as_str()
    }
}

impl From<MacroDef> for InterpretedFunctionPrototype {
    fn from(macro_def: MacroDef) -> InterpretedFunctionPrototype {
        InterpretedFunctionPrototype::new(macro_def)
    }
}

impl InterpretedFunctionPrototype {
    fn new(macro_def: MacroDef) -> InterpretedFunctionPrototype {
        let MacroDef {
            doc_comments,
            name,
            args,
            body,
        } = macro_def;
        InterpretedFunctionPrototype {
            function_name: name,
            doc_comments,
            arguments: args,
            body,
        }
    }
    fn bind_arguments(&self, mut args: Vec<AnyFunction>) -> Vec<BoundArgument> {
        args.drain(..).enumerate().map(|(i, value)| {
            // the bounds check should have been taken care previously of by the type checking
            // We'll have to get a little move fancy here if we ever allow variadic functions in the grammar, though
            let arg_name  = self.arguments[i].name.clone();
            BoundArgument { arg_name, value }
        }).collect()
    }

    fn apply(&self, args: Vec<AnyFunction>, compiler: &Compiler) -> CreateFunctionResult {
        let bound_args = self.bind_arguments(args);
        compiler.eval_private(&self.body, bound_args.as_slice())
    }
}

pub type BuiltinFunctionCreator = &'static Fn(Arguments) -> CreateFunctionResult;

pub struct BuiltinFunctionPrototype {
    pub function_name: &'static str,
    pub description: &'static str,
    pub arguments: &'static [(&'static str, GenType)],
    pub variadic: bool,
    pub create_fn: BuiltinFunctionCreator,
}

impl FunProto for BuiltinFunctionPrototype {
    fn get_name(&self) -> &str {
        &*self.function_name
    }
    fn arg_count(&self) -> usize {
        self.arguments.len()
    }
    fn get_arg(&self, index: usize) -> (&str, GenType) {
        self.arguments[index]
    }
    fn get_description(&self) -> &str {
        self.description
    }
}

impl Debug for BuiltinFunctionPrototype {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let create_fn_address = format!("{:p}", self.create_fn);
        f.debug_struct("BuiltinFunctionPrototype")
            .field("function_name", &self.function_name)
            .field("arguments", &self.arguments)
            .field("variadic", &self.variadic)
            .field("create_fn", &create_fn_address)
            .finish()
    }
}

impl BuiltinFunctionPrototype {
    fn apply(&self, args: Vec<AnyFunction>) -> CreateFunctionResult {
        (self.create_fn)(Arguments::new(args))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ArgumentTypes {
    pub last_is_variadic: bool,
    pub types: Vec<GenType>,
}

#[derive(Debug)]
pub enum FunctionPrototype {
    Builtin(&'static BuiltinFunctionPrototype),
    Interpreted(InterpretedFunctionPrototype),
}

impl From<InterpretedFunctionPrototype> for FunctionPrototype {
    fn from(proto: InterpretedFunctionPrototype) -> FunctionPrototype {
        FunctionPrototype::Interpreted(proto)
    }
}

impl From<&'static BuiltinFunctionPrototype> for FunctionPrototype {
    fn from(proto: &'static BuiltinFunctionPrototype) -> FunctionPrototype {
        FunctionPrototype::Builtin(proto)
    }
}

fn do_arguments_match<A: Iterator<Item = GenType>, B: Iterator<Item = GenType>>(
    expected_types: A,
    actual_types: B,
    variadic: bool,
) -> bool {
    use itertools::{EitherOrBoth, Itertools};

    let mut actual_types = actual_types.peekable();
    let mut expected_types = expected_types.peekable();

    // if this is a 0-arg function, then our job is really easy
    if expected_types.peek().is_none() {
        return actual_types.peek().is_none();
    }

    /*
     * expected_types is now guaranteed to be non-empty
     * we must require at least one argument for a varargs parameter. This is because we don't really
     * resolve to a "best" match. We instead assume that a function call will match at most two prototypes.
     * When a call does match two prototypes, we will select whichever one is NOT variadic, and error
     * if they are both variadic.
     */
    let mut last_arg_type = None;
    for either_or_both in expected_types.zip_longest(actual_types) {
        let arg_matches = match either_or_both {
            EitherOrBoth::Both(e, a) => {
                last_arg_type = Some(e);
                e == a
            }
            EitherOrBoth::Left(_) => false,
            EitherOrBoth::Right(arg_type) => variadic && Some(arg_type) == last_arg_type,
        };
        if !arg_matches {
            return false;
        }
    }
    true
}

impl FunctionPrototype {
    pub fn new<T: Into<InterpretedFunctionPrototype>>(t: T) -> FunctionPrototype {
        FunctionPrototype::Interpreted(t.into())
    }

    pub fn name(&self) -> &str {
        match *self {
            FunctionPrototype::Interpreted(ref int) => &*int.function_name,
            FunctionPrototype::Builtin(ref bi) => &bi.function_name,
        }
    }

    pub fn is_variadic(&self) -> bool {
        match *self {
            FunctionPrototype::Builtin(ref builtin) => builtin.variadic,
            FunctionPrototype::Interpreted(_) => false, // variadic functions are not yet supported in the grammar
        }
    }

    pub fn is_same_signature(&self, other: &FunctionPrototype) -> bool {
        if self.name() != other.name() {
            return false;
        }

        let arg_count = self.get_arg_count();
        if arg_count != other.get_arg_count() {
            return false;
        }

        for i in 0..arg_count {
            // we're only checking the type of the arguments, not their names
            if self.get_arg(i).1 != other.get_arg(i).1 {
                return false;
            }
        }

        if self.is_variadic() != other.is_variadic() {
            return false;
        }
        true
    }

    pub fn do_arguments_match(&self, actual_args: &[AnyFunction]) -> bool {
        let variadic = self.is_variadic();
        let actual_arg_types = actual_args.iter().map(AnyFunction::get_type);
        match *self {
            FunctionPrototype::Builtin(ref builtin) => {
                let iter = builtin.arguments.iter().map(|arg| arg.1);
                do_arguments_match(iter, actual_arg_types, variadic)
            }
            FunctionPrototype::Interpreted(ref int) => {
                let iter = int.arguments.iter().map(|arg| arg.arg_type.into());
                do_arguments_match(iter, actual_arg_types, variadic)
            }
        }
    }

    pub fn apply(&self, arguments: Vec<AnyFunction>, compiler: &Compiler) -> CreateFunctionResult {
        match *self {
            FunctionPrototype::Builtin(ref builtin) => builtin.apply(arguments),
            FunctionPrototype::Interpreted(ref int) => int.apply(arguments, compiler),
        }
    }

    fn get_arg_count(&self) -> usize {
        match &self {
            FunctionPrototype::Builtin(ref bi) => bi.arg_count(),
            FunctionPrototype::Interpreted(ref int) => int.arg_count(),
        }
    }

    fn get_arg(&self, i: usize) -> (&str, GenType) {
        match &self {
            FunctionPrototype::Builtin(ref bi) => bi.get_arg(i),
            FunctionPrototype::Interpreted(ref int) => int.get_arg(i),
        }
    }

    fn get_description(&self) -> &str {
        match &self {
            FunctionPrototype::Builtin(ref bi) => bi.get_description(),
            FunctionPrototype::Interpreted(ref int) => int.get_description(),
        }
    }
}

impl Display for FunctionPrototype {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // function name and argument list
        f.write_str(self.name())?;
        f.write_str("(")?;
        let variadic = self.is_variadic();
        let arg_count = self.get_arg_count();
        for i in 0..arg_count {
            if i > 0 {
                f.write_str(", ")?;
            }
            let (arg_name, arg_type) = self.get_arg(i);
            write!(f, "{}: {}", arg_name, arg_type)?;
            if variadic && i == arg_count.saturating_sub(1) {
                f.write_str("...")?;
            }
        }
        f.write_str(") - ")?;

        f.write_str(self.get_description())
    }
}

#[derive(Clone)]
pub struct BoundArgument {
    pub arg_name: IString,
    pub value: AnyFunction,
}

impl BoundArgument {
    pub fn new(arg_name: IString, value: AnyFunction) -> BoundArgument {
        BoundArgument { arg_name, value }
    }
}