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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! This crate contains contains the implementation for the gluon programming language.
//!
//! Gluon is a programming language suitable for embedding in an existing application to extend its
//! behaviour. For information about how to use this library the best resource currently is the
//! [tutorial](https://github.com/Marwes/gluon/blob/master/TUTORIAL.md) which contains examples on
//! how to write gluon programs as well as how to run them using this library.
#[macro_use]
extern crate log;
#[macro_use]
extern crate quick_error;

#[macro_use]
pub extern crate gluon_vm as vm;
pub extern crate gluon_base as base;
pub extern crate gluon_parser as parser;
pub extern crate gluon_check as check;

mod io;
pub mod import;

pub use vm::thread::{RootedThread, Thread};

use std::result::Result as StdResult;
use std::string::String as StdString;

use base::ast;
use base::error::Errors;
use base::types::TcType;
use base::symbol::{Name, NameBuf, Symbol, Symbols, SymbolModule};
use base::metadata::Metadata;

use vm::Variants;
use vm::api::generic::A;
use vm::api::{Getable, VMType, Generic, IO};
use vm::Error as VMError;
use vm::compiler::CompiledFunction;
use vm::thread::{RootedValue, ThreadInternal};
use vm::internal::ClosureDataDef;

quick_error! {
    /// Error type wrapping all possible errors that can be generated from gluon
    #[derive(Debug)]
    pub enum Error {
        /// Error found when parsing gluon code
        Parse(err: Errors<::parser::Error>) {
            description(err.description())
            display("{}", err)
            from()
        }
        /// Error found when typechecking gluon code
        Typecheck(err: ::base::error::InFile<::check::typecheck::TypeError<Symbol>>) {
            description(err.description())
            display("{}", err)
            from()
        }
        /// Error found when performing an IO action such as loading a file
        IO(err: ::std::io::Error) {
            description(err.description())
            display("{}", err)
            from()
        }
        /// Error found when executing code in the virtual machine
        VM(err: ::vm::Error) {
            description(err.description())
            display("{}", err)
            from()
        }
        /// Error found when expanding macros
        Macro(err: Errors<::vm::macros::Error>) {
            description(err.description())
            display("{}", err)
            from()
        }
    }
}

/// Type alias for results returned by gluon
pub type Result<T> = StdResult<T, Error>;

/// Type which makes parsing, typechecking and compiling an AST into bytecode
pub struct Compiler {
    symbols: Symbols,
    implicit_prelude: bool,
}

/// Advanced compiler pipeline which ensures that the compilation phases are run in order even if
/// not the entire compilation procedure is needed
pub mod compiler_pipeline {
    use super::*;

    use base::ast;
    use base::types::TcType;
    use base::symbol::Symbol;

    use vm::compiler::CompiledFunction;
    use vm::thread::{RootedValue, ThreadInternal};
    use vm::internal::ClosureDataDef;

    pub struct MacroValue(pub ast::LExpr<ast::TcIdent<Symbol>>);

    pub trait MacroExpandable {
        fn expand_macro(self,
                        compiler: &mut Compiler,
                        thread: &Thread,
                        file: &str)
                        -> Result<MacroValue>;
    }

    impl<'s> MacroExpandable for &'s str {
        fn expand_macro(self,
                        compiler: &mut Compiler,
                        thread: &Thread,
                        file: &str)
                        -> Result<MacroValue> {
            compiler.parse_expr(file, self)
                    .map_err(From::from)
                    .and_then(|expr| expr.expand_macro(compiler, thread, file))
        }
    }

    impl MacroExpandable for ast::LExpr<ast::TcIdent<Symbol>> {
        fn expand_macro(mut self,
                        compiler: &mut Compiler,
                        thread: &Thread,
                        file: &str)
                        -> Result<MacroValue> {
            if compiler.implicit_prelude {
                compiler.include_implicit_prelude(file, &mut self);
            }
            try!(thread.get_macros().run(thread, &mut self));
            Ok(MacroValue(self))
        }
    }

