From 1105ed95b8b1eaf0346bb3c5aca87d7084b4ddd6 Mon Sep 17 00:00:00 2001 From: Leorize Date: Thu, 11 Nov 2021 17:55:42 -0600 Subject: [PATCH] union: add a way to stringify unions This will be very helpful for debugging as it hides away implementation details within union. --- tests/tconv.nim | 6 ++++++ union.nim | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/tests/tconv.nim b/tests/tconv.nim index 2beca87..6f5c4d8 100644 --- a/tests/tconv.nim +++ b/tests/tconv.nim @@ -79,3 +79,9 @@ suite "Union conversions": check (10 as union(int | float)) == (10 as union(int | string)) check ("string" as union(int | float | string | seq[string])) == ("string" as union(int | string)) check ("string" as union(int | float | string | seq[string])) != (42 as union(int | string)) + + test "Auto string representation for unions": + check $(10 as union(int | float)) == "int(10)" + check $("string" as union(int | string)) == "string(\"string\")" + check $([1, 2] as union(int | array[2, int])) == "array[0..1, int]([1, 2])" + check $(@[1, 2] as union(string | seq[int])) == "seq[int](@[1, 2])" diff --git a/union.nim b/union.nim index cb638e0..10f6379 100644 --- a/union.nim +++ b/union.nim @@ -706,3 +706,11 @@ func `==`*[U, V: Union](a: U, b: V): bool {.inline.} = false else: false + +proc `$`*[T: Union](u: T): string = + ## Stringify `u` based on its current type in the format `type(value)`. + ## Its main purpose is to enable debugging. + unpack(u): + result = $typeof(it) & "(" + result.addQuoted it + result.add ")"