@nstudio/nativescript-compiler 9.2.0-alpha.15 → 9.2.0-alpha.17

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.
Files changed (71) hide show
  1. package/dist/kit/kit-index.js +9 -0
  2. package/dist/kotlin/access.js +7 -9
  3. package/dist/kotlin/arguments.js +2 -2
  4. package/dist/kotlin/class-accessors.js +1 -1
  5. package/dist/kotlin/class-declaration.js +23 -2
  6. package/dist/kotlin/class-methods.js +21 -11
  7. package/dist/kotlin/components.js +2 -7
  8. package/dist/kotlin/core-api.js +2 -21
  9. package/dist/kotlin/declarations.js +86 -9
  10. package/dist/kotlin/functions.js +1 -4
  11. package/dist/kotlin/global-calls.js +1 -4
  12. package/dist/kotlin/literals.js +3 -6
  13. package/dist/kotlin/names.js +2 -0
  14. package/dist/kotlin/native/classfiles.js +2 -13
  15. package/dist/kotlin/operators.js +12 -6
  16. package/dist/kotlin/optional-chains.js +2 -9
  17. package/dist/kotlin/overrides.js +3 -15
  18. package/dist/kotlin/placement.js +1 -12
  19. package/dist/kotlin/statements.js +1 -13
  20. package/dist/kotlin/translator.js +2 -10
  21. package/dist/kotlin/type-tests.js +1 -1
  22. package/dist/kotlin/types.js +2 -19
  23. package/dist/program/core-facts.js +9 -0
  24. package/dist/semantics/facts.js +37 -1
  25. package/dist/semantics/forms/by-name.js +18 -4
  26. package/dist/semantics/lang.js +36 -1
  27. package/dist/semantics/lower.js +90 -0
  28. package/dist/semantics/lowering-methods.js +115 -3
  29. package/dist/semantics/marks.js +30 -0
  30. package/dist/semantics/refusals.js +12 -11
  31. package/dist/semantics/tdz.js +103 -8
  32. package/dist/swift/access.js +6 -8
  33. package/dist/swift/assignment.js +10 -2
  34. package/dist/swift/calls.js +7 -2
  35. package/dist/swift/class-accessors.js +1 -1
  36. package/dist/swift/class-declaration.js +3 -2
  37. package/dist/swift/class-methods.js +16 -1
  38. package/dist/swift/classes.js +23 -9
  39. package/dist/swift/components.js +0 -4
  40. package/dist/swift/core-api.js +9 -29
  41. package/dist/swift/declarations.js +0 -5
  42. package/dist/swift/expression-statements.js +7 -0
  43. package/dist/swift/global-calls.js +0 -4
  44. package/dist/swift/lenient.js +3 -5
  45. package/dist/swift/method-values.js +1 -19
  46. package/dist/swift/modules.js +2 -0
  47. package/dist/swift/names.js +0 -9
  48. package/dist/swift/native/api.js +3 -1
  49. package/dist/swift/native/dispatch.js +2 -8
  50. package/dist/swift/operators.js +7 -6
  51. package/dist/swift/optional-chains.js +1 -8
  52. package/dist/swift/parameters.js +0 -4
  53. package/dist/swift/placement.js +7 -12
  54. package/dist/swift/protocols.js +25 -4
  55. package/dist/swift/results.js +0 -4
  56. package/dist/swift/statements.js +1 -13
  57. package/dist/swift/translator.js +0 -10
  58. package/dist/types/adapter-api.d.ts +3 -3
  59. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Array.kt +53 -12
  60. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/JSON.kt +30 -4
  61. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Language.kt +33 -0
  62. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Prototypes.kt +9 -1
  63. package/kit-android/src/main/kotlin/org/nativescript/kit/runtime/Values.kt +137 -28
  64. package/kit-apple/Sources/NativeScriptKit/Core/color.color-common.swift +17 -0
  65. package/kit-apple/Sources/NativeScriptKit/Core/color.index.ios.swift +60 -0
  66. package/kit-apple/Sources/NativeScriptKit/Core/js-libs.easysax.easysax.swift +24 -6
  67. package/kit-apple/Sources/NativeScriptKit/Core/kit-index.json +3 -3
  68. package/kit-apple/Sources/NativeScriptKit/Core/ui.gestures.gestures-common.swift +2 -0
  69. package/kit-apple/Sources/NativeScriptKit/Runtime/JSON.swift +151 -82
  70. package/kit-apple/Sources/NativeScriptKit/Runtime/Prototypes.swift +13 -1
  71. package/package.json +1 -1
@@ -3,6 +3,7 @@ import { CF_CLASSES, functionParts, RT } from "../syntax.js";
3
3
  import { posted } from "./bridging.js";
4
4
  import { lookupClass, lookupInit, nativeTable } from "./sdk.js";
5
5
  import { compareText } from "../../program/order.js";
6
+ import { newerVersion } from "../../semantics/lang.js";
6
7
  /** The member names script reads, writes and calls on `any` values in these files. */