    pub struct TypecheckValue(pub ast::LExpr<ast::TcIdent<Symbol>>, pub TcType);

    pub trait Typecheckable {
        fn typecheck(self,
                     compiler: &mut Compiler,
                     thread: &Thread,
                     file: &str,
                     expr_str: &str)
                     -> Result<TypecheckValue>
            where Self: Sized
        {
            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<&TcType>)
                              -> Result<TypecheckValue>;
    }
    impl<T> Typecheckable for T
        where T: MacroExpandable
{
        fn typecheck_expected(self,
                              compiler: &mut Compiler,
                              thread: &Thread,
                              file: &str,
                              expr_str: &str,
                              expected_type: Option<&TcType>)
                              -> Result<TypecheckValue>
            where Self: Sized
        {
            self.expand_macro(compiler, thread, file)
                .and_then(|expr| {
                    expr.typecheck_expected(compiler, thread, file, expr_str, expected_type)
                })
        }
    }
    impl Typecheckable for MacroValue {
        fn typecheck_expected(mut self,
                              compiler: &mut Compiler,
                              thread: &Thread,
                              file: &str,
                              expr_str: &str,
                              expected_type: Option<&TcType>)
                              -> Result<TypecheckValue>
            where Self: Sized
        {
            compiler.typecheck_expr_expected(thread, file, expr_str, &mut self.0, expected_type)
                    .map(move |typ| TypecheckValue(self.0, typ))
        }
    }

    pub struct CompileValue(pub ast::LExpr<ast::TcIdent<Symbol>>, pub TcType, pub CompiledFunction);

    pub trait Compileable<Extra> {
        fn compile(self,
                   compiler: &mut Compiler,
                   thread: &Thread,
                   file: &str,
                   arg: Extra)
                   -> Result<CompileValue>;
    }
    impl<'a, 'b, T> Compileable<(&'a str, Option<&'b TcType>)> for T
        where T: Typecheckable
{
        fn compile(self,
                   compiler: &mut Compiler,
                   thread: &Thread,
                   file: &str,
                   (expr_str, expected_type): (&'a str, Option<&'b TcType>))
                   -> Result<CompileValue> {
            self.typecheck_expected(compiler, thread, file, expr_str, expected_type)
                .and_then(|tc_value| tc_value.compile(compiler, thread, file, ()))
        }
    }
    impl<Extra> Compileable<Extra> for TypecheckValue {
        fn compile(self,
                   compiler: &mut Compiler,
                   thread: &Thread,
                   file: &str,
                   _: Extra)
                   -> Result<CompileValue> {
            let function = compiler.compile_script(thread, file, &self.0);
            Ok(CompileValue(self.0, self.1, function))
        }
    }

