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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Implementation of the `import!` macro.

use std::any::Any;
use std::borrow::Cow;
use std::collections::hash_map::Entry;
use std::fs::File;
use std::io;
use std::io::Read;
use std::mem;
use std::path::PathBuf;
use std::sync::{Mutex, RwLock};

use futures::sync::oneshot;
use futures::{future, Future};

use itertools::Itertools;

use crate::base::ast::{expr_to_path, Expr, Literal, SpannedExpr, Typed, TypedIdent};
use crate::base::error::{Errors, InFile};
use crate::base::filename_to_module;
use crate::base::fnv::FnvMap;
use crate::base::pos::{self, BytePos, Span};
use crate::base::symbol::Symbol;
use crate::base::types::{ArcType, Type};

use crate::vm::{
    self,
    macros::{Error as MacroError, Macro, MacroExpander, MacroFuture},
    thread::{Thread, ThreadInternal},
    ExternLoader, ExternModule,
};

use super::Compiler;

quick_error! {
    /// Error type for the import macro
    #[derive(Debug)]
    pub enum Error {
        /// The importer found a cyclic dependency when loading files
        CyclicDependency(module: String, cycle: Vec<String>) {
            description("Cyclic dependency")
            display(
                "Module '{}' occurs in a cyclic dependency: `{}`",
                module,
                cycle.iter().chain(Some(module)).format(" -> ")
            )
        }
        /// Generic message error
        String(message: String) {
            description(message)
            display("{}", message)
        }
        /// The importer could not load the imported file
        IO(err: io::Error) {
            description(err.description())
            display("{}", err)
            from()
        }
    }
}

pub const COMPILER_KEY: &str = "Compiler";

include!(concat!(env!("OUT_DIR"), "/std_modules.rs"));

pub trait Importer: Any + Clone + Sync + Send {
    fn import(
        &self,
        compiler: &mut Compiler,
        vm: &Thread,
        earlier_errors_exist: bool,
        modulename: &str,
        input: &str,
        expr: SpannedExpr<Symbol>,
    ) -> Result<(), (Option<ArcType>, MacroError)>;
}

#[derive(Clone)]
pub struct DefaultImporter;
impl Importer for DefaultImporter {
    fn import(
        &self,
        compiler: &mut Compiler,
        vm: &Thread,
        earlier_errors_exist: bool,
        modulename: &str,
        input: &str,
        mut expr: SpannedExpr<Symbol>,
    ) -> Result<(), (Option<ArcType>, MacroError)> {
        use crate::compiler_pipeline::*;

        let result = {
            let result = MacroValue { expr: &mut expr }
                .typecheck(compiler, vm, modulename, input)
                .map_err(|err| err.into());

            if result.is_ok() && earlier_errors_exist {
                trace!(
                    "Typechecked {} but earlier errors exist, bailing",
                    modulename
                );
                // We must not pass error patterns or expressions to the core translator so break
                // early. An error will be returned by the macro expander so we can just return Ok
                return Err((
                    Some(expr.env_type_of(&*vm.get_env())),
                    Box::new(crate::Error::Multiple(Errors::default())),
                ));
            }

            result.and_then(|value| {
                value
                    .load_script(compiler, vm, modulename, input, ())
                    .wait()
            })
        };

        result.map_err(|err| (Some(expr.env_type_of(&*vm.get_env())), err.into()))
    }
}

enum UnloadedModule {
    Source(Cow<'static, str>),
    Extern(ExternModule),
}

/// Macro which rewrites occurances of `import! "filename"` to a load of that file if it is not
/// already loaded and then a global access to the loaded module
pub struct Import<I = DefaultImporter> {
    pub paths: RwLock<Vec<PathBuf>>,
    pub loaders: RwLock<FnvMap<String, ExternLoader>>,
    pub importer: I,

    /// Map of modules currently being loaded
    loading: Mutex<FnvMap<String, future::Shared<oneshot::Receiver<()>>>>,
}

impl<I> Import<I> {
    /// Creates a new import macro
    pub fn new(importer: I) -> Import<I> {
        Import {
            paths: RwLock::new(vec![PathBuf::from(".")]),
            loaders: RwLock::default(),
            importer: importer,
            loading: Mutex::default(),
        }
    }