7
8
  export function untypedMembers(checker, files) {
8
9
  const uses = new Map();
@@ -58,7 +59,7 @@ export function nativeDispatch(modules, uses, deploymentTarget, defined = {}, de
58
59
  const hidden = new Map(candidates.filter(({ cls }) => named.get(cls.swift) === 1 && qualified(cls)).map(({ cls }) => [cls.swift, typeName(cls)]));
59
60
  const typed = (type) => (hidden.size ? type.replace(/(?<![\w.])[A-Z]\w*/g, (n) => hidden.get(n) ?? n) : type);
60
61
  const gets = [], sets = [], calls = [];
61
- const guarded = (introduced, code) => (introduced && newer(introduced, deploymentTarget) ? `if #available(iOS ${introduced}, *) { ${code} }` : code);
62
+ const guarded = (introduced, code) => (introduced && newerVersion(introduced, deploymentTarget) ? `if #available(iOS ${introduced}, *) { ${code} }` : code);
62
63
  for (const [name, u] of [...uses].sort(([a], [b]) => compareText(a, b))) {
63
64
  const get = [], set = [], call = [];
64
65
  for (const { js, cls } of candidates) {
@@ -209,10 +210,3 @@ function fromNative(code, type) {
209
210
  return `${code} as Any?`;
210
211
  return `${RT.jsNativeResult}(${code})`;
211
212
  }
212
- function newer(version, than) {
213
- const a = version.split('.').map(Number), b = than.split('.').map(Number);
214
- for (let i = 0; i < Math.max(a.length, b.length); i++)
215
- if ((a[i] ?? 0) !== (b[i] ?? 0))
216
- return (a[i] ?? 0) > (b[i] ?? 0);
217
- return false;
218
- }
@@ -12,6 +12,7 @@ import { constClassExpr, hasInstanceClass } from "../semantics/classes.js";
12
12
  import { isUntyped, spelledType } from "../semantics/types.js";
13
13
  import { bigIntArithmetic, bigIntCompare, bigIntPlan } from "../semantics/apis/bigint.js";
14
14
  import { BIT_ASSIGNMENTS, addCall, bitOperation, concatOperand, numericThrowing, untypedBinary, untypedConversion } from "../semantics/apis/operators.js";
15
+ import { planRelational } from "../semantics/lower.js";
15
16
  /** BigInt's operations the backend spells as an operator. */
16
17
  const BIGINT_INFIX = { add: '+', subtract: '-', multiply: '*', and: '&', or: '|', xor: '^' };
17
18
  export const operatorsMethods = {
@@ -157,15 +158,15 @@ export const operatorsMethods = {
157
158
  case K.GreaterThanToken:
158
159
  case K.LessThanEqualsToken:
159
160
  case K.GreaterThanEqualsToken: {
160
- const sym = ts.tokenToString(op);
161
- if (this.isString(e.left) && this.isString(e.right))
162
- return `${RT.jsCompare}(${l()}, ${r()}) ${sym} 0`;
161
+ const plan = planRelational(op, this.isString(e.left), this.isString(e.right), this.isAny(e.left) || this.isAny(e.right));
162
+ if (plan.kind === 'string')
163
+ return `${RT.jsCompare}(${l()}, ${r()}) ${plan.op} 0`;
163
164
  // An untyped side may hold a string, and two strings compare as strings.
164
- if (this.isAny(e.left) || this.isAny(e.right)) {
165
+ if (plan.kind === 'dynamic') {
165
166
  const [a, b] = [this.coerce(e.left, 'Any?'), this.coerce(e.right, 'Any?')];
166
- return op === K.LessThanToken ? `(${RT.jsLessThan}(${a}, ${b}) == true)` : op === K.GreaterThanToken ? `(${RT.jsGreaterThan}(${a}, ${b}) == true)` : op === K.LessThanEqualsToken ? `(${RT.jsGreaterThan}(${a}, ${b}) == false)` : `(${RT.jsLessThan}(${a}, ${b}) == false)`;
167
+ return plan.op === '<' ? `(${RT.jsLessThan}(${a}, ${b}) == true)` : plan.op === '>' ? `(${RT.jsGreaterThan}(${a}, ${b}) == true)` : plan.op === '<=' ? `(${RT.jsGreaterThan}(${a}, ${b}) == false)` : `(${RT.jsLessThan}(${a}, ${b}) == false)`;
167
168
  }
168
- return this.marks.infix(this.toNumber(e.left), sym, this.toNumber(e.right));
169
+ return this.marks.infix(this.toNumber(e.left), plan.op, this.toNumber(e.right));
169
170
  }
170
171
  case K.QuestionQuestionToken: {
171
172
  const t = this.typeOf(e);
@@ -379,14 +379,7 @@ export const optionalChainsMethods = {
379
379
  * A string, number or boolean read `e` of type `t` as the optional it holds, where it converts undefined (a read, or
380
380
  * a choice one of whose branches does); null where it converts nothing.
381
381
  */
382
- convertedOptional(e, t) {
383
- if (this.library)
384
- return null;
385
- const inner = ts.skipOuterExpressions(e);
386
- if (ts.isConditionalExpression(inner) && this.typeOf(inner) === t && [inner.whenTrue, inner.whenFalse].some((x) => this.undefinedConverted(this.coerce(ts.skipOuterExpressions(x, ts.OuterExpressionKinds.Parentheses), t))))
387
- return this.coerce(inner, optionalType(t));
388
- return this.undefinedConverted(this.expr(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses)));
389
- },
382
+ /* convertedOptional is installed from semantics/lowering-methods.ts */
390
383
  /**
391
384
  * App and plugin code's string, number or boolean read that converts undefined (`(x ?? "undefined")`): the optional it
392
385
  * converts, for a use that takes undefined as it is (a comparison). Null for any other code.
@@ -2,7 +2,6 @@
2
2
  import ts from 'typescript';
3
3
  import { assignsTo, ident, isFunctionType, isOptional, nullishType, optionalType, swiftString, RT } from "./syntax.js";
4
4
  import { boundNames, hasModifier } from "../semantics/ast.js";
5
- import { isConstant } from "../semantics/lang.js";
6
5
  import { isUntyped, spelledType } from "../semantics/types.js";
7
6
  export const parametersMethods = {
8
7
  /** A parameter's Swift type as `params` declares it (an unwrapped optional written as optional, as a function type has it). */
@@ -131,9 +130,6 @@ export const parametersMethods = {
131
130
  * A parameter Swift gives its default value itself: a constant, unless the method it overrides takes the parameter as optional.
132
131
  * An untyped one is given its default in the body, where an explicit undefined (nil) takes it too and null does not.
133
132
  */
134
- constantDefault(p) {
135
- return !!p.initializer && isConstant(p.initializer) && !this.optionalDefaults.has(p) && !this.familyDefaultsDiffer(p) && !this.isAny(p.name) && !this.states.defaultTakesUndefined(p);
136
- },
137
133
  /** An app parameter whose default its body applies (`paramPrelude`): an argument is given as the optional it may be. */
138
134
  filledDefault(d) {
139
135
  return !this.library && !!d && ts.isParameter(d) && !!d.initializer && !d.dotDotDotToken && !this.templateParams && !d.getSourceFile().isDeclarationFile && !this.constantDefault(d);
@@ -109,18 +109,7 @@ export const placementMethods = {
109
109
  const t = contextual ? this.type(contextual, e) : ts.isFunctionLike(slot) ? this.returnTypeOf(slot) : ts.isIdentifier(slot.name ?? slot) ? this.typeOf(slot.name) : 'Any?';
110
110
  return !/[?!]$/.test(t);
111
111
  },
112
- /** A `nullishRead` value as its `JSNullish<T>`. */
113
- nullishCode(e) {
114
- if (!ts.isCallExpression(e) && !ts.isPropertyAccessExpression(e))
115
- return this.refName(e);
116
- this.nullishCalls.add(e);
117
- try {
118
- return this.expr(e);
119
- }
120
- finally {
121
- this.nullishCalls.delete(e);
122
- }
123
- },
112
+ /* nullishCode is installed from semantics/lowering-methods.ts */
124
113
  /** An app generic class's instance where the same class with an `any` type argument is wanted: Swift's generic classes are invariant. */
125
114
  checkAnyArgument(e, target) {
126
115
  const want = /^(\w+)<(.+)>[?!]?$/.exec(target);
@@ -694,6 +683,12 @@ export const placementMethods = {
694
683
  const viewedFrom = this.classNamed(source.replace(/[?!]$/, ''));
695
684
  if (viewedFrom && this.states.viewedClass(viewedFrom) && source.replace(/[?!]$/, '') !== target.replace(/[?!]$/, '') && this.isObjectShape(target.replace(/[?!]$/, '')))
696
685
  return this.convert(this.expr(e), source, target);
686
+ // A class whose declared protocol was dropped by `protocolWitnesses`: wrap through `IFaceObject(jsObject:)`.
687
+ const targetProto = target.replace(/[?!]$/, '');
688
+ if (!this.library && viewedFrom && source.replace(/[?!]$/, '') !== targetProto && this.protocols.has(targetProto) && this.facts.hasInterface(this, this.interfaces, (d, s) => this.topName(d, s), targetProto) && !this.conformsToProtocol(viewedFrom, targetProto)) {
689
+ const wrapped = `${targetProto}Object(jsObject: ${this.expr(e)})`;
690
+ return isOptional(source) || source.endsWith('!') ? this.marks.unwrappedIf(`(${this.expr(e)}).map { ${targetProto}Object(jsObject: $0) }`, !(isOptional(target) || target.endsWith('!'))) : wrapped;
691
+ }
697
692
  const viewedStatics = /^(\w+)\.Type$/.exec(source)?.[1];
698
693
  if (viewedStatics && this.classNamed(viewedStatics) && this.states.viewedStatics(this.classNamed(viewedStatics)) && /^\w+$/.test(target) && this.isObjectShape(target))
699
694
  return this.viewOf(target, this.expr(e));
@@ -49,6 +49,24 @@ export const protocolsMethods = {
49
49
  this.used.add(i);
50
50
  return { named, met, implemented };
51
51
  },
52
+ /** Whether `cls` (or an app base class) conforms natively to protocol `name` in Swift. */
53
+ conformsToProtocol(cls, name) {
54
+ for (let c = cls; c; c = this.sourceBase(c)) {
55
+ const kitRoot = this.kitRootOf(c);
56
+ const named = implementedInterfaces(this.checker, c).map((i) => ({ name: this.heritageName(i), type: this.checker.getTypeAtLocation(i) }));
57
+ const met = [...(this.structural.get(c) ?? [])].map((d) => ({ name: this.topName(d, d.name.text), type: this.checker.getTypeAtLocation(d.name) }));
58
+ const hit = [...named, ...met].find((i) => i.name === name);
59
+ if (!hit || !isEmittedInterface(hit.type) || isLibDeclaration(hit.type.getSymbol()?.declarations?.[0]) || this.uncompiledType(hit.type))
60
+ continue;
61
+ if ((hit.type.getSymbol()?.declarations ?? []).every((d) => d.getSourceFile().isDeclarationFile && (this.library || !isCoreDeclaration(d) || !this.core.has(hit.name))))
62
+ continue;
63
+ if (kitRoot && hit.type.getProperties().some((p) => !!this.core.kitMember(kitRoot, p.name)))
64
+ continue;
65
+ if (this.protocolWitnesses(c, hit.name, hit.type, [], false))
66
+ return true;
67
+ }
68
+ return false;
69
+ },
52
70
  /**
53
71
  * A component class's conformance to the app interfaces it implements, as an extension of it. Every app protocol
54
72
  * refines JSDynamic, which here reads and writes the interfaces' fields only.
@@ -96,7 +114,7 @@ export const protocolsMethods = {
96
114
  * `handlerError(error: Error)`) conforms through a witness of the protocol's
97
115
  * signature that calls it; any other difference leaves the protocol out.
98
116
  */
99
- protocolWitnesses(cls, name, type, out) {
117
+ protocolWitnesses(cls, name, type, out, record = true) {
100
118
  const decl = type.getSymbol()?.declarations?.find(ts.isInterfaceDeclaration);
101
119
  if (!decl || !this.protocols.has(name))
102
120
  return true;
@@ -144,10 +162,13 @@ export const protocolsMethods = {
144
162
  const args = want.map((_, k) => `__p${k}`);
145
163
  const call = this.marks.tryCode(`self.${ident(name)}(${args.map((a, k) => (have[k] === want[k] ? a : erased(have[k], k) ? this.marks.ownTried(`${RT.jsChecked}(${a}, ${metatype(have[k])})`) : `${a} as Any?`)).join(', ')})`);
146
164
  const body = ret === 'Void' ? call : ownRet === 'Void' ? `${call}; return nil` : byResult ? `let __r: ${ownRet} = ${call}; return __r` : `return ${call}`;
147
- added.push(` func ${ident(name)}(${want.map((t, k) => `_ ${args[k]}: ${t}`).join(', ')}) throws${ret === 'Void' ? '' : ` -> ${ret}`} { ${body} }`);
148
- this.declare(name, { kind: 'func', params: want.map((t, k) => `_ ${args[k]}: ${t}`).join(', '), throws: true, type: ret });
165
+ if (record) {
166
+ added.push(` func ${ident(name)}(${want.map((t, k) => `_ ${args[k]}: ${t}`).join(', ')}) throws${ret === 'Void' ? '' : ` -> ${ret}`} { ${body} }`);
167
+ this.declare(name, { kind: 'func', params: want.map((t, k) => `_ ${args[k]}: ${t}`).join(', '), throws: true, type: ret });
168
+ }
149
169
  }
150
- out.push(...added);
170
+ if (record)
171
+ out.push(...added);
151
172
  return true;
152
173
  },
153
174
  };
@@ -129,10 +129,6 @@ export const resultsMethods = {
129
129
  }
130
130
  return this.undefinedAs(slot.raw, t, slot.target);
131
131
  },
132
- /** The slot of the await `e` is, where its continuation holds the value optional. */
133
- awaited(e) {
134
- return this.awaitSlots.get(ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses));
135
- },
136
132
  /** A local Swift holds optional though its type says a value (`const x = f()` of a call that may give nothing). */
137
133
  heldOptionalLocal(e, type) {
138
134
  e = ts.skipOuterExpressions(e, ts.OuterExpressionKinds.Parentheses);
@@ -182,19 +182,7 @@ export const statementsMethods = {
182
182
  });
183
183
  return forward;
184
184
  },
185
- block(b, base) {
186
- if (base === undefined)
187
- base = this.indent;
188
- const saved = this.indent;
189
- this.indent = base + ' ';
190
- try {
191
- const body = this.statements(ts.isBlock(b) ? [...b.statements] : [b]);
192
- return `{\n${body.join('\n')}\n${base}}`;
193
- }
194
- finally {
195
- this.indent = saved;
196
- }
197
- },
185
+ /* block is installed from semantics/lowering-methods.ts */
198
186
  stmt(s) {
199
187
  try {
200
188
  return HELD_LOSS ? atLossSite('swift', this, s, () => this.stmtChecked(s)) : this.stmtChecked(s);
@@ -305,16 +305,6 @@ export class Translator {
305
305
  }
306
306
  freshCounts = null;
307
307
  programFreshCounts = new Map();
308
- nested(body) {
309
- const saved = this.indent;
310
- this.indent += ' ';
311
- try {
312
- return body();
313
- }
314
- finally {
315
- this.indent = saved;
316
- }
317
- }
318
308
  /** Translates a function's body: no async region or loop of the enclosing function reaches into it. */
319
309
  inFunction(returnType, body) {
320
310
  const refined = this.refinedVersion;
@@ -622,8 +622,8 @@ export interface KotlinTranslatorView extends TranslatorView {
622
622
  statics: string[];
623
623
  };
624
624
  }
625
- /** A refusal's class: JavaScript a compiled release cannot run by design (`limit`), or code the compiler does not translate yet (`gap`). */
626
- export type RefusalClass = 'limit' | 'gap';
625
+ /** A refusal's class: fundamentally incompatible with an engine-free release (`limit`), technically possible but intentionally excluded by design (`excluded`), or not translated yet (`gap`). */
626
+ export type RefusalClass = 'limit' | 'excluded' | 'gap';
627
627
  /** A kind of refusal: its title, suggestion and example, as a build's refusal report shows them. */
628
628
  export interface RefusalKind {
629
629
  class: RefusalClass;
@@ -636,7 +636,7 @@ export interface RefusalKind {
636
636
  why?: string;
637
637
  }
638
638
  /** The ids of the compiler's own refusals, which a hook may refuse with too. */
639
- export type CompilerRefusalId = 'proxy' | 'reflect' | 'eval' | 'function-constructor' | 'finalization-registry' | 'shared-array-buffer' | 'atomics' | 'with' | 'computed-import' | 'computed-require' | 'arguments-callee' | 'proto' | 'process-env' | 'undefined-constant' | 'shared-typed-copy' | 'shared-copy' | 'lone-surrogate' | 'generic-any-argument' | 'generic-field-overload' | 'generic-field-erased' | 'array-hole' | 'function-arguments' | 'builtin-prototype' | 'object-call' | 'library-member' | 'function-value' | 'other-receiver' | 'builtin-receiver' | 'function-new' | 'wrapper-object' | 'class-prototype' | 'function-this' | 'element-accessor' | 'private-receiver' | 'finally-jump' | 'class-expression' | 'named-function-expression' | 'unsupported-base' | 'worker' | 'delete-member' | 'index-type' | 'native' | 'internal' | 'unhandled';
639
+ export type CompilerRefusalId = 'proxy' | 'reflect' | 'eval' | 'function-constructor' | 'finalization-registry' | 'shared-array-buffer' | 'atomics' | 'with' | 'computed-import' | 'computed-require' | 'arguments-callee' | 'proto' | 'process-env' | 'undefined-constant' | 'shared-typed-copy' | 'shared-copy' | 'lone-surrogate' | 'generic-any-argument' | 'generic-field-overload' | 'generic-field-erased' | 'array-hole' | 'function-arguments' | 'builtin-prototype' | 'object-call' | 'library-member' | 'function-value' | 'other-receiver' | 'builtin-receiver' | 'function-new' | 'wrapper-object' | 'class-prototype' | 'function-this' | 'element-accessor' | 'private-receiver' | 'finally-jump' | 'class-expression' | 'named-function-expression' | 'unsupported-base' | 'delete-member' | 'index-type' | 'native' | 'internal' | 'unhandled';
640
640
  /** The id of a refusal a build reports: the compiler's own, or its framework adapter's (`AdapterRefusalIds`). */
641
641
  export type RefusalId = CompilerRefusalId | keyof AdapterRefusalIds;
642
642
  /**
@@ -69,11 +69,15 @@ open class JSArray<T>(storage: ArrayList<T>) : Iterable<T>, JSReactiveConvertibl
69
69
  return read(i.toInt())
70
70
  }
71
71
 
72
- operator fun get(i: Int): T {
73
- track()
74
- return read(i)
72
+ private fun readTracked(i: Int): T {
73
+ jsTracker!!.track()
74
+ val v = storage[i]
75
+ jsReactiveAny(v)
76
+ return v
75
77
  }
76
78
 
79
+ operator fun get(i: Int): T = if (jsTracker == null) storage[i] else readTracked(i)
80
+
77
81
  operator fun get(i: Double): T = get(i.toInt())
78
82
 
79
83
  /** Indices a write past the end skipped (`a[1] = x` of an empty array): holes, which `for…in` and `Object.keys` leave out. */
@@ -424,60 +428,92 @@ open class JSArray<T>(storage: ArrayList<T>) : Iterable<T>, JSReactiveConvertibl
424
428
  }
425
429
 
426
430
  fun forEach(f: (T) -> Unit) {
431
+ val list = storage
427
432
  val n = size
428
433
  var i = 0
429
- while (i < n && i < storage.size) { f(read(i)); i++ }
434
+ if (jsTracker == null) {
435
+ while (i < n && i < list.size) { f(list[i]); i++ }
436
+ } else {
437
+ while (i < n && i < list.size) { f(read(i)); i++ }
438
+ }
430
439
  }
431
440
 
432
441
  fun forEach(f: (T, Double) -> Unit) {
442
+ val list = storage
433
443
  val n = size
434
444
  var i = 0
435
- while (i < n && i < storage.size) { f(read(i), i.toDouble()); i++ }
445
+ if (jsTracker == null) {
446
+ while (i < n && i < list.size) { f(list[i], i.toDouble()); i++ }
447
+ } else {
448
+ while (i < n && i < list.size) { f(read(i), i.toDouble()); i++ }
449
+ }
436
450
  }
437
451
 
438
452
  fun forEach(f: (T, Double, JSArray<T>) -> Unit) {
453
+ val list = storage
439
454
  val n = size
440
455
  var i = 0
441
- while (i < n && i < storage.size) { f(read(i), i.toDouble(), this); i++ }
456
+ while (i < n && i < list.size) { f(read(i), i.toDouble(), this); i++ }
442
457
  }
443
458
 
444
459
  fun <U> map(f: (T) -> U): JSArray<U> {
460
+ val list = storage
445
461
  val n = size
446
462
  val out = ArrayList<U>(n)
447
463
  var i = 0
448
- while (i < n && i < storage.size) { out.add(f(read(i))); i++ }
464
+ if (jsTracker == null) {
465
+ while (i < n && i < list.size) { out.add(f(list[i])); i++ }
466
+ } else {
467
+ while (i < n && i < list.size) { out.add(f(read(i))); i++ }
468
+ }
449
469
  return JSArray(out)
450
470
  }
451
471
 
452
472
  fun <U> map(f: (T, Double) -> U): JSArray<U> {
473
+ val list = storage
453
474
  val n = size
454
475
  val out = ArrayList<U>(n)
455
476
  var i = 0
456
- while (i < n && i < storage.size) { out.add(f(read(i), i.toDouble())); i++ }
477
+ if (jsTracker == null) {
478
+ while (i < n && i < list.size) { out.add(f(list[i], i.toDouble())); i++ }
479
+ } else {
480
+ while (i < n && i < list.size) { out.add(f(read(i), i.toDouble())); i++ }
481
+ }
457
482
  return JSArray(out)
458
483
  }
459
484
 
460
485
  fun <U> map(f: (T, Double, JSArray<T>) -> U): JSArray<U> {
486
+ val list = storage
461
487
  val n = size
462
488
  val out = ArrayList<U>(n)
463
489
  var i = 0
464
- while (i < n && i < storage.size) { out.add(f(read(i), i.toDouble(), this)); i++ }
490
+ while (i < n && i < list.size) { out.add(f(read(i), i.toDouble(), this)); i++ }
465
491
  return JSArray(out)
466
492
  }
467
493
 
468
494
  fun filter(f: (T) -> Boolean): JSArray<T> {
495
+ val list = storage
469
496
  val n = size
470
497
  val out = ArrayList<T>()
471
498
  var i = 0
472
- while (i < n && i < storage.size) { val v = read(i); if (f(v)) out.add(v); i++ }
499
+ if (jsTracker == null) {
500
+ while (i < n && i < list.size) { val v = list[i]; if (f(v)) out.add(v); i++ }
501
+ } else {
502
+ while (i < n && i < list.size) { val v = read(i); if (f(v)) out.add(v); i++ }
503
+ }
473
504
  return JSArray(out)
474
505
  }
475
506
 
476
507
  fun filter(f: (T, Double) -> Boolean): JSArray<T> {
508
+ val list = storage
477
509
  val n = size
478
510
  val out = ArrayList<T>()
479
511
  var i = 0
480
- while (i < n && i < storage.size) { val v = read(i); if (f(v, i.toDouble())) out.add(v); i++ }
512
+ if (jsTracker == null) {
513
+ while (i < n && i < list.size) { val v = list[i]; if (f(v, i.toDouble())) out.add(v); i++ }
514
+ } else {
515
+ while (i < n && i < list.size) { val v = read(i); if (f(v, i.toDouble())) out.add(v); i++ }
516
+ }
481
517
  return JSArray(out)
482
518
  }
483
519
 
@@ -507,9 +543,14 @@ open class JSArray<T>(storage: ArrayList<T>) : Iterable<T>, JSReactiveConvertibl
507
543
 
508
544
  fun <U> reduce(f: (U, T) -> U, initial: U): U {
509
545
  var acc = initial
546
+ val list = storage
510
547
  val n = size
511
548
  var i = 0
512
- while (i < n && i < storage.size) { acc = f(acc, read(i)); i++ }
549
+ if (jsTracker == null) {
550
+ while (i < n && i < list.size) { acc = f(acc, list[i]); i++ }
551
+ } else {
552
+ while (i < n && i < list.size) { acc = f(acc, read(i)); i++ }
553
+ }
513
554
  return acc
514
555
  }
515
556
 
@@ -109,7 +109,7 @@ private class JSONParser(val source: String) {
109
109
  value = top.array
110
110
  }
111
111
  is Container.Object -> {
112
- top.obj[top.key] = value
112
+ top.obj.defineParsed(top.key, value)
113
113
  if (peek() == ','.code) {
114
114
  position++
115
115
  skipWhitespace()
@@ -365,7 +365,7 @@ interface JSToJSON {
365
365
 
366
366
  /** SerializeJSONProperty and its kin, writing into one builder. */
367
367
  private class JSONWriter(val gap: String?) {
368
- private val out = StringBuilder()
368
+ private val out = StringBuilder(256)
369
369
  /** The arrays and objects being written, outermost first, and the key each is written under (for a cycle's message). */
370
370
  private val holders = ArrayList<Any>()
371
371
  private val holderKeys = ArrayList<String>()
@@ -382,8 +382,12 @@ private class JSONWriter(val gap: String?) {
382
382
  */
383
383
  private fun property(holder: Any?, key: String?, index: Int, value: Any?, depth: Int): Boolean {
384
384
  var v = jsBox(value)
385
- if (v is JSToJSON) v = jsBox(v.jsToJSON(key ?: index.toString()))
386
- else if (v is JSDynamic && v !is JSError) {
385
+ if (v is JSObject) {
386
+ val toJSON = if (v.isPlainFast) v.storage["toJSON"] else v.jsGet("toJSON")
387
+ if (toJSON is Function<*>) v = jsBox(jsCall(toJSON, key ?: index.toString()))
388
+ } else if (v is JSToJSON) {
389
+ v = jsBox(v.jsToJSON(key ?: index.toString()))
390
+ } else if (v is JSDynamic && v !is JSError) {
387
391
  val toJSON = v.jsGet("toJSON")
388
392
  if (toJSON is Function<*>) v = jsBox(jsCall(toJSON, key ?: index.toString()))
389
393
  }
@@ -415,6 +419,7 @@ private class JSONWriter(val gap: String?) {
415
419
  is Pair<*, *> -> array(v, key ?: index.toString(), listOf(v.first, v.second), depth)
416
420
  is Triple<*, *, *> -> array(v, key ?: index.toString(), listOf(v.first, v.second, v.third), depth)
417
421
  is JSRegExp -> out.append("{}")
422
+ is JSObject -> if (v.isPlainFast && allowed == null && replacer == null) plainObj(v, key ?: index.toString(), depth) else obj(v, key ?: index.toString(), depth)
418
423
  is JSDynamic -> obj(v, key ?: index.toString(), depth)
419
424
  else -> out.append("{}")
420
425
  }
@@ -497,6 +502,27 @@ private class JSONWriter(val gap: String?) {
497
502
  leave()
498
503
  }
499
504
 
505
+ /** Fast path for a plain JSObject with no replacer, filter, slots, prototype, or reactive tracker. */
506
+ private fun plainObj(owner: JSObject, key: String, depth: Int) {
507
+ enter(key, owner)
508
+ val keys = owner.namedKeys
509
+ val map = owner.storage
510
+ out.append('{')
511
+ var written = false
512
+ for (i in 0 until keys.size) {
513
+ val k = keys[i]
514
+ val mark = out.length
515
+ if (written) out.append(',')
516
+ newline(depth + 1)
517
+ appendJSONQuoted(out, k)
518
+ out.append(if (gap == null) ":" else ": ")
519
+ if (property(owner, k, -1, map[k], depth + 1)) written = true else out.setLength(mark)
520
+ }
521
+ if (written) newline(depth)
522
+ out.append('}')
523
+ leave()
524
+ }
525
+
500
526
  /** SerializeJSONObject: the keys as they are on entry, each value read as it is written. */
501
527
  private fun obj(owner: JSDynamic, key: String, depth: Int) {
502
528
  enter(key, owner)
@@ -356,6 +356,39 @@ fun <T : Any> jsMethodReceiver(self: Any?, own: T, cls: Class<*>): T = if (cls.i
356
356
  /** A method read from a prototype for an instance (`View.prototype._setMinWidthNative`): the instance is its `this`. */
357
357
  fun jsBoundTo(value: Any?, receiver: Any?): Any? = if (value is JSMethod) JSFunction { args -> value.call(receiver, args.toTypedArray()) } else value
358
358
 
359
+ /** Zero-vararg exact-arity fast paths for `jsCallMethod` (0–3 arguments). */
360
+ fun jsCallMethod(target: Any?, key: String): Any? {
361
+ if ((key == "bind" || key == "call" || key == "apply") && jsIsFunction(target)) return jsCallMethod(target, key, *JS_EMPTY_ARGS)
362
+ var f = jsGet(target, key)
363
+ if (jsBox(f) == null && jsBox(target) is JSDynamic && JSPrototypes.objectPrototype.has(key)) f = JSPrototypes.objectPrototype[key]
364
+ if (f is JSMethod) return jsBox(f.call(target, JS_EMPTY_ARGS))
365
+ return jsCall(f)
366
+ }
367
+
368
+ fun jsCallMethod(target: Any?, key: String, a0: Any?): Any? {
369
+ if ((key == "bind" || key == "call" || key == "apply") && jsIsFunction(target)) return jsCallMethod(target, key, *arrayOf(a0))
370
+ var f = jsGet(target, key)
371
+ if (jsBox(f) == null && jsBox(target) is JSDynamic && JSPrototypes.objectPrototype.has(key)) f = JSPrototypes.objectPrototype[key]
372
+ if (f is JSMethod) return jsBox(f.call(target, arrayOf(a0)))
373
+ return jsCall(f, a0)
374
+ }
375
+
376
+ fun jsCallMethod(target: Any?, key: String, a0: Any?, a1: Any?): Any? {
377
+ if ((key == "bind" || key == "call" || key == "apply") && jsIsFunction(target)) return jsCallMethod(target, key, *arrayOf(a0, a1))
378
+ var f = jsGet(target, key)
379
+ if (jsBox(f) == null && jsBox(target) is JSDynamic && JSPrototypes.objectPrototype.has(key)) f = JSPrototypes.objectPrototype[key]
380
+ if (f is JSMethod) return jsBox(f.call(target, arrayOf(a0, a1)))
381
+ return jsCall(f, a0, a1)
382
+ }
383
+
384
+ fun jsCallMethod(target: Any?, key: String, a0: Any?, a1: Any?, a2: Any?): Any? {
385
+ if ((key == "bind" || key == "call" || key == "apply") && jsIsFunction(target)) return jsCallMethod(target, key, *arrayOf(a0, a1, a2))
386
+ var f = jsGet(target, key)
387
+ if (jsBox(f) == null && jsBox(target) is JSDynamic && JSPrototypes.objectPrototype.has(key)) f = JSPrototypes.objectPrototype[key]
388
+ if (f is JSMethod) return jsBox(f.call(target, arrayOf(a0, a1, a2)))
389
+ return jsCall(f, a0, a1, a2)
390
+ }
391
+
359
392
  /** `object.method(args)` on an untyped object: a method sees the object as `this`. */
360
393
  fun jsCallMethod(target: Any?, key: String, vararg args: Any?): Any? {
361
394
  // `fn.call(thisArg, …)`, `fn.apply(thisArg, list)` of a function value: a method sees `thisArg`, any other function ignores it.
@@ -105,6 +105,14 @@ object JSPrototypes {
105
105
  return objectPrototype
106
106
  }
107
107
 
108
+ /** `Object.getPrototypeOf` of a class constructor: its superclass, else `Function.prototype`. */
109
+ fun prototypeOfClass(cls: Class<*>): Any? {
110
+ if (customPrototypes.containsKey(cls)) return customPrototypes[cls]
111
+ val superclass = cls.superclass
112
+ if (superclass != null && superclass != Any::class.java) return superclass
113
+ return builtin("Function")
114
+ }
115
+
108
116
  /** The nearest prototype in a class's chain that has the key. */
109
117
  fun holder(cls: Class<*>, key: String): JSObject? {
110
118
  if (table.isEmpty() && declared.isEmpty()) return null
@@ -176,7 +184,7 @@ fun jsGetPrototypeOf(value: Any?): Any? = when (val v = jsBox(value)) {
176
184
  null, JSNull -> throw JSException(JSTypeError("Cannot convert undefined or null to object"))
177
185
  is JSObject -> JSPrototypes.prototypeOf(v)
178
186
  is JSRecord<*> -> JSPrototypes.prototypeOf(v.obj)
179
- is Class<*> -> JSPrototypes.builtin("Function")
187
+ is Class<*> -> JSPrototypes.prototypeOfClass(v)
180
188
  is JSArray<*>, is Pair<*, *>, is Triple<*, *, *> -> JSPrototypes.builtin("Array")
181
189
  is String -> JSPrototypes.builtin("String")
182
190
  is Boolean -> JSPrototypes.builtin("Boolean")