    pub trait Executable<Extra> {
        fn run_expr<'vm>(self,
                         compiler: &mut Compiler,
                         vm: &'vm Thread,
                         name: &str,
                         arg: Extra)
                         -> Result<(RootedValue<&'vm Thread>, TcType)>;
        fn load_script(self,
                       compiler: &mut Compiler,
                       vm: &Thread,
                       filename: &str,
                       arg: Extra)
                       -> Result<()>;
    }
    impl<C, Extra> Executable<Extra> for C
        where C: Compileable<Extra>
{
        fn run_expr<'vm>(self,
                         compiler: &mut Compiler,
                         vm: &'vm Thread,
                         name: &str,
                         arg: Extra)
                         -> Result<(RootedValue<&'vm Thread>, TcType)> {

            self.compile(compiler, vm, name, arg)
                .and_then(|v| v.run_expr(compiler, vm, name, ()))
        }
        fn load_script(self,
                       compiler: &mut Compiler,
                       vm: &Thread,
                       filename: &str,
                       arg: Extra)
                       -> Result<()> {
            self.compile(compiler, vm, filename, arg)
                .and_then(|v| v.load_script(compiler, vm, filename, ()))
        }
    }
    impl Executable<()> for CompileValue {
        fn run_expr<'vm>(self,
                         _compiler: &mut Compiler,
                         vm: &'vm Thread,
                         name: &str,
                         _: ())
                         -> Result<(RootedValue<&'vm Thread>, TcType)> {
            let CompileValue(_, typ, mut function) = self;
            function.id = Symbol::new(name);
            let function = vm.global_env().new_function(function);
            let closure = {
                let stack = vm.current_frame();
                vm.alloc(&stack.stack, ClosureDataDef(function, &[]))
            };
            let value = try!(vm.call_module(&typ, closure));
            Ok((vm.root_value_ref(value), typ))
        }
        fn load_script(self,
                       _compiler: &mut Compiler,
                       vm: &Thread,
                       _filename: &str,
                       _: ())
                       -> Result<()> {
            use check::metadata;

            let CompileValue(mut expr, typ, function) = self;
            let metadata = metadata::metadata(&*vm.get_env(), &mut expr);
            let function = vm.global_env().new_function(function);
            let closure = {
                let stack = vm.current_frame();
                vm.alloc(&stack.stack, ClosureDataDef(function, &[]))
            };
            let value = try!(vm.call_module(&typ, closure));
            try!(vm.global_env().set_global(function.name.clone(), typ, metadata, value));
            Ok(())
        }
    }
}

impl Compiler {
    /// Creates a new compiler with default settings
    pub fn new() -> Compiler {
        Compiler {
            symbols: Symbols::new(),
            implicit_prelude: true,
        }
    }

    /// Sets wheter the implicit prelude should be include when compiling a file using this
    /// compiler (default: true)
    pub fn implicit_prelude(mut self, implicit_prelude: bool) -> Compiler {
        self.implicit_prelude = implicit_prelude;
        self
    }

    /// Parse `input`, returning an expression if successful
    pub fn parse_expr(&mut self,
                      file: &str,
                      input: &str)
                      -> StdResult<ast::LExpr<ast::TcIdent<Symbol>>, Errors<::parser::Error>> {
        Ok(try!(::parser::parse_tc(&mut SymbolModule::new(file.into(), &mut self.symbols),
                                   input)
                    .map_err(|t| t.1)))
    }

    /// Parse `input`, returning an expression if successful
    pub fn parse_partial_expr(&mut self,
                              file: &str,
                              input: &str)
                              -> StdResult<ast::LExpr<ast::TcIdent<Symbol>>,
                                           (Option<ast::LExpr<ast::TcIdent<Symbol>>>,
                                            Errors<::parser::Error>)> {
        ::parser::parse_tc(&mut SymbolModule::new(file.into(), &mut self.symbols),
                           input)
    }

    /// Parse and typecheck `expr_str` returning the typechecked expression and type of the
    /// expression
    pub fn typecheck_expr(&mut self,
                          vm: &Thread,
                          file: &str,
                          expr_str: &str,
                          expr: &mut ast::LExpr<ast::TcIdent<Symbol>>)
                          -> Result<TcType> {
        self.typecheck_expr_expected(vm, file, expr_str, expr, None)
    }

    fn typecheck_expr_expected(&mut self,
                               vm: &Thread,
                               file: &str,
                               expr_str: &str,
                               expr: &mut ast::LExpr<ast::TcIdent<Symbol>>,
                               expected_type: Option<&TcType>)
                               -> Result<TcType> {
        use check::typecheck::Typecheck;
        use base::error;
        let env = vm.get_env();
        let mut tc = Typecheck::new(file.into(), &mut self.symbols, &*env);
        let typ = try!(tc.typecheck_expr_expected(expr, expected_type)
                         .map_err(|err| error::InFile::new(StdString::from(file), expr_str, err)));
        Ok(typ)
    }