    /// Adds a path to the list of paths which the importer uses to find files
    pub fn add_path<P: Into<PathBuf>>(&self, path: P) {
        self.paths.write().unwrap().push(path.into());
    }

    pub fn set_paths(&self, paths: Vec<PathBuf>) {
        *self.paths.write().unwrap() = paths;
    }

    pub fn add_loader(&self, module: &str, loader: ExternLoader) {
        self.loaders
            .write()
            .unwrap()
            .insert(String::from(module), loader);
    }

    pub fn modules(&self) -> Vec<Cow<'static, str>> {
        STD_LIBS
            .iter()
            .map(|t| Cow::Borrowed(t.0))
            .chain(self.loaders.read().unwrap().keys().cloned().map(Cow::Owned))
            .collect()
    }

    fn get_unloaded_module(
        &self,
        vm: &Thread,
        module: &str,
        filename: &str,
    ) -> Result<UnloadedModule, MacroError> {
        let mut buffer = String::new();

        // Retrieve the source, first looking in the standard library included in the
        // binary

        let std_file = STD_LIBS.iter().find(|tup| tup.0 == module);
        if let Some(tup) = std_file {
            return Ok(UnloadedModule::Source(Cow::Borrowed(tup.1)));
        }
        Ok(match std_file {
            Some(tup) => UnloadedModule::Source(Cow::Borrowed(tup.1)),
            None => {
                {
                    let mut loaders = self.loaders.write().unwrap();
                    if let Some(loader) = loaders.get_mut(module) {
                        let value = loader(vm)?;
                        return Ok(UnloadedModule::Extern(value));
                    }
                }
                let paths = self.paths.read().unwrap();
                let file = paths
                    .iter()
                    .filter_map(|p| {
                        let base = p.join(filename);
                        match File::open(&base) {
                            Ok(file) => Some(file),
                            Err(_) => None,
                        }
                    })
                    .next();
                let mut file = file.ok_or_else(|| {
                    Error::String(format!(
                        "Could not find module '{}'. Searched {}.",
                        module,
                        paths
                            .iter()
                            .map(|p| format!("`{}`", p.display()))
                            .format(", ")
                    ))
                })?;
                file.read_to_string(&mut buffer)?;
                UnloadedModule::Source(Cow::Owned(buffer))
            }
        })
    }

    pub fn load_module(
        &self,
        compiler: &mut Compiler,
        vm: &Thread,
        macros: &mut MacroExpander,
        module_id: &Symbol,
        span: Span<BytePos>,
    ) -> Result<Option<impl Future<Item = (), Error = ()>>, (Option<ArcType>, MacroError)>
    where
        I: Importer,
    {
        assert!(module_id.is_global());
        let modulename = module_id.name().definition_name();
        let mut filename = modulename.replace(".", "/");
        filename.push_str(".glu");
        {
            let state = get_state(macros);
            if state.visited.iter().any(|m| **m == *filename) {
                let cycle = state
                    .visited
                    .iter()
                    .skip_while(|m| **m != *filename)
                    .cloned()
                    .collect();
                return Err((
                    None,
                    Error::CyclicDependency(filename.clone(), cycle).into(),
                ));
            }
            state.visited.push(filename.clone());
        }

        // Prevent any other threads from importing this module while we compile it
        let sender = {
            let mut loading = self.loading.lock().unwrap();
            match loading.entry(module_id.to_string()) {
                Entry::Occupied(entry) => {
                    get_state(macros).visited.pop();
                    return Ok(Some(entry.get().clone().map(|_| ()).map_err(|_| ())));
                }
                Entry::Vacant(entry) => {
                    let (sender, receiver) = oneshot::channel();
                    entry.insert(receiver.shared());
                    sender
                }
            }
        };
        if vm.global_env().global_exists(module_id.definition_name()) {
            let _ = sender.send(());
            get_state(macros).visited.pop();
            return Ok(None);
        }

        let result = self.load_module_(compiler, vm, macros, module_id, &filename, span);

        if let Err((ref typ, ref err)) = result {
            debug!("Import error {}: {}", module_id, err);
            if let Some(typ) = typ {
                debug!("Import got type {}", typ);
            }
        }

        let _ = sender.send(());

        get_state(macros).visited.pop();
        self.loading.lock().unwrap().remove(module_id.as_ref());

        result.map(|_| None)
    }

