-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModuleLoader.js
67 lines (53 loc) · 1.59 KB
/
ModuleLoader.js
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
//@ts-check
const fs = require("fs");
const {Parser} = require("./Parser");
const {Tokenizer} = require("./Tokenizer");
const Runtime = require("./Runtime");
const LOG = false;
class ModuleLoader {
/**
* @static
* @param {string} filepath
* @param {Runtime.Runtime} runtime
* @return {Map<string, Runtime.Variable> | FailureResult}
* @memberof ModuleLoader
*/
static loadModule(filepath, runtime) {
const source = fs.readFileSync(filepath, "utf8");
const ast = this.generateAST(source);
if(ast instanceof FailureResult) {
ast.__source = source;
return ast;
}
const module = runtime.runModule(ast.node);
return module;
}
/**
* @static
* @param {string} source
* @return {SuccessParseResult | FailureResult}
* @memberof ModuleLoader
*/
static generateAST(source) {
const tokenizer = new Tokenizer({source});
const tokenizerResult = tokenizer.tokenize();
LOG && console.log(tokenizerResult);
if(tokenizerResult instanceof FailureResult) {
if(!tokenizerResult.__source) tokenizerResult.__source = source;
return tokenizerResult;
}
const parser = new Parser({tokens: tokenizerResult.tokens});
const astResult = parser.parse();
if(astResult instanceof FailureResult) {
if(!astResult.__source) astResult.__source = source;
LOG && console.dir(astResult, {depth: null});
//LOG && console.log(astResult.toString());
} else {
LOG && console.dir(astResult, {depth: null});
//LOG && console.log(astResult.toString());
}
return astResult;
}
}
module.exports = ModuleLoader;
const {SuccessParseResult, FailureResult} = require("./Result");