    pub fn typecheck_str(&mut self,
                         vm: &Thread,
                         file: &str,
                         expr_str: &str,
                         expected_type: Option<&TcType>)
                         -> Result<(ast::LExpr<ast::TcIdent<Symbol>>, TcType)> {
        let mut expr = try!(self.parse_expr(file, expr_str));
        if self.implicit_prelude {
            self.include_implicit_prelude(file, &mut expr);
        }
        try!(vm.get_macros().run(vm, &mut expr));
        let typ = try!(self.typecheck_expr_expected(vm, file, expr_str, &mut expr, expected_type));
        Ok((expr, typ))
    }

    /// Compiles `expr` into a function which can be added and run by the `vm`
    pub fn compile_script(&mut self,
                          vm: &Thread,
                          filename: &str,
                          expr: &ast::LExpr<ast::TcIdent<Symbol>>)
                          -> CompiledFunction {
        use vm::compiler::Compiler;
        debug!("Compile `{}`", filename);
        let mut function = {
            let env = vm.get_env();
            let name = Name::new(filename);
            let name = NameBuf::from(name.module());
            let symbols = SymbolModule::new(StdString::from(name.as_ref()), &mut self.symbols);
            let mut compiler = Compiler::new(&*env, vm.global_env(), symbols);
            compiler.compile_expr(&expr)
        };
        function.id = Symbol::new(filename);
        function
    }

    /// Parses and typechecks `expr_str` followed by extracting metadata from the created
    /// expression
    pub fn extract_metadata(&mut self,
                            vm: &Thread,
                            file: &str,
                            expr_str: &str)
                            -> Result<(ast::LExpr<ast::TcIdent<Symbol>>, TcType, Metadata)> {
        use check::metadata;
        let (mut expr, typ) = try!(self.typecheck_str(vm, file, expr_str, None));

        let metadata = metadata::metadata(&*vm.get_env(), &mut expr);
        Ok((expr, typ, metadata))
    }

    /// Compiles `input` and if it is successful runs the resulting code and stores the resulting
    /// value in the vm.
    ///
    /// If at any point the function fails the resulting error is returned and nothing is added to
    /// the VM.
    pub fn load_script(&mut self, vm: &Thread, filename: &str, input: &str) -> Result<()> {
        let (expr, typ, metadata) = try!(self.extract_metadata(vm, filename, input));
        let function = self.compile_script(vm, filename, &expr);
        let function = vm.global_env().new_function(function);
        let closure = {
            let stack = vm.current_frame();
            vm.alloc(&stack.stack, ClosureDataDef(function, &[]))
        };
        let value = try!(vm.call_module(&typ, closure));
        try!(vm.global_env().set_global(function.name.clone(), typ, metadata, value));
        info!("Loaded module `{}` filename", filename);
        Ok(())
    }

    /// Loads `filename` and compiles and runs its input by calling `load_script`
    pub fn load_file(&mut self, vm: &Thread, filename: &str) -> Result<()> {
        use std::fs::File;
        use std::io::Read;
        let mut buffer = StdString::new();
        {
            let mut file = try!(File::open(filename));
            try!(file.read_to_string(&mut buffer));
        }
        let name = filename_to_module(filename);
        self.load_script(vm, &name, &buffer)
    }

