├── .DS_Store ├── test-runner ├── tests.js ├── tests.html └── assert.js ├── test ├── type-declarations.js ├── basic.js └── sub-typing.js ├── LICENSE ├── TypedObject.js └── explainer.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tschneidereit/proposal-typed-objects/HEAD/.DS_Store -------------------------------------------------------------------------------- /test-runner/tests.js: -------------------------------------------------------------------------------- 1 | import {} from "../test/basic.js"; 2 | import {} from "../test/type-declarations.js"; 3 | import {} from "../test/sub-typing.js"; 4 | -------------------------------------------------------------------------------- /test-runner/tests.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /test/type-declarations.js: -------------------------------------------------------------------------------- 1 | /*--- 2 | flags: [module] 3 | ---*/ 4 | 5 | import { StructType } from "./../TypedObject.js"; 6 | 7 | const LinkedList = StructType.declare("LinkedList"); 8 | LinkedList.define([{ name: "next", type: LinkedList }], []); 9 | 10 | let list = new LinkedList(); 11 | list.next = new LinkedList(); 12 | 13 | assert(list instanceof LinkedList); 14 | assert(list.next instanceof LinkedList); 15 | assert.sameValue(list.next.next, null); 16 | -------------------------------------------------------------------------------- /test/basic.js: -------------------------------------------------------------------------------- 1 | /*--- 2 | flags: [module] 3 | ---*/ 4 | 5 | import { StructType, int32 } from "./../TypedObject.js"; 6 | 7 | const Point2D = new StructType( 8 | [{ name: "x", type: int32 }, { name: "y", type: int32 }], 9 | [], 10 | "Point2D" 11 | ); 12 | 13 | const Line = new StructType( 14 | [{ name: "start", type: Point2D }, { name: "end", type: Point2D }], 15 | [ 16 | { 17 | name: "length", 18 | get: function length() { 19 | return Math.sqrt((this.end.x - this.start.x) ** 2 + (this.end.y - this.start.y) ** 2); 20 | } 21 | }, 22 | { 23 | name: "moveStart", 24 | value: function moveStart(dX, dY) { 25 | this.start.x += dX; 26 | this.start.y += dY; 27 | } 28 | } 29 | ], 30 | "Line" 31 | ); 32 | 33 | let start = new Point2D(10); 34 | assert.sameValue(start.x, 10); 35 | assert.sameValue(start[0], 10); 36 | assert.sameValue(start.y, 0); 37 | assert.sameValue(start[1], 0); 38 | 39 | let line = new Line(start); 40 | assert.sameValue(line.start, start); 41 | assert.sameValue(line[0], start); 42 | assert.sameValue(line.end, null); 43 | assert.sameValue(line[1], line.end); 44 | 45 | line.end = Point2D.fromObject({ x: "10", y: 20.5 }); 46 | assert.sameValue(line.length, 20); 47 | line.moveStart(10, 20); 48 | assert.sameValue(line.length, 10); 49 | 50 | let end = new Point2D(); 51 | line.end = end; 52 | assert.sameValue(line.end, end); 53 | assert.sameValue(line[1], end); 54 | line[1] = new Point2D(); 55 | assert.notSameValue(line.end, end); 56 | assert.sameValue(line.end, line[1]); 57 | 58 | // TODO: enable these once typed objects really do have fields as own properties 59 | // assert(line.hasOwnProperty(0)); 60 | // assert(line.hasOwnProperty(1)); 61 | assert(!line.hasOwnProperty(2)); 62 | assert(!line.hasOwnProperty("start")); 63 | assert(!line.hasOwnProperty("end")); 64 | 65 | assert.throws(TypeError, () => { 66 | new StructType([{ name: "member", type: int32}, {name: "member", type: int32}], [], "Type"); 67 | }, "Repeating named typed field"); 68 | 69 | assert.throws(TypeError, () => { 70 | new StructType([{ name: "member", type: int32}], [{name: "member", value: 42}], [], "Type"); 71 | }, "Repeating named typed field as untyped member"); 72 | 73 | assert.throws(TypeError, () => { 74 | new StructType([], [{ name: "member", type: 7}, {name: "member", value: 42}], [], "Type"); 75 | }, "Repeating untyped member"); 76 | -------------------------------------------------------------------------------- /test/sub-typing.js: -------------------------------------------------------------------------------- 1 | /*--- 2 | flags: [module] 3 | ---*/ 4 | 5 | import { StructType, int32, float32 } from "./../TypedObject.js"; 6 | 7 | const Point2D = new StructType( 8 | [{ name: "x", type: int32 }, { name: "y", type: int32 }], 9 | [], 10 | "Point2D" 11 | ); 12 | const Point3D = new StructType(Point2D, [{ name: "z", type: int32 }], [], "Point3D"); 13 | 14 | let start = new Point3D(0, 1, 2); 15 | assert(start instanceof Point3D); 16 | assert(start instanceof Point2D); 17 | 18 | const Line = new StructType( 19 | [{ name: "start", type: Point2D }, { name: "end", type: Point2D }], 20 | [], 21 | "Line" 22 | ); 23 | 24 | let line = new Line(start, new Point3D(4, 5, 6)); 25 | assert.sameValue(line.start, start); 26 | assert(line.end instanceof Point3D); 27 | assert(line.end instanceof Point2D); 28 | 29 | assert.throws(TypeError, () => { 30 | const InvalidOverride = new StructType(Point2D, [{ name: "x", type: float32 }], [], "Invalid"); 31 | }, "Overriding value typed field with wrong value type"); 32 | 33 | assert.throws(TypeError, () => { 34 | const InvalidOverride = new StructType(Point2D, [{ name: "x", type: Point2D }], [], "Invalid"); 35 | }, "Overriding value typed field with struct type"); 36 | 37 | assert.throws(TypeError, () => { 38 | const InvalidOverride = new StructType(Line, [{ name: "start", type: float32 }], [], "Invalid"); 39 | }, "Overriding struct type field with value type"); 40 | 41 | assert.throws(TypeError, () => { 42 | const InvalidOverride = new StructType(Point2D, [], [{ name: "x", value: 42 }], "Invalid"); 43 | }, "Overriding typed field with untyped member"); 44 | 45 | assert.throws(TypeError, () => { 46 | const Base = new StructType([], [{ name: "member", value: 42}], "Base"); 47 | const InvalidOverride = new StructType(Base, [{ name: "member", type: int32 }], [], "Invalid"); 48 | }, "Overriding untyped member with typed field"); 49 | 50 | assert.throws(TypeError, () => { 51 | const InvalidOverride = new StructType(Point2D, [{ name: "x", type: int32, readonly: true }], [], "Invalid"); 52 | }, "Overriding readonly typed field with read-write field"); 53 | 54 | assert.throws(TypeError, () => { 55 | const Base = new StructType([{ name: "member", type: int32, readonly: true}], [], "Base"); 56 | const InvalidOverride = new StructType(Base, [{ name: "member", type: int32, readonly: false}], [], "Invalid"); 57 | }, "Overriding read-write typed field with readonly field"); 58 | -------------------------------------------------------------------------------- /test-runner/assert.js: -------------------------------------------------------------------------------- 1 | // Copyright (C) 2017 Ecma International. All rights reserved. 2 | // This code is governed by the BSD license found in the LICENSE file. 3 | /*--- 4 | description: | 5 | Collection of assertion functions used throughout test262 6 | ---*/ 7 | 8 | function assert(mustBeTrue, message) { 9 | if (mustBeTrue === true) { 10 | return; 11 | } 12 | 13 | if (message === undefined) { 14 | message = 'Expected true but got ' + String(mustBeTrue); 15 | } 16 | $ERROR(message); 17 | } 18 | 19 | assert._isSameValue = function (a, b) { 20 | if (a === b) { 21 | // Handle +/-0 vs. -/+0 22 | return a !== 0 || 1 / a === 1 / b; 23 | } 24 | 25 | // Handle NaN vs. NaN 26 | return a !== a && b !== b; 27 | }; 28 | 29 | assert.sameValue = function (actual, expected, message) { 30 | if (assert._isSameValue(actual, expected)) { 31 | return; 32 | } 33 | 34 | if (message === undefined) { 35 | message = ''; 36 | } else { 37 | message += ' '; 38 | } 39 | 40 | message += 'Expected SameValue(«' + String(actual) + '», «' + String(expected) + '») to be true'; 41 | 42 | $ERROR(message); 43 | }; 44 | 45 | assert.notSameValue = function (actual, unexpected, message) { 46 | if (!assert._isSameValue(actual, unexpected)) { 47 | return; 48 | } 49 | 50 | if (message === undefined) { 51 | message = ''; 52 | } else { 53 | message += ' '; 54 | } 55 | 56 | message += 'Expected SameValue(«' + String(actual) + '», «' + String(unexpected) + '») to be false'; 57 | 58 | $ERROR(message); 59 | }; 60 | 61 | assert.throws = function (expectedErrorConstructor, func, message) { 62 | if (typeof func !== "function") { 63 | $ERROR('assert.throws requires two arguments: the error constructor ' + 64 | 'and a function to run'); 65 | return; 66 | } 67 | if (message === undefined) { 68 | message = ''; 69 | } else { 70 | message += ' '; 71 | } 72 | 73 | try { 74 | func(); 75 | } catch (thrown) { 76 | if (typeof thrown !== 'object' || thrown === null) { 77 | message += 'Thrown value was not an object!'; 78 | $ERROR(message); 79 | } else if (thrown.constructor !== expectedErrorConstructor) { 80 | message += 'Expected a ' + expectedErrorConstructor.name + ' but got a ' + thrown.constructor.name; 81 | $ERROR(message); 82 | } 83 | return; 84 | } 85 | 86 | message += 'Expected a ' + expectedErrorConstructor.name + ' to be thrown but no exception was thrown at all'; 87 | $ERROR(message); 88 | }; 89 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /TypedObject.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Mozilla Foundation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | const { freeze, seal, defineProperty } = Object; 16 | 17 | export const uint8 = makeNumericCoercer(Uint8Array, "uint8"); 18 | export const uint16 = makeNumericCoercer(Uint16Array, "uint16"); 19 | export const uint32 = makeNumericCoercer(Uint32Array, "uint32"); 20 | export const int8 = makeNumericCoercer(Int8Array, "int8"); 21 | export const int16 = makeNumericCoercer(Int16Array, "int16"); 22 | export const int32 = makeNumericCoercer(Int32Array, "int32"); 23 | export const float32 = makeNumericCoercer(Float32Array, "float32"); 24 | export const float64 = makeNumericCoercer(Float64Array, "float64"); 25 | 26 | export function any(input) { 27 | return input; 28 | } 29 | 30 | export function string(input) { 31 | return input + ""; 32 | } 33 | 34 | export function object(input) { 35 | if (!(typeof input === "object" || typeof input === "function")) { 36 | throw new TypeError(`${input} is not an object`); 37 | } 38 | return input; 39 | } 40 | 41 | export class Struct { 42 | /** 43 | * Creates a new instance of the Struct type. 44 | * 45 | * Initial values are given as indexed parameters, with `undefined` denoting defaulted arguments. 46 | * Non-defaulted arguments have to be of the right type, which for Structs means either the right struct type, or a sub-class of it. 47 | * For primitive values, it means being numeric, or having a `valueOf` implementation that enables coercion to a number. 48 | * No integral or range checks are performed; instead, automatic coercion to the right integer or floating point type is performed. 49 | * 50 | * @param {...any} fieldValues Initial values for all of the Struct's fields 51 | */ 52 | constructor(fieldValues, subClassSignal) { 53 | if (subClassSignal !== properSubClassSignal) { 54 | throw new TypeError( 55 | "Sub-classes of Struct can only be created using the `StructType` constructor" 56 | ); 57 | } 58 | 59 | const structure = new.target.structure(); 60 | const values = []; 61 | 62 | for (let i = 0; i < structure.length; i++) { 63 | const { name, type } = structure[i]; 64 | let value = fieldValues[i]; 65 | 66 | if (typeof value === "undefined") { 67 | value = defaults.get(type); 68 | } else if (structTypes.has(type)) { 69 | if (!(value instanceof type)) { 70 | throw new TypeError( 71 | `Wrong type for argument ${i}: expected instance of ${type.name}, but got ${value}` 72 | ); 73 | } 74 | } else { 75 | value = type(value); 76 | } 77 | 78 | defineProperty(values, i, { value, writable: true }); 79 | } 80 | 81 | freeze(this); 82 | valuesMap.set(this, values); 83 | } 84 | 85 | toString() { 86 | let result = `struct ${this.constructor.name} {`; 87 | const structure = this.constructor.structure(); 88 | for (let i = 0; i < structure.length; i++) { 89 | const field = structure[i]; 90 | const type = field.type; 91 | result += ` ${type.name}(${this[i]}),`; 92 | } 93 | result += ` }`; 94 | return result; 95 | } 96 | 97 | static fromObject(sourceObject = {}) { 98 | const structure = this.structure(); 99 | const values = []; 100 | 101 | for (let i = 0; i < structure.length; i++) { 102 | const { name, type } = structure[i]; 103 | 104 | if (name === undefined) { 105 | name = i; 106 | } 107 | 108 | if (!(name in sourceObject)) { 109 | throw new TypeError(`Field ${name} not found on source object ${sourceObject}`); 110 | } 111 | 112 | let value = sourceObject[name]; 113 | 114 | if (value !== undefined) { 115 | let coercer = coercersMap.get(type) || type; 116 | value = coercer(value); 117 | } else { 118 | value = defaults.get(type); 119 | } 120 | 121 | values.push(value); 122 | } 123 | 124 | return new this(...values, properSubClassSignal); 125 | } 126 | 127 | static structure() { 128 | return structTypes.get(this); 129 | } 130 | 131 | static define(fields, untypedMembers) { 132 | if (!structTypes.has(this)) { 133 | throw new TypeError( 134 | "Struct.define can only be applied to declared but not defined struct types" 135 | ); 136 | } 137 | 138 | if (structTypes.get(this)) { 139 | throw new TypeError(`Struct type ${this.name} already defined`); 140 | } 141 | 142 | const structure = []; 143 | 144 | const baseStructure = this.__proto__.structure(); 145 | for (let i = 0; i < baseStructure.length; i++) { 146 | defineProperty(structure, i, { value: baseStructure[i] }); 147 | } 148 | 149 | structTypes.set(this, structure); 150 | addFields(this, structure, fields); 151 | addUntypedMembers(this, structure, untypedMembers); 152 | 153 | freeze(structure); 154 | seal(this); 155 | } 156 | } 157 | 158 | freeze(Struct); 159 | 160 | export const StructType = function( 161 | baseOrFields, 162 | untypedMembersOrFields, 163 | nameOrUntypedMembers, 164 | name = undefined 165 | ) { 166 | let base = Struct; 167 | let fields; 168 | let untypedMembers; 169 | 170 | if (name !== undefined) { 171 | // If `name` is given, the overload must be 172 | // 0: Base class 173 | // 1: Typed fields 174 | // 2: Untyped fields and methods 175 | // 3: Name 176 | base = baseOrFields; 177 | fields = untypedMembersOrFields; 178 | untypedMembers = nameOrUntypedMembers; 179 | } else { 180 | // Otherwise, it must be 181 | // 1: Typed fields 182 | // 2: Untyped fields and methods 183 | // 2: Name 184 | fields = baseOrFields; 185 | untypedMembers = untypedMembersOrFields; 186 | name = nameOrUntypedMembers; 187 | } 188 | 189 | const def = createStructType(base, name); 190 | def.define(fields, untypedMembers); 191 | 192 | return def; 193 | }; 194 | 195 | StructType.declare = function(nameOrBase, name = undefined) { 196 | let base = nameOrBase; 197 | 198 | if (name === undefined) { 199 | name = nameOrBase; 200 | base = Struct; 201 | } 202 | 203 | return createStructType(base, name); 204 | }; 205 | 206 | function createStructType(base, name) { 207 | class def extends base { 208 | // TODO: properly propagate the subclassing signal through the inheritance chain. 209 | constructor(...fieldValues) { 210 | if (base === Struct) { 211 | super(fieldValues, properSubClassSignal); 212 | } else { 213 | super(...fieldValues); 214 | } 215 | } 216 | } 217 | 218 | defineProperty(def, "name", { value: name }); 219 | 220 | defaults.set(def, null); 221 | coercersMap.set(def, makeStructCoercer(def)); 222 | structTypes.set(def, null); 223 | namedStructMembers.set(def, { __proto__: namedStructMembers.get(base) }); 224 | 225 | return def; 226 | } 227 | 228 | const valuesMap = new WeakMap(); 229 | const coercersMap = new WeakMap(); 230 | 231 | const structTypes = new WeakMap(); 232 | structTypes.set(Struct, freeze([])); 233 | 234 | const namedStructMembers = new WeakMap(); 235 | namedStructMembers.set(Struct, freeze({ __proto__: null })); 236 | 237 | const properSubClassSignal = Symbol("TypedObject struct sub-class"); 238 | 239 | function addFields(typeDefinition, structure, fields) { 240 | let i = structure.length; 241 | for (const { name, type, readonly = false } of fields) { 242 | if (!(structTypes.has(type) || defaults.has(type))) { 243 | throw new TypeError(`Invalid type ${type} for field ${name}`); 244 | } 245 | 246 | // TODO: remove name 247 | const field = freeze({ __proto__: null, name, type, readonly }); 248 | defineProperty(structure, structure.length, { value: field }); 249 | addField(typeDefinition, i, field); 250 | 251 | i++; 252 | } 253 | } 254 | 255 | function addUntypedMembers(typeDefinition, structure, untypedMembers) { 256 | for (const descriptor of untypedMembers) { 257 | addNamedMember(typeDefinition, descriptor.name, descriptor); 258 | } 259 | } 260 | 261 | function addField(typeDefinition, index, { name, type, readonly }) { 262 | function getter() { 263 | return valuesMap.get(this)[index]; 264 | } 265 | 266 | let setter; 267 | if (structTypes.has(type)) { 268 | setter = function(value) { 269 | if (!(value instanceof type)) { 270 | throw new TypeError( 271 | `Wrong type for field "${index}": expected instance of ${type.name}, but got ${value}` 272 | ); 273 | } 274 | valuesMap.get(this)[index] = value; 275 | }; 276 | } else { 277 | setter = function(value) { 278 | valuesMap.get(this)[index] = type(value); 279 | }; 280 | } 281 | 282 | if (readonly) { 283 | setter = function(_) { 284 | throw new TypeError("Can't set readonly field '" + index + "'"); 285 | }; 286 | } 287 | 288 | defineProperty(typeDefinition.prototype, index, { __proto__: null, get: getter, set: setter }); 289 | 290 | if (name) { 291 | addNamedMember(typeDefinition, name, { 292 | __proto__: null, 293 | get: getter, 294 | set: setter, 295 | type, 296 | readonly 297 | }); 298 | } 299 | } 300 | 301 | function addNamedMember(typeDefinition, name, descriptor) { 302 | if (typeof name === "string") { 303 | if (isIndexKey(name)) { 304 | throw new TypeError(`Invalid member name ${name}: member names cannot be valid index keys`); 305 | } 306 | } else if (typeof name !== "symbol") { 307 | throw new TypeError(`Invalid member name ${name}: member names must be strings or symbols`); 308 | } 309 | 310 | const namedMembers = namedStructMembers.get(typeDefinition); 311 | validateOverride(namedMembers, name, descriptor); 312 | defineProperty(namedMembers, name, { value: descriptor }); 313 | 314 | defineProperty(typeDefinition.prototype, name, descriptor); 315 | } 316 | 317 | function validateOverride(namedMembers, name, descriptor) { 318 | const existingMember = namedMembers[name]; 319 | if (!existingMember) { 320 | return; 321 | } 322 | 323 | if (existingMember.readonly) { 324 | throw new TypeError(`Can't override readonly field ${name}`); 325 | } else if (descriptor.readonly) { 326 | throw new TypeError(`Can't override read-write field ${name} with readonly field`); 327 | } 328 | 329 | if (existingMember.type) { 330 | if (!descriptor.type) { 331 | throw new TypeError(`Can't override typed field ${name} with untyped field`); 332 | } else if (existingMember.type !== descriptor.type) { 333 | throw new TypeError(`Can't override typed field ${name}: types must match exactly. Expected ${existingMember.type.name}, got ${descriptor.type.name}`); 334 | } 335 | } else if (descriptor.type) { 336 | throw new TypeError(`Can't override untyped field ${name} with typed field`); 337 | } 338 | } 339 | 340 | function isIndexKey(name) { 341 | return name >>> (0 + "") === name; 342 | } 343 | 344 | const defaults = new WeakMap([ 345 | [uint8, 0], 346 | [uint16, 0], 347 | [uint32, 0], 348 | [int8, 0], 349 | [int16, 0], 350 | [int32, 0], 351 | [float32, 0], 352 | [float64, 0], 353 | [any, undefined], 354 | [string, ""], 355 | [object, null] 356 | ]); 357 | 358 | function makeStructCoercer(structType) { 359 | const structCoercer = input => { 360 | if (input instanceof structType) { 361 | return input; 362 | } 363 | 364 | if (input == null) { 365 | return null; 366 | } 367 | 368 | return structType.fromObject(input); 369 | }; 370 | 371 | defineProperty(structCoercer, "name", { value: structType.name }); 372 | return structCoercer; 373 | } 374 | 375 | function makeNumericCoercer(arrayType, name) { 376 | const typedArray = new arrayType(1); 377 | const numericCoercer = input => { 378 | typedArray[0] = input; 379 | return typedArray[0]; 380 | }; 381 | defineProperty(numericCoercer, "name", { value: name }); 382 | return numericCoercer; 383 | } 384 | -------------------------------------------------------------------------------- /explainer.md: -------------------------------------------------------------------------------- 1 | # Explainer for Typed Objects 2 | 3 | ## Outline 4 | 5 | The explainer proceeds as follows: 6 | 7 | - [Explainer for Typed Objects](#explainer-for-typed-objects) 8 | - [Outline](#outline) 9 | - [Overview](#overview) 10 | - [Characteristics of Struct types](#characteristics-of-struct-types) 11 | - [Types](#types) 12 | - [Value Types](#value-types) 13 | - [Struct Types](#struct-types) 14 | - [Typed field definitions](#typed-field-definitions) 15 | - [Struct Type references](#struct-type-references) 16 | - [Struct Type forward declaration](#struct-type-forward-declaration) 17 | - [Instantiation](#instantiation) 18 | - [Instantiating Struct Types](#instantiating-struct-types) 19 | - [Struct type details](#struct-type-details) 20 | - [Memory layout](#memory-layout) 21 | - [Typed fields](#typed-fields) 22 | - [Reading from typed fields](#reading-from-typed-fields) 23 | - [Writing to typed fields](#writing-to-typed-fields) 24 | - [Immutable typed fields](#immutable-typed-fields) 25 | - [Named typed fields](#named-typed-fields) 26 | - [Inheritance](#inheritance) 27 | - [Layout of subtypes](#layout-of-subtypes) 28 | - [Type-checking for Struct Type references](#type-checking-for-struct-type-references) 29 | - [Overriding named fields](#overriding-named-fields) 30 | - [Exotic behavior of Struct type instances](#exotic-behavior-of-struct-type-instances) 31 | - [Prototypes](#prototypes) 32 | - [Read-only `[[Prototype]]`](#read-only-prototype) 33 | - [Exotic behavior of prototypes](#exotic-behavior-of-prototypes) 34 | 35 | ## Overview 36 | 37 | Typed Objects add a new type of objects to JavaScript: objects with pre-defined storage for member fields with equally pre-defined types. This proposal focuses on mutable Struct types, but the concept is applicable to Value types, too. 38 | 39 | ### Characteristics of Struct types 40 | 41 | Struct Types have these characteristics: 42 | - Fixed layout: a Struct's layout is fixed during construction, i.e. it is sealed during its entire lifetime. 43 | - Indexed typed member fields: a Struct has as own members an indexed list of typed fields, as given in its [definition](#struct-type-definitions). 44 | - Possible field types: typed fields can hold values as described in the [section on Value Type definitions](#value-type-definitions), including references to other Struct type instances. 45 | - Named aliases as `prototype` accessors: typed fields can optionally be given a—String or Symbol—name, in which case an accessor is installed on the `prototype`. 46 | - Support for recursive types: Struct types can be forward-declared and filled in later, enabling support for—directly or indirectly—recursive types. 47 | - Inheritance: Struct types can extend other Struct types (but not other JS classes/constructor functions). Additional typed fields are appended to the end of the parent type's indexed list. 48 | - Prototypes are exotic objects which forbid the definition of properties that shadow typed fields, or have numeric index names. 49 | - Immutable prototype chain—`[[SetPrototypeOf]]` throws when applied to any members of the `Struct` prototype chain. 50 | 51 | See individual sections for more details on these characteristics. 52 | 53 | ## Types 54 | 55 | The central part of the Typed Objects specification are [*Value Types*](#value-types) and [*Struct Types*](#struct-types). Instances of Value Types are immutable and don't have internal structure or object identity: they are primitive values similar to numeric values like `10.5` or `42`, or strings like `"foo"`. Instances of Struct Types are objects like `{ answer: 42 }`, except they have a fixed layout in memory, and each field is defined such that it can hold an instance of a Value Type (and only that, instead of arbitrary values). 56 | 57 | ## Value Types 58 | 59 | The following common Value Types are provided by this spec: 60 | 61 | uint8 int8 any 62 | uint16 int16 string 63 | uint32 int32 float32 object 64 | uint64 int64 float64 ref(T) 65 | 66 | They're exposed as *Function* objects with the internal methods `[[Read]]` and `[[Write]]`, which convert between `Value` and internal representations for the type. `[[Write]]` additionally performs a type-specific type check. Calling the Value Type object as a function executes the steps of the internal `[[Write]]` method followed by those of the internal `[[Read]]` method. I.e., it applies the steps for checking and converting from `Value` into the type's internal representation, and then back to `Value`. 67 | 68 | Host environments can provide additional kinds of Value Types, with their own implementations of `[[Read]]` and `[[Write]]`. 69 | 70 | For all Value Types provided by this specification, `[[Read]]` converts from the internal representation to a value and returns it. The behavior of `[[Write]]` for all types provided by this specification is described below. 71 | 72 | For the numeric types and the `string` type, the implementations of `[[Write]]` apply coercions: they ensure that the given value is of the right type by coercing it. For numeric types, the coercion is identical to [that applied when writing to an element in a Typed Array](https://tc39.github.io/ecma262/#sec-numbertorawbytes). For `string`, it's identical to that applied when coercing a value to string by other means, e.g. when appending it to an existing string: `"existing string" + value`. 73 | 74 | For `object`, a type check without coercion is performed: 75 | 76 | ```js 77 | object("foo") // throws 78 | object({}) // returns the object {} 79 | object(null) // returns null 80 | ``` 81 | 82 | For [`ref(T)`](#struct-type-references), the same kind of type check without coercion is performed, but additionally the object is required to match `T`, in a manner [described below](#type-checking-for-struct-type-references). 83 | 84 | For `any`, the coercion is a no-op, because any kind of value is acceptable: 85 | 86 | ```js 87 | any(x) === x 88 | ``` 89 | 90 | ## Struct Types 91 | 92 | Struct Types are defined using the `StructType` constructor, which has two overloads: 93 | 94 | ```js 95 | function StructType(typedFields, name = undefined) 96 | function StructType(baseType, typedFields, name = undefined) 97 | ``` 98 | 99 | The difference between the two overloads is whether the type inherits from the base Struct Type, `Struct`, or a more specialized type. 100 | 101 | Parameters: 102 | - `baseType` - A `constructor function` whose instances are `instanceof Struct`, i.e. `Struct` or a sub-class of `Struct`. 103 | - `typedFields` - An `Iterable` list of [typed field definitions](#typed-field-definitions). 104 | - `name` [optional] - A `string` used as the type's name. 105 | 106 | ### Typed field definitions 107 | 108 | A typed field definition is an `object` definining the characteristics of a `Struct`'s typed field. It has the following members: 109 | - `type` - A [Value Type](#value-types), specifying the field's type. 110 | - `name` [optional] - A `string` or `symbol` used as an optional name for the field. If given, an accessor is created that allows reading and, if the field is writable, writing the field using a name in addition to its index. 111 | - `readonly` [optional] - A `boolean`. If `true`, the field can only be set via the type's constructor and is immutable afterwards. 112 | 113 | ### Struct Type references 114 | 115 | Just as other JS objects, Struct Type instances are passed by reference. These references are instances of [Value Types](#value-types). Defining a Struct Type using the `StructType` constructor actually defines two types: the Struct Type itself, and an accompanying Value Type for references to instances of the Struct Type. Just as other Value Types, it can be used as the type of a Struct Type's fields. This type is exposed as the `ref` property on the Struct Type's constructor: 116 | ```js 117 | const Point = new StructType([{ name: "x", type: float64 }, { name: "y", type: float64 }]); 118 | const Line = new StructType([{ name: "from", type: Point.ref }, { name: "to", type: Point.ref }]); 119 | ``` 120 | 121 | ### Struct Type forward declaration 122 | 123 | To enable recursive types, it's possible to declare a Struct Type without defining it. Declaration is done using `StructType.declare`, which has two overloads: 124 | ```js 125 | StructType.declare(name) 126 | StructType.declare(baseType, name) 127 | ``` 128 | 129 | The first overload declares a Struct Type that extends `Struct`, the second creates a Struct type that extends the given `baseType`. 130 | 131 | The type can then be defined using its `define` method: 132 | ```js 133 | const LinkedList = StructType.declare("LinkedList"); 134 | LinkedList.define([{ name: "next", type: LinkedList.ref }]); 135 | ``` 136 | 137 | `define` takes a single parameter, `typedFields`, and performs the same steps for defining the type's fields as `new StructType` does. 138 | 139 | 140 | ## Instantiation 141 | 142 | ### Instantiating Struct Types 143 | 144 | You can create an instance of a Struct Type using the `new` operator: 145 | 146 | ```js 147 | const Point = new StructType([{ name: "x", type: float64 }, { name: "y", type: float64 }]); 148 | 149 | let from = new Point(); 150 | console.log(from[0], from.x); // logs "0, 0" 151 | ``` 152 | 153 | The resulting object is called a *typed object*: it will have the fields specified in `Line`. 154 | If no parameters are passed, each field will be initialized to its type's default value: 155 | - `0` for numeric types 156 | - `''` for `string` 157 | - `null` for `object` and Struct Type references 158 | - `undefined` for `any` 159 | 160 | Any parameters passed are used as initial values for the type's typed fields: 161 | 162 | ```js 163 | const Point = new StructType([{ name: "x", type: float64 }, { name: "y", type: float64 }]); 164 | const Line = new StructType([{ name: "from", type: Point.ref }, { name: "to", type: Point.ref }]); 165 | 166 | let from = new Point(42, 7); 167 | let line = new Line(from); 168 | console.log(line.from === from, line[0] === line.from, line.from.x); //logs "true, true, 42" 169 | ``` 170 | 171 | ## Struct type details 172 | 173 | Struct types are specified as a new kind of [Built-in Exotic Object](https://tc39.github.io/ecma262/#sec-built-in-exotic-object-internal-methods-and-slots). They override some internal methods, much like [Integer-Indexed Exotic Objects](https://tc39.github.io/ecma262/#sec-integer-indexed-exotic-objects) do. 174 | 175 | ### Memory layout 176 | 177 | Struct type objects have the following internal slots: 178 | - `[[FieldTypes]]` — A list containing references to each of the type's field's types. 179 | 180 | Struct type instance objects have the following internal slots: 181 | - `[[StructType]]` — An immutable reference to the instance's type. 182 | - `[[Values]]` — A list of the abstract values for all the fields produce by the fields' associated Value Type `[[Write]]` method 183 | 184 | For the `Struct` type itself, `[[FieldTypes]]` is set to an empty list. 185 | 186 | ### Typed fields 187 | 188 | Struct types have their property-access related internal methods overridden to perform type checking and coercion, based on the internal slots described above. 189 | 190 | #### Reading from typed fields 191 | 192 | Reading from a typed field returns the result of converting the internal representation of the field's contents to a value representation, using the field's type's `[[Read]]` method. 193 | 194 | In slightly more detail, a `[[Get]]` operation on a Struct Type instance `O` with property key `P`, and receiver `receiver` performs the following steps: 195 | 1. If [Type](https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values)(P) is `String`, then 196 | 1. Let `numericIndex` be ! [CanonicalNumericIndexString](https://tc39.github.io/ecma262/#sec-canonicalnumericindexstring)(P) . 197 | 2. If `numericIndex` is not *undefined*, then 198 | 1. Let `fieldType` be `O.[[StructType]].[[FieldTypes]][numericIndex]`. 199 | 2. Let `TV` be `O.[[Values]][numericIndex]`. 200 | 3. Return ! `fieldType.[[Read]](TV)`. 201 | 2. Return ? [OrdinaryGet](https://tc39.github.io/ecma262/#sec-ordinaryget)(O, P, Receiver). 202 | 203 | #### Writing to typed fields 204 | 205 | Writing to a typed field stores the result of converting the given value `V` to an internal representation as the field's contents, using the field's type's `[[Write]]` method. 206 | 207 | In slightly more detail, a `[[Set]]` operation on a Struct Type instance `O` with property key `P`, value `V`, and receiver `receiver` performs the following steps: 208 | 1. If [Type](https://tc39.github.io/ecma262/#sec-ecmascript-data-types-and-values)(P) is `String`, then 209 | 1. Let `numericIndex` be ! [CanonicalNumericIndexString](https://tc39.github.io/ecma262/#sec-canonicalnumericindexstring)(P) . 210 | 2. If `numericIndex` is not *undefined*, then 211 | 1. Let `fieldType` be `O.[[StructType]].[[FieldTypes]][numericIndex]`. 212 | 2. Let `TV` be ? `fieldType.[[Write]](V)`. 213 | 3. Set `O.[[Values]][numericIndex]` to `TV`. 214 | 4. Return `V`. 215 | 2. Return ? [OrdinaryGet](https://tc39.github.io/ecma262/#sec-ordinaryget)(O, P, Receiver). 216 | 217 | #### Immutable typed fields 218 | 219 | Typed fields can be marked as `readonly`, in which case any attempt to write to them after the Struct's construction throws an error. 220 | 221 | #### Named typed fields 222 | 223 | When defining a Struct type, its typed fields can optionally be given names. These names can be strings or symbols, with the only restriction being that a string name can't be a valid numeric index, i.e. [CanonicalNumericIndexString](https://tc39.github.io/ecma262/#sec-canonicalnumericindexstring) must return `undefined`. 224 | 225 | If a typed field is named, an accessor with that name will be added to the Struct type's `prototype`. That accessor simply forwards `[[Get]]` and `[[Set]]` operations to the field's numeric index. 226 | 227 | ### Inheritance 228 | 229 | Struct types can extend other Struct types. If no base type is given, a Struct type will extend `Struct`, which is itself a Struct type without any typed fields. 230 | 231 | #### Layout of subtypes 232 | 233 | When initializing a Struct Type object `O` as a subtype of a Struct Type `P`, the supertype's fields are copied and additional fields are appended by extending `O`'s `[[FieldOffsets]]` and `[[FieldTypes]]` internal slots. Instances of the new Struct Type have their `[[Values]]` buffer extended accordingly. 234 | 235 | ### Type-checking for Struct Type references 236 | 237 | The type check for Struct Type references ensures that the given value is an instance of either the specified type itself, or of a sub-type. The applied test has to be stronger than `instanceof`, since that is easily falsifiable, removing the guarantees around the struct's layout and behavior. 238 | 239 | Instead, to facilitate type-checks, Struct type instances have an internal slot `[[StructType]]`, containing a reference to the associated Struct type constructor. Struct type constructors, in turn, have an internal slot `[[BaseType]]`, containing a reference to the type this type extends. For the `Struct` constructor, the value of this field is `null`. 240 | 241 | Given a value `V`, the `[[Write]]` internal method of Struct Type reference types performs the following steps to verify type compatibility for the given value: 242 | 1. Let `O` be `? ToObject(V)`. 243 | 2. If `O` does not have the internal slot `[[StructType]]`, throw a `TypeError` exception. 244 | 3. Let `type` be `O.[[StructType]]`. 245 | 4. Repeat, while `type` is not `null` 246 | 1. If `type` is equal to *expectedType*, return *true*. 247 | 2. Let `type` be `type.[[BaseType]]`. 248 | 249 | *Note: in practice, implementations don't need to, and aren't expected to, perform this expensive test. Well-established [fast subtying checks that are equivalent to this check exist](https://www.researchgate.net/publication/221552851/download).* 250 | 251 | #### Overriding named fields 252 | 253 | Named fields can be overridden, but some restrictions apply: 254 | - A field can't change from mutable to immutable and vice-versa. 255 | - The type of mutable fields is invariant—the field's type must be exactly the same as the overridden field's type. 256 | - The type of immutable fields is covariant—the field's type can be a subtype of the overridden field's type. 257 | 258 | #### Exotic behavior of Struct type instances 259 | 260 | Struct type instances are exotic objects in two ways: 261 | 262 | 1. They are [immutable prototype exotic objects](https://tc39.github.io/ecma262/#sec-immutable-prototype-exotic-objects). See the section on [read-only prototypes](#read-only-prototype) below. 263 | 2. They override the same set of internal methods as [Integer-Indexed Exotic Objects](https://tc39.github.io/ecma262/#sec-integer-indexed-exotic-objects) to provide special handling of integer-index property keys, as [described above](#typed-fields). 264 | 265 | ### Prototypes 266 | 267 | Prototypes are set up the same way as for classes: the constructor function form one prototype chain, starting with `Struct`, and instances have another prototype chain, starting with `Struct.prototype`. 268 | 269 | E.g., for the Struct type `Point` 270 | - the `[[Prototype]]` is set to `Struct` 271 | - the `[[Prototype]]` of instances of `Point` is set to `Point.prototype` 272 | - The `[[Prototype]]` of `Point.prototype` is set to `Struct.prototype` 273 | 274 | #### Read-only `[[Prototype]]` 275 | 276 | The above-described prototype chains are immutable: `[[SetPrototypeOf]]` throws for all objects on the prototype chains. I.e., all these objects are [immutable prototype exotic objects](https://tc39.github.io/ecma262/#sec-immutable-prototype-exotic-objects). 277 | 278 | #### Exotic behavior of prototypes 279 | 280 | The prototypes of Struct instances are exotic objects in two ways: 281 | 1. As described above, they are [immutable prototype exotic objects](https://tc39.github.io/ecma262/#sec-immutable-prototype-exotic-objects). 282 | 2. Their overrides of `[[DefineOwnProperty]]` and `[[Set]]` prevent shadowing of [named typed fields](#named-typed-fields), and defining any integer index property key-named properties. 283 | 284 | Combined, these rules enable the same degree of strong reasoning about a Struct type instance's fields whether it's accessed by its integer index property key, or by its—optional—string or symbol name. This also enables easier and more stable optimization in engines, leading to higher and more predictable performance. 285 | --------------------------------------------------------------------------------