-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.js
More file actions
357 lines (357 loc) · 11.9 KB
/
Copy pathlexer.js
File metadata and controls
357 lines (357 loc) · 11.9 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
export var TokenType;
(function (TokenType) {
TokenType[TokenType["Keyword"] = 0] = "Keyword";
TokenType[TokenType["Identifier"] = 1] = "Identifier";
TokenType[TokenType["NumberLiteral"] = 2] = "NumberLiteral";
TokenType[TokenType["StringLiteral"] = 3] = "StringLiteral";
TokenType[TokenType["Operator"] = 4] = "Operator";
TokenType[TokenType["Punctuation"] = 5] = "Punctuation";
TokenType[TokenType["EOF"] = 6] = "EOF";
TokenType[TokenType["FunctionName"] = 7] = "FunctionName";
TokenType[TokenType["FunctionParams"] = 8] = "FunctionParams";
TokenType[TokenType["FunctionBody"] = 9] = "FunctionBody";
TokenType[TokenType["FunctionCall"] = 10] = "FunctionCall";
TokenType[TokenType["Console"] = 11] = "Console";
TokenType[TokenType["SingleLineComment"] = 12] = "SingleLineComment";
TokenType[TokenType["MultiLineComment"] = 13] = "MultiLineComment";
})(TokenType || (TokenType = {}));
// Reserved keywords (Chinese -> JS keywords)
export const keywords = {
让: "let",
变量: "var",
常量: "const",
函数: "function",
返回: "return",
为: "for",
为每个: "forEach",
当: "while",
做: "do",
如果: "if",
否则如果: "else if",
否则: "else",
抛出: "throw",
尝试: "try",
捕获: "catch",
最终: "finally",
新建: "new",
实例: "instanceof",
类型: "typeof",
真: "true",
假: "false",
空: "null",
未定义: "undefined",
导出: "export",
导入: "import",
// Console methods
// 控制台: "console",
// 打印: "log",
// 错误: "error",
// 警告: "warn",
// 清除: "clear",
// 断言: "assert",
// 计时: "time",
// 计时结束: "timeEnd",
// 组: "group",
// 组结束: "groupEnd",
// 跟踪: "trace",
};
// Define operators and punctuation
export const operators = [
"+",
"-",
"*",
"/",
"=",
"==",
"!=",
"<",
">",
"&&",
"||",
"!",
];
export const punctuation = ["(", ")", "{", "}", "[", "]", ";", ",", "."];
// Updated Lexer class
export class Lexer {
constructor(source) {
this.current = 0;
this.source = source;
}
isAtEnd() {
return this.current >= this.source.length;
}
advance() {
return this.source[this.current++];
}
peek() {
return this.isAtEnd() ? "" : this.source[this.current];
}
isDigit(char) {
return /\d/.test(char);
}
isAlpha(char) {
return /[\u4e00-\u9fa5a-zA-Z_]/.test(char); // Support Chinese characters and Latin
}
isAlphaNumeric(char) {
return this.isAlpha(char) || this.isDigit(char);
}
skipWhitespace() {
while (!this.isAtEnd() && /\s/.test(this.peek())) {
this.advance();
}
}
number() {
let value = "";
while (this.isDigit(this.peek())) {
value += this.advance();
}
return { type: TokenType.NumberLiteral, value };
}
string() {
let value = "";
const quoteType = this.advance(); // Get the opening quote
value += quoteType; // Include the opening quote in the value
while (!this.isAtEnd() && this.peek() !== quoteType) {
if (this.peek() === "\\") {
// Handle escape sequences
value += this.advance(); // Add the backslash
if (!this.isAtEnd()) {
value += this.advance(); // Add the escaped character
}
}
else {
value += this.advance(); // Add regular characters
}
}
if (!this.isAtEnd()) {
value += this.advance(); // Consume the closing quote
}
return { type: TokenType.StringLiteral, value };
}
operatorOrPunctuation() {
const char = this.peek();
// Check for operators
for (const op of operators) {
if (this.source.startsWith(op, this.current)) {
this.current += op.length;
return { type: TokenType.Operator, value: op };
}
}
// Check for punctuation
if (punctuation.includes(char)) {
this.advance();
return { type: TokenType.Punctuation, value: char };
}
return null;
}
identifier() {
let value = "";
while (this.isAlphaNumeric(this.peek())) {
value += this.advance();
}
if (keywords.hasOwnProperty(value)) {
return { type: TokenType.Keyword, value: keywords[value] };
}
// Check for function keyword
if (value === "函数") {
return this.functionDefinition();
}
// Check for console methods
if (value === "console") {
return this.consoleMethod();
}
// Check for function calls
if (this.peek() === "(") {
return this.functionCall(value); // If function name is followed by '(', treat it as a function call and pass the function name as an argument
}
return { type: TokenType.Identifier, value };
}
functionDefinition() {
let value = "function ";
let name = "";
let params = "";
const nextChar = this.source[this.current + 1];
//consume the function keyword
this.advance(); // '函书'
// skip whitespace
this.skipWhitespace();
// since function name is mandatory, we can assume that the next character is an identifier
// assume that the function name is a single identifier
// assume that the function name is followed by an opening parenthesis
// assume that the function parameters are separated by commas
// assume that the function parameters are followed by a closing parenthesis
// keep consuming characters until we reach the opening curly brace
// make sure params are separated by commas
// if there is no opening curly brace, we can assume that the function body is part of a larger expression
// we will check if the next character is a newline character in the next iteration
while (this.isAlphaNumeric(this.peek()) || this.peek() !== "{") {
name += this.advance();
}
value += name;
return { type: TokenType.FunctionBody, value };
}
functionCall(funcName) {
let value = "";
// append the function name
value += funcName;
// expect the first character to be an opening parenthesis and consume it
// expect the last character to be a closing parenthesis
// keep consuming characters until we reach a semicolon
// if there is no semicolon, we can assume that the function call is part of a larger expression
// we will check if the next character is an next line character in the next iteration
while (!this.isAtEnd() && this.peek() !== ";") {
value += this.advance();
}
return { type: TokenType.FunctionCall, value };
}
consoleMethod() {
let value = "console";
this.advance(); // Advance past the dot '.'
let method = "";
// Match the method part after console.
while (this.isAlpha(this.peek())) {
method += this.advance();
}
if ([
"log",
"error",
"warn",
"clear",
"assert",
"time",
"timeEnd",
"group",
"groupEnd",
"trace",
].includes(method)) {
let code = `${value}.${method}`;
let parenthesisCount = 1;
// Add opening parenthesis
code += this.advance(); // Consume '('
// Append content inside parenthesis
while (parenthesisCount > 0 && !this.isAtEnd()) {
const char = this.peek();
if (char === "(")
parenthesisCount++;
if (char === ")")
parenthesisCount--;
code += this.advance();
}
return { type: TokenType.Console, value: code };
}
else {
throw new Error(`Unexpected console method: ${method}`);
}
}
singleLineComment() {
let value = "//";
this.advance(); // Consume the '/' character
while (!this.isAtEnd() && this.peek() !== "\n") {
value += this.advance();
}
if (!this.isAtEnd() && this.peek() === "\n") {
value += this.advance(); // Consume the newline character
}
return { type: TokenType.SingleLineComment, value };
}
multiLineComment() {
let value = "/*";
this.advance(); // Consume the '/*' characters
while (!this.isAtEnd() &&
(this.peek() !== "*" || this.source[this.current + 1] !== "/")) {
value += this.advance();
}
value += this.advance(); // Consume the '*'
value += this.advance(); // Consume the '/'
return { type: TokenType.MultiLineComment, value };
}
nextToken() {
this.skipWhitespace();
if (this.isAtEnd()) {
return { type: TokenType.EOF, value: "" };
}
const char = this.peek();
const nextChar = this.source[this.current + 1];
// Check for comments
if (char === "/") {
if (nextChar === "/") {
this.advance(); // Consume the first '/'
this.advance(); // Consume the second '/'
return this.singleLineComment();
}
else if (nextChar === "*") {
return this.multiLineComment();
}
}
if (this.isDigit(char)) {
return this.number();
}
if ((char === '"' || char === "'" || char === "`") &&
typeof char === "string") {
return this.string();
}
if (this.isAlpha(char)) {
const identifier = this.identifier();
if (identifier.type === TokenType.Keyword &&
identifier.value === "function") {
return this.functionDefinition();
}
else {
return identifier;
}
}
const opOrPunc = this.operatorOrPunctuation();
if (opOrPunc) {
return opOrPunc;
}
// If we encounter an unexpected character, throw an error
throw new Error(`Unexpected character: ${char}`);
}
tokenize() {
const tokens = [];
let token = this.nextToken();
while (token.type !== TokenType.EOF) {
tokens.push(token);
token = this.nextToken();
}
tokens.push(token); // Push EOF token
return tokens;
}
translate(tokens) {
let result = "";
for (const token of tokens) {
switch (token.type) {
case TokenType.NumberLiteral:
result += token.value;
break;
case TokenType.StringLiteral:
result += token.value;
break;
case TokenType.Identifier:
result += token.value;
break;
case TokenType.FunctionCall:
result += token.value;
break;
case TokenType.Operator:
result += token.value;
break;
case TokenType.Punctuation:
result += token.value;
break;
case TokenType.Keyword:
result += token.value;
break;
case TokenType.Console:
result += token.value;
break;
case TokenType.SingleLineComment:
case TokenType.MultiLineComment:
break; // Ignore comments in translation
case TokenType.EOF:
break; // End of file
}
}
return result;
}
}