@junoscript/juno 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Modules/async.ts +81 -0
- package/Modules/juno-node-fs.ts +105 -0
- package/Modules/juno-test.jn +156 -0
- package/dist/CLI/build-juno.d.ts +5 -0
- package/dist/CLI/build-juno.js +58 -0
- package/dist/CLI/generate-juno-types.d.ts +1 -0
- package/dist/CLI/generate-juno-types.js +51 -0
- package/dist/CLI/junode.d.ts +2 -0
- package/dist/CLI/junode.js +32 -0
- package/dist/Lexer/lexer.d.ts +42 -0
- package/dist/Lexer/lexer.js +300 -0
- package/dist/Lexer/parser.d.ts +395 -0
- package/dist/Lexer/parser.js +1881 -0
- package/dist/Modules/async.d.ts +33 -0
- package/dist/Modules/async.js +76 -0
- package/dist/Modules/index.d.ts +195 -0
- package/dist/Modules/index.js +31 -0
- package/dist/Modules/juno-node-fs.d.ts +52 -0
- package/dist/Modules/juno-node-fs.js +129 -0
- package/dist/Modules/juno-node.d.ts +74 -0
- package/dist/Modules/juno-node.js +56 -0
- package/dist/Modules/juno-test.d.ts +141 -0
- package/dist/Modules/juno-test.js +134 -0
- package/dist/Modules/juno-types.d.ts +35 -0
- package/dist/Modules/juno-types.js +2 -0
- package/dist/Modules/juno.d.ts +21 -0
- package/dist/Modules/juno.js +76 -0
- package/dist/Modules/types.d.ts +56 -0
- package/dist/Modules/types.js +87 -0
- package/dist/Runtime/interpreter.d.ts +64 -0
- package/dist/Runtime/interpreter.js +2533 -0
- package/dist/Runtime/resolve-import.d.ts +2 -0
- package/dist/Runtime/resolve-import.js +30 -0
- package/dist/vscode-junoscript/src/language.d.ts +86 -0
- package/dist/vscode-junoscript/src/language.js +4206 -0
- package/package.json +19 -4
- package/types/array.jn +158 -0
- package/types/boolean.jn +18 -0
- package/types/error.jn +28 -0
- package/types/error.ts +9 -0
- package/types/index.jn +11 -0
- package/types/iterable.jn +211 -0
- package/types/map.jn +44 -0
- package/types/map.ts +132 -0
- package/types/number.ts +52 -0
- package/types/object.jn +94 -0
- package/types/object.ts +49 -0
- package/types/queue.jn +46 -0
- package/types/random.jn +25 -0
- package/types/random.ts +1 -0
- package/types/range.jn +27 -0
- package/types/set.jn +139 -0
- package/types/set.ts +209 -0
- package/types/string.jn +33 -0
- package/types/string.ts +1 -0
- package/types/tuple.jn +11 -0
- package/README.md +0 -3
|
@@ -0,0 +1,1881 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Parser = void 0;
|
|
4
|
+
exports.parse = parse;
|
|
5
|
+
const lexer_1 = require("./lexer");
|
|
6
|
+
const precedence = { '|': 1, '&': 2, '??': 3, '==': 4, '!=': 4, '<': 5, '<=': 5, '>': 5, '>=': 5, '+': 6, '-': 6, '*': 7, '/': 7, '%': 7 };
|
|
7
|
+
const opTypes = { EqualEqual: '==', NotEqual: '!=', Less: '<', LessEqual: '<=', Greater: '>', GreaterEqual: '>=', Nullish: '??', Pipe: '|', Ampersand: '&', Plus: '+', Minus: '-', Multiply: '*', Divide: '/', Percent: '%' };
|
|
8
|
+
const assignmentOperators = { Equal: '=', PlusEqual: '+=', MinusEqual: '-=', MultiplyEqual: '*=', DivideEqual: '/=', PercentEqual: '%=', PipeEqual: '|=', AmpersandEqual: '&=' };
|
|
9
|
+
class Parser {
|
|
10
|
+
tokens;
|
|
11
|
+
pos = 0;
|
|
12
|
+
softExpressionIndents = 0;
|
|
13
|
+
constructor(tokens) {
|
|
14
|
+
this.tokens = tokens;
|
|
15
|
+
}
|
|
16
|
+
get current() { return this.tokens[this.pos]; }
|
|
17
|
+
is(type, value) { const t = this.current; return t.type === type && (value === undefined || t.value === value); }
|
|
18
|
+
take(type, message = `Expected ${type}`) { if (!this.is(type))
|
|
19
|
+
this.fail(message); return this.tokens[this.pos++]; }
|
|
20
|
+
value(token) { return token.value; }
|
|
21
|
+
match(type, value) { if (!this.is(type, value))
|
|
22
|
+
return false; this.pos++; return true; }
|
|
23
|
+
fail(message) { throw new SyntaxError(`${message} at ${this.current.line}:${this.current.column}`); }
|
|
24
|
+
loc(token) { return { line: token.line, column: token.column }; }
|
|
25
|
+
identifier() {
|
|
26
|
+
const token = this.take('Identifier', 'Expected identifier');
|
|
27
|
+
return { name: String(this.value(token)), loc: this.loc(token) };
|
|
28
|
+
}
|
|
29
|
+
propertyName() {
|
|
30
|
+
if (this.is('Identifier') || this.is('Keyword')) {
|
|
31
|
+
const token = this.tokens[this.pos++];
|
|
32
|
+
return { name: String(this.value(token)), loc: this.loc(token) };
|
|
33
|
+
}
|
|
34
|
+
if (this.is('String')) {
|
|
35
|
+
const token = this.take('String');
|
|
36
|
+
return { name: String(this.value(token)), loc: this.loc(token) };
|
|
37
|
+
}
|
|
38
|
+
if (this.is('Number')) {
|
|
39
|
+
const token = this.take('Number');
|
|
40
|
+
return { name: String(this.value(token)), loc: this.loc(token) };
|
|
41
|
+
}
|
|
42
|
+
return this.identifier();
|
|
43
|
+
}
|
|
44
|
+
separators() { while (this.match('Newline') || this.match('Comma')) { } }
|
|
45
|
+
objectSeparators() { while (this.match('Newline') || this.match('Comma') || this.match('Indent') || this.match('Dedent')) { } }
|
|
46
|
+
parenthesisSeparators() { while (this.match('Newline') || this.match('Indent') || this.match('Dedent')) { } }
|
|
47
|
+
parse() {
|
|
48
|
+
const body = [];
|
|
49
|
+
const topSeparators = () => { while (this.match('Newline') || this.match('Comma') || this.match('Dedent')) { } };
|
|
50
|
+
topSeparators();
|
|
51
|
+
while (!this.is('EOF')) {
|
|
52
|
+
body.push(this.statement());
|
|
53
|
+
topSeparators();
|
|
54
|
+
}
|
|
55
|
+
return body;
|
|
56
|
+
}
|
|
57
|
+
parseExpressionOnly() {
|
|
58
|
+
const value = this.expression();
|
|
59
|
+
while (this.match('Newline')) { }
|
|
60
|
+
if (!this.is('EOF'))
|
|
61
|
+
this.fail('Unexpected token after expression');
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
statement() {
|
|
65
|
+
if (this.match('Keyword', 'import'))
|
|
66
|
+
return this.importStatement();
|
|
67
|
+
if (this.match('Keyword', 'export')) {
|
|
68
|
+
const isDefault = this.match('Keyword', 'default');
|
|
69
|
+
const declaration = this.statement();
|
|
70
|
+
if (!['Import', 'Variable', 'Destructure', 'ArrayDestructure', 'FunctionDeclaration', 'TypeDeclaration', 'ConstructorDeclaration'].includes(declaration.kind))
|
|
71
|
+
this.fail('export must precede a declaration');
|
|
72
|
+
return { kind: 'Export', declaration, default: isDefault };
|
|
73
|
+
}
|
|
74
|
+
if (this.match('Keyword', 'let') || this.match('Keyword', 'const')) {
|
|
75
|
+
const mutable = this.value(this.tokens[this.pos - 1]) === 'let';
|
|
76
|
+
if (this.match('LeftBrace')) {
|
|
77
|
+
const bindings = [];
|
|
78
|
+
const patternSeparators = () => { while (this.match('Newline') || this.match('Indent') || this.match('Dedent')) { } };
|
|
79
|
+
patternSeparators();
|
|
80
|
+
while (!this.is('RightBrace')) {
|
|
81
|
+
bindings.push(this.identifier());
|
|
82
|
+
patternSeparators();
|
|
83
|
+
if (this.match('Comma'))
|
|
84
|
+
patternSeparators();
|
|
85
|
+
else if (!this.is('RightBrace'))
|
|
86
|
+
this.fail("Expected ',' or '}' in object destructuring");
|
|
87
|
+
}
|
|
88
|
+
this.take('RightBrace');
|
|
89
|
+
this.take('Equal', "Expected '=' after object destructuring");
|
|
90
|
+
return { kind: 'Destructure', bindings, mutable, initializer: this.expression() };
|
|
91
|
+
}
|
|
92
|
+
if (this.match('LeftBracket')) {
|
|
93
|
+
const bindings = [];
|
|
94
|
+
let index = 0;
|
|
95
|
+
while (!this.is('RightBracket')) {
|
|
96
|
+
if (this.match('Comma')) {
|
|
97
|
+
index++;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const rest = this.match('Ellipsis');
|
|
101
|
+
const binding = this.identifier();
|
|
102
|
+
bindings.push({ ...binding, index, rest });
|
|
103
|
+
if (rest && !this.is('RightBracket'))
|
|
104
|
+
this.fail('A rest binding must be the last element');
|
|
105
|
+
if (!rest)
|
|
106
|
+
index++;
|
|
107
|
+
if (!this.match('Comma') && !this.is('RightBracket'))
|
|
108
|
+
this.fail("Expected ',' or ']' in array destructuring");
|
|
109
|
+
}
|
|
110
|
+
this.take('RightBracket');
|
|
111
|
+
this.take('Equal', "Expected '=' after array destructuring");
|
|
112
|
+
return { kind: 'ArrayDestructure', bindings, mutable, initializer: this.expression() };
|
|
113
|
+
}
|
|
114
|
+
const { name, loc } = this.identifier();
|
|
115
|
+
const type = this.match('Colon') ? this.type() : undefined;
|
|
116
|
+
let initializer;
|
|
117
|
+
if (this.match('Equal')) {
|
|
118
|
+
const multiline = this.match('Newline');
|
|
119
|
+
if (multiline)
|
|
120
|
+
this.take('Indent', 'Expected an indented initializer');
|
|
121
|
+
initializer = this.expression();
|
|
122
|
+
}
|
|
123
|
+
if (!initializer && !type)
|
|
124
|
+
this.fail('A variable needs a type or initializer');
|
|
125
|
+
if (!mutable && !initializer)
|
|
126
|
+
this.fail('const requires an initializer');
|
|
127
|
+
return { kind: 'Variable', name, loc, mutable, type, initializer };
|
|
128
|
+
}
|
|
129
|
+
if (this.match('Keyword', 'fun')) {
|
|
130
|
+
const { name, loc } = this.identifier();
|
|
131
|
+
const genericParameters = this.match('Less') ? this.genericParameters() : [];
|
|
132
|
+
const params = this.parameters(), returnType = this.match('Colon') ? this.type() : undefined;
|
|
133
|
+
this.take('Equal', "Expected '=' before function body");
|
|
134
|
+
const body = this.is('Keyword', 'match')
|
|
135
|
+
? [{ kind: 'Return', value: this.expression() }]
|
|
136
|
+
: this.block();
|
|
137
|
+
return {
|
|
138
|
+
kind: 'FunctionDeclaration', name, loc,
|
|
139
|
+
generics: genericParameters.map(item => item.name),
|
|
140
|
+
genericLocs: genericParameters.map(item => item.loc),
|
|
141
|
+
genericConstraints: genericParameters.map(item => item.constraint),
|
|
142
|
+
genericDefaults: genericParameters.map(item => item.defaultType),
|
|
143
|
+
params, returnType, body
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (this.match('Keyword', 'type')) {
|
|
147
|
+
const { name, loc } = this.identifier();
|
|
148
|
+
const genericParameters = this.match('Less') ? this.genericParameters() : [];
|
|
149
|
+
this.take('Equal', "Expected '=' in type declaration");
|
|
150
|
+
const indented = this.match('Newline');
|
|
151
|
+
if (indented && this.is('Indent') && this.tokens[this.pos + 1]?.type !== 'Pipe' && this.tokens[this.pos + 1]?.type !== 'Ampersand')
|
|
152
|
+
this.pos++;
|
|
153
|
+
const value = this.type();
|
|
154
|
+
if (indented) {
|
|
155
|
+
this.separators();
|
|
156
|
+
if (this.is('Dedent'))
|
|
157
|
+
this.take('Dedent');
|
|
158
|
+
}
|
|
159
|
+
return { kind: 'TypeDeclaration', name, loc, generics: genericParameters.map(item => item.name), genericLocs: genericParameters.map(item => item.loc), genericConstraints: genericParameters.map(item => item.constraint), genericDefaults: genericParameters.map(item => item.defaultType), value };
|
|
160
|
+
}
|
|
161
|
+
if (this.match('Keyword', 'constructor')) {
|
|
162
|
+
const { name, loc } = this.identifier();
|
|
163
|
+
const genericParameters = this.match('Less') ? this.genericParameters() : [];
|
|
164
|
+
const inheritedType = this.match('Colon')
|
|
165
|
+
? this.type()
|
|
166
|
+
: { kind: 'ObjectType', members: [] };
|
|
167
|
+
this.take('LeftBrace', "Expected '{' before constructor overloads");
|
|
168
|
+
const overloads = [];
|
|
169
|
+
const methods = [];
|
|
170
|
+
this.objectSeparators();
|
|
171
|
+
while (!this.is('RightBrace') && !this.is('EOF')) {
|
|
172
|
+
this.take('Keyword', "Expected anonymous 'fun' constructor overload");
|
|
173
|
+
if (this.value(this.tokens[this.pos - 1]) !== 'fun')
|
|
174
|
+
this.fail("Expected anonymous 'fun' constructor overload");
|
|
175
|
+
if (!this.is('LeftParen')) {
|
|
176
|
+
const method = this.propertyName();
|
|
177
|
+
const methodGenericParameters = this.match('Less') ? this.genericParameters() : [];
|
|
178
|
+
const params = this.parameters();
|
|
179
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
180
|
+
this.take('Equal', "Expected '=' before constructor method body");
|
|
181
|
+
methods.push({ kind: 'FunctionDeclaration', name: method.name, loc: method.loc, generics: methodGenericParameters.map(item => item.name), genericLocs: methodGenericParameters.map(item => item.loc), genericConstraints: methodGenericParameters.map(item => item.constraint), genericDefaults: methodGenericParameters.map(item => item.defaultType), params, returnType, body: this.block() });
|
|
182
|
+
this.objectSeparators();
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const params = this.parameters();
|
|
186
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
187
|
+
this.take('Equal', "Expected '=' before constructor body");
|
|
188
|
+
overloads.push({ kind: 'Function', params, returnType, body: this.block() });
|
|
189
|
+
this.objectSeparators();
|
|
190
|
+
}
|
|
191
|
+
this.take('RightBrace');
|
|
192
|
+
if (!overloads.length)
|
|
193
|
+
this.fail('A constructor needs at least one anonymous function');
|
|
194
|
+
return { kind: 'ConstructorDeclaration', name, loc, generics: genericParameters.map(item => item.name), genericLocs: genericParameters.map(item => item.loc), genericConstraints: genericParameters.map(item => item.constraint), genericDefaults: genericParameters.map(item => item.defaultType), inheritedType, overloads, methods };
|
|
195
|
+
}
|
|
196
|
+
if (this.match('Keyword', 'return'))
|
|
197
|
+
return { kind: 'Return', value: this.is('Newline') || this.is('Dedent') || this.is('EOF') ? undefined : this.expression() };
|
|
198
|
+
if (this.match('Keyword', 'break'))
|
|
199
|
+
return { kind: 'Break', loc: this.loc(this.tokens[this.pos - 1]) };
|
|
200
|
+
if (this.is('Identifier') && assignmentOperators[this.tokens[this.pos + 1]?.type]) {
|
|
201
|
+
const { name, loc } = this.identifier(), operatorToken = this.current, operator = assignmentOperators[operatorToken.type];
|
|
202
|
+
this.pos++;
|
|
203
|
+
return { kind: 'ExpressionStatement', expression: { kind: 'Assignment', name, loc, operatorLoc: this.loc(operatorToken), operator, value: this.expression() } };
|
|
204
|
+
}
|
|
205
|
+
if (this.match('Keyword', 'if')) {
|
|
206
|
+
const condition = this.expression(), consequent = this.block();
|
|
207
|
+
this.separators();
|
|
208
|
+
const alternate = this.match('Keyword', 'else') ? this.block() : undefined;
|
|
209
|
+
return { kind: 'If', condition, consequent, alternate };
|
|
210
|
+
}
|
|
211
|
+
if (this.match('Keyword', 'while'))
|
|
212
|
+
return { kind: 'While', condition: this.expression(), body: this.block() };
|
|
213
|
+
if (this.match('Keyword', 'for')) {
|
|
214
|
+
const mutable = this.match('Keyword', 'let') || !this.match('Keyword', 'const'), { name: binding, loc } = this.identifier();
|
|
215
|
+
this.take('Keyword', "Expected 'of'");
|
|
216
|
+
const iterable = this.expression();
|
|
217
|
+
return { kind: 'ForOf', binding, loc, mutable, iterable, body: this.block() };
|
|
218
|
+
}
|
|
219
|
+
const expression = this.expression();
|
|
220
|
+
const assignmentOperator = assignmentOperators[this.current.type];
|
|
221
|
+
if (assignmentOperator) {
|
|
222
|
+
const operatorToken = this.current;
|
|
223
|
+
this.pos++;
|
|
224
|
+
if (expression.kind === 'Member')
|
|
225
|
+
return { kind: 'ExpressionStatement', expression: { kind: 'MemberAssignment', object: expression.object, property: expression.property, propertyLoc: expression.loc, loc: this.loc(operatorToken), operator: assignmentOperator, value: this.expression() } };
|
|
226
|
+
if (expression.kind === 'Index')
|
|
227
|
+
return { kind: 'ExpressionStatement', expression: { kind: 'MemberAssignment', object: expression.object, index: expression.index, loc: this.loc(operatorToken), operator: assignmentOperator, value: this.expression() } };
|
|
228
|
+
this.fail('Only variables and object properties can be assigned here');
|
|
229
|
+
}
|
|
230
|
+
return { kind: 'ExpressionStatement', expression };
|
|
231
|
+
}
|
|
232
|
+
importStatement() {
|
|
233
|
+
let defaultImport;
|
|
234
|
+
let defaultImportLoc;
|
|
235
|
+
const namedImports = [];
|
|
236
|
+
const namedImportLocs = [];
|
|
237
|
+
const namedImportList = () => {
|
|
238
|
+
this.parenthesisSeparators();
|
|
239
|
+
while (!this.is('RightBrace')) {
|
|
240
|
+
const ident = this.identifier();
|
|
241
|
+
namedImports.push(ident.name);
|
|
242
|
+
namedImportLocs.push(ident.loc);
|
|
243
|
+
this.parenthesisSeparators();
|
|
244
|
+
if (this.match('Comma'))
|
|
245
|
+
this.parenthesisSeparators();
|
|
246
|
+
else if (!this.is('RightBrace'))
|
|
247
|
+
this.fail("Expected ',' or '}' after imported name");
|
|
248
|
+
}
|
|
249
|
+
this.take('RightBrace', "Expected '}' after imported names");
|
|
250
|
+
};
|
|
251
|
+
if (this.match('LeftBrace')) {
|
|
252
|
+
namedImportList();
|
|
253
|
+
}
|
|
254
|
+
else {
|
|
255
|
+
const ident = this.identifier();
|
|
256
|
+
defaultImport = ident.name;
|
|
257
|
+
defaultImportLoc = ident.loc;
|
|
258
|
+
if (this.match('Comma')) {
|
|
259
|
+
this.take('LeftBrace', "Expected '{' before named imports");
|
|
260
|
+
namedImportList();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
this.parenthesisSeparators();
|
|
264
|
+
this.take('Keyword', "Expected 'from' after import names");
|
|
265
|
+
const moduleToken = this.take('String', "Expected 'juno', 'juno:node', or 'types' module name");
|
|
266
|
+
const module = String(this.value(moduleToken));
|
|
267
|
+
if (!defaultImport && namedImports.length === 0)
|
|
268
|
+
this.fail('Import must name at least one binding');
|
|
269
|
+
return { kind: 'Import', module, defaultImport, defaultImportLoc, namedImports, namedImportLocs };
|
|
270
|
+
}
|
|
271
|
+
block() {
|
|
272
|
+
this.take('Newline', 'Expected a newline before indented block');
|
|
273
|
+
while (this.match('Newline')) { }
|
|
274
|
+
this.take('Indent', 'Expected an indented block');
|
|
275
|
+
const body = [];
|
|
276
|
+
this.separators();
|
|
277
|
+
while (!this.is('Dedent') && !this.is('EOF')) {
|
|
278
|
+
body.push(this.statement());
|
|
279
|
+
this.separators();
|
|
280
|
+
}
|
|
281
|
+
this.take('Dedent');
|
|
282
|
+
return body;
|
|
283
|
+
}
|
|
284
|
+
matchPattern() {
|
|
285
|
+
const patterns = [this.matchPatternAtom()];
|
|
286
|
+
while (this.match('Pipe'))
|
|
287
|
+
patterns.push(this.matchPatternAtom());
|
|
288
|
+
return patterns.length === 1 ? patterns[0] : { kind: 'PatternUnion', patterns, loc: patterns[0].loc };
|
|
289
|
+
}
|
|
290
|
+
matchPatternAtom() {
|
|
291
|
+
if (this.match('String') || this.match('Number') || this.match('BigInt')) {
|
|
292
|
+
const token = this.tokens[this.pos - 1];
|
|
293
|
+
return { kind: 'PatternLiteral', value: this.value(token), loc: this.loc(token) };
|
|
294
|
+
}
|
|
295
|
+
if (this.match('Keyword', 'true') || this.match('Keyword', 'false') || this.match('Keyword', 'null')) {
|
|
296
|
+
const token = this.tokens[this.pos - 1];
|
|
297
|
+
const value = this.value(token);
|
|
298
|
+
return { kind: 'PatternLiteral', value: value === 'true' ? true : value === 'false' ? false : null, loc: this.loc(token) };
|
|
299
|
+
}
|
|
300
|
+
if (this.match('LeftBrace')) {
|
|
301
|
+
const start = this.tokens[this.pos - 1];
|
|
302
|
+
const properties = [];
|
|
303
|
+
this.objectSeparators();
|
|
304
|
+
while (!this.is('RightBrace')) {
|
|
305
|
+
const property = this.propertyName();
|
|
306
|
+
const pattern = this.match('Colon') ? this.matchPatternAtom() : undefined;
|
|
307
|
+
properties.push({ name: property.name, pattern, loc: property.loc });
|
|
308
|
+
this.parenthesisSeparators();
|
|
309
|
+
if (this.match('Comma'))
|
|
310
|
+
this.objectSeparators();
|
|
311
|
+
else if (!this.is('RightBrace'))
|
|
312
|
+
this.fail("Expected ',' or '}' in match object pattern");
|
|
313
|
+
}
|
|
314
|
+
this.take('RightBrace');
|
|
315
|
+
return { kind: 'PatternObject', properties, loc: this.loc(start) };
|
|
316
|
+
}
|
|
317
|
+
const token = this.take('Identifier', 'Expected a literal, type, variable, or object pattern');
|
|
318
|
+
return { kind: 'PatternIdentifier', name: String(this.value(token)), nullable: this.match('Question'), loc: this.loc(token) };
|
|
319
|
+
}
|
|
320
|
+
matchExpression(token) {
|
|
321
|
+
const value = this.expression();
|
|
322
|
+
this.take('Newline', 'Expected a newline after match value');
|
|
323
|
+
this.take('Indent', 'Expected indented match cases');
|
|
324
|
+
const cases = [];
|
|
325
|
+
this.separators();
|
|
326
|
+
while (!this.is('Dedent') && !this.is('EOF')) {
|
|
327
|
+
if (this.match('Keyword', 'case')) {
|
|
328
|
+
const caseToken = this.tokens[this.pos - 1];
|
|
329
|
+
const pattern = this.matchPattern();
|
|
330
|
+
const guard = this.match('Keyword', 'when') ? this.expression() : undefined;
|
|
331
|
+
cases.push({ pattern, guard, body: this.block(), loc: this.loc(caseToken) });
|
|
332
|
+
}
|
|
333
|
+
else if (this.match('Keyword', 'default')) {
|
|
334
|
+
const defaultToken = this.tokens[this.pos - 1];
|
|
335
|
+
if (cases.some(item => !item.pattern))
|
|
336
|
+
this.fail('A match expression can only have one default case');
|
|
337
|
+
cases.push({ body: this.block(), loc: this.loc(defaultToken) });
|
|
338
|
+
}
|
|
339
|
+
else
|
|
340
|
+
this.fail("Expected 'case' or 'default' in match expression");
|
|
341
|
+
this.separators();
|
|
342
|
+
}
|
|
343
|
+
this.take('Dedent');
|
|
344
|
+
return { kind: 'Match', value, cases, loc: this.loc(token) };
|
|
345
|
+
}
|
|
346
|
+
parameters() {
|
|
347
|
+
this.take('LeftParen');
|
|
348
|
+
const params = [];
|
|
349
|
+
let optionalSeen = false, restSeen = false;
|
|
350
|
+
while (!this.is('RightParen')) {
|
|
351
|
+
const ellipsis = this.is('Ellipsis');
|
|
352
|
+
const rest = ellipsis || this.is('Dot') && this.tokens[this.pos + 1]?.type === 'Dot' && this.tokens[this.pos + 2]?.type === 'Dot';
|
|
353
|
+
if (rest)
|
|
354
|
+
this.pos += ellipsis ? 1 : 3;
|
|
355
|
+
if (restSeen)
|
|
356
|
+
this.fail('A rest parameter must be the last parameter');
|
|
357
|
+
const { name, loc } = this.identifier(), type = this.match('Colon') ? this.type() : undefined, defaultValue = this.match('Equal') ? this.expression() : undefined;
|
|
358
|
+
if (rest && defaultValue !== undefined)
|
|
359
|
+
this.fail('A rest parameter cannot have a default value');
|
|
360
|
+
if (rest && !type)
|
|
361
|
+
this.fail('A rest parameter must have an array type');
|
|
362
|
+
if (rest && type && type.kind !== 'NamedType' && type.kind !== 'ArrayType' && !(type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray')))
|
|
363
|
+
this.fail('A rest parameter must have an array type or an array-constrained generic type');
|
|
364
|
+
if (!rest && defaultValue !== undefined)
|
|
365
|
+
optionalSeen = true;
|
|
366
|
+
else if (!rest && optionalSeen)
|
|
367
|
+
this.fail('Parameters with default values must follow parameters without default values');
|
|
368
|
+
params.push({ name, loc, type, defaultValue, rest });
|
|
369
|
+
restSeen ||= rest;
|
|
370
|
+
if (!this.match('Comma') && !this.is('RightParen'))
|
|
371
|
+
this.fail("Expected ',' or ')' in parameters");
|
|
372
|
+
}
|
|
373
|
+
this.take('RightParen');
|
|
374
|
+
return params;
|
|
375
|
+
}
|
|
376
|
+
genericParameters() {
|
|
377
|
+
const parameters = [];
|
|
378
|
+
let defaultSeen = false;
|
|
379
|
+
do {
|
|
380
|
+
const parameter = this.identifier();
|
|
381
|
+
const constraint = this.match('Identifier', 'is') ? this.type() : undefined;
|
|
382
|
+
const defaultType = this.match('Equal') ? this.type() : undefined;
|
|
383
|
+
if (defaultType)
|
|
384
|
+
defaultSeen = true;
|
|
385
|
+
else if (defaultSeen)
|
|
386
|
+
this.fail('Required generic parameters must precede defaulted generic parameters');
|
|
387
|
+
parameters.push({ ...parameter, constraint, defaultType });
|
|
388
|
+
} while (this.match('Comma'));
|
|
389
|
+
this.take('Greater');
|
|
390
|
+
return parameters;
|
|
391
|
+
}
|
|
392
|
+
type(stopAtConditionalQuestion = false) {
|
|
393
|
+
while (this.match('Newline') || this.match('Indent')) { }
|
|
394
|
+
if (this.is('Pipe') || this.is('Ampersand')) {
|
|
395
|
+
const operator = this.current.type;
|
|
396
|
+
const parts = [];
|
|
397
|
+
while (this.is(operator)) {
|
|
398
|
+
this.pos++;
|
|
399
|
+
while (this.match('Newline') || this.match('Indent')) { }
|
|
400
|
+
parts.push(this.typeAtom());
|
|
401
|
+
while (this.match('Newline')) { }
|
|
402
|
+
}
|
|
403
|
+
const kind = operator === 'Pipe' ? 'UnionType' : 'IntersectionType';
|
|
404
|
+
return parts.length === 1 ? parts[0] : { kind, types: parts };
|
|
405
|
+
}
|
|
406
|
+
const optional = () => {
|
|
407
|
+
let value = this.typeAtom();
|
|
408
|
+
if (!stopAtConditionalQuestion && this.match('Question'))
|
|
409
|
+
value = { kind: 'UnionType', types: [value, { kind: 'NamedType', name: 'null' }] };
|
|
410
|
+
return value;
|
|
411
|
+
};
|
|
412
|
+
let left = optional();
|
|
413
|
+
while (this.is('Pipe') || this.is('Ampersand') || this.is('Newline') && (this.tokens[this.pos + 1]?.type === 'Pipe' || this.tokens[this.pos + 1]?.type === 'Ampersand') || this.is('Newline') && this.tokens[this.pos + 1]?.type === 'Indent' && (this.tokens[this.pos + 2]?.type === 'Pipe' || this.tokens[this.pos + 2]?.type === 'Ampersand')) {
|
|
414
|
+
while (this.match('Newline') || this.match('Indent')) { }
|
|
415
|
+
const operator = this.current.type;
|
|
416
|
+
if (operator !== 'Pipe' && operator !== 'Ampersand')
|
|
417
|
+
break;
|
|
418
|
+
this.pos++;
|
|
419
|
+
while (this.match('Newline') || this.match('Indent')) { }
|
|
420
|
+
const right = optional(), kind = operator === 'Pipe' ? 'UnionType' : 'IntersectionType';
|
|
421
|
+
left = left.kind === kind ? { ...left, types: [...left.types, right] } : { kind, types: [left, right] };
|
|
422
|
+
}
|
|
423
|
+
if (this.match('Identifier', 'is')) {
|
|
424
|
+
const token = this.tokens[this.pos - 1];
|
|
425
|
+
const target = this.type(true);
|
|
426
|
+
if (left.kind !== 'NamedType' || target.kind !== 'NamedType')
|
|
427
|
+
this.fail("'is' type operands must be type names");
|
|
428
|
+
if (this.match('Question')) {
|
|
429
|
+
const consequent = this.type();
|
|
430
|
+
this.take('Colon', "Expected ':' in conditional type");
|
|
431
|
+
return { kind: 'ConditionalType', check: left, target, consequent, alternate: this.type(), loc: this.loc(token) };
|
|
432
|
+
}
|
|
433
|
+
return { kind: 'ConditionalType', check: left, target, consequent: { kind: 'LiteralType', value: true }, alternate: { kind: 'LiteralType', value: false }, loc: this.loc(token) };
|
|
434
|
+
}
|
|
435
|
+
return left;
|
|
436
|
+
}
|
|
437
|
+
typeAtom() {
|
|
438
|
+
let result;
|
|
439
|
+
if (this.is('Identifier', 'typeof') && this.tokens[this.pos + 1]?.type === 'Less') {
|
|
440
|
+
const token = this.take('Identifier');
|
|
441
|
+
this.take('Less');
|
|
442
|
+
const expression = this.expression(6);
|
|
443
|
+
const typeQueryExpression = (value) => value.kind === 'Identifier' || value.kind === 'Member' && typeQueryExpression(value.object) || value.kind === 'Index' && typeQueryExpression(value.object) && (value.index.kind === 'Identifier' || value.index.kind === 'Literal');
|
|
444
|
+
if (!typeQueryExpression(expression))
|
|
445
|
+
this.fail('typeof<> only accepts an identifier, member, or indexed access');
|
|
446
|
+
this.take('Greater', "Expected '>' after typeof expression");
|
|
447
|
+
result = { kind: 'TypeOfType', expression, loc: this.loc(token) };
|
|
448
|
+
}
|
|
449
|
+
else if (this.match('Minus')) {
|
|
450
|
+
const minus = this.tokens[this.pos - 1];
|
|
451
|
+
const number = this.take('Number', 'Expected a number after \'-\' in literal type');
|
|
452
|
+
result = { kind: 'LiteralType', value: -this.value(number), loc: this.loc(minus) };
|
|
453
|
+
}
|
|
454
|
+
else if (this.match('Number')) {
|
|
455
|
+
const token = this.tokens[this.pos - 1];
|
|
456
|
+
result = { kind: 'LiteralType', value: this.value(token), loc: this.loc(token) };
|
|
457
|
+
}
|
|
458
|
+
else if (this.match('String')) {
|
|
459
|
+
const token = this.tokens[this.pos - 1];
|
|
460
|
+
result = { kind: 'LiteralType', value: this.value(token), loc: this.loc(token) };
|
|
461
|
+
}
|
|
462
|
+
else if (this.match('Keyword', 'true') || this.match('Keyword', 'false')) {
|
|
463
|
+
const token = this.tokens[this.pos - 1];
|
|
464
|
+
result = { kind: 'LiteralType', value: this.value(token) === 'true', loc: this.loc(token) };
|
|
465
|
+
}
|
|
466
|
+
else if (this.match('LeftBrace')) {
|
|
467
|
+
const members = [];
|
|
468
|
+
this.objectSeparators();
|
|
469
|
+
while (!this.is('RightBrace') && !this.is('EOF')) {
|
|
470
|
+
if (this.match('LeftBracket')) {
|
|
471
|
+
const key = this.identifier();
|
|
472
|
+
this.take('Colon', "Expected ':' after index parameter");
|
|
473
|
+
const indexType = this.type();
|
|
474
|
+
this.take('RightBracket', "Expected ']' after index parameter type");
|
|
475
|
+
this.take('Colon', "Expected ':' before indexed value type");
|
|
476
|
+
const valueType = this.type();
|
|
477
|
+
members.push({ name: key.name, loc: key.loc, type: valueType, indexType, optional: false, readonly: false, constant: false });
|
|
478
|
+
this.objectSeparators();
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
let readonly = false, sealed = false, constant = false;
|
|
482
|
+
while (this.is('Keyword') && ['readonly', 'sealed', 'const'].includes(String(this.value(this.current)))) {
|
|
483
|
+
const modifier = String(this.value(this.tokens[this.pos++]));
|
|
484
|
+
if (modifier === 'readonly')
|
|
485
|
+
readonly = true;
|
|
486
|
+
else if (modifier === 'sealed')
|
|
487
|
+
sealed = true;
|
|
488
|
+
else
|
|
489
|
+
constant = true;
|
|
490
|
+
}
|
|
491
|
+
const explicitFunction = this.match('Keyword', 'fun');
|
|
492
|
+
const accessor = this.is('Identifier') && ['get', 'set'].includes(String(this.value(this.current))) && this.tokens[this.pos + 1]?.type === 'Identifier'
|
|
493
|
+
? String(this.value(this.tokens[this.pos++]))
|
|
494
|
+
: undefined;
|
|
495
|
+
const anonymousFunction = explicitFunction && this.is('LeftParen');
|
|
496
|
+
const { name, loc } = anonymousFunction
|
|
497
|
+
? { name: '', loc: this.loc(this.tokens[this.pos - 1]) }
|
|
498
|
+
: this.propertyName();
|
|
499
|
+
const genericParameters = !anonymousFunction && this.match('Less') ? this.genericParameters() : [];
|
|
500
|
+
let optional = this.match('Question');
|
|
501
|
+
let params, method = false, type, body;
|
|
502
|
+
if (this.is('LeftParen')) {
|
|
503
|
+
method = true;
|
|
504
|
+
params = this.parameters();
|
|
505
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
506
|
+
if (this.match('Equal')) {
|
|
507
|
+
body = this.is('Newline') ? this.block() : [{ kind: 'Return', value: this.expression() }];
|
|
508
|
+
const last = body.at(-1);
|
|
509
|
+
if (anonymousFunction && last?.kind === 'ExpressionStatement') {
|
|
510
|
+
body[body.length - 1] = { kind: 'Return', value: last.expression };
|
|
511
|
+
}
|
|
512
|
+
type = returnType ?? { kind: 'NamedType', name: 'any' };
|
|
513
|
+
}
|
|
514
|
+
else
|
|
515
|
+
type = returnType ?? { kind: 'NamedType', name: 'void' };
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
if (explicitFunction)
|
|
519
|
+
this.fail("Expected '(' after object function name");
|
|
520
|
+
if (this.match('Colon'))
|
|
521
|
+
type = this.type();
|
|
522
|
+
else if (this.is('Equal'))
|
|
523
|
+
type = { kind: 'NamedType', name: 'any' };
|
|
524
|
+
else
|
|
525
|
+
this.fail("Expected ':' or '=' after field name");
|
|
526
|
+
}
|
|
527
|
+
const defaultValue = this.match('Equal') ? this.expression() : undefined;
|
|
528
|
+
if (constant && defaultValue === undefined)
|
|
529
|
+
this.fail('const type fields need a default value');
|
|
530
|
+
if (!method && defaultValue && type.kind === 'NamedType' && type.name === 'any')
|
|
531
|
+
type = inferredTypeNode(defaultValue);
|
|
532
|
+
if (accessor === 'get' && params?.length)
|
|
533
|
+
this.fail('A getter cannot have parameters');
|
|
534
|
+
if (accessor === 'set' && params?.length !== 1)
|
|
535
|
+
this.fail('A setter must have exactly one parameter');
|
|
536
|
+
const accessorType = accessor === 'set' ? params?.[0]?.type ?? { kind: 'NamedType', name: 'any' } : type;
|
|
537
|
+
members.push({ name, loc, optional, readonly, sealed, constant, type: accessorType, defaultValue, method, accessor, generics: genericParameters.map(item => item.name), genericLocs: genericParameters.map(item => item.loc), genericConstraints: genericParameters.map(item => item.constraint), genericDefaults: genericParameters.map(item => item.defaultType), params, body });
|
|
538
|
+
this.objectSeparators();
|
|
539
|
+
}
|
|
540
|
+
this.take('RightBrace');
|
|
541
|
+
result = { kind: 'ObjectType', members };
|
|
542
|
+
}
|
|
543
|
+
else if (this.is('Keyword', 'fun') || this.is('LeftParen')) {
|
|
544
|
+
const explicitFunction = this.match('Keyword', 'fun');
|
|
545
|
+
const genericParameters = explicitFunction && this.match('Less') ? this.genericParameters() : undefined;
|
|
546
|
+
this.take('LeftParen', "Expected '(' in function type");
|
|
547
|
+
const args = [];
|
|
548
|
+
const paramNames = [];
|
|
549
|
+
let rest;
|
|
550
|
+
let restName;
|
|
551
|
+
if (!this.is('RightParen'))
|
|
552
|
+
do {
|
|
553
|
+
if (rest)
|
|
554
|
+
this.fail('A rest parameter must be the last parameter');
|
|
555
|
+
const variadic = this.match('Ellipsis');
|
|
556
|
+
let name;
|
|
557
|
+
if (this.is('Identifier') && this.tokens[this.pos + 1]?.type === 'Colon') {
|
|
558
|
+
name = this.identifier().name;
|
|
559
|
+
this.take('Colon');
|
|
560
|
+
}
|
|
561
|
+
const argument = this.type();
|
|
562
|
+
if (variadic) {
|
|
563
|
+
rest = argument;
|
|
564
|
+
restName = name;
|
|
565
|
+
}
|
|
566
|
+
else {
|
|
567
|
+
args.push(argument);
|
|
568
|
+
paramNames.push(name);
|
|
569
|
+
}
|
|
570
|
+
} while (this.match('Comma'));
|
|
571
|
+
this.take('RightParen');
|
|
572
|
+
if (this.match('Arrow') || this.match('FatArrow')) {
|
|
573
|
+
result = { kind: 'FunctionType', params: args, paramNames, rest, restName, genericParameters, result: this.type() };
|
|
574
|
+
}
|
|
575
|
+
else if (!explicitFunction && !rest && args.length === 1)
|
|
576
|
+
result = args[0];
|
|
577
|
+
else
|
|
578
|
+
this.fail('Expected function return type after -> or =>');
|
|
579
|
+
}
|
|
580
|
+
else if (this.match('LeftBracket')) {
|
|
581
|
+
const elements = [];
|
|
582
|
+
if (!this.is('RightBracket'))
|
|
583
|
+
do {
|
|
584
|
+
elements.push(this.type());
|
|
585
|
+
} while (this.match('Comma') && !this.is('RightBracket'));
|
|
586
|
+
this.take('RightBracket', "Expected ']' after tuple type");
|
|
587
|
+
result = { kind: 'GenericType', name: 'Tuple', args: elements };
|
|
588
|
+
}
|
|
589
|
+
else if (this.match('Keyword', 'null')) {
|
|
590
|
+
result = { kind: 'NamedType', name: 'null', loc: this.loc(this.tokens[this.pos - 1]) };
|
|
591
|
+
}
|
|
592
|
+
else {
|
|
593
|
+
const { name, loc } = this.identifier();
|
|
594
|
+
let args = [];
|
|
595
|
+
if (this.match('Less')) {
|
|
596
|
+
args.push(this.type());
|
|
597
|
+
while (this.match('Comma'))
|
|
598
|
+
args.push(this.type());
|
|
599
|
+
this.take('Greater');
|
|
600
|
+
}
|
|
601
|
+
result = args.length ? { kind: 'GenericType', name, args, loc } : { kind: 'NamedType', name, loc };
|
|
602
|
+
}
|
|
603
|
+
while (this.match('LeftBracket')) {
|
|
604
|
+
const bracket = this.tokens[this.pos - 1];
|
|
605
|
+
if (this.match('RightBracket'))
|
|
606
|
+
result = { kind: 'ArrayType', element: result };
|
|
607
|
+
else {
|
|
608
|
+
const index = this.type();
|
|
609
|
+
this.take('RightBracket', "Expected ']' after indexed access type");
|
|
610
|
+
result = { kind: 'IndexedAccessType', object: result, index, loc: this.loc(bracket) };
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return result;
|
|
614
|
+
}
|
|
615
|
+
expression(min = 0) {
|
|
616
|
+
let left = this.prefix();
|
|
617
|
+
let typeArguments;
|
|
618
|
+
let continuationIndents = 0;
|
|
619
|
+
const continuationLine = (requireDot) => {
|
|
620
|
+
if (!this.is('Newline'))
|
|
621
|
+
return false;
|
|
622
|
+
const saved = this.pos;
|
|
623
|
+
while (this.match('Newline')) { }
|
|
624
|
+
const indented = this.match('Indent');
|
|
625
|
+
if (requireDot && !this.is('Dot')) {
|
|
626
|
+
this.pos = saved;
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
if (indented)
|
|
630
|
+
continuationIndents++;
|
|
631
|
+
return true;
|
|
632
|
+
};
|
|
633
|
+
while (true) {
|
|
634
|
+
// A member chain may continue on the next indented line either with
|
|
635
|
+
// a leading dot or after a trailing dot on the previous line.
|
|
636
|
+
if (continuationLine(true))
|
|
637
|
+
continue;
|
|
638
|
+
// A generic call can also follow a grouped arrow or a factory call.
|
|
639
|
+
if (this.is('Less') && (left.kind === 'Identifier' || left.kind === 'Member' || left.kind === 'Function' || left.kind === 'Call')) {
|
|
640
|
+
const saved = this.pos;
|
|
641
|
+
try {
|
|
642
|
+
this.pos++;
|
|
643
|
+
typeArguments = [this.type()];
|
|
644
|
+
while (this.match('Comma'))
|
|
645
|
+
typeArguments.push(this.type());
|
|
646
|
+
this.take('Greater');
|
|
647
|
+
if (!this.is('LeftParen')) {
|
|
648
|
+
this.pos = saved;
|
|
649
|
+
typeArguments = undefined;
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
catch {
|
|
653
|
+
this.pos = saved;
|
|
654
|
+
typeArguments = undefined;
|
|
655
|
+
}
|
|
656
|
+
if (typeArguments)
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
if (this.match('Dot')) {
|
|
660
|
+
continuationLine(false);
|
|
661
|
+
const property = this.propertyName();
|
|
662
|
+
left = { kind: 'Member', object: left, property: property.name, optional: false, loc: property.loc };
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
if (this.is('Question') && this.tokens[this.pos + 1]?.type === 'Dot') {
|
|
666
|
+
this.pos += 2;
|
|
667
|
+
const property = this.propertyName();
|
|
668
|
+
left = { kind: 'Member', object: left, property: property.name, optional: true, loc: property.loc };
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
if (this.match('LeftBracket')) {
|
|
672
|
+
const token = this.tokens[this.pos - 1];
|
|
673
|
+
const index = this.expression();
|
|
674
|
+
this.take('RightBracket', "Expected ']' after index");
|
|
675
|
+
left = { kind: 'Index', object: left, index, loc: this.loc(token) };
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
if (this.match('LeftParen')) {
|
|
679
|
+
const args = [];
|
|
680
|
+
this.parenthesisSeparators();
|
|
681
|
+
if (!this.is('RightParen'))
|
|
682
|
+
do {
|
|
683
|
+
if (this.match('Ellipsis')) {
|
|
684
|
+
const token = this.tokens[this.pos - 1];
|
|
685
|
+
args.push({ kind: 'Spread', value: this.expression(), loc: this.loc(token) });
|
|
686
|
+
}
|
|
687
|
+
else
|
|
688
|
+
args.push(this.expression());
|
|
689
|
+
this.parenthesisSeparators();
|
|
690
|
+
} while (this.match('Comma') && (this.parenthesisSeparators(), true));
|
|
691
|
+
this.take('RightParen');
|
|
692
|
+
left = { kind: 'Call', callee: left, args, typeArguments };
|
|
693
|
+
typeArguments = undefined;
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (this.match('Bang')) {
|
|
697
|
+
const token = this.tokens[this.pos - 1];
|
|
698
|
+
left = { kind: 'Unary', operator: 'postfix!', operand: left, loc: this.loc(token) };
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
if (this.match('Increment') || this.match('Decrement')) {
|
|
702
|
+
const token = this.tokens[this.pos - 1];
|
|
703
|
+
if (!['Identifier', 'Member', 'Index'].includes(left.kind))
|
|
704
|
+
this.fail('Increment and decrement require an assignable target');
|
|
705
|
+
left = { kind: 'Unary', operator: token.type === 'Increment' ? 'postfix++' : 'postfix--', operand: left, loc: this.loc(token) };
|
|
706
|
+
continue;
|
|
707
|
+
}
|
|
708
|
+
if (this.is('Question') && min <= 0) {
|
|
709
|
+
const token = this.current;
|
|
710
|
+
this.pos++;
|
|
711
|
+
const consequent = this.expression();
|
|
712
|
+
this.take('Colon', "Expected ':' in conditional expression");
|
|
713
|
+
const alternate = this.expression();
|
|
714
|
+
left = { kind: 'Conditional', condition: left, consequent, alternate, loc: this.loc(token) };
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (this.softExpressionIndents > 0 && this.is('Newline')) {
|
|
718
|
+
const saved = this.pos;
|
|
719
|
+
while (this.match('Newline')) { }
|
|
720
|
+
let consumed = 0;
|
|
721
|
+
while (consumed < this.softExpressionIndents && this.match('Dedent'))
|
|
722
|
+
consumed++;
|
|
723
|
+
if (consumed > 0) {
|
|
724
|
+
this.softExpressionIndents -= consumed;
|
|
725
|
+
break;
|
|
726
|
+
}
|
|
727
|
+
this.pos = saved;
|
|
728
|
+
}
|
|
729
|
+
if (continuationIndents > 0 && this.is('Newline')) {
|
|
730
|
+
while (this.match('Newline')) { }
|
|
731
|
+
while (continuationIndents > 0 && this.match('Dedent'))
|
|
732
|
+
continuationIndents--;
|
|
733
|
+
if (continuationIndents === 0)
|
|
734
|
+
break;
|
|
735
|
+
}
|
|
736
|
+
const op = opTypes[this.current.type], p = op ? precedence[op] : undefined;
|
|
737
|
+
if (!op || p === undefined || p < min)
|
|
738
|
+
break;
|
|
739
|
+
const operatorToken = this.current;
|
|
740
|
+
this.pos++;
|
|
741
|
+
left = { kind: 'Binary', operator: op, left, right: this.expression(p + 1), loc: this.loc(operatorToken) };
|
|
742
|
+
}
|
|
743
|
+
return left;
|
|
744
|
+
}
|
|
745
|
+
templateExpression(value, loc) {
|
|
746
|
+
const parts = [];
|
|
747
|
+
let cursor = 0;
|
|
748
|
+
while (cursor < value.length) {
|
|
749
|
+
const start = value.indexOf('${', cursor);
|
|
750
|
+
if (start < 0) {
|
|
751
|
+
parts.push(value.slice(cursor).replace(/\uE000/g, '$'));
|
|
752
|
+
break;
|
|
753
|
+
}
|
|
754
|
+
if (start > cursor)
|
|
755
|
+
parts.push(value.slice(cursor, start).replace(/\uE000/g, '$'));
|
|
756
|
+
let depth = 1, quote = '', escaped = false, end = start + 2;
|
|
757
|
+
for (; end < value.length; end++) {
|
|
758
|
+
const char = value[end];
|
|
759
|
+
if (escaped) {
|
|
760
|
+
escaped = false;
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (char === '\\') {
|
|
764
|
+
escaped = true;
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
if (quote) {
|
|
768
|
+
if (char === quote)
|
|
769
|
+
quote = '';
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
773
|
+
quote = char;
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
if (char === '{')
|
|
777
|
+
depth++;
|
|
778
|
+
else if (char === '}' && --depth === 0)
|
|
779
|
+
break;
|
|
780
|
+
}
|
|
781
|
+
if (depth !== 0)
|
|
782
|
+
this.fail('Unterminated string interpolation');
|
|
783
|
+
const rawSource = value.slice(start + 2, end);
|
|
784
|
+
const leadingWhitespace = rawSource.length - rawSource.trimStart().length;
|
|
785
|
+
const source = rawSource.trim();
|
|
786
|
+
if (!source)
|
|
787
|
+
this.fail('String interpolation cannot be empty');
|
|
788
|
+
const expression = new Parser((0, lexer_1.Lexer)(source).tokenize()).parseExpressionOnly();
|
|
789
|
+
const offset = start + 2 + leadingWhitespace;
|
|
790
|
+
const shiftLoc = (loc) => {
|
|
791
|
+
if (!loc)
|
|
792
|
+
return loc;
|
|
793
|
+
const absoluteOffset = offset + loc.column - 1;
|
|
794
|
+
const before = value.slice(0, absoluteOffset);
|
|
795
|
+
const lastNewline = before.lastIndexOf('\n');
|
|
796
|
+
return {
|
|
797
|
+
line: loc.line + (before.match(/\n/g)?.length ?? 0),
|
|
798
|
+
column: (lastNewline < 0 ? loc.column + offset : absoluteOffset - lastNewline) + (loc.line > 1 ? loc.column - 1 : 0)
|
|
799
|
+
};
|
|
800
|
+
};
|
|
801
|
+
const shiftExpression = (node) => {
|
|
802
|
+
if ('loc' in node)
|
|
803
|
+
node.loc = shiftLoc(node.loc);
|
|
804
|
+
switch (node.kind) {
|
|
805
|
+
case 'Template':
|
|
806
|
+
for (const part of node.parts)
|
|
807
|
+
if (typeof part !== 'string')
|
|
808
|
+
shiftExpression(part);
|
|
809
|
+
break;
|
|
810
|
+
case 'RegEx': break;
|
|
811
|
+
case 'Array':
|
|
812
|
+
node.elements.forEach(shiftExpression);
|
|
813
|
+
break;
|
|
814
|
+
case 'Spread':
|
|
815
|
+
shiftExpression(node.value);
|
|
816
|
+
break;
|
|
817
|
+
case 'Object':
|
|
818
|
+
for (const property of node.properties) {
|
|
819
|
+
property.keyLoc = shiftLoc(property.keyLoc);
|
|
820
|
+
shiftExpression(property.value);
|
|
821
|
+
}
|
|
822
|
+
break;
|
|
823
|
+
case 'Unary':
|
|
824
|
+
shiftExpression(node.operand);
|
|
825
|
+
break;
|
|
826
|
+
case 'Assignment':
|
|
827
|
+
shiftExpression(node.value);
|
|
828
|
+
break;
|
|
829
|
+
case 'MemberAssignment':
|
|
830
|
+
node.propertyLoc = shiftLoc(node.propertyLoc);
|
|
831
|
+
shiftExpression(node.object);
|
|
832
|
+
if (node.index)
|
|
833
|
+
shiftExpression(node.index);
|
|
834
|
+
shiftExpression(node.value);
|
|
835
|
+
break;
|
|
836
|
+
case 'Binary':
|
|
837
|
+
shiftExpression(node.left);
|
|
838
|
+
shiftExpression(node.right);
|
|
839
|
+
break;
|
|
840
|
+
case 'Conditional':
|
|
841
|
+
shiftExpression(node.condition);
|
|
842
|
+
shiftExpression(node.consequent);
|
|
843
|
+
shiftExpression(node.alternate);
|
|
844
|
+
break;
|
|
845
|
+
case 'Match':
|
|
846
|
+
shiftExpression(node.value);
|
|
847
|
+
node.cases.forEach(item => { if (item.guard)
|
|
848
|
+
shiftExpression(item.guard); item.body.forEach(shiftStatement); });
|
|
849
|
+
break;
|
|
850
|
+
case 'Try':
|
|
851
|
+
if (node.value)
|
|
852
|
+
shiftExpression(node.value);
|
|
853
|
+
node.body?.forEach(shiftStatement);
|
|
854
|
+
node.catches.forEach(item => item.body.forEach(shiftStatement));
|
|
855
|
+
node.finallyBody?.forEach(shiftStatement);
|
|
856
|
+
break;
|
|
857
|
+
case 'Member':
|
|
858
|
+
shiftExpression(node.object);
|
|
859
|
+
break;
|
|
860
|
+
case 'Index':
|
|
861
|
+
shiftExpression(node.object);
|
|
862
|
+
shiftExpression(node.index);
|
|
863
|
+
break;
|
|
864
|
+
case 'Call':
|
|
865
|
+
shiftExpression(node.callee);
|
|
866
|
+
node.args.forEach(shiftExpression);
|
|
867
|
+
break;
|
|
868
|
+
case 'Function':
|
|
869
|
+
for (const param of node.params) {
|
|
870
|
+
param.loc = shiftLoc(param.loc);
|
|
871
|
+
if (param.defaultValue)
|
|
872
|
+
shiftExpression(param.defaultValue);
|
|
873
|
+
}
|
|
874
|
+
node.body.forEach(shiftStatement);
|
|
875
|
+
if (node.expressionBody)
|
|
876
|
+
shiftExpression(node.expressionBody);
|
|
877
|
+
break;
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
const shiftStatement = (statement) => {
|
|
881
|
+
if ('loc' in statement)
|
|
882
|
+
statement.loc = shiftLoc(statement.loc);
|
|
883
|
+
switch (statement.kind) {
|
|
884
|
+
case 'Variable':
|
|
885
|
+
if (statement.initializer)
|
|
886
|
+
shiftExpression(statement.initializer);
|
|
887
|
+
break;
|
|
888
|
+
case 'ExpressionStatement':
|
|
889
|
+
shiftExpression(statement.expression);
|
|
890
|
+
break;
|
|
891
|
+
case 'Return':
|
|
892
|
+
if (statement.value)
|
|
893
|
+
shiftExpression(statement.value);
|
|
894
|
+
break;
|
|
895
|
+
case 'Break':
|
|
896
|
+
statement.loc = shiftLoc(statement.loc);
|
|
897
|
+
break;
|
|
898
|
+
case 'If':
|
|
899
|
+
shiftExpression(statement.condition);
|
|
900
|
+
statement.consequent.forEach(shiftStatement);
|
|
901
|
+
statement.alternate?.forEach(shiftStatement);
|
|
902
|
+
break;
|
|
903
|
+
case 'ForOf':
|
|
904
|
+
shiftExpression(statement.iterable);
|
|
905
|
+
statement.body.forEach(shiftStatement);
|
|
906
|
+
break;
|
|
907
|
+
case 'While':
|
|
908
|
+
shiftExpression(statement.condition);
|
|
909
|
+
statement.body.forEach(shiftStatement);
|
|
910
|
+
break;
|
|
911
|
+
case 'FunctionDeclaration':
|
|
912
|
+
statement.body.forEach(shiftStatement);
|
|
913
|
+
break;
|
|
914
|
+
case 'TypeDeclaration': break;
|
|
915
|
+
case 'Import': break;
|
|
916
|
+
}
|
|
917
|
+
};
|
|
918
|
+
shiftExpression(expression);
|
|
919
|
+
parts.push(expression);
|
|
920
|
+
cursor = end + 1;
|
|
921
|
+
}
|
|
922
|
+
if (!parts.length)
|
|
923
|
+
parts.push(value.replace(/\uE000/g, '$'));
|
|
924
|
+
return { kind: 'Template', parts, loc };
|
|
925
|
+
}
|
|
926
|
+
prefix() {
|
|
927
|
+
if (this.match('Keyword', 'try'))
|
|
928
|
+
return this.tryExpression(this.tokens[this.pos - 1]);
|
|
929
|
+
if (this.match('Keyword', 'match'))
|
|
930
|
+
return this.matchExpression(this.tokens[this.pos - 1]);
|
|
931
|
+
if (this.match('Keyword', 'await')) {
|
|
932
|
+
const token = this.tokens[this.pos - 1];
|
|
933
|
+
return { kind: 'Unary', operator: 'await', operand: this.expression(7), loc: this.loc(token) };
|
|
934
|
+
}
|
|
935
|
+
if (this.match('Increment') || this.match('Decrement')) {
|
|
936
|
+
const token = this.tokens[this.pos - 1];
|
|
937
|
+
const operand = this.expression(8);
|
|
938
|
+
if (!['Identifier', 'Member', 'Index'].includes(operand.kind))
|
|
939
|
+
this.fail('Increment and decrement require an assignable target');
|
|
940
|
+
return { kind: 'Unary', operator: token.type === 'Increment' ? 'prefix++' : 'prefix--', operand, loc: this.loc(token) };
|
|
941
|
+
}
|
|
942
|
+
if (this.match('Minus') || this.match('Bang')) {
|
|
943
|
+
const token = this.tokens[this.pos - 1];
|
|
944
|
+
return { kind: 'Unary', operator: token.type === 'Minus' ? '-' : '!', operand: this.expression(7), loc: this.loc(token) };
|
|
945
|
+
}
|
|
946
|
+
if (this.match('BigInt')) {
|
|
947
|
+
const token = this.tokens[this.pos - 1];
|
|
948
|
+
return { kind: 'Literal', value: this.value(token), loc: this.loc(token) };
|
|
949
|
+
}
|
|
950
|
+
if (this.match('Number')) {
|
|
951
|
+
const token = this.tokens[this.pos - 1];
|
|
952
|
+
return { kind: 'Literal', value: this.value(token), loc: this.loc(token) };
|
|
953
|
+
}
|
|
954
|
+
if (this.match('String')) {
|
|
955
|
+
const token = this.tokens[this.pos - 1];
|
|
956
|
+
const value = this.value(token);
|
|
957
|
+
return value.includes('${') ? this.templateExpression(value, this.loc(token)) : { kind: 'Literal', value: value.replace(/\uE000/g, '$'), loc: this.loc(token) };
|
|
958
|
+
}
|
|
959
|
+
if (this.match('RegEx')) {
|
|
960
|
+
const token = this.tokens[this.pos - 1];
|
|
961
|
+
return { kind: 'RegEx', source: token.value.source, flags: token.value.flags, loc: this.loc(token) };
|
|
962
|
+
}
|
|
963
|
+
if (this.match('Keyword', 'true'))
|
|
964
|
+
return { kind: 'Literal', value: true, loc: this.loc(this.tokens[this.pos - 1]) };
|
|
965
|
+
if (this.match('Keyword', 'false'))
|
|
966
|
+
return { kind: 'Literal', value: false, loc: this.loc(this.tokens[this.pos - 1]) };
|
|
967
|
+
if (this.match('Keyword', 'null'))
|
|
968
|
+
return { kind: 'Literal', value: null, loc: this.loc(this.tokens[this.pos - 1]) };
|
|
969
|
+
if (this.match('Identifier')) {
|
|
970
|
+
const token = this.tokens[this.pos - 1];
|
|
971
|
+
const name = String(this.value(token));
|
|
972
|
+
const loc = this.loc(token);
|
|
973
|
+
if (this.match('FatArrow')) {
|
|
974
|
+
const params = [{ name, loc }];
|
|
975
|
+
if (this.match('Newline')) {
|
|
976
|
+
this.take('Indent', 'Expected an indented function body');
|
|
977
|
+
const body = [];
|
|
978
|
+
this.separators();
|
|
979
|
+
while (!this.is('Dedent') && !this.is('EOF')) {
|
|
980
|
+
body.push(this.statement());
|
|
981
|
+
this.separators();
|
|
982
|
+
}
|
|
983
|
+
this.take('Dedent');
|
|
984
|
+
return { kind: 'Function', params, body };
|
|
985
|
+
}
|
|
986
|
+
return { kind: 'Function', params, body: [], expressionBody: this.expression() };
|
|
987
|
+
}
|
|
988
|
+
return { kind: 'Identifier', name, loc };
|
|
989
|
+
}
|
|
990
|
+
if (this.is('LeftParen') || this.is('Less')) {
|
|
991
|
+
const opening = this.current;
|
|
992
|
+
const generic = this.match('Less');
|
|
993
|
+
const generics = generic ? this.genericParameters() : [];
|
|
994
|
+
const saved = this.pos;
|
|
995
|
+
let arrow = false;
|
|
996
|
+
try {
|
|
997
|
+
const params = this.parameters();
|
|
998
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
999
|
+
const newlineArrowBody = () => {
|
|
1000
|
+
this.take('Indent', 'Expected an indented function body');
|
|
1001
|
+
let depth = 0, expressionBody = false;
|
|
1002
|
+
for (let index = this.pos; index < this.tokens.length; index++) {
|
|
1003
|
+
const type = this.tokens[index].type;
|
|
1004
|
+
if (type === 'LeftParen' || type === 'LeftBracket' || type === 'LeftBrace')
|
|
1005
|
+
depth++;
|
|
1006
|
+
else if (type === 'RightParen' || type === 'RightBracket' || type === 'RightBrace') {
|
|
1007
|
+
if (depth === 0) {
|
|
1008
|
+
expressionBody = true;
|
|
1009
|
+
break;
|
|
1010
|
+
}
|
|
1011
|
+
depth--;
|
|
1012
|
+
}
|
|
1013
|
+
else if ((type === 'Dedent' || type === 'EOF') && depth === 0)
|
|
1014
|
+
break;
|
|
1015
|
+
}
|
|
1016
|
+
if (expressionBody) {
|
|
1017
|
+
this.softExpressionIndents++;
|
|
1018
|
+
return { body: [], expressionBody: this.expression() };
|
|
1019
|
+
}
|
|
1020
|
+
const body = [];
|
|
1021
|
+
this.separators();
|
|
1022
|
+
while (!this.is('Dedent') && !this.is('EOF')) {
|
|
1023
|
+
body.push(this.statement());
|
|
1024
|
+
this.separators();
|
|
1025
|
+
}
|
|
1026
|
+
this.take('Dedent');
|
|
1027
|
+
return { body };
|
|
1028
|
+
};
|
|
1029
|
+
if (this.match('FatArrow')) {
|
|
1030
|
+
arrow = true;
|
|
1031
|
+
const body = this.match('Newline') ? newlineArrowBody() : { body: [], expressionBody: this.expression() };
|
|
1032
|
+
return {
|
|
1033
|
+
kind: 'Function', loc: this.loc(opening), params, returnType, ...body,
|
|
1034
|
+
generics: generics.map(item => item.name),
|
|
1035
|
+
genericLocs: generics.map(item => item.loc),
|
|
1036
|
+
genericConstraints: generics.map(item => item.constraint),
|
|
1037
|
+
genericDefaults: generics.map(item => item.defaultType)
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
if (generic)
|
|
1041
|
+
this.fail("Expected '=>' after generic arrow parameters");
|
|
1042
|
+
}
|
|
1043
|
+
catch (error) {
|
|
1044
|
+
if (generic || arrow)
|
|
1045
|
+
throw error; /* Otherwise try parsing as a grouped expression. */
|
|
1046
|
+
}
|
|
1047
|
+
this.pos = saved;
|
|
1048
|
+
this.take('LeftParen');
|
|
1049
|
+
const value = this.expression();
|
|
1050
|
+
this.take('RightParen');
|
|
1051
|
+
return value;
|
|
1052
|
+
}
|
|
1053
|
+
if (this.match('LeftBracket')) {
|
|
1054
|
+
const token = this.tokens[this.pos - 1];
|
|
1055
|
+
const elements = [];
|
|
1056
|
+
this.parenthesisSeparators();
|
|
1057
|
+
while (!this.is('RightBracket') && !this.is('EOF')) {
|
|
1058
|
+
if (this.match('Ellipsis')) {
|
|
1059
|
+
const spread = this.tokens[this.pos - 1];
|
|
1060
|
+
elements.push({ kind: 'Spread', value: this.expression(), loc: this.loc(spread) });
|
|
1061
|
+
}
|
|
1062
|
+
else
|
|
1063
|
+
elements.push(this.expression());
|
|
1064
|
+
this.parenthesisSeparators();
|
|
1065
|
+
if (this.match('Comma'))
|
|
1066
|
+
this.parenthesisSeparators();
|
|
1067
|
+
else if (!this.is('RightBracket'))
|
|
1068
|
+
this.fail("Expected ',' or ']' in array");
|
|
1069
|
+
}
|
|
1070
|
+
this.take('RightBracket');
|
|
1071
|
+
return { kind: 'Array', elements, loc: this.loc(token) };
|
|
1072
|
+
}
|
|
1073
|
+
if (this.match('LeftBrace')) {
|
|
1074
|
+
const token = this.tokens[this.pos - 1];
|
|
1075
|
+
const properties = [];
|
|
1076
|
+
this.objectSeparators();
|
|
1077
|
+
while (!this.is('RightBrace') && !this.is('EOF')) {
|
|
1078
|
+
if (this.match('LeftBracket')) {
|
|
1079
|
+
const key = this.identifier();
|
|
1080
|
+
this.take('Colon', "Expected ':' after index parameter");
|
|
1081
|
+
const indexType = this.type();
|
|
1082
|
+
this.take('RightBracket', "Expected ']' after index parameter type");
|
|
1083
|
+
this.take('Colon', "Expected ':' before indexed value type");
|
|
1084
|
+
const declaredType = this.type();
|
|
1085
|
+
properties.push({ key: key.name, keyLoc: key.loc, value: { kind: 'Literal', value: null }, typeOnly: true, indexType, declaredType });
|
|
1086
|
+
this.objectSeparators();
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
if (this.match('Ellipsis')) {
|
|
1090
|
+
const value = this.expression();
|
|
1091
|
+
properties.push({ key: '', keyLoc: 'loc' in value ? value.loc : undefined, value, spread: true });
|
|
1092
|
+
this.objectSeparators();
|
|
1093
|
+
if (this.match('Comma'))
|
|
1094
|
+
this.objectSeparators();
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
let readonly = false, sealed = false;
|
|
1098
|
+
while (this.is('Keyword') && ['readonly', 'sealed'].includes(String(this.value(this.current)))) {
|
|
1099
|
+
const modifier = String(this.value(this.tokens[this.pos++]));
|
|
1100
|
+
if (modifier === 'readonly')
|
|
1101
|
+
readonly = true;
|
|
1102
|
+
else
|
|
1103
|
+
sealed = true;
|
|
1104
|
+
}
|
|
1105
|
+
const explicitFunction = this.match('Keyword', 'fun');
|
|
1106
|
+
const accessor = this.is('Identifier') && ['get', 'set'].includes(String(this.value(this.current))) && this.tokens[this.pos + 1]?.type === 'Identifier'
|
|
1107
|
+
? String(this.value(this.tokens[this.pos++]))
|
|
1108
|
+
: undefined;
|
|
1109
|
+
const anonymousFunction = explicitFunction && this.is('LeftParen');
|
|
1110
|
+
const property = anonymousFunction
|
|
1111
|
+
? { name: '', loc: this.loc(this.tokens[this.pos - 1]) }
|
|
1112
|
+
: this.propertyName();
|
|
1113
|
+
const genericParameters = explicitFunction && !anonymousFunction && this.match('Less') ? this.genericParameters() : [];
|
|
1114
|
+
let value;
|
|
1115
|
+
if (accessor) {
|
|
1116
|
+
const params = this.parameters();
|
|
1117
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
1118
|
+
if (accessor === 'get' && params.length)
|
|
1119
|
+
this.fail('A getter cannot have parameters');
|
|
1120
|
+
if (accessor === 'set' && params.length !== 1)
|
|
1121
|
+
this.fail('A setter must have exactly one parameter');
|
|
1122
|
+
this.take('Equal', "Expected '=' before accessor body");
|
|
1123
|
+
value = { kind: 'Function', params, returnType, body: this.block() };
|
|
1124
|
+
}
|
|
1125
|
+
else if (this.match('Colon'))
|
|
1126
|
+
value = this.expression();
|
|
1127
|
+
else if (this.match('LeftParen')) {
|
|
1128
|
+
this.pos--;
|
|
1129
|
+
const params = this.parameters();
|
|
1130
|
+
const returnType = this.match('Colon') ? this.type() : undefined;
|
|
1131
|
+
this.take('Equal', "Expected '=' for method body");
|
|
1132
|
+
const body = this.block();
|
|
1133
|
+
const last = body.at(-1);
|
|
1134
|
+
if (anonymousFunction && last?.kind === 'ExpressionStatement') {
|
|
1135
|
+
body[body.length - 1] = { kind: 'Return', value: last.expression };
|
|
1136
|
+
}
|
|
1137
|
+
value = {
|
|
1138
|
+
kind: 'Function',
|
|
1139
|
+
generics: genericParameters.map(item => item.name),
|
|
1140
|
+
genericLocs: genericParameters.map(item => item.loc),
|
|
1141
|
+
genericConstraints: genericParameters.map(item => item.constraint),
|
|
1142
|
+
genericDefaults: genericParameters.map(item => item.defaultType),
|
|
1143
|
+
params, returnType, body
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
else if (explicitFunction)
|
|
1147
|
+
this.fail("Expected '(' after object function name");
|
|
1148
|
+
else
|
|
1149
|
+
value = { kind: 'Identifier', name: property.name, loc: property.loc };
|
|
1150
|
+
properties.push({ key: property.name, keyLoc: property.loc, value, accessor, readonly, sealed });
|
|
1151
|
+
this.objectSeparators();
|
|
1152
|
+
if (this.match('Comma'))
|
|
1153
|
+
this.objectSeparators();
|
|
1154
|
+
}
|
|
1155
|
+
this.take('RightBrace');
|
|
1156
|
+
return { kind: 'Object', properties, loc: this.loc(token) };
|
|
1157
|
+
}
|
|
1158
|
+
if (this.match('Keyword', 'fun')) {
|
|
1159
|
+
const params = this.parameters(), returnType = this.match('Colon') ? this.type() : undefined;
|
|
1160
|
+
this.take('Equal');
|
|
1161
|
+
return { kind: 'Function', params, returnType, body: this.block() };
|
|
1162
|
+
}
|
|
1163
|
+
this.fail('Expected expression');
|
|
1164
|
+
}
|
|
1165
|
+
tryExpression(token) {
|
|
1166
|
+
let value, body;
|
|
1167
|
+
if (this.is('Newline'))
|
|
1168
|
+
body = this.block();
|
|
1169
|
+
else {
|
|
1170
|
+
value = this.expression();
|
|
1171
|
+
this.take('Newline', "Expected a newline after try expression");
|
|
1172
|
+
}
|
|
1173
|
+
while (this.match('Newline')) { }
|
|
1174
|
+
const indentedClauses = value !== undefined && this.match('Indent');
|
|
1175
|
+
const catches = [];
|
|
1176
|
+
let finallyBody;
|
|
1177
|
+
while (this.match('Keyword', 'catch')) {
|
|
1178
|
+
const catchToken = this.tokens[this.pos - 1];
|
|
1179
|
+
let binding, bindingLoc, type;
|
|
1180
|
+
if (this.match('LeftParen')) {
|
|
1181
|
+
const identifier = this.identifier();
|
|
1182
|
+
binding = identifier.name;
|
|
1183
|
+
bindingLoc = identifier.loc;
|
|
1184
|
+
if (this.match('Colon'))
|
|
1185
|
+
type = this.type();
|
|
1186
|
+
this.take('RightParen', "Expected ')' after catch binding");
|
|
1187
|
+
}
|
|
1188
|
+
catches.push({ binding, bindingLoc, type, body: this.block(), loc: this.loc(catchToken) });
|
|
1189
|
+
while (this.match('Newline')) { }
|
|
1190
|
+
}
|
|
1191
|
+
if (this.match('Keyword', 'finally'))
|
|
1192
|
+
finallyBody = this.block();
|
|
1193
|
+
if (!catches.length)
|
|
1194
|
+
this.fail("A try expression needs at least one catch");
|
|
1195
|
+
if (indentedClauses)
|
|
1196
|
+
this.take('Dedent', "Expected the end of the try expression");
|
|
1197
|
+
return { kind: 'Try', value, body, catches, finallyBody, loc: this.loc(token) };
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
exports.Parser = Parser;
|
|
1201
|
+
const unknownType = { kind: 'unknown' };
|
|
1202
|
+
function primitive(name) { return { kind: 'primitive', name }; }
|
|
1203
|
+
function inferredTypeNode(expression) {
|
|
1204
|
+
switch (expression.kind) {
|
|
1205
|
+
case 'RegEx': return { kind: 'NamedType', name: 'RegEx' };
|
|
1206
|
+
case 'Literal': return { kind: 'NamedType', name: typeof expression.value === 'bigint' ? 'BigInt' : expression.value === null ? 'null' : typeof expression.value };
|
|
1207
|
+
case 'Template': return { kind: 'NamedType', name: 'string' };
|
|
1208
|
+
case 'Array': return { kind: 'ArrayType', element: expression.elements[0] ? inferredTypeNode(expression.elements[0]) : { kind: 'NamedType', name: 'any' } };
|
|
1209
|
+
case 'Spread': {
|
|
1210
|
+
const type = inferredTypeNode(expression.value);
|
|
1211
|
+
return type.kind === 'ArrayType' ? type.element : { kind: 'NamedType', name: 'any' };
|
|
1212
|
+
}
|
|
1213
|
+
case 'Object': return { kind: 'ObjectType', members: expression.properties.flatMap(property => property.accessor === 'set' ? [] : [{
|
|
1214
|
+
name: property.key,
|
|
1215
|
+
type: property.typeOnly ? property.declaredType ?? { kind: 'NamedType', name: 'any' } : property.accessor === 'get' && property.value.kind === 'Function' ? property.value.returnType ?? { kind: 'NamedType', name: 'any' } : inferredTypeNode(property.value),
|
|
1216
|
+
optional: false,
|
|
1217
|
+
readonly: Boolean(property.readonly),
|
|
1218
|
+
sealed: Boolean(property.sealed),
|
|
1219
|
+
constant: false,
|
|
1220
|
+
indexType: property.indexType
|
|
1221
|
+
}]) };
|
|
1222
|
+
case 'Conditional': return inferredTypeNode(expression.consequent);
|
|
1223
|
+
case 'Is': return { kind: 'NamedType', name: 'boolean' };
|
|
1224
|
+
default: return { kind: 'NamedType', name: 'any' };
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
function inferExpressionType(expression, variables) {
|
|
1228
|
+
switch (expression.kind) {
|
|
1229
|
+
case 'RegEx': return primitive('RegEx');
|
|
1230
|
+
case 'Literal':
|
|
1231
|
+
if (typeof expression.value === 'bigint')
|
|
1232
|
+
return primitive('BigInt');
|
|
1233
|
+
if (typeof expression.value === 'number' || typeof expression.value === 'string' || typeof expression.value === 'boolean')
|
|
1234
|
+
return { kind: 'literal', value: expression.value };
|
|
1235
|
+
return primitive('null');
|
|
1236
|
+
case 'Template':
|
|
1237
|
+
return primitive('string');
|
|
1238
|
+
case 'Identifier':
|
|
1239
|
+
return variables.get(expression.name) ?? unknownType;
|
|
1240
|
+
case 'Array': {
|
|
1241
|
+
if (expression.elements.length === 0)
|
|
1242
|
+
return { kind: 'array', element: unknownType };
|
|
1243
|
+
const elements = expression.elements.map(element => {
|
|
1244
|
+
if (element.kind !== 'Spread')
|
|
1245
|
+
return inferExpressionType(element, variables);
|
|
1246
|
+
const spread = inferExpressionType(element.value, variables);
|
|
1247
|
+
return spread.kind === 'array' ? spread.element : unknownType;
|
|
1248
|
+
});
|
|
1249
|
+
return { kind: 'array', element: commonType(elements) };
|
|
1250
|
+
}
|
|
1251
|
+
case 'Spread': {
|
|
1252
|
+
const spread = inferExpressionType(expression.value, variables);
|
|
1253
|
+
return spread.kind === 'array' ? spread.element : unknownType;
|
|
1254
|
+
}
|
|
1255
|
+
case 'Object':
|
|
1256
|
+
return {
|
|
1257
|
+
kind: 'object',
|
|
1258
|
+
fields: new Map(expression.properties.filter(property => property.accessor !== 'set').map(property => [
|
|
1259
|
+
property.key,
|
|
1260
|
+
property.accessor === 'get' && property.value.kind === 'Function'
|
|
1261
|
+
? property.value.returnType ? typeFromNode(property.value.returnType) : inferFunctionReturnType(property.value.body, variables)
|
|
1262
|
+
: inferExpressionType(property.value, variables)
|
|
1263
|
+
]))
|
|
1264
|
+
};
|
|
1265
|
+
case 'Unary':
|
|
1266
|
+
if (expression.operator === '-' && expression.operand.kind === 'Literal' && typeof expression.operand.value === 'number')
|
|
1267
|
+
return { kind: 'literal', value: -expression.operand.value };
|
|
1268
|
+
return inferExpressionType(expression.operand, variables);
|
|
1269
|
+
case 'Conditional':
|
|
1270
|
+
return commonType([inferExpressionType(expression.consequent, variables), inferExpressionType(expression.alternate, variables)]);
|
|
1271
|
+
case 'Match': {
|
|
1272
|
+
const results = expression.cases.map(item => inferFunctionReturnType(item.body, new Map(variables)));
|
|
1273
|
+
if (!expression.cases.some(item => !item.pattern))
|
|
1274
|
+
results.push(primitive('null'));
|
|
1275
|
+
return commonType(results);
|
|
1276
|
+
}
|
|
1277
|
+
case 'Try': {
|
|
1278
|
+
const results = expression.catches.map(item => inferFunctionReturnType(item.body, new Map(variables)));
|
|
1279
|
+
return results.length ? commonType(results) : unknownType;
|
|
1280
|
+
}
|
|
1281
|
+
case 'Is': return primitive('boolean');
|
|
1282
|
+
case 'Member': {
|
|
1283
|
+
const object = inferExpressionType(expression.object, variables);
|
|
1284
|
+
return object.kind === 'object' ? object.fields.get(expression.property) ?? unknownType : unknownType;
|
|
1285
|
+
}
|
|
1286
|
+
case 'Index': {
|
|
1287
|
+
const object = inferExpressionType(expression.object, variables);
|
|
1288
|
+
const index = inferExpressionType(expression.index, variables);
|
|
1289
|
+
if (object.kind === 'array')
|
|
1290
|
+
return object.element;
|
|
1291
|
+
if (object.kind === 'object' && index.kind === 'primitive' && (index.name === 'string' || index.name === 'number')) {
|
|
1292
|
+
if (expression.index.kind === 'Literal')
|
|
1293
|
+
return object.fields.get(String(expression.index.value)) ?? unknownType;
|
|
1294
|
+
return object.fields.size ? commonType([...object.fields.values()]) : unknownType;
|
|
1295
|
+
}
|
|
1296
|
+
return unknownType;
|
|
1297
|
+
}
|
|
1298
|
+
case 'Binary': {
|
|
1299
|
+
const left = inferExpressionType(expression.left, variables);
|
|
1300
|
+
const right = inferExpressionType(expression.right, variables);
|
|
1301
|
+
const operator = expression.operator;
|
|
1302
|
+
if (operator === '??')
|
|
1303
|
+
return left.kind === 'primitive' && left.name === 'null' ? right : left;
|
|
1304
|
+
if (operator === '&' || operator === '|')
|
|
1305
|
+
return primitive('boolean');
|
|
1306
|
+
if (left.kind !== 'primitive' || right.kind !== 'primitive')
|
|
1307
|
+
return unknownType;
|
|
1308
|
+
const leftName = left.name, rightName = right.name;
|
|
1309
|
+
if (operator === '+') {
|
|
1310
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1311
|
+
(leftName === 'string' && rightName === 'string') ||
|
|
1312
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1313
|
+
if (!allowed) {
|
|
1314
|
+
throw new SyntaxError(`Invalid operands for '+': ${leftName} and ${rightName}. ` +
|
|
1315
|
+
`Use number + number, string + string, or BigInt + BigInt.`);
|
|
1316
|
+
}
|
|
1317
|
+
return left;
|
|
1318
|
+
}
|
|
1319
|
+
if (operator === '*' || operator === '/') {
|
|
1320
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1321
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1322
|
+
if (!allowed) {
|
|
1323
|
+
throw new SyntaxError(`Invalid operands for '${operator}': ${leftName} and ${rightName}. ` +
|
|
1324
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1325
|
+
}
|
|
1326
|
+
return left;
|
|
1327
|
+
}
|
|
1328
|
+
if (operator === '-') {
|
|
1329
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1330
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1331
|
+
if (!allowed) {
|
|
1332
|
+
throw new SyntaxError(`Invalid operands for '-': ${leftName} and ${rightName}. ` +
|
|
1333
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1334
|
+
}
|
|
1335
|
+
return left;
|
|
1336
|
+
}
|
|
1337
|
+
if (operator === '<') {
|
|
1338
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1339
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1340
|
+
if (!allowed) {
|
|
1341
|
+
throw new SyntaxError(`Invalid operands for '<': ${leftName} and ${rightName}. ` +
|
|
1342
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1343
|
+
}
|
|
1344
|
+
return primitive('boolean');
|
|
1345
|
+
}
|
|
1346
|
+
if (operator === '>') {
|
|
1347
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1348
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1349
|
+
if (!allowed) {
|
|
1350
|
+
throw new SyntaxError(`Invalid operands for '>': ${leftName} and ${rightName}. ` +
|
|
1351
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1352
|
+
}
|
|
1353
|
+
return primitive('boolean');
|
|
1354
|
+
}
|
|
1355
|
+
if (operator === '<=') {
|
|
1356
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1357
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1358
|
+
if (!allowed) {
|
|
1359
|
+
throw new SyntaxError(`Invalid operands for '<=': ${leftName} and ${rightName}. ` +
|
|
1360
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1361
|
+
}
|
|
1362
|
+
return primitive('boolean');
|
|
1363
|
+
}
|
|
1364
|
+
if (operator === '>=') {
|
|
1365
|
+
const allowed = (leftName === 'number' && rightName === 'number') ||
|
|
1366
|
+
(leftName === 'BigInt' && rightName === 'BigInt');
|
|
1367
|
+
if (!allowed) {
|
|
1368
|
+
throw new SyntaxError(`Invalid operands for '>=': ${leftName} and ${rightName}. ` +
|
|
1369
|
+
`Both operands must be number or both must be BigInt.`);
|
|
1370
|
+
}
|
|
1371
|
+
return primitive('boolean');
|
|
1372
|
+
}
|
|
1373
|
+
return unknownType;
|
|
1374
|
+
}
|
|
1375
|
+
case 'Assignment':
|
|
1376
|
+
return unknownType;
|
|
1377
|
+
case 'MemberAssignment':
|
|
1378
|
+
return unknownType;
|
|
1379
|
+
case 'Function': {
|
|
1380
|
+
const scope = new Map(variables);
|
|
1381
|
+
for (const param of expression.params) {
|
|
1382
|
+
const declared = param.type ? typeFromNode(param.type) : undefined;
|
|
1383
|
+
const inferred = param.defaultValue ? inferExpressionType(param.defaultValue, scope) : unknownType;
|
|
1384
|
+
const parameterType = declared ?? (param.rest ? { kind: 'array', element: inferred } : inferred);
|
|
1385
|
+
scope.set(param.name, parameterType);
|
|
1386
|
+
}
|
|
1387
|
+
const result = expression.returnType
|
|
1388
|
+
? typeFromNode(expression.returnType)
|
|
1389
|
+
: expression.expressionBody
|
|
1390
|
+
? inferExpressionType(expression.expressionBody, scope)
|
|
1391
|
+
: inferFunctionReturnType(expression.body, scope);
|
|
1392
|
+
return { kind: 'function', params: expression.params.map(param => ({
|
|
1393
|
+
type: param.type ? typeFromNode(param.type) : param.defaultValue ? inferExpressionType(param.defaultValue, scope) : unknownType,
|
|
1394
|
+
optional: param.defaultValue !== undefined,
|
|
1395
|
+
rest: param.rest === true
|
|
1396
|
+
})), result };
|
|
1397
|
+
}
|
|
1398
|
+
case 'Call': {
|
|
1399
|
+
const callee = inferExpressionType(expression.callee, variables);
|
|
1400
|
+
if (callee.kind !== 'function')
|
|
1401
|
+
return unknownType;
|
|
1402
|
+
if (callee.params) {
|
|
1403
|
+
const required = callee.params.filter(param => !param.optional && !param.rest).length;
|
|
1404
|
+
const rest = callee.params.some(param => param.rest);
|
|
1405
|
+
const maximum = rest ? Infinity : callee.params.length;
|
|
1406
|
+
const hasSpread = expression.args.some(argument => argument.kind === 'Spread');
|
|
1407
|
+
if (!hasSpread && (expression.args.length < required || expression.args.length > maximum)) {
|
|
1408
|
+
throw new SyntaxError(`Expected ${required}${maximum === required ? '' : ` to ${maximum === Infinity ? 'any number of' : maximum}`} arguments, received ${expression.args.length}`);
|
|
1409
|
+
}
|
|
1410
|
+
expression.args.forEach((argument, index) => {
|
|
1411
|
+
const parameter = callee.params.find((item, paramIndex) => item.rest ? index >= paramIndex : paramIndex === index);
|
|
1412
|
+
if (!parameter)
|
|
1413
|
+
return;
|
|
1414
|
+
const actual = inferExpressionType(argument, variables);
|
|
1415
|
+
if (!isAssignable(parameter.rest && parameter.type.kind === 'array' ? parameter.type.element : parameter.type, actual)) {
|
|
1416
|
+
throw new SyntaxError(`Argument ${index + 1} has type ${describeType(actual)}; expected ${describeType(parameter.rest && parameter.type.kind === 'array' ? parameter.type.element : parameter.type)}`);
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
}
|
|
1420
|
+
return callee.result ?? primitive('null');
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
function commonType(types) {
|
|
1425
|
+
const first = types[0] ?? unknownType;
|
|
1426
|
+
if (types.every(type => sameType(first, type)))
|
|
1427
|
+
return first;
|
|
1428
|
+
return unknownType;
|
|
1429
|
+
}
|
|
1430
|
+
function inferFunctionReturnType(statements, variables) {
|
|
1431
|
+
const returns = [];
|
|
1432
|
+
const collect = (body, scope) => {
|
|
1433
|
+
for (const statement of body) {
|
|
1434
|
+
if (statement.kind === 'Return')
|
|
1435
|
+
returns.push(statement.value ? inferExpressionType(statement.value, scope) : primitive('null'));
|
|
1436
|
+
else if (statement.kind === 'If') {
|
|
1437
|
+
collect(statement.consequent, new Map(scope));
|
|
1438
|
+
if (statement.alternate)
|
|
1439
|
+
collect(statement.alternate, new Map(scope));
|
|
1440
|
+
}
|
|
1441
|
+
else if (statement.kind === 'While' || statement.kind === 'ForOf') {
|
|
1442
|
+
collect(statement.body, new Map(scope));
|
|
1443
|
+
}
|
|
1444
|
+
else if (statement.kind === 'Variable' && statement.initializer) {
|
|
1445
|
+
scope.set(statement.name, statement.type ? typeFromNode(statement.type) : inferExpressionType(statement.initializer, scope));
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
};
|
|
1449
|
+
collect(statements, new Map(variables));
|
|
1450
|
+
return commonType(returns.length ? returns : [primitive('null')]);
|
|
1451
|
+
}
|
|
1452
|
+
function sameType(a, b) {
|
|
1453
|
+
if (a.kind !== b.kind)
|
|
1454
|
+
return false;
|
|
1455
|
+
if (a.kind === 'primitive' && b.kind === 'primitive')
|
|
1456
|
+
return a.name === b.name;
|
|
1457
|
+
if (a.kind === 'literal' && b.kind === 'literal')
|
|
1458
|
+
return a.value === b.value;
|
|
1459
|
+
if (a.kind === 'array' && b.kind === 'array')
|
|
1460
|
+
return sameType(a.element, b.element);
|
|
1461
|
+
if (a.kind === 'object' && b.kind === 'object') {
|
|
1462
|
+
return a.fields.size === b.fields.size && [...a.fields].every(([key, value]) => b.fields.has(key) && sameType(value, b.fields.get(key)));
|
|
1463
|
+
}
|
|
1464
|
+
return a.kind === 'function' || a.kind === 'unknown';
|
|
1465
|
+
}
|
|
1466
|
+
function typeFromNode(type, aliases = new Map(), resolving = new Set()) {
|
|
1467
|
+
if (type.kind === 'LiteralType')
|
|
1468
|
+
return { kind: 'literal', value: type.value };
|
|
1469
|
+
if (type.kind === 'NamedType') {
|
|
1470
|
+
if (type.name === 'any' || type.name === 'unknown')
|
|
1471
|
+
return unknownType;
|
|
1472
|
+
const alias = aliases.get(type.name);
|
|
1473
|
+
if (alias && !resolving.has(type.name)) {
|
|
1474
|
+
const next = new Set(resolving);
|
|
1475
|
+
next.add(type.name);
|
|
1476
|
+
return typeFromNode(alias, aliases, next);
|
|
1477
|
+
}
|
|
1478
|
+
return ['string', 'number', 'boolean', 'BigInt', 'null', 'void', 'never', 'RegEx'].includes(type.name)
|
|
1479
|
+
? primitive(type.name)
|
|
1480
|
+
: unknownType;
|
|
1481
|
+
}
|
|
1482
|
+
if (type.kind === 'ArrayType')
|
|
1483
|
+
return { kind: 'array', element: typeFromNode(type.element, aliases, resolving) };
|
|
1484
|
+
if (type.kind === 'TypeOfType')
|
|
1485
|
+
return unknownType;
|
|
1486
|
+
if (type.kind === 'IndexedAccessType') {
|
|
1487
|
+
const source = typeFromNode(type.object, aliases, resolving);
|
|
1488
|
+
const keys = type.index.kind === 'UnionType' ? type.index.types : [type.index];
|
|
1489
|
+
if (source.kind === 'array' && keys.every(key => key.kind === 'NamedType' && key.name === 'number' || key.kind === 'LiteralType' && typeof key.value === 'number'))
|
|
1490
|
+
return source.element;
|
|
1491
|
+
if (source.kind === 'object') {
|
|
1492
|
+
const selected = keys.flatMap(key => key.kind === 'LiteralType' && (typeof key.value === 'string' || typeof key.value === 'number') ? [source.fields.get(String(key.value))] : [])
|
|
1493
|
+
.filter((value) => Boolean(value));
|
|
1494
|
+
return selected.length === 1 ? selected[0] : selected.length ? { kind: 'union', types: selected } : unknownType;
|
|
1495
|
+
}
|
|
1496
|
+
return unknownType;
|
|
1497
|
+
}
|
|
1498
|
+
if (type.kind === 'GenericType' && (type.name === 'Array' || type.name === 'ReadonlyArray')) {
|
|
1499
|
+
return { kind: 'array', element: type.args[0] ? typeFromNode(type.args[0], aliases, resolving) : unknownType };
|
|
1500
|
+
}
|
|
1501
|
+
if (type.kind === 'GenericType' && ['Partial', 'Required', 'Readonly', 'Pick', 'Omit', 'KeyOf', 'Exclude'].includes(type.name) && type.args[0]) {
|
|
1502
|
+
if (type.name === 'Exclude') {
|
|
1503
|
+
const source = typeFromNode(type.args[0], aliases, resolving);
|
|
1504
|
+
const excluded = type.args[1] ? typeFromNode(type.args[1], aliases, resolving) : unknownType;
|
|
1505
|
+
const parts = source.kind === 'union' ? source.types : [source];
|
|
1506
|
+
const remaining = parts.filter(part => !isAssignable(excluded, part));
|
|
1507
|
+
return remaining.length === 1 ? remaining[0] : remaining.length ? { kind: 'union', types: remaining } : primitive('never');
|
|
1508
|
+
}
|
|
1509
|
+
const source = typeFromNode(type.args[0], aliases, resolving);
|
|
1510
|
+
if (type.name === 'KeyOf') {
|
|
1511
|
+
if (source.kind === 'array') {
|
|
1512
|
+
const names = ['length', 'indices', 'has', 'pick', 'omit', 'deepClone', 'deepFreeze', 'toDeepFreezed', 'at', 'concat', 'copy', 'copyWithin', 'entries', 'enumerate', 'every', 'fill', 'filter', 'find', 'findIndex', 'findLast', 'findLastIndex', 'flat', 'flatMap', 'forEach', 'includes', 'indexOf', 'iterator', 'join', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight', 'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'toArray', 'toReversed', 'toSorted', 'toSpliced', 'toString', 'unshift', 'with'];
|
|
1513
|
+
return { kind: 'union', types: [primitive('number'), ...names.map(value => ({ kind: 'literal', value }))] };
|
|
1514
|
+
}
|
|
1515
|
+
if (source.kind !== 'object')
|
|
1516
|
+
return unknownType;
|
|
1517
|
+
return { kind: 'union', types: [...source.fields.keys()].map(key => {
|
|
1518
|
+
const numeric = Number(key);
|
|
1519
|
+
return { kind: 'literal', value: key !== '' && Number.isFinite(numeric) && String(numeric) === key ? numeric : key };
|
|
1520
|
+
}) };
|
|
1521
|
+
}
|
|
1522
|
+
if (source.kind !== 'object')
|
|
1523
|
+
return unknownType;
|
|
1524
|
+
let fields = [...source.fields];
|
|
1525
|
+
if (type.name === 'Pick' || type.name === 'Omit') {
|
|
1526
|
+
const keyValues = (node) => {
|
|
1527
|
+
if (!node)
|
|
1528
|
+
return [];
|
|
1529
|
+
if (node.kind === 'LiteralType' && typeof node.value === 'string')
|
|
1530
|
+
return [node.value];
|
|
1531
|
+
if (node.kind === 'UnionType')
|
|
1532
|
+
return node.types.flatMap(keyValues);
|
|
1533
|
+
if (node.kind === 'ArrayType')
|
|
1534
|
+
return keyValues(node.element);
|
|
1535
|
+
return [];
|
|
1536
|
+
};
|
|
1537
|
+
const keys = new Set(keyValues(type.args[1]));
|
|
1538
|
+
fields = fields.filter(([key]) => type.name === 'Pick' ? keys.has(key) : !keys.has(key));
|
|
1539
|
+
}
|
|
1540
|
+
if (type.name === 'Partial')
|
|
1541
|
+
return { kind: 'object', fields: new Map() };
|
|
1542
|
+
return { kind: 'object', fields: new Map(fields) };
|
|
1543
|
+
}
|
|
1544
|
+
if (type.kind === 'ObjectType')
|
|
1545
|
+
return { kind: 'object', fields: new Map(type.members.filter(member => !member.indexType && (!member.method || member.accessor === 'get') && member.accessor !== 'set' && !member.optional && member.defaultValue === undefined && !(member.type.kind === 'UnionType' && member.type.types.some(part => part.kind === 'NamedType' && part.name === 'null'))).map(member => [member.name, typeFromNode(member.type, aliases, resolving)])) };
|
|
1546
|
+
if (type.kind === 'FunctionType')
|
|
1547
|
+
return { kind: 'function' };
|
|
1548
|
+
if (type.kind === 'UnionType')
|
|
1549
|
+
return { kind: 'union', types: type.types.map(part => typeFromNode(part, aliases, resolving)) };
|
|
1550
|
+
return unknownType;
|
|
1551
|
+
}
|
|
1552
|
+
function describeType(type) {
|
|
1553
|
+
if (type.kind === 'primitive')
|
|
1554
|
+
return type.name;
|
|
1555
|
+
if (type.kind === 'literal')
|
|
1556
|
+
return typeof type.value === 'string' ? JSON.stringify(type.value) : String(type.value);
|
|
1557
|
+
if (type.kind === 'union')
|
|
1558
|
+
return type.types.map(describeType).join(' | ');
|
|
1559
|
+
if (type.kind === 'array')
|
|
1560
|
+
return `${describeType(type.element)}[]`;
|
|
1561
|
+
if (type.kind === 'object')
|
|
1562
|
+
return `{ ${[...type.fields].map(([key, value]) => `${key}: ${describeType(value)}`).join(', ')} }`;
|
|
1563
|
+
return type.kind;
|
|
1564
|
+
}
|
|
1565
|
+
function isAssignable(expected, actual) {
|
|
1566
|
+
if (expected.kind === 'unknown' || actual.kind === 'unknown')
|
|
1567
|
+
return true;
|
|
1568
|
+
if (expected.kind === 'function' && actual.kind === 'object')
|
|
1569
|
+
return actual.fields.get('')?.kind === 'function';
|
|
1570
|
+
if (expected.kind === 'union')
|
|
1571
|
+
return actual.kind === 'union'
|
|
1572
|
+
? actual.types.every(part => expected.types.some(option => isAssignable(option, part)))
|
|
1573
|
+
: expected.types.some(option => isAssignable(option, actual));
|
|
1574
|
+
if (actual.kind === 'union')
|
|
1575
|
+
return actual.types.every(part => isAssignable(expected, part));
|
|
1576
|
+
if (expected.kind === 'literal') {
|
|
1577
|
+
if (actual.kind === 'literal')
|
|
1578
|
+
return expected.value === actual.value;
|
|
1579
|
+
if (actual.kind === 'primitive')
|
|
1580
|
+
return actual.name === typeof expected.value;
|
|
1581
|
+
return false;
|
|
1582
|
+
}
|
|
1583
|
+
if (actual.kind === 'literal' && expected.kind === 'primitive')
|
|
1584
|
+
return expected.name === typeof actual.value;
|
|
1585
|
+
if (expected.kind !== actual.kind)
|
|
1586
|
+
return false;
|
|
1587
|
+
if (expected.kind === 'primitive' && actual.kind === 'primitive')
|
|
1588
|
+
return expected.name === actual.name;
|
|
1589
|
+
if (expected.kind === 'array' && actual.kind === 'array')
|
|
1590
|
+
return isAssignable(expected.element, actual.element);
|
|
1591
|
+
if (expected.kind === 'object' && actual.kind === 'object') {
|
|
1592
|
+
return [...expected.fields].every(([key, type]) => actual.fields.has(key) && isAssignable(type, actual.fields.get(key)));
|
|
1593
|
+
}
|
|
1594
|
+
return true;
|
|
1595
|
+
}
|
|
1596
|
+
function validateArithmeticTypes(statements, variables = new Map()) {
|
|
1597
|
+
const aliases = new Map();
|
|
1598
|
+
for (const statement of statements) {
|
|
1599
|
+
if (statement.kind === 'TypeDeclaration')
|
|
1600
|
+
aliases.set(statement.name, statement.value);
|
|
1601
|
+
if (statement.kind === 'Export' && statement.declaration.kind === 'TypeDeclaration')
|
|
1602
|
+
aliases.set(statement.declaration.name, statement.declaration.value);
|
|
1603
|
+
if (statement.kind === 'Import' && statement.importedTypes)
|
|
1604
|
+
for (const [name, value] of Object.entries(statement.importedTypes))
|
|
1605
|
+
aliases.set(name, value);
|
|
1606
|
+
}
|
|
1607
|
+
for (const statement of statements)
|
|
1608
|
+
if (statement.kind === 'Import' && !statement.importedTypes) {
|
|
1609
|
+
try {
|
|
1610
|
+
const { readFileSync } = require('node:fs');
|
|
1611
|
+
const { resolve, dirname } = require('node:path');
|
|
1612
|
+
if (statement.module.startsWith('.')) {
|
|
1613
|
+
const base = resolve(process.cwd(), statement.module);
|
|
1614
|
+
const file = /\.jn$/i.test(base) ? base : `${base}.jn`;
|
|
1615
|
+
const imported = new Parser((0, lexer_1.Lexer)(readFileSync(file, 'utf8')).tokenize()).parse();
|
|
1616
|
+
for (const item of imported)
|
|
1617
|
+
if (item.kind === 'Export' && item.declaration.kind === 'TypeDeclaration')
|
|
1618
|
+
aliases.set(item.declaration.name, item.declaration.value);
|
|
1619
|
+
}
|
|
1620
|
+
else if (statement.module === 'juno' && statement.namedImports.includes('Error')) {
|
|
1621
|
+
aliases.set('Error', { kind: 'ObjectType', members: [
|
|
1622
|
+
{ name: 'name', type: { kind: 'NamedType', name: 'string' }, optional: false, readonly: false, constant: false },
|
|
1623
|
+
{ name: 'message', type: { kind: 'NamedType', name: 'string' }, optional: false, readonly: false, constant: false },
|
|
1624
|
+
{ name: 'stack', type: { kind: 'NamedType', name: 'string' }, optional: true, readonly: false, constant: false }
|
|
1625
|
+
] });
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
catch { /* unresolved modules are reported by the interpreter */ }
|
|
1629
|
+
}
|
|
1630
|
+
for (const statement of statements) {
|
|
1631
|
+
switch (statement.kind) {
|
|
1632
|
+
case 'Variable': {
|
|
1633
|
+
const declaredType = statement.type ? typeFromNode(statement.type, aliases) : undefined;
|
|
1634
|
+
const inferredType = statement.initializer
|
|
1635
|
+
? inferExpressionType(statement.initializer, variables)
|
|
1636
|
+
: undefined;
|
|
1637
|
+
const type = declaredType ?? inferredType;
|
|
1638
|
+
if (type)
|
|
1639
|
+
variables.set(statement.name, type);
|
|
1640
|
+
if (statement.initializer) {
|
|
1641
|
+
const actual = inferExpressionType(statement.initializer, variables);
|
|
1642
|
+
if (declaredType && !isAssignable(declaredType, actual)) {
|
|
1643
|
+
throw new SyntaxError(`Cannot assign ${describeType(actual)} to ${describeType(declaredType)} for '${statement.name}'`);
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
break;
|
|
1647
|
+
}
|
|
1648
|
+
case 'ExpressionStatement':
|
|
1649
|
+
inferExpressionType(statement.expression, variables);
|
|
1650
|
+
break;
|
|
1651
|
+
case 'Return':
|
|
1652
|
+
if (statement.value)
|
|
1653
|
+
inferExpressionType(statement.value, variables);
|
|
1654
|
+
break;
|
|
1655
|
+
case 'If':
|
|
1656
|
+
inferExpressionType(statement.condition, variables);
|
|
1657
|
+
validateArithmeticTypes(statement.consequent, new Map(variables));
|
|
1658
|
+
if (statement.alternate) {
|
|
1659
|
+
validateArithmeticTypes(statement.alternate, new Map(variables));
|
|
1660
|
+
}
|
|
1661
|
+
break;
|
|
1662
|
+
case 'While':
|
|
1663
|
+
inferExpressionType(statement.condition, variables);
|
|
1664
|
+
validateArithmeticTypes(statement.body, new Map(variables));
|
|
1665
|
+
break;
|
|
1666
|
+
case 'ForOf':
|
|
1667
|
+
inferExpressionType(statement.iterable, variables);
|
|
1668
|
+
validateArithmeticTypes(statement.body, new Map(variables));
|
|
1669
|
+
break;
|
|
1670
|
+
case 'FunctionDeclaration':
|
|
1671
|
+
{
|
|
1672
|
+
const scope = new Map(variables);
|
|
1673
|
+
const functionAliases = new Map(aliases);
|
|
1674
|
+
for (const generic of statement.generics ?? [])
|
|
1675
|
+
functionAliases.set(generic, { kind: 'NamedType', name: 'any' });
|
|
1676
|
+
const params = statement.params.map(param => {
|
|
1677
|
+
const declared = param.type ? typeFromNode(param.type, functionAliases) : undefined;
|
|
1678
|
+
const inferred = param.defaultValue ? inferExpressionType(param.defaultValue, scope) : unknownType;
|
|
1679
|
+
const type = declared ?? (param.rest ? { kind: 'array', element: inferred } : inferred);
|
|
1680
|
+
scope.set(param.name, type);
|
|
1681
|
+
return { type: param.rest && type.kind !== 'array' ? unknownType : type, optional: param.defaultValue !== undefined, rest: param.rest === true };
|
|
1682
|
+
});
|
|
1683
|
+
validateArithmeticTypes(statement.body, scope);
|
|
1684
|
+
const result = statement.returnType
|
|
1685
|
+
? typeFromNode(statement.returnType, functionAliases)
|
|
1686
|
+
: inferFunctionReturnType(statement.body, scope);
|
|
1687
|
+
variables.set(statement.name, { kind: 'function', params, result });
|
|
1688
|
+
}
|
|
1689
|
+
break;
|
|
1690
|
+
case 'Import':
|
|
1691
|
+
case 'TypeDeclaration':
|
|
1692
|
+
break;
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
function parse(source, options = {}) {
|
|
1697
|
+
const statements = new Parser((0, lexer_1.Lexer)(source).tokenize()).parse();
|
|
1698
|
+
const types = new Map();
|
|
1699
|
+
const visit = (items, seen = new Set()) => {
|
|
1700
|
+
for (const item of items) {
|
|
1701
|
+
if (item.kind === 'Export' && item.declaration.kind === 'TypeDeclaration')
|
|
1702
|
+
types.set(item.declaration.name, item.declaration.value);
|
|
1703
|
+
if (item.kind === 'TypeDeclaration')
|
|
1704
|
+
types.set(item.name, item.value);
|
|
1705
|
+
if (item.kind === 'Import' && item.module.startsWith('.')) {
|
|
1706
|
+
try {
|
|
1707
|
+
const fs = require('node:fs');
|
|
1708
|
+
const path = require('node:path');
|
|
1709
|
+
const base = path.resolve(options.filePath ? path.dirname(options.filePath) : process.cwd(), item.module);
|
|
1710
|
+
const candidates = /\.jn$/i.test(base) ? [base] : [`${base}.jn`, path.resolve(base, 'index.jn')];
|
|
1711
|
+
const file = candidates.find(candidate => fs.existsSync(candidate));
|
|
1712
|
+
if (!file || seen.has(file))
|
|
1713
|
+
continue;
|
|
1714
|
+
const nested = visitParsed(file, seen);
|
|
1715
|
+
for (const [name, value] of nested)
|
|
1716
|
+
if (item.namedImports.includes(name))
|
|
1717
|
+
types.set(name, value);
|
|
1718
|
+
}
|
|
1719
|
+
catch { /* module loading diagnostics are handled separately */ }
|
|
1720
|
+
}
|
|
1721
|
+
if (item.kind === 'Export' && item.declaration.kind === 'Import')
|
|
1722
|
+
visit([item.declaration], seen);
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
const visitParsed = (file, seen) => {
|
|
1726
|
+
seen.add(file);
|
|
1727
|
+
const nested = new Map();
|
|
1728
|
+
const parsed = new Parser((0, lexer_1.Lexer)(require('node:fs').readFileSync(file, 'utf8')).tokenize()).parse();
|
|
1729
|
+
for (const item of parsed) {
|
|
1730
|
+
if (item.kind === 'Export' && item.declaration.kind === 'TypeDeclaration')
|
|
1731
|
+
nested.set(item.declaration.name, item.declaration.value);
|
|
1732
|
+
else if (item.kind === 'TypeDeclaration')
|
|
1733
|
+
nested.set(item.name, item.value);
|
|
1734
|
+
else if (item.kind === 'Export' && item.declaration.kind === 'Import' && item.declaration.importedTypes)
|
|
1735
|
+
for (const [name, value] of Object.entries(item.declaration.importedTypes))
|
|
1736
|
+
nested.set(name, value);
|
|
1737
|
+
}
|
|
1738
|
+
return nested;
|
|
1739
|
+
};
|
|
1740
|
+
visit(statements);
|
|
1741
|
+
for (const item of statements)
|
|
1742
|
+
if (item.kind === 'Import' && item.module === 'juno' && item.namedImports.includes('Error'))
|
|
1743
|
+
types.set('Error', { kind: 'ObjectType', members: [
|
|
1744
|
+
{ name: 'name', type: { kind: 'NamedType', name: 'string' }, optional: false, readonly: false, constant: false },
|
|
1745
|
+
{ name: 'message', type: { kind: 'NamedType', name: 'string' }, optional: false, readonly: false, constant: false },
|
|
1746
|
+
{ name: 'stack', type: { kind: 'NamedType', name: 'string' }, optional: true, readonly: false, constant: false }
|
|
1747
|
+
] });
|
|
1748
|
+
for (const item of statements)
|
|
1749
|
+
if (item.kind === 'Import') {
|
|
1750
|
+
item.importedTypes = Object.fromEntries([...types].filter(([name]) => item.namedImports.includes(name)));
|
|
1751
|
+
}
|
|
1752
|
+
if (options.validate !== false) {
|
|
1753
|
+
validateBreakStatements(statements);
|
|
1754
|
+
validateDeclarations(statements);
|
|
1755
|
+
validateArithmeticTypes(statements);
|
|
1756
|
+
}
|
|
1757
|
+
return statements;
|
|
1758
|
+
}
|
|
1759
|
+
function validateBreakStatements(statements, loopDepth = 0) {
|
|
1760
|
+
for (const statement of statements) {
|
|
1761
|
+
if (statement.kind === 'Break') {
|
|
1762
|
+
if (loopDepth === 0)
|
|
1763
|
+
throw new SyntaxError(`'break' is only valid inside a loop at ${statement.loc?.line ?? 1}:${statement.loc?.column ?? 1}`);
|
|
1764
|
+
}
|
|
1765
|
+
else if (statement.kind === 'While' || statement.kind === 'ForOf') {
|
|
1766
|
+
validateBreakStatements(statement.body, loopDepth + 1);
|
|
1767
|
+
}
|
|
1768
|
+
else if (statement.kind === 'If') {
|
|
1769
|
+
validateBreakStatements(statement.consequent, loopDepth);
|
|
1770
|
+
if (statement.alternate)
|
|
1771
|
+
validateBreakStatements(statement.alternate, loopDepth);
|
|
1772
|
+
}
|
|
1773
|
+
else if (statement.kind === 'FunctionDeclaration') {
|
|
1774
|
+
validateBreakStatements(statement.body, 0);
|
|
1775
|
+
}
|
|
1776
|
+
else if (statement.kind === 'ConstructorDeclaration') {
|
|
1777
|
+
for (const overload of statement.overloads)
|
|
1778
|
+
validateBreakStatements(overload.body, 0);
|
|
1779
|
+
for (const method of statement.methods)
|
|
1780
|
+
validateBreakStatements(method.body, 0);
|
|
1781
|
+
}
|
|
1782
|
+
else if (statement.kind === 'Export') {
|
|
1783
|
+
validateBreakStatements([statement.declaration], loopDepth);
|
|
1784
|
+
}
|
|
1785
|
+
else if (statement.kind === 'Variable' && statement.initializer) {
|
|
1786
|
+
validateBreakExpression(statement.initializer, loopDepth);
|
|
1787
|
+
}
|
|
1788
|
+
else if (statement.kind === 'Destructure' || statement.kind === 'ArrayDestructure') {
|
|
1789
|
+
validateBreakExpression(statement.initializer, loopDepth);
|
|
1790
|
+
}
|
|
1791
|
+
else if (statement.kind === 'ExpressionStatement') {
|
|
1792
|
+
validateBreakExpression(statement.expression, loopDepth);
|
|
1793
|
+
}
|
|
1794
|
+
else if (statement.kind === 'Return' && statement.value) {
|
|
1795
|
+
validateBreakExpression(statement.value, loopDepth);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
function validateBreakExpression(expression, loopDepth) {
|
|
1800
|
+
if (expression.kind === 'Match') {
|
|
1801
|
+
validateBreakExpression(expression.value, loopDepth);
|
|
1802
|
+
for (const item of expression.cases) {
|
|
1803
|
+
if (item.guard)
|
|
1804
|
+
validateBreakExpression(item.guard, loopDepth);
|
|
1805
|
+
validateBreakStatements(item.body, loopDepth);
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
else if (expression.kind === 'Function') {
|
|
1809
|
+
validateBreakStatements(expression.body, 0);
|
|
1810
|
+
if (expression.expressionBody)
|
|
1811
|
+
validateBreakExpression(expression.expressionBody, 0);
|
|
1812
|
+
}
|
|
1813
|
+
else if (expression.kind === 'Array')
|
|
1814
|
+
expression.elements.forEach(item => validateBreakExpression(item, loopDepth));
|
|
1815
|
+
else if (expression.kind === 'Object')
|
|
1816
|
+
expression.properties.forEach(item => validateBreakExpression(item.value, loopDepth));
|
|
1817
|
+
else if (expression.kind === 'Spread')
|
|
1818
|
+
validateBreakExpression(expression.value, loopDepth);
|
|
1819
|
+
else if (expression.kind === 'Template')
|
|
1820
|
+
expression.parts.forEach(item => { if (typeof item !== 'string')
|
|
1821
|
+
validateBreakExpression(item, loopDepth); });
|
|
1822
|
+
else if (expression.kind === 'Unary')
|
|
1823
|
+
validateBreakExpression(expression.operand, loopDepth);
|
|
1824
|
+
else if (expression.kind === 'Assignment')
|
|
1825
|
+
validateBreakExpression(expression.value, loopDepth);
|
|
1826
|
+
else if (expression.kind === 'MemberAssignment') {
|
|
1827
|
+
validateBreakExpression(expression.object, loopDepth);
|
|
1828
|
+
if (expression.index)
|
|
1829
|
+
validateBreakExpression(expression.index, loopDepth);
|
|
1830
|
+
validateBreakExpression(expression.value, loopDepth);
|
|
1831
|
+
}
|
|
1832
|
+
else if (expression.kind === 'Binary') {
|
|
1833
|
+
validateBreakExpression(expression.left, loopDepth);
|
|
1834
|
+
validateBreakExpression(expression.right, loopDepth);
|
|
1835
|
+
}
|
|
1836
|
+
else if (expression.kind === 'Conditional') {
|
|
1837
|
+
validateBreakExpression(expression.condition, loopDepth);
|
|
1838
|
+
validateBreakExpression(expression.consequent, loopDepth);
|
|
1839
|
+
validateBreakExpression(expression.alternate, loopDepth);
|
|
1840
|
+
}
|
|
1841
|
+
else if (expression.kind === 'Is')
|
|
1842
|
+
validateBreakExpression(expression.value, loopDepth);
|
|
1843
|
+
else if (expression.kind === 'Member')
|
|
1844
|
+
validateBreakExpression(expression.object, loopDepth);
|
|
1845
|
+
else if (expression.kind === 'Index') {
|
|
1846
|
+
validateBreakExpression(expression.object, loopDepth);
|
|
1847
|
+
validateBreakExpression(expression.index, loopDepth);
|
|
1848
|
+
}
|
|
1849
|
+
else if (expression.kind === 'Call') {
|
|
1850
|
+
validateBreakExpression(expression.callee, loopDepth);
|
|
1851
|
+
expression.args.forEach(item => validateBreakExpression(item, loopDepth));
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
function validateDeclarations(statements, initialNames = new Set()) {
|
|
1855
|
+
const names = new Set(initialNames);
|
|
1856
|
+
for (const statement of statements) {
|
|
1857
|
+
const declarations = [];
|
|
1858
|
+
if (statement.kind === 'Import')
|
|
1859
|
+
declarations.push(...(statement.defaultImport ? [statement.defaultImport] : []), ...statement.namedImports);
|
|
1860
|
+
else if (statement.kind === 'Variable' || statement.kind === 'FunctionDeclaration' || statement.kind === 'TypeDeclaration')
|
|
1861
|
+
declarations.push(statement.name);
|
|
1862
|
+
else if (statement.kind === 'Destructure' || statement.kind === 'ArrayDestructure')
|
|
1863
|
+
declarations.push(...statement.bindings.flatMap(binding => binding.name && binding.name !== '_' ? [binding.name] : []));
|
|
1864
|
+
for (const name of declarations) {
|
|
1865
|
+
if (names.has(name))
|
|
1866
|
+
throw new SyntaxError(`Duplicate declaration '${name}' in the same scope`);
|
|
1867
|
+
names.add(name);
|
|
1868
|
+
}
|
|
1869
|
+
if (statement.kind === 'If') {
|
|
1870
|
+
validateDeclarations(statement.consequent);
|
|
1871
|
+
if (statement.alternate)
|
|
1872
|
+
validateDeclarations(statement.alternate);
|
|
1873
|
+
}
|
|
1874
|
+
else if (statement.kind === 'While' || statement.kind === 'ForOf')
|
|
1875
|
+
validateDeclarations(statement.body);
|
|
1876
|
+
else if (statement.kind === 'FunctionDeclaration') {
|
|
1877
|
+
const functionNames = new Set(statement.params.map(param => param.name));
|
|
1878
|
+
validateDeclarations(statement.body, functionNames);
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|