typenative 0.6.0 → 0.6.1
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 +69 -0
- package/README.md +2 -1
- package/bin/node/core.js +5 -0
- package/bin/node/events.js +139 -5
- package/bin/node/http.js +1265 -127
- package/bin/node/stream.js +56 -7
- package/bin/node/stream_web.js +2 -2
- package/bin/node/url.js +27 -2
- package/bin/regex_vm.js +50 -2
- package/bin/transpiler.js +1340 -184
- package/bin/version.js +1 -1
- package/examples/README.md +28 -29
- package/examples/angular-templates/README.md +22 -20
- package/examples/json-server/README.md +16 -13
- package/examples/marked-cli/README.md +37 -22
- package/examples/marked-cli/main.ts +122 -4
- package/examples/react-compiler/README.md +56 -41
- package/examples/react-compiler/main.ts +173 -7
- package/examples/react-compiler/run-node.mjs +2 -0
- package/examples/yaml-cli/README.md +36 -30
- package/examples/yaml-cli/main.ts +236 -14
- package/package.json +1 -1
- package/performance/README.md +1 -0
package/bin/transpiler.js
CHANGED
|
@@ -1465,6 +1465,144 @@ function findLocalConst(name) {
|
|
|
1465
1465
|
}
|
|
1466
1466
|
return undefined;
|
|
1467
1467
|
}
|
|
1468
|
+
// Whether converting expr to another object type is the only conversion its
|
|
1469
|
+
// object ever gets, so the copy needs no identity entry (TnAsCopy). It holds
|
|
1470
|
+
// when expr names a const of the enclosing function whose object was made
|
|
1471
|
+
// right there (an object literal, or a call of a function declaration whose
|
|
1472
|
+
// every return is an object literal) and nothing else ever sees that object:
|
|
1473
|
+
// every other use of the name is a field read (v.f), the uses that aren't
|
|
1474
|
+
// are call arguments of which at most one runs per call (any two sit in the
|
|
1475
|
+
// opposite branches of a ?: or an if), and no loop or function lies between
|
|
1476
|
+
// the declaration and such a use (it runs at most once per object)
|
|
1477
|
+
const unsharedSources = new WeakMap();
|
|
1478
|
+
function unsharedConversionSource(expr) {
|
|
1479
|
+
const id = unwrapParentheses(expr);
|
|
1480
|
+
if (!isIdentifier(id))
|
|
1481
|
+
return false;
|
|
1482
|
+
const declaration = findLocalConst(id);
|
|
1483
|
+
if (!declaration)
|
|
1484
|
+
return false;
|
|
1485
|
+
let unshared = unsharedSources.get(declaration);
|
|
1486
|
+
if (unshared === undefined) {
|
|
1487
|
+
unshared = isUnsharedConst(declaration, id);
|
|
1488
|
+
unsharedSources.set(declaration, unshared);
|
|
1489
|
+
}
|
|
1490
|
+
return unshared;
|
|
1491
|
+
}
|
|
1492
|
+
function isUnsharedConst(declaration, use) {
|
|
1493
|
+
const list = declaration.parent;
|
|
1494
|
+
const block = list?.parent?.parent;
|
|
1495
|
+
if (!isIdentifier(declaration.name) || list?.kind !== 'VariableDeclarationList' || list.declarationKind !== 'const')
|
|
1496
|
+
return false;
|
|
1497
|
+
if (!isVariableStatement(list.parent) || block?.kind !== 'Block' || !getEnclosingFunction(declaration))
|
|
1498
|
+
return false;
|
|
1499
|
+
if (!makesFreshObject(declaration.initializer, declaration))
|
|
1500
|
+
return false;
|
|
1501
|
+
const name = declaration.name.text;
|
|
1502
|
+
const passes = [];
|
|
1503
|
+
let ok = true;
|
|
1504
|
+
const walk = (node) => {
|
|
1505
|
+
if (!ok || !node)
|
|
1506
|
+
return;
|
|
1507
|
+
if (isIdentifier(node) && node.text === name && node !== declaration.name) {
|
|
1508
|
+
const parent = node.parent;
|
|
1509
|
+
// (a name that isn't a reference: a property's, a declaration's)
|
|
1510
|
+
if (parent?.name === node && parent.kind !== 'ShorthandPropertyAssignment')
|
|
1511
|
+
return;
|
|
1512
|
+
if (isPropertyAccessExpression(parent) && parent.expression === node) {
|
|
1513
|
+
// (a method call would hand the object over as this)
|
|
1514
|
+
if (isCallExpression(parent.parent) && parent.parent.expression === parent)
|
|
1515
|
+
ok = false;
|
|
1516
|
+
return;
|
|
1517
|
+
}
|
|
1518
|
+
if (isCallExpression(parent) && (parent.arguments ?? []).includes(node))
|
|
1519
|
+
passes.push(node);
|
|
1520
|
+
else
|
|
1521
|
+
ok = false;
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
for (const child of childNodes(node))
|
|
1525
|
+
walk(child);
|
|
1526
|
+
};
|
|
1527
|
+
walk(block);
|
|
1528
|
+
if (!ok || !passes.includes(use))
|
|
1529
|
+
return false;
|
|
1530
|
+
// each pass runs at most once per object…
|
|
1531
|
+
for (const pass of passes) {
|
|
1532
|
+
for (let n = pass.parent; n && n !== block; n = n.parent) {
|
|
1533
|
+
if (FUNCTION_LIKE_KINDS.has(n.kind) || LOOP_KINDS.includes(n.kind))
|
|
1534
|
+
return false;
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
// …and no two in one call
|
|
1538
|
+
for (let i = 0; i < passes.length; i++) {
|
|
1539
|
+
for (let j = i + 1; j < passes.length; j++) {
|
|
1540
|
+
if (!exclusiveBranches(passes[i], passes[j], block))
|
|
1541
|
+
return false;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return true;
|
|
1545
|
+
}
|
|
1546
|
+
// Whether a and b (under root) sit in the opposite branches of a ?: or an if
|
|
1547
|
+
function exclusiveBranches(a, b, root) {
|
|
1548
|
+
const childOnPath = new Map();
|
|
1549
|
+
for (let child = a, n = a.parent; n && child !== root; child = n, n = n.parent)
|
|
1550
|
+
childOnPath.set(n, child);
|
|
1551
|
+
for (let child = b, n = b.parent; n && child !== root; child = n, n = n.parent) {
|
|
1552
|
+
const fromA = childOnPath.get(n);
|
|
1553
|
+
if (fromA === undefined)
|
|
1554
|
+
continue;
|
|
1555
|
+
if (isConditionalExpression(n)) {
|
|
1556
|
+
return (fromA === n.whenTrue && child === n.whenFalse) || (fromA === n.whenFalse && child === n.whenTrue);
|
|
1557
|
+
}
|
|
1558
|
+
if (isIfStatement(n)) {
|
|
1559
|
+
return (fromA === n.thenStatement && child === n.elseStatement) || (fromA === n.elseStatement && child === n.thenStatement);
|
|
1560
|
+
}
|
|
1561
|
+
return false;
|
|
1562
|
+
}
|
|
1563
|
+
return false;
|
|
1564
|
+
}
|
|
1565
|
+
// Whether an initializer makes a new object no one else holds: an object
|
|
1566
|
+
// literal, or a call of a function declaration (not shadowed where it's
|
|
1567
|
+
// called) whose every return is an object literal
|
|
1568
|
+
function makesFreshObject(init, at) {
|
|
1569
|
+
const e = init ? unwrapParentheses(init) : undefined;
|
|
1570
|
+
if (!e)
|
|
1571
|
+
return false;
|
|
1572
|
+
if (isObjectLiteralExpression(e))
|
|
1573
|
+
return true;
|
|
1574
|
+
if (!isCallExpression(e) || !isIdentifier(e.expression) || e.questionDotToken)
|
|
1575
|
+
return false;
|
|
1576
|
+
const callee = e.expression.text;
|
|
1577
|
+
const fn = declaredFunctions.get(callee);
|
|
1578
|
+
if (!fn || !isFunctionDeclaration(fn) || !fn.body || fn.asteriskToken || asyncFunctionNames.has(callee))
|
|
1579
|
+
return false;
|
|
1580
|
+
if (findLocalConst(e.expression))
|
|
1581
|
+
return false;
|
|
1582
|
+
for (let f = getEnclosingFunction(at); f; f = getEnclosingFunction(f)) {
|
|
1583
|
+
if ((f.parameters ?? []).some((p) => isIdentifier(p.name) && p.name.text === callee))
|
|
1584
|
+
return false;
|
|
1585
|
+
}
|
|
1586
|
+
let returns = 0;
|
|
1587
|
+
let fresh = true;
|
|
1588
|
+
const walk = (node) => {
|
|
1589
|
+
if (!fresh || !node)
|
|
1590
|
+
return;
|
|
1591
|
+
if (node !== fn.body && FUNCTION_LIKE_KINDS.has(node.kind))
|
|
1592
|
+
return;
|
|
1593
|
+
if (isReturnStatement(node)) {
|
|
1594
|
+
returns++;
|
|
1595
|
+
const value = node.expression ? unwrapParentheses(node.expression) : undefined;
|
|
1596
|
+
if (!value || !isObjectLiteralExpression(value))
|
|
1597
|
+
fresh = false;
|
|
1598
|
+
return;
|
|
1599
|
+
}
|
|
1600
|
+
for (const child of childNodes(node))
|
|
1601
|
+
walk(child);
|
|
1602
|
+
};
|
|
1603
|
+
walk(fn.body);
|
|
1604
|
+
return fresh && returns > 0;
|
|
1605
|
+
}
|
|
1468
1606
|
function maybeUndefinedPrimitive(expr, consts, depth = 0) {
|
|
1469
1607
|
const e = unwrapParentheses(expr);
|
|
1470
1608
|
if (!e || depth > 4)
|
|
@@ -3234,6 +3372,24 @@ function calledFunctionDeclaration(name, at) {
|
|
|
3234
3372
|
}
|
|
3235
3373
|
function linkParents(node, parent) {
|
|
3236
3374
|
node.parent = parent;
|
|
3375
|
+
// A generic type parameter, or a type declared inside a function, names no
|
|
3376
|
+
// package-level Go type: a dynamic call's dispatcher cannot mention it
|
|
3377
|
+
if (Array.isArray(node.typeParameters)) {
|
|
3378
|
+
for (const tp of node.typeParameters)
|
|
3379
|
+
if (tp.name?.text) {
|
|
3380
|
+
genericGoParams.add(tp.name.text);
|
|
3381
|
+
genericGoParams.add(getSafeName(tp.name.text));
|
|
3382
|
+
}
|
|
3383
|
+
}
|
|
3384
|
+
if ((node.kind === 'TypeAliasDeclaration' || node.kind === 'InterfaceDeclaration' || node.kind === 'ClassDeclaration' || node.kind === 'EnumDeclaration') && node.name?.text) {
|
|
3385
|
+
for (let p = parent; p && p.kind !== 'SourceFile' && p.kind !== 'ModuleBlock'; p = p.parent) {
|
|
3386
|
+
if (FUNCTION_LIKE_KINDS.has(p.kind)) {
|
|
3387
|
+
localGoTypes.add(node.name.text);
|
|
3388
|
+
localGoTypes.add(getSafeName(node.name.text));
|
|
3389
|
+
break;
|
|
3390
|
+
}
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3237
3393
|
// f!(…) / o.m!(…): the assertion has no run-time effect — the plain call
|
|
3238
3394
|
while (node.kind === 'CallExpression' && node.expression?.kind === 'NonNullExpression')
|
|
3239
3395
|
node.expression = node.expression.expression;
|
|
@@ -3328,6 +3484,16 @@ const defaultImportNamespaces = new Set();
|
|
|
3328
3484
|
// Go helper functions required by the current transpilation (e.g. 'exec', 'readFile').
|
|
3329
3485
|
// Helper sources are appended to every generated Go file that references them.
|
|
3330
3486
|
const usedHelpers = new Set();
|
|
3487
|
+
// The Go func types of the function values this program creates (see
|
|
3488
|
+
// tnCallValueTyped): dynamic calls of those run without reflect.Value.Call.
|
|
3489
|
+
const dynamicFuncTypes = new Set();
|
|
3490
|
+
// Type names a function value's Go type cannot mention outside its own scope:
|
|
3491
|
+
// types declared inside functions, and generic type parameters
|
|
3492
|
+
const localGoTypes = new Set();
|
|
3493
|
+
const genericGoParams = new Set();
|
|
3494
|
+
// Enum Go types emitted as aliases of a primitive (type Kind = string): a
|
|
3495
|
+
// function type mentioning one is the primitive's type (deduped for Go)
|
|
3496
|
+
const primitiveEnumGoTypes = new Map();
|
|
3331
3497
|
// Packages that were imported only because a helper needs them. Tracked so
|
|
3332
3498
|
// per-file import lists can exclude them (helpers are emitted once, in the
|
|
3333
3499
|
// main file, which carries these imports instead).
|
|
@@ -3357,6 +3523,9 @@ export function transpileToNative(code, options) {
|
|
|
3357
3523
|
declaredInterfaces.clear();
|
|
3358
3524
|
interfacesByOriginalName.clear();
|
|
3359
3525
|
declaredTypeAliases.clear();
|
|
3526
|
+
// (rebuilt by linkParents while the files are parsed below)
|
|
3527
|
+
localGoTypes.clear();
|
|
3528
|
+
genericGoParams.clear();
|
|
3360
3529
|
variableTypeNodes.clear();
|
|
3361
3530
|
goRefVariables.clear();
|
|
3362
3531
|
narrowedVariables.clear();
|
|
@@ -3458,6 +3627,8 @@ export function transpileToNative(code, options) {
|
|
|
3458
3627
|
functionsUsedAsValuesCache = undefined;
|
|
3459
3628
|
referenceArrays.clear();
|
|
3460
3629
|
usedHelpers.clear();
|
|
3630
|
+
dynamicFuncTypes.clear();
|
|
3631
|
+
primitiveEnumGoTypes.clear();
|
|
3461
3632
|
helperProvidedPackages.clear();
|
|
3462
3633
|
mainPackageVariables.length = 0;
|
|
3463
3634
|
keyOrderTables.clear();
|
|
@@ -4298,6 +4469,12 @@ function visitNode(node, options = {}) {
|
|
|
4298
4469
|
useHelper('getenv');
|
|
4299
4470
|
return `TnGetenv(${visit(node.argumentExpression)})`;
|
|
4300
4471
|
}
|
|
4472
|
+
// [...s][i]: the i-th code point, without building the array of them
|
|
4473
|
+
const spreadString = stringSpreadSource(node.expression);
|
|
4474
|
+
if (spreadString && !isAssignmentTarget(node)) {
|
|
4475
|
+
useHelper('dynamic');
|
|
4476
|
+
return `TnCharAt(${visit(spreadString)}, ${numericIndex(node.argumentExpression)})`;
|
|
4477
|
+
}
|
|
4301
4478
|
// Maps (Record/Map) and string keys index directly; arrays/strings need an int index
|
|
4302
4479
|
const targetType = inferExpressionType(node.expression);
|
|
4303
4480
|
if (targetType === 'string') {
|
|
@@ -4582,6 +4759,14 @@ function visitNode(node, options = {}) {
|
|
|
4582
4759
|
if (owner)
|
|
4583
4760
|
return `${owner}_${node.name.kind === 'PrivateIdentifier' ? visit(node.name) : goFieldName(memberName)}`;
|
|
4584
4761
|
}
|
|
4762
|
+
// [...s].length: the string's code point count, without building the array
|
|
4763
|
+
if (node.name.text === 'length' && !isCallee(node) && !isAssignmentTarget(node)) {
|
|
4764
|
+
const spreadString = stringSpreadSource(node.expression);
|
|
4765
|
+
if (spreadString) {
|
|
4766
|
+
useHelper('strIndex');
|
|
4767
|
+
return `TnStrLength(${visit(spreadString)})`;
|
|
4768
|
+
}
|
|
4769
|
+
}
|
|
4585
4770
|
const leftSide = visit(node.expression);
|
|
4586
4771
|
const rightSide = visit(node.name);
|
|
4587
4772
|
const objectType = resolveExpressionType(node.expression);
|
|
@@ -4634,13 +4819,17 @@ function visitNode(node, options = {}) {
|
|
|
4634
4819
|
!leftGoType?.startsWith('*TnMap[') &&
|
|
4635
4820
|
!leftGoType?.includes('struct{') &&
|
|
4636
4821
|
!leftGoType?.startsWith('*[]')) {
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4822
|
+
// (a plain function's this typed as a class: its getters too)
|
|
4823
|
+
const typedClass = leftGoType?.startsWith('*') && leftGoType.slice(1).replace(/\[.*\]$/, '');
|
|
4824
|
+
const className = typedClass && classNames.has(typedClass)
|
|
4825
|
+
? typedClass
|
|
4826
|
+
: node.expression.kind === 'ThisKeyword'
|
|
4827
|
+
? getEnclosingClassName(node)
|
|
4828
|
+
: leftGoType
|
|
4829
|
+
? leftGoType.slice(1).replace(/\[.*\]$/, '')
|
|
4830
|
+
: undefined;
|
|
4642
4831
|
const accessorName = memberKey(node.name);
|
|
4643
|
-
if (className && classGetterMethods.has(`${className}.${accessorName}`)) {
|
|
4832
|
+
if (className && (classGetterMethods.has(`${className}.${accessorName}`) || classMember(className, 'get', accessorName))) {
|
|
4644
4833
|
return `${leftSide}.Get_${rightSide}()`;
|
|
4645
4834
|
}
|
|
4646
4835
|
}
|
|
@@ -5212,7 +5401,7 @@ function visitNode(node, options = {}) {
|
|
|
5212
5401
|
const args = (node.arguments ?? []).map((a) => `, ${toGoValueOfType(a, 'interface{}')}`).join('');
|
|
5213
5402
|
return `TnCallValue(${visit(node.expression)}${args})`;
|
|
5214
5403
|
}
|
|
5215
|
-
if (isUndeclaredClassMember(node.expression) && !(node.arguments ?? []).some((a) => isSpreadElement(a))) {
|
|
5404
|
+
if (isUndeclaredClassMember(node.expression) && !hasQuestionDot(node.expression) && !(node.arguments ?? []).some((a) => isSpreadElement(a))) {
|
|
5216
5405
|
useHelper('dynamic');
|
|
5217
5406
|
useHelper('error');
|
|
5218
5407
|
const args = (node.arguments ?? []).map((a) => `, ${toGoValueOfType(a, 'interface{}')}`).join('');
|
|
@@ -6148,7 +6337,7 @@ function visitNode(node, options = {}) {
|
|
|
6148
6337
|
? getEnclosingClassName(node)
|
|
6149
6338
|
: undefined;
|
|
6150
6339
|
const setterName = memberKey(node.left.name);
|
|
6151
|
-
if (setterClass && classSetterMethods.has(`${setterClass}.${setterName}`)) {
|
|
6340
|
+
if (setterClass && (classSetterMethods.has(`${setterClass}.${setterName}`) || classMember(setterClass, 'set', setterName))) {
|
|
6152
6341
|
return `${visit(node.left.expression)}.Set_${visit(node.left.name)}(${visit(node.right)})`;
|
|
6153
6342
|
}
|
|
6154
6343
|
}
|
|
@@ -6790,12 +6979,11 @@ function visitNode(node, options = {}) {
|
|
|
6790
6979
|
return '';
|
|
6791
6980
|
}
|
|
6792
6981
|
const typeParams = getTypeParameters(node.typeParameters, node);
|
|
6982
|
+
// (before the parameters: a default `p = this` reads __this)
|
|
6983
|
+
const thisPrologueCode = !isPropertyAssignment(node.parent) ? thisPrologue(node) : '';
|
|
6793
6984
|
const parameterInfo = withContextualParameters(node, getFunctionParametersInfo(node.parameters ?? []));
|
|
6794
|
-
if (
|
|
6795
|
-
|
|
6796
|
-
if (prologue)
|
|
6797
|
-
parameterInfo.prefixBlockContent = prologue + (parameterInfo.prefixBlockContent ?? '');
|
|
6798
|
-
}
|
|
6985
|
+
if (thisPrologueCode)
|
|
6986
|
+
parameterInfo.prefixBlockContent = thisPrologueCode + (parameterInfo.prefixBlockContent ?? '');
|
|
6799
6987
|
if (node.body && isBlock(node.body)) {
|
|
6800
6988
|
prescanVariableDeclarations(node.body);
|
|
6801
6989
|
}
|
|
@@ -6807,6 +6995,7 @@ function visitNode(node, options = {}) {
|
|
|
6807
6995
|
// (a function returning one of its arguments' array fields returns a
|
|
6808
6996
|
// reference to it: see returnsArrayReference)
|
|
6809
6997
|
const returnType = inferredRetType ? ` ${returnsArrayReference(node) ? '*' : ''}${inferredRetType}` : '';
|
|
6998
|
+
registerFunctionGoType(emittedFuncGoType(parameterInfo.signature, returnType));
|
|
6810
6999
|
if (options.isOutside) {
|
|
6811
7000
|
// async functions run their body in a goroutine sending over a channel
|
|
6812
7001
|
const isAsync = (node.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword');
|
|
@@ -6872,6 +7061,7 @@ function visitNode(node, options = {}) {
|
|
|
6872
7061
|
? withFunctionScopeTypes(node, () => inferFunctionBodyReturnType(node) ?? '') || undefined
|
|
6873
7062
|
: inferFunctionBodyReturnType(node);
|
|
6874
7063
|
const returnType = inferredRetType ? ` ${inferredRetType}` : '';
|
|
7064
|
+
registerFunctionGoType(emittedFuncGoType(parameterInfo.signature, returnType));
|
|
6875
7065
|
if (parameterInfo.prefixBlockContent && !isBlock(node.body)) {
|
|
6876
7066
|
return `func(${parameterInfo.signature})${returnType} {\n\t\t${coverageEnter(node)}${parameterInfo.prefixBlockContent}return ${toGoValueOfType(node.body, inferredRetType)};\n\t}`;
|
|
6877
7067
|
}
|
|
@@ -8031,6 +8221,65 @@ function isNilPlaceholder(expr) {
|
|
|
8031
8221
|
const u = unwrapParentheses(expr);
|
|
8032
8222
|
return isNonNullExpression(u) && isNilLiteral(unwrapParentheses(u.expression));
|
|
8033
8223
|
}
|
|
8224
|
+
// The Go fields of an object type (named or anonymous), as name → type
|
|
8225
|
+
function goStructFields(bare) {
|
|
8226
|
+
if (bare.startsWith('struct{'))
|
|
8227
|
+
return parseStructFields(bare);
|
|
8228
|
+
if (classNames.has(bare))
|
|
8229
|
+
return undefined;
|
|
8230
|
+
const properties = objectTypeFields(bare);
|
|
8231
|
+
if (!properties)
|
|
8232
|
+
return undefined;
|
|
8233
|
+
const fields = [...properties].map(([name, type]) => [goFieldName(name), type]);
|
|
8234
|
+
if (objectTypeHasKeyOrder(bare))
|
|
8235
|
+
fields.push(['__keys', '*[]string']);
|
|
8236
|
+
return fields;
|
|
8237
|
+
}
|
|
8238
|
+
// A conversion between two statically known struct types whose fields line up
|
|
8239
|
+
// by name: a struct literal, instead of the reflective TnAs plan. Only for a
|
|
8240
|
+
// source no other conversion can see (see unsharedConversionSource), so the
|
|
8241
|
+
// copy needs no identity entry. A target __keys field the source lacks stays
|
|
8242
|
+
// zero, as TnAs leaves it.
|
|
8243
|
+
function staticStructConversion(expr, goType, code) {
|
|
8244
|
+
if (!goType.startsWith('*') || goType.startsWith('*TnMap[') || goType.startsWith('*[]'))
|
|
8245
|
+
return undefined;
|
|
8246
|
+
const target = goType.slice(1);
|
|
8247
|
+
const targetFields = goStructFields(target);
|
|
8248
|
+
if (!targetFields)
|
|
8249
|
+
return undefined;
|
|
8250
|
+
const exprType = inferExpressionType(expr) ?? '';
|
|
8251
|
+
if (!exprType.startsWith('*'))
|
|
8252
|
+
return undefined;
|
|
8253
|
+
const source = exprType.slice(1);
|
|
8254
|
+
if (source === target)
|
|
8255
|
+
return undefined;
|
|
8256
|
+
const sourceFields = goStructFields(source);
|
|
8257
|
+
if (!sourceFields)
|
|
8258
|
+
return undefined;
|
|
8259
|
+
// (a prefix relationship is a union member view in TnAs — identity, not a copy)
|
|
8260
|
+
const targetNames = targetFields.map(([name]) => name);
|
|
8261
|
+
const sourceNames = sourceFields.map(([name]) => name);
|
|
8262
|
+
const isPrefix = (a, b) => a.length <= b.length && a.every((name, i) => name === b[i]);
|
|
8263
|
+
if (isPrefix(targetNames, sourceNames) || isPrefix(sourceNames, targetNames))
|
|
8264
|
+
return undefined;
|
|
8265
|
+
const sourceByName = new Map(sourceFields);
|
|
8266
|
+
const parts = [];
|
|
8267
|
+
for (const [name, fieldType] of targetFields) {
|
|
8268
|
+
if (name === '__keys')
|
|
8269
|
+
continue;
|
|
8270
|
+
const from = sourceByName.get(name);
|
|
8271
|
+
// (a target field the source lacks reads the source's expandos: a copy)
|
|
8272
|
+
if (from === undefined)
|
|
8273
|
+
return undefined;
|
|
8274
|
+
parts.push(`${name}: ${from === fieldType ? `__s.${name}` : convertBetweenGoTypes(`__s.${name}`, from, fieldType)}`);
|
|
8275
|
+
}
|
|
8276
|
+
if (parts.length === 0 || !unsharedConversionSource(expr))
|
|
8277
|
+
return undefined;
|
|
8278
|
+
// (the key order is the source's own, when it has one)
|
|
8279
|
+
if (sourceByName.has('__keys') && targetFields.some(([name]) => name === '__keys'))
|
|
8280
|
+
parts.push('__keys: __s.__keys');
|
|
8281
|
+
return `func() ${goType} { __s := ${code}; _ = __s; return &${target}{${parts.join(', ')}} }()`;
|
|
8282
|
+
}
|
|
8034
8283
|
function toGoValueOfType(expr, goType) {
|
|
8035
8284
|
// (JSON.parse(text) as T[]: decoded straight into the type, see TnJSONParseTyped)
|
|
8036
8285
|
const typedJSON = typedJSONParse(expr, goType);
|
|
@@ -8463,7 +8712,10 @@ function toGoValueOfType(expr, goType) {
|
|
|
8463
8712
|
// re.exec(s) / s.match(re): no match is null, not an empty array
|
|
8464
8713
|
const call = unwrapParentheses(expr);
|
|
8465
8714
|
if (isCallExpression(call) && isPropertyAccessExpression(call.expression) && MAYBE_MISSING_METHODS.has(call.expression.name.text)) {
|
|
8466
|
-
|
|
8715
|
+
// (a helper allocates the box only on a match: a miss returns nil
|
|
8716
|
+
// without the closure object and box a local `&__v` costs every call)
|
|
8717
|
+
useHelper('slicePtr');
|
|
8718
|
+
return `TnSlicePtr(${visit(expr)})`;
|
|
8467
8719
|
}
|
|
8468
8720
|
// f() declared to return T[] | undefined, c ? xs : undefined: undefined stays nil
|
|
8469
8721
|
const declaredResult = isCallExpression(call) && isIdentifier(call.expression) ? declaredFunctions.get(call.expression.text)?.type : undefined;
|
|
@@ -8481,13 +8733,15 @@ function toGoValueOfType(expr, goType) {
|
|
|
8481
8733
|
: () => visit(expr);
|
|
8482
8734
|
// (an optional chain: a?.items is undefined when a is)
|
|
8483
8735
|
if (nullableResult || nullishBranch || isOptionalChain(call)) {
|
|
8484
|
-
|
|
8736
|
+
useHelper('slicePtr');
|
|
8737
|
+
return `TnSlicePtr(${boxedRead()})`;
|
|
8485
8738
|
}
|
|
8486
8739
|
// a read out of a Map / Record: undefined (nil) when the key is missing,
|
|
8487
8740
|
// not a pointer to the map's zero-length value
|
|
8488
8741
|
const lookup = getMapLookup(call);
|
|
8489
8742
|
if (lookup && (extractMapValueType(inferExpressionType(lookup.mapNode) ?? '') ?? '') === goType.slice(1)) {
|
|
8490
|
-
|
|
8743
|
+
useHelper('slicePtr');
|
|
8744
|
+
return `func() ${goType} { if __v, __ok := ${lookup.map}.Lookup(${lookup.key}); __ok { return TnSlicePtr(__v) }; return nil }()`;
|
|
8491
8745
|
}
|
|
8492
8746
|
return `func() ${goType} { __v := ${boxedRead()}; return &__v }()`;
|
|
8493
8747
|
}
|
|
@@ -8567,14 +8821,20 @@ function toGoValueOfType(expr, goType) {
|
|
|
8567
8821
|
}
|
|
8568
8822
|
}
|
|
8569
8823
|
// a value of another object type where a struct is expected (TS types are
|
|
8570
|
-
// structural):
|
|
8824
|
+
// structural): a struct literal when both types are known, else converted
|
|
8825
|
+
// field by field at run time (a copy)
|
|
8571
8826
|
if (goType?.startsWith('*') && isStructGoType(goType.slice(1)) && !isNilLiteral(expr) && !isObjectLiteralExpression(unwrapParentheses(expr))) {
|
|
8827
|
+
const statically = staticStructConversion(expr, goType, code);
|
|
8828
|
+
if (statically)
|
|
8829
|
+
return statically;
|
|
8572
8830
|
const exprType = inferExpressionType(expr) ?? '';
|
|
8573
8831
|
// (a class instance as an object type: its fields, copied)
|
|
8574
8832
|
const fromClass = classNames.has(exprType.slice(1)) && !isPolymorphicClass(exprType.slice(1));
|
|
8575
8833
|
if (exprType.startsWith('*') && exprType !== goType && (isStructGoType(exprType.slice(1)) || fromClass) && !classNames.has(goType.slice(1))) {
|
|
8576
8834
|
useHelper('dynamic');
|
|
8577
|
-
|
|
8835
|
+
// (an object no other conversion can see: copied without an identity entry)
|
|
8836
|
+
const as = !fromClass && unsharedConversionSource(expr) ? 'TnAsCopy' : 'TnAs';
|
|
8837
|
+
return `${as}[${goType}](interface{}(${code}))`;
|
|
8578
8838
|
}
|
|
8579
8839
|
}
|
|
8580
8840
|
// *Struct slot: take the address (shares the value, like a JS object reference)
|
|
@@ -9365,6 +9625,15 @@ function visitDynamicArithmetic(node, op) {
|
|
|
9365
9625
|
useHelper('dynamic');
|
|
9366
9626
|
return `${visit(node.left)} = ${converted}`;
|
|
9367
9627
|
}
|
|
9628
|
+
// s += x on a string variable or field, x dynamic (a stream's data chunk):
|
|
9629
|
+
// appended in place when s is long, as for a string x (see strAppend)
|
|
9630
|
+
if (op === '+=' && isConcat && inferExpressionType(node.left) === 'string') {
|
|
9631
|
+
const target = visit(node.left);
|
|
9632
|
+
if (/^[A-Za-z_][\wǂ]*(\.[A-Za-z_][\wǂ]*)*$/.test(target)) {
|
|
9633
|
+
useHelper('strAppend');
|
|
9634
|
+
return `${target} = TnStrAppend(${target}, ${operand(node.right, rightDynamic)})`;
|
|
9635
|
+
}
|
|
9636
|
+
}
|
|
9368
9637
|
return `${operand(node.left, leftDynamic && !isCompound)} ${op} ${operand(node.right, rightDynamic)}`;
|
|
9369
9638
|
}
|
|
9370
9639
|
// `x === v` where x is *T and v is T: equal only when x is non-nil and *x == v
|
|
@@ -11530,6 +11799,11 @@ let currentCallNode;
|
|
|
11530
11799
|
// Expressions emitted as statements though their parent would use the value
|
|
11531
11800
|
// (a void arrow's expression body)
|
|
11532
11801
|
const discardedExpressions = new Set();
|
|
11802
|
+
// The expressions whose truthiness (only) is used — a condition, an operand
|
|
11803
|
+
// of ! or && / || — and the primitive type an optional chain emitted for one
|
|
11804
|
+
// (its undefined is its zero value, which is falsy too: no boxed pointer)
|
|
11805
|
+
const truthinessOperands = new WeakSet();
|
|
11806
|
+
const truthinessPrimitiveType = new WeakMap();
|
|
11533
11807
|
function isDiscardedValue(node) {
|
|
11534
11808
|
if (discardedExpressions.has(node))
|
|
11535
11809
|
return true;
|
|
@@ -13948,6 +14222,18 @@ function spreadIterableClassArguments(node) {
|
|
|
13948
14222
|
arg.expression = array;
|
|
13949
14223
|
}
|
|
13950
14224
|
}
|
|
14225
|
+
// The string behind [...s] (an array literal holding just that spread), when
|
|
14226
|
+
// the array is only built to be measured or indexed: [...s].length is the code
|
|
14227
|
+
// point count and [...s][i] the i-th code point, without building the array
|
|
14228
|
+
function stringSpreadSource(expr) {
|
|
14229
|
+
const node = unwrapParentheses(expr);
|
|
14230
|
+
if (!isArrayLiteralExpression(node) || (node.elements ?? []).length !== 1)
|
|
14231
|
+
return undefined;
|
|
14232
|
+
const element = node.elements[0];
|
|
14233
|
+
if (!element || !isSpreadElement(element))
|
|
14234
|
+
return undefined;
|
|
14235
|
+
return inferExpressionType(element.expression) === 'string' ? element.expression : undefined;
|
|
14236
|
+
}
|
|
13951
14237
|
// A spread source as a Go slice; Sets spread their elements (map keys) and
|
|
13952
14238
|
// strings spread into []string of runes (like JS [...str])
|
|
13953
14239
|
function visitSpreadSource(expr) {
|
|
@@ -15846,6 +16132,9 @@ function inferExpressionTypeOf(expr) {
|
|
|
15846
16132
|
}
|
|
15847
16133
|
if (ownerType === '*regexp.Regexp' || ownerType === '*TnRegex') {
|
|
15848
16134
|
if (methodName === 'exec') {
|
|
16135
|
+
// (only tested for presence: a boolean)
|
|
16136
|
+
if (onlyTestedForTruthiness(expr))
|
|
16137
|
+
return 'bool';
|
|
15849
16138
|
// Named-group patterns return a match object with a .groups record
|
|
15850
16139
|
const receiver = expr.expression.expression;
|
|
15851
16140
|
// (on the RE2 path: the backtracking engine's exec gives the match array)
|
|
@@ -16581,6 +16870,7 @@ function isLogicalOperator(token) {
|
|
|
16581
16870
|
}
|
|
16582
16871
|
// JS truthiness of an expression as a Go bool, by its Go type
|
|
16583
16872
|
function toGoCondition(expr) {
|
|
16873
|
+
truthinessOperands.add(expr);
|
|
16584
16874
|
if (isParenthesizedExpression(expr))
|
|
16585
16875
|
return `(${toGoCondition(expr.expression)})`;
|
|
16586
16876
|
if (isPrefixUnaryExpression(expr) && expr.operator === 'ExclamationToken') {
|
|
@@ -16598,7 +16888,11 @@ function toGoCondition(expr) {
|
|
|
16598
16888
|
// and is undefined: false)
|
|
16599
16889
|
if (isCallExpression(unwrapParentheses(expr)) && emitsNoValue(expr))
|
|
16600
16890
|
return `func() bool { ${visit(expr, { inline: true })}; return false }()`;
|
|
16601
|
-
|
|
16891
|
+
const type = inferExpressionType(expr);
|
|
16892
|
+
const code = visit(expr, { inline: true });
|
|
16893
|
+
// (an optional chain's primitive result for a truthiness operand is emitted
|
|
16894
|
+
// unboxed — no pointer to test)
|
|
16895
|
+
return truthinessCheck(code, truthinessPrimitiveType.get(expr) ?? type);
|
|
16602
16896
|
}
|
|
16603
16897
|
// Whether every case of a switch is a distinct, non-empty string literal
|
|
16604
16898
|
function switchHasOnlyStringCases(node) {
|
|
@@ -17217,6 +17511,67 @@ function objectAssignTargetType(call) {
|
|
|
17217
17511
|
}
|
|
17218
17512
|
return undefined;
|
|
17219
17513
|
}
|
|
17514
|
+
// Object.assign({ defaults }, typedSource, …) with a struct target and typed
|
|
17515
|
+
// struct sources: the target type's fields set directly, instead of through
|
|
17516
|
+
// the reflective TnAssignTo. A source field that is unset (nil) leaves the
|
|
17517
|
+
// default, as tnAssignFields does.
|
|
17518
|
+
function staticObjectAssign(call, targetType, argCodes) {
|
|
17519
|
+
if (!targetType.startsWith('*') || targetType.startsWith('*TnMap['))
|
|
17520
|
+
return undefined;
|
|
17521
|
+
const target = targetType.slice(1);
|
|
17522
|
+
const targetFields = goStructFields(target);
|
|
17523
|
+
if (!targetFields)
|
|
17524
|
+
return undefined;
|
|
17525
|
+
const fields = new Map(targetFields);
|
|
17526
|
+
const args = call.arguments ?? [];
|
|
17527
|
+
const targetNode = unwrapParentheses(args[0]);
|
|
17528
|
+
// (a literal's duplicate keys: the last value is the property's)
|
|
17529
|
+
const defaults = new Map();
|
|
17530
|
+
const simple = (e) => isIdentifier(e) || isNumericLiteral(e) || isStringLiteral(e) || isPropertyAccessExpression(e) ||
|
|
17531
|
+
['TrueKeyword', 'FalseKeyword', 'NullKeyword'].includes(e.kind);
|
|
17532
|
+
for (const p of targetNode.properties ?? []) {
|
|
17533
|
+
if (!(isPropertyAssignment(p) || isShorthandPropertyAssignment(p)) || !isIdentifier(p.name))
|
|
17534
|
+
return undefined;
|
|
17535
|
+
const field = goFieldName(p.name.text);
|
|
17536
|
+
const fieldType = fields.get(field);
|
|
17537
|
+
if (fieldType === undefined)
|
|
17538
|
+
return undefined;
|
|
17539
|
+
const value = isPropertyAssignment(p) ? p.initializer : p.name;
|
|
17540
|
+
// (visited already as part of the call's arguments: only plain reads again)
|
|
17541
|
+
if (!simple(unwrapParentheses(value)))
|
|
17542
|
+
return undefined;
|
|
17543
|
+
defaults.set(field, toGoValueOfType(value, fieldType));
|
|
17544
|
+
}
|
|
17545
|
+
const parts = [...defaults].map(([field, value]) => `${field}: ${value}`);
|
|
17546
|
+
const targetTemp = getTempName('asg');
|
|
17547
|
+
const steps = [];
|
|
17548
|
+
for (let i = 1; i < args.length; i++) {
|
|
17549
|
+
const sourceNode = unwrapParentheses(args[i]);
|
|
17550
|
+
// (a literal source's explicit undefined properties: the dynamic path)
|
|
17551
|
+
if (isObjectLiteralExpression(sourceNode) || isObjectCreateNull(sourceNode))
|
|
17552
|
+
return undefined;
|
|
17553
|
+
const sourceType = inferExpressionType(sourceNode) ?? '';
|
|
17554
|
+
if (!sourceType.startsWith('*'))
|
|
17555
|
+
return undefined;
|
|
17556
|
+
const sourceFields = goStructFields(sourceType.slice(1));
|
|
17557
|
+
if (!sourceFields)
|
|
17558
|
+
return undefined;
|
|
17559
|
+
const sourceTemp = getTempName('src');
|
|
17560
|
+
const assignments = [];
|
|
17561
|
+
for (const [name, from] of sourceFields) {
|
|
17562
|
+
if (name === '__keys')
|
|
17563
|
+
continue;
|
|
17564
|
+
const to = fields.get(name);
|
|
17565
|
+
if (to === undefined)
|
|
17566
|
+
continue;
|
|
17567
|
+
const read = `${sourceTemp}.${name}`;
|
|
17568
|
+
const write = from === to ? read : convertBetweenGoTypes(read, from, to);
|
|
17569
|
+
assignments.push(isNilableGoType(from) ? `if ${read} != nil { ${targetTemp}.${name} = ${write} }` : `${targetTemp}.${name} = ${write}`);
|
|
17570
|
+
}
|
|
17571
|
+
steps.push(`${sourceTemp} := ${argCodes[i]}; _ = ${sourceTemp}; if ${sourceTemp} != nil { ${assignments.join('; ')} }`);
|
|
17572
|
+
}
|
|
17573
|
+
return `func() ${targetType} { ${targetTemp} := &${target}{${parts.join(', ')}}; ${steps.join('; ')}; return ${targetTemp} }()`;
|
|
17574
|
+
}
|
|
17220
17575
|
// A fresh empty value of a pointer Go type (&S{}, an empty Map)
|
|
17221
17576
|
function newGoValueOf(goType) {
|
|
17222
17577
|
const mapArgs = goType.startsWith('*TnMap[') ? splitMapTypeArgs(goType) : undefined;
|
|
@@ -17419,6 +17774,13 @@ function isNilableGoType(goType) {
|
|
|
17419
17774
|
function visitOptionalPropertyAccess(node) {
|
|
17420
17775
|
const baseExpr = visit(node.expression);
|
|
17421
17776
|
const baseType = inferExpressionType(node.expression);
|
|
17777
|
+
// (a member the class doesn't declare — a prototype method added at run
|
|
17778
|
+
// time: read by name, which finds it in the class's prototype table)
|
|
17779
|
+
if (isUndeclaredClassMember(node)) {
|
|
17780
|
+
useHelper('dynamic');
|
|
17781
|
+
const tmp = getTempName('opt');
|
|
17782
|
+
return `func() interface{} { ${tmp} := ${baseExpr}; if ${tmp} == nil { return nil }; return TnGet(${tmp}, ${toGoStringLiteral(node.name.text)}) }()`;
|
|
17783
|
+
}
|
|
17422
17784
|
// m?.size of a Map / Set that may be absent: its size, or undefined
|
|
17423
17785
|
if (baseType?.startsWith('*TnMap[') && node.name.text === 'size' && hasQuestionDot(node)) {
|
|
17424
17786
|
return `func() *float64 { if __m := ${baseExpr}; __m != nil { __n := float64(__m.Len()); return &__n }; return nil }()`;
|
|
@@ -17561,6 +17923,13 @@ function visitOptionalChainContinuation(node) {
|
|
|
17561
17923
|
if (!innerType) {
|
|
17562
17924
|
return `func() interface{} { ${tmp} := ${baseExpr}; if ${tmp} == nil { return nil }; ${innerCode}; return nil }()`;
|
|
17563
17925
|
}
|
|
17926
|
+
// (a primitive whose value is only tested: an absent chain's undefined is
|
|
17927
|
+
// falsy, so the zero value needs no boxed pointer)
|
|
17928
|
+
if (truthinessOperands.has(node) && ['bool', 'string', 'float64'].includes(innerType)) {
|
|
17929
|
+
const zero = innerType === 'string' ? '""' : innerType === 'float64' ? '0' : 'false';
|
|
17930
|
+
truthinessPrimitiveType.set(node, innerType);
|
|
17931
|
+
return `func() ${innerType} { ${tmp} := ${baseExpr}; if ${tmp} == nil { return ${zero} }; return ${innerCode} }()`;
|
|
17932
|
+
}
|
|
17564
17933
|
const resultType = makeNullableType(innerType);
|
|
17565
17934
|
const value = resultType === innerType ? innerCode : `func() ${resultType} { __v := ${innerCode}; return &__v }()`;
|
|
17566
17935
|
return `func() ${resultType} { ${tmp} := ${baseExpr}; if ${tmp} == nil { return *new(${resultType}) }; return ${value} }()`;
|
|
@@ -17576,6 +17945,16 @@ function visitOptionalCall(node) {
|
|
|
17576
17945
|
const guardedCall = { args: callArgs.map((a) => visit(a)), nodes: callArgs, types: callArgs.map((a) => inferExpressionType(a) ?? ''), recv: '' };
|
|
17577
17946
|
return guarded(guardedCall);
|
|
17578
17947
|
}
|
|
17948
|
+
// a?.m(…) of a member the class doesn't declare (a prototype method added
|
|
17949
|
+
// at run time): called by name, when the receiver is set
|
|
17950
|
+
if (isPropertyAccessExpression(node.expression) && isUndeclaredClassMember(node.expression)) {
|
|
17951
|
+
useHelper('dynamic');
|
|
17952
|
+
useHelper('error');
|
|
17953
|
+
const recv = getTempName('optc');
|
|
17954
|
+
const method = memberKey(node.expression.name) ?? '';
|
|
17955
|
+
const callArgs = (node.arguments ?? []).map((a) => `, ${toGoValueOfType(a, 'interface{}')}`).join('');
|
|
17956
|
+
return `func() interface{} { ${recv} := ${visit(node.expression.expression)}; if TnIsNil(${recv}) { return nil }; return TnCallMember(${recv}, ${toGoStringLiteral(method)}${callArgs}) }()`;
|
|
17957
|
+
}
|
|
17579
17958
|
const fnType = inferExpressionType(node.expression) ?? '';
|
|
17580
17959
|
const returnType = fnType.startsWith('func(') ? goFuncReturnType(fnType) : undefined;
|
|
17581
17960
|
const fn = getTempName('fn');
|
|
@@ -17595,6 +17974,13 @@ function visitOptionalCall(node) {
|
|
|
17595
17974
|
return `func() { if ${fn} := ${visit(node.expression)}; ${fn} != nil { ${fn}(${args}) } }()`;
|
|
17596
17975
|
return `func() interface{} { if ${fn} := ${visit(node.expression)}; ${fn} != nil { ${fn}(${args}) }; return nil }()`;
|
|
17597
17976
|
}
|
|
17977
|
+
// (a primitive whose value is only tested: an absent function's undefined
|
|
17978
|
+
// is falsy, so the zero value needs no boxed pointer)
|
|
17979
|
+
if (['bool', 'string', 'float64'].includes(returnType) && truthinessOperands.has(node)) {
|
|
17980
|
+
const zero = returnType === 'string' ? '""' : returnType === 'float64' ? '0' : 'false';
|
|
17981
|
+
truthinessPrimitiveType.set(node, returnType);
|
|
17982
|
+
return `func() ${returnType} { ${fn} := ${visit(node.expression)}; if ${fn} == nil { return ${zero} }; return ${fn}(${args}) }()`;
|
|
17983
|
+
}
|
|
17598
17984
|
const resultType = makeNullableType(returnType);
|
|
17599
17985
|
const value = resultType === returnType ? `${fn}(${args})` : `func() ${resultType} { v := ${fn}(${args}); return &v }()`;
|
|
17600
17986
|
return `func() ${resultType} { ${fn} := ${visit(node.expression)}; if ${fn} == nil { return nil }; return ${value} }()`;
|
|
@@ -17610,6 +17996,15 @@ function visitOptionalCall(node) {
|
|
|
17610
17996
|
if (baseType && NULLABLE_PRIMITIVE_TYPES.includes(baseType)) {
|
|
17611
17997
|
return visitNullablePrimitiveOptionalCall(node, baseExpr, baseType);
|
|
17612
17998
|
}
|
|
17999
|
+
// a?.m(…) of a member the class doesn't declare (a prototype method added
|
|
18000
|
+
// at run time): called by name, when the receiver is set
|
|
18001
|
+
if (hasQuestionDot(node.expression) && isUndeclaredClassMember(node.expression)) {
|
|
18002
|
+
useHelper('dynamic');
|
|
18003
|
+
useHelper('error');
|
|
18004
|
+
const recv = getTempName('optc');
|
|
18005
|
+
const callArgs = (node.arguments ?? []).map((a) => `, ${toGoValueOfType(a, 'interface{}')}`).join('');
|
|
18006
|
+
return `func() interface{} { ${recv} := ${baseExpr}; if TnIsNil(${recv}) { return nil }; return TnCallMember(${recv}, ${toGoStringLiteral(methodName)}${callArgs}) }()`;
|
|
18007
|
+
}
|
|
17613
18008
|
// a?.m(…) on any value: undefined when a is nullish (no call)
|
|
17614
18009
|
// a?.push(x) on any value: the mutator's own path (it writes the array
|
|
17615
18010
|
// back to a), run only when a is set
|
|
@@ -18386,6 +18781,9 @@ function enumHasComputedMember(node) {
|
|
|
18386
18781
|
function visitEnumDeclaration(node, inPlace = false) {
|
|
18387
18782
|
const enumName = getSafeName(node.name.text);
|
|
18388
18783
|
const baseType = enumBaseTypes.get(node.name.text) ?? getEnumBaseType(node);
|
|
18784
|
+
// (a string enum is a Go alias: its type is the string's)
|
|
18785
|
+
if (baseType === 'string' || baseType === 'interface{}')
|
|
18786
|
+
primitiveEnumGoTypes.set(enumName, baseType);
|
|
18389
18787
|
let nextNumericValue = 0;
|
|
18390
18788
|
let canAutoIncrement = true;
|
|
18391
18789
|
let hasComputedMember = false;
|
|
@@ -18748,6 +19146,11 @@ function getType(typeNode, getArrayType = false) {
|
|
|
18748
19146
|
}
|
|
18749
19147
|
if (isTypeReferenceNode(typeNode) && isIdentifier(typeNode.typeName)) {
|
|
18750
19148
|
const name = typeNode.typeName.text;
|
|
19149
|
+
// (a union member — `parentPath: NodePath_Final | null` — that names a
|
|
19150
|
+
// class whose type alias a generic conditional hides: the class)
|
|
19151
|
+
if (typeNode.parent?.kind === 'UnionType' && classNames.has(name) && (typeNode.typeArguments ?? []).length === 0 && !isTypeParameterInScope(name, typeNode)) {
|
|
19152
|
+
return isPolymorphicClass(name) ? 'interface{}' : `*${name}`;
|
|
19153
|
+
}
|
|
18751
19154
|
if (valueShadowedTypeNames.has(name) || openObjectTypeNames.has(name))
|
|
18752
19155
|
return 'interface{}';
|
|
18753
19156
|
// (an object type of several call signatures plus properties — Babel's
|
|
@@ -19518,10 +19921,15 @@ const callHandlers = {
|
|
|
19518
19921
|
// (an existing object is updated in place and returned, whatever its type)
|
|
19519
19922
|
const existingTarget = !!call && (call.arguments ?? []).length > 0 && !isObjectLiteralExpression(unwrapParentheses(call.arguments[0])) && !isObjectCreateNull(unwrapParentheses(call.arguments[0])) && !(call.arguments ?? []).some((a) => isSpreadElement(a));
|
|
19520
19923
|
if (call && (targetType || existingTarget)) {
|
|
19521
|
-
useHelper('objectAssignTo');
|
|
19522
19924
|
const target = unwrapParentheses(call.arguments[0]);
|
|
19523
19925
|
// a literal target: a fresh value of the type, its own properties first
|
|
19524
19926
|
const literal = isObjectLiteralExpression(target) || isObjectCreateNull(target);
|
|
19927
|
+
if (literal && !existingTarget && targetType && targetType !== 'interface{}') {
|
|
19928
|
+
const statically = staticObjectAssign(call, targetType, args);
|
|
19929
|
+
if (statically)
|
|
19930
|
+
return statically;
|
|
19931
|
+
}
|
|
19932
|
+
useHelper('objectAssignTo');
|
|
19525
19933
|
const head = !literal ? args[0] : targetType === 'interface{}' ? `TnEmptyLike(${args[1]})` : newGoValueOf(targetType ?? '');
|
|
19526
19934
|
// (a literal source's explicit undefined properties are copied too)
|
|
19527
19935
|
const setsUndefined = (a) => isObjectLiteralExpression(a) && (a.properties ?? []).some((p) => isPropertyAssignment(p) && isIdentifier(p.initializer) && p.initializer.text === 'undefined');
|
|
@@ -19963,12 +20371,42 @@ function regexSubject(arg) {
|
|
|
19963
20371
|
useHelper('dynamic');
|
|
19964
20372
|
return argType === '*string' ? `TnJSString(TnPtrValue(${arg}))` : `TnJSString(interface{}(${arg}))`;
|
|
19965
20373
|
}
|
|
20374
|
+
// Whether a value is only read for its truthiness (!!x, if (a || x), …): a
|
|
20375
|
+
// regex exec there can test without building the match array
|
|
20376
|
+
function onlyTestedForTruthiness(node) {
|
|
20377
|
+
let child = node;
|
|
20378
|
+
for (let parent = node.parent; parent; parent = parent.parent) {
|
|
20379
|
+
if (isParenthesizedExpression(parent) || parent.kind === 'NonNullExpression') {
|
|
20380
|
+
child = parent;
|
|
20381
|
+
continue;
|
|
20382
|
+
}
|
|
20383
|
+
if (parent.kind === 'PrefixUnaryExpression' && parent.operatorToken?.kind === 'ExclamationToken')
|
|
20384
|
+
return true;
|
|
20385
|
+
if (isBinaryExpression(parent) && ['AmpersandAmpersandToken', 'BarBarToken'].includes(parent.operatorToken?.kind)) {
|
|
20386
|
+
child = parent;
|
|
20387
|
+
continue;
|
|
20388
|
+
}
|
|
20389
|
+
if (isIfStatement(parent) && parent.expression === child)
|
|
20390
|
+
return true;
|
|
20391
|
+
if (isWhileStatement(parent) && parent.expression === child)
|
|
20392
|
+
return true;
|
|
20393
|
+
if (isConditionalExpression(parent) && parent.condition === child)
|
|
20394
|
+
return true;
|
|
20395
|
+
return false;
|
|
20396
|
+
}
|
|
20397
|
+
return false;
|
|
20398
|
+
}
|
|
19966
20399
|
const regexpMethodHandlers = {
|
|
19967
20400
|
test: (obj, args) => currentReceiverGoType === '*TnRegex'
|
|
19968
20401
|
? `${obj}.Test(${regexSubject(args[0])})`
|
|
19969
20402
|
: `${obj}.MatchString(${regexSubject(args[0])})`,
|
|
19970
20403
|
exec: (obj, args) => {
|
|
19971
20404
|
args = [regexSubject(args[0])];
|
|
20405
|
+
// only its presence is tested (!!re.exec(s), if (a || re.exec(s))): no
|
|
20406
|
+
// match array to build
|
|
20407
|
+
if (currentReceiverGoType === '*TnRegex' && currentCallNode && onlyTestedForTruthiness(currentCallNode)) {
|
|
20408
|
+
return `${obj}.Test(${args[0]})`;
|
|
20409
|
+
}
|
|
19972
20410
|
if (currentReceiverGoType === '*TnRegex')
|
|
19973
20411
|
return `${obj}.Find(${args[0]})`;
|
|
19974
20412
|
// Named groups come back as a match object with a .groups record
|
|
@@ -20051,7 +20489,13 @@ const dateMethodHandlers = {
|
|
|
20051
20489
|
};
|
|
20052
20490
|
// append(base, args…) where some arguments are spreads (`x...`): one
|
|
20053
20491
|
// append per run, as Go allows a spread only as the last argument
|
|
20054
|
-
function appendArguments(base, args) {
|
|
20492
|
+
function appendArguments(base, args, elementType) {
|
|
20493
|
+
// (one value: the 2x growth helper — building a long list with Go's 1.25x
|
|
20494
|
+
// growth copies it out about five times over)
|
|
20495
|
+
if (args.length === 1 && !args[0].endsWith('...') && elementType) {
|
|
20496
|
+
useHelper('arrayPush');
|
|
20497
|
+
return `TnPush[${elementType}](${base}, ${args[0]})`;
|
|
20498
|
+
}
|
|
20055
20499
|
if (!args.some((a) => a.endsWith('...')))
|
|
20056
20500
|
return `append(${[base, ...args].join(', ')})`;
|
|
20057
20501
|
let out = base;
|
|
@@ -20071,6 +20515,7 @@ function appendArguments(base, args) {
|
|
|
20071
20515
|
const arrayMethodHandlers = {
|
|
20072
20516
|
// push / unshift return the new length when their value is used
|
|
20073
20517
|
push: (obj, args) => {
|
|
20518
|
+
const element = currentReceiverGoType?.startsWith('[]') ? currentReceiverGoType.slice(2) : undefined;
|
|
20074
20519
|
// (an array a call returns — a getter's — is no Go variable: appended to a copy)
|
|
20075
20520
|
// (a field through a call's pointer result — getter().items — is addressable)
|
|
20076
20521
|
const receiver = currentCallNode && isPropertyAccessExpression(currentCallNode.expression) ? currentCallNode.expression.expression : undefined;
|
|
@@ -20078,24 +20523,24 @@ const arrayMethodHandlers = {
|
|
|
20078
20523
|
// (a call returning an array reference — a Map of arrays' value through
|
|
20079
20524
|
// getOrInsertWith — appends to the array it refers to)
|
|
20080
20525
|
if (receiver && inferRawExpressionType(receiver)?.startsWith('*[]')) {
|
|
20081
|
-
return `func() float64 { __p := ${obj}; *__p = ${appendArguments('*__p', args)}; return float64(len(*__p)) }()`;
|
|
20526
|
+
return `func() float64 { __p := ${obj}; *__p = ${appendArguments('*__p', args, element)}; return float64(len(*__p)) }()`;
|
|
20082
20527
|
}
|
|
20083
20528
|
// (a read out of a container — FLIPPED_ALIAS_KEYS[alias], a Map's value
|
|
20084
20529
|
// —: the array lives in it, so the appended one is stored back, as push
|
|
20085
20530
|
// mutates it in JS)
|
|
20086
20531
|
if (receiver && isElementAccessExpression(receiver) && (hasDynamicProperties(receiver.expression) || (inferExpressionType(receiver.expression) ?? '').startsWith('*TnMap['))) {
|
|
20087
|
-
return (`func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args)}; ` +
|
|
20532
|
+
return (`func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args, element)}; ` +
|
|
20088
20533
|
`TnSetIndex(${visit(receiver.expression)}, ${visit(receiver.argumentExpression)}, __s); return float64(len(__s)) }()`);
|
|
20089
20534
|
}
|
|
20090
20535
|
if (receiver && isPropertyAccessExpression(receiver) && hasDynamicProperties(receiver.expression) && !hasQuestionDot(receiver)) {
|
|
20091
|
-
return (`func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args)}; ` +
|
|
20536
|
+
return (`func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args, element)}; ` +
|
|
20092
20537
|
`TnSet(${visit(receiver.expression)}, ${toGoStringLiteral(receiver.name.text)}, __s); return float64(len(__s)) }()`);
|
|
20093
20538
|
}
|
|
20094
|
-
return `func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args)}; return float64(len(__s)) }()`;
|
|
20539
|
+
return `func() float64 { __s := ${obj}; __s = ${appendArguments('__s', args, element)}; return float64(len(__s)) }()`;
|
|
20095
20540
|
}
|
|
20096
20541
|
return currentCallNode && !isDiscardedValue(currentCallNode)
|
|
20097
|
-
? `func() float64 { ${obj} = ${appendArguments(obj, args)}; return float64(len(${obj})) }()`
|
|
20098
|
-
: `${obj} = ${appendArguments(obj, args)}`;
|
|
20542
|
+
? `func() float64 { ${obj} = ${appendArguments(obj, args, element)}; return float64(len(${obj})) }()`
|
|
20543
|
+
: `${obj} = ${appendArguments(obj, args, element)}`;
|
|
20099
20544
|
},
|
|
20100
20545
|
pop: (obj) => {
|
|
20101
20546
|
const elementType = receiverElementType();
|
|
@@ -20112,7 +20557,7 @@ const arrayMethodHandlers = {
|
|
|
20112
20557
|
return `func() ${elementType} { if len(${obj}) == 0 { var __zero ${elementType}; return __zero }; __first := ${obj}[0]; ${obj} = ${obj}[1:]; return __first }()`;
|
|
20113
20558
|
},
|
|
20114
20559
|
unshift: (obj, args) => {
|
|
20115
|
-
const prefix = appendArguments(`[]${receiverElementType()}{}`, args);
|
|
20560
|
+
const prefix = appendArguments(`[]${receiverElementType()}{}`, args, receiverElementType());
|
|
20116
20561
|
return currentCallNode && !isDiscardedValue(currentCallNode)
|
|
20117
20562
|
? `func() float64 { ${obj} = append(${prefix}, ${obj}...); return float64(len(${obj})) }()`
|
|
20118
20563
|
: `${obj} = append(${prefix}, ${obj}...)`;
|
|
@@ -20155,7 +20600,7 @@ const arrayMethodHandlers = {
|
|
|
20155
20600
|
}
|
|
20156
20601
|
const insert = args.slice(2);
|
|
20157
20602
|
// (the deleted count is clamped to the elements after start)
|
|
20158
|
-
const inserted = insert.length > 0 ? appendArguments(`${obj}[:__start]`, insert) : `${obj}[:__start]`;
|
|
20603
|
+
const inserted = insert.length > 0 ? appendArguments(`${obj}[:__start]`, insert, elementType) : `${obj}[:__start]`;
|
|
20159
20604
|
return `func() []${elementType} { __start := ${start}; __end := __start + max(0, int(${indexArg(1)})); if __end > len(${obj}) { __end = len(${obj}) }; __rm := append([]${elementType}{}, ${obj}[__start:__end]...); __tail := append([]${elementType}{}, ${obj}[__end:]...); ${obj} = ${inserted}; ${obj} = append(${obj}, __tail...); return __rm }()`;
|
|
20160
20605
|
},
|
|
20161
20606
|
fill: (obj, args) => {
|
|
@@ -20246,6 +20691,15 @@ const arrayMethodHandlers = {
|
|
|
20246
20691
|
// padStart / padEnd for string arrays (rarely used, but added for completeness)
|
|
20247
20692
|
// (undefined past either end: a primitive element is T | undefined, *T)
|
|
20248
20693
|
at: (obj, args) => {
|
|
20694
|
+
// [...s].at(i): its i-th code point, without building the array of them
|
|
20695
|
+
const spreadString = currentCallNode && isPropertyAccessExpression(currentCallNode.expression)
|
|
20696
|
+
? stringSpreadSource(currentCallNode.expression.expression)
|
|
20697
|
+
: undefined;
|
|
20698
|
+
if (spreadString) {
|
|
20699
|
+
useHelper('dynamic');
|
|
20700
|
+
useHelper('strIndex');
|
|
20701
|
+
return `func() *string { __s := ${visit(spreadString)}; __n := int(TnStrLength(__s)); __i := int(${args[0]}); if __i < 0 { __i += __n }; if __i < 0 || __i >= __n { return nil }; __v := TnCharAt(__s, float64(__i)); return &__v }()`;
|
|
20702
|
+
}
|
|
20249
20703
|
const element = receiverElementType();
|
|
20250
20704
|
const primitive = ['string', 'float64', 'bool'].includes(element);
|
|
20251
20705
|
const resultType = primitive ? `*${element}` : element;
|
|
@@ -21380,7 +21834,17 @@ function isDescriptorMethod(n) {
|
|
|
21380
21834
|
// A plain function's this: its `this: T` annotation's Go type, else any
|
|
21381
21835
|
function plainFunctionThisType(fn) {
|
|
21382
21836
|
const declared = fn.tnThisType ? getType(fn.tnThisType) : '';
|
|
21383
|
-
|
|
21837
|
+
if (declared && declared !== ':' && declared.startsWith('*'))
|
|
21838
|
+
return declared;
|
|
21839
|
+
// (a class's name that a type alias also uses — Babel's NodePath_Final<T>,
|
|
21840
|
+
// a default import of its class: `this: NodePath` is the class's instances)
|
|
21841
|
+
const typeNode = fn.tnThisType;
|
|
21842
|
+
if (typeNode?.kind === 'TypeReference' && isIdentifier(typeNode.typeName)) {
|
|
21843
|
+
const name = typeNode.typeName.text;
|
|
21844
|
+
if (classNames.has(name) && !isPolymorphicClass(name) && !isTypeParameterInScope(name, typeNode))
|
|
21845
|
+
return `*${name}`;
|
|
21846
|
+
}
|
|
21847
|
+
return 'interface{}';
|
|
21384
21848
|
}
|
|
21385
21849
|
// A plain function using its own this reads it once, on entry, into __this
|
|
21386
21850
|
// (the value its caller set, TnThis): arrows in it keep seeing that one
|
|
@@ -21494,13 +21958,35 @@ function goFuncParamTypes(funcType) {
|
|
|
21494
21958
|
funcType = funcType.trim();
|
|
21495
21959
|
const result = goFuncReturnType(funcType);
|
|
21496
21960
|
const paramList = funcType.slice(5, funcType.length - (result ? result.length + 1 : 0) - 1).trim();
|
|
21497
|
-
return splitGoParameters(paramList).map(
|
|
21498
|
-
|
|
21499
|
-
|
|
21500
|
-
|
|
21501
|
-
|
|
21502
|
-
|
|
21503
|
-
|
|
21961
|
+
return splitGoParameters(paramList).map(goParameterType);
|
|
21962
|
+
}
|
|
21963
|
+
// A Go parameter declaration without its name ('__this interface{}' → 'interface{}')
|
|
21964
|
+
function goParameterType(p) {
|
|
21965
|
+
const space = p.indexOf(' ');
|
|
21966
|
+
const first = space > 0 ? p.slice(0, space) : p;
|
|
21967
|
+
// (ǂ stands for $ and _ in names: see goIdentifierChars)
|
|
21968
|
+
const isName = space > 0 && !['chan', 'func', 'map', 'struct', 'interface'].includes(first) && /^[A-Za-z_ǂ][\wǂ]*$/.test(first);
|
|
21969
|
+
return isName ? p.slice(space + 1) : p;
|
|
21970
|
+
}
|
|
21971
|
+
// The Go func type of a function emitted with this parameter signature and
|
|
21972
|
+
// result ('a int, b string', ' bool' → 'func(int, string) bool')
|
|
21973
|
+
function emittedFuncGoType(signature, returnType) {
|
|
21974
|
+
const params = splitGoParameters(signature).map(goParameterType).join(', ');
|
|
21975
|
+
return `func(${params})${returnType}`.replace(/\bany\b/g, 'interface{}');
|
|
21976
|
+
}
|
|
21977
|
+
// A function value of this Go type may be called dynamically: tnCallValueTyped
|
|
21978
|
+
// gets a case for it, so the call needs no reflect.Value.Call
|
|
21979
|
+
function registerFunctionGoType(funcType) {
|
|
21980
|
+
if (!funcType.startsWith('func(') || funcType.startsWith('func['))
|
|
21981
|
+
return;
|
|
21982
|
+
// (one spelling per Go type: spacing and `any` do not change it)
|
|
21983
|
+
const normalized = funcType.replace(/\bany\b/g, 'interface{}').replace(/\s+/g, ' ').replace(/interface \{\}/g, 'interface{}');
|
|
21984
|
+
// (a local or generic type has no package-level Go type to name)
|
|
21985
|
+
for (const match of normalized.matchAll(/[A-Za-z_ǂ][\wǂ]*/g)) {
|
|
21986
|
+
if (localGoTypes.has(match[0]) || genericGoParams.has(match[0]))
|
|
21987
|
+
return;
|
|
21988
|
+
}
|
|
21989
|
+
dynamicFuncTypes.add(normalized);
|
|
21504
21990
|
}
|
|
21505
21991
|
// f.call(thisArg, a, b) → f(a, b); f.apply(thisArg, args) → f(args[0], args[1], …);
|
|
21506
21992
|
// f.bind(thisArg, a) → a closure over the bound arguments (this is TnThis)
|
|
@@ -21946,7 +22432,7 @@ function collectClassImplementedInterfaces() {
|
|
|
21946
22432
|
// member of a class TypeScript narrowed it to — called / read by name
|
|
21947
22433
|
// (this counts in plain functions, whose this may be any instance)
|
|
21948
22434
|
function isUndeclaredClassMember(access) {
|
|
21949
|
-
if (!isPropertyAccessExpression(access) ||
|
|
22435
|
+
if (!isPropertyAccessExpression(access) || access.name?.kind === 'PrivateIdentifier')
|
|
21950
22436
|
return false;
|
|
21951
22437
|
// (this.isScope() in a class whose prototype gets methods assigned —
|
|
21952
22438
|
// Object.assign(NodePath.prototype, validators) —: called by name)
|
|
@@ -21957,7 +22443,27 @@ function isUndeclaredClassMember(access) {
|
|
|
21957
22443
|
if (access.expression.kind === 'SuperKeyword')
|
|
21958
22444
|
return false;
|
|
21959
22445
|
const receiverType = inferExpressionType(access.expression) ?? '';
|
|
21960
|
-
|
|
22446
|
+
const className = receiverType.startsWith('*') ? receiverType.slice(1).replace(/\[.*\]$/, '') : '';
|
|
22447
|
+
const member = memberKey(access.name) ?? '';
|
|
22448
|
+
if (!className || !classNames.has(className))
|
|
22449
|
+
return false;
|
|
22450
|
+
if (!classHasMember(className, member))
|
|
22451
|
+
return true;
|
|
22452
|
+
// (set-only: a read is undefined, and the Go struct has only Set_x)
|
|
22453
|
+
return !isCallee(access) && !!classMember(className, 'set', member) && !classMember(className, 'get', member) && !classHasDataField(className, member);
|
|
22454
|
+
}
|
|
22455
|
+
// Whether a class declares a data field (or parameter property) of the name
|
|
22456
|
+
function classHasDataField(className, member) {
|
|
22457
|
+
for (let name = className, depth = 0; name && depth < 20; name = classParentNames.get(name), depth++) {
|
|
22458
|
+
const declaration = declaredClasses.get(name);
|
|
22459
|
+
if (!declaration)
|
|
22460
|
+
return false;
|
|
22461
|
+
if ((declaration.members ?? []).some((m) => isPropertyDeclaration(m) && !hasModifier(m, 'StaticKeyword') && memberKey(m.name) === member))
|
|
22462
|
+
return true;
|
|
22463
|
+
if (getParameterProperties(declaration).some((p) => p.name?.text === member))
|
|
22464
|
+
return true;
|
|
22465
|
+
}
|
|
22466
|
+
return false;
|
|
21961
22467
|
}
|
|
21962
22468
|
// x.f on an object type (an interface's struct) that has no f — Babel's
|
|
21963
22469
|
// generator reads node.handlers under @ts-expect-error —: read by name
|
|
@@ -26639,7 +27145,7 @@ const helperPackages = {
|
|
|
26639
27145
|
regexEngine: ['strings', 'fmt', 'strconv', 'sync', 'sync/atomic', 'unicode', 'unicode/utf8'],
|
|
26640
27146
|
namedGroups: ['regexp', 'unicode/utf8'],
|
|
26641
27147
|
regexMatch: ['regexp', 'math', 'strconv', 'unsafe', 'unicode/utf8'],
|
|
26642
|
-
strIndex: ['unicode/utf8', 'sync/atomic', 'unsafe', 'math', 'strings', 'sort'],
|
|
27148
|
+
strIndex: ['unicode/utf8', 'sync', 'sync/atomic', 'unsafe', 'math', 'strings', 'sort'],
|
|
26643
27149
|
jsReplacement: ['strings'],
|
|
26644
27150
|
moduleUrl: ['os'],
|
|
26645
27151
|
asyncWait: [],
|
|
@@ -26668,6 +27174,31 @@ const helperPackages = {
|
|
|
26668
27174
|
// Field names are intentionally lowercase: every generated file is `package main`,
|
|
26669
27175
|
// so `result.stdout` in emitted code resolves to the struct field directly.
|
|
26670
27176
|
const goHelpers = {
|
|
27177
|
+
arrayPush: `// append with geometric (2x) growth: Go grows a large slice by 1.25x, so the
|
|
27178
|
+
// repeated copies when a list is built by pushes add up to about five times
|
|
27179
|
+
// its final memory
|
|
27180
|
+
func TnPush[T any](s []T, v T) []T {
|
|
27181
|
+
if len(s) == cap(s) {
|
|
27182
|
+
n := len(s) * 2
|
|
27183
|
+
if n < 16 {
|
|
27184
|
+
n = 16
|
|
27185
|
+
}
|
|
27186
|
+
ns := make([]T, len(s), n)
|
|
27187
|
+
copy(ns, s)
|
|
27188
|
+
s = ns
|
|
27189
|
+
}
|
|
27190
|
+
return append(s, v)
|
|
27191
|
+
}`,
|
|
27192
|
+
slicePtr: `// A *[]T slot from a slice: nil stays nil (no match, undefined), and the box
|
|
27193
|
+
// is allocated only for a value, not for every call a local &v would cost
|
|
27194
|
+
func TnSlicePtr[T any](v []T) *[]T {
|
|
27195
|
+
if v == nil {
|
|
27196
|
+
return nil
|
|
27197
|
+
}
|
|
27198
|
+
p := new([]T)
|
|
27199
|
+
*p = v
|
|
27200
|
+
return p
|
|
27201
|
+
}`,
|
|
26671
27202
|
generatorSeq: `// A generator's push form (a range function) yielding T: the same function
|
|
26672
27203
|
// when it yields T already, else each value converted
|
|
26673
27204
|
func tnSeqAs[T any, S any](s func(func(S) bool)) func(func(T) bool) {
|
|
@@ -28770,6 +29301,33 @@ func tnCallCollection(obj interface{}, isSet bool, name string, args []interface
|
|
|
28770
29301
|
return nil, false
|
|
28771
29302
|
}
|
|
28772
29303
|
|
|
29304
|
+
// A dynamic call's argument as a parameter's Go type (undefined / null is the
|
|
29305
|
+
// zero value, a value of another type is converted as tnConvertTo does)
|
|
29306
|
+
func tnCoerceArg[T any](v interface{}) T {
|
|
29307
|
+
if x, ok := v.(T); ok {
|
|
29308
|
+
return x
|
|
29309
|
+
}
|
|
29310
|
+
var zero T
|
|
29311
|
+
if v == nil {
|
|
29312
|
+
return zero
|
|
29313
|
+
}
|
|
29314
|
+
if rv, ok := TnConvertDynamic(v, reflect.TypeFor[T]()); ok && rv.IsValid() {
|
|
29315
|
+
if x, ok := rv.Interface().(T); ok {
|
|
29316
|
+
return x
|
|
29317
|
+
}
|
|
29318
|
+
}
|
|
29319
|
+
return zero
|
|
29320
|
+
}
|
|
29321
|
+
|
|
29322
|
+
// A variadic parameter's values from a dynamic call's arguments
|
|
29323
|
+
func tnCoerceArgs[T any](args []interface{}, from int) []T {
|
|
29324
|
+
var out []T
|
|
29325
|
+
for ; from < len(args); from++ {
|
|
29326
|
+
out = append(out, tnCoerceArg[T](args[from]))
|
|
29327
|
+
}
|
|
29328
|
+
return out
|
|
29329
|
+
}
|
|
29330
|
+
|
|
28773
29331
|
// Calls a function value held as any, converting the arguments to its
|
|
28774
29332
|
// parameter types; its result (or nil)
|
|
28775
29333
|
func TnCallValue(fn interface{}, args ...interface{}) interface{} {
|
|
@@ -28810,6 +29368,10 @@ func TnCallValue(fn interface{}, args ...interface{}) interface{} {
|
|
|
28810
29368
|
case func(interface{}, interface{}) bool:
|
|
28811
29369
|
return f(TnArg(args, 0), TnArg(args, 1))
|
|
28812
29370
|
}
|
|
29371
|
+
// (the program's own function types: called without reflect)
|
|
29372
|
+
if v, ok := tnCallValueTyped(fn, args); ok {
|
|
29373
|
+
return v
|
|
29374
|
+
}
|
|
28813
29375
|
fv := reflect.ValueOf(fn)
|
|
28814
29376
|
if fv.Kind() != reflect.Func {
|
|
28815
29377
|
panic(TnNodeError("TypeError", "", "value is not a function"))
|
|
@@ -28993,6 +29555,12 @@ func TnSet(obj interface{}, key string, value interface{}) {
|
|
|
28993
29555
|
}
|
|
28994
29556
|
return
|
|
28995
29557
|
}
|
|
29558
|
+
// (a record — a TnMap held as any, such as a {} literal: its key, as
|
|
29559
|
+
// tnSetMember's Set call stores it, without reflection)
|
|
29560
|
+
if r, ok := obj.(interface{ TnSetProp(string, interface{}) bool }); ok && r.TnSetProp(key, value) {
|
|
29561
|
+
tnExpandoDelete(obj, key)
|
|
29562
|
+
return
|
|
29563
|
+
}
|
|
28996
29564
|
if obj != nil {
|
|
28997
29565
|
if p := tnPlanOf(obj, key); p.kind != tnFieldSlow && !p.setter {
|
|
28998
29566
|
if base := (*[2]unsafe.Pointer)(unsafe.Pointer(&obj))[1]; base != nil {
|
|
@@ -30673,6 +31241,90 @@ func tnConvIdentityOf(src unsafe.Pointer, dst reflect.Type, srcSize uintptr) (re
|
|
|
30673
31241
|
return entry.out, ok
|
|
30674
31242
|
}
|
|
30675
31243
|
|
|
31244
|
+
// The objects struct conversions (tnConvPlan.convert) made, by source object
|
|
31245
|
+
// and target type. An entry holds its source, so the address names no other
|
|
31246
|
+
// object while the entry lives, and its converted object weakly: once nothing
|
|
31247
|
+
// else holds that object, a new one can't be told from it. (One weak pointer
|
|
31248
|
+
// per conversion, no cleanup or finalizer: those made every conversion of a
|
|
31249
|
+
// short-lived object cost a few garbage-collector specials.) Entries whose
|
|
31250
|
+
// object was collected go in a sweep, run when the index has doubled since
|
|
31251
|
+
// the last one.
|
|
31252
|
+
type tnStructIdentityKey struct {
|
|
31253
|
+
src uintptr
|
|
31254
|
+
dst unsafe.Pointer // (the target type's descriptor)
|
|
31255
|
+
}
|
|
31256
|
+
|
|
31257
|
+
type tnStructIdentity struct {
|
|
31258
|
+
src unsafe.Pointer
|
|
31259
|
+
out weak.Pointer[byte]
|
|
31260
|
+
}
|
|
31261
|
+
|
|
31262
|
+
var tnStructIdentities = map[tnStructIdentityKey]tnStructIdentity{}
|
|
31263
|
+
var tnStructIdentityMu sync.Mutex
|
|
31264
|
+
var tnStructIdentitySweepAt = 1 << 12
|
|
31265
|
+
|
|
31266
|
+
// The entries found or made last, by a hash of their key: an object
|
|
31267
|
+
// converted again and again (an options object read per node) skips the
|
|
31268
|
+
// index. A slot holds its object, so its key's entry in the index stays the
|
|
31269
|
+
// one it names (an entry is only replaced once its object is gone): at most
|
|
31270
|
+
// one object per slot is kept alive this way
|
|
31271
|
+
var tnStructIdentityRecent [1 << 8]struct {
|
|
31272
|
+
key tnStructIdentityKey
|
|
31273
|
+
out unsafe.Pointer
|
|
31274
|
+
}
|
|
31275
|
+
|
|
31276
|
+
// The converted object for src as a dst (memory of dst's type): the one made
|
|
31277
|
+
// before (cached true), else a new one remembered for src
|
|
31278
|
+
func tnStructIdentityOf(src unsafe.Pointer, dst reflect.Type, srcSize uintptr) (unsafe.Pointer, bool) {
|
|
31279
|
+
if srcSize == 0 || src == nil || dst.Size() == 0 {
|
|
31280
|
+
return reflect.New(dst).UnsafePointer(), false
|
|
31281
|
+
}
|
|
31282
|
+
key := tnStructIdentityKey{uintptr(src), (*[2]unsafe.Pointer)(unsafe.Pointer(&dst))[1]}
|
|
31283
|
+
slot := &tnStructIdentityRecent[((key.src>>4)^(uintptr(key.dst)>>5))*0x9E3779B1>>16&(1<<8-1)]
|
|
31284
|
+
tnStructIdentityMu.Lock()
|
|
31285
|
+
if slot.key == key && slot.out != nil {
|
|
31286
|
+
out := slot.out
|
|
31287
|
+
tnStructIdentityMu.Unlock()
|
|
31288
|
+
return out, true
|
|
31289
|
+
}
|
|
31290
|
+
if e, ok := tnStructIdentities[key]; ok {
|
|
31291
|
+
if out := e.out.Value(); out != nil {
|
|
31292
|
+
slot.key, slot.out = key, unsafe.Pointer(out)
|
|
31293
|
+
tnStructIdentityMu.Unlock()
|
|
31294
|
+
return unsafe.Pointer(out), true
|
|
31295
|
+
}
|
|
31296
|
+
}
|
|
31297
|
+
if len(tnStructIdentities) >= tnStructIdentitySweepAt {
|
|
31298
|
+
for k, e := range tnStructIdentities {
|
|
31299
|
+
if e.out.Value() == nil {
|
|
31300
|
+
delete(tnStructIdentities, k)
|
|
31301
|
+
}
|
|
31302
|
+
}
|
|
31303
|
+
tnStructIdentitySweepAt = max(1<<12, 2*len(tnStructIdentities))
|
|
31304
|
+
}
|
|
31305
|
+
out := reflect.New(dst).UnsafePointer()
|
|
31306
|
+
e := tnStructIdentity{src: src, out: weak.Make((*byte)(out))}
|
|
31307
|
+
tnStructIdentities[key] = e
|
|
31308
|
+
slot.key, slot.out = key, out
|
|
31309
|
+
tnStructIdentityMu.Unlock()
|
|
31310
|
+
return out, false
|
|
31311
|
+
}
|
|
31312
|
+
|
|
31313
|
+
// TnAs for a conversion the compiler knows is the only one its source object
|
|
31314
|
+
// ever gets (see unsharedConversionSource): a fresh object that nothing else
|
|
31315
|
+
// holds, converted once, needs no identity entry — a plain copy
|
|
31316
|
+
func TnAsCopy[T any](v interface{}) T {
|
|
31317
|
+
if t, ok := v.(T); ok {
|
|
31318
|
+
return t
|
|
31319
|
+
}
|
|
31320
|
+
if v != nil {
|
|
31321
|
+
if p := tnConvPlanOf(v, reflect.TypeOf((*T)(nil)).Elem()); p.ok && (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1] != nil {
|
|
31322
|
+
return p.convertTo(v, false).Interface().(T)
|
|
31323
|
+
}
|
|
31324
|
+
}
|
|
31325
|
+
return TnAs[T](v)
|
|
31326
|
+
}
|
|
31327
|
+
|
|
30676
31328
|
var tnConvPlans [1 << 10]atomic.Pointer[tnConvPlan]
|
|
30677
31329
|
var tnConvPlanIndex = map[[2]unsafe.Pointer]*tnConvPlan{}
|
|
30678
31330
|
var tnConvPlanMu sync.RWMutex
|
|
@@ -30759,6 +31411,11 @@ func tnMakeConvPlan(v interface{}, t reflect.Type, from unsafe.Pointer, to unsaf
|
|
|
30759
31411
|
|
|
30760
31412
|
// v (a non-nil pointer to a struct) as a new value of the plan's target type
|
|
30761
31413
|
func (p *tnConvPlan) convert(v interface{}) reflect.Value {
|
|
31414
|
+
return p.convertTo(v, true)
|
|
31415
|
+
}
|
|
31416
|
+
|
|
31417
|
+
// (identity false: a copy no other conversion will look for — TnAsCopy)
|
|
31418
|
+
func (p *tnConvPlan) convertTo(v interface{}, identity bool) reflect.Value {
|
|
30762
31419
|
src := (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1]
|
|
30763
31420
|
if p.view {
|
|
30764
31421
|
if p.narrow {
|
|
@@ -30773,8 +31430,14 @@ func (p *tnConvPlan) convert(v interface{}) reflect.Value {
|
|
|
30773
31430
|
// the same converted object, its fields refreshed from the source — JS
|
|
30774
31431
|
// identity for Set / Map keys and === (a Babel node read as a
|
|
30775
31432
|
// t.Identifier: hoistable.has(path.node) finds binding.identifier))
|
|
30776
|
-
|
|
30777
|
-
|
|
31433
|
+
var dst unsafe.Pointer
|
|
31434
|
+
cached := false
|
|
31435
|
+
if identity {
|
|
31436
|
+
dst, cached = tnStructIdentityOf(src, p.dst, p.src.Size())
|
|
31437
|
+
} else {
|
|
31438
|
+
dst = reflect.New(p.dst).UnsafePointer()
|
|
31439
|
+
}
|
|
31440
|
+
out := reflect.NewAt(p.dst, dst)
|
|
30778
31441
|
if cached {
|
|
30779
31442
|
reflect.NewAt(p.dst, dst).Elem().SetZero()
|
|
30780
31443
|
}
|
|
@@ -30813,14 +31476,12 @@ func (p *tnConvPlan) convert(v interface{}) reflect.Value {
|
|
|
30813
31476
|
}
|
|
30814
31477
|
}
|
|
30815
31478
|
}
|
|
30816
|
-
// (a narrowing copy — the source has every target field plus extras — is
|
|
30817
|
-
// registered so field writes through it reach the source: JS object
|
|
30818
|
-
// identity across merged-union member views)
|
|
30819
|
-
if p.src.NumField() > p.dst.NumField() && !cached {
|
|
30820
|
-
tnRegisterView(out.Interface(), reflect.NewAt(p.src, src).Interface())
|
|
30821
|
-
}
|
|
30822
31479
|
// the properties the object carries beyond its struct (tnExpandos): a
|
|
30823
|
-
// target field of the same name reads them
|
|
31480
|
+
// target field of the same name reads them (only an object of a type
|
|
31481
|
+
// that ever had one can: tnExpandoPropsOf)
|
|
31482
|
+
if !tnExpandoTypes.has(v) {
|
|
31483
|
+
return out
|
|
31484
|
+
}
|
|
30824
31485
|
for _, ef := range p.expandos {
|
|
30825
31486
|
value, ok := tnExpandoGet(v, ef.name)
|
|
30826
31487
|
if !ok || value == nil {
|
|
@@ -30903,25 +31564,30 @@ func tnFuncResults(out []reflect.Value, t reflect.Type) []reflect.Value {
|
|
|
30903
31564
|
return results
|
|
30904
31565
|
}
|
|
30905
31566
|
|
|
31567
|
+
// The conversion plan from v's type to t (v non-nil)
|
|
31568
|
+
func tnConvPlanOf(v interface{}, t reflect.Type) *tnConvPlan {
|
|
31569
|
+
from, to := (*[2]unsafe.Pointer)(unsafe.Pointer(&v)), (*[2]unsafe.Pointer)(unsafe.Pointer(&t))[1]
|
|
31570
|
+
h := ((uintptr(from[0])>>4 ^ uintptr(to)>>7) * 0x9E3779B1) >> 12 & (1<<10 - 1)
|
|
31571
|
+
p := tnConvPlans[h].Load()
|
|
31572
|
+
if p == nil || p.from != from[0] || p.to != to {
|
|
31573
|
+
key := [2]unsafe.Pointer{from[0], to}
|
|
31574
|
+
tnConvPlanMu.RLock()
|
|
31575
|
+
p = tnConvPlanIndex[key]
|
|
31576
|
+
tnConvPlanMu.RUnlock()
|
|
31577
|
+
if p == nil {
|
|
31578
|
+
p = tnMakeConvPlan(v, t, from[0], to)
|
|
31579
|
+
tnConvPlanMu.Lock()
|
|
31580
|
+
tnConvPlanIndex[key] = p
|
|
31581
|
+
tnConvPlanMu.Unlock()
|
|
31582
|
+
}
|
|
31583
|
+
tnConvPlans[h].Store(p)
|
|
31584
|
+
}
|
|
31585
|
+
return p
|
|
31586
|
+
}
|
|
31587
|
+
|
|
30906
31588
|
func TnConvertDynamic(v interface{}, t reflect.Type) (reflect.Value, bool) {
|
|
30907
31589
|
if v != nil {
|
|
30908
|
-
|
|
30909
|
-
h := ((uintptr(from[0])>>4 ^ uintptr(to)>>7) * 0x9E3779B1) >> 12 & (1<<10 - 1)
|
|
30910
|
-
p := tnConvPlans[h].Load()
|
|
30911
|
-
if p == nil || p.from != from[0] || p.to != to {
|
|
30912
|
-
key := [2]unsafe.Pointer{from[0], to}
|
|
30913
|
-
tnConvPlanMu.RLock()
|
|
30914
|
-
p = tnConvPlanIndex[key]
|
|
30915
|
-
tnConvPlanMu.RUnlock()
|
|
30916
|
-
if p == nil {
|
|
30917
|
-
p = tnMakeConvPlan(v, t, from[0], to)
|
|
30918
|
-
tnConvPlanMu.Lock()
|
|
30919
|
-
tnConvPlanIndex[key] = p
|
|
30920
|
-
tnConvPlanMu.Unlock()
|
|
30921
|
-
}
|
|
30922
|
-
tnConvPlans[h].Store(p)
|
|
30923
|
-
}
|
|
30924
|
-
if p.ok && from[1] != nil {
|
|
31590
|
+
if p := tnConvPlanOf(v, t); p.ok && (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1] != nil {
|
|
30925
31591
|
return p.convert(v), true
|
|
30926
31592
|
}
|
|
30927
31593
|
}
|
|
@@ -31758,6 +32424,12 @@ func TnFlatItems(v interface{}) []interface{} {
|
|
|
31758
32424
|
return []interface{}{v}
|
|
31759
32425
|
}
|
|
31760
32426
|
|
|
32427
|
+
// (a class whose *[Symbol.iterator]() has a push form, e.g. an OpList: its
|
|
32428
|
+
// values without reflection, a channel or a goroutine)
|
|
32429
|
+
type tnSeqIter interface {
|
|
32430
|
+
Symbol_iterator__seq() func(func(interface{}) bool)
|
|
32431
|
+
}
|
|
32432
|
+
|
|
31761
32433
|
func TnToArray(v interface{}) []interface{} {
|
|
31762
32434
|
switch t := v.(type) {
|
|
31763
32435
|
case nil:
|
|
@@ -31766,6 +32438,18 @@ func TnToArray(v interface{}) []interface{} {
|
|
|
31766
32438
|
return append([]interface{}{}, t...)
|
|
31767
32439
|
case tnArrayLike:
|
|
31768
32440
|
return append([]interface{}{}, (*t.TnItems())...)
|
|
32441
|
+
case tnSeqIter:
|
|
32442
|
+
out := []interface{}{}
|
|
32443
|
+
for x := range t.Symbol_iterator__seq() {
|
|
32444
|
+
out = append(out, x)
|
|
32445
|
+
}
|
|
32446
|
+
return out
|
|
32447
|
+
case interface{ Symbol_iterator() chan interface{} }:
|
|
32448
|
+
out := []interface{}{}
|
|
32449
|
+
for x := range t.Symbol_iterator() {
|
|
32450
|
+
out = append(out, x)
|
|
32451
|
+
}
|
|
32452
|
+
return out
|
|
31769
32453
|
case string:
|
|
31770
32454
|
out := []interface{}{}
|
|
31771
32455
|
for _, r := range t {
|
|
@@ -31914,17 +32598,27 @@ type tnStrShortEntry struct {
|
|
|
31914
32598
|
ascii bool
|
|
31915
32599
|
}
|
|
31916
32600
|
|
|
31917
|
-
|
|
32601
|
+
// (guarded by a mutex: a pointer published then replaced would race with a
|
|
32602
|
+
// reader, and an entry per miss is an allocation per inline token)
|
|
32603
|
+
var tnStrShortMu sync.Mutex
|
|
32604
|
+
var tnStrShortS string
|
|
32605
|
+
var tnStrShortA bool
|
|
31918
32606
|
|
|
31919
32607
|
func tnStrShortASCII(s string) bool {
|
|
31920
32608
|
if len(s) <= 64 {
|
|
31921
32609
|
return tnStrIsASCII(s)
|
|
31922
32610
|
}
|
|
31923
|
-
|
|
31924
|
-
|
|
32611
|
+
tnStrShortMu.Lock()
|
|
32612
|
+
if len(tnStrShortS) == len(s) && unsafe.StringData(tnStrShortS) == unsafe.StringData(s) {
|
|
32613
|
+
ascii := tnStrShortA
|
|
32614
|
+
tnStrShortMu.Unlock()
|
|
32615
|
+
return ascii
|
|
31925
32616
|
}
|
|
32617
|
+
tnStrShortMu.Unlock()
|
|
31926
32618
|
ascii := tnStrIsASCII(s)
|
|
31927
|
-
|
|
32619
|
+
tnStrShortMu.Lock()
|
|
32620
|
+
tnStrShortS, tnStrShortA = s, ascii
|
|
32621
|
+
tnStrShortMu.Unlock()
|
|
31928
32622
|
return ascii
|
|
31929
32623
|
}
|
|
31930
32624
|
|
|
@@ -32852,23 +33546,36 @@ func (d *tnJTDecoder) escaped(start int) (string, bool) {
|
|
|
32852
33546
|
jsonStringify: `// JSON.stringify: JS's SerializeJSONProperty over TypeNative values
|
|
32853
33547
|
// (unexported struct fields included; Go's encoder would skip them)
|
|
32854
33548
|
type tnJSONWriter struct {
|
|
32855
|
-
buf
|
|
33549
|
+
buf []byte
|
|
32856
33550
|
indent string
|
|
32857
33551
|
replacer func(key string, value interface{}) interface{}
|
|
32858
33552
|
allow map[string]bool
|
|
32859
33553
|
stack []uintptr
|
|
32860
33554
|
}
|
|
32861
33555
|
|
|
33556
|
+
var tnJSONWriterPool = sync.Pool{
|
|
33557
|
+
New: func() interface{} {
|
|
33558
|
+
return &tnJSONWriter{buf: make([]byte, 0, 512)}
|
|
33559
|
+
},
|
|
33560
|
+
}
|
|
33561
|
+
|
|
32862
33562
|
func TnJSONStringify(v interface{}, indent string) string {
|
|
32863
|
-
w :=
|
|
33563
|
+
w := tnJSONWriterPool.Get().(*tnJSONWriter)
|
|
33564
|
+
w.buf = w.buf[:0]
|
|
33565
|
+
w.indent = indent
|
|
33566
|
+
w.stack = w.stack[:0]
|
|
32864
33567
|
w.property("", v, 0)
|
|
32865
|
-
|
|
33568
|
+
s := string(w.buf)
|
|
33569
|
+
if cap(w.buf) <= 65536 {
|
|
33570
|
+
tnJSONWriterPool.Put(w)
|
|
33571
|
+
}
|
|
33572
|
+
return s
|
|
32866
33573
|
}
|
|
32867
33574
|
|
|
32868
33575
|
// JSON.stringify(value, replacer, space): the replacer is a key/value
|
|
32869
33576
|
// function or a list of keys; space a number of spaces or a string (≤ 10)
|
|
32870
33577
|
func TnJSONStringifyWith(v interface{}, replacer interface{}, space interface{}) string {
|
|
32871
|
-
w := &tnJSONWriter{}
|
|
33578
|
+
w := &tnJSONWriter{buf: make([]byte, 0, 256)}
|
|
32872
33579
|
switch s := space.(type) {
|
|
32873
33580
|
case float64:
|
|
32874
33581
|
w.indent = strings.Repeat(" ", int(math.Max(0, math.Min(10, s))))
|
|
@@ -32903,7 +33610,7 @@ func TnJSONStringifyWith(v interface{}, replacer interface{}, space interface{})
|
|
|
32903
33610
|
if !w.property("", v, 0) {
|
|
32904
33611
|
return ""
|
|
32905
33612
|
}
|
|
32906
|
-
return w.buf
|
|
33613
|
+
return string(w.buf)
|
|
32907
33614
|
}
|
|
32908
33615
|
|
|
32909
33616
|
// Values being written, innermost last: meeting one again is a cycle
|
|
@@ -32924,12 +33631,24 @@ func (w *tnJSONWriter) newline(depth int) {
|
|
|
32924
33631
|
if w.indent == "" {
|
|
32925
33632
|
return
|
|
32926
33633
|
}
|
|
32927
|
-
w.buf.
|
|
33634
|
+
w.buf = append(w.buf, '\\n')
|
|
32928
33635
|
for i := 0; i < depth; i++ {
|
|
32929
|
-
w.buf
|
|
33636
|
+
w.buf = append(w.buf, w.indent...)
|
|
32930
33637
|
}
|
|
32931
33638
|
}
|
|
32932
33639
|
|
|
33640
|
+
func tnJSONAppendNum(buf []byte, f float64) []byte {
|
|
33641
|
+
if f > -9007199254740992 && f < 9007199254740992 {
|
|
33642
|
+
if i := int64(f); float64(i) == f {
|
|
33643
|
+
return strconv.AppendInt(buf, i, 10)
|
|
33644
|
+
}
|
|
33645
|
+
}
|
|
33646
|
+
if math.IsNaN(f) || math.IsInf(f, 0) {
|
|
33647
|
+
return append(buf, "null"...)
|
|
33648
|
+
}
|
|
33649
|
+
return append(buf, TnNumStr(f)...)
|
|
33650
|
+
}
|
|
33651
|
+
|
|
32933
33652
|
// toJSON() methods (Dates' included): the value serialized in their place
|
|
32934
33653
|
func tnJSONToJSON(v interface{}) interface{} {
|
|
32935
33654
|
switch t := v.(type) {
|
|
@@ -32966,27 +33685,41 @@ func tnJSONFieldName(name string) string {
|
|
|
32966
33685
|
|
|
32967
33686
|
// Writes one value; false when it serializes to undefined (functions)
|
|
32968
33687
|
func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
32969
|
-
v = tnJSONToJSON(v)
|
|
32970
33688
|
switch t := v.(type) {
|
|
32971
|
-
case nil,
|
|
32972
|
-
w.buf.
|
|
33689
|
+
case nil, *tnNullValue:
|
|
33690
|
+
w.buf = append(w.buf, "null"...)
|
|
32973
33691
|
return true
|
|
32974
33692
|
case bool:
|
|
32975
33693
|
if t {
|
|
32976
|
-
w.buf.
|
|
33694
|
+
w.buf = append(w.buf, "true"...)
|
|
32977
33695
|
} else {
|
|
32978
|
-
w.buf.
|
|
33696
|
+
w.buf = append(w.buf, "false"...)
|
|
32979
33697
|
}
|
|
32980
33698
|
return true
|
|
32981
33699
|
case float64:
|
|
32982
|
-
|
|
32983
|
-
|
|
33700
|
+
w.buf = tnJSONAppendNum(w.buf, t)
|
|
33701
|
+
return true
|
|
33702
|
+
case string:
|
|
33703
|
+
w.buf = tnJSONAppendQuote(w.buf, t)
|
|
33704
|
+
return true
|
|
33705
|
+
}
|
|
33706
|
+
v = tnJSONToJSON(v)
|
|
33707
|
+
switch t := v.(type) {
|
|
33708
|
+
case nil, interface{ TnIsNullValue() }:
|
|
33709
|
+
w.buf = append(w.buf, "null"...)
|
|
33710
|
+
return true
|
|
33711
|
+
case bool:
|
|
33712
|
+
if t {
|
|
33713
|
+
w.buf = append(w.buf, "true"...)
|
|
32984
33714
|
} else {
|
|
32985
|
-
w.buf.
|
|
33715
|
+
w.buf = append(w.buf, "false"...)
|
|
32986
33716
|
}
|
|
32987
33717
|
return true
|
|
33718
|
+
case float64:
|
|
33719
|
+
w.buf = tnJSONAppendNum(w.buf, t)
|
|
33720
|
+
return true
|
|
32988
33721
|
case string:
|
|
32989
|
-
|
|
33722
|
+
w.buf = tnJSONAppendQuote(w.buf, t)
|
|
32990
33723
|
return true
|
|
32991
33724
|
case []byte:
|
|
32992
33725
|
// a Buffer serializes through its toJSON(): { type, data }
|
|
@@ -33000,25 +33733,39 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
|
33000
33733
|
})
|
|
33001
33734
|
}
|
|
33002
33735
|
rv := reflect.ValueOf(v)
|
|
33003
|
-
if rv.Type().String() == "*big.Int" {
|
|
33736
|
+
if rv.Kind() == reflect.Pointer && rv.Type().Elem().Kind() != reflect.Struct && rv.Type().Elem().Kind() != reflect.Slice && rv.Type().String() == "*big.Int" {
|
|
33004
33737
|
panic(TnNodeError("TypeError", "", "Do not know how to serialize a BigInt"))
|
|
33005
33738
|
}
|
|
33739
|
+
if rv.Kind() == reflect.Pointer && !rv.IsNil() && rv.Elem().Kind() == reflect.Slice && w.replacer == nil && w.allow == nil {
|
|
33740
|
+
w.enter(rv.Pointer())
|
|
33741
|
+
defer w.leave()
|
|
33742
|
+
rv = rv.Elem()
|
|
33743
|
+
}
|
|
33006
33744
|
switch rv.Kind() {
|
|
33007
33745
|
case reflect.Func:
|
|
33008
33746
|
return false
|
|
33009
33747
|
case reflect.Pointer, reflect.Interface:
|
|
33010
33748
|
if rv.IsNil() {
|
|
33011
|
-
w.buf.
|
|
33749
|
+
w.buf = append(w.buf, "null"...)
|
|
33012
33750
|
return true
|
|
33013
33751
|
}
|
|
33014
33752
|
if rv.Kind() == reflect.Pointer {
|
|
33753
|
+
if rv.Elem().Kind() == reflect.Struct && w.replacer == nil && w.allow == nil {
|
|
33754
|
+
plan := tnJSONGetPlan(rv.Elem().Type())
|
|
33755
|
+
if !plan.hasCustom {
|
|
33756
|
+
return w.fastStructPtr(rv.UnsafePointer(), plan, depth)
|
|
33757
|
+
}
|
|
33758
|
+
if rv.Type().String() == "*big.Int" {
|
|
33759
|
+
panic(TnNodeError("TypeError", "", "Do not know how to serialize a BigInt"))
|
|
33760
|
+
}
|
|
33761
|
+
}
|
|
33015
33762
|
// Records and Maps: insertion order; Maps and Sets serialize as {}
|
|
33016
33763
|
if m, ok := v.(interface {
|
|
33017
33764
|
Entries() [][]interface{}
|
|
33018
33765
|
TnJSKind() uint8
|
|
33019
33766
|
}); ok {
|
|
33020
33767
|
if m.TnJSKind() != 0 {
|
|
33021
|
-
w.buf.
|
|
33768
|
+
w.buf = append(w.buf, "{}"...)
|
|
33022
33769
|
return true
|
|
33023
33770
|
}
|
|
33024
33771
|
return w.object(depth, func(emit func(string, interface{})) {
|
|
@@ -33027,9 +33774,6 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
|
33027
33774
|
}
|
|
33028
33775
|
})
|
|
33029
33776
|
}
|
|
33030
|
-
if rv.Elem().Kind() == reflect.Struct && w.replacer == nil && w.allow == nil && !rv.Elem().Type().Implements(tnJSONMarshalerType) {
|
|
33031
|
-
return w.fastStruct(rv, depth)
|
|
33032
|
-
}
|
|
33033
33777
|
if rv.Elem().Kind() == reflect.Struct || rv.Elem().Kind() == reflect.Slice || rv.Elem().Kind() == reflect.Map {
|
|
33034
33778
|
w.enter(rv.Pointer())
|
|
33035
33779
|
defer w.leave()
|
|
@@ -33042,33 +33786,60 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
|
33042
33786
|
return w.property(key, reflect.NewAt(elem.Type(), unsafe.Pointer(elem.UnsafeAddr())).Elem().Interface(), depth)
|
|
33043
33787
|
case reflect.Slice, reflect.Array:
|
|
33044
33788
|
if rv.Kind() == reflect.Slice && rv.IsNil() {
|
|
33045
|
-
w.buf.
|
|
33789
|
+
w.buf = append(w.buf, "[]"...)
|
|
33046
33790
|
return true
|
|
33047
33791
|
}
|
|
33048
|
-
|
|
33049
|
-
|
|
33792
|
+
n := rv.Len()
|
|
33793
|
+
if n == 0 {
|
|
33794
|
+
w.buf = append(w.buf, "[]"...)
|
|
33050
33795
|
return true
|
|
33051
33796
|
}
|
|
33052
33797
|
if rv.Kind() == reflect.Slice {
|
|
33053
33798
|
w.enter(rv.Pointer())
|
|
33054
33799
|
defer w.leave()
|
|
33800
|
+
if w.replacer == nil && w.allow == nil {
|
|
33801
|
+
et := rv.Type().Elem()
|
|
33802
|
+
if et.Kind() == reflect.Pointer && et.Elem().Kind() == reflect.Struct {
|
|
33803
|
+
plan := tnJSONGetPlan(et.Elem())
|
|
33804
|
+
if !plan.hasCustom {
|
|
33805
|
+
ptrs := unsafe.Slice((*unsafe.Pointer)(rv.UnsafePointer()), n)
|
|
33806
|
+
w.buf = append(w.buf, '[')
|
|
33807
|
+
for i, p := range ptrs {
|
|
33808
|
+
if i > 0 {
|
|
33809
|
+
w.buf = append(w.buf, ',')
|
|
33810
|
+
}
|
|
33811
|
+
w.newline(depth + 1)
|
|
33812
|
+
if p == nil {
|
|
33813
|
+
w.buf = append(w.buf, "null"...)
|
|
33814
|
+
} else {
|
|
33815
|
+
w.fastStructPtr(p, plan, depth+1)
|
|
33816
|
+
}
|
|
33817
|
+
}
|
|
33818
|
+
w.newline(depth)
|
|
33819
|
+
w.buf = append(w.buf, ']')
|
|
33820
|
+
return true
|
|
33821
|
+
}
|
|
33822
|
+
}
|
|
33823
|
+
}
|
|
33055
33824
|
}
|
|
33056
|
-
w.buf.
|
|
33057
|
-
for i := 0; i <
|
|
33825
|
+
w.buf = append(w.buf, '[')
|
|
33826
|
+
for i := 0; i < n; i++ {
|
|
33058
33827
|
if i > 0 {
|
|
33059
|
-
w.buf.
|
|
33828
|
+
w.buf = append(w.buf, ',')
|
|
33060
33829
|
}
|
|
33061
33830
|
w.newline(depth + 1)
|
|
33062
33831
|
item := rv.Index(i).Interface()
|
|
33832
|
+
var itemKey string
|
|
33063
33833
|
if w.replacer != nil {
|
|
33064
|
-
|
|
33834
|
+
itemKey = strconv.Itoa(i)
|
|
33835
|
+
item = w.replacer(itemKey, item)
|
|
33065
33836
|
}
|
|
33066
|
-
if !w.property(
|
|
33067
|
-
w.buf.
|
|
33837
|
+
if !w.property(itemKey, item, depth+1) {
|
|
33838
|
+
w.buf = append(w.buf, "null"...)
|
|
33068
33839
|
}
|
|
33069
33840
|
}
|
|
33070
33841
|
w.newline(depth)
|
|
33071
|
-
w.buf.
|
|
33842
|
+
w.buf = append(w.buf, ']')
|
|
33072
33843
|
return true
|
|
33073
33844
|
case reflect.Map:
|
|
33074
33845
|
// Dynamic objects (JSON.parse results): Go maps keep no order, keys sort
|
|
@@ -33090,7 +33861,7 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
|
33090
33861
|
case reflect.Struct:
|
|
33091
33862
|
if m, ok := v.(json.Marshaler); ok {
|
|
33092
33863
|
if data, err := m.MarshalJSON(); err == nil {
|
|
33093
|
-
w.buf.
|
|
33864
|
+
w.buf = append(w.buf, data...)
|
|
33094
33865
|
return true
|
|
33095
33866
|
}
|
|
33096
33867
|
}
|
|
@@ -33098,10 +33869,10 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
|
|
|
33098
33869
|
}
|
|
33099
33870
|
data, err := tnJSONMarshal(v)
|
|
33100
33871
|
if err != nil {
|
|
33101
|
-
w.buf.
|
|
33872
|
+
w.buf = append(w.buf, "null"...)
|
|
33102
33873
|
return true
|
|
33103
33874
|
}
|
|
33104
|
-
w.buf.
|
|
33875
|
+
w.buf = append(w.buf, data...)
|
|
33105
33876
|
return true
|
|
33106
33877
|
}
|
|
33107
33878
|
|
|
@@ -33180,51 +33951,48 @@ func (w *tnJSONWriter) structFieldsInOrder(rv reflect.Value, emit func(string, i
|
|
|
33180
33951
|
|
|
33181
33952
|
// A JSON string as JSON.stringify writes it: U+2028 / U+2029 stay raw (Go's
|
|
33182
33953
|
// encoder escapes them), invalid UTF-8 becomes \\ufffd
|
|
33183
|
-
func
|
|
33954
|
+
func tnJSONAppendQuote(buf []byte, s string) []byte {
|
|
33184
33955
|
const hex = "0123456789abcdef"
|
|
33185
|
-
buf
|
|
33956
|
+
buf = append(buf, '"')
|
|
33186
33957
|
start := 0
|
|
33187
33958
|
for i := 0; i < len(s); {
|
|
33188
33959
|
c := s[i]
|
|
33189
|
-
if c
|
|
33190
|
-
|
|
33191
|
-
|
|
33192
|
-
|
|
33193
|
-
|
|
33194
|
-
|
|
33960
|
+
if c < utf8.RuneSelf {
|
|
33961
|
+
if c >= 0x20 && c != '"' && c != '\\\\' {
|
|
33962
|
+
i++
|
|
33963
|
+
continue
|
|
33964
|
+
}
|
|
33965
|
+
buf = append(buf, s[start:i]...)
|
|
33966
|
+
switch c {
|
|
33967
|
+
case '"', '\\\\':
|
|
33968
|
+
buf = append(buf, '\\\\', c)
|
|
33969
|
+
case '\\n':
|
|
33970
|
+
buf = append(buf, '\\\\', 'n')
|
|
33971
|
+
case '\\r':
|
|
33972
|
+
buf = append(buf, '\\\\', 'r')
|
|
33973
|
+
case '\\t':
|
|
33974
|
+
buf = append(buf, '\\\\', 't')
|
|
33975
|
+
case '\\b':
|
|
33976
|
+
buf = append(buf, '\\\\', 'b')
|
|
33977
|
+
case '\\f':
|
|
33978
|
+
buf = append(buf, '\\\\', 'f')
|
|
33979
|
+
default:
|
|
33980
|
+
buf = append(buf, '\\\\', 'u', '0', '0', hex[c>>4], hex[c&0xF])
|
|
33195
33981
|
}
|
|
33196
|
-
i += size
|
|
33197
|
-
continue
|
|
33198
|
-
}
|
|
33199
|
-
if c >= 0x20 && c != '"' && c != '\\\\' {
|
|
33200
33982
|
i++
|
|
33983
|
+
start = i
|
|
33201
33984
|
continue
|
|
33202
33985
|
}
|
|
33203
|
-
|
|
33204
|
-
|
|
33205
|
-
|
|
33206
|
-
|
|
33207
|
-
|
|
33208
|
-
case '\\n':
|
|
33209
|
-
buf.WriteByte('n')
|
|
33210
|
-
case '\\r':
|
|
33211
|
-
buf.WriteByte('r')
|
|
33212
|
-
case '\\t':
|
|
33213
|
-
buf.WriteByte('t')
|
|
33214
|
-
case '\\b':
|
|
33215
|
-
buf.WriteByte('b')
|
|
33216
|
-
case '\\f':
|
|
33217
|
-
buf.WriteByte('f')
|
|
33218
|
-
default:
|
|
33219
|
-
buf.WriteString("u00")
|
|
33220
|
-
buf.WriteByte(hex[c>>4])
|
|
33221
|
-
buf.WriteByte(hex[c&0xF])
|
|
33986
|
+
r, size := utf8.DecodeRuneInString(s[i:])
|
|
33987
|
+
if r == utf8.RuneError && size == 1 {
|
|
33988
|
+
buf = append(buf, s[start:i]...)
|
|
33989
|
+
buf = append(buf, "\\\\ufffd"...)
|
|
33990
|
+
start = i + 1
|
|
33222
33991
|
}
|
|
33223
|
-
i
|
|
33224
|
-
start = i
|
|
33992
|
+
i += size
|
|
33225
33993
|
}
|
|
33226
|
-
buf
|
|
33227
|
-
buf
|
|
33994
|
+
buf = append(buf, s[start:]...)
|
|
33995
|
+
return append(buf, '"')
|
|
33228
33996
|
}
|
|
33229
33997
|
|
|
33230
33998
|
// A struct type's JSON fields (structFields' rules), resolved once per type:
|
|
@@ -33239,14 +34007,35 @@ type tnJSONField struct {
|
|
|
33239
34007
|
null bool // (T | null: nil is null, not undefined)
|
|
33240
34008
|
}
|
|
33241
34009
|
|
|
33242
|
-
|
|
33243
|
-
|
|
34010
|
+
type tnJSONStructPlan struct {
|
|
34011
|
+
typ reflect.Type
|
|
34012
|
+
fields []tnJSONField
|
|
34013
|
+
hasKeys bool
|
|
34014
|
+
keysOffset uintptr
|
|
34015
|
+
cycleFree bool
|
|
34016
|
+
hasCustom bool
|
|
34017
|
+
}
|
|
34018
|
+
|
|
34019
|
+
var (
|
|
34020
|
+
tnJSONPlans sync.Map
|
|
34021
|
+
tnJSONMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
|
|
34022
|
+
tnToJSONStrType = reflect.TypeOf((*interface{ toJSON() string })(nil)).Elem()
|
|
34023
|
+
tnToJSONFloatType = reflect.TypeOf((*interface{ toJSON() float64 })(nil)).Elem()
|
|
34024
|
+
tnToJSONBoolType = reflect.TypeOf((*interface{ toJSON() bool })(nil)).Elem()
|
|
34025
|
+
tnToJSONAnyType = reflect.TypeOf((*interface{ toJSON() interface{} })(nil)).Elem()
|
|
34026
|
+
tnTnToJSONType = reflect.TypeOf((*interface{ TnToJSON(string) interface{} })(nil)).Elem()
|
|
34027
|
+
tnTnItemsType = reflect.TypeOf((*interface{ TnItems() *[]interface{} })(nil)).Elem()
|
|
34028
|
+
tnJSKindType = reflect.TypeOf((*interface{ TnJSKind() uint8 })(nil)).Elem()
|
|
34029
|
+
tnEntriesType = reflect.TypeOf((*interface{ Entries() [][]interface{} })(nil)).Elem()
|
|
34030
|
+
tnTimeType = reflect.TypeOf(time.Time{})
|
|
34031
|
+
)
|
|
33244
34032
|
|
|
33245
|
-
func
|
|
34033
|
+
func tnJSONGetPlan(t reflect.Type) *tnJSONStructPlan {
|
|
33246
34034
|
if plan, ok := tnJSONPlans.Load(t); ok {
|
|
33247
|
-
return plan.(
|
|
34035
|
+
return plan.(*tnJSONStructPlan)
|
|
33248
34036
|
}
|
|
33249
34037
|
fields := []tnJSONField{}
|
|
34038
|
+
cycleFree := true
|
|
33250
34039
|
var walk func(t reflect.Type, base uintptr)
|
|
33251
34040
|
walk = func(t reflect.Type, base uintptr) {
|
|
33252
34041
|
for i := 0; i < t.NumField(); i++ {
|
|
@@ -33261,9 +34050,8 @@ func tnJSONPlan(t reflect.Type) []tnJSONField {
|
|
|
33261
34050
|
continue
|
|
33262
34051
|
}
|
|
33263
34052
|
name := tnJSONFieldName(f.Name)
|
|
33264
|
-
|
|
33265
|
-
|
|
33266
|
-
key.WriteByte(':')
|
|
34053
|
+
key := tnJSONAppendQuote(make([]byte, 0, len(name)+3), name)
|
|
34054
|
+
key = append(key, ':')
|
|
33267
34055
|
kind := uint8(0)
|
|
33268
34056
|
switch f.Type {
|
|
33269
34057
|
case reflect.TypeOf(float64(0)):
|
|
@@ -33272,65 +34060,90 @@ func tnJSONPlan(t reflect.Type) []tnJSONField {
|
|
|
33272
34060
|
kind = 2
|
|
33273
34061
|
case reflect.TypeOf(false):
|
|
33274
34062
|
kind = 3
|
|
34063
|
+
default:
|
|
34064
|
+
cycleFree = false
|
|
33275
34065
|
}
|
|
33276
|
-
fields = append(fields, tnJSONField{offset: base + f.Offset, typ: f.Type, name: name, key: key
|
|
34066
|
+
fields = append(fields, tnJSONField{offset: base + f.Offset, typ: f.Type, name: name, key: string(key), kind: kind, null: f.Tag.Get("tn") == "null"})
|
|
33277
34067
|
}
|
|
33278
34068
|
}
|
|
33279
34069
|
walk(t, 0)
|
|
33280
|
-
|
|
33281
|
-
|
|
34070
|
+
var hasKeys bool
|
|
34071
|
+
var keysOffset uintptr
|
|
34072
|
+
if kf, ok := t.FieldByName("__keys"); ok && kf.Type == reflect.TypeOf((*[]string)(nil)) {
|
|
34073
|
+
hasKeys = true
|
|
34074
|
+
keysOffset = kf.Offset
|
|
34075
|
+
}
|
|
34076
|
+
pt := reflect.PointerTo(t)
|
|
34077
|
+
hasCustom := t == tnTimeType || pt.String() == "*big.Int" ||
|
|
34078
|
+
t.Implements(tnJSONMarshalerType) || pt.Implements(tnJSONMarshalerType) ||
|
|
34079
|
+
pt.Implements(tnToJSONStrType) || pt.Implements(tnToJSONFloatType) ||
|
|
34080
|
+
pt.Implements(tnToJSONBoolType) || pt.Implements(tnToJSONAnyType) ||
|
|
34081
|
+
pt.Implements(tnTnToJSONType) || pt.Implements(tnTnItemsType) ||
|
|
34082
|
+
pt.Implements(tnJSKindType) || pt.Implements(tnEntriesType)
|
|
34083
|
+
plan := &tnJSONStructPlan{
|
|
34084
|
+
typ: t,
|
|
34085
|
+
fields: fields,
|
|
34086
|
+
hasKeys: hasKeys,
|
|
34087
|
+
keysOffset: keysOffset,
|
|
34088
|
+
cycleFree: cycleFree,
|
|
34089
|
+
hasCustom: hasCustom,
|
|
34090
|
+
}
|
|
34091
|
+
tnJSONPlans.Store(t, plan)
|
|
34092
|
+
return plan
|
|
33282
34093
|
}
|
|
33283
34094
|
|
|
33284
34095
|
// A struct behind a pointer, written in place: no copy of the struct, no
|
|
33285
34096
|
// boxing of its numbers, strings and booleans
|
|
33286
|
-
func (w *tnJSONWriter)
|
|
34097
|
+
func (w *tnJSONWriter) fastStructPtr(base unsafe.Pointer, plan *tnJSONStructPlan, depth int) bool {
|
|
33287
34098
|
// (an object whose keys were created in another order: see structFields)
|
|
33288
|
-
if
|
|
33289
|
-
w.enter(
|
|
34099
|
+
if plan.hasKeys && *(**[]string)(unsafe.Add(base, plan.keysOffset)) != nil {
|
|
34100
|
+
w.enter(uintptr(base))
|
|
33290
34101
|
defer w.leave()
|
|
33291
|
-
|
|
34102
|
+
elem := reflect.NewAt(plan.typ, base).Elem()
|
|
34103
|
+
return w.object(depth, func(emit func(string, interface{})) { w.structFields(elem, emit) })
|
|
33292
34104
|
}
|
|
33293
|
-
|
|
33294
|
-
|
|
33295
|
-
|
|
33296
|
-
|
|
34105
|
+
if !plan.cycleFree {
|
|
34106
|
+
w.enter(uintptr(base))
|
|
34107
|
+
defer w.leave()
|
|
34108
|
+
}
|
|
34109
|
+
w.buf = append(w.buf, '{')
|
|
33297
34110
|
wrote := false
|
|
33298
|
-
for _, f := range
|
|
33299
|
-
mark := w.buf
|
|
34111
|
+
for _, f := range plan.fields {
|
|
34112
|
+
mark := len(w.buf)
|
|
33300
34113
|
if wrote {
|
|
33301
|
-
w.buf.
|
|
34114
|
+
w.buf = append(w.buf, ',')
|
|
33302
34115
|
}
|
|
33303
34116
|
w.newline(depth + 1)
|
|
33304
|
-
w.buf.
|
|
34117
|
+
w.buf = append(w.buf, f.key...)
|
|
33305
34118
|
if w.indent != "" {
|
|
33306
|
-
w.buf.
|
|
34119
|
+
w.buf = append(w.buf, ' ')
|
|
33307
34120
|
}
|
|
33308
34121
|
p := unsafe.Add(base, f.offset)
|
|
33309
34122
|
switch f.kind {
|
|
33310
34123
|
case 1:
|
|
33311
|
-
|
|
33312
|
-
w.buf.WriteString("null")
|
|
33313
|
-
} else {
|
|
33314
|
-
w.buf.WriteString(TnNumStr(x))
|
|
33315
|
-
}
|
|
34124
|
+
w.buf = tnJSONAppendNum(w.buf, *(*float64)(p))
|
|
33316
34125
|
case 2:
|
|
33317
|
-
|
|
34126
|
+
w.buf = tnJSONAppendQuote(w.buf, *(*string)(p))
|
|
33318
34127
|
case 3:
|
|
33319
|
-
|
|
34128
|
+
if *(*bool)(p) {
|
|
34129
|
+
w.buf = append(w.buf, "true"...)
|
|
34130
|
+
} else {
|
|
34131
|
+
w.buf = append(w.buf, "false"...)
|
|
34132
|
+
}
|
|
33320
34133
|
default:
|
|
33321
34134
|
// (an unset field — a nil pointer or any — is undefined: no key, as in JS)
|
|
33322
34135
|
fv := reflect.NewAt(f.typ, p).Elem()
|
|
33323
34136
|
if (fv.Kind() == reflect.Pointer || fv.Kind() == reflect.Interface) && fv.IsNil() {
|
|
33324
34137
|
if f.null {
|
|
33325
|
-
w.buf.
|
|
34138
|
+
w.buf = append(w.buf, "null"...)
|
|
33326
34139
|
wrote = true
|
|
33327
34140
|
continue
|
|
33328
34141
|
}
|
|
33329
|
-
w.buf.
|
|
34142
|
+
w.buf = w.buf[:mark]
|
|
33330
34143
|
continue
|
|
33331
34144
|
}
|
|
33332
34145
|
if !w.property(f.name, fv.Interface(), depth+1) {
|
|
33333
|
-
w.buf.
|
|
34146
|
+
w.buf = w.buf[:mark] // undefined values leave the key out
|
|
33334
34147
|
continue
|
|
33335
34148
|
}
|
|
33336
34149
|
}
|
|
@@ -33339,12 +34152,12 @@ func (w *tnJSONWriter) fastStruct(rv reflect.Value, depth int) bool {
|
|
|
33339
34152
|
if wrote {
|
|
33340
34153
|
w.newline(depth)
|
|
33341
34154
|
}
|
|
33342
|
-
w.buf.
|
|
34155
|
+
w.buf = append(w.buf, '}')
|
|
33343
34156
|
return true
|
|
33344
34157
|
}
|
|
33345
34158
|
|
|
33346
34159
|
func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}))) bool {
|
|
33347
|
-
w.buf.
|
|
34160
|
+
w.buf = append(w.buf, '{')
|
|
33348
34161
|
wrote := false
|
|
33349
34162
|
each(func(key string, value interface{}) {
|
|
33350
34163
|
if w.allow != nil && !w.allow[key] {
|
|
@@ -33353,18 +34166,18 @@ func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}
|
|
|
33353
34166
|
if w.replacer != nil {
|
|
33354
34167
|
value = w.replacer(key, value)
|
|
33355
34168
|
}
|
|
33356
|
-
mark := w.buf
|
|
34169
|
+
mark := len(w.buf)
|
|
33357
34170
|
if wrote {
|
|
33358
|
-
w.buf.
|
|
34171
|
+
w.buf = append(w.buf, ',')
|
|
33359
34172
|
}
|
|
33360
34173
|
w.newline(depth + 1)
|
|
33361
|
-
|
|
33362
|
-
w.buf.
|
|
34174
|
+
w.buf = tnJSONAppendQuote(w.buf, key)
|
|
34175
|
+
w.buf = append(w.buf, ':')
|
|
33363
34176
|
if w.indent != "" {
|
|
33364
|
-
w.buf.
|
|
34177
|
+
w.buf = append(w.buf, ' ')
|
|
33365
34178
|
}
|
|
33366
34179
|
if !w.property(key, value, depth+1) {
|
|
33367
|
-
w.buf.
|
|
34180
|
+
w.buf = w.buf[:mark] // undefined values leave the key out
|
|
33368
34181
|
return
|
|
33369
34182
|
}
|
|
33370
34183
|
wrote = true
|
|
@@ -33372,12 +34185,239 @@ func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}
|
|
|
33372
34185
|
if wrote {
|
|
33373
34186
|
w.newline(depth)
|
|
33374
34187
|
}
|
|
33375
|
-
w.buf.
|
|
34188
|
+
w.buf = append(w.buf, '}')
|
|
33376
34189
|
return true
|
|
33377
34190
|
}
|
|
33378
34191
|
|
|
33379
34192
|
// JSON.parse: a SyntaxError for invalid input, as in JS
|
|
33380
34193
|
// Objects decode into ordered records, so their keys keep the text's order
|
|
34194
|
+
func tnFastJSONWS(s string, i int) int {
|
|
34195
|
+
for i < len(s) {
|
|
34196
|
+
c := s[i]
|
|
34197
|
+
if c != ' ' && c != '\\t' && c != '\\n' && c != '\\r' {
|
|
34198
|
+
break
|
|
34199
|
+
}
|
|
34200
|
+
i++
|
|
34201
|
+
}
|
|
34202
|
+
return i
|
|
34203
|
+
}
|
|
34204
|
+
|
|
34205
|
+
func tnFastJSONString(s string, i int) (string, int, bool) {
|
|
34206
|
+
if i >= len(s) || s[i] != '"' {
|
|
34207
|
+
return "", 0, false
|
|
34208
|
+
}
|
|
34209
|
+
i++
|
|
34210
|
+
start := i
|
|
34211
|
+
for i < len(s) {
|
|
34212
|
+
c := s[i]
|
|
34213
|
+
if c == '"' {
|
|
34214
|
+
return s[start:i], i + 1, true
|
|
34215
|
+
}
|
|
34216
|
+
if c == '\\\\' || c < 0x20 || c >= 0x80 {
|
|
34217
|
+
break
|
|
34218
|
+
}
|
|
34219
|
+
i++
|
|
34220
|
+
}
|
|
34221
|
+
if i >= len(s) || s[i] < 0x20 {
|
|
34222
|
+
return "", 0, false
|
|
34223
|
+
}
|
|
34224
|
+
buf := make([]byte, 0, (len(s)-start)+8)
|
|
34225
|
+
buf = append(buf, s[start:i]...)
|
|
34226
|
+
for i < len(s) {
|
|
34227
|
+
c := s[i]
|
|
34228
|
+
if c == '"' {
|
|
34229
|
+
return string(buf), i + 1, true
|
|
34230
|
+
}
|
|
34231
|
+
if c < 0x20 || c >= 0x80 {
|
|
34232
|
+
return "", 0, false
|
|
34233
|
+
}
|
|
34234
|
+
if c != '\\\\' {
|
|
34235
|
+
buf = append(buf, c)
|
|
34236
|
+
i++
|
|
34237
|
+
continue
|
|
34238
|
+
}
|
|
34239
|
+
if i+1 >= len(s) {
|
|
34240
|
+
return "", 0, false
|
|
34241
|
+
}
|
|
34242
|
+
esc := s[i+1]
|
|
34243
|
+
switch esc {
|
|
34244
|
+
case '"', '\\\\', '/':
|
|
34245
|
+
buf = append(buf, esc)
|
|
34246
|
+
case 'b':
|
|
34247
|
+
buf = append(buf, '\\b')
|
|
34248
|
+
case 'f':
|
|
34249
|
+
buf = append(buf, '\\f')
|
|
34250
|
+
case 'n':
|
|
34251
|
+
buf = append(buf, '\\n')
|
|
34252
|
+
case 'r':
|
|
34253
|
+
buf = append(buf, '\\r')
|
|
34254
|
+
case 't':
|
|
34255
|
+
buf = append(buf, '\\t')
|
|
34256
|
+
default:
|
|
34257
|
+
return "", 0, false
|
|
34258
|
+
}
|
|
34259
|
+
i += 2
|
|
34260
|
+
}
|
|
34261
|
+
return "", 0, false
|
|
34262
|
+
}
|
|
34263
|
+
|
|
34264
|
+
func tnFastJSONValue(s string, i int, depth int) (interface{}, int, bool) {
|
|
34265
|
+
if depth > 512 {
|
|
34266
|
+
return nil, 0, false
|
|
34267
|
+
}
|
|
34268
|
+
i = tnFastJSONWS(s, i)
|
|
34269
|
+
if i >= len(s) {
|
|
34270
|
+
return nil, 0, false
|
|
34271
|
+
}
|
|
34272
|
+
switch s[i] {
|
|
34273
|
+
case '{':
|
|
34274
|
+
m := TnNewMap[string, interface{}]()
|
|
34275
|
+
i = tnFastJSONWS(s, i+1)
|
|
34276
|
+
if i < len(s) && s[i] == '}' {
|
|
34277
|
+
return m, i + 1, true
|
|
34278
|
+
}
|
|
34279
|
+
for {
|
|
34280
|
+
k, next, ok := tnFastJSONString(s, i)
|
|
34281
|
+
if !ok {
|
|
34282
|
+
return nil, 0, false
|
|
34283
|
+
}
|
|
34284
|
+
i = tnFastJSONWS(s, next)
|
|
34285
|
+
if i >= len(s) || s[i] != ':' {
|
|
34286
|
+
return nil, 0, false
|
|
34287
|
+
}
|
|
34288
|
+
val, next, ok := tnFastJSONValue(s, i+1, depth+1)
|
|
34289
|
+
if !ok {
|
|
34290
|
+
return nil, 0, false
|
|
34291
|
+
}
|
|
34292
|
+
m.Set(k, val)
|
|
34293
|
+
i = tnFastJSONWS(s, next)
|
|
34294
|
+
if i >= len(s) {
|
|
34295
|
+
return nil, 0, false
|
|
34296
|
+
}
|
|
34297
|
+
if s[i] == '}' {
|
|
34298
|
+
return m, i + 1, true
|
|
34299
|
+
}
|
|
34300
|
+
if s[i] != ',' {
|
|
34301
|
+
return nil, 0, false
|
|
34302
|
+
}
|
|
34303
|
+
i = tnFastJSONWS(s, i+1)
|
|
34304
|
+
if i < len(s) && s[i] == '}' {
|
|
34305
|
+
return nil, 0, false
|
|
34306
|
+
}
|
|
34307
|
+
}
|
|
34308
|
+
case '[':
|
|
34309
|
+
arr := []interface{}{}
|
|
34310
|
+
i = tnFastJSONWS(s, i+1)
|
|
34311
|
+
if i < len(s) && s[i] == ']' {
|
|
34312
|
+
return arr, i + 1, true
|
|
34313
|
+
}
|
|
34314
|
+
for {
|
|
34315
|
+
val, next, ok := tnFastJSONValue(s, i, depth+1)
|
|
34316
|
+
if !ok {
|
|
34317
|
+
return nil, 0, false
|
|
34318
|
+
}
|
|
34319
|
+
arr = append(arr, val)
|
|
34320
|
+
i = tnFastJSONWS(s, next)
|
|
34321
|
+
if i >= len(s) {
|
|
34322
|
+
return nil, 0, false
|
|
34323
|
+
}
|
|
34324
|
+
if s[i] == ']' {
|
|
34325
|
+
return arr, i + 1, true
|
|
34326
|
+
}
|
|
34327
|
+
if s[i] != ',' {
|
|
34328
|
+
return nil, 0, false
|
|
34329
|
+
}
|
|
34330
|
+
i = tnFastJSONWS(s, i+1)
|
|
34331
|
+
if i < len(s) && s[i] == ']' {
|
|
34332
|
+
return nil, 0, false
|
|
34333
|
+
}
|
|
34334
|
+
}
|
|
34335
|
+
case '"':
|
|
34336
|
+
return tnFastJSONString(s, i)
|
|
34337
|
+
case 't':
|
|
34338
|
+
if i+4 <= len(s) && s[i:i+4] == "true" {
|
|
34339
|
+
return true, i + 4, true
|
|
34340
|
+
}
|
|
34341
|
+
return nil, 0, false
|
|
34342
|
+
case 'f':
|
|
34343
|
+
if i+5 <= len(s) && s[i:i+5] == "false" {
|
|
34344
|
+
return false, i + 5, true
|
|
34345
|
+
}
|
|
34346
|
+
return nil, 0, false
|
|
34347
|
+
case 'n':
|
|
34348
|
+
if i+4 <= len(s) && s[i:i+4] == "null" {
|
|
34349
|
+
return TnNull, i + 4, true
|
|
34350
|
+
}
|
|
34351
|
+
return nil, 0, false
|
|
34352
|
+
default:
|
|
34353
|
+
start := i
|
|
34354
|
+
neg := false
|
|
34355
|
+
if s[i] == '-' {
|
|
34356
|
+
neg = true
|
|
34357
|
+
i++
|
|
34358
|
+
if i >= len(s) {
|
|
34359
|
+
return nil, 0, false
|
|
34360
|
+
}
|
|
34361
|
+
}
|
|
34362
|
+
if s[i] == '0' {
|
|
34363
|
+
i++
|
|
34364
|
+
if i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
|
34365
|
+
return nil, 0, false
|
|
34366
|
+
}
|
|
34367
|
+
} else if s[i] >= '1' && s[i] <= '9' {
|
|
34368
|
+
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
|
34369
|
+
i++
|
|
34370
|
+
}
|
|
34371
|
+
} else {
|
|
34372
|
+
return nil, 0, false
|
|
34373
|
+
}
|
|
34374
|
+
isInt := true
|
|
34375
|
+
if i < len(s) && s[i] == '.' {
|
|
34376
|
+
isInt = false
|
|
34377
|
+
i++
|
|
34378
|
+
if i >= len(s) || s[i] < '0' || s[i] > '9' {
|
|
34379
|
+
return nil, 0, false
|
|
34380
|
+
}
|
|
34381
|
+
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
|
34382
|
+
i++
|
|
34383
|
+
}
|
|
34384
|
+
}
|
|
34385
|
+
if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
|
|
34386
|
+
isInt = false
|
|
34387
|
+
i++
|
|
34388
|
+
if i < len(s) && (s[i] == '+' || s[i] == '-') {
|
|
34389
|
+
i++
|
|
34390
|
+
}
|
|
34391
|
+
if i >= len(s) || s[i] < '0' || s[i] > '9' {
|
|
34392
|
+
return nil, 0, false
|
|
34393
|
+
}
|
|
34394
|
+
for i < len(s) && s[i] >= '0' && s[i] <= '9' {
|
|
34395
|
+
i++
|
|
34396
|
+
}
|
|
34397
|
+
}
|
|
34398
|
+
digits := start
|
|
34399
|
+
if neg {
|
|
34400
|
+
digits++
|
|
34401
|
+
}
|
|
34402
|
+
if isInt && i-digits <= 15 {
|
|
34403
|
+
var u uint64
|
|
34404
|
+
for j := digits; j < i; j++ {
|
|
34405
|
+
u = u*10 + uint64(s[j]-'0')
|
|
34406
|
+
}
|
|
34407
|
+
f := float64(u)
|
|
34408
|
+
if neg {
|
|
34409
|
+
f = -f
|
|
34410
|
+
}
|
|
34411
|
+
return f, i, true
|
|
34412
|
+
}
|
|
34413
|
+
f, err := strconv.ParseFloat(s[start:i], 64)
|
|
34414
|
+
if err != nil {
|
|
34415
|
+
return nil, 0, false
|
|
34416
|
+
}
|
|
34417
|
+
return f, i, true
|
|
34418
|
+
}
|
|
34419
|
+
}
|
|
34420
|
+
|
|
33381
34421
|
func tnJSONDecodeOrdered(dec *json.Decoder) (interface{}, error) {
|
|
33382
34422
|
tok, err := dec.Token()
|
|
33383
34423
|
if err != nil {
|
|
@@ -33420,6 +34460,9 @@ func tnJSONDecodeOrdered(dec *json.Decoder) (interface{}, error) {
|
|
|
33420
34460
|
}
|
|
33421
34461
|
|
|
33422
34462
|
func TnJSONParse(text string) interface{} {
|
|
34463
|
+
if v, end, ok := tnFastJSONValue(text, 0, 0); ok && tnFastJSONWS(text, end) == len(text) {
|
|
34464
|
+
return v
|
|
34465
|
+
}
|
|
33423
34466
|
dec := json.NewDecoder(strings.NewReader(text))
|
|
33424
34467
|
if ordered, err := tnJSONDecodeOrdered(dec); err == nil {
|
|
33425
34468
|
if _, extra := dec.Token(); extra == io.EOF {
|
|
@@ -33797,6 +34840,25 @@ func (m *TnMap[K, V]) TnProp(key string) (interface{}, bool) {
|
|
|
33797
34840
|
return v, present
|
|
33798
34841
|
}
|
|
33799
34842
|
|
|
34843
|
+
// obj[key] = value on a record held in a dynamic value (a plain object
|
|
34844
|
+
// literal, {}): the key set without reflection, as tnSetMember's Set call
|
|
34845
|
+
// would. False when the key or value isn't already of the map's types (the
|
|
34846
|
+
// reflective path converts those)
|
|
34847
|
+
func (m *TnMap[K, V]) TnSetProp(key string, value interface{}) bool {
|
|
34848
|
+
k, ok := any(key).(K)
|
|
34849
|
+
if !ok || m == nil {
|
|
34850
|
+
return false
|
|
34851
|
+
}
|
|
34852
|
+
var v V
|
|
34853
|
+
if value != nil {
|
|
34854
|
+
if v, ok = value.(V); !ok {
|
|
34855
|
+
return false
|
|
34856
|
+
}
|
|
34857
|
+
}
|
|
34858
|
+
m.Set(k, v)
|
|
34859
|
+
return true
|
|
34860
|
+
}
|
|
34861
|
+
|
|
33800
34862
|
func (m *TnMap[K, V]) Lookup(k K) (V, bool) {
|
|
33801
34863
|
if m == nil {
|
|
33802
34864
|
var zero V
|
|
@@ -34546,6 +35608,8 @@ func TnRegexWrapReplaceFirst(r *TnRegex, s string, repl string) string {
|
|
|
34546
35608
|
|
|
34547
35609
|
func TnRegexReplaceFuncW(r *TnRegex, s string, fn func([]string, int) string, all bool) string {
|
|
34548
35610
|
var out strings.Builder
|
|
35611
|
+
// (a replacement keeps the length roughly: grow once, not by doubling)
|
|
35612
|
+
out.Grow(len(s))
|
|
34549
35613
|
last := 0
|
|
34550
35614
|
ascii := tnStrASCII(s)
|
|
34551
35615
|
r.scan(s, true, func(groups []string, lo int, hi int) bool {
|
|
@@ -34567,6 +35631,7 @@ func TnRegexReplaceFuncW(r *TnRegex, s string, fn func([]string, int) string, al
|
|
|
34567
35631
|
|
|
34568
35632
|
func (r *TnRegex) replace(s string, repl string, all bool) string {
|
|
34569
35633
|
var out strings.Builder
|
|
35634
|
+
out.Grow(len(s) + max(0, len(repl)-1))
|
|
34570
35635
|
last := 0
|
|
34571
35636
|
plain := strings.IndexByte(repl, '$') < 0
|
|
34572
35637
|
r.scan(s, !plain, func(groups []string, lo int, hi int) bool {
|
|
@@ -36036,6 +37101,7 @@ func TnTimeNow() time.Time {
|
|
|
36036
37101
|
// as tasks. Refs (pending timers, async work, open handles) keep it alive.
|
|
36037
37102
|
var tnLoopMu sync.Mutex
|
|
36038
37103
|
var tnLoopTasks []func()
|
|
37104
|
+
var tnHasLoopTasks int32
|
|
36039
37105
|
var tnLoopSignal = make(chan struct{}, 1)
|
|
36040
37106
|
var tnLoopRefs int64
|
|
36041
37107
|
|
|
@@ -36115,13 +37181,15 @@ func tnLoopNotify() {
|
|
|
36115
37181
|
func TnLoopRef() { atomic.AddInt64(&tnLoopRefs, 1) }
|
|
36116
37182
|
|
|
36117
37183
|
func TnLoopUnref() {
|
|
36118
|
-
atomic.AddInt64(&tnLoopRefs, -1)
|
|
36119
|
-
|
|
37184
|
+
if atomic.AddInt64(&tnLoopRefs, -1) <= 0 {
|
|
37185
|
+
tnLoopNotify()
|
|
37186
|
+
}
|
|
36120
37187
|
}
|
|
36121
37188
|
|
|
36122
37189
|
func TnLoopPost(fn func()) {
|
|
36123
37190
|
tnLoopMu.Lock()
|
|
36124
37191
|
tnLoopTasks = append(tnLoopTasks, fn)
|
|
37192
|
+
atomic.StoreInt32(&tnHasLoopTasks, 1)
|
|
36125
37193
|
tnLoopMu.Unlock()
|
|
36126
37194
|
tnLoopNotify()
|
|
36127
37195
|
}
|
|
@@ -36139,6 +37207,7 @@ func tnLoopRunOrPost(fn func()) {
|
|
|
36139
37207
|
}
|
|
36140
37208
|
tnLoopMu.Lock()
|
|
36141
37209
|
tnLoopTasks = append(tnLoopTasks, fn)
|
|
37210
|
+
atomic.StoreInt32(&tnHasLoopTasks, 1)
|
|
36142
37211
|
tnLoopMu.Unlock()
|
|
36143
37212
|
defer func() {
|
|
36144
37213
|
if r := recover(); r != nil {
|
|
@@ -36151,6 +37220,22 @@ func tnLoopRunOrPost(fn func()) {
|
|
|
36151
37220
|
tnRelease()
|
|
36152
37221
|
}
|
|
36153
37222
|
|
|
37223
|
+
func tnLoopRun(fn func()) {
|
|
37224
|
+
<-tnBaton
|
|
37225
|
+
defer func() {
|
|
37226
|
+
if r := recover(); r != nil {
|
|
37227
|
+
go func() { panic(r) }()
|
|
37228
|
+
select {}
|
|
37229
|
+
}
|
|
37230
|
+
}()
|
|
37231
|
+
TnRunMicrotasks()
|
|
37232
|
+
TnLoopRunPending()
|
|
37233
|
+
tnRunTask(fn)
|
|
37234
|
+
TnRunMicrotasks()
|
|
37235
|
+
TnLoopRunPending()
|
|
37236
|
+
tnRelease()
|
|
37237
|
+
}
|
|
37238
|
+
|
|
36154
37239
|
// Runs a callback on the loop from a goroutine that does not hold the baton,
|
|
36155
37240
|
// and waits for it
|
|
36156
37241
|
func TnLoopCall(fn func()) {
|
|
@@ -36164,19 +37249,31 @@ func TnLoopCall(fn func()) {
|
|
|
36164
37249
|
|
|
36165
37250
|
// (baton holder) Runs the queued tasks, each followed by its microtasks
|
|
36166
37251
|
func TnLoopRunPending() bool {
|
|
37252
|
+
if atomic.LoadInt32(&tnHasLoopTasks) == 0 {
|
|
37253
|
+
return false
|
|
37254
|
+
}
|
|
36167
37255
|
ran := false
|
|
36168
37256
|
for {
|
|
36169
37257
|
tnLoopMu.Lock()
|
|
36170
37258
|
if len(tnLoopTasks) == 0 {
|
|
37259
|
+
atomic.StoreInt32(&tnHasLoopTasks, 0)
|
|
36171
37260
|
tnLoopMu.Unlock()
|
|
36172
37261
|
return ran
|
|
36173
37262
|
}
|
|
36174
37263
|
fn := tnLoopTasks[0]
|
|
37264
|
+
tnLoopTasks[0] = nil
|
|
36175
37265
|
tnLoopTasks = tnLoopTasks[1:]
|
|
37266
|
+
if len(tnLoopTasks) == 0 {
|
|
37267
|
+
tnLoopTasks = tnLoopTasks[:0]
|
|
37268
|
+
atomic.StoreInt32(&tnHasLoopTasks, 0)
|
|
37269
|
+
}
|
|
36176
37270
|
tnLoopMu.Unlock()
|
|
36177
37271
|
ran = true
|
|
36178
37272
|
tnRunTask(fn)
|
|
36179
37273
|
TnRunMicrotasks()
|
|
37274
|
+
if atomic.LoadInt32(&tnHasLoopTasks) == 0 {
|
|
37275
|
+
return true
|
|
37276
|
+
}
|
|
36180
37277
|
}
|
|
36181
37278
|
}
|
|
36182
37279
|
|
|
@@ -36281,6 +37378,7 @@ func tnWakeQueue(tok chan struct{}) {
|
|
|
36281
37378
|
}
|
|
36282
37379
|
tnMicrotasksMu.Lock()
|
|
36283
37380
|
tnMicrotasks = append(tnMicrotasks, func() { tnDeliver(tok) })
|
|
37381
|
+
atomic.StoreInt32(&tnHasMicrotasks, 1)
|
|
36284
37382
|
tnMicrotasksMu.Unlock()
|
|
36285
37383
|
tnLoopNotify()
|
|
36286
37384
|
}
|
|
@@ -36422,25 +37520,39 @@ func (tnLoopGroup) Wait() { TnRunLoop() }
|
|
|
36422
37520
|
// queueMicrotask: run after the current synchronous code (end of main or of a loop task)
|
|
36423
37521
|
var tnMicrotasks []func()
|
|
36424
37522
|
var tnMicrotasksMu sync.Mutex
|
|
37523
|
+
var tnHasMicrotasks int32
|
|
36425
37524
|
|
|
36426
37525
|
func TnQueueMicrotask(fn func()) {
|
|
36427
37526
|
fn = TnAsyncWrap(fn)
|
|
36428
37527
|
tnMicrotasksMu.Lock()
|
|
36429
37528
|
tnMicrotasks = append(tnMicrotasks, fn)
|
|
37529
|
+
atomic.StoreInt32(&tnHasMicrotasks, 1)
|
|
36430
37530
|
tnMicrotasksMu.Unlock()
|
|
36431
37531
|
}
|
|
36432
37532
|
|
|
36433
37533
|
func TnRunMicrotasks() {
|
|
37534
|
+
if atomic.LoadInt32(&tnHasMicrotasks) == 0 {
|
|
37535
|
+
return
|
|
37536
|
+
}
|
|
36434
37537
|
for {
|
|
36435
37538
|
tnMicrotasksMu.Lock()
|
|
36436
37539
|
if len(tnMicrotasks) == 0 {
|
|
37540
|
+
atomic.StoreInt32(&tnHasMicrotasks, 0)
|
|
36437
37541
|
tnMicrotasksMu.Unlock()
|
|
36438
37542
|
return
|
|
36439
37543
|
}
|
|
36440
37544
|
fn := tnMicrotasks[0]
|
|
37545
|
+
tnMicrotasks[0] = nil
|
|
36441
37546
|
tnMicrotasks = tnMicrotasks[1:]
|
|
37547
|
+
if len(tnMicrotasks) == 0 {
|
|
37548
|
+
tnMicrotasks = tnMicrotasks[:0]
|
|
37549
|
+
atomic.StoreInt32(&tnHasMicrotasks, 0)
|
|
37550
|
+
}
|
|
36442
37551
|
tnMicrotasksMu.Unlock()
|
|
36443
37552
|
TnAsyncRun(nil, fn)
|
|
37553
|
+
if atomic.LoadInt32(&tnHasMicrotasks) == 0 {
|
|
37554
|
+
return
|
|
37555
|
+
}
|
|
36444
37556
|
}
|
|
36445
37557
|
}`,
|
|
36446
37558
|
uri: `// encodeURIComponent: escapes everything except A-Z a-z 0-9 - _ . ! ~ * ' ( )
|
|
@@ -37233,6 +38345,48 @@ func TnStrAppend(s, part string) string {
|
|
|
37233
38345
|
return unsafe.String(&buf[0], n)
|
|
37234
38346
|
}`,
|
|
37235
38347
|
};
|
|
38348
|
+
// tnCallValueTyped: a case per Go func type this program builds, converting
|
|
38349
|
+
// the dynamic call's arguments and calling it — the same work TnCallValue's
|
|
38350
|
+
// reflective path does, without reflect.Value.Call (which is most of a
|
|
38351
|
+
// dynamic call's cost). Shapes TnCallValue's own switch covers stay there.
|
|
38352
|
+
function emitTypedDynamicCalls() {
|
|
38353
|
+
const cases = [];
|
|
38354
|
+
// (aliases of a primitive are the primitive's type: one case for both)
|
|
38355
|
+
const types = new Set();
|
|
38356
|
+
for (const raw of dynamicFuncTypes) {
|
|
38357
|
+
let t = raw;
|
|
38358
|
+
for (const [name, base] of primitiveEnumGoTypes) {
|
|
38359
|
+
t = t.replace(new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g'), base);
|
|
38360
|
+
}
|
|
38361
|
+
types.add(t);
|
|
38362
|
+
}
|
|
38363
|
+
for (const fnType of [...types].sort()) {
|
|
38364
|
+
if (!fnType.startsWith('func('))
|
|
38365
|
+
continue;
|
|
38366
|
+
const result = goFuncReturnType(fnType);
|
|
38367
|
+
const params = goFuncParamTypes(fnType);
|
|
38368
|
+
const variadic = params.length > 0 && params[params.length - 1].startsWith('...');
|
|
38369
|
+
const fixed = variadic ? params.length - 1 : params.length;
|
|
38370
|
+
const argExprs = params.slice(0, fixed).map((p, i) => `tnCoerceArg[${p}](TnArg(args, ${i}))`);
|
|
38371
|
+
if (variadic) {
|
|
38372
|
+
const elem = params[params.length - 1].slice(3);
|
|
38373
|
+
argExprs.push(`tnCoerceArgs[${elem}](args, ${fixed})...`);
|
|
38374
|
+
}
|
|
38375
|
+
const call = `f(${argExprs.join(', ')})`;
|
|
38376
|
+
const results = result ? splitGoParameters(result) : [];
|
|
38377
|
+
let body;
|
|
38378
|
+
if (results.length === 0)
|
|
38379
|
+
body = `${call}; return nil, true`;
|
|
38380
|
+
else if (results.length === 1)
|
|
38381
|
+
body = `return ${call}, true`;
|
|
38382
|
+
else
|
|
38383
|
+
body = `${results.map((_, i) => (i === 0 ? '__r0' : '_')).join(', ')} := ${call}; return __r0, true`;
|
|
38384
|
+
cases.push(`\tcase ${fnType}:\n\t\t${body}`);
|
|
38385
|
+
}
|
|
38386
|
+
if (cases.length === 0)
|
|
38387
|
+
return 'func tnCallValueTyped(fn interface{}, args []interface{}) (interface{}, bool) {\n\treturn nil, false\n}';
|
|
38388
|
+
return `// Dynamic calls of the program's own function types, without reflection\nfunc tnCallValueTyped(fn interface{}, args []interface{}) (interface{}, bool) {\n\tswitch f := fn.(type) {\n${cases.join('\n')}\n\t}\n\treturn nil, false\n}`;
|
|
38389
|
+
}
|
|
37236
38390
|
// Returns the Go source for all helpers used in this transpilation, or '' if none.
|
|
37237
38391
|
// Emitted only into the main output file: every generated file shares `package main`,
|
|
37238
38392
|
// so helpers are visible across files and must not be duplicated.
|
|
@@ -37241,6 +38395,8 @@ function emitGoHelpers() {
|
|
|
37241
38395
|
.sort()
|
|
37242
38396
|
.map((id) => goHelpers[id] ?? nodeRegistry.goHelpers[id])
|
|
37243
38397
|
.filter(Boolean);
|
|
38398
|
+
if (usedHelpers.has('dynamic'))
|
|
38399
|
+
sources.push(emitTypedDynamicCalls());
|
|
37244
38400
|
if (usedHelpers.has('nodeUtil')) {
|
|
37245
38401
|
const names = [...classNames].sort().map((name) => `${toGoStringLiteral(getSafeName(name))}: true`);
|
|
37246
38402
|
sources.push(`// Classes util.inspect prints as \`Name { … }\`\nvar tnInspectClassNames = map[string]bool{${names.join(', ')}}`);
|