typenative 0.6.0 → 0.6.2

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/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
- const className = node.expression.kind === 'ThisKeyword'
4638
- ? getEnclosingClassName(node)
4639
- : leftGoType
4640
- ? leftGoType.slice(1).replace(/\[.*\]$/, '')
4641
- : undefined;
4822
+ // (a plain function's this typed as a class: its getters too)
4823
+ const typedClass = leftGoType?.startsWith('*') ? leftGoType.slice(1).replace(/\[.*\]$/, '') : undefined;
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 (!isPropertyAssignment(node.parent)) {
6795
- const prologue = thisPrologue(node);
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
- return `func() ${goType} { __v := ${visit(expr)}; if __v == nil { return nil }; return &__v }()`;
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
- return `func() ${goType} { __v := ${boxedRead()}; if __v == nil { return nil }; return &__v }()`;
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
- return `func() ${goType} { if __v, __ok := ${lookup.map}.Lookup(${lookup.key}); __ok { return &__v }; return nil }()`;
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): converted field by field (a copy)
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
- return `TnAs[${goType}](interface{}(${code}))`;
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
- return truthinessCheck(visit(expr, { inline: true }), inferExpressionType(expr));
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;
@@ -21046,6 +21500,31 @@ function visitRegexReplace(node) {
21046
21500
  // (an expression read twice must be pure: a name, fields, a Record lookup)
21047
21501
  else if (reIsWrapper && /^[\w.]+(\.Get\("[^"\\]*"\))?[\w.]*$/.test(re))
21048
21502
  isGlobal = `${re}.global`;
21503
+ else if (reIsWrapper) {
21504
+ // new RegExp(p, 'g…') written out: its flags are known here
21505
+ const flags = newRegExpLiteralFlags(pattern);
21506
+ if (flags !== undefined)
21507
+ isGlobal = flags.includes('g') ? 'true' : 'false';
21508
+ // any other RegExp (a call's result, new RegExp(p, flags)): evaluated
21509
+ // once, its g flag tested at run time
21510
+ else
21511
+ return `func() string { __rx := ${re}; return ${emitRegexReplace(pattern, replacement, target, reIsWrapper, '__rx', '__rx.global')} }()`;
21512
+ }
21513
+ return emitRegexReplace(pattern, replacement, target, reIsWrapper, re, isGlobal);
21514
+ }
21515
+ // The flags of new RegExp(p) / new RegExp(p, 'literal flags'); undefined for
21516
+ // any other expression or flags computed at run time
21517
+ function newRegExpLiteralFlags(node) {
21518
+ const expr = unwrapParentheses(node);
21519
+ if (!isNewExpression(expr) || !isIdentifier(expr.expression) || expr.expression.text !== 'RegExp')
21520
+ return undefined;
21521
+ const args = expr.arguments ?? [];
21522
+ if (args.length < 2)
21523
+ return args.length === 1 && isRegularExpressionLiteral(unwrapParentheses(args[0])) ? undefined : '';
21524
+ const flags = unwrapParentheses(args[1]);
21525
+ return isStringLiteral(flags) || isNoSubstitutionTemplateLiteral(flags) ? flags.text : undefined;
21526
+ }
21527
+ function emitRegexReplace(pattern, replacement, target, reIsWrapper, re, isGlobal) {
21049
21528
  importedPackages.add('regexp');
21050
21529
  if (isArrowFunction(replacement) || isFunctionExpression(replacement)) {
21051
21530
  useHelper('regexReplaceFunc');
@@ -21380,7 +21859,17 @@ function isDescriptorMethod(n) {
21380
21859
  // A plain function's this: its `this: T` annotation's Go type, else any
21381
21860
  function plainFunctionThisType(fn) {
21382
21861
  const declared = fn.tnThisType ? getType(fn.tnThisType) : '';
21383
- return declared && declared !== ':' && declared.startsWith('*') ? declared : 'interface{}';
21862
+ if (declared && declared !== ':' && declared.startsWith('*'))
21863
+ return declared;
21864
+ // (a class's name that a type alias also uses — Babel's NodePath_Final<T>,
21865
+ // a default import of its class: `this: NodePath` is the class's instances)
21866
+ const typeNode = fn.tnThisType;
21867
+ if (typeNode?.kind === 'TypeReference' && isIdentifier(typeNode.typeName)) {
21868
+ const name = typeNode.typeName.text;
21869
+ if (classNames.has(name) && !isPolymorphicClass(name) && !isTypeParameterInScope(name, typeNode))
21870
+ return `*${name}`;
21871
+ }
21872
+ return 'interface{}';
21384
21873
  }
21385
21874
  // A plain function using its own this reads it once, on entry, into __this
21386
21875
  // (the value its caller set, TnThis): arrows in it keep seeing that one
@@ -21494,13 +21983,35 @@ function goFuncParamTypes(funcType) {
21494
21983
  funcType = funcType.trim();
21495
21984
  const result = goFuncReturnType(funcType);
21496
21985
  const paramList = funcType.slice(5, funcType.length - (result ? result.length + 1 : 0) - 1).trim();
21497
- return splitGoParameters(paramList).map((p) => {
21498
- const space = p.indexOf(' ');
21499
- const first = space > 0 ? p.slice(0, space) : p;
21500
- // (ǂ stands for $ and _ in names: see goIdentifierChars)
21501
- const isName = space > 0 && !['chan', 'func', 'map', 'struct', 'interface'].includes(first) && /^[A-Za-z_ǂ][\wǂ]*$/.test(first);
21502
- return isName ? p.slice(space + 1) : p;
21503
- });
21986
+ return splitGoParameters(paramList).map(goParameterType);
21987
+ }
21988
+ // A Go parameter declaration without its name ('__this interface{}' → 'interface{}')
21989
+ function goParameterType(p) {
21990
+ const space = p.indexOf(' ');
21991
+ const first = space > 0 ? p.slice(0, space) : p;
21992
+ // (ǂ stands for $ and _ in names: see goIdentifierChars)
21993
+ const isName = space > 0 && !['chan', 'func', 'map', 'struct', 'interface'].includes(first) && /^[A-Za-z_ǂ][\wǂ]*$/.test(first);
21994
+ return isName ? p.slice(space + 1) : p;
21995
+ }
21996
+ // The Go func type of a function emitted with this parameter signature and
21997
+ // result ('a int, b string', ' bool' → 'func(int, string) bool')
21998
+ function emittedFuncGoType(signature, returnType) {
21999
+ const params = splitGoParameters(signature).map(goParameterType).join(', ');
22000
+ return `func(${params})${returnType}`.replace(/\bany\b/g, 'interface{}');
22001
+ }
22002
+ // A function value of this Go type may be called dynamically: tnCallValueTyped
22003
+ // gets a case for it, so the call needs no reflect.Value.Call
22004
+ function registerFunctionGoType(funcType) {
22005
+ if (!funcType.startsWith('func(') || funcType.startsWith('func['))
22006
+ return;
22007
+ // (one spelling per Go type: spacing and `any` do not change it)
22008
+ const normalized = funcType.replace(/\bany\b/g, 'interface{}').replace(/\s+/g, ' ').replace(/interface \{\}/g, 'interface{}');
22009
+ // (a local or generic type has no package-level Go type to name)
22010
+ for (const match of normalized.matchAll(/[A-Za-z_ǂ][\wǂ]*/g)) {
22011
+ if (localGoTypes.has(match[0]) || genericGoParams.has(match[0]))
22012
+ return;
22013
+ }
22014
+ dynamicFuncTypes.add(normalized);
21504
22015
  }
21505
22016
  // f.call(thisArg, a, b) → f(a, b); f.apply(thisArg, args) → f(args[0], args[1], …);
21506
22017
  // f.bind(thisArg, a) → a closure over the bound arguments (this is TnThis)
@@ -21946,7 +22457,7 @@ function collectClassImplementedInterfaces() {
21946
22457
  // member of a class TypeScript narrowed it to — called / read by name
21947
22458
  // (this counts in plain functions, whose this may be any instance)
21948
22459
  function isUndeclaredClassMember(access) {
21949
- if (!isPropertyAccessExpression(access) || hasQuestionDot(access) || access.name?.kind === 'PrivateIdentifier')
22460
+ if (!isPropertyAccessExpression(access) || access.name?.kind === 'PrivateIdentifier')
21950
22461
  return false;
21951
22462
  // (this.isScope() in a class whose prototype gets methods assigned —
21952
22463
  // Object.assign(NodePath.prototype, validators) —: called by name)
@@ -21957,7 +22468,27 @@ function isUndeclaredClassMember(access) {
21957
22468
  if (access.expression.kind === 'SuperKeyword')
21958
22469
  return false;
21959
22470
  const receiverType = inferExpressionType(access.expression) ?? '';
21960
- return receiverType.startsWith('*') && classNames.has(receiverType.slice(1)) && !classHasMember(receiverType.slice(1), memberKey(access.name) ?? '');
22471
+ const className = receiverType.startsWith('*') ? receiverType.slice(1).replace(/\[.*\]$/, '') : '';
22472
+ const member = memberKey(access.name) ?? '';
22473
+ if (!className || !classNames.has(className))
22474
+ return false;
22475
+ if (!classHasMember(className, member))
22476
+ return true;
22477
+ // (set-only: a read is undefined, and the Go struct has only Set_x)
22478
+ return !isCallee(access) && !!classMember(className, 'set', member) && !classMember(className, 'get', member) && !classHasDataField(className, member);
22479
+ }
22480
+ // Whether a class declares a data field (or parameter property) of the name
22481
+ function classHasDataField(className, member) {
22482
+ for (let name = className, depth = 0; name && depth < 20; name = classParentNames.get(name), depth++) {
22483
+ const declaration = declaredClasses.get(name);
22484
+ if (!declaration)
22485
+ return false;
22486
+ if ((declaration.members ?? []).some((m) => isPropertyDeclaration(m) && !hasModifier(m, 'StaticKeyword') && memberKey(m.name) === member))
22487
+ return true;
22488
+ if (getParameterProperties(declaration).some((p) => p.name?.text === member))
22489
+ return true;
22490
+ }
22491
+ return false;
21961
22492
  }
21962
22493
  // x.f on an object type (an interface's struct) that has no f — Babel's
21963
22494
  // generator reads node.handlers under @ts-expect-error —: read by name
@@ -26639,7 +27170,7 @@ const helperPackages = {
26639
27170
  regexEngine: ['strings', 'fmt', 'strconv', 'sync', 'sync/atomic', 'unicode', 'unicode/utf8'],
26640
27171
  namedGroups: ['regexp', 'unicode/utf8'],
26641
27172
  regexMatch: ['regexp', 'math', 'strconv', 'unsafe', 'unicode/utf8'],
26642
- strIndex: ['unicode/utf8', 'sync/atomic', 'unsafe', 'math', 'strings', 'sort'],
27173
+ strIndex: ['unicode/utf8', 'sync', 'sync/atomic', 'unsafe', 'math', 'strings', 'sort'],
26643
27174
  jsReplacement: ['strings'],
26644
27175
  moduleUrl: ['os'],
26645
27176
  asyncWait: [],
@@ -26668,6 +27199,31 @@ const helperPackages = {
26668
27199
  // Field names are intentionally lowercase: every generated file is `package main`,
26669
27200
  // so `result.stdout` in emitted code resolves to the struct field directly.
26670
27201
  const goHelpers = {
27202
+ arrayPush: `// append with geometric (2x) growth: Go grows a large slice by 1.25x, so the
27203
+ // repeated copies when a list is built by pushes add up to about five times
27204
+ // its final memory
27205
+ func TnPush[T any](s []T, v T) []T {
27206
+ if len(s) == cap(s) {
27207
+ n := len(s) * 2
27208
+ if n < 16 {
27209
+ n = 16
27210
+ }
27211
+ ns := make([]T, len(s), n)
27212
+ copy(ns, s)
27213
+ s = ns
27214
+ }
27215
+ return append(s, v)
27216
+ }`,
27217
+ slicePtr: `// A *[]T slot from a slice: nil stays nil (no match, undefined), and the box
27218
+ // is allocated only for a value, not for every call a local &v would cost
27219
+ func TnSlicePtr[T any](v []T) *[]T {
27220
+ if v == nil {
27221
+ return nil
27222
+ }
27223
+ p := new([]T)
27224
+ *p = v
27225
+ return p
27226
+ }`,
26671
27227
  generatorSeq: `// A generator's push form (a range function) yielding T: the same function
26672
27228
  // when it yields T already, else each value converted
26673
27229
  func tnSeqAs[T any, S any](s func(func(S) bool)) func(func(T) bool) {
@@ -28770,6 +29326,33 @@ func tnCallCollection(obj interface{}, isSet bool, name string, args []interface
28770
29326
  return nil, false
28771
29327
  }
28772
29328
 
29329
+ // A dynamic call's argument as a parameter's Go type (undefined / null is the
29330
+ // zero value, a value of another type is converted as tnConvertTo does)
29331
+ func tnCoerceArg[T any](v interface{}) T {
29332
+ if x, ok := v.(T); ok {
29333
+ return x
29334
+ }
29335
+ var zero T
29336
+ if v == nil {
29337
+ return zero
29338
+ }
29339
+ if rv, ok := TnConvertDynamic(v, reflect.TypeFor[T]()); ok && rv.IsValid() {
29340
+ if x, ok := rv.Interface().(T); ok {
29341
+ return x
29342
+ }
29343
+ }
29344
+ return zero
29345
+ }
29346
+
29347
+ // A variadic parameter's values from a dynamic call's arguments
29348
+ func tnCoerceArgs[T any](args []interface{}, from int) []T {
29349
+ var out []T
29350
+ for ; from < len(args); from++ {
29351
+ out = append(out, tnCoerceArg[T](args[from]))
29352
+ }
29353
+ return out
29354
+ }
29355
+
28773
29356
  // Calls a function value held as any, converting the arguments to its
28774
29357
  // parameter types; its result (or nil)
28775
29358
  func TnCallValue(fn interface{}, args ...interface{}) interface{} {
@@ -28810,6 +29393,10 @@ func TnCallValue(fn interface{}, args ...interface{}) interface{} {
28810
29393
  case func(interface{}, interface{}) bool:
28811
29394
  return f(TnArg(args, 0), TnArg(args, 1))
28812
29395
  }
29396
+ // (the program's own function types: called without reflect)
29397
+ if v, ok := tnCallValueTyped(fn, args); ok {
29398
+ return v
29399
+ }
28813
29400
  fv := reflect.ValueOf(fn)
28814
29401
  if fv.Kind() != reflect.Func {
28815
29402
  panic(TnNodeError("TypeError", "", "value is not a function"))
@@ -28993,6 +29580,12 @@ func TnSet(obj interface{}, key string, value interface{}) {
28993
29580
  }
28994
29581
  return
28995
29582
  }
29583
+ // (a record — a TnMap held as any, such as a {} literal: its key, as
29584
+ // tnSetMember's Set call stores it, without reflection)
29585
+ if r, ok := obj.(interface{ TnSetProp(string, interface{}) bool }); ok && r.TnSetProp(key, value) {
29586
+ tnExpandoDelete(obj, key)
29587
+ return
29588
+ }
28996
29589
  if obj != nil {
28997
29590
  if p := tnPlanOf(obj, key); p.kind != tnFieldSlow && !p.setter {
28998
29591
  if base := (*[2]unsafe.Pointer)(unsafe.Pointer(&obj))[1]; base != nil {
@@ -30673,6 +31266,90 @@ func tnConvIdentityOf(src unsafe.Pointer, dst reflect.Type, srcSize uintptr) (re
30673
31266
  return entry.out, ok
30674
31267
  }
30675
31268
 
31269
+ // The objects struct conversions (tnConvPlan.convert) made, by source object
31270
+ // and target type. An entry holds its source, so the address names no other
31271
+ // object while the entry lives, and its converted object weakly: once nothing
31272
+ // else holds that object, a new one can't be told from it. (One weak pointer
31273
+ // per conversion, no cleanup or finalizer: those made every conversion of a
31274
+ // short-lived object cost a few garbage-collector specials.) Entries whose
31275
+ // object was collected go in a sweep, run when the index has doubled since
31276
+ // the last one.
31277
+ type tnStructIdentityKey struct {
31278
+ src uintptr
31279
+ dst unsafe.Pointer // (the target type's descriptor)
31280
+ }
31281
+
31282
+ type tnStructIdentity struct {
31283
+ src unsafe.Pointer
31284
+ out weak.Pointer[byte]
31285
+ }
31286
+
31287
+ var tnStructIdentities = map[tnStructIdentityKey]tnStructIdentity{}
31288
+ var tnStructIdentityMu sync.Mutex
31289
+ var tnStructIdentitySweepAt = 1 << 12
31290
+
31291
+ // The entries found or made last, by a hash of their key: an object
31292
+ // converted again and again (an options object read per node) skips the
31293
+ // index. A slot holds its object, so its key's entry in the index stays the
31294
+ // one it names (an entry is only replaced once its object is gone): at most
31295
+ // one object per slot is kept alive this way
31296
+ var tnStructIdentityRecent [1 << 8]struct {
31297
+ key tnStructIdentityKey
31298
+ out unsafe.Pointer
31299
+ }
31300
+
31301
+ // The converted object for src as a dst (memory of dst's type): the one made
31302
+ // before (cached true), else a new one remembered for src
31303
+ func tnStructIdentityOf(src unsafe.Pointer, dst reflect.Type, srcSize uintptr) (unsafe.Pointer, bool) {
31304
+ if srcSize == 0 || src == nil || dst.Size() == 0 {
31305
+ return reflect.New(dst).UnsafePointer(), false
31306
+ }
31307
+ key := tnStructIdentityKey{uintptr(src), (*[2]unsafe.Pointer)(unsafe.Pointer(&dst))[1]}
31308
+ slot := &tnStructIdentityRecent[((key.src>>4)^(uintptr(key.dst)>>5))*0x9E3779B1>>16&(1<<8-1)]
31309
+ tnStructIdentityMu.Lock()
31310
+ if slot.key == key && slot.out != nil {
31311
+ out := slot.out
31312
+ tnStructIdentityMu.Unlock()
31313
+ return out, true
31314
+ }
31315
+ if e, ok := tnStructIdentities[key]; ok {
31316
+ if out := e.out.Value(); out != nil {
31317
+ slot.key, slot.out = key, unsafe.Pointer(out)
31318
+ tnStructIdentityMu.Unlock()
31319
+ return unsafe.Pointer(out), true
31320
+ }
31321
+ }
31322
+ if len(tnStructIdentities) >= tnStructIdentitySweepAt {
31323
+ for k, e := range tnStructIdentities {
31324
+ if e.out.Value() == nil {
31325
+ delete(tnStructIdentities, k)
31326
+ }
31327
+ }
31328
+ tnStructIdentitySweepAt = max(1<<12, 2*len(tnStructIdentities))
31329
+ }
31330
+ out := reflect.New(dst).UnsafePointer()
31331
+ e := tnStructIdentity{src: src, out: weak.Make((*byte)(out))}
31332
+ tnStructIdentities[key] = e
31333
+ slot.key, slot.out = key, out
31334
+ tnStructIdentityMu.Unlock()
31335
+ return out, false
31336
+ }
31337
+
31338
+ // TnAs for a conversion the compiler knows is the only one its source object
31339
+ // ever gets (see unsharedConversionSource): a fresh object that nothing else
31340
+ // holds, converted once, needs no identity entry — a plain copy
31341
+ func TnAsCopy[T any](v interface{}) T {
31342
+ if t, ok := v.(T); ok {
31343
+ return t
31344
+ }
31345
+ if v != nil {
31346
+ if p := tnConvPlanOf(v, reflect.TypeOf((*T)(nil)).Elem()); p.ok && (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1] != nil {
31347
+ return p.convertTo(v, false).Interface().(T)
31348
+ }
31349
+ }
31350
+ return TnAs[T](v)
31351
+ }
31352
+
30676
31353
  var tnConvPlans [1 << 10]atomic.Pointer[tnConvPlan]
30677
31354
  var tnConvPlanIndex = map[[2]unsafe.Pointer]*tnConvPlan{}
30678
31355
  var tnConvPlanMu sync.RWMutex
@@ -30759,6 +31436,11 @@ func tnMakeConvPlan(v interface{}, t reflect.Type, from unsafe.Pointer, to unsaf
30759
31436
 
30760
31437
  // v (a non-nil pointer to a struct) as a new value of the plan's target type
30761
31438
  func (p *tnConvPlan) convert(v interface{}) reflect.Value {
31439
+ return p.convertTo(v, true)
31440
+ }
31441
+
31442
+ // (identity false: a copy no other conversion will look for — TnAsCopy)
31443
+ func (p *tnConvPlan) convertTo(v interface{}, identity bool) reflect.Value {
30762
31444
  src := (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1]
30763
31445
  if p.view {
30764
31446
  if p.narrow {
@@ -30773,8 +31455,14 @@ func (p *tnConvPlan) convert(v interface{}) reflect.Value {
30773
31455
  // the same converted object, its fields refreshed from the source — JS
30774
31456
  // identity for Set / Map keys and === (a Babel node read as a
30775
31457
  // t.Identifier: hoistable.has(path.node) finds binding.identifier))
30776
- out, cached := tnConvIdentityOf(src, p.dst, p.src.Size())
30777
- dst := out.UnsafePointer()
31458
+ var dst unsafe.Pointer
31459
+ cached := false
31460
+ if identity {
31461
+ dst, cached = tnStructIdentityOf(src, p.dst, p.src.Size())
31462
+ } else {
31463
+ dst = reflect.New(p.dst).UnsafePointer()
31464
+ }
31465
+ out := reflect.NewAt(p.dst, dst)
30778
31466
  if cached {
30779
31467
  reflect.NewAt(p.dst, dst).Elem().SetZero()
30780
31468
  }
@@ -30813,14 +31501,12 @@ func (p *tnConvPlan) convert(v interface{}) reflect.Value {
30813
31501
  }
30814
31502
  }
30815
31503
  }
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
31504
  // the properties the object carries beyond its struct (tnExpandos): a
30823
- // target field of the same name reads them
31505
+ // target field of the same name reads them (only an object of a type
31506
+ // that ever had one can: tnExpandoPropsOf)
31507
+ if !tnExpandoTypes.has(v) {
31508
+ return out
31509
+ }
30824
31510
  for _, ef := range p.expandos {
30825
31511
  value, ok := tnExpandoGet(v, ef.name)
30826
31512
  if !ok || value == nil {
@@ -30903,25 +31589,30 @@ func tnFuncResults(out []reflect.Value, t reflect.Type) []reflect.Value {
30903
31589
  return results
30904
31590
  }
30905
31591
 
31592
+ // The conversion plan from v's type to t (v non-nil)
31593
+ func tnConvPlanOf(v interface{}, t reflect.Type) *tnConvPlan {
31594
+ from, to := (*[2]unsafe.Pointer)(unsafe.Pointer(&v)), (*[2]unsafe.Pointer)(unsafe.Pointer(&t))[1]
31595
+ h := ((uintptr(from[0])>>4 ^ uintptr(to)>>7) * 0x9E3779B1) >> 12 & (1<<10 - 1)
31596
+ p := tnConvPlans[h].Load()
31597
+ if p == nil || p.from != from[0] || p.to != to {
31598
+ key := [2]unsafe.Pointer{from[0], to}
31599
+ tnConvPlanMu.RLock()
31600
+ p = tnConvPlanIndex[key]
31601
+ tnConvPlanMu.RUnlock()
31602
+ if p == nil {
31603
+ p = tnMakeConvPlan(v, t, from[0], to)
31604
+ tnConvPlanMu.Lock()
31605
+ tnConvPlanIndex[key] = p
31606
+ tnConvPlanMu.Unlock()
31607
+ }
31608
+ tnConvPlans[h].Store(p)
31609
+ }
31610
+ return p
31611
+ }
31612
+
30906
31613
  func TnConvertDynamic(v interface{}, t reflect.Type) (reflect.Value, bool) {
30907
31614
  if v != nil {
30908
- from, to := (*[2]unsafe.Pointer)(unsafe.Pointer(&v)), (*[2]unsafe.Pointer)(unsafe.Pointer(&t))[1]
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 {
31615
+ if p := tnConvPlanOf(v, t); p.ok && (*[2]unsafe.Pointer)(unsafe.Pointer(&v))[1] != nil {
30925
31616
  return p.convert(v), true
30926
31617
  }
30927
31618
  }
@@ -31758,6 +32449,12 @@ func TnFlatItems(v interface{}) []interface{} {
31758
32449
  return []interface{}{v}
31759
32450
  }
31760
32451
 
32452
+ // (a class whose *[Symbol.iterator]() has a push form, e.g. an OpList: its
32453
+ // values without reflection, a channel or a goroutine)
32454
+ type tnSeqIter interface {
32455
+ Symbol_iterator__seq() func(func(interface{}) bool)
32456
+ }
32457
+
31761
32458
  func TnToArray(v interface{}) []interface{} {
31762
32459
  switch t := v.(type) {
31763
32460
  case nil:
@@ -31766,6 +32463,18 @@ func TnToArray(v interface{}) []interface{} {
31766
32463
  return append([]interface{}{}, t...)
31767
32464
  case tnArrayLike:
31768
32465
  return append([]interface{}{}, (*t.TnItems())...)
32466
+ case tnSeqIter:
32467
+ out := []interface{}{}
32468
+ for x := range t.Symbol_iterator__seq() {
32469
+ out = append(out, x)
32470
+ }
32471
+ return out
32472
+ case interface{ Symbol_iterator() chan interface{} }:
32473
+ out := []interface{}{}
32474
+ for x := range t.Symbol_iterator() {
32475
+ out = append(out, x)
32476
+ }
32477
+ return out
31769
32478
  case string:
31770
32479
  out := []interface{}{}
31771
32480
  for _, r := range t {
@@ -31914,17 +32623,27 @@ type tnStrShortEntry struct {
31914
32623
  ascii bool
31915
32624
  }
31916
32625
 
31917
- var tnStrShortLast atomic.Pointer[tnStrShortEntry]
32626
+ // (guarded by a mutex: a pointer published then replaced would race with a
32627
+ // reader, and an entry per miss is an allocation per inline token)
32628
+ var tnStrShortMu sync.Mutex
32629
+ var tnStrShortS string
32630
+ var tnStrShortA bool
31918
32631
 
31919
32632
  func tnStrShortASCII(s string) bool {
31920
32633
  if len(s) <= 64 {
31921
32634
  return tnStrIsASCII(s)
31922
32635
  }
31923
- if c := tnStrShortLast.Load(); c != nil && len(c.s) == len(s) && unsafe.StringData(c.s) == unsafe.StringData(s) {
31924
- return c.ascii
32636
+ tnStrShortMu.Lock()
32637
+ if len(tnStrShortS) == len(s) && unsafe.StringData(tnStrShortS) == unsafe.StringData(s) {
32638
+ ascii := tnStrShortA
32639
+ tnStrShortMu.Unlock()
32640
+ return ascii
31925
32641
  }
32642
+ tnStrShortMu.Unlock()
31926
32643
  ascii := tnStrIsASCII(s)
31927
- tnStrShortLast.Store(&tnStrShortEntry{s, ascii})
32644
+ tnStrShortMu.Lock()
32645
+ tnStrShortS, tnStrShortA = s, ascii
32646
+ tnStrShortMu.Unlock()
31928
32647
  return ascii
31929
32648
  }
31930
32649
 
@@ -32852,23 +33571,36 @@ func (d *tnJTDecoder) escaped(start int) (string, bool) {
32852
33571
  jsonStringify: `// JSON.stringify: JS's SerializeJSONProperty over TypeNative values
32853
33572
  // (unexported struct fields included; Go's encoder would skip them)
32854
33573
  type tnJSONWriter struct {
32855
- buf bytes.Buffer
33574
+ buf []byte
32856
33575
  indent string
32857
33576
  replacer func(key string, value interface{}) interface{}
32858
33577
  allow map[string]bool
32859
33578
  stack []uintptr
32860
33579
  }
32861
33580
 
33581
+ var tnJSONWriterPool = sync.Pool{
33582
+ New: func() interface{} {
33583
+ return &tnJSONWriter{buf: make([]byte, 0, 512)}
33584
+ },
33585
+ }
33586
+
32862
33587
  func TnJSONStringify(v interface{}, indent string) string {
32863
- w := &tnJSONWriter{indent: indent}
33588
+ w := tnJSONWriterPool.Get().(*tnJSONWriter)
33589
+ w.buf = w.buf[:0]
33590
+ w.indent = indent
33591
+ w.stack = w.stack[:0]
32864
33592
  w.property("", v, 0)
32865
- return w.buf.String()
33593
+ s := string(w.buf)
33594
+ if cap(w.buf) <= 65536 {
33595
+ tnJSONWriterPool.Put(w)
33596
+ }
33597
+ return s
32866
33598
  }
32867
33599
 
32868
33600
  // JSON.stringify(value, replacer, space): the replacer is a key/value
32869
33601
  // function or a list of keys; space a number of spaces or a string (≤ 10)
32870
33602
  func TnJSONStringifyWith(v interface{}, replacer interface{}, space interface{}) string {
32871
- w := &tnJSONWriter{}
33603
+ w := &tnJSONWriter{buf: make([]byte, 0, 256)}
32872
33604
  switch s := space.(type) {
32873
33605
  case float64:
32874
33606
  w.indent = strings.Repeat(" ", int(math.Max(0, math.Min(10, s))))
@@ -32903,7 +33635,7 @@ func TnJSONStringifyWith(v interface{}, replacer interface{}, space interface{})
32903
33635
  if !w.property("", v, 0) {
32904
33636
  return ""
32905
33637
  }
32906
- return w.buf.String()
33638
+ return string(w.buf)
32907
33639
  }
32908
33640
 
32909
33641
  // Values being written, innermost last: meeting one again is a cycle
@@ -32924,10 +33656,22 @@ func (w *tnJSONWriter) newline(depth int) {
32924
33656
  if w.indent == "" {
32925
33657
  return
32926
33658
  }
32927
- w.buf.WriteByte('\\n')
33659
+ w.buf = append(w.buf, '\\n')
32928
33660
  for i := 0; i < depth; i++ {
32929
- w.buf.WriteString(w.indent)
33661
+ w.buf = append(w.buf, w.indent...)
33662
+ }
33663
+ }
33664
+
33665
+ func tnJSONAppendNum(buf []byte, f float64) []byte {
33666
+ if f > -9007199254740992 && f < 9007199254740992 {
33667
+ if i := int64(f); float64(i) == f {
33668
+ return strconv.AppendInt(buf, i, 10)
33669
+ }
33670
+ }
33671
+ if math.IsNaN(f) || math.IsInf(f, 0) {
33672
+ return append(buf, "null"...)
32930
33673
  }
33674
+ return append(buf, TnNumStr(f)...)
32931
33675
  }
32932
33676
 
32933
33677
  // toJSON() methods (Dates' included): the value serialized in their place
@@ -32966,27 +33710,41 @@ func tnJSONFieldName(name string) string {
32966
33710
 
32967
33711
  // Writes one value; false when it serializes to undefined (functions)
32968
33712
  func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
32969
- v = tnJSONToJSON(v)
32970
33713
  switch t := v.(type) {
32971
- case nil, interface{ TnIsNullValue() }:
32972
- w.buf.WriteString("null")
33714
+ case nil, *tnNullValue:
33715
+ w.buf = append(w.buf, "null"...)
32973
33716
  return true
32974
33717
  case bool:
32975
33718
  if t {
32976
- w.buf.WriteString("true")
33719
+ w.buf = append(w.buf, "true"...)
32977
33720
  } else {
32978
- w.buf.WriteString("false")
33721
+ w.buf = append(w.buf, "false"...)
32979
33722
  }
32980
33723
  return true
32981
33724
  case float64:
32982
- if math.IsNaN(t) || math.IsInf(t, 0) {
32983
- w.buf.WriteString("null")
33725
+ w.buf = tnJSONAppendNum(w.buf, t)
33726
+ return true
33727
+ case string:
33728
+ w.buf = tnJSONAppendQuote(w.buf, t)
33729
+ return true
33730
+ }
33731
+ v = tnJSONToJSON(v)
33732
+ switch t := v.(type) {
33733
+ case nil, interface{ TnIsNullValue() }:
33734
+ w.buf = append(w.buf, "null"...)
33735
+ return true
33736
+ case bool:
33737
+ if t {
33738
+ w.buf = append(w.buf, "true"...)
32984
33739
  } else {
32985
- w.buf.WriteString(TnNumStr(t))
33740
+ w.buf = append(w.buf, "false"...)
32986
33741
  }
32987
33742
  return true
33743
+ case float64:
33744
+ w.buf = tnJSONAppendNum(w.buf, t)
33745
+ return true
32988
33746
  case string:
32989
- tnJSONQuote(&w.buf, t)
33747
+ w.buf = tnJSONAppendQuote(w.buf, t)
32990
33748
  return true
32991
33749
  case []byte:
32992
33750
  // a Buffer serializes through its toJSON(): { type, data }
@@ -33000,25 +33758,39 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
33000
33758
  })
33001
33759
  }
33002
33760
  rv := reflect.ValueOf(v)
33003
- if rv.Type().String() == "*big.Int" {
33761
+ if rv.Kind() == reflect.Pointer && rv.Type().Elem().Kind() != reflect.Struct && rv.Type().Elem().Kind() != reflect.Slice && rv.Type().String() == "*big.Int" {
33004
33762
  panic(TnNodeError("TypeError", "", "Do not know how to serialize a BigInt"))
33005
33763
  }
33764
+ if rv.Kind() == reflect.Pointer && !rv.IsNil() && rv.Elem().Kind() == reflect.Slice && w.replacer == nil && w.allow == nil {
33765
+ w.enter(rv.Pointer())
33766
+ defer w.leave()
33767
+ rv = rv.Elem()
33768
+ }
33006
33769
  switch rv.Kind() {
33007
33770
  case reflect.Func:
33008
33771
  return false
33009
33772
  case reflect.Pointer, reflect.Interface:
33010
33773
  if rv.IsNil() {
33011
- w.buf.WriteString("null")
33774
+ w.buf = append(w.buf, "null"...)
33012
33775
  return true
33013
33776
  }
33014
33777
  if rv.Kind() == reflect.Pointer {
33778
+ if rv.Elem().Kind() == reflect.Struct && w.replacer == nil && w.allow == nil {
33779
+ plan := tnJSONGetPlan(rv.Elem().Type())
33780
+ if !plan.hasCustom {
33781
+ return w.fastStructPtr(rv.UnsafePointer(), plan, depth)
33782
+ }
33783
+ if rv.Type().String() == "*big.Int" {
33784
+ panic(TnNodeError("TypeError", "", "Do not know how to serialize a BigInt"))
33785
+ }
33786
+ }
33015
33787
  // Records and Maps: insertion order; Maps and Sets serialize as {}
33016
33788
  if m, ok := v.(interface {
33017
33789
  Entries() [][]interface{}
33018
33790
  TnJSKind() uint8
33019
33791
  }); ok {
33020
33792
  if m.TnJSKind() != 0 {
33021
- w.buf.WriteString("{}")
33793
+ w.buf = append(w.buf, "{}"...)
33022
33794
  return true
33023
33795
  }
33024
33796
  return w.object(depth, func(emit func(string, interface{})) {
@@ -33027,9 +33799,6 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
33027
33799
  }
33028
33800
  })
33029
33801
  }
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
33802
  if rv.Elem().Kind() == reflect.Struct || rv.Elem().Kind() == reflect.Slice || rv.Elem().Kind() == reflect.Map {
33034
33803
  w.enter(rv.Pointer())
33035
33804
  defer w.leave()
@@ -33042,33 +33811,60 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
33042
33811
  return w.property(key, reflect.NewAt(elem.Type(), unsafe.Pointer(elem.UnsafeAddr())).Elem().Interface(), depth)
33043
33812
  case reflect.Slice, reflect.Array:
33044
33813
  if rv.Kind() == reflect.Slice && rv.IsNil() {
33045
- w.buf.WriteString("[]")
33814
+ w.buf = append(w.buf, "[]"...)
33046
33815
  return true
33047
33816
  }
33048
- if rv.Len() == 0 {
33049
- w.buf.WriteString("[]")
33817
+ n := rv.Len()
33818
+ if n == 0 {
33819
+ w.buf = append(w.buf, "[]"...)
33050
33820
  return true
33051
33821
  }
33052
33822
  if rv.Kind() == reflect.Slice {
33053
33823
  w.enter(rv.Pointer())
33054
33824
  defer w.leave()
33825
+ if w.replacer == nil && w.allow == nil {
33826
+ et := rv.Type().Elem()
33827
+ if et.Kind() == reflect.Pointer && et.Elem().Kind() == reflect.Struct {
33828
+ plan := tnJSONGetPlan(et.Elem())
33829
+ if !plan.hasCustom {
33830
+ ptrs := unsafe.Slice((*unsafe.Pointer)(rv.UnsafePointer()), n)
33831
+ w.buf = append(w.buf, '[')
33832
+ for i, p := range ptrs {
33833
+ if i > 0 {
33834
+ w.buf = append(w.buf, ',')
33835
+ }
33836
+ w.newline(depth + 1)
33837
+ if p == nil {
33838
+ w.buf = append(w.buf, "null"...)
33839
+ } else {
33840
+ w.fastStructPtr(p, plan, depth+1)
33841
+ }
33842
+ }
33843
+ w.newline(depth)
33844
+ w.buf = append(w.buf, ']')
33845
+ return true
33846
+ }
33847
+ }
33848
+ }
33055
33849
  }
33056
- w.buf.WriteByte('[')
33057
- for i := 0; i < rv.Len(); i++ {
33850
+ w.buf = append(w.buf, '[')
33851
+ for i := 0; i < n; i++ {
33058
33852
  if i > 0 {
33059
- w.buf.WriteByte(',')
33853
+ w.buf = append(w.buf, ',')
33060
33854
  }
33061
33855
  w.newline(depth + 1)
33062
33856
  item := rv.Index(i).Interface()
33857
+ var itemKey string
33063
33858
  if w.replacer != nil {
33064
- item = w.replacer(strconv.Itoa(i), item)
33859
+ itemKey = strconv.Itoa(i)
33860
+ item = w.replacer(itemKey, item)
33065
33861
  }
33066
- if !w.property(strconv.Itoa(i), item, depth+1) {
33067
- w.buf.WriteString("null")
33862
+ if !w.property(itemKey, item, depth+1) {
33863
+ w.buf = append(w.buf, "null"...)
33068
33864
  }
33069
33865
  }
33070
33866
  w.newline(depth)
33071
- w.buf.WriteByte(']')
33867
+ w.buf = append(w.buf, ']')
33072
33868
  return true
33073
33869
  case reflect.Map:
33074
33870
  // Dynamic objects (JSON.parse results): Go maps keep no order, keys sort
@@ -33090,7 +33886,7 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
33090
33886
  case reflect.Struct:
33091
33887
  if m, ok := v.(json.Marshaler); ok {
33092
33888
  if data, err := m.MarshalJSON(); err == nil {
33093
- w.buf.Write(data)
33889
+ w.buf = append(w.buf, data...)
33094
33890
  return true
33095
33891
  }
33096
33892
  }
@@ -33098,10 +33894,10 @@ func (w *tnJSONWriter) property(key string, v interface{}, depth int) bool {
33098
33894
  }
33099
33895
  data, err := tnJSONMarshal(v)
33100
33896
  if err != nil {
33101
- w.buf.WriteString("null")
33897
+ w.buf = append(w.buf, "null"...)
33102
33898
  return true
33103
33899
  }
33104
- w.buf.Write(data)
33900
+ w.buf = append(w.buf, data...)
33105
33901
  return true
33106
33902
  }
33107
33903
 
@@ -33180,51 +33976,48 @@ func (w *tnJSONWriter) structFieldsInOrder(rv reflect.Value, emit func(string, i
33180
33976
 
33181
33977
  // A JSON string as JSON.stringify writes it: U+2028 / U+2029 stay raw (Go's
33182
33978
  // encoder escapes them), invalid UTF-8 becomes \\ufffd
33183
- func tnJSONQuote(buf *bytes.Buffer, s string) {
33979
+ func tnJSONAppendQuote(buf []byte, s string) []byte {
33184
33980
  const hex = "0123456789abcdef"
33185
- buf.WriteByte('"')
33981
+ buf = append(buf, '"')
33186
33982
  start := 0
33187
33983
  for i := 0; i < len(s); {
33188
33984
  c := s[i]
33189
- if c >= utf8.RuneSelf {
33190
- r, size := utf8.DecodeRuneInString(s[i:])
33191
- if r == utf8.RuneError && size == 1 {
33192
- buf.WriteString(s[start:i])
33193
- buf.WriteString("\\\\ufffd")
33194
- start = i + 1
33985
+ if c < utf8.RuneSelf {
33986
+ if c >= 0x20 && c != '"' && c != '\\\\' {
33987
+ i++
33988
+ continue
33989
+ }
33990
+ buf = append(buf, s[start:i]...)
33991
+ switch c {
33992
+ case '"', '\\\\':
33993
+ buf = append(buf, '\\\\', c)
33994
+ case '\\n':
33995
+ buf = append(buf, '\\\\', 'n')
33996
+ case '\\r':
33997
+ buf = append(buf, '\\\\', 'r')
33998
+ case '\\t':
33999
+ buf = append(buf, '\\\\', 't')
34000
+ case '\\b':
34001
+ buf = append(buf, '\\\\', 'b')
34002
+ case '\\f':
34003
+ buf = append(buf, '\\\\', 'f')
34004
+ default:
34005
+ buf = append(buf, '\\\\', 'u', '0', '0', hex[c>>4], hex[c&0xF])
33195
34006
  }
33196
- i += size
33197
- continue
33198
- }
33199
- if c >= 0x20 && c != '"' && c != '\\\\' {
33200
34007
  i++
34008
+ start = i
33201
34009
  continue
33202
34010
  }
33203
- buf.WriteString(s[start:i])
33204
- buf.WriteByte('\\\\')
33205
- switch c {
33206
- case '"', '\\\\':
33207
- buf.WriteByte(c)
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])
34011
+ r, size := utf8.DecodeRuneInString(s[i:])
34012
+ if r == utf8.RuneError && size == 1 {
34013
+ buf = append(buf, s[start:i]...)
34014
+ buf = append(buf, "\\\\ufffd"...)
34015
+ start = i + 1
33222
34016
  }
33223
- i++
33224
- start = i
34017
+ i += size
33225
34018
  }
33226
- buf.WriteString(s[start:])
33227
- buf.WriteByte('"')
34019
+ buf = append(buf, s[start:]...)
34020
+ return append(buf, '"')
33228
34021
  }
33229
34022
 
33230
34023
  // A struct type's JSON fields (structFields' rules), resolved once per type:
@@ -33239,14 +34032,35 @@ type tnJSONField struct {
33239
34032
  null bool // (T | null: nil is null, not undefined)
33240
34033
  }
33241
34034
 
33242
- var tnJSONPlans sync.Map
33243
- var tnJSONMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
34035
+ type tnJSONStructPlan struct {
34036
+ typ reflect.Type
34037
+ fields []tnJSONField
34038
+ hasKeys bool
34039
+ keysOffset uintptr
34040
+ cycleFree bool
34041
+ hasCustom bool
34042
+ }
34043
+
34044
+ var (
34045
+ tnJSONPlans sync.Map
34046
+ tnJSONMarshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
34047
+ tnToJSONStrType = reflect.TypeOf((*interface{ toJSON() string })(nil)).Elem()
34048
+ tnToJSONFloatType = reflect.TypeOf((*interface{ toJSON() float64 })(nil)).Elem()
34049
+ tnToJSONBoolType = reflect.TypeOf((*interface{ toJSON() bool })(nil)).Elem()
34050
+ tnToJSONAnyType = reflect.TypeOf((*interface{ toJSON() interface{} })(nil)).Elem()
34051
+ tnTnToJSONType = reflect.TypeOf((*interface{ TnToJSON(string) interface{} })(nil)).Elem()
34052
+ tnTnItemsType = reflect.TypeOf((*interface{ TnItems() *[]interface{} })(nil)).Elem()
34053
+ tnJSKindType = reflect.TypeOf((*interface{ TnJSKind() uint8 })(nil)).Elem()
34054
+ tnEntriesType = reflect.TypeOf((*interface{ Entries() [][]interface{} })(nil)).Elem()
34055
+ tnTimeType = reflect.TypeOf(time.Time{})
34056
+ )
33244
34057
 
33245
- func tnJSONPlan(t reflect.Type) []tnJSONField {
34058
+ func tnJSONGetPlan(t reflect.Type) *tnJSONStructPlan {
33246
34059
  if plan, ok := tnJSONPlans.Load(t); ok {
33247
- return plan.([]tnJSONField)
34060
+ return plan.(*tnJSONStructPlan)
33248
34061
  }
33249
34062
  fields := []tnJSONField{}
34063
+ cycleFree := true
33250
34064
  var walk func(t reflect.Type, base uintptr)
33251
34065
  walk = func(t reflect.Type, base uintptr) {
33252
34066
  for i := 0; i < t.NumField(); i++ {
@@ -33261,9 +34075,8 @@ func tnJSONPlan(t reflect.Type) []tnJSONField {
33261
34075
  continue
33262
34076
  }
33263
34077
  name := tnJSONFieldName(f.Name)
33264
- var key bytes.Buffer
33265
- tnJSONQuote(&key, name)
33266
- key.WriteByte(':')
34078
+ key := tnJSONAppendQuote(make([]byte, 0, len(name)+3), name)
34079
+ key = append(key, ':')
33267
34080
  kind := uint8(0)
33268
34081
  switch f.Type {
33269
34082
  case reflect.TypeOf(float64(0)):
@@ -33272,65 +34085,90 @@ func tnJSONPlan(t reflect.Type) []tnJSONField {
33272
34085
  kind = 2
33273
34086
  case reflect.TypeOf(false):
33274
34087
  kind = 3
34088
+ default:
34089
+ cycleFree = false
33275
34090
  }
33276
- fields = append(fields, tnJSONField{offset: base + f.Offset, typ: f.Type, name: name, key: key.String(), kind: kind, null: f.Tag.Get("tn") == "null"})
34091
+ 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
34092
  }
33278
34093
  }
33279
34094
  walk(t, 0)
33280
- tnJSONPlans.Store(t, fields)
33281
- return fields
34095
+ var hasKeys bool
34096
+ var keysOffset uintptr
34097
+ if kf, ok := t.FieldByName("__keys"); ok && kf.Type == reflect.TypeOf((*[]string)(nil)) {
34098
+ hasKeys = true
34099
+ keysOffset = kf.Offset
34100
+ }
34101
+ pt := reflect.PointerTo(t)
34102
+ hasCustom := t == tnTimeType || pt.String() == "*big.Int" ||
34103
+ t.Implements(tnJSONMarshalerType) || pt.Implements(tnJSONMarshalerType) ||
34104
+ pt.Implements(tnToJSONStrType) || pt.Implements(tnToJSONFloatType) ||
34105
+ pt.Implements(tnToJSONBoolType) || pt.Implements(tnToJSONAnyType) ||
34106
+ pt.Implements(tnTnToJSONType) || pt.Implements(tnTnItemsType) ||
34107
+ pt.Implements(tnJSKindType) || pt.Implements(tnEntriesType)
34108
+ plan := &tnJSONStructPlan{
34109
+ typ: t,
34110
+ fields: fields,
34111
+ hasKeys: hasKeys,
34112
+ keysOffset: keysOffset,
34113
+ cycleFree: cycleFree,
34114
+ hasCustom: hasCustom,
34115
+ }
34116
+ tnJSONPlans.Store(t, plan)
34117
+ return plan
33282
34118
  }
33283
34119
 
33284
34120
  // A struct behind a pointer, written in place: no copy of the struct, no
33285
34121
  // boxing of its numbers, strings and booleans
33286
- func (w *tnJSONWriter) fastStruct(rv reflect.Value, depth int) bool {
34122
+ func (w *tnJSONWriter) fastStructPtr(base unsafe.Pointer, plan *tnJSONStructPlan, depth int) bool {
33287
34123
  // (an object whose keys were created in another order: see structFields)
33288
- if tnHasKeyOrder(rv.Elem().Type()) && !rv.Elem().FieldByName("__keys").IsNil() {
33289
- w.enter(rv.Pointer())
34124
+ if plan.hasKeys && *(**[]string)(unsafe.Add(base, plan.keysOffset)) != nil {
34125
+ w.enter(uintptr(base))
33290
34126
  defer w.leave()
33291
- return w.object(depth, func(emit func(string, interface{})) { w.structFields(rv.Elem(), emit) })
34127
+ elem := reflect.NewAt(plan.typ, base).Elem()
34128
+ return w.object(depth, func(emit func(string, interface{})) { w.structFields(elem, emit) })
33292
34129
  }
33293
- w.enter(rv.Pointer())
33294
- defer w.leave()
33295
- base := rv.UnsafePointer()
33296
- w.buf.WriteByte('{')
34130
+ if !plan.cycleFree {
34131
+ w.enter(uintptr(base))
34132
+ defer w.leave()
34133
+ }
34134
+ w.buf = append(w.buf, '{')
33297
34135
  wrote := false
33298
- for _, f := range tnJSONPlan(rv.Elem().Type()) {
33299
- mark := w.buf.Len()
34136
+ for _, f := range plan.fields {
34137
+ mark := len(w.buf)
33300
34138
  if wrote {
33301
- w.buf.WriteByte(',')
34139
+ w.buf = append(w.buf, ',')
33302
34140
  }
33303
34141
  w.newline(depth + 1)
33304
- w.buf.WriteString(f.key)
34142
+ w.buf = append(w.buf, f.key...)
33305
34143
  if w.indent != "" {
33306
- w.buf.WriteByte(' ')
34144
+ w.buf = append(w.buf, ' ')
33307
34145
  }
33308
34146
  p := unsafe.Add(base, f.offset)
33309
34147
  switch f.kind {
33310
34148
  case 1:
33311
- if x := *(*float64)(p); math.IsNaN(x) || math.IsInf(x, 0) {
33312
- w.buf.WriteString("null")
33313
- } else {
33314
- w.buf.WriteString(TnNumStr(x))
33315
- }
34149
+ w.buf = tnJSONAppendNum(w.buf, *(*float64)(p))
33316
34150
  case 2:
33317
- tnJSONQuote(&w.buf, *(*string)(p))
34151
+ w.buf = tnJSONAppendQuote(w.buf, *(*string)(p))
33318
34152
  case 3:
33319
- w.buf.WriteString(strconv.FormatBool(*(*bool)(p)))
34153
+ if *(*bool)(p) {
34154
+ w.buf = append(w.buf, "true"...)
34155
+ } else {
34156
+ w.buf = append(w.buf, "false"...)
34157
+ }
33320
34158
  default:
33321
34159
  // (an unset field — a nil pointer or any — is undefined: no key, as in JS)
33322
34160
  fv := reflect.NewAt(f.typ, p).Elem()
33323
34161
  if (fv.Kind() == reflect.Pointer || fv.Kind() == reflect.Interface) && fv.IsNil() {
33324
34162
  if f.null {
33325
- w.buf.WriteString("null")
34163
+ w.buf = append(w.buf, "null"...)
33326
34164
  wrote = true
33327
34165
  continue
33328
34166
  }
33329
- w.buf.Truncate(mark)
34167
+ w.buf = w.buf[:mark]
33330
34168
  continue
33331
34169
  }
33332
34170
  if !w.property(f.name, fv.Interface(), depth+1) {
33333
- w.buf.Truncate(mark) // undefined values leave the key out
34171
+ w.buf = w.buf[:mark] // undefined values leave the key out
33334
34172
  continue
33335
34173
  }
33336
34174
  }
@@ -33339,12 +34177,12 @@ func (w *tnJSONWriter) fastStruct(rv reflect.Value, depth int) bool {
33339
34177
  if wrote {
33340
34178
  w.newline(depth)
33341
34179
  }
33342
- w.buf.WriteByte('}')
34180
+ w.buf = append(w.buf, '}')
33343
34181
  return true
33344
34182
  }
33345
34183
 
33346
34184
  func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}))) bool {
33347
- w.buf.WriteByte('{')
34185
+ w.buf = append(w.buf, '{')
33348
34186
  wrote := false
33349
34187
  each(func(key string, value interface{}) {
33350
34188
  if w.allow != nil && !w.allow[key] {
@@ -33353,18 +34191,18 @@ func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}
33353
34191
  if w.replacer != nil {
33354
34192
  value = w.replacer(key, value)
33355
34193
  }
33356
- mark := w.buf.Len()
34194
+ mark := len(w.buf)
33357
34195
  if wrote {
33358
- w.buf.WriteByte(',')
34196
+ w.buf = append(w.buf, ',')
33359
34197
  }
33360
34198
  w.newline(depth + 1)
33361
- tnJSONQuote(&w.buf, key)
33362
- w.buf.WriteByte(':')
34199
+ w.buf = tnJSONAppendQuote(w.buf, key)
34200
+ w.buf = append(w.buf, ':')
33363
34201
  if w.indent != "" {
33364
- w.buf.WriteByte(' ')
34202
+ w.buf = append(w.buf, ' ')
33365
34203
  }
33366
34204
  if !w.property(key, value, depth+1) {
33367
- w.buf.Truncate(mark) // undefined values leave the key out
34205
+ w.buf = w.buf[:mark] // undefined values leave the key out
33368
34206
  return
33369
34207
  }
33370
34208
  wrote = true
@@ -33372,12 +34210,239 @@ func (w *tnJSONWriter) object(depth int, each func(emit func(string, interface{}
33372
34210
  if wrote {
33373
34211
  w.newline(depth)
33374
34212
  }
33375
- w.buf.WriteByte('}')
34213
+ w.buf = append(w.buf, '}')
33376
34214
  return true
33377
34215
  }
33378
34216
 
33379
34217
  // JSON.parse: a SyntaxError for invalid input, as in JS
33380
34218
  // Objects decode into ordered records, so their keys keep the text's order
34219
+ func tnFastJSONWS(s string, i int) int {
34220
+ for i < len(s) {
34221
+ c := s[i]
34222
+ if c != ' ' && c != '\\t' && c != '\\n' && c != '\\r' {
34223
+ break
34224
+ }
34225
+ i++
34226
+ }
34227
+ return i
34228
+ }
34229
+
34230
+ func tnFastJSONString(s string, i int) (string, int, bool) {
34231
+ if i >= len(s) || s[i] != '"' {
34232
+ return "", 0, false
34233
+ }
34234
+ i++
34235
+ start := i
34236
+ for i < len(s) {
34237
+ c := s[i]
34238
+ if c == '"' {
34239
+ return s[start:i], i + 1, true
34240
+ }
34241
+ if c == '\\\\' || c < 0x20 || c >= 0x80 {
34242
+ break
34243
+ }
34244
+ i++
34245
+ }
34246
+ if i >= len(s) || s[i] < 0x20 {
34247
+ return "", 0, false
34248
+ }
34249
+ buf := make([]byte, 0, (len(s)-start)+8)
34250
+ buf = append(buf, s[start:i]...)
34251
+ for i < len(s) {
34252
+ c := s[i]
34253
+ if c == '"' {
34254
+ return string(buf), i + 1, true
34255
+ }
34256
+ if c < 0x20 || c >= 0x80 {
34257
+ return "", 0, false
34258
+ }
34259
+ if c != '\\\\' {
34260
+ buf = append(buf, c)
34261
+ i++
34262
+ continue
34263
+ }
34264
+ if i+1 >= len(s) {
34265
+ return "", 0, false
34266
+ }
34267
+ esc := s[i+1]
34268
+ switch esc {
34269
+ case '"', '\\\\', '/':
34270
+ buf = append(buf, esc)
34271
+ case 'b':
34272
+ buf = append(buf, '\\b')
34273
+ case 'f':
34274
+ buf = append(buf, '\\f')
34275
+ case 'n':
34276
+ buf = append(buf, '\\n')
34277
+ case 'r':
34278
+ buf = append(buf, '\\r')
34279
+ case 't':
34280
+ buf = append(buf, '\\t')
34281
+ default:
34282
+ return "", 0, false
34283
+ }
34284
+ i += 2
34285
+ }
34286
+ return "", 0, false
34287
+ }
34288
+
34289
+ func tnFastJSONValue(s string, i int, depth int) (interface{}, int, bool) {
34290
+ if depth > 512 {
34291
+ return nil, 0, false
34292
+ }
34293
+ i = tnFastJSONWS(s, i)
34294
+ if i >= len(s) {
34295
+ return nil, 0, false
34296
+ }
34297
+ switch s[i] {
34298
+ case '{':
34299
+ m := TnNewMap[string, interface{}]()
34300
+ i = tnFastJSONWS(s, i+1)
34301
+ if i < len(s) && s[i] == '}' {
34302
+ return m, i + 1, true
34303
+ }
34304
+ for {
34305
+ k, next, ok := tnFastJSONString(s, i)
34306
+ if !ok {
34307
+ return nil, 0, false
34308
+ }
34309
+ i = tnFastJSONWS(s, next)
34310
+ if i >= len(s) || s[i] != ':' {
34311
+ return nil, 0, false
34312
+ }
34313
+ val, next, ok := tnFastJSONValue(s, i+1, depth+1)
34314
+ if !ok {
34315
+ return nil, 0, false
34316
+ }
34317
+ m.Set(k, val)
34318
+ i = tnFastJSONWS(s, next)
34319
+ if i >= len(s) {
34320
+ return nil, 0, false
34321
+ }
34322
+ if s[i] == '}' {
34323
+ return m, i + 1, true
34324
+ }
34325
+ if s[i] != ',' {
34326
+ return nil, 0, false
34327
+ }
34328
+ i = tnFastJSONWS(s, i+1)
34329
+ if i < len(s) && s[i] == '}' {
34330
+ return nil, 0, false
34331
+ }
34332
+ }
34333
+ case '[':
34334
+ arr := []interface{}{}
34335
+ i = tnFastJSONWS(s, i+1)
34336
+ if i < len(s) && s[i] == ']' {
34337
+ return arr, i + 1, true
34338
+ }
34339
+ for {
34340
+ val, next, ok := tnFastJSONValue(s, i, depth+1)
34341
+ if !ok {
34342
+ return nil, 0, false
34343
+ }
34344
+ arr = append(arr, val)
34345
+ i = tnFastJSONWS(s, next)
34346
+ if i >= len(s) {
34347
+ return nil, 0, false
34348
+ }
34349
+ if s[i] == ']' {
34350
+ return arr, i + 1, true
34351
+ }
34352
+ if s[i] != ',' {
34353
+ return nil, 0, false
34354
+ }
34355
+ i = tnFastJSONWS(s, i+1)
34356
+ if i < len(s) && s[i] == ']' {
34357
+ return nil, 0, false
34358
+ }
34359
+ }
34360
+ case '"':
34361
+ return tnFastJSONString(s, i)
34362
+ case 't':
34363
+ if i+4 <= len(s) && s[i:i+4] == "true" {
34364
+ return true, i + 4, true
34365
+ }
34366
+ return nil, 0, false
34367
+ case 'f':
34368
+ if i+5 <= len(s) && s[i:i+5] == "false" {
34369
+ return false, i + 5, true
34370
+ }
34371
+ return nil, 0, false
34372
+ case 'n':
34373
+ if i+4 <= len(s) && s[i:i+4] == "null" {
34374
+ return TnNull, i + 4, true
34375
+ }
34376
+ return nil, 0, false
34377
+ default:
34378
+ start := i
34379
+ neg := false
34380
+ if s[i] == '-' {
34381
+ neg = true
34382
+ i++
34383
+ if i >= len(s) {
34384
+ return nil, 0, false
34385
+ }
34386
+ }
34387
+ if s[i] == '0' {
34388
+ i++
34389
+ if i < len(s) && s[i] >= '0' && s[i] <= '9' {
34390
+ return nil, 0, false
34391
+ }
34392
+ } else if s[i] >= '1' && s[i] <= '9' {
34393
+ for i < len(s) && s[i] >= '0' && s[i] <= '9' {
34394
+ i++
34395
+ }
34396
+ } else {
34397
+ return nil, 0, false
34398
+ }
34399
+ isInt := true
34400
+ if i < len(s) && s[i] == '.' {
34401
+ isInt = false
34402
+ i++
34403
+ if i >= len(s) || s[i] < '0' || s[i] > '9' {
34404
+ return nil, 0, false
34405
+ }
34406
+ for i < len(s) && s[i] >= '0' && s[i] <= '9' {
34407
+ i++
34408
+ }
34409
+ }
34410
+ if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
34411
+ isInt = false
34412
+ i++
34413
+ if i < len(s) && (s[i] == '+' || s[i] == '-') {
34414
+ i++
34415
+ }
34416
+ if i >= len(s) || s[i] < '0' || s[i] > '9' {
34417
+ return nil, 0, false
34418
+ }
34419
+ for i < len(s) && s[i] >= '0' && s[i] <= '9' {
34420
+ i++
34421
+ }
34422
+ }
34423
+ digits := start
34424
+ if neg {
34425
+ digits++
34426
+ }
34427
+ if isInt && i-digits <= 15 {
34428
+ var u uint64
34429
+ for j := digits; j < i; j++ {
34430
+ u = u*10 + uint64(s[j]-'0')
34431
+ }
34432
+ f := float64(u)
34433
+ if neg {
34434
+ f = -f
34435
+ }
34436
+ return f, i, true
34437
+ }
34438
+ f, err := strconv.ParseFloat(s[start:i], 64)
34439
+ if err != nil {
34440
+ return nil, 0, false
34441
+ }
34442
+ return f, i, true
34443
+ }
34444
+ }
34445
+
33381
34446
  func tnJSONDecodeOrdered(dec *json.Decoder) (interface{}, error) {
33382
34447
  tok, err := dec.Token()
33383
34448
  if err != nil {
@@ -33420,6 +34485,9 @@ func tnJSONDecodeOrdered(dec *json.Decoder) (interface{}, error) {
33420
34485
  }
33421
34486
 
33422
34487
  func TnJSONParse(text string) interface{} {
34488
+ if v, end, ok := tnFastJSONValue(text, 0, 0); ok && tnFastJSONWS(text, end) == len(text) {
34489
+ return v
34490
+ }
33423
34491
  dec := json.NewDecoder(strings.NewReader(text))
33424
34492
  if ordered, err := tnJSONDecodeOrdered(dec); err == nil {
33425
34493
  if _, extra := dec.Token(); extra == io.EOF {
@@ -33797,6 +34865,25 @@ func (m *TnMap[K, V]) TnProp(key string) (interface{}, bool) {
33797
34865
  return v, present
33798
34866
  }
33799
34867
 
34868
+ // obj[key] = value on a record held in a dynamic value (a plain object
34869
+ // literal, {}): the key set without reflection, as tnSetMember's Set call
34870
+ // would. False when the key or value isn't already of the map's types (the
34871
+ // reflective path converts those)
34872
+ func (m *TnMap[K, V]) TnSetProp(key string, value interface{}) bool {
34873
+ k, ok := any(key).(K)
34874
+ if !ok || m == nil {
34875
+ return false
34876
+ }
34877
+ var v V
34878
+ if value != nil {
34879
+ if v, ok = value.(V); !ok {
34880
+ return false
34881
+ }
34882
+ }
34883
+ m.Set(k, v)
34884
+ return true
34885
+ }
34886
+
33800
34887
  func (m *TnMap[K, V]) Lookup(k K) (V, bool) {
33801
34888
  if m == nil {
33802
34889
  var zero V
@@ -34546,6 +35633,8 @@ func TnRegexWrapReplaceFirst(r *TnRegex, s string, repl string) string {
34546
35633
 
34547
35634
  func TnRegexReplaceFuncW(r *TnRegex, s string, fn func([]string, int) string, all bool) string {
34548
35635
  var out strings.Builder
35636
+ // (a replacement keeps the length roughly: grow once, not by doubling)
35637
+ out.Grow(len(s))
34549
35638
  last := 0
34550
35639
  ascii := tnStrASCII(s)
34551
35640
  r.scan(s, true, func(groups []string, lo int, hi int) bool {
@@ -34567,6 +35656,7 @@ func TnRegexReplaceFuncW(r *TnRegex, s string, fn func([]string, int) string, al
34567
35656
 
34568
35657
  func (r *TnRegex) replace(s string, repl string, all bool) string {
34569
35658
  var out strings.Builder
35659
+ out.Grow(len(s) + max(0, len(repl)-1))
34570
35660
  last := 0
34571
35661
  plain := strings.IndexByte(repl, '$') < 0
34572
35662
  r.scan(s, !plain, func(groups []string, lo int, hi int) bool {
@@ -36036,6 +37126,7 @@ func TnTimeNow() time.Time {
36036
37126
  // as tasks. Refs (pending timers, async work, open handles) keep it alive.
36037
37127
  var tnLoopMu sync.Mutex
36038
37128
  var tnLoopTasks []func()
37129
+ var tnHasLoopTasks int32
36039
37130
  var tnLoopSignal = make(chan struct{}, 1)
36040
37131
  var tnLoopRefs int64
36041
37132
 
@@ -36115,13 +37206,15 @@ func tnLoopNotify() {
36115
37206
  func TnLoopRef() { atomic.AddInt64(&tnLoopRefs, 1) }
36116
37207
 
36117
37208
  func TnLoopUnref() {
36118
- atomic.AddInt64(&tnLoopRefs, -1)
36119
- tnLoopNotify()
37209
+ if atomic.AddInt64(&tnLoopRefs, -1) <= 0 {
37210
+ tnLoopNotify()
37211
+ }
36120
37212
  }
36121
37213
 
36122
37214
  func TnLoopPost(fn func()) {
36123
37215
  tnLoopMu.Lock()
36124
37216
  tnLoopTasks = append(tnLoopTasks, fn)
37217
+ atomic.StoreInt32(&tnHasLoopTasks, 1)
36125
37218
  tnLoopMu.Unlock()
36126
37219
  tnLoopNotify()
36127
37220
  }
@@ -36139,6 +37232,7 @@ func tnLoopRunOrPost(fn func()) {
36139
37232
  }
36140
37233
  tnLoopMu.Lock()
36141
37234
  tnLoopTasks = append(tnLoopTasks, fn)
37235
+ atomic.StoreInt32(&tnHasLoopTasks, 1)
36142
37236
  tnLoopMu.Unlock()
36143
37237
  defer func() {
36144
37238
  if r := recover(); r != nil {
@@ -36151,6 +37245,22 @@ func tnLoopRunOrPost(fn func()) {
36151
37245
  tnRelease()
36152
37246
  }
36153
37247
 
37248
+ func tnLoopRun(fn func()) {
37249
+ <-tnBaton
37250
+ defer func() {
37251
+ if r := recover(); r != nil {
37252
+ go func() { panic(r) }()
37253
+ select {}
37254
+ }
37255
+ }()
37256
+ TnRunMicrotasks()
37257
+ TnLoopRunPending()
37258
+ tnRunTask(fn)
37259
+ TnRunMicrotasks()
37260
+ TnLoopRunPending()
37261
+ tnRelease()
37262
+ }
37263
+
36154
37264
  // Runs a callback on the loop from a goroutine that does not hold the baton,
36155
37265
  // and waits for it
36156
37266
  func TnLoopCall(fn func()) {
@@ -36164,19 +37274,31 @@ func TnLoopCall(fn func()) {
36164
37274
 
36165
37275
  // (baton holder) Runs the queued tasks, each followed by its microtasks
36166
37276
  func TnLoopRunPending() bool {
37277
+ if atomic.LoadInt32(&tnHasLoopTasks) == 0 {
37278
+ return false
37279
+ }
36167
37280
  ran := false
36168
37281
  for {
36169
37282
  tnLoopMu.Lock()
36170
37283
  if len(tnLoopTasks) == 0 {
37284
+ atomic.StoreInt32(&tnHasLoopTasks, 0)
36171
37285
  tnLoopMu.Unlock()
36172
37286
  return ran
36173
37287
  }
36174
37288
  fn := tnLoopTasks[0]
37289
+ tnLoopTasks[0] = nil
36175
37290
  tnLoopTasks = tnLoopTasks[1:]
37291
+ if len(tnLoopTasks) == 0 {
37292
+ tnLoopTasks = tnLoopTasks[:0]
37293
+ atomic.StoreInt32(&tnHasLoopTasks, 0)
37294
+ }
36176
37295
  tnLoopMu.Unlock()
36177
37296
  ran = true
36178
37297
  tnRunTask(fn)
36179
37298
  TnRunMicrotasks()
37299
+ if atomic.LoadInt32(&tnHasLoopTasks) == 0 {
37300
+ return true
37301
+ }
36180
37302
  }
36181
37303
  }
36182
37304
 
@@ -36281,6 +37403,7 @@ func tnWakeQueue(tok chan struct{}) {
36281
37403
  }
36282
37404
  tnMicrotasksMu.Lock()
36283
37405
  tnMicrotasks = append(tnMicrotasks, func() { tnDeliver(tok) })
37406
+ atomic.StoreInt32(&tnHasMicrotasks, 1)
36284
37407
  tnMicrotasksMu.Unlock()
36285
37408
  tnLoopNotify()
36286
37409
  }
@@ -36422,25 +37545,39 @@ func (tnLoopGroup) Wait() { TnRunLoop() }
36422
37545
  // queueMicrotask: run after the current synchronous code (end of main or of a loop task)
36423
37546
  var tnMicrotasks []func()
36424
37547
  var tnMicrotasksMu sync.Mutex
37548
+ var tnHasMicrotasks int32
36425
37549
 
36426
37550
  func TnQueueMicrotask(fn func()) {
36427
37551
  fn = TnAsyncWrap(fn)
36428
37552
  tnMicrotasksMu.Lock()
36429
37553
  tnMicrotasks = append(tnMicrotasks, fn)
37554
+ atomic.StoreInt32(&tnHasMicrotasks, 1)
36430
37555
  tnMicrotasksMu.Unlock()
36431
37556
  }
36432
37557
 
36433
37558
  func TnRunMicrotasks() {
37559
+ if atomic.LoadInt32(&tnHasMicrotasks) == 0 {
37560
+ return
37561
+ }
36434
37562
  for {
36435
37563
  tnMicrotasksMu.Lock()
36436
37564
  if len(tnMicrotasks) == 0 {
37565
+ atomic.StoreInt32(&tnHasMicrotasks, 0)
36437
37566
  tnMicrotasksMu.Unlock()
36438
37567
  return
36439
37568
  }
36440
37569
  fn := tnMicrotasks[0]
37570
+ tnMicrotasks[0] = nil
36441
37571
  tnMicrotasks = tnMicrotasks[1:]
37572
+ if len(tnMicrotasks) == 0 {
37573
+ tnMicrotasks = tnMicrotasks[:0]
37574
+ atomic.StoreInt32(&tnHasMicrotasks, 0)
37575
+ }
36442
37576
  tnMicrotasksMu.Unlock()
36443
37577
  TnAsyncRun(nil, fn)
37578
+ if atomic.LoadInt32(&tnHasMicrotasks) == 0 {
37579
+ return
37580
+ }
36444
37581
  }
36445
37582
  }`,
36446
37583
  uri: `// encodeURIComponent: escapes everything except A-Z a-z 0-9 - _ . ! ~ * ' ( )
@@ -37233,6 +38370,48 @@ func TnStrAppend(s, part string) string {
37233
38370
  return unsafe.String(&buf[0], n)
37234
38371
  }`,
37235
38372
  };
38373
+ // tnCallValueTyped: a case per Go func type this program builds, converting
38374
+ // the dynamic call's arguments and calling it — the same work TnCallValue's
38375
+ // reflective path does, without reflect.Value.Call (which is most of a
38376
+ // dynamic call's cost). Shapes TnCallValue's own switch covers stay there.
38377
+ function emitTypedDynamicCalls() {
38378
+ const cases = [];
38379
+ // (aliases of a primitive are the primitive's type: one case for both)
38380
+ const types = new Set();
38381
+ for (const raw of dynamicFuncTypes) {
38382
+ let t = raw;
38383
+ for (const [name, base] of primitiveEnumGoTypes) {
38384
+ t = t.replace(new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g'), base);
38385
+ }
38386
+ types.add(t);
38387
+ }
38388
+ for (const fnType of [...types].sort()) {
38389
+ if (!fnType.startsWith('func('))
38390
+ continue;
38391
+ const result = goFuncReturnType(fnType);
38392
+ const params = goFuncParamTypes(fnType);
38393
+ const variadic = params.length > 0 && params[params.length - 1].startsWith('...');
38394
+ const fixed = variadic ? params.length - 1 : params.length;
38395
+ const argExprs = params.slice(0, fixed).map((p, i) => `tnCoerceArg[${p}](TnArg(args, ${i}))`);
38396
+ if (variadic) {
38397
+ const elem = params[params.length - 1].slice(3);
38398
+ argExprs.push(`tnCoerceArgs[${elem}](args, ${fixed})...`);
38399
+ }
38400
+ const call = `f(${argExprs.join(', ')})`;
38401
+ const results = result ? splitGoParameters(result) : [];
38402
+ let body;
38403
+ if (results.length === 0)
38404
+ body = `${call}; return nil, true`;
38405
+ else if (results.length === 1)
38406
+ body = `return ${call}, true`;
38407
+ else
38408
+ body = `${results.map((_, i) => (i === 0 ? '__r0' : '_')).join(', ')} := ${call}; return __r0, true`;
38409
+ cases.push(`\tcase ${fnType}:\n\t\t${body}`);
38410
+ }
38411
+ if (cases.length === 0)
38412
+ return 'func tnCallValueTyped(fn interface{}, args []interface{}) (interface{}, bool) {\n\treturn nil, false\n}';
38413
+ 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}`;
38414
+ }
37236
38415
  // Returns the Go source for all helpers used in this transpilation, or '' if none.
37237
38416
  // Emitted only into the main output file: every generated file shares `package main`,
37238
38417
  // so helpers are visible across files and must not be duplicated.
@@ -37241,6 +38420,8 @@ function emitGoHelpers() {
37241
38420
  .sort()
37242
38421
  .map((id) => goHelpers[id] ?? nodeRegistry.goHelpers[id])
37243
38422
  .filter(Boolean);
38423
+ if (usedHelpers.has('dynamic'))
38424
+ sources.push(emitTypedDynamicCalls());
37244
38425
  if (usedHelpers.has('nodeUtil')) {
37245
38426
  const names = [...classNames].sort().map((name) => `${toGoStringLiteral(getSafeName(name))}: true`);
37246
38427
  sources.push(`// Classes util.inspect prints as \`Name { … }\`\nvar tnInspectClassNames = map[string]bool{${names.join(', ')}}`);