
var fs = require('fs');

var nearley = require('../lib/nearley.js');
var Compile = require('../lib/compile.js');
var parserGrammar = nearley.Grammar.fromCompiled(require('../lib/nearley-language-bootstrapped.js'));
var generate = require('../lib/generate.js');

function parse(grammar, input) {
    var p = new nearley.Parser(grammar);
    p.feed(input);
    return p.results;
}

function compile(source) {
    // parse
    var results = parse(parserGrammar, source);

    // compile
    var c = Compile(results[0], {});

    // generate
    var compiledGrammar = generate(c, 'grammar');

    // eval
    return evalGrammar(compiledGrammar);
}

function evalGrammar(compiledGrammar) {
    var f = new Function('module', compiledGrammar);
    var m = {exports: {}};
    f(m);
    return new nearley.Grammar.fromCompiled(m.exports);
}

function read(filename) {
    return fs.readFileSync(filename, 'utf-8');
}

module.exports = {
    nearley: nearley,
    read: read,
    compile: compile,
    parse: parse,
    evalGrammar: evalGrammar,
};


@@ -17,16 +17,44 @@
 e('fs');
+%0Avar path = require('path');
 %0A%0Avar ne
@@ -680,38 +680,95 @@
 ion 
-evalGrammar(compiledGrammar) %7B
+requireFromString(source) %7B%0A    var filename = '.'%0A    var Module = module.constructor;
 %0A   
@@ -776,35 +776,168 @@
 var 
-f
+m
  = new 
-Function('module', 
+Module();%0A    m.paths = Module._nodeModulePaths(path.dirname(filename))%0A    m._compile(source, filename);%0A    return m.exports;%0A%7D%0A%0Afunction evalGrammar(
 comp
@@ -944,25 +944,26 @@
 iledGrammar)
-;
+ %7B
 %0A    var m =
@@ -963,34 +963,51 @@
 var 
-m = %7B
 exports
-: %7B%7D%7D;%0A    f(m
+ = requireFromString(compiledGrammar
 );%0A 
@@ -1049,18 +1049,16 @@
 ompiled(
-m.
 exports)

correct require()-from-string