goscript 0.0.22 → 0.0.24
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/README.md +1 -1
- package/cmd/goscript/cmd_compile.go +3 -3
- package/compiler/analysis.go +302 -182
- package/compiler/analysis_test.go +220 -0
- package/compiler/assignment.go +42 -43
- package/compiler/builtin_test.go +102 -0
- package/compiler/compiler.go +117 -29
- package/compiler/compiler_test.go +36 -8
- package/compiler/composite-lit.go +133 -53
- package/compiler/config.go +7 -3
- package/compiler/config_test.go +6 -33
- package/compiler/decl.go +36 -0
- package/compiler/expr-call.go +116 -60
- package/compiler/expr-selector.go +88 -43
- package/compiler/expr-star.go +57 -65
- package/compiler/expr-type.go +132 -5
- package/compiler/expr-value.go +8 -38
- package/compiler/expr.go +326 -30
- package/compiler/field.go +3 -3
- package/compiler/lit.go +34 -2
- package/compiler/primitive.go +19 -12
- package/compiler/spec-struct.go +140 -9
- package/compiler/spec-value.go +119 -41
- package/compiler/spec.go +21 -6
- package/compiler/stmt-assign.go +65 -3
- package/compiler/stmt-for.go +11 -0
- package/compiler/stmt-range.go +119 -11
- package/compiler/stmt-select.go +211 -0
- package/compiler/stmt-type-switch.go +147 -0
- package/compiler/stmt.go +175 -238
- package/compiler/type-assert.go +125 -379
- package/compiler/type.go +216 -129
- package/dist/gs/builtin/builtin.js +37 -0
- package/dist/gs/builtin/builtin.js.map +1 -0
- package/dist/gs/builtin/channel.js +471 -0
- package/dist/gs/builtin/channel.js.map +1 -0
- package/dist/gs/builtin/defer.js +54 -0
- package/dist/gs/builtin/defer.js.map +1 -0
- package/dist/gs/builtin/io.js +15 -0
- package/dist/gs/builtin/io.js.map +1 -0
- package/dist/gs/builtin/map.js +44 -0
- package/dist/gs/builtin/map.js.map +1 -0
- package/dist/gs/builtin/slice.js +799 -0
- package/dist/gs/builtin/slice.js.map +1 -0
- package/dist/gs/builtin/type.js +745 -0
- package/dist/gs/builtin/type.js.map +1 -0
- package/dist/gs/builtin/varRef.js +14 -0
- package/dist/gs/builtin/varRef.js.map +1 -0
- package/dist/gs/context/context.js +55 -0
- package/dist/gs/context/context.js.map +1 -0
- package/dist/gs/context/index.js +2 -0
- package/dist/gs/context/index.js.map +1 -0
- package/dist/gs/runtime/index.js +2 -0
- package/dist/gs/runtime/index.js.map +1 -0
- package/dist/gs/runtime/runtime.js +158 -0
- package/dist/gs/runtime/runtime.js.map +1 -0
- package/dist/gs/time/index.js +2 -0
- package/dist/gs/time/index.js.map +1 -0
- package/dist/gs/time/time.js +115 -0
- package/dist/gs/time/time.js.map +1 -0
- package/package.json +7 -6
- package/builtin/builtin.go +0 -11
- package/builtin/builtin.ts +0 -2379
- package/dist/builtin/builtin.d.ts +0 -513
- package/dist/builtin/builtin.js +0 -1686
- package/dist/builtin/builtin.js.map +0 -1
package/dist/builtin/builtin.js
DELETED
|
@@ -1,1686 +0,0 @@
|
|
|
1
|
-
export function asArray(slice) {
|
|
2
|
-
return slice;
|
|
3
|
-
}
|
|
4
|
-
/**
|
|
5
|
-
* isComplexSlice checks if a slice is a complex slice (has __meta__ property)
|
|
6
|
-
*/
|
|
7
|
-
function isComplexSlice(slice) {
|
|
8
|
-
return (slice !== null &&
|
|
9
|
-
slice !== undefined &&
|
|
10
|
-
'__meta__' in slice &&
|
|
11
|
-
slice.__meta__ !== undefined);
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
|
-
* Creates a new slice with the specified length and capacity.
|
|
15
|
-
* @param length The length of the slice.
|
|
16
|
-
* @param capacity The capacity of the slice (optional).
|
|
17
|
-
* @returns A new slice.
|
|
18
|
-
*/
|
|
19
|
-
export const makeSlice = (length, capacity) => {
|
|
20
|
-
if (capacity === undefined) {
|
|
21
|
-
capacity = length;
|
|
22
|
-
}
|
|
23
|
-
if (length < 0 || capacity < 0 || length > capacity) {
|
|
24
|
-
throw new Error(`Invalid slice length (${length}) or capacity (${capacity})`);
|
|
25
|
-
}
|
|
26
|
-
const arr = new Array(length);
|
|
27
|
-
// Always create a complex slice with metadata to preserve capacity information
|
|
28
|
-
const proxy = arr;
|
|
29
|
-
proxy.__meta__ = {
|
|
30
|
-
backing: new Array(capacity),
|
|
31
|
-
offset: 0,
|
|
32
|
-
length: length,
|
|
33
|
-
capacity: capacity,
|
|
34
|
-
};
|
|
35
|
-
for (let i = 0; i < length; i++) {
|
|
36
|
-
proxy.__meta__.backing[i] = arr[i];
|
|
37
|
-
}
|
|
38
|
-
return proxy;
|
|
39
|
-
};
|
|
40
|
-
/**
|
|
41
|
-
* goSlice creates a slice from s[low:high:max]
|
|
42
|
-
* Arguments mirror Go semantics; omitted indices are undefined.
|
|
43
|
-
*
|
|
44
|
-
* @param s The original slice
|
|
45
|
-
* @param low Starting index (defaults to 0)
|
|
46
|
-
* @param high Ending index (defaults to s.length)
|
|
47
|
-
* @param max Capacity limit (defaults to original capacity)
|
|
48
|
-
*/
|
|
49
|
-
export const goSlice = (s, low, high, max) => {
|
|
50
|
-
if (s === null || s === undefined) {
|
|
51
|
-
throw new Error('Cannot slice nil');
|
|
52
|
-
}
|
|
53
|
-
const slen = len(s);
|
|
54
|
-
low = low ?? 0;
|
|
55
|
-
high = high ?? slen;
|
|
56
|
-
if (low < 0 || high < low) {
|
|
57
|
-
throw new Error(`Invalid slice indices: ${low}:${high}`);
|
|
58
|
-
}
|
|
59
|
-
// In Go, high can be up to capacity, not just length
|
|
60
|
-
const scap = cap(s);
|
|
61
|
-
if (high > scap) {
|
|
62
|
-
throw new Error(`Slice index out of range: ${high} > ${scap}`);
|
|
63
|
-
}
|
|
64
|
-
if (Array.isArray(s) &&
|
|
65
|
-
!isComplexSlice(s) &&
|
|
66
|
-
low === 0 &&
|
|
67
|
-
high === s.length &&
|
|
68
|
-
max === undefined) {
|
|
69
|
-
return s;
|
|
70
|
-
}
|
|
71
|
-
let backing;
|
|
72
|
-
let oldOffset = 0;
|
|
73
|
-
let oldCap = scap;
|
|
74
|
-
// Get the backing array and offset
|
|
75
|
-
if (isComplexSlice(s)) {
|
|
76
|
-
backing = s.__meta__.backing;
|
|
77
|
-
oldOffset = s.__meta__.offset;
|
|
78
|
-
oldCap = s.__meta__.capacity;
|
|
79
|
-
}
|
|
80
|
-
else {
|
|
81
|
-
backing = s;
|
|
82
|
-
}
|
|
83
|
-
let newCap;
|
|
84
|
-
if (max !== undefined) {
|
|
85
|
-
if (max < high) {
|
|
86
|
-
throw new Error(`Invalid slice indices: ${low}:${high}:${max}`);
|
|
87
|
-
}
|
|
88
|
-
if (isComplexSlice(s) && max > oldOffset + oldCap) {
|
|
89
|
-
throw new Error(`Slice index out of range: ${max} > ${oldOffset + oldCap}`);
|
|
90
|
-
}
|
|
91
|
-
if (!isComplexSlice(s) && max > s.length) {
|
|
92
|
-
throw new Error(`Slice index out of range: ${max} > ${s.length}`);
|
|
93
|
-
}
|
|
94
|
-
newCap = max - low;
|
|
95
|
-
}
|
|
96
|
-
else {
|
|
97
|
-
// For slices of slices, capacity should be the capacity of the original slice minus the low index
|
|
98
|
-
if (isComplexSlice(s)) {
|
|
99
|
-
newCap = oldCap - low;
|
|
100
|
-
}
|
|
101
|
-
else {
|
|
102
|
-
newCap = s.length - low;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
const newLength = high - low;
|
|
106
|
-
const newOffset = oldOffset + low;
|
|
107
|
-
const target = {
|
|
108
|
-
__meta__: {
|
|
109
|
-
backing: backing,
|
|
110
|
-
offset: newOffset,
|
|
111
|
-
length: newLength,
|
|
112
|
-
capacity: newCap,
|
|
113
|
-
},
|
|
114
|
-
};
|
|
115
|
-
const handler = {
|
|
116
|
-
get(target, prop) {
|
|
117
|
-
if (typeof prop === 'string' && /^\d+$/.test(prop)) {
|
|
118
|
-
const index = Number(prop);
|
|
119
|
-
if (index >= 0 && index < target.__meta__.length) {
|
|
120
|
-
return target.__meta__.backing[target.__meta__.offset + index];
|
|
121
|
-
}
|
|
122
|
-
throw new Error(`Slice index out of range: ${index} >= ${target.__meta__.length}`);
|
|
123
|
-
}
|
|
124
|
-
if (prop === 'length') {
|
|
125
|
-
return target.__meta__.length;
|
|
126
|
-
}
|
|
127
|
-
if (prop === '__meta__') {
|
|
128
|
-
return target.__meta__;
|
|
129
|
-
}
|
|
130
|
-
if (prop === 'slice' ||
|
|
131
|
-
prop === 'map' ||
|
|
132
|
-
prop === 'filter' ||
|
|
133
|
-
prop === 'reduce' ||
|
|
134
|
-
prop === 'forEach' ||
|
|
135
|
-
prop === Symbol.iterator) {
|
|
136
|
-
const backingSlice = target.__meta__.backing.slice(target.__meta__.offset, target.__meta__.offset + target.__meta__.length);
|
|
137
|
-
return backingSlice[prop].bind(backingSlice);
|
|
138
|
-
}
|
|
139
|
-
return Reflect.get(target, prop);
|
|
140
|
-
},
|
|
141
|
-
set(target, prop, value) {
|
|
142
|
-
if (typeof prop === 'string' && /^\d+$/.test(prop)) {
|
|
143
|
-
const index = Number(prop);
|
|
144
|
-
if (index >= 0 && index < target.__meta__.length) {
|
|
145
|
-
target.__meta__.backing[target.__meta__.offset + index] = value;
|
|
146
|
-
return true;
|
|
147
|
-
}
|
|
148
|
-
if (index === target.__meta__.length &&
|
|
149
|
-
target.__meta__.length < target.__meta__.capacity) {
|
|
150
|
-
target.__meta__.backing[target.__meta__.offset + index] = value;
|
|
151
|
-
target.__meta__.length++;
|
|
152
|
-
return true;
|
|
153
|
-
}
|
|
154
|
-
throw new Error(`Slice index out of range: ${index} >= ${target.__meta__.length}`);
|
|
155
|
-
}
|
|
156
|
-
if (prop === 'length' || prop === '__meta__') {
|
|
157
|
-
return false;
|
|
158
|
-
}
|
|
159
|
-
return Reflect.set(target, prop, value);
|
|
160
|
-
},
|
|
161
|
-
};
|
|
162
|
-
return new Proxy(target, handler);
|
|
163
|
-
};
|
|
164
|
-
/**
|
|
165
|
-
* Creates a new map (TypeScript Map).
|
|
166
|
-
* @returns A new TypeScript Map.
|
|
167
|
-
*/
|
|
168
|
-
export const makeMap = () => {
|
|
169
|
-
return new Map();
|
|
170
|
-
};
|
|
171
|
-
/**
|
|
172
|
-
* Converts a JavaScript array to a Go slice.
|
|
173
|
-
* For multi-dimensional arrays, recursively converts nested arrays to slices.
|
|
174
|
-
* @param arr The JavaScript array to convert
|
|
175
|
-
* @param depth How many levels of nesting to convert (default: 1, use Infinity for all levels)
|
|
176
|
-
* @returns A Go slice containing the same elements
|
|
177
|
-
*/
|
|
178
|
-
export const arrayToSlice = (arr, depth = 1) => {
|
|
179
|
-
if (arr == null)
|
|
180
|
-
return [];
|
|
181
|
-
if (arr.length === 0)
|
|
182
|
-
return arr;
|
|
183
|
-
const target = {
|
|
184
|
-
__meta__: {
|
|
185
|
-
backing: arr,
|
|
186
|
-
offset: 0,
|
|
187
|
-
length: arr.length,
|
|
188
|
-
capacity: arr.length,
|
|
189
|
-
},
|
|
190
|
-
};
|
|
191
|
-
const handler = {
|
|
192
|
-
get(target, prop) {
|
|
193
|
-
if (typeof prop === 'string' && /^\d+$/.test(prop)) {
|
|
194
|
-
const index = Number(prop);
|
|
195
|
-
if (index >= 0 && index < target.__meta__.length) {
|
|
196
|
-
return target.__meta__.backing[target.__meta__.offset + index];
|
|
197
|
-
}
|
|
198
|
-
throw new Error(`Slice index out of range: ${index} >= ${target.__meta__.length}`);
|
|
199
|
-
}
|
|
200
|
-
if (prop === 'length') {
|
|
201
|
-
return target.__meta__.length;
|
|
202
|
-
}
|
|
203
|
-
if (prop === '__meta__') {
|
|
204
|
-
return target.__meta__;
|
|
205
|
-
}
|
|
206
|
-
if (prop === 'slice' ||
|
|
207
|
-
prop === 'map' ||
|
|
208
|
-
prop === 'filter' ||
|
|
209
|
-
prop === 'reduce' ||
|
|
210
|
-
prop === 'forEach' ||
|
|
211
|
-
prop === Symbol.iterator) {
|
|
212
|
-
const backingSlice = target.__meta__.backing.slice(target.__meta__.offset, target.__meta__.offset + target.__meta__.length);
|
|
213
|
-
return backingSlice[prop].bind(backingSlice);
|
|
214
|
-
}
|
|
215
|
-
return Reflect.get(target, prop);
|
|
216
|
-
},
|
|
217
|
-
set(target, prop, value) {
|
|
218
|
-
if (typeof prop === 'string' && /^\d+$/.test(prop)) {
|
|
219
|
-
const index = Number(prop);
|
|
220
|
-
if (index >= 0 && index < target.__meta__.length) {
|
|
221
|
-
target.__meta__.backing[target.__meta__.offset + index] = value;
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
if (index === target.__meta__.length &&
|
|
225
|
-
target.__meta__.length < target.__meta__.capacity) {
|
|
226
|
-
target.__meta__.backing[target.__meta__.offset + index] = value;
|
|
227
|
-
target.__meta__.length++;
|
|
228
|
-
return true;
|
|
229
|
-
}
|
|
230
|
-
throw new Error(`Slice index out of range: ${index} >= ${target.__meta__.length}`);
|
|
231
|
-
}
|
|
232
|
-
if (prop === 'length' || prop === '__meta__') {
|
|
233
|
-
return false;
|
|
234
|
-
}
|
|
235
|
-
return Reflect.set(target, prop, value);
|
|
236
|
-
},
|
|
237
|
-
};
|
|
238
|
-
// Recursively convert nested arrays if depth > 1
|
|
239
|
-
if (depth > 1 && arr.length > 0) {
|
|
240
|
-
for (let i = 0; i < arr.length; i++) {
|
|
241
|
-
const item = arr[i];
|
|
242
|
-
if (isComplexSlice(item)) {
|
|
243
|
-
}
|
|
244
|
-
else if (Array.isArray(item)) {
|
|
245
|
-
arr[i] = arrayToSlice(item, depth - 1);
|
|
246
|
-
}
|
|
247
|
-
else if (item &&
|
|
248
|
-
typeof item === 'object' &&
|
|
249
|
-
isComplexSlice(item)) {
|
|
250
|
-
// Preserve capacity information for complex slices
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
return new Proxy(target, handler);
|
|
255
|
-
};
|
|
256
|
-
/**
|
|
257
|
-
* Returns the length of a collection (string, array, slice, map, or set).
|
|
258
|
-
* @param obj The collection to get the length of.
|
|
259
|
-
* @returns The length of the collection.
|
|
260
|
-
*/
|
|
261
|
-
export const len = (obj) => {
|
|
262
|
-
if (obj === null || obj === undefined) {
|
|
263
|
-
return 0;
|
|
264
|
-
}
|
|
265
|
-
if (typeof obj === 'string') {
|
|
266
|
-
return obj.length;
|
|
267
|
-
}
|
|
268
|
-
if (obj instanceof Map || obj instanceof Set) {
|
|
269
|
-
return obj.size;
|
|
270
|
-
}
|
|
271
|
-
if (isComplexSlice(obj)) {
|
|
272
|
-
return obj.__meta__.length;
|
|
273
|
-
}
|
|
274
|
-
if (Array.isArray(obj)) {
|
|
275
|
-
return obj.length;
|
|
276
|
-
}
|
|
277
|
-
return 0; // Default fallback
|
|
278
|
-
};
|
|
279
|
-
/**
|
|
280
|
-
* Returns the capacity of a slice.
|
|
281
|
-
* @param obj The slice.
|
|
282
|
-
* @returns The capacity of the slice.
|
|
283
|
-
*/
|
|
284
|
-
export const cap = (obj) => {
|
|
285
|
-
if (obj === null || obj === undefined) {
|
|
286
|
-
return 0;
|
|
287
|
-
}
|
|
288
|
-
if (isComplexSlice(obj)) {
|
|
289
|
-
return obj.__meta__.capacity;
|
|
290
|
-
}
|
|
291
|
-
if (Array.isArray(obj)) {
|
|
292
|
-
return obj.length;
|
|
293
|
-
}
|
|
294
|
-
return 0;
|
|
295
|
-
};
|
|
296
|
-
/**
|
|
297
|
-
* Appends elements to a slice.
|
|
298
|
-
* Note: In Go, append can return a new slice if the underlying array is reallocated.
|
|
299
|
-
* This helper emulates that by returning the modified or new slice.
|
|
300
|
-
* @param slice The slice to append to.
|
|
301
|
-
* @param elements The elements to append.
|
|
302
|
-
* @returns The modified or new slice.
|
|
303
|
-
*/
|
|
304
|
-
export const append = (slice, ...elements) => {
|
|
305
|
-
if (slice === null || slice === undefined) {
|
|
306
|
-
if (elements.length === 0) {
|
|
307
|
-
return [];
|
|
308
|
-
}
|
|
309
|
-
else {
|
|
310
|
-
return elements.slice(0);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
if (elements.length === 0) {
|
|
314
|
-
return slice;
|
|
315
|
-
}
|
|
316
|
-
const oldLen = len(slice);
|
|
317
|
-
const oldCap = cap(slice);
|
|
318
|
-
const newLen = oldLen + elements.length;
|
|
319
|
-
if (newLen <= oldCap) {
|
|
320
|
-
if (isComplexSlice(slice)) {
|
|
321
|
-
const offset = slice.__meta__.offset;
|
|
322
|
-
const backing = slice.__meta__.backing;
|
|
323
|
-
for (let i = 0; i < elements.length; i++) {
|
|
324
|
-
backing[offset + oldLen + i] = elements[i];
|
|
325
|
-
}
|
|
326
|
-
const result = new Array(newLen);
|
|
327
|
-
for (let i = 0; i < oldLen; i++) {
|
|
328
|
-
result[i] = backing[offset + i];
|
|
329
|
-
}
|
|
330
|
-
for (let i = 0; i < elements.length; i++) {
|
|
331
|
-
result[oldLen + i] = elements[i];
|
|
332
|
-
}
|
|
333
|
-
result.__meta__ = {
|
|
334
|
-
backing: backing,
|
|
335
|
-
offset: offset,
|
|
336
|
-
length: newLen,
|
|
337
|
-
capacity: oldCap,
|
|
338
|
-
};
|
|
339
|
-
return result;
|
|
340
|
-
}
|
|
341
|
-
else {
|
|
342
|
-
const result = new Array(newLen);
|
|
343
|
-
for (let i = 0; i < oldLen; i++) {
|
|
344
|
-
result[i] = slice[i];
|
|
345
|
-
}
|
|
346
|
-
for (let i = 0; i < elements.length; i++) {
|
|
347
|
-
result[i + oldLen] = elements[i];
|
|
348
|
-
if (i + oldLen < oldCap && Array.isArray(slice)) {
|
|
349
|
-
slice[i + oldLen] = elements[i];
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
result.__meta__ = {
|
|
353
|
-
backing: slice,
|
|
354
|
-
offset: 0,
|
|
355
|
-
length: newLen,
|
|
356
|
-
capacity: oldCap,
|
|
357
|
-
};
|
|
358
|
-
return result;
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
else {
|
|
362
|
-
let newCap = oldCap;
|
|
363
|
-
if (newCap == 0) {
|
|
364
|
-
newCap = elements.length;
|
|
365
|
-
}
|
|
366
|
-
else {
|
|
367
|
-
if (newCap < 1024) {
|
|
368
|
-
newCap *= 2;
|
|
369
|
-
}
|
|
370
|
-
else {
|
|
371
|
-
newCap += newCap / 4;
|
|
372
|
-
}
|
|
373
|
-
// Ensure the new capacity fits all the elements
|
|
374
|
-
if (newCap < newLen) {
|
|
375
|
-
newCap = newLen;
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
const newBacking = new Array(newCap);
|
|
379
|
-
if (isComplexSlice(slice)) {
|
|
380
|
-
const offset = slice.__meta__.offset;
|
|
381
|
-
const backing = slice.__meta__.backing;
|
|
382
|
-
for (let i = 0; i < oldLen; i++) {
|
|
383
|
-
newBacking[i] = backing[offset + i];
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
else {
|
|
387
|
-
for (let i = 0; i < oldLen; i++) {
|
|
388
|
-
newBacking[i] = slice[i];
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
for (let i = 0; i < elements.length; i++) {
|
|
392
|
-
newBacking[oldLen + i] = elements[i];
|
|
393
|
-
}
|
|
394
|
-
if (newLen === newCap) {
|
|
395
|
-
return newBacking.slice(0, newLen);
|
|
396
|
-
}
|
|
397
|
-
const result = new Array(newLen);
|
|
398
|
-
for (let i = 0; i < newLen; i++) {
|
|
399
|
-
result[i] = newBacking[i];
|
|
400
|
-
}
|
|
401
|
-
result.__meta__ = {
|
|
402
|
-
backing: newBacking,
|
|
403
|
-
offset: 0,
|
|
404
|
-
length: newLen,
|
|
405
|
-
capacity: newCap,
|
|
406
|
-
};
|
|
407
|
-
return result;
|
|
408
|
-
}
|
|
409
|
-
};
|
|
410
|
-
/**
|
|
411
|
-
* Copies elements from src to dst.
|
|
412
|
-
* @param dst The destination slice.
|
|
413
|
-
* @param src The source slice.
|
|
414
|
-
* @returns The number of elements copied.
|
|
415
|
-
*/
|
|
416
|
-
export const copy = (dst, src) => {
|
|
417
|
-
if (dst === null || src === null) {
|
|
418
|
-
return 0;
|
|
419
|
-
}
|
|
420
|
-
const dstLen = len(dst);
|
|
421
|
-
const srcLen = len(src);
|
|
422
|
-
const count = Math.min(dstLen, srcLen);
|
|
423
|
-
if (count === 0) {
|
|
424
|
-
return 0;
|
|
425
|
-
}
|
|
426
|
-
if (isComplexSlice(dst)) {
|
|
427
|
-
const dstOffset = dst.__meta__.offset;
|
|
428
|
-
const dstBacking = dst.__meta__.backing;
|
|
429
|
-
if (isComplexSlice(src)) {
|
|
430
|
-
const srcOffset = src.__meta__.offset;
|
|
431
|
-
const srcBacking = src.__meta__.backing;
|
|
432
|
-
for (let i = 0; i < count; i++) {
|
|
433
|
-
dstBacking[dstOffset + i] = srcBacking[srcOffset + i];
|
|
434
|
-
dst[i] = srcBacking[srcOffset + i]; // Update the proxy array
|
|
435
|
-
}
|
|
436
|
-
}
|
|
437
|
-
else {
|
|
438
|
-
for (let i = 0; i < count; i++) {
|
|
439
|
-
dstBacking[dstOffset + i] = src[i];
|
|
440
|
-
dst[i] = src[i]; // Update the proxy array
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
else {
|
|
445
|
-
if (isComplexSlice(src)) {
|
|
446
|
-
const srcOffset = src.__meta__.offset;
|
|
447
|
-
const srcBacking = src.__meta__.backing;
|
|
448
|
-
for (let i = 0; i < count; i++) {
|
|
449
|
-
dst[i] = srcBacking[srcOffset + i];
|
|
450
|
-
}
|
|
451
|
-
}
|
|
452
|
-
else {
|
|
453
|
-
for (let i = 0; i < count; i++) {
|
|
454
|
-
dst[i] = src[i];
|
|
455
|
-
}
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
return count;
|
|
459
|
-
};
|
|
460
|
-
/**
|
|
461
|
-
* Converts a string to an array of Unicode code points (runes).
|
|
462
|
-
* @param str The input string.
|
|
463
|
-
* @returns An array of numbers representing the Unicode code points.
|
|
464
|
-
*/
|
|
465
|
-
export const stringToRunes = (str) => {
|
|
466
|
-
return Array.from(str).map((c) => c.codePointAt(0) || 0);
|
|
467
|
-
};
|
|
468
|
-
/**
|
|
469
|
-
* Converts an array of Unicode code points (runes) to a string.
|
|
470
|
-
* @param runes The input array of numbers representing Unicode code points.
|
|
471
|
-
* @returns The resulting string.
|
|
472
|
-
*/
|
|
473
|
-
export const runesToString = (runes) => {
|
|
474
|
-
return runes?.length ? String.fromCharCode(...runes) : '';
|
|
475
|
-
};
|
|
476
|
-
/**
|
|
477
|
-
* Converts a number to a byte (uint8) by truncating to the range 0-255.
|
|
478
|
-
* Equivalent to Go's byte() conversion.
|
|
479
|
-
* @param n The number to convert to a byte.
|
|
480
|
-
* @returns The byte value (0-255).
|
|
481
|
-
*/
|
|
482
|
-
export const byte = (n) => {
|
|
483
|
-
return n & 0xff; // Bitwise AND with 255 ensures we get a value in the range 0-255
|
|
484
|
-
};
|
|
485
|
-
/** Wrap a non-null T in a pointer‐box. */
|
|
486
|
-
export function box(v) {
|
|
487
|
-
// We create a new object wrapper for every box call to ensure
|
|
488
|
-
// distinct pointer identity, crucial for pointer comparisons (p1 == p2).
|
|
489
|
-
return { value: v };
|
|
490
|
-
}
|
|
491
|
-
/** Dereference a pointer‐box, throws on null → simulates Go panic. */
|
|
492
|
-
export function unbox(b) {
|
|
493
|
-
if (b === null) {
|
|
494
|
-
throw new Error('runtime error: invalid memory address or nil pointer dereference');
|
|
495
|
-
}
|
|
496
|
-
return b.value;
|
|
497
|
-
}
|
|
498
|
-
/**
|
|
499
|
-
* Gets a value from a map, with a default value if the key doesn't exist.
|
|
500
|
-
* @param map The map to get from.
|
|
501
|
-
* @param key The key to get.
|
|
502
|
-
* @param defaultValue The default value to return if the key doesn't exist (defaults to 0).
|
|
503
|
-
* @returns The value for the key, or the default value if the key doesn't exist.
|
|
504
|
-
*/
|
|
505
|
-
export const mapGet = (map, key, defaultValue = null) => {
|
|
506
|
-
return map.has(key) ? map.get(key) : defaultValue;
|
|
507
|
-
};
|
|
508
|
-
/**
|
|
509
|
-
* Sets a value in a map.
|
|
510
|
-
* @param map The map to set in.
|
|
511
|
-
* @param key The key to set.
|
|
512
|
-
* @param value The value to set.
|
|
513
|
-
*/
|
|
514
|
-
export const mapSet = (map, key, value) => {
|
|
515
|
-
map.set(key, value);
|
|
516
|
-
};
|
|
517
|
-
/**
|
|
518
|
-
* Deletes a key from a map.
|
|
519
|
-
* @param map The map to delete from.
|
|
520
|
-
* @param key The key to delete.
|
|
521
|
-
*/
|
|
522
|
-
export const deleteMapEntry = (map, key) => {
|
|
523
|
-
map.delete(key);
|
|
524
|
-
};
|
|
525
|
-
/**
|
|
526
|
-
* Checks if a key exists in a map.
|
|
527
|
-
* @param map The map to check in.
|
|
528
|
-
* @param key The key to check.
|
|
529
|
-
* @returns True if the key exists, false otherwise.
|
|
530
|
-
*/
|
|
531
|
-
export const mapHas = (map, key) => {
|
|
532
|
-
return map.has(key);
|
|
533
|
-
};
|
|
534
|
-
/**
|
|
535
|
-
* Represents the kinds of Go types that can be registered at runtime.
|
|
536
|
-
*/
|
|
537
|
-
export var TypeKind;
|
|
538
|
-
(function (TypeKind) {
|
|
539
|
-
TypeKind["Basic"] = "basic";
|
|
540
|
-
TypeKind["Interface"] = "interface";
|
|
541
|
-
TypeKind["Struct"] = "struct";
|
|
542
|
-
TypeKind["Map"] = "map";
|
|
543
|
-
TypeKind["Slice"] = "slice";
|
|
544
|
-
TypeKind["Array"] = "array";
|
|
545
|
-
TypeKind["Pointer"] = "pointer";
|
|
546
|
-
TypeKind["Function"] = "function";
|
|
547
|
-
TypeKind["Channel"] = "channel";
|
|
548
|
-
})(TypeKind || (TypeKind = {}));
|
|
549
|
-
// Type guard functions for TypeInfo variants
|
|
550
|
-
export function isStructTypeInfo(info) {
|
|
551
|
-
return info.kind === TypeKind.Struct;
|
|
552
|
-
}
|
|
553
|
-
export function isInterfaceTypeInfo(info) {
|
|
554
|
-
return info.kind === TypeKind.Interface;
|
|
555
|
-
}
|
|
556
|
-
export function isBasicTypeInfo(info) {
|
|
557
|
-
return info.kind === TypeKind.Basic;
|
|
558
|
-
}
|
|
559
|
-
export function isMapTypeInfo(info) {
|
|
560
|
-
return info.kind === TypeKind.Map;
|
|
561
|
-
}
|
|
562
|
-
export function isSliceTypeInfo(info) {
|
|
563
|
-
return info.kind === TypeKind.Slice;
|
|
564
|
-
}
|
|
565
|
-
export function isArrayTypeInfo(info) {
|
|
566
|
-
return info.kind === TypeKind.Array;
|
|
567
|
-
}
|
|
568
|
-
export function isPointerTypeInfo(info) {
|
|
569
|
-
return info.kind === TypeKind.Pointer;
|
|
570
|
-
}
|
|
571
|
-
export function isFunctionTypeInfo(info) {
|
|
572
|
-
return info.kind === TypeKind.Function;
|
|
573
|
-
}
|
|
574
|
-
export function isChannelTypeInfo(info) {
|
|
575
|
-
return info.kind === TypeKind.Channel;
|
|
576
|
-
}
|
|
577
|
-
// Registry to store runtime type information
|
|
578
|
-
const typeRegistry = new Map();
|
|
579
|
-
/**
|
|
580
|
-
* Registers a struct type with the runtime type system.
|
|
581
|
-
*
|
|
582
|
-
* @param name The name of the type.
|
|
583
|
-
* @param zeroValue The zero value for the type.
|
|
584
|
-
* @param methods Array of method signatures for the struct.
|
|
585
|
-
* @param ctor Constructor for the struct.
|
|
586
|
-
* @param fields Record of field names and their types.
|
|
587
|
-
* @returns The struct type information object.
|
|
588
|
-
*/
|
|
589
|
-
export const registerStructType = (name, zeroValue, methods, ctor, fields = {}) => {
|
|
590
|
-
const typeInfo = {
|
|
591
|
-
name,
|
|
592
|
-
kind: TypeKind.Struct,
|
|
593
|
-
zeroValue,
|
|
594
|
-
methods,
|
|
595
|
-
ctor,
|
|
596
|
-
fields,
|
|
597
|
-
};
|
|
598
|
-
typeRegistry.set(name, typeInfo);
|
|
599
|
-
return typeInfo;
|
|
600
|
-
};
|
|
601
|
-
/**
|
|
602
|
-
* Registers an interface type with the runtime type system.
|
|
603
|
-
*
|
|
604
|
-
* @param name The name of the type.
|
|
605
|
-
* @param zeroValue The zero value for the type (usually null).
|
|
606
|
-
* @param methods Array of method signatures for the interface.
|
|
607
|
-
* @returns The interface type information object.
|
|
608
|
-
*/
|
|
609
|
-
export const registerInterfaceType = (name, zeroValue, methods) => {
|
|
610
|
-
const typeInfo = {
|
|
611
|
-
name,
|
|
612
|
-
kind: TypeKind.Interface,
|
|
613
|
-
zeroValue,
|
|
614
|
-
methods,
|
|
615
|
-
};
|
|
616
|
-
typeRegistry.set(name, typeInfo);
|
|
617
|
-
return typeInfo;
|
|
618
|
-
};
|
|
619
|
-
/**
|
|
620
|
-
* Normalizes a type info to a structured TypeInfo object.
|
|
621
|
-
*
|
|
622
|
-
* @param info The type info or name.
|
|
623
|
-
* @returns A normalized TypeInfo object.
|
|
624
|
-
*/
|
|
625
|
-
function normalizeTypeInfo(info) {
|
|
626
|
-
if (typeof info === 'string') {
|
|
627
|
-
const typeInfo = typeRegistry.get(info);
|
|
628
|
-
if (typeInfo) {
|
|
629
|
-
return typeInfo;
|
|
630
|
-
}
|
|
631
|
-
return {
|
|
632
|
-
kind: TypeKind.Basic,
|
|
633
|
-
name: info,
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
return info;
|
|
637
|
-
}
|
|
638
|
-
function compareOptionalTypeInfo(type1, type2) {
|
|
639
|
-
if (type1 === undefined && type2 === undefined)
|
|
640
|
-
return true;
|
|
641
|
-
if (type1 === undefined || type2 === undefined)
|
|
642
|
-
return false;
|
|
643
|
-
// Assuming areTypeInfosIdentical will handle normalization if needed,
|
|
644
|
-
// but type1 and type2 here are expected to be direct fields from TypeInfo objects.
|
|
645
|
-
return areTypeInfosIdentical(type1, type2);
|
|
646
|
-
}
|
|
647
|
-
function areFuncParamOrResultArraysIdentical(arr1, arr2) {
|
|
648
|
-
if (arr1 === undefined && arr2 === undefined)
|
|
649
|
-
return true;
|
|
650
|
-
if (arr1 === undefined || arr2 === undefined)
|
|
651
|
-
return false;
|
|
652
|
-
if (arr1.length !== arr2.length)
|
|
653
|
-
return false;
|
|
654
|
-
for (let i = 0; i < arr1.length; i++) {
|
|
655
|
-
if (!areTypeInfosIdentical(arr1[i], arr2[i])) {
|
|
656
|
-
return false;
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
return true;
|
|
660
|
-
}
|
|
661
|
-
function areFuncSignaturesIdentical(func1, func2) {
|
|
662
|
-
if ((func1.isVariadic || false) !== (func2.isVariadic || false)) {
|
|
663
|
-
return false;
|
|
664
|
-
}
|
|
665
|
-
return (areFuncParamOrResultArraysIdentical(func1.params, func2.params) &&
|
|
666
|
-
areFuncParamOrResultArraysIdentical(func1.results, func2.results));
|
|
667
|
-
}
|
|
668
|
-
function areMethodArgsArraysIdentical(args1, args2) {
|
|
669
|
-
if (args1 === undefined && args2 === undefined)
|
|
670
|
-
return true;
|
|
671
|
-
if (args1 === undefined || args2 === undefined)
|
|
672
|
-
return false;
|
|
673
|
-
if (args1.length !== args2.length)
|
|
674
|
-
return false;
|
|
675
|
-
for (let i = 0; i < args1.length; i++) {
|
|
676
|
-
// Compare based on type only, names of args/results don't affect signature identity here.
|
|
677
|
-
if (!areTypeInfosIdentical(args1[i].type, args2[i].type)) {
|
|
678
|
-
return false;
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
return true;
|
|
682
|
-
}
|
|
683
|
-
export function areTypeInfosIdentical(type1InfoOrName, type2InfoOrName) {
|
|
684
|
-
const t1Norm = normalizeTypeInfo(type1InfoOrName);
|
|
685
|
-
const t2Norm = normalizeTypeInfo(type2InfoOrName);
|
|
686
|
-
if (t1Norm === t2Norm)
|
|
687
|
-
return true; // Object identity
|
|
688
|
-
if (t1Norm.kind !== t2Norm.kind)
|
|
689
|
-
return false;
|
|
690
|
-
// If types have names, the names must match for identity.
|
|
691
|
-
// If one has a name and the other doesn't, they are not identical.
|
|
692
|
-
if (t1Norm.name !== t2Norm.name)
|
|
693
|
-
return false;
|
|
694
|
-
// If both are named and names match, for Basic, Struct, Interface, this is sufficient for identity.
|
|
695
|
-
if (t1Norm.name !== undefined /* && t2Norm.name is also defined and equal */) {
|
|
696
|
-
if (t1Norm.kind === TypeKind.Basic ||
|
|
697
|
-
t1Norm.kind === TypeKind.Struct ||
|
|
698
|
-
t1Norm.kind === TypeKind.Interface) {
|
|
699
|
-
return true;
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
// For other types (Pointer, Slice, etc.), or if both are anonymous (name is undefined),
|
|
703
|
-
// structural comparison is needed.
|
|
704
|
-
switch (t1Norm.kind) {
|
|
705
|
-
case TypeKind.Basic:
|
|
706
|
-
// Names matched if they were defined, or both undefined (which means true by t1Norm.name !== t2Norm.name being false)
|
|
707
|
-
return true;
|
|
708
|
-
case TypeKind.Pointer:
|
|
709
|
-
return compareOptionalTypeInfo(t1Norm.elemType, t2Norm.elemType);
|
|
710
|
-
case TypeKind.Slice:
|
|
711
|
-
return compareOptionalTypeInfo(t1Norm.elemType, t2Norm.elemType);
|
|
712
|
-
case TypeKind.Array:
|
|
713
|
-
return (t1Norm.length === t2Norm.length &&
|
|
714
|
-
compareOptionalTypeInfo(t1Norm.elemType, t2Norm.elemType));
|
|
715
|
-
case TypeKind.Map:
|
|
716
|
-
return (compareOptionalTypeInfo(t1Norm.keyType, t2Norm.keyType) &&
|
|
717
|
-
compareOptionalTypeInfo(t1Norm.elemType, t2Norm.elemType));
|
|
718
|
-
case TypeKind.Channel:
|
|
719
|
-
return (
|
|
720
|
-
// Ensure direction property exists before comparing, or handle undefined if it can be
|
|
721
|
-
(t1Norm.direction || 'both') === (t2Norm.direction || 'both') &&
|
|
722
|
-
compareOptionalTypeInfo(t1Norm.elemType, t2Norm.elemType));
|
|
723
|
-
case TypeKind.Function:
|
|
724
|
-
return areFuncSignaturesIdentical(t1Norm, t2Norm);
|
|
725
|
-
case TypeKind.Struct:
|
|
726
|
-
case TypeKind.Interface:
|
|
727
|
-
// If we reach here, names were undefined (both anonymous) or names matched but was not Basic/Struct/Interface.
|
|
728
|
-
// For anonymous Struct/Interface, strict identity means full structural comparison.
|
|
729
|
-
// For now, we consider anonymous types not identical unless they are the same object (caught above).
|
|
730
|
-
// If they were named and matched, 'return true' was hit earlier for these kinds.
|
|
731
|
-
return false;
|
|
732
|
-
default:
|
|
733
|
-
return false;
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
/**
|
|
737
|
-
* Validates that a map key matches the expected type info.
|
|
738
|
-
*
|
|
739
|
-
* @param key The key to validate
|
|
740
|
-
* @param keyTypeInfo The normalized type info for the key
|
|
741
|
-
* @returns True if the key matches the type info, false otherwise
|
|
742
|
-
*/
|
|
743
|
-
function validateMapKey(key, keyTypeInfo) {
|
|
744
|
-
if (keyTypeInfo.kind === TypeKind.Basic) {
|
|
745
|
-
// For string keys
|
|
746
|
-
if (keyTypeInfo.name === 'string') {
|
|
747
|
-
return typeof key === 'string';
|
|
748
|
-
}
|
|
749
|
-
else if (keyTypeInfo.name === 'int' ||
|
|
750
|
-
keyTypeInfo.name === 'float64' ||
|
|
751
|
-
keyTypeInfo.name === 'number') {
|
|
752
|
-
if (typeof key === 'string') {
|
|
753
|
-
return /^-?\d+(\.\d+)?$/.test(key);
|
|
754
|
-
}
|
|
755
|
-
else {
|
|
756
|
-
return typeof key === 'number';
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
return false;
|
|
761
|
-
}
|
|
762
|
-
/**
|
|
763
|
-
* Checks if a value matches a basic type info.
|
|
764
|
-
*
|
|
765
|
-
* @param value The value to check.
|
|
766
|
-
* @param info The basic type info to match against.
|
|
767
|
-
* @returns True if the value matches the basic type, false otherwise.
|
|
768
|
-
*/
|
|
769
|
-
function matchesBasicType(value, info) {
|
|
770
|
-
if (info.name === 'string')
|
|
771
|
-
return typeof value === 'string';
|
|
772
|
-
if (info.name === 'number' || info.name === 'int' || info.name === 'float64')
|
|
773
|
-
return typeof value === 'number';
|
|
774
|
-
if (info.name === 'boolean' || info.name === 'bool')
|
|
775
|
-
return typeof value === 'boolean';
|
|
776
|
-
return false;
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Checks if a value matches a struct type info.
|
|
780
|
-
*
|
|
781
|
-
* @param value The value to check.
|
|
782
|
-
* @param info The struct type info to match against.
|
|
783
|
-
* @returns True if the value matches the struct type, false otherwise.
|
|
784
|
-
*/
|
|
785
|
-
function matchesStructType(value, info) {
|
|
786
|
-
if (!isStructTypeInfo(info))
|
|
787
|
-
return false;
|
|
788
|
-
// For structs, use instanceof with the constructor
|
|
789
|
-
if (info.ctor && value instanceof info.ctor) {
|
|
790
|
-
return true;
|
|
791
|
-
}
|
|
792
|
-
// Check if the value has all methods defined in the struct's TypeInfo
|
|
793
|
-
// This is a structural check, not a signature check here.
|
|
794
|
-
// Signature checks are more relevant for interface satisfaction.
|
|
795
|
-
if (info.methods && typeof value === 'object' && value !== null) {
|
|
796
|
-
const allMethodsExist = info.methods.every((methodSig) => typeof value[methodSig.name] === 'function');
|
|
797
|
-
if (!allMethodsExist) {
|
|
798
|
-
return false;
|
|
799
|
-
}
|
|
800
|
-
// Further signature checking could be added here if needed for struct-to-struct assignability
|
|
801
|
-
}
|
|
802
|
-
if (typeof value === 'object' && value !== null && info.fields) {
|
|
803
|
-
const fieldNames = Object.keys(info.fields || {});
|
|
804
|
-
const valueFields = Object.keys(value);
|
|
805
|
-
const fieldsExist = fieldNames.every((field) => field in value);
|
|
806
|
-
const sameFieldCount = valueFields.length === fieldNames.length;
|
|
807
|
-
const allFieldsInStruct = valueFields.every((field) => fieldNames.includes(field));
|
|
808
|
-
if (fieldsExist && sameFieldCount && allFieldsInStruct) {
|
|
809
|
-
return Object.entries(info.fields).every(([fieldName, fieldType]) => {
|
|
810
|
-
return matchesType(value[fieldName], normalizeTypeInfo(fieldType));
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
return false;
|
|
814
|
-
}
|
|
815
|
-
return false;
|
|
816
|
-
}
|
|
817
|
-
/**
|
|
818
|
-
* Checks if a value matches an interface type info.
|
|
819
|
-
*
|
|
820
|
-
* @param value The value to check.
|
|
821
|
-
* @param info The interface type info to match against.
|
|
822
|
-
* @returns True if the value matches the interface type, false otherwise.
|
|
823
|
-
*/
|
|
824
|
-
/**
|
|
825
|
-
* Checks if a value matches an interface type info by verifying it implements
|
|
826
|
-
* all required methods with compatible signatures.
|
|
827
|
-
*
|
|
828
|
-
* @param value The value to check.
|
|
829
|
-
* @param info The interface type info to match against.
|
|
830
|
-
* @returns True if the value matches the interface type, false otherwise.
|
|
831
|
-
*/
|
|
832
|
-
function matchesInterfaceType(value, info) {
|
|
833
|
-
// Check basic conditions first
|
|
834
|
-
if (!isInterfaceTypeInfo(info) || typeof value !== 'object' || value === null) {
|
|
835
|
-
return false;
|
|
836
|
-
}
|
|
837
|
-
// For interfaces, check if the value has all the required methods with compatible signatures
|
|
838
|
-
return info.methods.every((requiredMethodSig) => {
|
|
839
|
-
const actualMethod = value[requiredMethodSig.name];
|
|
840
|
-
// Method must exist and be a function
|
|
841
|
-
if (typeof actualMethod !== 'function') {
|
|
842
|
-
return false;
|
|
843
|
-
}
|
|
844
|
-
// Check parameter count (basic arity check)
|
|
845
|
-
// Note: This is a simplified check as JavaScript functions can have optional/rest parameters
|
|
846
|
-
const declaredParamCount = actualMethod.length;
|
|
847
|
-
const requiredParamCount = requiredMethodSig.args.length;
|
|
848
|
-
// Strict arity checking can be problematic in JS, so we'll be lenient
|
|
849
|
-
// A method with fewer params than required is definitely incompatible
|
|
850
|
-
if (declaredParamCount < requiredParamCount) {
|
|
851
|
-
return false;
|
|
852
|
-
}
|
|
853
|
-
// Check return types if we can determine them
|
|
854
|
-
// This is challenging in JavaScript without runtime type information
|
|
855
|
-
// If the value has a __goTypeName property, it might be a registered type
|
|
856
|
-
// with more type information available
|
|
857
|
-
if (value.__goTypeName) {
|
|
858
|
-
const valueTypeInfo = typeRegistry.get(value.__goTypeName);
|
|
859
|
-
if (valueTypeInfo && isStructTypeInfo(valueTypeInfo)) {
|
|
860
|
-
// Find the matching method in the value's type info
|
|
861
|
-
const valueMethodSig = valueTypeInfo.methods.find(m => m.name === requiredMethodSig.name);
|
|
862
|
-
if (valueMethodSig) {
|
|
863
|
-
// Compare return types
|
|
864
|
-
if (valueMethodSig.returns.length !== requiredMethodSig.returns.length) {
|
|
865
|
-
return false;
|
|
866
|
-
}
|
|
867
|
-
// Compare each return type for compatibility
|
|
868
|
-
for (let i = 0; i < requiredMethodSig.returns.length; i++) {
|
|
869
|
-
const requiredReturnType = normalizeTypeInfo(requiredMethodSig.returns[i].type);
|
|
870
|
-
const valueReturnType = normalizeTypeInfo(valueMethodSig.returns[i].type);
|
|
871
|
-
// For interface return types, we need to check if the value's return type
|
|
872
|
-
// implements the required interface
|
|
873
|
-
if (isInterfaceTypeInfo(requiredReturnType)) {
|
|
874
|
-
// This would be a recursive check, but we'll simplify for now
|
|
875
|
-
// by just checking if the types are the same or if the value type
|
|
876
|
-
// is registered as implementing the interface
|
|
877
|
-
if (requiredReturnType.name !== valueReturnType.name) {
|
|
878
|
-
// Check if valueReturnType implements requiredReturnType
|
|
879
|
-
// This would require additional implementation tracking
|
|
880
|
-
return false;
|
|
881
|
-
}
|
|
882
|
-
}
|
|
883
|
-
// For non-interface types, check direct type compatibility
|
|
884
|
-
else if (requiredReturnType.name !== valueReturnType.name) {
|
|
885
|
-
return false;
|
|
886
|
-
}
|
|
887
|
-
}
|
|
888
|
-
// Similarly, we could check parameter types for compatibility
|
|
889
|
-
// but we'll skip that for brevity
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
// If we can't determine detailed type information, we'll accept the method
|
|
894
|
-
// as long as it exists with a compatible arity
|
|
895
|
-
return true;
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Checks if a value matches a map type info.
|
|
900
|
-
*
|
|
901
|
-
* @param value The value to check.
|
|
902
|
-
* @param info The map type info to match against.
|
|
903
|
-
* @returns True if the value matches the map type, false otherwise.
|
|
904
|
-
*/
|
|
905
|
-
function matchesMapType(value, info) {
|
|
906
|
-
if (typeof value !== 'object' || value === null)
|
|
907
|
-
return false;
|
|
908
|
-
if (!isMapTypeInfo(info))
|
|
909
|
-
return false;
|
|
910
|
-
if (info.keyType || info.elemType) {
|
|
911
|
-
let entries = [];
|
|
912
|
-
if (value instanceof Map) {
|
|
913
|
-
entries = Array.from(value.entries());
|
|
914
|
-
}
|
|
915
|
-
else {
|
|
916
|
-
entries = Object.entries(value);
|
|
917
|
-
}
|
|
918
|
-
if (entries.length === 0)
|
|
919
|
-
return true; // Empty map matches any map type
|
|
920
|
-
const sampleSize = Math.min(5, entries.length);
|
|
921
|
-
for (let i = 0; i < sampleSize; i++) {
|
|
922
|
-
const [k, v] = entries[i];
|
|
923
|
-
if (info.keyType) {
|
|
924
|
-
if (!validateMapKey(k, normalizeTypeInfo(info.keyType))) {
|
|
925
|
-
return false;
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
if (info.elemType &&
|
|
929
|
-
!matchesType(v, normalizeTypeInfo(info.elemType))) {
|
|
930
|
-
return false;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
return true;
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Checks if a value matches an array or slice type info.
|
|
938
|
-
*
|
|
939
|
-
* @param value The value to check.
|
|
940
|
-
* @param info The array or slice type info to match against.
|
|
941
|
-
* @returns True if the value matches the array or slice type, false otherwise.
|
|
942
|
-
*/
|
|
943
|
-
function matchesArrayOrSliceType(value, info) {
|
|
944
|
-
// For slices and arrays, check if the value is an array and sample element types
|
|
945
|
-
if (!Array.isArray(value))
|
|
946
|
-
return false;
|
|
947
|
-
if (!isArrayTypeInfo(info) && !isSliceTypeInfo(info))
|
|
948
|
-
return false;
|
|
949
|
-
if (info.elemType) {
|
|
950
|
-
const arr = value;
|
|
951
|
-
if (arr.length === 0)
|
|
952
|
-
return true; // Empty array matches any array type
|
|
953
|
-
const sampleSize = Math.min(5, arr.length);
|
|
954
|
-
for (let i = 0; i < sampleSize; i++) {
|
|
955
|
-
if (!matchesType(arr[i], normalizeTypeInfo(info.elemType))) {
|
|
956
|
-
return false;
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
return true;
|
|
961
|
-
}
|
|
962
|
-
/**
|
|
963
|
-
* Checks if a value matches a pointer type info.
|
|
964
|
-
*
|
|
965
|
-
* @param value The value to check.
|
|
966
|
-
* @param info The pointer type info to match against.
|
|
967
|
-
* @returns True if the value matches the pointer type, false otherwise.
|
|
968
|
-
*/
|
|
969
|
-
function matchesPointerType(value, info) {
|
|
970
|
-
// Allow null/undefined values to match pointer types to support nil pointer assertions
|
|
971
|
-
// This enables Go's nil pointer type assertions like `ptr, ok := i.(*SomeType)` to work correctly
|
|
972
|
-
if (value === null || value === undefined) {
|
|
973
|
-
return true;
|
|
974
|
-
}
|
|
975
|
-
// Check if the value is a Box (has a 'value' property)
|
|
976
|
-
if (typeof value !== 'object' || !('value' in value)) {
|
|
977
|
-
return false;
|
|
978
|
-
}
|
|
979
|
-
if (!isPointerTypeInfo(info))
|
|
980
|
-
return false;
|
|
981
|
-
if (info.elemType) {
|
|
982
|
-
const elemTypeInfo = normalizeTypeInfo(info.elemType);
|
|
983
|
-
return matchesType(value.value, elemTypeInfo);
|
|
984
|
-
}
|
|
985
|
-
return true;
|
|
986
|
-
}
|
|
987
|
-
/**
|
|
988
|
-
* Checks if a value matches a function type info.
|
|
989
|
-
*
|
|
990
|
-
* @param value The value to check.
|
|
991
|
-
* @param info The function type info to match against.
|
|
992
|
-
* @returns True if the value matches the function type, false otherwise.
|
|
993
|
-
*/
|
|
994
|
-
function matchesFunctionType(value, info) {
|
|
995
|
-
// First check if the value is a function
|
|
996
|
-
if (typeof value !== 'function') {
|
|
997
|
-
return false;
|
|
998
|
-
}
|
|
999
|
-
// This is important for named function types
|
|
1000
|
-
if (info.name && value.__goTypeName) {
|
|
1001
|
-
return info.name === value.__goTypeName;
|
|
1002
|
-
}
|
|
1003
|
-
return true;
|
|
1004
|
-
}
|
|
1005
|
-
/**
|
|
1006
|
-
* Checks if a value matches a channel type info.
|
|
1007
|
-
*
|
|
1008
|
-
* @param value The value to check.
|
|
1009
|
-
* @param info The channel type info to match against.
|
|
1010
|
-
* @returns True if the value matches the channel type, false otherwise.
|
|
1011
|
-
*/
|
|
1012
|
-
function matchesChannelType(value, info) {
|
|
1013
|
-
// First check if it's a channel or channel reference
|
|
1014
|
-
if (typeof value !== 'object' || value === null) {
|
|
1015
|
-
return false;
|
|
1016
|
-
}
|
|
1017
|
-
// If it's a ChannelRef, get the underlying channel
|
|
1018
|
-
let channel = value;
|
|
1019
|
-
let valueDirection = 'both';
|
|
1020
|
-
if ('channel' in value && 'direction' in value) {
|
|
1021
|
-
channel = value.channel;
|
|
1022
|
-
valueDirection = value.direction;
|
|
1023
|
-
}
|
|
1024
|
-
// Check if it has channel methods
|
|
1025
|
-
if (!('send' in channel) ||
|
|
1026
|
-
!('receive' in channel) ||
|
|
1027
|
-
!('close' in channel) ||
|
|
1028
|
-
typeof channel.send !== 'function' ||
|
|
1029
|
-
typeof channel.receive !== 'function' ||
|
|
1030
|
-
typeof channel.close !== 'function') {
|
|
1031
|
-
return false;
|
|
1032
|
-
}
|
|
1033
|
-
if (info.elemType) {
|
|
1034
|
-
if (info.elemType === 'string' &&
|
|
1035
|
-
'zeroValue' in channel &&
|
|
1036
|
-
channel.zeroValue !== '') {
|
|
1037
|
-
return false;
|
|
1038
|
-
}
|
|
1039
|
-
if (info.elemType === 'number' &&
|
|
1040
|
-
'zeroValue' in channel &&
|
|
1041
|
-
typeof channel.zeroValue !== 'number') {
|
|
1042
|
-
return false;
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
if (info.direction) {
|
|
1046
|
-
return valueDirection === info.direction;
|
|
1047
|
-
}
|
|
1048
|
-
return true;
|
|
1049
|
-
}
|
|
1050
|
-
/**
|
|
1051
|
-
* Checks if a value matches a type info.
|
|
1052
|
-
*
|
|
1053
|
-
* @param value The value to check.
|
|
1054
|
-
* @param info The type info to match against.
|
|
1055
|
-
* @returns True if the value matches the type info, false otherwise.
|
|
1056
|
-
*/
|
|
1057
|
-
function matchesType(value, info) {
|
|
1058
|
-
if (value === null || value === undefined) {
|
|
1059
|
-
return false;
|
|
1060
|
-
}
|
|
1061
|
-
switch (info.kind) {
|
|
1062
|
-
case TypeKind.Basic:
|
|
1063
|
-
return matchesBasicType(value, info);
|
|
1064
|
-
case TypeKind.Struct:
|
|
1065
|
-
return matchesStructType(value, info);
|
|
1066
|
-
case TypeKind.Interface:
|
|
1067
|
-
return matchesInterfaceType(value, info);
|
|
1068
|
-
case TypeKind.Map:
|
|
1069
|
-
return matchesMapType(value, info);
|
|
1070
|
-
case TypeKind.Slice:
|
|
1071
|
-
case TypeKind.Array:
|
|
1072
|
-
return matchesArrayOrSliceType(value, info);
|
|
1073
|
-
case TypeKind.Pointer:
|
|
1074
|
-
return matchesPointerType(value, info);
|
|
1075
|
-
case TypeKind.Function:
|
|
1076
|
-
return matchesFunctionType(value, info);
|
|
1077
|
-
case TypeKind.Channel:
|
|
1078
|
-
return matchesChannelType(value, info);
|
|
1079
|
-
default:
|
|
1080
|
-
console.warn(`Type matching for kind '${info.kind}' not implemented.`);
|
|
1081
|
-
return false;
|
|
1082
|
-
}
|
|
1083
|
-
}
|
|
1084
|
-
export function typeAssert(value, typeInfo) {
|
|
1085
|
-
const normalizedType = normalizeTypeInfo(typeInfo);
|
|
1086
|
-
if (isPointerTypeInfo(normalizedType) && value === null) {
|
|
1087
|
-
return { value: null, ok: true };
|
|
1088
|
-
}
|
|
1089
|
-
if (isStructTypeInfo(normalizedType) &&
|
|
1090
|
-
normalizedType.methods && normalizedType.methods.length > 0 &&
|
|
1091
|
-
typeof value === 'object' &&
|
|
1092
|
-
value !== null) {
|
|
1093
|
-
// Check if the value implements all methods of the struct type with compatible signatures.
|
|
1094
|
-
// This is more for interface satisfaction by a struct.
|
|
1095
|
-
// For struct-to-struct assertion, usually instanceof or field checks are primary.
|
|
1096
|
-
const allMethodsMatch = normalizedType.methods.every((requiredMethodSig) => {
|
|
1097
|
-
const actualMethod = value[requiredMethodSig.name];
|
|
1098
|
-
if (typeof actualMethod !== 'function') {
|
|
1099
|
-
return false;
|
|
1100
|
-
}
|
|
1101
|
-
const valueTypeInfoVal = value.$typeInfo;
|
|
1102
|
-
if (valueTypeInfoVal) {
|
|
1103
|
-
const normalizedValueType = normalizeTypeInfo(valueTypeInfoVal);
|
|
1104
|
-
if (isStructTypeInfo(normalizedValueType) || isInterfaceTypeInfo(normalizedValueType)) {
|
|
1105
|
-
const actualValueMethodSig = normalizedValueType.methods.find(m => m.name === requiredMethodSig.name);
|
|
1106
|
-
if (actualValueMethodSig) {
|
|
1107
|
-
// Perform full signature comparison using MethodSignatures
|
|
1108
|
-
const paramsMatch = areMethodArgsArraysIdentical(requiredMethodSig.args, actualValueMethodSig.args);
|
|
1109
|
-
const resultsMatch = areMethodArgsArraysIdentical(requiredMethodSig.returns, actualValueMethodSig.returns);
|
|
1110
|
-
return paramsMatch && resultsMatch;
|
|
1111
|
-
}
|
|
1112
|
-
else {
|
|
1113
|
-
// Value has TypeInfo listing methods, but this specific method isn't listed.
|
|
1114
|
-
// This implies a mismatch for strict signature check based on TypeInfo.
|
|
1115
|
-
return false;
|
|
1116
|
-
}
|
|
1117
|
-
}
|
|
1118
|
-
}
|
|
1119
|
-
// Fallback: Original behavior if value has no TypeInfo that lists methods,
|
|
1120
|
-
// or if the method wasn't found in its TypeInfo (covered by 'else' returning false above).
|
|
1121
|
-
// The original comment was: "For now, presence and function type is checked by matchesStructType/matchesInterfaceType"
|
|
1122
|
-
// This 'return true' implies that if we couldn't do a full signature check via TypeInfo,
|
|
1123
|
-
// we still consider it a match if the function simply exists on the object.
|
|
1124
|
-
return true;
|
|
1125
|
-
});
|
|
1126
|
-
if (allMethodsMatch) {
|
|
1127
|
-
return { value: value, ok: true };
|
|
1128
|
-
}
|
|
1129
|
-
}
|
|
1130
|
-
if (isStructTypeInfo(normalizedType) &&
|
|
1131
|
-
normalizedType.fields &&
|
|
1132
|
-
typeof value === 'object' &&
|
|
1133
|
-
value !== null) {
|
|
1134
|
-
const fieldNames = Object.keys(normalizedType.fields);
|
|
1135
|
-
const valueFields = Object.keys(value);
|
|
1136
|
-
// For struct type assertions, we need exact field matching
|
|
1137
|
-
const structFieldsMatch = fieldNames.length === valueFields.length &&
|
|
1138
|
-
fieldNames.every((field) => field in value) &&
|
|
1139
|
-
valueFields.every((field) => fieldNames.includes(field));
|
|
1140
|
-
if (structFieldsMatch) {
|
|
1141
|
-
const typesMatch = Object.entries(normalizedType.fields).every(([fieldName, fieldType]) => {
|
|
1142
|
-
return matchesType(value[fieldName], normalizeTypeInfo(fieldType));
|
|
1143
|
-
});
|
|
1144
|
-
return { value: value, ok: typesMatch };
|
|
1145
|
-
}
|
|
1146
|
-
else {
|
|
1147
|
-
return { value: null, ok: false };
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
if (isMapTypeInfo(normalizedType) &&
|
|
1151
|
-
typeof value === 'object' &&
|
|
1152
|
-
value !== null) {
|
|
1153
|
-
if (normalizedType.keyType || normalizedType.elemType) {
|
|
1154
|
-
let entries = [];
|
|
1155
|
-
if (value instanceof Map) {
|
|
1156
|
-
entries = Array.from(value.entries());
|
|
1157
|
-
}
|
|
1158
|
-
else {
|
|
1159
|
-
entries = Object.entries(value);
|
|
1160
|
-
}
|
|
1161
|
-
if (entries.length === 0) {
|
|
1162
|
-
return { value: value, ok: true };
|
|
1163
|
-
}
|
|
1164
|
-
const sampleSize = Math.min(5, entries.length);
|
|
1165
|
-
for (let i = 0; i < sampleSize; i++) {
|
|
1166
|
-
const [k, v] = entries[i];
|
|
1167
|
-
if (normalizedType.keyType) {
|
|
1168
|
-
if (!validateMapKey(k, normalizeTypeInfo(normalizedType.keyType))) {
|
|
1169
|
-
return { value: null, ok: false };
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
if (normalizedType.elemType) {
|
|
1173
|
-
const elemTypeInfo = normalizeTypeInfo(normalizedType.elemType);
|
|
1174
|
-
if (!matchesType(v, elemTypeInfo)) {
|
|
1175
|
-
return { value: null, ok: false };
|
|
1176
|
-
}
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
// If we get here, the map type assertion passes
|
|
1180
|
-
return { value: value, ok: true };
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
const matches = matchesType(value, normalizedType);
|
|
1184
|
-
if (matches) {
|
|
1185
|
-
return { value: value, ok: true };
|
|
1186
|
-
}
|
|
1187
|
-
// If we get here, the assertion failed
|
|
1188
|
-
// For registered types, use the zero value from the registry
|
|
1189
|
-
if (typeof typeInfo === 'string') {
|
|
1190
|
-
const registeredType = typeRegistry.get(typeInfo);
|
|
1191
|
-
if (registeredType && registeredType.zeroValue !== undefined) {
|
|
1192
|
-
return { value: registeredType.zeroValue, ok: false };
|
|
1193
|
-
}
|
|
1194
|
-
}
|
|
1195
|
-
else if (normalizedType.zeroValue !== undefined) {
|
|
1196
|
-
return { value: normalizedType.zeroValue, ok: false };
|
|
1197
|
-
}
|
|
1198
|
-
return { value: null, ok: false };
|
|
1199
|
-
}
|
|
1200
|
-
// A simple implementation of buffered channels
|
|
1201
|
-
class BufferedChannel {
|
|
1202
|
-
buffer = [];
|
|
1203
|
-
closed = false;
|
|
1204
|
-
capacity;
|
|
1205
|
-
zeroValue; // Made public for access by ChannelRef or for type inference
|
|
1206
|
-
// Senders queue: stores { value, resolve for send, reject for send }
|
|
1207
|
-
senders = [];
|
|
1208
|
-
// Receivers queue for receive(): stores { resolve for receive, reject for receive }
|
|
1209
|
-
receivers = [];
|
|
1210
|
-
// Receivers queue for receiveWithOk(): stores { resolve for receiveWithOk }
|
|
1211
|
-
receiversWithOk = [];
|
|
1212
|
-
constructor(capacity, zeroValue) {
|
|
1213
|
-
if (capacity < 0) {
|
|
1214
|
-
throw new Error('Channel capacity cannot be negative');
|
|
1215
|
-
}
|
|
1216
|
-
this.capacity = capacity;
|
|
1217
|
-
this.zeroValue = zeroValue;
|
|
1218
|
-
}
|
|
1219
|
-
async send(value) {
|
|
1220
|
-
if (this.closed) {
|
|
1221
|
-
throw new Error('send on closed channel');
|
|
1222
|
-
}
|
|
1223
|
-
// Attempt to hand off to a waiting receiver (rendezvous)
|
|
1224
|
-
if (this.receivers.length > 0) {
|
|
1225
|
-
const receiverTask = this.receivers.shift();
|
|
1226
|
-
queueMicrotask(() => receiverTask.resolveReceive(value));
|
|
1227
|
-
return;
|
|
1228
|
-
}
|
|
1229
|
-
if (this.receiversWithOk.length > 0) {
|
|
1230
|
-
const receiverTask = this.receiversWithOk.shift();
|
|
1231
|
-
queueMicrotask(() => receiverTask.resolveReceive({ value, ok: true }));
|
|
1232
|
-
return;
|
|
1233
|
-
}
|
|
1234
|
-
// If no waiting receivers, try to buffer if space is available
|
|
1235
|
-
if (this.buffer.length < this.capacity) {
|
|
1236
|
-
this.buffer.push(value);
|
|
1237
|
-
return;
|
|
1238
|
-
}
|
|
1239
|
-
// Buffer is full (or capacity is 0 and no receivers are waiting). Sender must block.
|
|
1240
|
-
return new Promise((resolve, reject) => {
|
|
1241
|
-
this.senders.push({ value, resolveSend: resolve, rejectSend: reject });
|
|
1242
|
-
});
|
|
1243
|
-
}
|
|
1244
|
-
async receive() {
|
|
1245
|
-
// Attempt to get from buffer first
|
|
1246
|
-
if (this.buffer.length > 0) {
|
|
1247
|
-
const value = this.buffer.shift();
|
|
1248
|
-
// If a sender was waiting because the buffer was full, unblock it.
|
|
1249
|
-
if (this.senders.length > 0) {
|
|
1250
|
-
const senderTask = this.senders.shift();
|
|
1251
|
-
this.buffer.push(senderTask.value); // Sender's value now goes into buffer
|
|
1252
|
-
queueMicrotask(() => senderTask.resolveSend()); // Unblock sender
|
|
1253
|
-
}
|
|
1254
|
-
return value;
|
|
1255
|
-
}
|
|
1256
|
-
// Buffer is empty.
|
|
1257
|
-
// If channel is closed (and buffer is empty), subsequent receives panic.
|
|
1258
|
-
if (this.closed) {
|
|
1259
|
-
throw new Error('receive on closed channel');
|
|
1260
|
-
}
|
|
1261
|
-
// Buffer is empty, channel is open.
|
|
1262
|
-
// Attempt to rendezvous with a waiting sender.
|
|
1263
|
-
if (this.senders.length > 0) {
|
|
1264
|
-
const senderTask = this.senders.shift();
|
|
1265
|
-
queueMicrotask(() => senderTask.resolveSend()); // Unblock the sender
|
|
1266
|
-
return senderTask.value; // Return the value from sender
|
|
1267
|
-
}
|
|
1268
|
-
// Buffer is empty, channel is open, no waiting senders. Receiver must block.
|
|
1269
|
-
return new Promise((resolve, reject) => {
|
|
1270
|
-
this.receivers.push({ resolveReceive: resolve, rejectReceive: reject });
|
|
1271
|
-
});
|
|
1272
|
-
}
|
|
1273
|
-
async receiveWithOk() {
|
|
1274
|
-
// Attempt to get from buffer first
|
|
1275
|
-
if (this.buffer.length > 0) {
|
|
1276
|
-
const value = this.buffer.shift();
|
|
1277
|
-
if (this.senders.length > 0) {
|
|
1278
|
-
const senderTask = this.senders.shift();
|
|
1279
|
-
this.buffer.push(senderTask.value);
|
|
1280
|
-
queueMicrotask(() => senderTask.resolveSend());
|
|
1281
|
-
}
|
|
1282
|
-
return { value, ok: true };
|
|
1283
|
-
}
|
|
1284
|
-
// Buffer is empty.
|
|
1285
|
-
// Attempt to rendezvous with a waiting sender.
|
|
1286
|
-
if (this.senders.length > 0) {
|
|
1287
|
-
const senderTask = this.senders.shift();
|
|
1288
|
-
queueMicrotask(() => senderTask.resolveSend());
|
|
1289
|
-
return { value: senderTask.value, ok: true };
|
|
1290
|
-
}
|
|
1291
|
-
// Buffer is empty, no waiting senders.
|
|
1292
|
-
// If channel is closed, return zero value with ok: false.
|
|
1293
|
-
if (this.closed) {
|
|
1294
|
-
return { value: this.zeroValue, ok: false };
|
|
1295
|
-
}
|
|
1296
|
-
// Buffer is empty, channel is open, no waiting senders. Receiver must block.
|
|
1297
|
-
return new Promise((resolve) => {
|
|
1298
|
-
this.receiversWithOk.push({ resolveReceive: resolve });
|
|
1299
|
-
});
|
|
1300
|
-
}
|
|
1301
|
-
async selectReceive(id) {
|
|
1302
|
-
if (this.buffer.length > 0) {
|
|
1303
|
-
const value = this.buffer.shift();
|
|
1304
|
-
if (this.senders.length > 0) {
|
|
1305
|
-
const senderTask = this.senders.shift();
|
|
1306
|
-
this.buffer.push(senderTask.value);
|
|
1307
|
-
queueMicrotask(() => senderTask.resolveSend());
|
|
1308
|
-
}
|
|
1309
|
-
return { value, ok: true, id };
|
|
1310
|
-
}
|
|
1311
|
-
if (this.senders.length > 0) {
|
|
1312
|
-
const senderTask = this.senders.shift();
|
|
1313
|
-
queueMicrotask(() => senderTask.resolveSend());
|
|
1314
|
-
return { value: senderTask.value, ok: true, id };
|
|
1315
|
-
}
|
|
1316
|
-
if (this.closed) {
|
|
1317
|
-
return { value: this.zeroValue, ok: false, id };
|
|
1318
|
-
}
|
|
1319
|
-
return new Promise((resolve) => {
|
|
1320
|
-
this.receiversWithOk.push({
|
|
1321
|
-
resolveReceive: (result) => {
|
|
1322
|
-
resolve({ ...result, id });
|
|
1323
|
-
},
|
|
1324
|
-
});
|
|
1325
|
-
});
|
|
1326
|
-
}
|
|
1327
|
-
async selectSend(value, id) {
|
|
1328
|
-
if (this.closed) {
|
|
1329
|
-
// A select case sending on a closed channel panics in Go.
|
|
1330
|
-
// This will cause Promise.race in selectStatement to reject.
|
|
1331
|
-
throw new Error('send on closed channel');
|
|
1332
|
-
}
|
|
1333
|
-
if (this.receivers.length > 0) {
|
|
1334
|
-
const receiverTask = this.receivers.shift();
|
|
1335
|
-
queueMicrotask(() => receiverTask.resolveReceive(value));
|
|
1336
|
-
return { value: true, ok: true, id };
|
|
1337
|
-
}
|
|
1338
|
-
if (this.receiversWithOk.length > 0) {
|
|
1339
|
-
const receiverTask = this.receiversWithOk.shift();
|
|
1340
|
-
queueMicrotask(() => receiverTask.resolveReceive({ value, ok: true }));
|
|
1341
|
-
return { value: true, ok: true, id };
|
|
1342
|
-
}
|
|
1343
|
-
if (this.buffer.length < this.capacity) {
|
|
1344
|
-
this.buffer.push(value);
|
|
1345
|
-
return { value: true, ok: true, id };
|
|
1346
|
-
}
|
|
1347
|
-
return new Promise((resolve, reject) => {
|
|
1348
|
-
this.senders.push({
|
|
1349
|
-
value,
|
|
1350
|
-
resolveSend: () => resolve({ value: true, ok: true, id }),
|
|
1351
|
-
rejectSend: (e) => reject(e), // Propagate error if channel closes
|
|
1352
|
-
});
|
|
1353
|
-
});
|
|
1354
|
-
}
|
|
1355
|
-
close() {
|
|
1356
|
-
if (this.closed) {
|
|
1357
|
-
throw new Error('close of closed channel');
|
|
1358
|
-
}
|
|
1359
|
-
this.closed = true;
|
|
1360
|
-
const sendersToNotify = [...this.senders]; // Shallow copy for iteration
|
|
1361
|
-
this.senders = [];
|
|
1362
|
-
for (const senderTask of sendersToNotify) {
|
|
1363
|
-
queueMicrotask(() => senderTask.rejectSend(new Error('send on closed channel')));
|
|
1364
|
-
}
|
|
1365
|
-
const receiversToNotify = [...this.receivers];
|
|
1366
|
-
this.receivers = [];
|
|
1367
|
-
for (const receiverTask of receiversToNotify) {
|
|
1368
|
-
queueMicrotask(() => receiverTask.rejectReceive(new Error('receive on closed channel')));
|
|
1369
|
-
}
|
|
1370
|
-
const receiversWithOkToNotify = [...this.receiversWithOk];
|
|
1371
|
-
this.receiversWithOk = [];
|
|
1372
|
-
for (const receiverTask of receiversWithOkToNotify) {
|
|
1373
|
-
queueMicrotask(() => receiverTask.resolveReceive({ value: this.zeroValue, ok: false }));
|
|
1374
|
-
}
|
|
1375
|
-
}
|
|
1376
|
-
canReceiveNonBlocking() {
|
|
1377
|
-
return this.buffer.length > 0 || this.senders.length > 0 || this.closed;
|
|
1378
|
-
}
|
|
1379
|
-
canSendNonBlocking() {
|
|
1380
|
-
if (this.closed) {
|
|
1381
|
-
return true; // Ready to panic
|
|
1382
|
-
}
|
|
1383
|
-
return (this.buffer.length < this.capacity ||
|
|
1384
|
-
this.receivers.length > 0 ||
|
|
1385
|
-
this.receiversWithOk.length > 0);
|
|
1386
|
-
}
|
|
1387
|
-
}
|
|
1388
|
-
/**
|
|
1389
|
-
* A bidirectional channel reference.
|
|
1390
|
-
*/
|
|
1391
|
-
export class BidirectionalChannelRef {
|
|
1392
|
-
channel;
|
|
1393
|
-
direction = 'both';
|
|
1394
|
-
constructor(channel) {
|
|
1395
|
-
this.channel = channel;
|
|
1396
|
-
}
|
|
1397
|
-
// Delegate all methods to the underlying channel
|
|
1398
|
-
send(value) {
|
|
1399
|
-
return this.channel.send(value);
|
|
1400
|
-
}
|
|
1401
|
-
receive() {
|
|
1402
|
-
return this.channel.receive();
|
|
1403
|
-
}
|
|
1404
|
-
receiveWithOk() {
|
|
1405
|
-
return this.channel.receiveWithOk();
|
|
1406
|
-
}
|
|
1407
|
-
close() {
|
|
1408
|
-
this.channel.close();
|
|
1409
|
-
}
|
|
1410
|
-
canSendNonBlocking() {
|
|
1411
|
-
return this.channel.canSendNonBlocking();
|
|
1412
|
-
}
|
|
1413
|
-
canReceiveNonBlocking() {
|
|
1414
|
-
return this.channel.canReceiveNonBlocking();
|
|
1415
|
-
}
|
|
1416
|
-
selectSend(value, id) {
|
|
1417
|
-
return this.channel.selectSend(value, id);
|
|
1418
|
-
}
|
|
1419
|
-
selectReceive(id) {
|
|
1420
|
-
return this.channel.selectReceive(id);
|
|
1421
|
-
}
|
|
1422
|
-
}
|
|
1423
|
-
/**
|
|
1424
|
-
* A send-only channel reference.
|
|
1425
|
-
*/
|
|
1426
|
-
export class SendOnlyChannelRef {
|
|
1427
|
-
channel;
|
|
1428
|
-
direction = 'send';
|
|
1429
|
-
constructor(channel) {
|
|
1430
|
-
this.channel = channel;
|
|
1431
|
-
}
|
|
1432
|
-
// Allow send operations
|
|
1433
|
-
send(value) {
|
|
1434
|
-
return this.channel.send(value);
|
|
1435
|
-
}
|
|
1436
|
-
// Allow close operations
|
|
1437
|
-
close() {
|
|
1438
|
-
this.channel.close();
|
|
1439
|
-
}
|
|
1440
|
-
canSendNonBlocking() {
|
|
1441
|
-
return this.channel.canSendNonBlocking();
|
|
1442
|
-
}
|
|
1443
|
-
selectSend(value, id) {
|
|
1444
|
-
return this.channel.selectSend(value, id);
|
|
1445
|
-
}
|
|
1446
|
-
// Disallow receive operations
|
|
1447
|
-
receive() {
|
|
1448
|
-
throw new Error('Cannot receive from send-only channel');
|
|
1449
|
-
}
|
|
1450
|
-
receiveWithOk() {
|
|
1451
|
-
throw new Error('Cannot receive from send-only channel');
|
|
1452
|
-
}
|
|
1453
|
-
canReceiveNonBlocking() {
|
|
1454
|
-
return false;
|
|
1455
|
-
}
|
|
1456
|
-
selectReceive(id) {
|
|
1457
|
-
throw new Error('Cannot receive from send-only channel');
|
|
1458
|
-
}
|
|
1459
|
-
}
|
|
1460
|
-
/**
|
|
1461
|
-
* A receive-only channel reference.
|
|
1462
|
-
*/
|
|
1463
|
-
export class ReceiveOnlyChannelRef {
|
|
1464
|
-
channel;
|
|
1465
|
-
direction = 'receive';
|
|
1466
|
-
constructor(channel) {
|
|
1467
|
-
this.channel = channel;
|
|
1468
|
-
}
|
|
1469
|
-
// Allow receive operations
|
|
1470
|
-
receive() {
|
|
1471
|
-
return this.channel.receive();
|
|
1472
|
-
}
|
|
1473
|
-
receiveWithOk() {
|
|
1474
|
-
return this.channel.receiveWithOk();
|
|
1475
|
-
}
|
|
1476
|
-
canReceiveNonBlocking() {
|
|
1477
|
-
return this.channel.canReceiveNonBlocking();
|
|
1478
|
-
}
|
|
1479
|
-
selectReceive(id) {
|
|
1480
|
-
return this.channel.selectReceive(id);
|
|
1481
|
-
}
|
|
1482
|
-
// Disallow send operations
|
|
1483
|
-
send(value) {
|
|
1484
|
-
throw new Error('Cannot send to receive-only channel');
|
|
1485
|
-
}
|
|
1486
|
-
// Disallow close operations
|
|
1487
|
-
close() {
|
|
1488
|
-
throw new Error('Cannot close receive-only channel');
|
|
1489
|
-
}
|
|
1490
|
-
canSendNonBlocking() {
|
|
1491
|
-
return false;
|
|
1492
|
-
}
|
|
1493
|
-
selectSend(value, id) {
|
|
1494
|
-
throw new Error('Cannot send to receive-only channel');
|
|
1495
|
-
}
|
|
1496
|
-
}
|
|
1497
|
-
/**
|
|
1498
|
-
* Creates a new channel reference with the specified direction.
|
|
1499
|
-
*/
|
|
1500
|
-
export function makeChannelRef(channel, direction) {
|
|
1501
|
-
switch (direction) {
|
|
1502
|
-
case 'send':
|
|
1503
|
-
return new SendOnlyChannelRef(channel);
|
|
1504
|
-
case 'receive':
|
|
1505
|
-
return new ReceiveOnlyChannelRef(channel);
|
|
1506
|
-
default: // 'both'
|
|
1507
|
-
return new BidirectionalChannelRef(channel);
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
/**
|
|
1511
|
-
* Helper for 'select' statements. Takes an array of select cases
|
|
1512
|
-
* and resolves when one of them completes, following Go's select rules.
|
|
1513
|
-
*
|
|
1514
|
-
* @param cases Array of SelectCase objects
|
|
1515
|
-
* @param hasDefault Whether there is a default case
|
|
1516
|
-
* @returns A promise that resolves with the result of the selected case
|
|
1517
|
-
*/
|
|
1518
|
-
export async function selectStatement(cases, hasDefault = false) {
|
|
1519
|
-
if (cases.length === 0 && !hasDefault) {
|
|
1520
|
-
// Go spec: If there are no cases, the select statement blocks forever.
|
|
1521
|
-
// Emulate blocking forever with a promise that never resolves.
|
|
1522
|
-
return new Promise(() => { }); // Promise never resolves
|
|
1523
|
-
}
|
|
1524
|
-
// 1. Check for ready (non-blocking) operations
|
|
1525
|
-
const readyCases = [];
|
|
1526
|
-
for (const caseObj of cases) {
|
|
1527
|
-
if (caseObj.id === -1) {
|
|
1528
|
-
// Skip default case in this check
|
|
1529
|
-
continue;
|
|
1530
|
-
}
|
|
1531
|
-
// Add check for channel existence
|
|
1532
|
-
if (caseObj.channel) {
|
|
1533
|
-
if (caseObj.isSend && caseObj.channel.canSendNonBlocking()) {
|
|
1534
|
-
readyCases.push(caseObj);
|
|
1535
|
-
}
|
|
1536
|
-
else if (!caseObj.isSend && caseObj.channel.canReceiveNonBlocking()) {
|
|
1537
|
-
readyCases.push(caseObj);
|
|
1538
|
-
}
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
if (readyCases.length > 0) {
|
|
1542
|
-
// If one or more cases are ready, choose one pseudo-randomly
|
|
1543
|
-
const selectedCase = readyCases[Math.floor(Math.random() * readyCases.length)];
|
|
1544
|
-
// Execute the selected operation and its onSelected handler
|
|
1545
|
-
// Add check for channel existence
|
|
1546
|
-
if (selectedCase.channel) {
|
|
1547
|
-
if (selectedCase.isSend) {
|
|
1548
|
-
const result = await selectedCase.channel.selectSend(selectedCase.value, selectedCase.id);
|
|
1549
|
-
if (selectedCase.onSelected) {
|
|
1550
|
-
await selectedCase.onSelected(result); // Await the handler
|
|
1551
|
-
}
|
|
1552
|
-
}
|
|
1553
|
-
else {
|
|
1554
|
-
const result = await selectedCase.channel.selectReceive(selectedCase.id);
|
|
1555
|
-
if (selectedCase.onSelected) {
|
|
1556
|
-
await selectedCase.onSelected(result); // Await the handler
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
}
|
|
1560
|
-
else {
|
|
1561
|
-
// This case should ideally not happen if channel is required for non-default cases
|
|
1562
|
-
console.error('Selected case without a channel:', selectedCase);
|
|
1563
|
-
}
|
|
1564
|
-
return; // Return after executing a ready case
|
|
1565
|
-
}
|
|
1566
|
-
// 2. If no operations are ready and there's a default case, select default
|
|
1567
|
-
if (hasDefault) {
|
|
1568
|
-
// Find the default case (it will have id -1)
|
|
1569
|
-
const defaultCase = cases.find((c) => c.id === -1);
|
|
1570
|
-
if (defaultCase && defaultCase.onSelected) {
|
|
1571
|
-
// Execute the onSelected handler for the default case
|
|
1572
|
-
await defaultCase.onSelected({
|
|
1573
|
-
value: undefined,
|
|
1574
|
-
ok: false,
|
|
1575
|
-
id: -1,
|
|
1576
|
-
}); // Await the handler
|
|
1577
|
-
}
|
|
1578
|
-
return; // Return after executing the default case
|
|
1579
|
-
}
|
|
1580
|
-
// 3. If no operations are ready and no default case, block until one is ready
|
|
1581
|
-
// Use Promise.race on the blocking promises
|
|
1582
|
-
const blockingPromises = cases
|
|
1583
|
-
.filter((c) => c.id !== -1)
|
|
1584
|
-
.map((caseObj) => {
|
|
1585
|
-
// Exclude default case
|
|
1586
|
-
// Add check for channel existence (though it should always exist here)
|
|
1587
|
-
if (caseObj.channel) {
|
|
1588
|
-
if (caseObj.isSend) {
|
|
1589
|
-
return caseObj.channel.selectSend(caseObj.value, caseObj.id);
|
|
1590
|
-
}
|
|
1591
|
-
else {
|
|
1592
|
-
return caseObj.channel.selectReceive(caseObj.id);
|
|
1593
|
-
}
|
|
1594
|
-
}
|
|
1595
|
-
// Return a promise that never resolves if channel is somehow missing
|
|
1596
|
-
return new Promise(() => { });
|
|
1597
|
-
});
|
|
1598
|
-
const result = await Promise.race(blockingPromises);
|
|
1599
|
-
// Execute onSelected handler for the selected case
|
|
1600
|
-
const selectedCase = cases.find((c) => c.id === result.id);
|
|
1601
|
-
if (selectedCase && selectedCase.onSelected) {
|
|
1602
|
-
await selectedCase.onSelected(result); // Await the handler
|
|
1603
|
-
}
|
|
1604
|
-
// No explicit return needed here, as the function will implicitly return after the await
|
|
1605
|
-
}
|
|
1606
|
-
/**
|
|
1607
|
-
* Creates a new channel with the specified buffer size and zero value.
|
|
1608
|
-
* @param bufferSize The size of the channel buffer. If 0, creates an unbuffered channel.
|
|
1609
|
-
* @param zeroValue The zero value for the channel's element type.
|
|
1610
|
-
* @param direction Optional direction for the channel. Default is 'both' (bidirectional).
|
|
1611
|
-
* @returns A new channel instance or channel reference.
|
|
1612
|
-
*/
|
|
1613
|
-
export const makeChannel = (bufferSize, zeroValue, direction = 'both') => {
|
|
1614
|
-
const channel = new BufferedChannel(bufferSize, zeroValue);
|
|
1615
|
-
// Wrap the channel with the appropriate ChannelRef based on direction
|
|
1616
|
-
if (direction === 'send') {
|
|
1617
|
-
return new SendOnlyChannelRef(channel);
|
|
1618
|
-
}
|
|
1619
|
-
else if (direction === 'receive') {
|
|
1620
|
-
return new ReceiveOnlyChannelRef(channel);
|
|
1621
|
-
}
|
|
1622
|
-
else {
|
|
1623
|
-
return channel;
|
|
1624
|
-
}
|
|
1625
|
-
};
|
|
1626
|
-
/**
|
|
1627
|
-
* DisposableStack manages synchronous disposable resources, mimicking Go's defer behavior.
|
|
1628
|
-
* Functions added via `defer` are executed in LIFO order when the stack is disposed.
|
|
1629
|
-
* Implements the `Disposable` interface for use with `using` declarations.
|
|
1630
|
-
*/
|
|
1631
|
-
export class DisposableStack {
|
|
1632
|
-
stack = [];
|
|
1633
|
-
/**
|
|
1634
|
-
* Adds a function to be executed when the stack is disposed.
|
|
1635
|
-
* @param fn The function to defer.
|
|
1636
|
-
*/
|
|
1637
|
-
defer(fn) {
|
|
1638
|
-
this.stack.push(fn);
|
|
1639
|
-
}
|
|
1640
|
-
/**
|
|
1641
|
-
* Disposes of the resources in the stack by executing the deferred functions
|
|
1642
|
-
* in Last-In, First-Out (LIFO) order.
|
|
1643
|
-
* If a deferred function throws an error, disposal stops, and the error is rethrown,
|
|
1644
|
-
* similar to Go's panic behavior during defer execution.
|
|
1645
|
-
*/
|
|
1646
|
-
[Symbol.dispose]() {
|
|
1647
|
-
// Emulate Go: if a deferred throws, stop and rethrow
|
|
1648
|
-
while (this.stack.length) {
|
|
1649
|
-
const fn = this.stack.pop();
|
|
1650
|
-
fn();
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
}
|
|
1654
|
-
/**
|
|
1655
|
-
* AsyncDisposableStack manages asynchronous disposable resources, mimicking Go's defer behavior.
|
|
1656
|
-
* Functions added via `defer` are executed sequentially in LIFO order when the stack is disposed.
|
|
1657
|
-
* Implements the `AsyncDisposable` interface for use with `await using` declarations.
|
|
1658
|
-
*/
|
|
1659
|
-
export class AsyncDisposableStack {
|
|
1660
|
-
stack = [];
|
|
1661
|
-
/**
|
|
1662
|
-
* Adds a synchronous or asynchronous function to be executed when the stack is disposed.
|
|
1663
|
-
* @param fn The function to defer. Can return void or a Promise<void>.
|
|
1664
|
-
*/
|
|
1665
|
-
defer(fn) {
|
|
1666
|
-
this.stack.push(fn);
|
|
1667
|
-
}
|
|
1668
|
-
/**
|
|
1669
|
-
* Asynchronously disposes of the resources in the stack by executing the deferred functions
|
|
1670
|
-
* sequentially in Last-In, First-Out (LIFO) order. It awaits each function if it returns a promise.
|
|
1671
|
-
*/
|
|
1672
|
-
async [Symbol.asyncDispose]() {
|
|
1673
|
-
// Execute in LIFO order, awaiting each potentially async function
|
|
1674
|
-
for (let i = this.stack.length - 1; i >= 0; --i) {
|
|
1675
|
-
await this.stack[i]();
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
}
|
|
1679
|
-
/**
|
|
1680
|
-
* Implementation of Go's built-in println function
|
|
1681
|
-
* @param args Arguments to print
|
|
1682
|
-
*/
|
|
1683
|
-
export function println(...args) {
|
|
1684
|
-
console.log(...args);
|
|
1685
|
-
}
|
|
1686
|
-
//# sourceMappingURL=builtin.js.map
|