-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.web.js
More file actions
364 lines (319 loc) · 10.4 KB
/
index.web.js
File metadata and controls
364 lines (319 loc) · 10.4 KB
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
/**
* @file The Mimo library entry point for BROWSER environments.
* It exports the Mimo class but avoids importing any Node.js-specific modules.
*/
import { Interpreter } from './interpreter/index.js';
import { Lexer } from './lexer/Lexer.js';
import { Parser } from './parser/Parser.js';
import { MimoError } from './interpreter/MimoError.js';
import { Linter } from './tools/lint/Linter.js';
import { PrettyPrinter } from './tools/PrettyPrinter.js';
import { extractComments } from './tools/format/CommentLexer.js';
import { attachComments } from './tools/format/CommentAttacher.js';
/**
* Tokenizer module - handles lexical analysis
*/
export class MimoTokenizer {
constructor(source, filePath = '/playground.mimo') {
this.source = source;
this.filePath = filePath;
this.lexer = new Lexer(source, filePath);
}
tokenize() {
const tokens = [];
let token;
while ((token = this.lexer.nextToken()) !== null) {
tokens.push(token);
}
return tokens;
}
}
/**
* Parser module - handles syntax analysis
*/
export class MimoParser {
constructor(tokens, filePath = '/playground.mimo', errorHandler = null) {
this.tokens = tokens;
this.filePath = filePath;
this.parser = new Parser(tokens, filePath);
if (errorHandler) {
this.parser.setErrorHandler(errorHandler);
}
}
parse() {
return this.parser.parse();
}
}
/**
* AST Hook Manager - manages AST interception callbacks
*/
export class ASTHookManager {
constructor() {
this.hooks = [];
}
/**
* Register a callback to receive the AST
* @param {Function} callback - Function that receives (ast, filePath) as parameters
* @param {string} [name] - Optional name for the hook
*/
registerHook(callback, name = null) {
if (typeof callback !== 'function') {
throw new Error('AST hook must be a function');
}
const hook = {
callback,
name: name || `hook_${this.hooks.length}`,
id: Date.now() + Math.random()
};
this.hooks.push(hook);
return hook.id;
}
/**
* Unregister a hook by ID
* @param {string|number} hookId - The ID returned by registerHook
*/
unregisterHook(hookId) {
this.hooks = this.hooks.filter(hook => hook.id !== hookId);
}
/**
* Unregister all hooks with a specific name
* @param {string} name - The name of hooks to remove
*/
unregisterHooksByName(name) {
this.hooks = this.hooks.filter(hook => hook.name !== name);
}
/**
* Clear all registered hooks
*/
clearHooks() {
this.hooks = [];
}
/**
* Execute all registered hooks with the AST
* @param {Object} ast - The parsed AST
* @param {string} filePath - The file path
*/
executeHooks(ast, filePath) {
for (const hook of this.hooks) {
try {
hook.callback(ast, filePath);
} catch (error) {
console.error(`Error in AST hook '${hook.name}':`, error);
}
}
}
/**
* Get list of registered hooks
*/
getHooks() {
return this.hooks.map(hook => ({
id: hook.id,
name: hook.name
}));
}
}
/**
* Main Mimo class with modular design and AST interception
*/
export class Mimo {
constructor(adapter, options = {}) {
if (!adapter) {
throw new Error("Mimo constructor requires an adapter object.");
}
this.interpreter = new Interpreter(adapter);
this.astHookManager = new ASTHookManager();
// Configuration options
this.options = {
enableASTHooks: options.enableASTHooks !== false,
throwOnHookError: options.throwOnHookError || false,
...options
};
}
/**
* Register an AST hook
* @param {Function} callback - Function that receives (ast, filePath)
* @param {string} [name] - Optional name for the hook
* @returns {string|number} Hook ID for later removal
*/
onAST(callback, name) {
return this.astHookManager.registerHook(callback, name);
}
/**
* Remove an AST hook by ID
* @param {string|number} hookId - The hook ID
*/
offAST(hookId) {
this.astHookManager.unregisterHook(hookId);
}
/**
* Get the AST hook manager for advanced hook management
*/
getASTHookManager() {
return this.astHookManager;
}
/**
* Tokenize source code
* @param {string} source - The source code
* @param {string} [filePath] - Optional file path
* @returns {Array} Array of tokens
*/
tokenize(source, filePath = '/playground.mimo') {
const tokenizer = new MimoTokenizer(source, filePath);
return tokenizer.tokenize();
}
/**
* Parse tokens into an AST
* @param {Array} tokens - Array of tokens
* @param {string} [filePath] - Optional file path
* @returns {Object} The parsed AST
*/
parse(tokens, filePath = '/playground.mimo') {
const parser = new MimoParser(tokens, filePath, this.interpreter.errorHandler);
this.interpreter.errorHandler.addSourceFile(filePath, ''); // Add empty source for now
return parser.parse();
}
/**
* Parse source code directly into an AST
* @param {string} source - The source code
* @param {string} [filePath] - Optional file path
* @returns {Object} The parsed AST
*/
parseSource(source, filePath = '/playground.mimo') {
const tokens = this.tokenize(source, filePath);
this.interpreter.errorHandler.addSourceFile(filePath, source);
const parser = new MimoParser(tokens, filePath, this.interpreter.errorHandler);
const ast = parser.parse();
// Execute AST hooks if enabled
if (this.options.enableASTHooks) {
this.astHookManager.executeHooks(ast, filePath);
}
return ast;
}
/**
* Run source code with full pipeline
* @param {string} source - The source code
* @param {string} [filePath] - Optional file path
* @returns {*} The execution result
*/
run(source, filePath = '/playground.mimo') {
const effectivePath = filePath;
try {
// Tokenize
const tokens = this.tokenize(source, effectivePath);
// Parse and get AST
const ast = this.parseSource(source, effectivePath);
// Interpret
const result = this.interpreter.interpret(ast, effectivePath);
return result;
} catch (error) {
if (error instanceof MimoError) {
throw error.format(this.interpreter.errorHandler.getLine(error.location.file, error.location.line));
} else {
throw error;
}
}
}
/**
* Run pre-parsed AST
* @param {Object} ast - The parsed AST
* @param {string} [filePath] - Optional file path
* @returns {*} The execution result
*/
runAST(ast, filePath = '/playground.mimo') {
try {
return this.interpreter.interpret(ast, filePath);
} catch (error) {
if (error instanceof MimoError) {
throw error.format(this.interpreter.errorHandler.getLine(error.location.file, error.location.line));
} else {
throw error;
}
}
}
}
// Export all classes and modules
export { Interpreter } from './interpreter/index.js';
export { Lexer } from './lexer/Lexer.js';
export { Parser } from './parser/Parser.js';
export { MimoError } from './interpreter/MimoError.js';
export { Linter } from './tools/lint/Linter.js';
export { PrettyPrinter } from './tools/PrettyPrinter.js';
const DEFAULT_LINT_RULES = {
'no-unused-vars': true,
'prefer-const': true,
'no-magic-numbers': false
};
export function lintSource(source, filePath = '/playground.mimo', rules = {}) {
const enabledRules = { ...DEFAULT_LINT_RULES, ...rules };
try {
const lexer = new Lexer(source, filePath);
const tokens = [];
let token;
while ((token = lexer.nextToken()) !== null) {
tokens.push(token);
}
const parser = new Parser(tokens, filePath);
const ast = parser.parse();
const linter = new Linter({ rules: enabledRules });
const messages = linter.verify(ast, source, filePath);
return {
ok: true,
file: filePath,
messages: messages.map(msg => ({
line: msg.line,
column: msg.column,
endColumn: msg.endColumn,
message: msg.message,
ruleId: msg.ruleId,
severity: 'warning'
}))
};
} catch (err) {
// Convert syntax/parse errors into lint diagnostics
return {
ok: false,
file: filePath,
error: {
message: err.message,
line: err.location?.line || 1,
column: err.location?.column || 1
},
messages: [{
line: err.location?.line || 1,
column: err.location?.column || 1,
endColumn: (err.location?.column || 1) + 1,
message: err.message,
ruleId: 'syntax-error',
severity: 'error'
}]
};
}
}
export function formatSource(source) {
try {
// Extract comments from raw source (formatter-only path)
const { comments } = extractComments(source);
const lexer = new Lexer(source, '/format.mimo');
const tokens = [];
let token;
while ((token = lexer.nextToken()) !== null) {
tokens.push(token);
}
const parser = new Parser(tokens, '/format.mimo');
const ast = parser.parse();
// Attach extracted comments to AST nodes
attachComments(ast, comments);
const printer = new PrettyPrinter();
// A8: format() already normalises the trailing newline
const formatted = printer.format(ast);
return {
ok: true,
formatted,
};
} catch (err) {
return {
ok: false,
error: err.message,
};
}
}