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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//! Advanced compiler pipeline which ensures that the compilation phases are run in order even if
//! not the entire compilation procedure is needed.
//!
//! Each trait in this module represents a stage in a full compilation so to only run compilation
//! up until and including typechecking the `Typecheckable` trait can be used. Furthermore, if
//! compilation should continue at some point after typechecking has succeeded, the result of
//! typechecking (`TypecheckValue`) can be used as input to the next stage, ensuring that it is
//! difficult to forget a stage.

use std::borrow::{Borrow, BorrowMut};

use base::ast::SpannedExpr;
use base::error::InFile;
use base::types::ArcType;
use base::source::Source;
use base::symbol::{Name, NameBuf, Symbol, SymbolModule};

use vm::compiler::CompiledFunction;
use vm::future::{BoxFutureValue, FutureValue};
use vm::macros::MacroExpander;
use vm::thread::{RootedValue, Thread, ThreadInternal};

use {Compiler, Error, Result};

/// Result type of successful macro expansion
pub struct MacroValue<E> {
    pub expr: E,
}

pub trait MacroExpandable {
    type Expr: BorrowMut<SpannedExpr<Symbol>>;

    fn expand_macro(self,
                    compiler: &mut Compiler,
                    thread: &Thread,
                    file: &str)
                    -> Result<MacroValue<Self::Expr>>
        where Self: Sized
    {
        let mut macros = MacroExpander::new(thread);
        let expr = self.expand_macro_with(compiler, &mut macros, file)?;
        macros.finish()?;
        Ok(expr)
    }

    fn expand_macro_with(self,
                         compiler: &mut Compiler,
                         macros: &mut MacroExpander,
                         file: &str)
                         -> Result<MacroValue<Self::Expr>>;
}

impl<'s> MacroExpandable for &'s str {
    type Expr = SpannedExpr<Symbol>;

    fn expand_macro_with(self,
                         compiler: &mut Compiler,
                         macros: &mut MacroExpander,
                         file: &str)
                         -> Result<MacroValue<Self::Expr>> {

        compiler
            .parse_expr(file, self)
            .map_err(From::from)
            .and_then(|mut expr| {
                          expr.expand_macro_with(compiler, macros, file)?;
                          Ok(MacroValue { expr: expr })
                      })
    }
}

impl<'s> MacroExpandable for &'s mut SpannedExpr<Symbol> {
    type Expr = &'s mut SpannedExpr<Symbol>;

    fn expand_macro_with(self,
                         compiler: &mut Compiler,
                         macros: &mut MacroExpander,
                         file: &str)
                         -> Result<MacroValue<Self::Expr>> {
        if compiler.implicit_prelude {
            compiler.include_implicit_prelude(file, self);
        }
        macros.run(self);
        Ok(MacroValue { expr: self })
    }
}

/// Result type of successful typechecking
pub struct TypecheckValue<E> {
    pub expr: E,
    pub typ: ArcType,
}

pub trait Typecheckable: Sized {
    type Expr: BorrowMut<SpannedExpr<Symbol>>;

    fn typecheck(self,
                 compiler: &mut Compiler,
                 thread: &Thread,
                 file: &str,
                 expr_str: &str)
                 -> Result<TypecheckValue<Self::Expr>> {
        self.typecheck_expected(compiler, thread, file, expr_str, None)
    }
    fn typecheck_expected(self,
                          compiler: &mut Compiler,
                          thread: &Thread,
                          file: &str,
                          expr_str: &str,
                          expected_type: Option<&ArcType>)
                          -> Result<TypecheckValue<Self::Expr>>;
}

impl<T> Typecheckable for T
    where T: MacroExpandable
{
    type Expr = T::Expr;

    fn typecheck_expected(self,
                          compiler: &mut Compiler,
                          thread: &Thread,
                          file: &str,
                          expr_str: &str,
                          expected_type: Option<&ArcType>)
                          -> Result<TypecheckValue<Self::Expr>> {

        self.expand_macro(compiler, thread, file)
            .and_then(|expr| {
                          expr.typecheck_expected(compiler, thread, file, expr_str, expected_type)
                      })
    }
}

impl<E> Typecheckable for MacroValue<E>
    where E: BorrowMut<SpannedExpr<Symbol>>
{
    type Expr = E;

    fn typecheck_expected(mut self,
                          compiler: &mut Compiler,
                          thread: &Thread,
                          file: &str,
                          expr_str: &str,
                          expected_type: Option<&ArcType>)
                          -> Result<TypecheckValue<Self::Expr>> {
        use check::typecheck::Typecheck;

        let env = thread.get_env();
        let mut tc = Typecheck::new(file.into(), &mut compiler.symbols, &*env);

        let typ = tc.typecheck_expr_expected(self.expr.borrow_mut(), expected_type)
            .map_err(|err| InFile::new(file, expr_str, err))?;

        Ok(TypecheckValue {
               expr: self.expr,
               typ: typ,
           })
    }
}

/// Result of successful compilation
pub struct CompileValue<E> {
    pub expr: E,
    pub typ: ArcType,
    pub function: CompiledFunction,
}

pub trait Compileable<Extra> {
    type Expr;

