Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 26 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,18 +243,32 @@ Generics (`src/generics/lib.generics.ts`):
- `Atomics`: `add`, `sub`, `and`, `or`, `xor`, `exchange`, `compareExchange`, `load`,
`store`, `isLockFree` over the integer typed arrays, and `wait`/`notify` over an
`Int32Array` or a `BigInt64Array` (no `waitAsync`)
- `Reflect`: `get`, `set`, `has`, `ownKeys`, `isExtensible`, `preventExtensions`, `apply`,
`construct`. A target's keys are looked up at run time, as those of a value of type `any`:
a class's public fields, accessors and methods (of its actual class), an object literal's or a
tuple's fields, an array's indices; `get` gives an `any`. `ownKeys` gives what `Object.keys` does
(no accessors, methods or `"length"`). No object can gain or lose a key, so `set` of a key it does
not have, or of a value its type does not take, is `false`, as is `set` of an object literal (boxed
as `any`, it is a copy); `isExtensible` is `false`. `apply` does not use `thisArgument`. What can't
be done throws a `TypeError` saying the method is not available: `deleteProperty` (keys are fixed),
and, as there are no prototypes or property descriptors, `getPrototypeOf`, `setPrototypeOf`,
`defineProperty`, `getOwnPropertyDescriptor`. The key
operations need the compiler's run-time keys of `any`, so they are not under `-mm=own`; there
`construct` is lent its arguments array, so a constructor can't keep a string or an object from it.
- `ObjectDictionary<T>`, the value of a string index signature (`{ [key: string]: T }`) and of an
object literal with a key known only at run time: the one object that gains and loses keys. The
compiler's `Object` functions take it: `Object.keys`, `getOwnPropertyNames`, `values` and
`entries` give its entries in the order they were added, `Object.hasOwn(d, k)` is `k in d`,
`Object.assign(d, ...sources)` copies each source's fields or entries into it, and
`Object.fromEntries(pairs)` makes one of an array of `[key, value]` pairs.
`Object.preventExtensions`, `seal` and `freeze` close it, and `Object.isExtensible`, `isSealed`
and `isFrozen` say how far; a write it no longer takes then throws a `TypeError`, as in
JavaScript's strict mode. Any other object's keys are fixed when it is made, as a sealed object's
are: `Object.isSealed` of it is `true`, `isExtensible` `false`, and `Object.freeze` of it is the
object itself (not frozen). An array grows, so it is extensible; a number or a string is frozen.
- `Reflect`: `get`, `set`, `has`, `ownKeys`, `deleteProperty`, `isExtensible`,
`preventExtensions`, `apply`, `construct`. A target's keys are looked up at run time, as those of
a value of type `any`: a class's public fields, accessors and methods (of its actual class), an
object literal's or a tuple's fields, an array's indices, a dictionary's entries; `get` gives an
`any`. `ownKeys` gives what `Object.keys` does (no accessors, methods or `"length"`). A
dictionary gains a key by `set` and loses one by `deleteProperty`, until `preventExtensions` (or
`Object.seal`, `Object.freeze`) closes it. Any other object is sealed: `set` of a key it does not
have, or of a value its type does not take, is `false`, as is `set` of an object literal (boxed
as `any`, it is a copy), and `deleteProperty` of a key it has; `isExtensible` is `false`. An array
is extensible but can't be closed: `preventExtensions` of one is `false`. `apply` does not use
`thisArgument`. What can't be done throws a `TypeError` saying the method is not available: as
there are no prototypes or property descriptors, `getPrototypeOf`, `setPrototypeOf`,
`defineProperty`, `getOwnPropertyDescriptor`. The key operations (`deleteProperty` too) need the
compiler's run-time keys of `any`, so they are not under `-mm=own`; there `construct` is lent its
arguments array, so a constructor can't keep a string or an object from it.
- `Thread`: `Thread.spawn(fn)` runs `fn` on a new native thread and returns a `ThreadHandle<R>`
whose `join()` waits for it and gives back `fn`'s result, or throws an `Error` with the message
of what `fn` threw. `Thread.hardwareConcurrency()` says how many threads the machine runs at
Expand Down
102 changes: 92 additions & 10 deletions src/generics/lib.generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1790,12 +1790,15 @@ namespace Atomics {
// at run time by the type it had when it was boxed, as `x[k]`, `k in x` and `Object.keys(x)` of `any`
// look them up - a class's public fields and accessors (its actual class's, a base's too) and its
// methods, an object literal's or a tuple's fields, an array's or a string's indices. A key is a string
// or a number; there are no symbol keys. Under -mm=own, where `any` has no keys, get, set, has and
// ownKeys are compile errors.
// An object's keys are fixed when it is made, so none can be added or removed: isExtensible is false,
// and set of a key the object does not have is false. What can't be done throws a TypeError saying the
// method is not available: deleteProperty (a key can't be removed), and, as there are no prototypes or
// property descriptors, getPrototypeOf, setPrototypeOf, defineProperty and getOwnPropertyDescriptor.
// or a number; there are no symbol keys. Under -mm=own, where `any` has no keys, get, set, has, ownKeys
// and deleteProperty are compile errors.
// A dictionary (`{ [key: string]: T }`, ObjectDictionary) gains and loses keys: set adds one, deleteProperty
// removes one, and it is extensible until preventExtensions (or Object.seal, Object.freeze) closes it. Any
// other object's keys are fixed when it is made, as a sealed object's are: isExtensible is false, set of a
// key it does not have is false, and so is deleteProperty of a key it has. An array is extensible (it grows
// by one past its end) but can't be closed: preventExtensions of one is false. What can't be done throws a
// TypeError saying the method is not available: as there are no prototypes or property descriptors,
// getPrototypeOf, setPrototypeOf, defineProperty and getOwnPropertyDescriptor.
namespace Reflect {
// null and undefined are not objects, a TypeError as in JavaScript. The target is not boxed: under
// -mm=own it stays the caller's.
Expand Down Expand Up @@ -1845,8 +1848,20 @@ namespace Reflect {
throw new TypeError("Reflect." + method + " is not available: " + reason);
}

// true when the target no longer has the key: a dictionary's entry is deleted, unless it is sealed or
// frozen (false); any other object is sealed, false for a key it has
function deleteProperty<T, K>(target: T, propertyKey: K): boolean {
return __notAvailable<boolean>("deleteProperty", "an object's keys are fixed when it is made");
const object = __object(target, "deleteProperty");
if (!(propertyKey in object)) {
return true;
}

if (Object.isSealed(object)) {
return false;
}

delete object[propertyKey];
return true;
}

function defineProperty<T, K, A>(target: T, propertyKey: K, attributes: A): boolean {
Expand All @@ -1865,15 +1880,18 @@ namespace Reflect {
return __notAvailable<boolean>("setPrototypeOf", "there are no prototypes");
}

// by the target's own type, not through `any`: a dictionary that is not closed, or an array
function isExtensible<T>(target: T): boolean {
__checkObject(target, "isExtensible");
return false;
return Object.isExtensible(target);
}

// there is nothing to prevent: no object can gain a key
// true when the target can't gain a key now: a dictionary is closed, an object with fixed keys already
// is; an array can't be (false)
function preventExtensions<T>(target: T): boolean {
__checkObject(target, "preventExtensions");
return true;
Object.preventExtensions(target);
return !Object.isExtensible(target);
}

// `target(...argumentsList)`. A function is not called with a `this` of the caller's choosing:
Expand Down Expand Up @@ -3856,16 +3874,36 @@ class Set<V = any> {
// writes them with `set`; outside this class they are always entries, never these members (@dictionary).
// Under -mm=own it owns its values: a value written in moves in, one read borrows, one overwritten or
// deleted is dropped. The keys are its own copies.
// It is the one object that gains and loses keys, so the one Object.preventExtensions, Object.seal and
// Object.freeze close (the compiler calls `close`; `closed` answers Object.isExtensible, isSealed and
// isFrozen): then a write it no longer takes throws a TypeError, as JavaScript's strict mode does.
@dictionary
class ObjectDictionary<T = any> {
private index: Map<string, int>;
private _keys: string[];
private _values: T[];
// how far it is closed: 0 open, 1 no key added (preventExtensions), 2 nor deleted (seal), 3 nor any
// value written (freeze)
private _closed: int;

constructor() {
this.index = new Map<string, int>();
this._keys = [];
this._values = [];
this._closed = 0;
}

// closes it as far as `level` (closed no less than it was: a frozen dictionary stays frozen)
close(level: int) {
if (level > this._closed) {
this._closed = level;
}
}

// how far it is closed, as JavaScript reports it: one that takes no key and has none is sealed and
// frozen too
closed(): int {
return this._closed > 0 && this._keys.length == 0 ? 3 : this._closed;
}

get size() {
Expand All @@ -3890,13 +3928,21 @@ class ObjectDictionary<T = any> {

const i = this.index.get(key);
if (i === undefined) {
if (this._closed > 0) {
throw new TypeError("Cannot add property " + key + ", object is not extensible");
}

// a copy of the key: the caller's stays the caller's
this.index.set("" + key, this._values.length);
this._keys.push("" + key);
this._values.push(value);
return;
}

if (this._closed == 3) {
throw new TypeError("Cannot assign to read only property '" + key + "' of object");
}

this._values[i] = value;
}

Expand All @@ -3912,6 +3958,10 @@ class ObjectDictionary<T = any> {
return false;
}

if (this._closed >= 2) {
throw new TypeError("Cannot delete property '" + key + "' of object");
}

this.index.delete(key);
this._keys.splice(i, 1);
this._values.splice(i, 1);
Expand All @@ -3937,6 +3987,38 @@ function objectDictionaryAssign<T>(target: ObjectDictionary<T>, source: ObjectDi
}
}

// `Object.values(d)` and `Object.entries(d)` of a dictionary: its values, or its [key, value] pairs, in the
// order its entries were added (the compiler calls them). Functions of their own, as objectDictionaryAssign,
// so that under -mm=own a dictionary of objects, which can't be copied out, fails only where one is used.
function objectDictionaryValues<T>(d: ObjectDictionary<T>): T[] {
const r: T[] = [];
for (const k in d) {
r.push(<T>d[k]);
}

return r;
}

function objectDictionaryEntries<T>(d: ObjectDictionary<T>): [string, T][] {
const r: [string, T][] = [];
for (const k in d) {
r.push([k, <T>d[k]]);
}

return r;
}

// `Object.fromEntries(entries)`: a dictionary of the [key, value] pairs, in their order, a later value of a
// key in place of an earlier one (the compiler calls it, T the pairs' value type). A key is its text.
function objectDictionaryFromEntries<T, E>(entries: E): ObjectDictionary<T> {
const d = new ObjectDictionary<T>();
for (const e of entries) {
d["" + e[0]] = <T>e[1];
}

return d;
}

namespace __Iterator
{
// example how to restrict to iterators only
Expand Down
120 changes: 120 additions & 0 deletions tests/object_dictionary_builtins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
// Object's functions of a dictionary (`{ [key: string]: T }`), the one object that gains and loses keys:
// keys, values and entries in the order its entries were added, hasOwn, assign, fromEntries; closed by
// preventExtensions, seal and freeze, after which a write it no longer takes throws a TypeError. Of any
// other object, whose keys are fixed when it is made, isExtensible is false and isSealed true; an array
// grows, so it is extensible; what is no object is frozen.
function entriesAndAssign() {
const d: { [key: string]: number } = { a: 1, b: 2 };
d["c"] = 3;

assert(Object.keys(d).join(",") == "a,b,c", "keys");
assert(Object.getOwnPropertyNames(d).join(",") == "a,b,c", "getOwnPropertyNames");
assert(Object.values(d).join(",") == "1,2,3", "values");

const entries = Object.entries(d);
assert(entries.length == 3 && entries[1][0] == "b" && entries[1][1] == 2, "entries");

assert(Object.hasOwn(d, "a") && !Object.hasOwn(d, "z"), "hasOwn");

const more: { [key: string]: number } = { c: 30, d: 4 };
const same = Object.assign(d, more, { e: 5 });
assert(Object.keys(same).join(",") == "a,b,c,d,e", "assign adds the sources' keys, in order");
assert(d["c"] == 30 && d["e"] == 5, "assign writes over a key it has");

const pairs: [string, number][] = [["x", 1], ["y", 2], ["x", 3]];
const fromPairs = Object.fromEntries(pairs);
assert(Object.keys(fromPairs).join(",") == "x,y" && fromPairs["x"] == 3, "fromEntries: a later value in place");

const back = Object.fromEntries(Object.entries(d));
assert(Object.values(back).join(",") == "1,2,30,4,5", "fromEntries of entries");
}

function closing() {
const open: { [key: string]: number } = { a: 1 };
assert(Object.isExtensible(open) && !Object.isSealed(open) && !Object.isFrozen(open), "a dictionary is open");

const noMore: { [key: string]: number } = { a: 1, b: 2 };
Object.preventExtensions(noMore);
assert(!Object.isExtensible(noMore) && !Object.isSealed(noMore), "preventExtensions");
let caught = "";
try {
noMore["c"] = 3;
} catch (e) {
caught = (<TypeError>e).message;
}
assert(caught == "Cannot add property c, object is not extensible", "no key added");
noMore["a"] = 10;
delete noMore["b"];
assert(noMore["a"] == 10 && !Object.hasOwn(noMore, "b"), "a key written and deleted");

const sealed: { [key: string]: number } = { a: 1 };
assert(Object.seal(sealed) === sealed, "seal is its object");
assert(Object.isSealed(sealed) && !Object.isFrozen(sealed), "sealed");
sealed["a"] = 2;
caught = "";
try {
delete sealed["a"];
} catch (e) {
caught = (<TypeError>e).message;
}
assert(caught == "Cannot delete property 'a' of object", "no key deleted");
assert(sealed["a"] == 2, "a key written");

const frozen: { [key: string]: number } = { a: 1 };
Object.freeze(frozen);
assert(Object.isFrozen(frozen) && Object.isSealed(frozen) && !Object.isExtensible(frozen), "frozen");
caught = "";
try {
frozen["a"] = 2;
} catch (e) {
caught = (<TypeError>e).message;
}
assert(caught == "Cannot assign to read only property 'a' of object", "no value written");
assert(frozen["a"] == 1, "the value is as it was");

// closed no less than it was
Object.preventExtensions(frozen);
assert(Object.isFrozen(frozen), "still frozen");

// one that takes no key and has none is sealed and frozen too
const empty: { [key: string]: number } = {};
Object.preventExtensions(empty);
assert(Object.isSealed(empty) && Object.isFrozen(empty), "an empty one closed");
}

class Point {
constructor(public x: number) {}

get twice() {
return this.x * 2;
}

norm() {
return this.x;
}
}

function others() {
const p = new Point(1);
assert(!Object.isExtensible(p) && Object.isSealed(p) && !Object.isFrozen(p), "an object's keys are fixed");
assert(Object.freeze(p) === p && p.x == 1, "freeze of an object is the object");
assert(Object.hasOwn(p, "x") && !Object.hasOwn(p, "norm") && !Object.hasOwn(p, "twice"),
"hasOwn: a field, not a method or an accessor");

const o = { a: 1 };
assert(!Object.isExtensible(o) && Object.isSealed(o), "an object literal's keys are fixed");
assert(Object.hasOwn(o, "a") && !Object.hasOwn(o, "b"), "hasOwn of an object literal");

const a = [1, 2];
assert(Object.isExtensible(a) && !Object.isSealed(a) && !Object.isFrozen(a), "an array grows");
assert(Object.hasOwn(a, 1) && !Object.hasOwn(a, 2), "hasOwn of an array's index");

assert(Object.isFrozen(5) && Object.isFrozen("s") && !Object.isExtensible(true), "what is no object is frozen");
}

function main() {
entriesAndAssign();
closing();
others();
print("ALL DONE");
}
2 changes: 1 addition & 1 deletion tests/reflect_apply.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// Reflect.apply and Reflect.construct: a call and a `new` with their arguments given as an array,
// of one type or several; isExtensible and preventExtensions, as no object can gain a key.
// of one type or several; isExtensible and preventExtensions of an object, whose keys are fixed when it is made.
class Counter {
constructor(public n: number, public up: boolean) {}
}
Expand Down
Loading
Loading