Skip to content

Commit c7e61e1

Browse files
committed
string.inspect circular references
1 parent 8c626a4 commit c7e61e1

File tree

5 files changed

+281
-15
lines changed

5 files changed

+281
-15
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
- The deprecated `from` function in the `dynamic` module has been removed.
1212
- Fixed a bug in the `sample` function from the `list` module where it would end
1313
up picking the same element twice from a given list.
14+
- Improved formatting of JavaScript errors in `string.inspect`.
15+
- JavaScript circular references can now be printed by `string.inspect`.
1416

1517
## v0.60.0 - 2025-05-13
1618

src/gleam_stdlib.mjs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -678,22 +678,29 @@ export function inspect(v) {
678678
if (t === "string") return inspectString(v);
679679
if (t === "bigint" || Number.isInteger(v)) return v.toString();
680680
if (t === "number") return float_to_string(v);
681-
if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`;
682-
if (v instanceof List) return inspectList(v);
683681
if (v instanceof UtfCodepoint) return inspectUtfCodepoint(v);
684682
if (v instanceof BitArray) return `<<${bit_array_inspect(v, "")}>>`;
685-
if (v instanceof CustomType) return inspectCustomType(v);
686-
if (v instanceof Dict) return inspectDict(v);
687-
if (v instanceof Set) return `//js(Set(${[...v].map(inspect).join(", ")}))`;
688683
if (v instanceof RegExp) return `//js(${v})`;
689684
if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`;
685+
if (v instanceof globalThis.Error) return `//js(${v.toString()})`;
690686
if (v instanceof Function) {
691687
const args = [];
692688
for (const i of Array(v.length).keys())
693689
args.push(String.fromCharCode(i + 97));
694690
return `//fn(${args.join(", ")}) { ... }`;
695691
}
696-
return inspectObject(v);
692+
693+
try {
694+
if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`;
695+
if (v instanceof List) return inspectList(v);
696+
if (v instanceof CustomType) return inspectCustomType(v);
697+
if (v instanceof Dict) return inspectDict(v);
698+
if (v instanceof Set) return `//js(Set(${[...v].map(inspect).join(", ")}))`;
699+
return inspectObject(v);
700+
} catch (e) {
701+
if (e instanceof RangeError) return "//js(circular)";
702+
throw e;
703+
}
697704
}
698705

699706
function inspectString(str) {

0 commit comments

Comments
 (0)