Skip to content

Commit

Permalink
Merge pull request #15 from alaviss/features/stringify
Browse files Browse the repository at this point in the history
union: add a way to stringify unions
  • Loading branch information
alaviss authored Nov 12, 2021
2 parents 0b4b4b1 + 1105ed9 commit ff03f5d
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tests/tconv.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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])"
8 changes: 8 additions & 0 deletions union.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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 ")"

0 comments on commit ff03f5d

Please sign in to comment.