    fn load_module_(
        &self,
        compiler: &mut Compiler,
        vm: &Thread,
        macros: &mut MacroExpander,
        module_id: &Symbol,
        filename: &str,
        span: Span<BytePos>,
    ) -> Result<(), (Option<ArcType>, MacroError)>
    where
        I: Importer,
    {
        use crate::compiler_pipeline::*;

        let modulename = module_id.name().definition_name();
        // Retrieve the source, first looking in the standard library included in the
        // binary
        let unloaded_module = self
            .get_unloaded_module(vm, &modulename, &filename)
            .map_err(|err| (None, err.into()))?;

        match unloaded_module {
            UnloadedModule::Extern(ExternModule {
                value,
                typ,
                metadata,
            }) => {
                vm.set_global(module_id.clone(), typ, metadata, value.get_value())
                    .map_err(|err| (None, err.into()))?;
            }
            UnloadedModule::Source(file_contents) => {
                // Modules marked as this would create a cyclic dependency if they included the implicit
                // prelude
                let implicit_prelude = !file_contents.starts_with("//@NO-IMPLICIT-PRELUDE");
                compiler.set_implicit_prelude(implicit_prelude);

                let prev_errors = mem::replace(&mut macros.errors, Errors::new());

                let result =
                    file_contents.expand_macro_with(compiler, macros, &modulename, &file_contents);

                let has_errors =
                    macros.errors.has_errors() || result.is_err() || macros.error_in_expr;
                let errors = mem::replace(&mut macros.errors, prev_errors);
                if errors.has_errors() {
                    macros.errors.push(pos::spanned(
                        span,
                        Box::new(crate::Error::Macro(InFile::new(
                            compiler.code_map().clone(),
                            errors,
                        ))),
                    ));
                }

                let macro_result = match result {
                    Ok(m) => m,
                    Err((None, err)) => {
                        return Err((None, err.into()));
                    }
                    Err((Some(m), err)) => {
                        macros.errors.push(pos::spanned(span, err.into()));
                        m
                    }
                };

                self.importer.import(
                    compiler,
                    vm,
                    has_errors,
                    &modulename,
                    &file_contents,
                    macro_result.expr,
                )?;
            }
        }
        Ok(())
    }
}

/// Adds an extern module to `thread`, letting it be loaded with `import! name` from gluon code.
///
/// ```
/// extern crate gluon;
/// #[macro_use]
/// extern crate gluon_vm;
///
/// use gluon::vm::{self, ExternModule};
/// use gluon::{Compiler, Thread};
/// use gluon::import::add_extern_module;
///
/// fn yell(s: &str) -> String {
///     s.to_uppercase()
/// }
///
/// fn my_module(thread: &Thread) -> vm::Result<ExternModule> {
///     ExternModule::new(
///         thread,
///         record!{
///             message => "Hello World!",
///             yell => primitive!(1, yell)
///         }
///     )
/// }
///
/// fn main_() -> gluon::Result<()> {
///     let thread = gluon::new_vm();
///     add_extern_module(&thread, "my_module", my_module);
///     let script = r#"
///         let module = import! "my_module"
///         module.yell module.message
///     "#;
///     let (result, _) = Compiler::new().run_expr::<String>(&thread, "example", script)?;
///     assert_eq!(result, "HELLO WORLD!");
///     Ok(())
/// }
/// fn main() {
///     if let Err(err) = main_() {
///         panic!("{}", err)
///     }
/// }
/// ```
pub fn add_extern_module<F>(thread: &Thread, name: &str, loader: F)
where
    F: FnMut(&Thread) -> vm::Result<ExternModule> + Send + Sync + 'static,
{
    add_extern_module_(thread, name, Box::new(loader))
}

fn add_extern_module_(thread: &Thread, name: &str, loader: ExternLoader) {
    let opt_macro = thread.get_macros().get("import");
    let import = opt_macro
        .as_ref()
        .and_then(|mac| mac.downcast_ref::<Import>())
        .unwrap_or_else(|| {
            ice!(
                "Can't add an extern module with a import macro. \
                 Did you mean to create this `Thread` with `gluon::new_vm`"
            )
        });
    import.add_loader(name, loader);
}

