Repository navigation
Expand file tree
/
Copy patharrow-function-parser.ts
More file actions
98 lines (84 loc) · 2.23 KB
/
Copy patharrow-function-parser.ts
File metadata and controls
98 lines (84 loc) · 2.23 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
/**
* 箭头函数解析器 - 负责解析箭头函数表达式
*/
import type { ArrowFunctionExpr, Identifier } from "../../types/ast-types";
import { PrimaryParser } from "./primary-parser";
import { isIdentifierStart } from "./utils";
/**
* ArrowFunctionParser 类 - 继承 PrimaryParser,添加箭头函数解析功能
*/
export class ArrowFunctionParser extends PrimaryParser {
/**
* 尝试解析带括号的箭头函数: (a, b) => expr
* 使用回溯机制
*/
protected tryParseArrowFunction(): ArrowFunctionExpr | null {
const savedPos = this.pos;
try {
this.expect("(");
this.skipWhitespace();
const params: Identifier[] = [];
// 解析参数列表
while (this.peek() !== ")") {
if (!isIdentifierStart(this.peek())) {
throw new Error("Expected identifier");
}
params.push(this.parseIdentifier());
this.skipWhitespace();
if (this.peek() === ",") {
this.advance();
this.skipWhitespace();
} else {
break;
}
}
this.expect(")");
this.skipWhitespace();
// 检查 =>
if (this.source.slice(this.pos, this.pos + 2) !== "=>") {
throw new Error("Expected =>");
}
this.pos += 2;
this.skipWhitespace();
// 解析函数体
const body = this.parseExpression();
return {
type: "ArrowFunctionExpr",
params,
body,
};
} catch {
// 回溯
this.pos = savedPos;
return null;
}
}
/**
* 尝试解析单参数无括号的箭头函数: a => expr
* 使用回溯机制
*/
protected tryParseSingleParamArrowFunction(): ArrowFunctionExpr | null {
const savedPos = this.pos;
try {
const param = this.parseIdentifier();
this.skipWhitespace();
// 检查 =>
if (this.source.slice(this.pos, this.pos + 2) !== "=>") {
throw new Error("Expected =>");
}
this.pos += 2;
this.skipWhitespace();
// 解析函数体
const body = this.parseExpression();
return {
type: "ArrowFunctionExpr",
params: [param],
body,
};
} catch {
// 回溯
this.pos = savedPos;
return null;
}
}
}