-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
80 lines (68 loc) · 2.13 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
import { generateTokens } from "./compiler/lexer/tokenizer.js";
import { parseTokens } from "./compiler/parser/parser.js";
import { interpret } from "./compiler/execute/interpreter.js";
import { generateCodeJsFromAstArray } from "./converter/js/convert.js";
/**
* @typedef {import('./compiler/lexer/tokenizer.js').Token} Token
*/
/**
* @typedef {import('./compiler/parser/parser.js').Node} Node
*/
/**
* The main class for the Mimo language.
*/
export default class Mimo {
constructor() {
// Initialize the environment for variables
this.env = {};
}
/**
* Tokenize the given code into a list of tokens.
* @param {string} code - The code to be tokenized.
* @returns {Promise<Token[]>} A promise that resolves to an array of tokens.
*/
async tokenize(code) {
return generateTokens(code);
}
/**
* Parse the list of tokens into an abstract syntax tree (AST).
* @param {Token[]} tokens - The list of tokens to be parsed.
* @returns {Promise<Node[]>} A promise that resolves to an array of AST nodes.
*/
async parse(tokens) {
return parseTokens(tokens);
}
/**
* Interpret the AST and execute the code.
* @param {Node[]} program - The AST to be interpreted.
* @returns {Promise<Object>} A promise that resolves to the result of interpreting the AST.
*/
async interpret(program) {
return interpret(program, this.env);
}
/**
* Run the given code by tokenizing, parsing, and interpreting it.
* @param {string} code - The code to be run.
* @returns {Promise<{program: Node[], env: Object}>} A promise that resolves to an object containing the AST and the environment.
*/
async run(code) {
const tokens = await this.tokenize(code);
const program = await this.parse(tokens, this.env);
const env = await this.interpret(program);
return { program, env };
}
/**
* Clear the environment for variables.
*/
clearEnv() {
this.env = {};
}
/**
* Convert the AST to JavaScript code.
* @param {Node[]} ast - The AST to be converted.
* @returns {string} The generated JavaScript code.
*/
toJS(ast) {
return generateCodeJsFromAstArray(ast);
}
}