    fn compile(self,
               compiler: &mut Compiler,
               thread: &Thread,
               file: &str,
               expr_str: &str,
               arg: Extra)
               -> Result<CompileValue<Self::Expr>>;
}
impl<'a, 'b, T> Compileable<Option<&'b ArcType>> for T
    where T: Typecheckable
{
    type Expr = T::Expr;

    fn compile(self,
               compiler: &mut Compiler,
               thread: &Thread,
               file: &str,
               expr_str: &str,
               expected_type: Option<&'b ArcType>)
               -> Result<CompileValue<Self::Expr>> {

        self.typecheck_expected(compiler, thread, file, expr_str, expected_type)
            .and_then(|tc_value| tc_value.compile(compiler, thread, file, expr_str, ()))
    }
}
impl<E, Extra> Compileable<Extra> for TypecheckValue<E>
    where E: Borrow<SpannedExpr<Symbol>>
{
    type Expr = E;

    fn compile(self,
               compiler: &mut Compiler,
               thread: &Thread,
               filename: &str,
               expr_str: &str,
               _: Extra)
               -> Result<CompileValue<Self::Expr>> {
        use vm::compiler::Compiler;
        debug!("Compile `{}`", filename);
        let mut function = {
            let env = thread.get_env();
            let name = Name::new(filename);
            let name = NameBuf::from(name.module());
            let symbols = SymbolModule::new(String::from(AsRef::<str>::as_ref(&name)),
                                            &mut compiler.symbols);
            let source = Source::new(expr_str);
            let mut compiler = Compiler::new(&*env,
                                             thread.global_env(),
                                             symbols,
                                             &source,
                                             filename.to_string(),
                                             compiler.emit_debug_info);
            compiler.compile_expr(self.expr.borrow())?
        };
        function.id = Symbol::from(filename);
        Ok(CompileValue {
               expr: self.expr,
               typ: self.typ,
               function: function,
           })
    }
}

/// Result of successful execution
pub struct ExecuteValue<'vm, E> {
    pub expr: E,
    pub typ: ArcType,
    pub value: RootedValue<&'vm Thread>,
}

pub trait Executable<'vm, Extra> {
    type Expr;

    fn run_expr(self,
                compiler: &mut Compiler,
                vm: &'vm Thread,
                name: &str,
                expr_str: &str,
                arg: Extra)
                -> BoxFutureValue<'vm, ExecuteValue<'vm, Self::Expr>, Error>;

    fn load_script(self,
                   compiler: &mut Compiler,
                   vm: &'vm Thread,
                   filename: &str,
                   expr_str: &str,
                   arg: Extra)
                   -> BoxFutureValue<'vm, (), Error>;
}
impl<'vm, C, Extra> Executable<'vm, Extra> for C
    where C: Compileable<Extra>,
          C::Expr: BorrowMut<SpannedExpr<Symbol>> + Send + 'vm
{
    type Expr = C::Expr;

    fn run_expr(self,
                compiler: &mut Compiler,
                vm: &'vm Thread,
                name: &str,
                expr_str: &str,
                arg: Extra)
                -> BoxFutureValue<'vm, ExecuteValue<'vm, Self::Expr>, Error> {

        match self.compile(compiler, vm, name, expr_str, arg) {
            Ok(v) => v.run_expr(compiler, vm, name, expr_str, ()),
            Err(err) => FutureValue::Value(Err(err)),
        }
    }
    fn load_script(self,
                   compiler: &mut Compiler,
                   vm: &'vm Thread,
                   filename: &str,
                   expr_str: &str,
                   arg: Extra)
                   -> BoxFutureValue<'vm, (), Error> {

        match self.compile(compiler, vm, filename, expr_str, arg) {
            Ok(v) => v.load_script(compiler, vm, filename, expr_str, ()),
            Err(err) => FutureValue::Value(Err(err)),
        }
    }
}
impl<'vm, E> Executable<'vm, ()> for CompileValue<E>
    where E: BorrowMut<SpannedExpr<Symbol>> + Send + 'vm
{
    type Expr = E;

    fn run_expr(self,
                _compiler: &mut Compiler,
                vm: &'vm Thread,
                name: &str,
                _expr_str: &str,
                _: ())
                -> BoxFutureValue<'vm, ExecuteValue<'vm, Self::Expr>, Error> {

        let CompileValue {
            expr,
            typ,
            mut function,
        } = self;
        function.id = Symbol::from(name);
        let closure = try_future!(vm.global_env().new_global_thunk(function));
        vm.call_thunk(closure)
            .map(|(vm, value)| {
                     ExecuteValue {
                         expr: expr,
                         typ: typ,
                         value: vm.root_value(value),
                     }
                 })
            .map_err(Error::from)
            .boxed()
    }
    fn load_script(self,
                   _compiler: &mut Compiler,
                   vm: &'vm Thread,
                   filename: &str,
                   _expr_str: &str,
                   _: ())
                   -> BoxFutureValue<'vm, (), Error> {
        use check::metadata;

        let CompileValue {
            mut expr,
            typ,
            function,
        } = self;
        let metadata = metadata::metadata(&*vm.get_env(), expr.borrow_mut());
        let closure = try_future!(vm.global_env().new_global_thunk(function));
        let filename = filename.to_string();
        vm.call_thunk(closure)
            .map_err(Error::from)
            .and_then(move |(_, value)| {
                          try_future!(vm.set_global(closure.function.name.clone(),
                                                    typ,
                                                    metadata,
                                                    value));
                          info!("Loaded module `{}` filename", filename);
                          FutureValue::sync(Ok(()))
                      })
            .boxed()
    }
}