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
//! The module system.

mod read;

use std::collections::{HashMap, HashSet};
use std::fmt::{Debug, Formatter, Result as FmtResult};
use std::mem::swap;

use either::{Left, Right};
use gc::Gc;

use ast::{ConvertError as AstConvertError, ModuleHeaderError, convert_body, parse_module_header};
use collections::GcLinkedList;
use context::{Context, InterpreterContext};
use macro_expand::expand_module;
pub use modules::read::{ReadModuleError, ReadModuleErrorKind, read_module};
use symbol::Symbol;
use util::is_internal;
use value::Value;

/// A single OftLisp module.
///
/// TODO: Fix Debug bound.
#[derive(Finalize, Trace)]
pub struct Module<C: 'static + Context, IC: 'static + InterpreterContext> {
    /// The exported values.
    pub exports: HashMap<Symbol, Gc<Value<IC>>>,

    /// The exported macros.
    pub export_macros: HashMap<Symbol, Gc<Value<IC>>>,

    /// The imported symbols.
    pub imports: HashMap<Symbol, Vec<Symbol>>,

    /// The body of the module.
    pub body: Vec<(Symbol, Gc<C::Expr>)>,
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> Clone for Module<C, IC> {
    fn clone(&self) -> Self {
        Module {
            exports: self.exports.clone(),
            export_macros: self.export_macros.clone(),
            imports: self.imports.clone(),
            body: self.body.clone(),
        }
    }
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> Debug for Module<C, IC> {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        fmt.debug_struct("Module")
            .field("exports", &self.exports)
            .field("export_macros", &self.export_macros)
            .field("imports", &self.imports)
            .field("body", &self.body)
            .finish()
    }
}

/// A single OftLisp module, stripped of any info from the macro expansion
/// phase.
///
/// TODO: Fix Clone, Debug bounds.
#[derive(Clone, Debug, Finalize, Trace)]
pub struct ExportedModule<C: 'static + Context> {
    /// The exported values.
    pub exports: HashSet<Symbol>,

    /// The imported symbols.
    pub imports: HashMap<Symbol, Vec<Symbol>>,

    /// The body of the module.
    pub body: Vec<(Symbol, Gc<C::Expr>)>,
}

impl<C: 'static + Context> ExportedModule<C> {
    /// Converts from a [`Module`](struct.Module.html).
    pub fn from_module<IC: 'static + InterpreterContext>(m: &Module<C, IC>) -> ExportedModule<C> {
        let exports = m.exports.iter().map(|(&k, _)| k).collect();
        ExportedModule {
            exports,
            imports: m.imports.clone(),
            body: m.body.clone(),
        }
    }
}

/// A store of loaded modules.
///
/// TODO: Fix Clone, Debug bounds.
#[derive(Clone, Debug, Finalize, Trace)]
pub struct Modules<C: 'static + Context, IC: 'static + InterpreterContext> {
    mods: HashMap<Symbol, Module<C, IC>>,
    seen: HashSet<Symbol>,
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> Modules<C, IC> {
    /// Creates a new module store.
    pub fn new() -> Modules<C, IC> {
        Modules {
            mods: HashMap::new(),
            seen: HashSet::new(),
        }
    }

    /// Converts the modules into a map.
    ///
    /// This is done after macro expansion, to be able to pass the expanded
    /// modules to the compiler, independent of the `InterpreterContext` used
    /// for macro expansion.
    pub fn export(&self) -> HashMap<Symbol, ExportedModule<C>> {
        self.mods
            .iter()
            .map(|(&name, m)| (name, ExportedModule::from_module(m)))
            .collect()
    }

    /// Loads a module.
    pub fn load_module(
        &mut self,
        import_path: Symbol,
    ) -> Result<&Module<C, IC>, LoadModuleError<C, IC>> {
        if !self.mods.contains_key(&import_path) {
            if self.seen.contains(&import_path) {
                return Err(LoadModuleError::DependencyLoop(import_path));
            }
            self.seen.insert(import_path);
            self.load_module_real(import_path)?;
        }
        Ok(self.mods.get(&import_path).unwrap())
    }

    fn load_module_real(&mut self, import_path: Symbol) -> Result<(), LoadModuleError<C, IC>> {
        // Primitives are loaded specially.
        let primitives_import_path = "std/internal/primitives".into();
        if import_path == primitives_import_path {
            self.mods.insert(
                primitives_import_path,
                Module {
                    exports: IC::primitives(),
                    export_macros: HashMap::new(),
                    imports: HashMap::new(),
                    body: vec![],
                },
            );
            return Ok(());
        }

        // Load the module's source.
        let values = read_module(import_path)?;

        // Parse the header out.
        let (name, exports_sym, mut imports, body) = parse_module_header(values)?;
        if name != import_path {
            panic!("TODO name != import_path");
        }

        // Load imports.
        let mut env = GcLinkedList::new();
        let mut menv = GcLinkedList::new();
        let prelude = "std/prelude".into();
        if !is_internal(import_path) && !imports.contains_key(&prelude) {
            let m = self.load_module(prelude)?;
            imports.insert(
                prelude,
                m.exports
                    .keys()
                    .chain(m.export_macros.keys())
                    .cloned()
                    .collect(),
            );
        }
        for (from, vals) in &mut imports {
            let m = self.load_module(*from)?;
            let mut new_vals = vec![];
            for name in vals.iter() {
                if let Some(val) = m.export_macros.get(name) {
                    menv.push((*name, val.clone()));
                } else if let Some(val) = m.exports.get(name) {
                    env.push((*name, val.clone()));
                    new_vals.push(*name);
                } else {
                    return Err(LoadModuleError::NoSuchImport(*from, *name));
                }
            }
            swap(vals, &mut new_vals);
        }

        // Expand macros.
        debug!("Starting to expand {}...", import_path);
        let body = match expand_module(body, &mut env, &mut menv) {
            Ok(val) => val,
            Err(Left(err)) => return Err(LoadModuleError::MacroExpansionError(err)),
            Err(Right(err)) => unimplemented!("{:?}", err),
        };
        debug!("Done expanding {}...", import_path);

        // Convert the expanded module.
        let ibody: Vec<Gc<Value<IC>>> = body.clone();
        let body = body.into_iter()
            .map(|v| v.transmute_data::<C>().map(Gc::new))
            .collect::<Option<_>>()
            .ok_or(LoadModuleError::InvalidValue)?;
        let body: Vec<Gc<Value<C>>> = body;
        let ibody: Vec<Gc<Value<IC>>> = ibody;

        // Convert to the base AST type.
        let ibody = convert_body(ibody).map_err(
            LoadModuleError::MacroConversionError,
        )?;
        let body = convert_body(body)?;

        // Convert to each context's AST type.
        let ibody = ibody.into_iter().map(|(k, v)| (k, IC::from_expr(v)));
        let body = body.into_iter()
            .map(|(k, v)| (k, C::from_expr(v)))
            .collect();

        // Interpret the module.
        for (name, v) in ibody {
            let v = IC::eval(v, &mut env).map_err(
                LoadModuleError::MacroExpansionError,
            )?;
            env.push((name, v));
        }

        // Move the exports out.
        let mut exports = HashMap::new();
        let mut export_macros = HashMap::new();
        for sym in exports_sym {
            if let Some(val) = menv.lookup(sym) {
                export_macros.insert(sym, val);
            } else if let Some(val) = env.lookup(sym) {
                exports.insert(sym, val);
            } else {
                unimplemented!("{} should export {}", name, sym);
            }
        }

        // Add the module to the module store.
        self.mods.insert(
            import_path,
            Module {
                exports,
                export_macros,
                imports,
                body,
            },
        );
        Ok(())
    }
}

/// Errors encountered when loading a module.
pub enum LoadModuleError<C: 'static + Context, IC: 'static + InterpreterContext> {
    /// An error while building an AST, post-macro-expansion.
    AstConvertError(AstConvertError<C>),

