diff --git a/README.md b/README.md index be63c16..3d72dc5 100644 --- a/README.md +++ b/README.md @@ -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]}`); @@ -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`: `get`, `set`, `has`, `delete`. `WeakSet`: `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. diff --git a/src/generics/lib.generics.ts b/src/generics/lib.generics.ts index 7810194..05cac58 100644 --- a/src/generics/lib.generics.ts +++ b/src/generics/lib.generics.ts @@ -1558,7 +1558,8 @@ namespace JSON { // compiled for that type, and a null cannot be cast to a number. function toValue(value: T): R { if (typeof value == "string") { - return JsonValue.ofString(value); + // a copy: the JsonValue keeps its string, and an array's element is only lent here + return JsonValue.ofString(value + ""); } else if (typeof value == "boolean") { return JsonValue.ofBoolean(value); } else if (typeof value == "null") { @@ -1574,7 +1575,13 @@ namespace JSON { return result; } else if (typeof value == "class") { if (value instanceof JsonValue) { - return 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 (value).clone(); + } else { + return value; + } } return toValue(value.toJSON()); @@ -1603,11 +1610,13 @@ namespace JSON { // `replacer` is there for `JSON.stringify(value, null, 2)`: only null is taken function stringify(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(space); } - return toValue(value).stringify(indent(space)); + return toValue(value).stringify(spacing); } } diff --git a/src/lib.d.ts b/src/lib.d.ts index cc12682..8fe5702 100644 --- a/src/lib.d.ts +++ b/src/lib.d.ts @@ -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; diff --git a/src/lib.ts b/src/lib.ts index cdd920d..829424c 100644 --- a/src/lib.ts +++ b/src/lib.ts @@ -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"); diff --git a/tests/json.ts b/tests/json.ts index 66a98c0..6f1d616 100644 --- a/tests/json.ts +++ b/tests/json.ts @@ -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) { } @@ -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; } } @@ -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)); @@ -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)); @@ -143,6 +168,7 @@ function main() { strings(); rejected(); writing(); + chained(); roundTrip(); console.log("ALL DONE"); }