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
pub mod ast;
pub(crate) mod errors;
pub mod libraries;
mod map;
pub(crate) mod parser;
mod source;

#[cfg(test)]
mod parse_test;

#[allow(unused)]
pub(crate) mod grammar {
    include!(concat!(env!("OUT_DIR"), "/interpreter/grammar.rs"));
}

pub use self::source::Source;

use self::ast::{Expr, FunctionCall, FunctionMapper, MacroDef, Program};
use self::map::{create_memoized_fun, finish_mapped};
use builtins::BUILTIN_FNS;
use failure::Error;
use IString;
use {
    AnyFunction, BoundArgument, ConstBin, ConstBoolean, ConstChar, ConstDecimal, ConstInt,
    ConstString, ConstUint, CreateFunctionResult, FunctionPrototype,
};

pub struct Module {
    _name: IString,
    functions: Vec<FunctionPrototype>,
}

impl Module {
    pub fn new(name: IString, function_defs: Vec<MacroDef>) -> Module {
        let functions = function_defs
            .into_iter()
            .map(FunctionPrototype::new)
            .collect();
        Module {
            _name: name,
            functions,
        }
    }

    #[allow(unused)]
    pub fn add_function(&mut self, function: MacroDef) {
        let new_function = FunctionPrototype::new(function);

        let existing_function = self
            .functions
            .iter()
            .position(|fun| fun.is_same_signature(&new_function));
        if let Some(index) = existing_function {
            // replace the existing function
            self.functions[index] = new_function;
        } else {
            self.functions.push(new_function);
        }
    }

    fn function_iterator(&self) -> impl Iterator<Item = &FunctionPrototype> {
        self.functions.iter()
    }
}

pub struct Compiler {
    modules: Vec<Module>,
}

impl Compiler {
    fn new() -> Compiler {
        Compiler {
            modules: Vec::new(),
        }
    }
    fn add_module(&mut self, module: Module) {
        self.modules.push(module);
    }

    pub fn eval(&self, expr: &Expr) -> CreateFunctionResult {
        self.eval_private(expr, &[])
    }

    pub fn eval_private(&self, expr: &Expr, bound_args: &[BoundArgument]) -> CreateFunctionResult {
        match *expr {
            Expr::ArgumentUsage(ref name) => self.eval_arg_usage(name.clone(), bound_args),
            Expr::BooleanLiteral(ref lit) => Ok(ConstBoolean::new(*lit)),
            Expr::StringLiteral(ref lit) => Ok(ConstString::new(lit.clone())),
            Expr::IntLiteral(ref lit) => Ok(ConstUint::new(*lit)),
            Expr::SignedIntLiteral(ref lit) => Ok(ConstInt::new(*lit)),
            Expr::DecimalLiteral(ref lit) => Ok(ConstDecimal::new(*lit)),
            Expr::CharLiteral(ref lit) => Ok(ConstChar::new(*lit)),
            Expr::BinaryLiteral(ref lit) => Ok(ConstBin::new(lit.clone())),
            Expr::Function(ref call) => self.eval_function_call(call, bound_args),
        }
    }

    pub fn function_iterator(&self) -> impl Iterator<Item = &FunctionPrototype> {
        self.modules
            .iter()
            .flat_map(|module| module.function_iterator())
            .chain(BUILTIN_FNS.iter().map(|f| *f))
    }

    fn eval_function_call(
        &self,
        call: &FunctionCall,
        bound_args: &[BoundArgument],
    ) -> CreateFunctionResult {
        // first eval all the arguments for the function call and collect the results in an array
        // Any error here will short circuit the eval
        let mut resolved_args = Vec::with_capacity(call.args.len());
        for arg in call.args.iter() {
            let arg_result = self.eval_private(arg, bound_args)?;
            resolved_args.push(arg_result);
        }

        // now that we have resolved all the arguments, look for a matching function prototype
        let name = call.function_name.clone();
        // first check the bound args for a matching function
        let mut resolved = bound_args
            .iter()
            .find(|bound| &*bound.arg_name == &*name)
            .map(|bound| bound.value.clone());

        if resolved.is_none() {
            let function = self.find_function(name, resolved_args.as_slice())?;
            let res = function.apply(resolved_args, self)?;
            resolved = Some(res);
        }
        let resolved = resolved.unwrap();

        if let Some(mapper) = call.mapper.as_ref() {
            self.eval_mapped_function(resolved, mapper, bound_args)
        } else {
            Ok(resolved)
        }
    }

