typenative 0.3.0 → 0.4.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/CHANGELOG.md +71 -0
- package/README.md +17 -1
- package/bin/cli.js +25 -11
- package/bin/go/convert.js +11 -1
- package/bin/index.js +221 -44
- package/bin/main.js +35 -14
- package/bin/node/assert.js +2 -2
- package/bin/node/buffer.js +9 -0
- package/bin/node/dns.js +1 -1
- package/bin/node/events.js +1 -1
- package/bin/node/fs.js +1 -1
- package/bin/node/fs_watch.js +407 -0
- package/bin/node/http2.js +33 -6
- package/bin/node/readline.js +1 -1
- package/bin/node/registry.js +2 -1
- package/bin/node/stream.js +6 -3
- package/bin/node/timers.js +1 -1
- package/bin/node/tls.js +3 -1
- package/bin/node/typed_arrays.js +608 -0
- package/bin/node/util.js +3 -0
- package/bin/node/zlib.js +131 -16
- package/bin/transpiler.js +684 -62
- package/bin/version.js +1 -1
- package/conformance.md +16 -4
- package/examples/README.md +54 -0
- package/examples/fibonacci/README.md +89 -0
- package/examples/fibonacci/bench.mjs +87 -0
- package/examples/fibonacci/main.ts +21 -0
- package/examples/hello-world/README.md +62 -0
- package/examples/hello-world/bench.mjs +66 -0
- package/examples/hello-world/main.ts +7 -0
- package/examples/json-server/README.md +125 -0
- package/examples/json-server/bench.mjs +171 -0
- package/examples/json-server/main.ts +67 -0
- package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
- package/govendor/github.com/andybalholm/brotli/README.md +19 -0
- package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
- package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
- package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
- package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
- package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
- package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
- package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
- package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
- package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
- package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
- package/govendor/github.com/andybalholm/brotli/command.go +254 -0
- package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
- package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
- package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
- package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
- package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
- package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
- package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
- package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
- package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
- package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
- package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
- package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
- package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
- package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
- package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
- package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
- package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
- package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
- package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
- package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
- package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
- package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
- package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
- package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
- package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
- package/govendor/github.com/andybalholm/brotli/http.go +201 -0
- package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
- package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
- package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
- package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
- package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
- package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
- package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
- package/govendor/github.com/andybalholm/brotli/params.go +37 -0
- package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
- package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
- package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
- package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
- package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
- package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
- package/govendor/github.com/andybalholm/brotli/state.go +313 -0
- package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
- package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
- package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
- package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
- package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
- package/govendor/github.com/andybalholm/brotli/util.go +7 -0
- package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
- package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
- package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
- package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
- package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
- package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
- package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
- package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
- package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
- package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
- package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
- package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
- package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
- package/govendor/manifest.txt +3 -1
- package/package.json +1 -1
- package/types/typenative-npm.d.ts +72 -0
- package/types/typenative.d.ts +117 -1
package/bin/transpiler.js
CHANGED
|
@@ -18,6 +18,8 @@ import { registerStringDecoder } from './node/string_decoder.js';
|
|
|
18
18
|
import { registerCrypto } from './node/crypto.js';
|
|
19
19
|
import { registerCryptoKeys } from './node/crypto_keys.js';
|
|
20
20
|
import { registerZlib } from './node/zlib.js';
|
|
21
|
+
import { registerFsWatch } from './node/fs_watch.js';
|
|
22
|
+
import { registerTypedArrays, isTypedArrayGoType } from './node/typed_arrays.js';
|
|
21
23
|
import { registerTimers } from './node/timers.js';
|
|
22
24
|
import { registerEvents } from './node/events.js';
|
|
23
25
|
import { registerStream } from './node/stream.js';
|
|
@@ -348,6 +350,9 @@ const generatorFunctionNames = new Set();
|
|
|
348
350
|
// While emitting an async/generator function body: `return`/`yield` send here
|
|
349
351
|
let asyncChannelVar;
|
|
350
352
|
let asyncFunctionNode;
|
|
353
|
+
// True while emitting the body of an async function (not a generator): its
|
|
354
|
+
// return settles the promise (ordered wake); a generator's sends stay raw
|
|
355
|
+
let asyncChannelIsAsync = false;
|
|
351
356
|
// Variables holding JS arrays: stored as *[]T so aliasing shares the slice
|
|
352
357
|
// header (push/splice through any alias are visible everywhere)
|
|
353
358
|
const referenceArrays = new Set();
|
|
@@ -503,6 +508,9 @@ function sourceFileIndexOf(node) {
|
|
|
503
508
|
// A line holding only this sentinel becomes //line <go file>:<next line>,
|
|
504
509
|
// which returns the following generated code (helpers) to its real Go position
|
|
505
510
|
const LINE_RESET = '/*tn@' + 'reset*/';
|
|
511
|
+
// First line of every generated Go file (Go's convention for generated code;
|
|
512
|
+
// the CLI only deletes stale .go files that start with it)
|
|
513
|
+
export const GENERATED_HEADER = '// Code generated by TypeNative. DO NOT EDIT.';
|
|
506
514
|
function lineMarker(node) {
|
|
507
515
|
if (!node?.line)
|
|
508
516
|
return '';
|
|
@@ -1021,6 +1029,7 @@ export function transpileToNative(code, options) {
|
|
|
1021
1029
|
usedHelpers.clear();
|
|
1022
1030
|
helperProvidedPackages.clear();
|
|
1023
1031
|
mainPackageVariables.length = 0;
|
|
1032
|
+
goInterfaceAdapters.clear();
|
|
1024
1033
|
const transpiledCode = visit(sourceFile, { addFunctionOutside: true });
|
|
1025
1034
|
const transpiledCodeOutside = outsideNodes.map((n) => withLineMarker(n, visit(n, { isOutside: true }))).join('\n');
|
|
1026
1035
|
// Keep the process alive until detached async work and timers settle
|
|
@@ -1056,7 +1065,9 @@ export function transpileToNative(code, options) {
|
|
|
1056
1065
|
: goImportLine(pkg);
|
|
1057
1066
|
// process.on('uncaughtException'): a throw in the top-level code is handed to it too
|
|
1058
1067
|
const body = usedHelpers.has('nodeUncaught') ? `func() {\n\tdefer TnMainRecover()\n\t${mainCode.trim()}\n\t}()` : mainCode.trim();
|
|
1059
|
-
const main =
|
|
1068
|
+
const main = `${GENERATED_HEADER}
|
|
1069
|
+
|
|
1070
|
+
package main
|
|
1060
1071
|
|
|
1061
1072
|
${mainImports.sort().map((pkg) => importLine(pkg)).join('\n')}
|
|
1062
1073
|
|
|
@@ -1280,11 +1291,21 @@ function visit(node, options = {}) {
|
|
|
1280
1291
|
if (isStringLiteral(node.argumentExpression)) {
|
|
1281
1292
|
return `${visit(node.expression)}[${visit(node.argumentExpression)}]`;
|
|
1282
1293
|
}
|
|
1294
|
+
// Typed array elements read as numbers (out of range: 0)
|
|
1295
|
+
if (isTypedArrayGoType(targetType) && !isAssignmentTarget(node)) {
|
|
1296
|
+
return `${visit(node.expression)}.Get(${visit(node.argumentExpression)})`;
|
|
1297
|
+
}
|
|
1283
1298
|
// Buffer / Uint8Array elements read as numbers
|
|
1284
1299
|
if (targetType === '[]byte' && !isAssignmentTarget(node)) {
|
|
1285
1300
|
useHelper('dynamic');
|
|
1286
1301
|
return `float64(TnAt(${visit(node.expression)}, ${visit(node.argumentExpression)}))`;
|
|
1287
1302
|
}
|
|
1303
|
+
// pair[0] on a [string, number] tuple ([]interface{}): the element's type
|
|
1304
|
+
const tupleElement = tupleElementGoType(node);
|
|
1305
|
+
if (tupleElement && !isAssignmentTarget(node)) {
|
|
1306
|
+
useHelper('dynamic');
|
|
1307
|
+
return `TnAs[${tupleElement}](TnAt(${visit(node.expression)}, ${visit(node.argumentExpression)}))`;
|
|
1308
|
+
}
|
|
1288
1309
|
// Reading past the end of an array gives undefined in JS: the zero value here
|
|
1289
1310
|
if (targetType?.startsWith('[]') && !isAssignmentTarget(node)) {
|
|
1290
1311
|
useHelper('dynamic');
|
|
@@ -1514,6 +1535,10 @@ function visit(node, options = {}) {
|
|
|
1514
1535
|
variableTypeNodes.set(node.name.text, node.type);
|
|
1515
1536
|
else
|
|
1516
1537
|
variableTypeNodes.delete(node.name.text);
|
|
1538
|
+
if (node.initializer && isArrayBufferExpression(node.initializer))
|
|
1539
|
+
arrayBufferVariables.add(node.name.text);
|
|
1540
|
+
else
|
|
1541
|
+
arrayBufferVariables.delete(node.name.text);
|
|
1517
1542
|
if (node.initializer && isGoRefCall(node.initializer))
|
|
1518
1543
|
goRefVariables.add(node.name.text);
|
|
1519
1544
|
else
|
|
@@ -1626,6 +1651,9 @@ function visit(node, options = {}) {
|
|
|
1626
1651
|
return visitNullablePrimitiveOptionalCall(node, visit(node.expression.expression), receiverType);
|
|
1627
1652
|
}
|
|
1628
1653
|
}
|
|
1654
|
+
const typedArrayCall = visitTypedArrayCall(node);
|
|
1655
|
+
if (typedArrayCall !== undefined)
|
|
1656
|
+
return typedArrayCall;
|
|
1629
1657
|
const nodeCall = visitNodeCall(node);
|
|
1630
1658
|
if (nodeCall !== undefined)
|
|
1631
1659
|
return nodeCall;
|
|
@@ -1714,6 +1742,9 @@ function visit(node, options = {}) {
|
|
|
1714
1742
|
node.expression.expression.text === 'Array' &&
|
|
1715
1743
|
node.expression.name.text === 'from') {
|
|
1716
1744
|
const sourceNode = (node.arguments ?? [])[0];
|
|
1745
|
+
if (isTypedArrayGoType(inferExpressionType(sourceNode)) && (node.arguments ?? []).length === 1) {
|
|
1746
|
+
return `${visit(sourceNode)}.tnFloats()`;
|
|
1747
|
+
}
|
|
1717
1748
|
const callbackNode = (node.arguments ?? [])[1];
|
|
1718
1749
|
const paramTypes = ['interface{}', 'float64'];
|
|
1719
1750
|
if (callbackNode && (isArrowFunction(callbackNode) || isFunctionExpression(callbackNode))) {
|
|
@@ -1818,6 +1849,14 @@ function visit(node, options = {}) {
|
|
|
1818
1849
|
useHelper('error');
|
|
1819
1850
|
return `TnIsErrorOf(${visit(node.left)}, ${toGoStringLiteral(node.right.text)})`;
|
|
1820
1851
|
}
|
|
1852
|
+
if (node.operatorToken.kind === 'InstanceOfKeyword' && isIdentifier(node.right) && !classNames.has(node.right.text)) {
|
|
1853
|
+
// x instanceof Int32Array / URL / …: a Node global class's Go type
|
|
1854
|
+
const nodeClassKey = nodeClassKeyOfName(node.right.text);
|
|
1855
|
+
const nodeClass = nodeClassKey ? nodeRegistry.classes[nodeClassKey] : undefined;
|
|
1856
|
+
if (nodeClass) {
|
|
1857
|
+
return `func() bool { _, ok := interface{}(${visit(node.left)}).(${nodeClass.goType}); return ok }()`;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1821
1860
|
if (node.operatorToken.kind === 'InstanceOfKeyword' && isIdentifier(node.right)) {
|
|
1822
1861
|
// x instanceof C: the runtime type is C's pointer type
|
|
1823
1862
|
return `func() bool { _, ok := interface{}(${visit(node.left)}).(*${getSafeName(node.right.text)}); return ok }()`;
|
|
@@ -1995,6 +2034,12 @@ function visit(node, options = {}) {
|
|
|
1995
2034
|
const goFieldAssignment = visitGoFieldAssignment(node, op);
|
|
1996
2035
|
if (goFieldAssignment !== undefined)
|
|
1997
2036
|
return goFieldAssignment;
|
|
2037
|
+
// ta[i] = v / ta[i] op= v on a typed array: Set converts to the element type
|
|
2038
|
+
if (isElementAccessExpression(node.left) && isTypedArrayGoType(inferExpressionType(node.left.expression))) {
|
|
2039
|
+
const typedAssignment = visitTypedArrayAssignment(node.left, op, node.right);
|
|
2040
|
+
if (typedAssignment !== undefined)
|
|
2041
|
+
return typedAssignment;
|
|
2042
|
+
}
|
|
1998
2043
|
// buf[i] = v on a Buffer / Uint8Array: bytes wrap modulo 256
|
|
1999
2044
|
if (op === '=' && isElementAccessExpression(node.left) && inferExpressionType(node.left.expression) === '[]byte') {
|
|
2000
2045
|
useHelper('buffer');
|
|
@@ -2079,10 +2124,17 @@ function visit(node, options = {}) {
|
|
|
2079
2124
|
return '';
|
|
2080
2125
|
}
|
|
2081
2126
|
else if (isAwaitExpression(node)) {
|
|
2082
|
-
// Promises are channels:
|
|
2083
|
-
// (a bare receive would block it
|
|
2127
|
+
// Promises are channels: the await keeps the event loop running while it
|
|
2128
|
+
// waits (a bare receive would block it). Inside an async function body —
|
|
2129
|
+
// a goroutine of its own — TnAwait parks for the ordered wake (promise
|
|
2130
|
+
// continuations resume in settlement order); an await in code running
|
|
2131
|
+
// inline on the loop goroutine (an async callback) must keep draining the
|
|
2132
|
+
// loop itself
|
|
2084
2133
|
useHelper('promise');
|
|
2085
|
-
|
|
2134
|
+
const awaitFn = asyncChannelVar && asyncChannelIsAsync && getEnclosingFunction(node) === asyncFunctionNode
|
|
2135
|
+
? 'TnAwait'
|
|
2136
|
+
: 'TnAwaitInline';
|
|
2137
|
+
return `${awaitFn}(${visit(node.expression)})`;
|
|
2086
2138
|
}
|
|
2087
2139
|
else if (isVariableDeclarationList(node)) {
|
|
2088
2140
|
return ((node.declarations ?? []).map((n) => visit(n)).join(options.inline ? ';' : ';\n\t') +
|
|
@@ -2242,6 +2294,11 @@ function visit(node, options = {}) {
|
|
|
2242
2294
|
if (asyncChannelVar && getEnclosingFunction(node) === asyncFunctionNode) {
|
|
2243
2295
|
if (!node.expression)
|
|
2244
2296
|
return 'return';
|
|
2297
|
+
// An async return settles its promise (ordered wake); a generator's
|
|
2298
|
+
// sends stay raw (their consumers receive raw)
|
|
2299
|
+
if (asyncChannelIsAsync) {
|
|
2300
|
+
return `TnAsyncSend(${asyncChannelVar}, ${visit(node.expression)}); return` + (options.inline ? '' : ';\n\t');
|
|
2301
|
+
}
|
|
2245
2302
|
return `${asyncChannelVar} <- ${visit(node.expression)}; return` + (options.inline ? '' : ';\n\t');
|
|
2246
2303
|
}
|
|
2247
2304
|
const enclosingFn = getEnclosingFunction(node);
|
|
@@ -2589,9 +2646,14 @@ function visit(node, options = {}) {
|
|
|
2589
2646
|
result += `func New${name}${typeParams}(message string) *${name}${typeParamNames} {\n\t\tself := &${name}${typeParamNames}{}\n\t\tself.message = message\n\t\t${fieldInitializers(node)}return self\n\t}\n\n`;
|
|
2590
2647
|
}
|
|
2591
2648
|
else {
|
|
2592
|
-
|
|
2649
|
+
// No constructor: JS's implicit constructor(...args) { super(...args) }
|
|
2650
|
+
// takes the nearest ancestor constructor's parameters
|
|
2651
|
+
const inherited = parentClass && !extendsError ? inheritedConstructorParameters(parentClass) : null;
|
|
2652
|
+
const signature = inherited ? inherited.signature : '';
|
|
2653
|
+
const forwarded = inherited ? inherited.forward : [];
|
|
2654
|
+
const parentInit = parentClass && !extendsError ? `self.${goFieldName(parentClass)} = *${parentConstructorCall(parentClass, forwarded)}\n\t\t` : '';
|
|
2593
2655
|
const ctorBody = `{\n\t\tself := &${name}${typeParamNames}{}\n\t\t${parentInit}${fieldInitializers(node)}${nodeSelfLink(parentClass, node)}return self\n\t}`;
|
|
2594
|
-
result += emitConstructor(name, typeParams, typeParamNames,
|
|
2656
|
+
result += emitConstructor(name, typeParams, typeParamNames, signature, ctorBody);
|
|
2595
2657
|
}
|
|
2596
2658
|
// Inherited concrete methods are copied onto the subclass: Go embedding
|
|
2597
2659
|
// promotes the parent's receiver, which would break `this` dispatch
|
|
@@ -2674,12 +2736,15 @@ function visit(node, options = {}) {
|
|
|
2674
2736
|
const yieldType = getGeneratorYieldType(member);
|
|
2675
2737
|
const prevChannel = asyncChannelVar;
|
|
2676
2738
|
const prevFn = asyncFunctionNode;
|
|
2739
|
+
const prevIsAsync = asyncChannelIsAsync;
|
|
2677
2740
|
asyncChannelVar = '__ch';
|
|
2678
2741
|
asyncFunctionNode = member;
|
|
2742
|
+
asyncChannelIsAsync = false;
|
|
2679
2743
|
const methodParameterInfo = getFunctionParametersInfo(member.parameters ?? []);
|
|
2680
2744
|
const genBody = visit(member.body, { prefixBlockContent: methodParameterInfo.prefixBlockContent });
|
|
2681
2745
|
asyncChannelVar = prevChannel;
|
|
2682
2746
|
asyncFunctionNode = prevFn;
|
|
2747
|
+
asyncChannelIsAsync = prevIsAsync;
|
|
2683
2748
|
result += `${lineMarker(member)}func (self *${name}${typeParamNames}) ${genName}(${methodParameterInfo.signature}) chan ${yieldType} {\n\t__ch := make(chan ${yieldType})\n\tgo func() {\n\t\tdefer close(__ch)\n\t\t${genBody.trim()}\n\t}()\n\treturn __ch\n}\n\n`;
|
|
2684
2749
|
}
|
|
2685
2750
|
continue;
|
|
@@ -2800,7 +2865,17 @@ function visit(node, options = {}) {
|
|
|
2800
2865
|
return `make([]${elementType}, int(${length}))`;
|
|
2801
2866
|
}
|
|
2802
2867
|
const typeArgs = getTypeArguments((node.typeArguments ?? []));
|
|
2803
|
-
|
|
2868
|
+
// Array-reference parameters (*[]T) box their array arguments
|
|
2869
|
+
const ctorParams = classNames.has(className) ? constructorParameterNodes(className) : [];
|
|
2870
|
+
const args = (node.arguments ?? []).map((a, i) => {
|
|
2871
|
+
const param = i < ctorParams.length ? ctorParams[i] : undefined;
|
|
2872
|
+
if (param && !param.dotDotDotToken && !param.initializer && isIdentifier(param.name)) {
|
|
2873
|
+
const paramType = getParameterGoType(param);
|
|
2874
|
+
if (paramType.startsWith('*[]'))
|
|
2875
|
+
return toGoValueOfType(a, paramType);
|
|
2876
|
+
}
|
|
2877
|
+
return visit(a);
|
|
2878
|
+
});
|
|
2804
2879
|
// new F(…) where F holds a constructor function (construct signature)
|
|
2805
2880
|
if (!classNames.has(className) && inferExpressionType(node.expression)?.startsWith('func(')) {
|
|
2806
2881
|
return `${className}(${args.join(', ')})`;
|
|
@@ -2817,14 +2892,14 @@ function visit(node, options = {}) {
|
|
|
2817
2892
|
return `TnAssign(__obj, ${visit(p.expression)})`;
|
|
2818
2893
|
if (isShorthandPropertyAssignment(p))
|
|
2819
2894
|
return `__obj[${mapKeyText(p.name)}] = ${visit(p.name)}`;
|
|
2820
|
-
return `__obj[${
|
|
2895
|
+
return `__obj[${propertyKeyString(p.name)}] = ${visit(p.initializer)}`;
|
|
2821
2896
|
});
|
|
2822
2897
|
return `func() map[string]interface{} { __obj := map[string]interface{}{}; ${steps.join('; ')}; return __obj }()`;
|
|
2823
2898
|
}
|
|
2824
2899
|
const entries = (node.properties ?? [])
|
|
2825
2900
|
.map((p) => {
|
|
2826
2901
|
if (isPropertyAssignment(p))
|
|
2827
|
-
return `${
|
|
2902
|
+
return `${propertyKeyString(p.name)}: ${visit(p.initializer)}`;
|
|
2828
2903
|
if (isShorthandPropertyAssignment(p))
|
|
2829
2904
|
return `${mapKeyText(p.name)}: ${visit(p.name)}`;
|
|
2830
2905
|
return '';
|
|
@@ -2918,6 +2993,10 @@ function visit(node, options = {}) {
|
|
|
2918
2993
|
// Visits a value going into a slot of Go type `goType`; non-nil values for
|
|
2919
2994
|
// nullable primitives (*string/*float64/*bool) are boxed into pointers
|
|
2920
2995
|
function toGoValueOfType(expr, goType) {
|
|
2996
|
+
// (x as Task) on an any value stays dynamic; a typed slot asserts it
|
|
2997
|
+
if (goType && goType !== 'interface{}' && isAsExpression(expr) && getAsExpressionType(expr) === 'interface{}' && isDynamicValue(expr.expression)) {
|
|
2998
|
+
expr = expr.expression;
|
|
2999
|
+
}
|
|
2921
3000
|
if (goType === 'string' && inferExpressionType(expr) === 'TnJsxNode')
|
|
2922
3001
|
return `string(${visit(expr)})`;
|
|
2923
3002
|
if (goType &&
|
|
@@ -3185,7 +3264,11 @@ function visitUsingDeclaration(statement, rest) {
|
|
|
3185
3264
|
const hasAsync = (classNode?.members ?? []).some((m) => m.name?.text === '__asyncDispose');
|
|
3186
3265
|
if (isAwait && hasAsync)
|
|
3187
3266
|
useHelper('promise');
|
|
3188
|
-
|
|
3267
|
+
// The disposal may run on an async fn's goroutine or inline in a callback
|
|
3268
|
+
const awaitFn = asyncChannelVar && asyncChannelIsAsync && getEnclosingFunction(statement) === asyncFunctionNode
|
|
3269
|
+
? 'TnAwait'
|
|
3270
|
+
: 'TnAwaitInline';
|
|
3271
|
+
const call = isAwait && hasAsync ? `${awaitFn}(${name}.__asyncDispose())` : `${name}.__dispose()`;
|
|
3189
3272
|
return `defer func() { if ${name} != nil { ${call} } }()`;
|
|
3190
3273
|
})
|
|
3191
3274
|
.reverse();
|
|
@@ -3519,6 +3602,49 @@ function nodeParentGoName(expr) {
|
|
|
3519
3602
|
nodeParentClassKeys.set(goName, key);
|
|
3520
3603
|
return goName;
|
|
3521
3604
|
}
|
|
3605
|
+
// The constructor parameters of a user class: its own, else the nearest
|
|
3606
|
+
// ancestor's (the implicit constructor forwards them)
|
|
3607
|
+
function constructorParameterNodes(className) {
|
|
3608
|
+
let current = className;
|
|
3609
|
+
for (let depth = 0; depth < 50 && current; depth++) {
|
|
3610
|
+
const classNode = declaredClasses.get(current);
|
|
3611
|
+
if (!classNode)
|
|
3612
|
+
return [];
|
|
3613
|
+
const ctor = (classNode.members ?? []).find((m) => isConstructorDeclaration(m));
|
|
3614
|
+
if (ctor)
|
|
3615
|
+
return ctor.parameters ?? [];
|
|
3616
|
+
current = classParentNames.get(current) ?? '';
|
|
3617
|
+
}
|
|
3618
|
+
return [];
|
|
3619
|
+
}
|
|
3620
|
+
// The parameters of the nearest user-class ancestor with a constructor, as a
|
|
3621
|
+
// Go signature and the argument list forwarding them (null when none, or when
|
|
3622
|
+
// they need destructuring)
|
|
3623
|
+
function inheritedConstructorParameters(parentClass) {
|
|
3624
|
+
let current = parentClass;
|
|
3625
|
+
for (let depth = 0; depth < 50 && current; depth++) {
|
|
3626
|
+
const classNode = declaredClasses.get(current);
|
|
3627
|
+
if (!classNode)
|
|
3628
|
+
return null;
|
|
3629
|
+
const ctor = (classNode.members ?? []).find((m) => isConstructorDeclaration(m));
|
|
3630
|
+
if (ctor) {
|
|
3631
|
+
const params = ctor.parameters ?? [];
|
|
3632
|
+
if (params.length === 0 || params.some((p) => !isIdentifier(p.name)))
|
|
3633
|
+
return null;
|
|
3634
|
+
const info = getFunctionParametersInfo(params);
|
|
3635
|
+
const forward = [];
|
|
3636
|
+
for (const part of splitGoParameters(info.signature)) {
|
|
3637
|
+
const trimmed = part.trim();
|
|
3638
|
+
const space = trimmed.indexOf(' ');
|
|
3639
|
+
const paramName = trimmed.substring(0, space);
|
|
3640
|
+
forward.push(trimmed.substring(space + 1).trim().startsWith('...') ? `${paramName}...` : paramName);
|
|
3641
|
+
}
|
|
3642
|
+
return { signature: info.signature, forward: forward };
|
|
3643
|
+
}
|
|
3644
|
+
current = classParentNames.get(current) ?? '';
|
|
3645
|
+
}
|
|
3646
|
+
return null;
|
|
3647
|
+
}
|
|
3522
3648
|
function parentConstructorCall(parentClass, args) {
|
|
3523
3649
|
if (nodeParentClassKeys.has(parentClass)) {
|
|
3524
3650
|
const key = nodeParentClassKeys.get(parentClass) ?? '';
|
|
@@ -3653,6 +3779,15 @@ function isIncrementOrDecrement(node) {
|
|
|
3653
3779
|
// x++ / ++x: Go only has the statement form, so used as a value they become
|
|
3654
3780
|
// a closure returning the old (postfix) or new (prefix) value
|
|
3655
3781
|
function visitIncrementOrDecrement(node, isPrefix) {
|
|
3782
|
+
// ta[i]++ on a typed array: read, convert back on Set
|
|
3783
|
+
if (isElementAccessExpression(node.operand) && isTypedArrayGoType(inferExpressionType(node.operand.expression))) {
|
|
3784
|
+
const sign = node.operator === 'PlusPlusToken' ? '+' : '-';
|
|
3785
|
+
const arr = getTempName('ta');
|
|
3786
|
+
const index = getTempName('i');
|
|
3787
|
+
const old = getTempName('old');
|
|
3788
|
+
const result = isPrefix ? `${arr}.Get(${index})` : old;
|
|
3789
|
+
return `func() float64 { ${arr}, ${index} := ${visit(node.operand.expression)}, ${visit(node.operand.argumentExpression)}; ${old} := ${arr}.Get(${index}); ${arr}.Set(${index}, ${old} ${sign} 1); return ${result} }()`;
|
|
3790
|
+
}
|
|
3656
3791
|
const target = visit(node.operand, { inline: true });
|
|
3657
3792
|
const op = node.operator === 'PlusPlusToken' ? '++' : '--';
|
|
3658
3793
|
const parent = node.parent;
|
|
@@ -3663,6 +3798,185 @@ function visitIncrementOrDecrement(node, isPrefix) {
|
|
|
3663
3798
|
return `func() float64 { ${target}${op}; return ${target} }()`;
|
|
3664
3799
|
return `func() float64 { __old := ${target}; ${target}${op}; return __old }()`;
|
|
3665
3800
|
}
|
|
3801
|
+
// Expression replacing the receiver of the typed-array call being inlined by
|
|
3802
|
+
// visitArrayHigherOrderCall ('' otherwise)
|
|
3803
|
+
let typedArrayReceiverExpr = '';
|
|
3804
|
+
// Variables holding an ArrayBuffer (typed-array constructors view these)
|
|
3805
|
+
const arrayBufferVariables = new Set();
|
|
3806
|
+
const TYPED_ARRAY_CALLBACK_METHODS = [
|
|
3807
|
+
'map', 'filter', 'forEach', 'some', 'every', 'find', 'findIndex', 'findLast', 'findLastIndex', 'reduce',
|
|
3808
|
+
'reduceRight', 'entries'
|
|
3809
|
+
];
|
|
3810
|
+
// Whether a []byte expression is an ArrayBuffer rather than a Uint8Array /
|
|
3811
|
+
// Buffer: new ArrayBuffer(n), x.buffer, an ArrayBuffer-typed variable, and
|
|
3812
|
+
// slices of those
|
|
3813
|
+
function isArrayBufferExpression(node) {
|
|
3814
|
+
if (!node)
|
|
3815
|
+
return false;
|
|
3816
|
+
const expr = unwrapParentheses(node);
|
|
3817
|
+
if (isAsExpression(expr))
|
|
3818
|
+
return isArrayBufferTypeNode(expr.type) || isArrayBufferExpression(expr.expression);
|
|
3819
|
+
if (isNewExpression(expr) && isIdentifier(expr.expression)) {
|
|
3820
|
+
return expr.expression.text === 'ArrayBuffer' || expr.expression.text === 'SharedArrayBuffer';
|
|
3821
|
+
}
|
|
3822
|
+
if (isPropertyAccessExpression(expr))
|
|
3823
|
+
return expr.name.text === 'buffer';
|
|
3824
|
+
if (isCallExpression(expr) && isPropertyAccessExpression(expr.expression) && expr.expression.name.text === 'slice') {
|
|
3825
|
+
return isArrayBufferExpression(expr.expression.expression);
|
|
3826
|
+
}
|
|
3827
|
+
if (isIdentifier(expr)) {
|
|
3828
|
+
return arrayBufferVariables.has(expr.text) || isArrayBufferTypeNode(variableTypeNodes.get(expr.text));
|
|
3829
|
+
}
|
|
3830
|
+
return false;
|
|
3831
|
+
}
|
|
3832
|
+
function isArrayBufferTypeNode(typeNode) {
|
|
3833
|
+
if (!typeNode || !isTypeReferenceNode(typeNode) || !isIdentifier(typeNode.typeName))
|
|
3834
|
+
return false;
|
|
3835
|
+
const name = typeNode.typeName.text;
|
|
3836
|
+
return name === 'ArrayBuffer' || name === 'SharedArrayBuffer' || name === 'ArrayBufferLike';
|
|
3837
|
+
}
|
|
3838
|
+
// ta[i] = v / ta[i] op= v: one Set with the value converted like JS
|
|
3839
|
+
function visitTypedArrayAssignment(target, op, right) {
|
|
3840
|
+
const value = visit(right);
|
|
3841
|
+
if (op === '=')
|
|
3842
|
+
return `${visit(target.expression)}.Set(${visit(target.argumentExpression)}, ${value})`;
|
|
3843
|
+
const arr = getTempName('ta');
|
|
3844
|
+
const index = getTempName('i');
|
|
3845
|
+
const current = `${arr}.Get(${index})`;
|
|
3846
|
+
let combined = '';
|
|
3847
|
+
if (op === '+=' || op === '-=' || op === '*=' || op === '/=')
|
|
3848
|
+
combined = `${current} ${op[0]} (${value})`;
|
|
3849
|
+
else if (op === '%=') {
|
|
3850
|
+
importedPackages.add('math');
|
|
3851
|
+
combined = `math.Mod(${current}, ${value})`;
|
|
3852
|
+
}
|
|
3853
|
+
else if (op === '**=') {
|
|
3854
|
+
importedPackages.add('math');
|
|
3855
|
+
combined = `math.Pow(${current}, ${value})`;
|
|
3856
|
+
}
|
|
3857
|
+
else if (op === '&=' || op === '|=' || op === '^=') {
|
|
3858
|
+
useHelper('dynamic');
|
|
3859
|
+
combined = `float64(TnInt32(${current}) ${op[0]} TnInt32(${value}))`;
|
|
3860
|
+
}
|
|
3861
|
+
else if (op === '<<=' || op === '>>=') {
|
|
3862
|
+
useHelper('dynamic');
|
|
3863
|
+
combined = `float64(TnInt32(${current}) ${op.slice(0, 2)} (uint32(TnInt32(${value})) & 31))`;
|
|
3864
|
+
}
|
|
3865
|
+
else if (op === '>>>=') {
|
|
3866
|
+
useHelper('dynamic');
|
|
3867
|
+
combined = `float64(uint32(TnInt32(${current})) >> (uint32(TnInt32(${value})) & 31))`;
|
|
3868
|
+
}
|
|
3869
|
+
else
|
|
3870
|
+
return undefined;
|
|
3871
|
+
return `func() float64 { ${arr}, ${index} := ${visit(target.expression)}, ${visit(target.argumentExpression)}; return ${arr}.Set(${index}, ${combined}) }()`;
|
|
3872
|
+
}
|
|
3873
|
+
// Calls on typed arrays the Go type can't take: callback methods are inlined
|
|
3874
|
+
// over the elements as numbers (map / filter results become the same kind of
|
|
3875
|
+
// typed array); ArrayBuffer#slice copies
|
|
3876
|
+
function visitTypedArrayCall(node) {
|
|
3877
|
+
if (!isPropertyAccessExpression(node.expression))
|
|
3878
|
+
return undefined;
|
|
3879
|
+
const method = node.expression.name.text;
|
|
3880
|
+
const recvNode = node.expression.expression;
|
|
3881
|
+
if (method === 'slice' && isArrayBufferExpression(recvNode)) {
|
|
3882
|
+
useHelper('typedArrays');
|
|
3883
|
+
const args = (node.arguments ?? []).map((a) => `, ${visit(a)}`).join('');
|
|
3884
|
+
return `TnArrayBufferSlice(${visit(recvNode)}${args})`;
|
|
3885
|
+
}
|
|
3886
|
+
const recvType = inferExpressionType(recvNode);
|
|
3887
|
+
if (!isTypedArrayGoType(recvType) || !TYPED_ARRAY_CALLBACK_METHODS.includes(method))
|
|
3888
|
+
return undefined;
|
|
3889
|
+
const resultType = inferExpressionType(node) ?? '';
|
|
3890
|
+
const arr = getTempName('ta');
|
|
3891
|
+
const recv = visit(recvNode);
|
|
3892
|
+
typedArrayReceiverExpr = `${arr}.tnFloats()`;
|
|
3893
|
+
const inner = visitArrayHigherOrderCall(node);
|
|
3894
|
+
typedArrayReceiverExpr = '';
|
|
3895
|
+
if (!inner)
|
|
3896
|
+
return undefined;
|
|
3897
|
+
if (method === 'forEach')
|
|
3898
|
+
return `func() { ${arr} := ${recv}; ${inner} }()`;
|
|
3899
|
+
const value = method === 'map' || method === 'filter' ? `${arr}.tnLike(${inner})` : inner;
|
|
3900
|
+
return `func() ${resultType} { ${arr} := ${recv}; return ${value} }()`;
|
|
3901
|
+
}
|
|
3902
|
+
// Adapter types generated so far ('IntHeap__container_heap_Interface')
|
|
3903
|
+
const goInterfaceAdapters = new Set();
|
|
3904
|
+
// A class method declaration, searched up the inheritance chain
|
|
3905
|
+
function findClassMethod(className, methodName) {
|
|
3906
|
+
let name = className;
|
|
3907
|
+
for (let depth = 0; depth < 20 && name; depth++) {
|
|
3908
|
+
const cls = declaredClasses.get(name);
|
|
3909
|
+
if (!cls)
|
|
3910
|
+
return undefined;
|
|
3911
|
+
for (const member of cls.members ?? []) {
|
|
3912
|
+
if (member.kind === 'MethodDeclaration' && member.name && member.name.text === methodName)
|
|
3913
|
+
return member;
|
|
3914
|
+
}
|
|
3915
|
+
name = classParentNames.get(name) ?? '';
|
|
3916
|
+
}
|
|
3917
|
+
return undefined;
|
|
3918
|
+
}
|
|
3919
|
+
// A Go value of type `from` as a class method parameter of type `to`
|
|
3920
|
+
function adaptGoValue(expr, from, to) {
|
|
3921
|
+
if (from === to || to === 'interface{}' || to === 'any' || !to)
|
|
3922
|
+
return expr;
|
|
3923
|
+
if (from === 'any' || from === 'interface{}')
|
|
3924
|
+
return `${expr}.(${goLocalType(to)})`;
|
|
3925
|
+
if (to === 'float64' && isGoNumericKind(from))
|
|
3926
|
+
return `float64(${expr})`;
|
|
3927
|
+
return expr;
|
|
3928
|
+
}
|
|
3929
|
+
// heap.Push(h, x) with h an instance of `class IntHeap implements
|
|
3930
|
+
// heap.Interface`: Go needs Len() int, the class has Len(): number. The
|
|
3931
|
+
// adapter struct holds the instance and gives each interface method the
|
|
3932
|
+
// exact Go signature, converting arguments and results.
|
|
3933
|
+
function adaptClassToGoInterface(expr, fromType, toType, iface) {
|
|
3934
|
+
const className = fromType.slice(1);
|
|
3935
|
+
if (!declaredClasses.has(className))
|
|
3936
|
+
return '';
|
|
3937
|
+
for (const m of iface.ifaceMethods) {
|
|
3938
|
+
if (!findClassMethod(className, m.name))
|
|
3939
|
+
return '';
|
|
3940
|
+
}
|
|
3941
|
+
const adapterName = `${className}__${toType.replace(/[^A-Za-z0-9]/g, '_')}`;
|
|
3942
|
+
if (!goInterfaceAdapters.has(adapterName)) {
|
|
3943
|
+
goInterfaceAdapters.add(adapterName);
|
|
3944
|
+
const methods = [];
|
|
3945
|
+
for (const m of iface.ifaceMethods) {
|
|
3946
|
+
const method = findClassMethod(className, m.name);
|
|
3947
|
+
const declared = method.parameters ?? [];
|
|
3948
|
+
const params = [];
|
|
3949
|
+
const args = [];
|
|
3950
|
+
m.params.forEach((p, i) => {
|
|
3951
|
+
ensureGoTypePackages(p.goType);
|
|
3952
|
+
const variadic = p.goType.startsWith('...');
|
|
3953
|
+
params.push(`p${i} ${goLocalType(p.goType)}`);
|
|
3954
|
+
if (i >= declared.length)
|
|
3955
|
+
return;
|
|
3956
|
+
const target = declared[i].type ? getType(declared[i].type) : 'interface{}';
|
|
3957
|
+
args.push(variadic ? `p${i}...` : adaptGoValue(`p${i}`, p.goType, target));
|
|
3958
|
+
});
|
|
3959
|
+
const call = `a.v.${getSafeName(m.name)}(${args.join(', ')})`;
|
|
3960
|
+
let body = call;
|
|
3961
|
+
let results = '';
|
|
3962
|
+
if (m.results.length === 1) {
|
|
3963
|
+
ensureGoTypePackages(m.results[0]);
|
|
3964
|
+
results = ` ${goLocalType(m.results[0])}`;
|
|
3965
|
+
// (a truthiness check: a missing Map entry is '' in the self-hosted build)
|
|
3966
|
+
const recorded = classMethodReturnTypes.get(className)?.get(m.name);
|
|
3967
|
+
const returned = method.type ? getType(method.type) : recorded ? recorded : 'interface{}';
|
|
3968
|
+
body = `return ${toGoType(call, returned, m.results[0])}`;
|
|
3969
|
+
}
|
|
3970
|
+
else if (m.results.length > 1) {
|
|
3971
|
+
results = ` (${m.results.map((r) => goLocalType(r)).join(', ')})`;
|
|
3972
|
+
body = `return ${call}`;
|
|
3973
|
+
}
|
|
3974
|
+
methods.push(`func (a *${adapterName}) ${m.name}(${params.join(', ')})${results} { ${body} }`);
|
|
3975
|
+
}
|
|
3976
|
+
mainPackageVariables.push(`// ${className} as a ${toType}\ntype ${adapterName} struct{ v *${className} }\n\n${methods.join('\n')}`);
|
|
3977
|
+
}
|
|
3978
|
+
return `&${adapterName}{v: ${expr}}`;
|
|
3979
|
+
}
|
|
3666
3980
|
function compositeBody(rawEntries) {
|
|
3667
3981
|
const entries = rawEntries.map((e) => e.trimEnd());
|
|
3668
3982
|
if (!entries.some((e) => e.includes('\n')))
|
|
@@ -3733,6 +4047,11 @@ function getDictionaryValueType(node) {
|
|
|
3733
4047
|
function isDynamicObjectLiteral(node) {
|
|
3734
4048
|
if (isAnyContext(getContextualTypeNode(node)))
|
|
3735
4049
|
return true;
|
|
4050
|
+
// { [key]: v } has no struct shape (a Record context makes a typed map instead)
|
|
4051
|
+
if ((node.properties ?? []).some((p) => p.name?.kind === 'ComputedPropertyName') &&
|
|
4052
|
+
!isRecordTypeNode(resolveTypeNode(getContextualTypeNode(node)))) {
|
|
4053
|
+
return true;
|
|
4054
|
+
}
|
|
3736
4055
|
// { name: { … } } nested in a dynamic object (with no declared member type) is dynamic too
|
|
3737
4056
|
const parent = node.parent;
|
|
3738
4057
|
if (isPropertyAssignment(parent) &&
|
|
@@ -3780,7 +4099,9 @@ function getObjectLiteralGoType(node) {
|
|
|
3780
4099
|
// Values typed `any`/`unknown` are handled at runtime (TnGet/TnSet/...),
|
|
3781
4100
|
// never by guessing their type
|
|
3782
4101
|
function isDynamicValue(expr) {
|
|
3783
|
-
|
|
4102
|
+
// Go bridge results spell it `any`
|
|
4103
|
+
const type = inferExpressionType(expr);
|
|
4104
|
+
return type === 'interface{}' || type === 'any';
|
|
3784
4105
|
}
|
|
3785
4106
|
// A value whose type is a type parameter (a: T in f<T>): its properties are read dynamically
|
|
3786
4107
|
function isTypeParameterValue(expr) {
|
|
@@ -3873,6 +4194,13 @@ function mapKeyText(name) {
|
|
|
3873
4194
|
return visit(name.expression);
|
|
3874
4195
|
return visit(name);
|
|
3875
4196
|
}
|
|
4197
|
+
// A key of a dynamic object (map[string]interface{}): computed keys become
|
|
4198
|
+
// strings the way JS property keys do ({ [1]: x } has the key "1")
|
|
4199
|
+
function propertyKeyString(name) {
|
|
4200
|
+
if (name.kind !== 'ComputedPropertyName')
|
|
4201
|
+
return mapKeyText(name);
|
|
4202
|
+
return jsStringOf(visit(name.expression), inferExpressionType(name.expression));
|
|
4203
|
+
}
|
|
3876
4204
|
// { a: 1 } typed as Record<K, V> → map[K]V{"a": 1}
|
|
3877
4205
|
// An ordered map built from "key, value" entries (in source order)
|
|
3878
4206
|
function orderedMapLiteral(keyType, valueType, entries) {
|
|
@@ -4064,6 +4392,24 @@ function getEnclosingClassName(node) {
|
|
|
4064
4392
|
}
|
|
4065
4393
|
return undefined;
|
|
4066
4394
|
}
|
|
4395
|
+
// The Go type of `this` inside a class body (methods, constructor, field
|
|
4396
|
+
// initializers, arrow functions within them): *ClassName / *Box[T]; undefined
|
|
4397
|
+
// inside function expressions and object literals, where `this` is something else
|
|
4398
|
+
function thisGoType(node) {
|
|
4399
|
+
let current = node.parent;
|
|
4400
|
+
while (current) {
|
|
4401
|
+
if (isClassDeclaration(current)) {
|
|
4402
|
+
if (!current.name || !isIdentifier(current.name))
|
|
4403
|
+
return undefined;
|
|
4404
|
+
const params = (current.typeParameters ?? []).map((tp) => tp.name.text);
|
|
4405
|
+
return `*${current.name.text}${params.length > 0 ? `[${params.join(', ')}]` : ''}`;
|
|
4406
|
+
}
|
|
4407
|
+
if (isFunctionExpression(current) || isFunctionDeclaration(current) || isObjectLiteralExpression(current))
|
|
4408
|
+
return undefined;
|
|
4409
|
+
current = current.parent;
|
|
4410
|
+
}
|
|
4411
|
+
return undefined;
|
|
4412
|
+
}
|
|
4067
4413
|
// Declared return type of a function, unwrapping Promise<T> for async functions
|
|
4068
4414
|
function getReturnTypeNode(fn) {
|
|
4069
4415
|
const typeNode = fn?.type ?? (fn ? getContextualFunctionType(fn)?.type : undefined);
|
|
@@ -4173,8 +4519,26 @@ function getContextualTypeNode(node) {
|
|
|
4173
4519
|
return getReturnTypeNode(getEnclosingFunction(parent));
|
|
4174
4520
|
}
|
|
4175
4521
|
if (isArrowFunction(parent) && parent.body === node) {
|
|
4176
|
-
|
|
4522
|
+
const declared = getReturnTypeNode(parent);
|
|
4523
|
+
if (declared)
|
|
4524
|
+
return declared;
|
|
4525
|
+
// rows.map((r) => ({ … })) where the result must be Note[]: each item is a Note
|
|
4526
|
+
const call = parent.parent;
|
|
4527
|
+
if (isCallExpression(call) &&
|
|
4528
|
+
(call.arguments ?? [])[0] === parent &&
|
|
4529
|
+
isPropertyAccessExpression(call.expression) &&
|
|
4530
|
+
call.expression.name.text === 'map') {
|
|
4531
|
+
const resultType = resolveTypeNode(getContextualTypeNode(call));
|
|
4532
|
+
if (isArrayTypeNode(resultType))
|
|
4533
|
+
return resultType.elementType;
|
|
4534
|
+
}
|
|
4535
|
+
// items.reduce((acc, x) => ({ … }), init): the accumulator is the result type
|
|
4536
|
+
if (isReduceCall(call) && (call.arguments ?? [])[0] === parent)
|
|
4537
|
+
return getContextualTypeNode(call);
|
|
4538
|
+
return undefined;
|
|
4177
4539
|
}
|
|
4540
|
+
if (isReduceCall(parent) && (parent.arguments ?? [])[1] === node)
|
|
4541
|
+
return getContextualTypeNode(parent);
|
|
4178
4542
|
if (isCallExpression(parent) && isIdentifier(parent.expression)) {
|
|
4179
4543
|
const index = (parent.arguments ?? []).indexOf(node);
|
|
4180
4544
|
const fn = declaredFunctions.get(parent.expression.text);
|
|
@@ -4228,6 +4592,8 @@ function getArrayLiteralElementType(node) {
|
|
|
4228
4592
|
const spreadType = inferExpressionType(element.expression);
|
|
4229
4593
|
if (spreadType?.startsWith('[]'))
|
|
4230
4594
|
return spreadType.slice(2);
|
|
4595
|
+
if (isTypedArrayGoType(spreadType))
|
|
4596
|
+
return 'float64';
|
|
4231
4597
|
if (spreadType === 'string')
|
|
4232
4598
|
return 'string';
|
|
4233
4599
|
if (spreadType?.startsWith('*TnMap[') && extractMapValueType(spreadType) === 'struct{}') {
|
|
@@ -4300,6 +4666,54 @@ function unwrapParentheses(expr) {
|
|
|
4300
4666
|
expr = expr.expression;
|
|
4301
4667
|
return expr;
|
|
4302
4668
|
}
|
|
4669
|
+
function isReduceCall(node) {
|
|
4670
|
+
return (isCallExpression(node) &&
|
|
4671
|
+
isPropertyAccessExpression(node.expression) &&
|
|
4672
|
+
(node.expression.name.text === 'reduce' || node.expression.name.text === 'reduceRight'));
|
|
4673
|
+
}
|
|
4674
|
+
// The Go type of tuple[i] (a literal index into a tuple-typed value held as
|
|
4675
|
+
// []interface{}): '' when not a tuple read or the element is itself dynamic
|
|
4676
|
+
function tupleElementGoType(expr) {
|
|
4677
|
+
if (!isNumericLiteral(expr.argumentExpression))
|
|
4678
|
+
return '';
|
|
4679
|
+
if (inferExpressionType(expr.expression) !== '[]interface{}')
|
|
4680
|
+
return '';
|
|
4681
|
+
let typeNode = resolveTypeNode(getExpressionTypeNode(expr.expression));
|
|
4682
|
+
if (!typeNode && isIdentifier(expr.expression))
|
|
4683
|
+
typeNode = resolveTypeNode(callbackParameterTypeNode(expr.expression));
|
|
4684
|
+
if (!typeNode || typeNode.kind !== 'TupleType')
|
|
4685
|
+
return '';
|
|
4686
|
+
const element = (typeNode.elements ?? [])[Number(expr.argumentExpression.text)];
|
|
4687
|
+
if (!element)
|
|
4688
|
+
return '';
|
|
4689
|
+
const goType = getType(element.kind === 'NamedTupleMember' ? element.type : element);
|
|
4690
|
+
return !goType || goType === 'interface{}' || isUnboundGoType(goType) ? '' : goType;
|
|
4691
|
+
}
|
|
4692
|
+
// The declared element type of an untyped callback parameter of an array
|
|
4693
|
+
// method (pairs.sort((a, b) => …) with pairs: [string, number][])
|
|
4694
|
+
function callbackParameterTypeNode(name) {
|
|
4695
|
+
let fn = name.parent;
|
|
4696
|
+
while (fn && !isArrowFunction(fn) && !isFunctionExpression(fn))
|
|
4697
|
+
fn = fn.parent;
|
|
4698
|
+
if (!fn)
|
|
4699
|
+
return undefined;
|
|
4700
|
+
const index = (fn.parameters ?? []).findIndex((p) => isIdentifier(p.name) && p.name.text === name.text);
|
|
4701
|
+
if (index < 0 || fn.parameters[index].type)
|
|
4702
|
+
return undefined;
|
|
4703
|
+
const call = fn.parent;
|
|
4704
|
+
if (!isCallExpression(call) || !isPropertyAccessExpression(call.expression))
|
|
4705
|
+
return undefined;
|
|
4706
|
+
const method = call.expression.name.text;
|
|
4707
|
+
const elementParams = {
|
|
4708
|
+
sort: [0, 1], toSorted: [0, 1], map: [0], filter: [0], forEach: [0], some: [0], every: [0], find: [0],
|
|
4709
|
+
findIndex: [0], findLast: [0], findLastIndex: [0], flatMap: [0], reduce: [1], reduceRight: [1]
|
|
4710
|
+
};
|
|
4711
|
+
const slots = elementParams[method];
|
|
4712
|
+
if (!slots || !slots.includes(index) || (call.arguments ?? [])[0] !== fn)
|
|
4713
|
+
return undefined;
|
|
4714
|
+
const arrayType = resolveTypeNode(getExpressionTypeNode(call.expression.expression));
|
|
4715
|
+
return isArrayTypeNode(arrayType) ? arrayType.elementType : undefined;
|
|
4716
|
+
}
|
|
4303
4717
|
function getTupleElementType(tuple) {
|
|
4304
4718
|
const types = (tuple.elements ?? []).map((t) => getType(t.kind === 'NamedTupleMember' ? t.type : t));
|
|
4305
4719
|
return types.length > 0 && types.every((t) => t === types[0]) ? types[0] : 'interface{}';
|
|
@@ -4332,6 +4746,8 @@ function visitSpreadSource(expr) {
|
|
|
4332
4746
|
if (sourceType === 'string') {
|
|
4333
4747
|
return `func() []string { __parts := []string{}; for _, __r := range ${visit(expr)} { __parts = append(__parts, string(__r)) }; return __parts }()`;
|
|
4334
4748
|
}
|
|
4749
|
+
if (isTypedArrayGoType(sourceType))
|
|
4750
|
+
return `${visit(expr)}.tnFloats()`;
|
|
4335
4751
|
return visit(expr);
|
|
4336
4752
|
}
|
|
4337
4753
|
function visitSpreadArrayLiteral(node, elemType) {
|
|
@@ -4513,6 +4929,8 @@ function isMockAccess(node) {
|
|
|
4513
4929
|
function inferExpressionType(expr) {
|
|
4514
4930
|
if (isMockAccess(expr))
|
|
4515
4931
|
return '*TnMockFunctionContext';
|
|
4932
|
+
if (expr?.kind === 'ThisKeyword')
|
|
4933
|
+
return thisGoType(expr);
|
|
4516
4934
|
if (isAwaitExpression(expr)) {
|
|
4517
4935
|
// await unwraps the promise channel
|
|
4518
4936
|
const inner = inferExpressionType(expr.expression);
|
|
@@ -4625,11 +5043,16 @@ function inferExpressionType(expr) {
|
|
|
4625
5043
|
}
|
|
4626
5044
|
}
|
|
4627
5045
|
if (isElementAccessExpression(expr)) {
|
|
5046
|
+
const tupleElement = tupleElementGoType(expr);
|
|
5047
|
+
if (tupleElement)
|
|
5048
|
+
return tupleElement;
|
|
4628
5049
|
const objectType = inferExpressionType(expr.expression);
|
|
4629
5050
|
if (objectType === 'string')
|
|
4630
5051
|
return 'string';
|
|
4631
5052
|
if (objectType?.startsWith('[]'))
|
|
4632
5053
|
return objectType.slice(2);
|
|
5054
|
+
if (isTypedArrayGoType(objectType))
|
|
5055
|
+
return 'float64';
|
|
4633
5056
|
if (objectType?.startsWith('*TnMap['))
|
|
4634
5057
|
return extractMapValueType(objectType);
|
|
4635
5058
|
const declared = getExpressionTypeNode(expr);
|
|
@@ -4892,6 +5315,25 @@ function inferExpressionType(expr) {
|
|
|
4892
5315
|
return isStructGoType(valueType) ? `*${valueType}` : valueType;
|
|
4893
5316
|
}
|
|
4894
5317
|
}
|
|
5318
|
+
if (isTypedArrayGoType(ownerType)) {
|
|
5319
|
+
if (methodName === 'map' || methodName === 'filter')
|
|
5320
|
+
return ownerType;
|
|
5321
|
+
if (methodName === 'some' || methodName === 'every')
|
|
5322
|
+
return 'bool';
|
|
5323
|
+
if (['find', 'findIndex', 'findLast', 'findLastIndex'].includes(methodName))
|
|
5324
|
+
return 'float64';
|
|
5325
|
+
if (methodName === 'reduce' || methodName === 'reduceRight') {
|
|
5326
|
+
return (expr.arguments?.[1] ? inferExpressionType(expr.arguments[1]) : undefined) ?? 'float64';
|
|
5327
|
+
}
|
|
5328
|
+
if (methodName === 'entries')
|
|
5329
|
+
return '[][]interface{}';
|
|
5330
|
+
}
|
|
5331
|
+
if (methodName === 'from' &&
|
|
5332
|
+
isIdentifier(expr.expression.expression) &&
|
|
5333
|
+
expr.expression.expression.text === 'Array' &&
|
|
5334
|
+
isTypedArrayGoType(inferExpressionType(expr.arguments?.[0]))) {
|
|
5335
|
+
return '[]float64';
|
|
5336
|
+
}
|
|
4895
5337
|
if (isArrayLikeGoType(ownerType)) {
|
|
4896
5338
|
const elementType = getArrayElementTypeFromGoType(ownerType);
|
|
4897
5339
|
if (methodName === 'map') {
|
|
@@ -5766,6 +6208,9 @@ function buildArrayCallbackInvocationReduce(callbackInfo, accVar, itemVar, index
|
|
|
5766
6208
|
return `(${callbackInfo.fnExpr})(${args.join(', ')})`;
|
|
5767
6209
|
}
|
|
5768
6210
|
function visitArrayHigherOrderCall(node) {
|
|
6211
|
+
// Set by visitTypedArrayCall for this call only (callbacks may hold other calls)
|
|
6212
|
+
const typedReceiver = typedArrayReceiverExpr;
|
|
6213
|
+
typedArrayReceiverExpr = '';
|
|
5769
6214
|
if (!isPropertyAccessExpression(node.expression))
|
|
5770
6215
|
return undefined;
|
|
5771
6216
|
const methodName = node.expression.name.text;
|
|
@@ -5773,8 +6218,8 @@ function visitArrayHigherOrderCall(node) {
|
|
|
5773
6218
|
return undefined;
|
|
5774
6219
|
}
|
|
5775
6220
|
const arrayExprNode = node.expression.expression;
|
|
5776
|
-
const arrayExpr = visit(arrayExprNode);
|
|
5777
|
-
const ownerType = inferExpressionType(arrayExprNode);
|
|
6221
|
+
const arrayExpr = typedReceiver ? typedReceiver : visit(arrayExprNode);
|
|
6222
|
+
const ownerType = typedReceiver ? '[]float64' : inferExpressionType(arrayExprNode);
|
|
5778
6223
|
const elementType = isArrayLikeGoType(ownerType)
|
|
5779
6224
|
? getArrayElementTypeFromGoType(ownerType)
|
|
5780
6225
|
: 'interface{}';
|
|
@@ -6359,6 +6804,10 @@ function getAcessString(leftSide, rightSide, objectType) {
|
|
|
6359
6804
|
return `float64(len(${leftSide}))`;
|
|
6360
6805
|
}
|
|
6361
6806
|
// Buffers / Uint8Arrays / ArrayBuffers are []byte
|
|
6807
|
+
if (rightSide === 'buffer' && objectType === 'Buffer')
|
|
6808
|
+
return leftSide;
|
|
6809
|
+
if (rightSide === 'byteOffset' && objectType === 'Buffer')
|
|
6810
|
+
return 'float64(0)';
|
|
6362
6811
|
if (rightSide === 'byteLength' && objectType === 'Buffer') {
|
|
6363
6812
|
return `float64(len(${leftSide}))`;
|
|
6364
6813
|
}
|
|
@@ -7817,7 +8266,13 @@ function getCollectionArgumentTypes(node) {
|
|
|
7817
8266
|
if (!isPropertyAccessExpression(node.expression))
|
|
7818
8267
|
return undefined;
|
|
7819
8268
|
const method = node.expression.name.text;
|
|
7820
|
-
|
|
8269
|
+
let receiverType = inferExpressionType(node.expression.expression);
|
|
8270
|
+
// this.items.push(x): the field's declared type
|
|
8271
|
+
if (!receiverType) {
|
|
8272
|
+
const declared = getExpressionTypeNode(node.expression.expression);
|
|
8273
|
+
if (declared)
|
|
8274
|
+
receiverType = getType(declared);
|
|
8275
|
+
}
|
|
7821
8276
|
if (receiverType?.startsWith('*TnMap[')) {
|
|
7822
8277
|
const keyType = extractMapKeyType(receiverType);
|
|
7823
8278
|
const valueType = extractMapValueType(receiverType);
|
|
@@ -8048,15 +8503,18 @@ function emitChannelFunction(node, isAsync) {
|
|
|
8048
8503
|
const rejectOnPanic = isAsync ? `\n\t\tdefer TnRejectOnPanic(${channelVar})` : '';
|
|
8049
8504
|
const prevChannel = asyncChannelVar;
|
|
8050
8505
|
const prevFn = asyncFunctionNode;
|
|
8506
|
+
const prevIsAsync = asyncChannelIsAsync;
|
|
8051
8507
|
asyncChannelVar = channelVar;
|
|
8052
8508
|
asyncFunctionNode = node;
|
|
8509
|
+
asyncChannelIsAsync = isAsync;
|
|
8053
8510
|
const body = visit(node.body, { prefixBlockContent: parameterInfo.prefixBlockContent });
|
|
8054
8511
|
asyncChannelVar = prevChannel;
|
|
8055
8512
|
asyncFunctionNode = prevFn;
|
|
8513
|
+
asyncChannelIsAsync = prevIsAsync;
|
|
8056
8514
|
if (isAsync) {
|
|
8057
8515
|
// The body runs synchronously until its first await, holding the JS baton
|
|
8058
8516
|
useHelper('eventLoop');
|
|
8059
|
-
return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType}, 1)\n\tTnStartAsync(func() {\n\t\tdefer
|
|
8517
|
+
return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType}, 1)\n\tTnStartAsync(func() {\n\t\tdefer TnAsyncClose(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t})\n\treturn ${channelVar}\n}`);
|
|
8060
8518
|
}
|
|
8061
8519
|
return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType})\n\tgo func() {\n\t\tdefer close(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t}()\n\treturn ${channelVar}\n}`);
|
|
8062
8520
|
}
|
|
@@ -8271,7 +8729,7 @@ function includeLocalImport(code, dir, goFileName, tsx = false, fileName = '') {
|
|
|
8271
8729
|
.sort()
|
|
8272
8730
|
.map((pkg) => goImportLine(pkg))
|
|
8273
8731
|
.join('\n');
|
|
8274
|
-
const parts = ['package main'];
|
|
8732
|
+
const parts = [GENERATED_HEADER, 'package main'];
|
|
8275
8733
|
if (fileImports)
|
|
8276
8734
|
parts.push(fileImports);
|
|
8277
8735
|
if (fileInline.trim())
|
|
@@ -8422,7 +8880,7 @@ function platformHelper(id) {
|
|
|
8422
8880
|
return id;
|
|
8423
8881
|
const base = id.slice(0, id.length - 3);
|
|
8424
8882
|
const specific = `${base}@${targetGoos}`;
|
|
8425
|
-
return
|
|
8883
|
+
return specific in goHelpers || specific in nodeRegistry.goHelpers ? specific : `${base}@other`;
|
|
8426
8884
|
}
|
|
8427
8885
|
function useHelper(id) {
|
|
8428
8886
|
if (usedHelpers.has(id))
|
|
@@ -8451,11 +8909,13 @@ function bindNodeRegistryServices() {
|
|
|
8451
8909
|
nodeRegistry.typeOf = (node) => inferExpressionType(node) ?? '';
|
|
8452
8910
|
nodeRegistry.visit = (node) => visit(node);
|
|
8453
8911
|
nodeRegistry.categoryOf = (node) => resolveExpressionType(node) ?? '';
|
|
8912
|
+
nodeRegistry.isArrayBuffer = (node) => isArrayBufferExpression(node);
|
|
8454
8913
|
bindConvertServices({
|
|
8455
8914
|
pkg: needPkg,
|
|
8456
8915
|
helper: useHelper,
|
|
8457
8916
|
typeOf: (node) => inferExpressionType(node) ?? '',
|
|
8458
|
-
localType: goLocalType
|
|
8917
|
+
localType: goLocalType,
|
|
8918
|
+
adapt: adaptClassToGoInterface
|
|
8459
8919
|
});
|
|
8460
8920
|
bindBridgeServices({
|
|
8461
8921
|
pkg: needPkg,
|
|
@@ -8475,6 +8935,7 @@ function bindNodeRegistryServices() {
|
|
|
8475
8935
|
}
|
|
8476
8936
|
registerCore(nodeRegistry);
|
|
8477
8937
|
registerBuffer(nodeRegistry);
|
|
8938
|
+
registerTypedArrays(nodeRegistry);
|
|
8478
8939
|
registerPath(nodeRegistry);
|
|
8479
8940
|
registerFs(nodeRegistry);
|
|
8480
8941
|
registerUrl(nodeRegistry);
|
|
@@ -8490,6 +8951,7 @@ registerStringDecoder(nodeRegistry);
|
|
|
8490
8951
|
registerCrypto(nodeRegistry);
|
|
8491
8952
|
registerCryptoKeys(nodeRegistry);
|
|
8492
8953
|
registerZlib(nodeRegistry);
|
|
8954
|
+
registerFsWatch(nodeRegistry);
|
|
8493
8955
|
registerTimers(nodeRegistry);
|
|
8494
8956
|
registerEvents(nodeRegistry);
|
|
8495
8957
|
registerStream(nodeRegistry);
|
|
@@ -8529,7 +8991,7 @@ const helperPackages = {
|
|
|
8529
8991
|
namedGroups: ['regexp'],
|
|
8530
8992
|
moduleUrl: ['os'],
|
|
8531
8993
|
asyncWait: [],
|
|
8532
|
-
timerWait: ['sync', 'sync/atomic', 'time'],
|
|
8994
|
+
timerWait: ['sort', 'sync', 'sync/atomic', 'time'],
|
|
8533
8995
|
clock: ['time'],
|
|
8534
8996
|
eventLoop: ['sync', 'sync/atomic', 'time'],
|
|
8535
8997
|
uri: ['strings', 'fmt', 'net/url'],
|
|
@@ -10775,7 +11237,49 @@ type TnTimeout struct {
|
|
|
10775
11237
|
fn func()
|
|
10776
11238
|
refd bool
|
|
10777
11239
|
active bool
|
|
10778
|
-
|
|
11240
|
+
due time.Time
|
|
11241
|
+
seq int
|
|
11242
|
+
}
|
|
11243
|
+
|
|
11244
|
+
// Armed timers, owned by the baton holder. An expired timer's goroutine only
|
|
11245
|
+
// wakes the loop, which then runs every due timer in deadline order: timer
|
|
11246
|
+
// goroutines that expire together (a starved loop, a coarse OS clock) may post
|
|
11247
|
+
// in any order, but Node fires timers in deadline order.
|
|
11248
|
+
var __tnPendingTimers = map[*TnTimeout]struct{}{}
|
|
11249
|
+
var __tnTimerSeq int
|
|
11250
|
+
|
|
11251
|
+
func tnRunDueTimers() {
|
|
11252
|
+
now := time.Now()
|
|
11253
|
+
var due []*TnTimeout
|
|
11254
|
+
for t := range __tnPendingTimers {
|
|
11255
|
+
if !t.active {
|
|
11256
|
+
delete(__tnPendingTimers, t)
|
|
11257
|
+
} else if !t.due.After(now) {
|
|
11258
|
+
due = append(due, t)
|
|
11259
|
+
}
|
|
11260
|
+
}
|
|
11261
|
+
sort.Slice(due, func(i, j int) bool {
|
|
11262
|
+
if !due[i].due.Equal(due[j].due) {
|
|
11263
|
+
return due[i].due.Before(due[j].due)
|
|
11264
|
+
}
|
|
11265
|
+
return due[i].seq < due[j].seq
|
|
11266
|
+
})
|
|
11267
|
+
for _, t := range due {
|
|
11268
|
+
// An earlier callback may have cleared or refreshed it
|
|
11269
|
+
if !t.active || t.due.After(now) {
|
|
11270
|
+
continue
|
|
11271
|
+
}
|
|
11272
|
+
delete(__tnPendingTimers, t)
|
|
11273
|
+
t.active = false
|
|
11274
|
+
if t.refd {
|
|
11275
|
+
t.refd = false
|
|
11276
|
+
__tnTimers.Done()
|
|
11277
|
+
}
|
|
11278
|
+
t.fn()
|
|
11279
|
+
// Microtasks (promise continuations) run after each timer callback,
|
|
11280
|
+
// before the next one fires — as Node does
|
|
11281
|
+
TnRunMicrotasks()
|
|
11282
|
+
}
|
|
10779
11283
|
}
|
|
10780
11284
|
|
|
10781
11285
|
// node:test mock timers: when set (and the API is mocked) it takes over a timer;
|
|
@@ -10804,21 +11308,12 @@ func tnSetTimeout(kind string, ms float64, fn func()) *TnTimeout {
|
|
|
10804
11308
|
}
|
|
10805
11309
|
|
|
10806
11310
|
func (t *TnTimeout) arm() {
|
|
10807
|
-
|
|
10808
|
-
|
|
10809
|
-
|
|
10810
|
-
|
|
10811
|
-
|
|
10812
|
-
|
|
10813
|
-
}
|
|
10814
|
-
t.active = false
|
|
10815
|
-
if t.refd {
|
|
10816
|
-
t.refd = false
|
|
10817
|
-
__tnTimers.Done()
|
|
10818
|
-
}
|
|
10819
|
-
t.fn()
|
|
10820
|
-
})
|
|
10821
|
-
})
|
|
11311
|
+
__tnTimerSeq++
|
|
11312
|
+
t.seq = __tnTimerSeq
|
|
11313
|
+
d := time.Duration(t.ms * float64(time.Millisecond))
|
|
11314
|
+
t.due = time.Now().Add(d)
|
|
11315
|
+
__tnPendingTimers[t] = struct{}{}
|
|
11316
|
+
t.timer = time.AfterFunc(d, func() { TnLoopPost(tnRunDueTimers) })
|
|
10822
11317
|
}
|
|
10823
11318
|
|
|
10824
11319
|
func (t *TnTimeout) ref() *TnTimeout {
|
|
@@ -10958,6 +11453,7 @@ func (t *TnInterval) close() *TnInterval {
|
|
|
10958
11453
|
func TnClearTimeout(t *TnTimeout) {
|
|
10959
11454
|
if t != nil && t.active {
|
|
10960
11455
|
t.active = false
|
|
11456
|
+
delete(__tnPendingTimers, t)
|
|
10961
11457
|
if t.timer != nil {
|
|
10962
11458
|
t.timer.Stop()
|
|
10963
11459
|
}
|
|
@@ -11115,7 +11611,9 @@ func tnRunTask(fn func()) {
|
|
|
11115
11611
|
func tnLoopIdle() bool {
|
|
11116
11612
|
tnLoopMu.Lock()
|
|
11117
11613
|
defer tnLoopMu.Unlock()
|
|
11118
|
-
|
|
11614
|
+
tnMicrotasksMu.Lock()
|
|
11615
|
+
defer tnMicrotasksMu.Unlock()
|
|
11616
|
+
return len(tnLoopTasks) == 0 && len(tnMicrotasks) == 0 && atomic.LoadInt64(&tnLoopRefs) <= 0
|
|
11119
11617
|
}
|
|
11120
11618
|
|
|
11121
11619
|
// The end of main: run until nothing is pending
|
|
@@ -11143,8 +11641,86 @@ func TnRunLoop() {
|
|
|
11143
11641
|
}
|
|
11144
11642
|
}
|
|
11145
11643
|
|
|
11146
|
-
//
|
|
11644
|
+
// Parked awaits, keyed by promise channel. A promise resolution (TnAsyncSend /
|
|
11645
|
+
// TnAsyncClose) delivers under tnWakeMu and queues an ordered wakeup instead of
|
|
11646
|
+
// waking the awaiter directly: continuations must resume in the order their
|
|
11647
|
+
// promises settled, like Node's microtasks — awaiters racing for the baton
|
|
11648
|
+
// would resume out of order on a starved machine.
|
|
11649
|
+
var tnWakeMu sync.Mutex
|
|
11650
|
+
var tnAwaiting = map[any]chan struct{}{}
|
|
11651
|
+
|
|
11652
|
+
// (baton holder) hands the baton to a parked awaiter and waits for it to park
|
|
11653
|
+
// again (or finish): JS keeps running one thing at a time
|
|
11654
|
+
func tnDeliver(tok chan struct{}) {
|
|
11655
|
+
back := make(chan struct{})
|
|
11656
|
+
tnLendStack = append(tnLendStack, back)
|
|
11657
|
+
close(tok)
|
|
11658
|
+
<-back
|
|
11659
|
+
}
|
|
11660
|
+
|
|
11661
|
+
// Queues the ordered wakeup of a parked awaiter (nil tok: nobody parked)
|
|
11662
|
+
func tnWakeQueue(tok chan struct{}) {
|
|
11663
|
+
if tok == nil {
|
|
11664
|
+
return
|
|
11665
|
+
}
|
|
11666
|
+
tnMicrotasksMu.Lock()
|
|
11667
|
+
tnMicrotasks = append(tnMicrotasks, func() { tnDeliver(tok) })
|
|
11668
|
+
tnMicrotasksMu.Unlock()
|
|
11669
|
+
tnLoopNotify()
|
|
11670
|
+
}
|
|
11671
|
+
|
|
11672
|
+
// (baton holder) Receives from a channel, running loop tasks while waiting;
|
|
11673
|
+
// once nothing is left it parks. A promise wake resumes in settlement order
|
|
11674
|
+
// with the baton handed over; a raw send (a generator yield) resumes the old
|
|
11675
|
+
// way, racing for the baton
|
|
11147
11676
|
func TnLoopReceive[T any](ch chan T) (T, bool) {
|
|
11677
|
+
ctx := tnAsyncCtx
|
|
11678
|
+
defer func() { tnAsyncCtx = ctx }()
|
|
11679
|
+
for {
|
|
11680
|
+
select {
|
|
11681
|
+
case v, ok := <-ch:
|
|
11682
|
+
return v, ok
|
|
11683
|
+
default:
|
|
11684
|
+
}
|
|
11685
|
+
TnRunMicrotasks()
|
|
11686
|
+
if TnLoopRunPending() {
|
|
11687
|
+
continue
|
|
11688
|
+
}
|
|
11689
|
+
tok := make(chan struct{})
|
|
11690
|
+
tnWakeMu.Lock()
|
|
11691
|
+
select {
|
|
11692
|
+
case v, ok := <-ch:
|
|
11693
|
+
tnWakeMu.Unlock()
|
|
11694
|
+
return v, ok
|
|
11695
|
+
default:
|
|
11696
|
+
tnAwaiting[any(ch)] = tok
|
|
11697
|
+
}
|
|
11698
|
+
tnWakeMu.Unlock()
|
|
11699
|
+
tnRelease()
|
|
11700
|
+
select {
|
|
11701
|
+
case v, ok := <-ch:
|
|
11702
|
+
// The value is taken; when a promise wake was queued (the token
|
|
11703
|
+
// is gone) it hands the baton over, else take the baton ourselves
|
|
11704
|
+
tnWakeMu.Lock()
|
|
11705
|
+
_, raw := tnAwaiting[any(ch)]
|
|
11706
|
+
if raw {
|
|
11707
|
+
delete(tnAwaiting, any(ch))
|
|
11708
|
+
}
|
|
11709
|
+
tnWakeMu.Unlock()
|
|
11710
|
+
if raw {
|
|
11711
|
+
tnAcquire()
|
|
11712
|
+
} else {
|
|
11713
|
+
<-tok
|
|
11714
|
+
}
|
|
11715
|
+
return v, ok
|
|
11716
|
+
case <-tok:
|
|
11717
|
+
}
|
|
11718
|
+
}
|
|
11719
|
+
}
|
|
11720
|
+
|
|
11721
|
+
// (baton holder) Receives from a channel of raw sends (generator yields),
|
|
11722
|
+
// running loop tasks while waiting
|
|
11723
|
+
func tnRawReceive[T any](ch chan T) (T, bool) {
|
|
11148
11724
|
ctx := tnAsyncCtx
|
|
11149
11725
|
defer func() { tnAsyncCtx = ctx }()
|
|
11150
11726
|
for {
|
|
@@ -11442,12 +12018,48 @@ func TnRejectExecutor[T any](ch chan T) {
|
|
|
11442
12018
|
}
|
|
11443
12019
|
}
|
|
11444
12020
|
|
|
11445
|
-
|
|
11446
|
-
|
|
12021
|
+
// Promise resolution: the value (or rejection) is sent and the parked awaiter
|
|
12022
|
+
// woken in settlement order — Node runs promise continuations as ordered
|
|
12023
|
+
// microtasks; a bare channel wake would race for the baton and resume out of
|
|
12024
|
+
// order on a starved machine
|
|
12025
|
+
func TnAsyncSend[T any](ch chan T, v T) {
|
|
12026
|
+
tok := make(chan struct{})
|
|
12027
|
+
handoff := false
|
|
12028
|
+
tnWakeMu.Lock()
|
|
11447
12029
|
select {
|
|
11448
|
-
case ch <-
|
|
12030
|
+
case ch <- v:
|
|
11449
12031
|
default:
|
|
11450
12032
|
}
|
|
12033
|
+
if t, parked := tnAwaiting[any(ch)]; parked {
|
|
12034
|
+
delete(tnAwaiting, any(ch))
|
|
12035
|
+
tok = t
|
|
12036
|
+
handoff = true
|
|
12037
|
+
}
|
|
12038
|
+
tnWakeMu.Unlock()
|
|
12039
|
+
if handoff {
|
|
12040
|
+
tnWakeQueue(tok)
|
|
12041
|
+
}
|
|
12042
|
+
}
|
|
12043
|
+
|
|
12044
|
+
func TnAsyncClose[T any](ch chan T) {
|
|
12045
|
+
tok := make(chan struct{})
|
|
12046
|
+
handoff := false
|
|
12047
|
+
tnWakeMu.Lock()
|
|
12048
|
+
close(ch)
|
|
12049
|
+
if t, parked := tnAwaiting[any(ch)]; parked {
|
|
12050
|
+
delete(tnAwaiting, any(ch))
|
|
12051
|
+
tok = t
|
|
12052
|
+
handoff = true
|
|
12053
|
+
}
|
|
12054
|
+
tnWakeMu.Unlock()
|
|
12055
|
+
if handoff {
|
|
12056
|
+
tnWakeQueue(tok)
|
|
12057
|
+
}
|
|
12058
|
+
}
|
|
12059
|
+
|
|
12060
|
+
func TnResolveZero[T any](ch chan T) {
|
|
12061
|
+
var zero T
|
|
12062
|
+
TnAsyncSend(ch, zero)
|
|
11451
12063
|
}
|
|
11452
12064
|
|
|
11453
12065
|
// resolve / reject of a Promise executor used as values
|
|
@@ -11459,10 +12071,7 @@ func TnResolver[T any](ch chan T) func(...interface{}) {
|
|
|
11459
12071
|
v = x
|
|
11460
12072
|
}
|
|
11461
12073
|
}
|
|
11462
|
-
|
|
11463
|
-
case ch <- v:
|
|
11464
|
-
default:
|
|
11465
|
-
}
|
|
12074
|
+
TnAsyncSend(ch, v)
|
|
11466
12075
|
}
|
|
11467
12076
|
}
|
|
11468
12077
|
|
|
@@ -11481,7 +12090,7 @@ func TnRejecter[T any](ch chan T) func(...interface{}) {
|
|
|
11481
12090
|
|
|
11482
12091
|
func TnReject[T any](ch chan T, reason interface{}) {
|
|
11483
12092
|
tnRejections.Store(ch, reason)
|
|
11484
|
-
|
|
12093
|
+
TnAsyncClose(ch)
|
|
11485
12094
|
}
|
|
11486
12095
|
|
|
11487
12096
|
// A detached call (\`main();\`): the process waits for it; a rejection is fatal
|
|
@@ -11535,6 +12144,18 @@ func TnAwait[T any](ch chan T) T {
|
|
|
11535
12144
|
return v
|
|
11536
12145
|
}
|
|
11537
12146
|
|
|
12147
|
+
// await in code running inline on the loop goroutine (an async callback — an
|
|
12148
|
+
// arrow, an event handler): the self-draining receive — this goroutine is the
|
|
12149
|
+
// loop, so it must keep running tasks while it waits
|
|
12150
|
+
func TnAwaitInline[T any](ch chan T) T {
|
|
12151
|
+
received, ok := tnRawReceive(ch)
|
|
12152
|
+
v, reason, rejected := tnSettled(ch, received, ok)
|
|
12153
|
+
if rejected {
|
|
12154
|
+
panic(reason)
|
|
12155
|
+
}
|
|
12156
|
+
return v
|
|
12157
|
+
}
|
|
12158
|
+
|
|
11538
12159
|
func TnPromiseReject[T any](reason interface{}) chan T {
|
|
11539
12160
|
ch := make(chan T)
|
|
11540
12161
|
TnReject(ch, reason)
|
|
@@ -11550,8 +12171,8 @@ func TnPromiseCatch[T any, E any](p chan T, onRejected func(E)) chan T {
|
|
|
11550
12171
|
e, _ := reason.(E)
|
|
11551
12172
|
TnLoopCall(func() { TnAsyncRun(ctx, func() { onRejected(e) }) })
|
|
11552
12173
|
}
|
|
11553
|
-
out
|
|
11554
|
-
|
|
12174
|
+
TnAsyncSend(out, v)
|
|
12175
|
+
TnAsyncClose(out)
|
|
11555
12176
|
}()
|
|
11556
12177
|
return out
|
|
11557
12178
|
}
|
|
@@ -11565,8 +12186,8 @@ func TnPromiseCatchValue[T any, E any](p chan T, onRejected func(E) T) chan T {
|
|
|
11565
12186
|
e, _ := reason.(E)
|
|
11566
12187
|
TnLoopCall(func() { TnAsyncRun(ctx, func() { v = onRejected(e) }) })
|
|
11567
12188
|
}
|
|
11568
|
-
out
|
|
11569
|
-
|
|
12189
|
+
TnAsyncSend(out, v)
|
|
12190
|
+
TnAsyncClose(out)
|
|
11570
12191
|
}()
|
|
11571
12192
|
return out
|
|
11572
12193
|
}
|
|
@@ -11581,8 +12202,8 @@ func TnPromiseFinally[T any](p chan T, onFinally func()) chan T {
|
|
|
11581
12202
|
TnReject(out, reason)
|
|
11582
12203
|
return
|
|
11583
12204
|
}
|
|
11584
|
-
out
|
|
11585
|
-
|
|
12205
|
+
TnAsyncSend(out, v)
|
|
12206
|
+
TnAsyncClose(out)
|
|
11586
12207
|
}()
|
|
11587
12208
|
return out
|
|
11588
12209
|
}
|
|
@@ -11599,8 +12220,8 @@ func TnPromiseRace[T any](chs []chan T) chan T {
|
|
|
11599
12220
|
TnReject(out, reason)
|
|
11600
12221
|
return
|
|
11601
12222
|
}
|
|
11602
|
-
out
|
|
11603
|
-
|
|
12223
|
+
TnAsyncSend(out, v)
|
|
12224
|
+
TnAsyncClose(out)
|
|
11604
12225
|
})
|
|
11605
12226
|
}(ch)
|
|
11606
12227
|
}
|
|
@@ -11625,8 +12246,8 @@ func TnPromiseAllSettled[T any](chs []chan T) chan []*TnSettled[T] {
|
|
|
11625
12246
|
results[i] = &TnSettled[T]{status: "fulfilled", value: v}
|
|
11626
12247
|
}
|
|
11627
12248
|
}
|
|
11628
|
-
out
|
|
11629
|
-
|
|
12249
|
+
TnAsyncSend(out, results)
|
|
12250
|
+
TnAsyncClose(out)
|
|
11630
12251
|
}()
|
|
11631
12252
|
return out
|
|
11632
12253
|
}
|
|
@@ -11650,8 +12271,8 @@ func TnPromiseAny[T any](chs []chan T) chan T {
|
|
|
11650
12271
|
for range chs {
|
|
11651
12272
|
select {
|
|
11652
12273
|
case v := <-values:
|
|
11653
|
-
out
|
|
11654
|
-
|
|
12274
|
+
TnAsyncSend(out, v)
|
|
12275
|
+
TnAsyncClose(out)
|
|
11655
12276
|
return
|
|
11656
12277
|
case <-failures:
|
|
11657
12278
|
}
|
|
@@ -11662,7 +12283,7 @@ func TnPromiseAny[T any](chs []chan T) chan T {
|
|
|
11662
12283
|
}`,
|
|
11663
12284
|
promiseAll: `// Promise.all: every channel drained in order, results collected
|
|
11664
12285
|
func TnPromiseAll[T any](chs []chan T) chan []T {
|
|
11665
|
-
out := make(chan []T)
|
|
12286
|
+
out := make(chan []T, 1)
|
|
11666
12287
|
go func() {
|
|
11667
12288
|
results := make([]T, len(chs))
|
|
11668
12289
|
for i, ch := range chs {
|
|
@@ -11673,8 +12294,8 @@ func TnPromiseAll[T any](chs []chan T) chan []T {
|
|
|
11673
12294
|
}
|
|
11674
12295
|
results[i] = v
|
|
11675
12296
|
}
|
|
11676
|
-
out
|
|
11677
|
-
|
|
12297
|
+
TnAsyncSend(out, results)
|
|
12298
|
+
TnAsyncClose(out)
|
|
11678
12299
|
}()
|
|
11679
12300
|
return out
|
|
11680
12301
|
}`,
|
|
@@ -12514,7 +13135,8 @@ function visitForOfSequence(node, iterExpr, iterType) {
|
|
|
12514
13135
|
registerLocalVariable(declaration.name.text, elemType);
|
|
12515
13136
|
// A rejected iterator (a stream error) throws out of the loop
|
|
12516
13137
|
useHelper('promise');
|
|
12517
|
-
|
|
13138
|
+
// Raw receive: iterator channels are fed by raw sends (generator yields)
|
|
13139
|
+
let awaitPrefix = `${valueVar}, __ok := tnRawReceive(${chanVar})\n\t\tif !__ok {\n\t\t\tif __reason, __rejected := tnRejections.Load(${chanVar}); __rejected {\n\t\t\t\tpanic(__reason)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t_ = ${valueVar}\n\t\t`;
|
|
12518
13140
|
if (declaration && isArrayBindingPattern(declaration.name)) {
|
|
12519
13141
|
const memberType = elemType.startsWith('[]') ? elemType.slice(2) : undefined;
|
|
12520
13142
|
useHelper('dynamic');
|