    /// A dependency loop was detected.
    DependencyLoop(Symbol),

    /// An invalid value was returned by a macro.
    InvalidValue,

    /// An error during macro-expansion due to an invalid AST.
    MacroConversionError(AstConvertError<IC>),

    /// An error during macro-expansion.
    MacroExpansionError(IC::RuntimeError),

    /// An error occurring from a call to
    /// [`parse_module_header`](fn.parse_module_header.html).
    ModuleHeaderError(ModuleHeaderError),

    /// A non-existent (or private) value was attempted to be imported.
    NoSuchImport(Symbol, Symbol),

    /// An error reading a module with [`read_module`](fn.read_module.html).
    ReadModuleError(ReadModuleError),
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> From<AstConvertError<C>>
    for LoadModuleError<C, IC> {
    fn from(err: AstConvertError<C>) -> LoadModuleError<C, IC> {
        LoadModuleError::AstConvertError(err)
    }
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> From<ModuleHeaderError>
    for LoadModuleError<C, IC> {
    fn from(err: ModuleHeaderError) -> LoadModuleError<C, IC> {
        LoadModuleError::ModuleHeaderError(err)
    }
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> From<ReadModuleError>
    for LoadModuleError<C, IC> {
    fn from(err: ReadModuleError) -> LoadModuleError<C, IC> {
        LoadModuleError::ReadModuleError(err)
    }
}

impl<C: 'static + Context, IC: 'static + InterpreterContext> Debug for LoadModuleError<C, IC> {
    fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
        match *self {
            LoadModuleError::AstConvertError(ref err) => {
                fmt.debug_tuple("AstConvertError").field(err).finish()
            }
            LoadModuleError::DependencyLoop(ref path) => {
                fmt.debug_tuple("DependencyLoop").field(path).finish()
            }
            LoadModuleError::InvalidValue => fmt.debug_tuple("InvalidValue").finish(),
            LoadModuleError::MacroConversionError(ref err) => {
                fmt.debug_tuple("MacroConversionError").field(err).finish()
            }
            LoadModuleError::MacroExpansionError(ref err) => {
                fmt.debug_tuple("MacroExpansionError").field(err).finish()
            }
            LoadModuleError::NoSuchImport(ref from, ref name) => {
                fmt.debug_tuple("NoSuchImport")
                    .field(from)
                    .field(name)
                    .finish()
            }
            LoadModuleError::ModuleHeaderError(ref err) => {
                fmt.debug_tuple("ModuleHeaderError").field(err).finish()
            }
            LoadModuleError::ReadModuleError(ref err) => {
                fmt.debug_tuple("ReadModuleError").field(err).finish()
            }
        }
    }
}