    fn eval_mapped_function(
        &self,
        resolved_outer: AnyFunction,
        mapper: &FunctionMapper,
        bound_args: &[BoundArgument],
    ) -> CreateFunctionResult {
        let (memoized, resetter) = create_memoized_fun(resolved_outer);
        let bound_arg = BoundArgument::new(mapper.arg_name.clone(), memoized);
        let mut all_bound_args = Vec::with_capacity(bound_args.len() + 1);
        all_bound_args.push(bound_arg);
        for arg in bound_args.iter() {
            all_bound_args.push(arg.clone());
        }

        let mapped = self.eval_private(&mapper.mapper_body, all_bound_args.as_slice())?;
        let resolved = finish_mapped(mapped, resetter);
        Ok(resolved)
    }

    fn find_function<'a, 'b>(
        &'a self,
        name: IString,
        arguments: &'b [AnyFunction],
    ) -> Result<&'a FunctionPrototype, Error> {
        let name_clone = name.clone();
        let best_match: Option<&'a FunctionPrototype> = {
            let iter = self
                .modules
                .iter()
                .rev()
                .flat_map(|module| module.function_iterator())
                .chain(BUILTIN_FNS.iter().map(|f| *f))
                .filter(|proto| proto.name() == &*name_clone);

            let mut current_best: Option<&'a FunctionPrototype> = None;

            for candidate in iter {
                if candidate.do_arguments_match(arguments) {
                    if !candidate.is_variadic() {
                        return Ok(candidate);
                    } else if current_best.is_none() {
                        current_best = Some(candidate);
                    } else {
                        let option1 = current_best.unwrap();

                        return Err(errors::ambiguous_varargs_functions(
                            name, arguments, option1, candidate,
                        ));
                    }
                }
            }
            current_best
        };

        best_match.ok_or_else(|| errors::no_such_method(name, arguments))
    }

    fn eval_arg_usage(&self, name: IString, bound_args: &[BoundArgument]) -> CreateFunctionResult {
        let bound_arg = bound_args
            .iter()
            .filter(|a| a.arg_name == name)
            .next()
            .ok_or_else(|| errors::no_such_argument(name))?;

        Ok(bound_arg.value.clone())
    }
}

pub struct Interpreter {
    internal: Compiler,
}

impl Interpreter {
    pub fn new() -> Interpreter {
        Interpreter {
            internal: Compiler::new(),
        }
    }

    pub fn add_std_lib(&mut self) {
        for lib in self::libraries::STDLIBS.iter() {
            self.add_module(lib)
                .expect("Failed to add std library. This is a bug!");
        }
    }

    pub fn add_module(&mut self, source: &Source) -> Result<(), Error> {
        use std::borrow::Borrow;

        let module_name: IString = source.get_name().into();
        let text = source.read_to_str()?;
        let parsed = parser::parse_program(module_name.clone(), text.borrow())?;
        self.internal.add_module(Module::new(module_name, parsed.assignments));
        Ok(())
    }

    pub fn eval(&mut self, program: &str) -> CreateFunctionResult {
        let module_name: IString = "main".into();
        let Program { assignments, expr } = parser::parse_program(module_name.clone(), program)?;

        if let Some(expression) = expr {
            let main_module = Module::new(module_name, assignments);
            self.internal.add_module(main_module);

            self.internal.eval(&expression)
        } else {
            bail!("The program does not end with an expression. An expression is required")
        }
    }

    pub fn eval_any(&mut self, program: &str) -> Result<Option<AnyFunction>, Error> {
        let module_name: IString = "main".into();
        let Program { assignments, expr } = parser::parse_program(module_name.clone(), program)?;
        let main_module = Module::new(module_name, assignments);
        self.internal.add_module(main_module);

        if let Some(expression) = expr {
            let function = self.internal.eval(&expression)?;
            Ok(Some(function))
        } else {
            Ok(None)
        }
    }

    pub fn function_iterator(&self) -> impl Iterator<Item = &FunctionPrototype> {
        self.internal.function_iterator()
    }
}