macro_rules! add_extern_module_if {
    (
        #[cfg($($features: tt)*)],
        available_if = $msg: expr,
        args($vm: expr, $mod_name: expr, $loader: path)
    ) => {{
        #[cfg($($features)*)]
        $crate::import::add_extern_module($vm, $mod_name, $loader);

        #[cfg(not($($features)*))]
        $crate::import::add_extern_module($vm, $mod_name, |_: &::vm::thread::Thread| -> ::vm::Result<::vm::ExternModule> {
            Err(::vm::Error::Message(
                format!(
                    "{} is only available if {}",
                    $mod_name,
                    $msg
                )
            ))
        });
    }};
}

fn get_state<'m>(macros: &'m mut MacroExpander) -> &'m mut State {
    macros
        .state
        .entry(String::from("import"))
        .or_insert_with(|| {
            Box::new(State {
                visited: Vec::new(),
                modules_with_errors: FnvMap::default(),
            })
        })
        .downcast_mut::<State>()
        .unwrap()
}

struct State {
    visited: Vec<String>,
    modules_with_errors: FnvMap<String, Expr<Symbol>>,
}

impl<I> Macro for Import<I>
where
    I: Importer,
{
    fn expand(&self, macros: &mut MacroExpander, args: Vec<SpannedExpr<Symbol>>) -> MacroFuture {
        fn get_module_name(args: &[SpannedExpr<Symbol>]) -> Result<String, MacroError> {
            if args.len() != 1 {
                return Err(Error::String("Expected import to get 1 argument".into()).into());
            }

            let modulename = match args[0].value {
                Expr::Ident(_) | Expr::Projection(..) => {
                    let mut modulename = String::new();
                    expr_to_path(&args[0], &mut modulename)
                        .map_err(|err| Error::String(err.to_string()))?;
                    modulename
                }
                Expr::Literal(Literal::String(ref filename)) => {
                    format!("@{}", filename_to_module(filename))
                }
                _ => {
                    return Err(
                        Error::String("Expected a string literal or path to import".into()).into(),
                    );
                }
            };
            Ok(modulename)
        }

        let modulename = match get_module_name(&args) {
            Ok(modulename) => modulename,
            Err(err) => return Box::new(future::err(err)),
        };

        info!("import! {}", modulename);

        let vm = macros.vm;
        // Prefix globals with @ so they don't shadow any local variables
        let name = Symbol::from(if modulename.starts_with('@') {
            modulename.clone()
        } else {
            format!("@{}", modulename)
        });

        // Only load the script if it is not already loaded
        debug!("Import '{}' {:?}", modulename, get_state(macros).visited);
        if !vm.global_env().global_exists(&modulename) {
            if let Some(expr) = get_state(macros)
                .modules_with_errors
                .get(&modulename)
                .cloned()
            {
                macros.error_in_expr = true;
                trace!("Marking error due to {} import", modulename);
                return Box::new(future::ok(pos::spanned(args[0].span, expr)));
            }

            let mut compiler = macros
                .state
                .get(COMPILER_KEY)
                .and_then(|any| any.downcast_ref::<Compiler>())
                .expect("No `Compiler` in the macro state")
                .split();

            match self.load_module(&mut compiler, vm, macros, &name, args[0].span) {
                Ok(Some(future)) => {
                    let span = args[0].span;
                    return Box::new(
                        future
                            .map_err(|_| unreachable!())
                            .map(move |_| pos::spanned(span, Expr::Ident(TypedIdent::new(name)))),
                    );
                }
                Ok(None) => (),
                Err((typ, err)) => {
                    macros.errors.push(pos::spanned(args[0].span, err));

                    trace!(
                        "Marking error for {}: {}",
                        modulename,
                        typ.clone().unwrap_or_else(Type::hole)
                    );

                    let expr = Expr::Error(typ);
                    get_state(macros)
                        .modules_with_errors
                        .insert(modulename, expr.clone());

                    return Box::new(future::ok(pos::spanned(args[0].span, expr)));
                }
            }
        }
        Box::new(future::ok(pos::spanned(
            args[0].span,
            Expr::Ident(TypedIdent::new(name)),
        )))
    }
}