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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ Globals (`src/lib.ts`):
key or index that is not there gives a JSON null. Text that is not JSON is a `SyntaxError`, and
nesting past 512 levels a `RangeError`. A `\u0000` in a string is a `SyntaxError`, because a string
ends at its first 0. A value is built with `JsonValue.ofBoolean`, `ofNumber`, `ofString`, `newArray`
and `newObject`, then `push` and `set`.
and `newObject`, then `push` and `set`; `clone()` makes a deep copy.

```ts
const config = JSON.parse(`{"name":"tslang","sizes":[1,2]}`);
Expand Down Expand Up @@ -240,8 +240,10 @@ Generics (`src/generics/lib.generics.ts`):
`JsonValue`s, and classes with a `toJSON()`, which can return a `JsonValue` to write out the class's
fields. An object literal or a tuple is a `TypeError`, a `BigInt` too. `space` is a number or a
string; a replacer is not supported, only `null`.
Under `-mm=own` it takes a number or a string only (use `value.stringify()` for a `JsonValue`), and a
`JsonValue` is built one step at a time, not with chained `set`s.
It takes all of these under every memory model; under `-mm=own` it writes out a copy of a `JsonValue`
it is given (`clone()`), since the value is only lent to it. Under `-mm=own` a `JsonValue` is built
one step at a time (`const o = JsonValue.newObject(); o.set("a", ...);`), not with chained `set`s or
`push`es: their result borrows the value they were called on.
- `WeakMap<K, V>`: `get`, `set`, `has`, `delete`. `WeakSet<K>`: `add`, `has`, `delete`. Keys are
objects, compared by identity. `-mm=gc` only, as `WeakRef` is. A value is held strongly, so a value
that refers to its own key keeps that key alive.
Expand Down
19 changes: 14 additions & 5 deletions src/generics/lib.generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1558,7 +1558,8 @@ namespace JSON {
// compiled for that type, and a null cannot be cast to a number.
function toValue<T, R = JsonValue>(value: T): R {
if (typeof value == "string") {
return JsonValue.ofString(<string>value);
// a copy: the JsonValue keeps its string, and an array's element is only lent here
return JsonValue.ofString(<string>value + "");
} else if (typeof value == "boolean") {
return JsonValue.ofBoolean(<boolean>value);
} else if (typeof value == "null") {
Expand All @@ -1574,7 +1575,13 @@ namespace JSON {
return result;
} else if (typeof value == "class") {
if (value instanceof JsonValue) {
return <JsonValue>value;
// -mm=own: the value is only lent to JSON.stringify, and the result owns what it holds,
// so it holds a copy (elsewhere the result shares it)
if (__MEMORY_MODEL__ == "own") {
return (<JsonValue>value).clone();
} else {
return <JsonValue>value;
}
}

return toValue(value.toJSON());
Expand Down Expand Up @@ -1603,11 +1610,13 @@ namespace JSON {

// `replacer` is there for `JSON.stringify(value, null, 2)`: only null is taken
function stringify<T, S = string>(value: T, replacer?: null, space?: S): string {
if (space == undefined) {
return toValue(value).stringify();
// one call of toValue: under -mm=own a value used on two paths counts as moved on the first
let spacing = "";
if (space != undefined) {
spacing = indent(<S>space);
}

return toValue(value).stringify(indent(<S>space));
return toValue(value).stringify(spacing);
}
}

Expand Down
1 change: 1 addition & 0 deletions src/lib.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -730,6 +730,7 @@ declare class JsonValue {
@lends("this")
@keeps("value")
set(key: string, value: JsonValue): JsonValue;
clone(): JsonValue;
keys(): string[];
stringify(space?: string): string;
toString(): string;
Expand Down
19 changes: 19 additions & 0 deletions src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2384,6 +2384,25 @@ export class JsonValue {
return this;
}

// A copy of the whole value, sharing nothing with it. JSON.stringify uses it under -mm=own, where a
// JsonValue it is given is only lent to it.
public clone(): JsonValue {
const result = new JsonValue();
result.tag = this.tag;
result.flag = this.flag;
result.num = this.num;
result.str = this.str + "";
for (const item of this.items) {
result.items.push(item.clone());
}

for (const name of this.names) {
result.names.push(name + "");
}

return result;
}

// an object's keys, in their order
public keys(): string[] {
this.expect(JSON_OBJECT, "object");
Expand Down
42 changes: 34 additions & 8 deletions tests/json.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// not own: chained set() and JSON.stringify of an array or a JsonValue do not compile there; see json_read.ts.
// JSON.parse gives a JsonValue, read through its accessors; JSON.stringify takes numbers, strings,
// booleans, null, arrays of those, JsonValues and classes with toJSON().
// booleans, null, arrays of those, JsonValues and classes with toJSON(). Values are built one step at
// a time, which works under every memory model; chained set() and push() are tested where they
// compile, every model but -mm=own (see chained()).
class Point {
constructor(public x: number) {
}
Expand All @@ -16,7 +17,10 @@ class Person {
}

toJSON(): JsonValue {
return JsonValue.newObject().set("name", JsonValue.ofString(this.name)).set("age", JsonValue.ofNumber(this.age));
const result = JsonValue.newObject();
result.set("name", JsonValue.ofString(this.name));
result.set("age", JsonValue.ofNumber(this.age));
return result;
}
}

Expand Down Expand Up @@ -115,11 +119,14 @@ function writing() {
assert(JSON.stringify([new Person("B", 1)]) == `[{"name":"B","age":1}]`, "in an array");
assert(JSON.stringify(new Date(0)) == `"1970-01-01T00:00:00.000Z"`, "a Date");

const built = JsonValue.newObject()
.set("n", JsonValue.ofNumber(1))
.set("list", JsonValue.newArray().push(JsonValue.ofString("x")).push(new JsonValue()))
.set("empty", JsonValue.newObject())
.set("none", JsonValue.newArray());
const list = JsonValue.newArray();
list.push(JsonValue.ofString("x"));
list.push(new JsonValue());
const built = JsonValue.newObject();
built.set("n", JsonValue.ofNumber(1));
built.set("list", list);
built.set("empty", JsonValue.newObject());
built.set("none", JsonValue.newArray());
assert(JSON.stringify(built) == `{"n":1,"list":["x",null],"empty":{},"none":[]}`, "a built value");
assert(built.toString() == JSON.stringify(built), "toString");
built.set("n", JsonValue.ofBoolean(true));
Expand All @@ -131,6 +138,24 @@ function writing() {
assert(JSON.stringify([1], null, 0) == "[1]", "indented by nothing");
}

// Under -mm=own the result of set() and push() borrows the value they were called on, so a chain that
// starts from a new value (JsonValue.newObject().set(...)) can't be kept: the compiler has no way yet
// to say that a method gives its receiver back. Only the branch for the model built is compiled.
function chained() {
if (__MEMORY_MODEL__ != "own") {
const person = JsonValue.newObject().set("name", JsonValue.ofString("Ann")).set("age", JsonValue.ofNumber(30));
assert(JSON.stringify(person) == `{"name":"Ann","age":30}`, "a chain of set()");

const built = JsonValue.newObject()
.set("n", JsonValue.ofNumber(1))
.set("list", JsonValue.newArray().push(JsonValue.ofString("x")).push(new JsonValue()))
.set("empty", JsonValue.newObject());
assert(JSON.stringify(built) == `{"n":1,"list":["x",null],"empty":{}}`, "a chained build");
built.set("n", JsonValue.ofBoolean(true)).set("added", JsonValue.ofString("y"));
assert(JSON.stringify(built) == `{"n":true,"list":["x",null],"empty":{},"added":"y"}`, "set again, chained");
}
}

function roundTrip() {
const text = `{"s":"a\\"b\\u00e9","n":[1,-2.5,1e+21],"o":{"t":true,"f":false,"z":null}}`;
const again = JSON.stringify(JSON.parse(text));
Expand All @@ -143,6 +168,7 @@ function main() {
strings();
rejected();
writing();
chained();
roundTrip();
console.log("ALL DONE");
}
Loading