    fn run_expr_<'vm>(&mut self,
                      vm: &'vm Thread,
                      name: &str,
                      expr_str: &str,
                      expected_type: Option<&TcType>)
                      -> Result<(RootedValue<&'vm Thread>, TcType)> {
        let (expr, typ) = try!(self.typecheck_str(vm, name, expr_str, expected_type));
        let mut function = self.compile_script(vm, name, &expr);
        function.id = Symbol::new(name);
        let function = vm.global_env().new_function(function);
        let closure = {
            let stack = vm.current_frame();
            vm.alloc(&stack.stack, ClosureDataDef(function, &[]))
        };
        let value = try!(vm.call_module(&typ, closure));
        Ok((vm.root_value_ref(value), typ))
    }

    /// Compiles and runs the expression in `expr_str`. If successful the value from running the
    /// expression is returned
    pub fn run_expr<'vm, T>(&mut self, vm: &'vm Thread, name: &str, expr_str: &str) -> Result<T>
        where T: Getable<'vm> + VMType
    {
        let expected = T::make_type(vm);
        let (value, actual) = try!(self.run_expr_(vm, name, expr_str, Some(&expected)));
        unsafe {
            T::from_value(vm, Variants::new(&value))
                .ok_or_else(move || Error::from(VMError::WrongType(expected, actual)))
        }
    }

    pub fn run_io_expr<'vm, T>(&mut self, vm: &'vm Thread, name: &str, expr_str: &str) -> Result<T>
        where T: Getable<'vm> + VMType,
              T::Type: Sized
    {
        let expected = IO::<T>::make_type(vm);
        let (value, actual) = try!(self.run_expr_(vm, name, expr_str, Some(&expected)));
        unsafe {
            T::from_value(vm, Variants::new(&value))
                .ok_or_else(move || Error::from(VMError::WrongType(expected, actual)))
        }
    }

    fn include_implicit_prelude(&mut self,
                                name: &str,
                                expr: &mut ast::LExpr<ast::TcIdent<Symbol>>) {
        use std::mem;
        if name == "std.prelude" {
            return;
        }

        let prelude_import = r#"
    let __implicit_prelude = import "std/prelude.glu"
    and { Num, Eq, Ord, Show, Functor, Monad, Bool, Option, Result, not } = __implicit_prelude

    let { (+), (-), (*), (/) } = __implicit_prelude.num_Int
    and { (==) } = __implicit_prelude.eq_Int
    and { (<), (<=), (>=), (>) } = __implicit_prelude.make_Ord __implicit_prelude.ord_Int

    let { (+), (-), (*), (/) } = __implicit_prelude.num_Float
    and { (==) } = __implicit_prelude.eq_Float
    and { (<), (<=), (>=), (>) } = __implicit_prelude.make_Ord __implicit_prelude.ord_Float

    let { (==) } = __implicit_prelude.eq_Char
    and { (<), (<=), (>=), (>) } = __implicit_prelude.make_Ord __implicit_prelude.ord_Char

    in 0
    "#;
        let prelude_expr = self.parse_expr("", prelude_import).unwrap();
        let original_expr = mem::replace(expr, prelude_expr);
        fn assign_last_body(l: &mut ast::LExpr<ast::TcIdent<Symbol>>,
                            original_expr: ast::LExpr<ast::TcIdent<Symbol>>) {
            match l.value {
                ast::Expr::Let(_, ref mut e) => {
                    assign_last_body(e, original_expr);
                }
                _ => *l = original_expr,
            }
        }
        assign_last_body(expr, original_expr);
    }
}

pub fn filename_to_module(filename: &str) -> StdString {
    use std::path::Path;
    let path = Path::new(filename);
    let name = path.extension()
                   .map_or(filename, |ext| {
                       ext.to_str()
                          .map(|ext| &filename[..filename.len() - ext.len() - 1])
                          .unwrap_or(filename)
                   });

    name.replace("/", ".")
}

/// Creates a new virtual machine with support for importing other modules and with all primitives
/// loaded.
pub fn new_vm() -> RootedThread {
    let vm = RootedThread::new();
    vm.get_macros().insert(String::from("import"),
                           ::import::Import::new(::import::DefaultImporter));
    Compiler::new()
        .implicit_prelude(false)
        .run_expr::<Generic<A>>(&vm, "", r#" import "std/types.glu" "#)
        .unwrap();
    ::vm::primitives::load(&vm).expect("Loaded primitives library");
    ::vm::channel::load(&vm).expect("Loaded channel library");
    ::io::load(&vm).expect("Loaded IO library");
    vm
}