typeToString can now show (recursively) resolved type aliases; fixes #8569 #8083 #8570 (#11678)

* nested typeToString
* typeToString: preferResolved
* add test
* fix test
* preferMixed
* fix tests
This commit is contained in:
Timothee Cour 2019-08-30 23:26:45 -07:00 • committed by Andreas Rumpf
commit 9ae0dd611f
6 changed files with 272 additions and 203 deletions

View file

@ -36,7 +36,7 @@ tsigmatch.nim(143, 13) Error: type mismatch: got <array[0..0, proc (x: int){.gcs
but expected one of:
proc takesFuncs(fs: openArray[proc (x: int) {.gcsafe, locks: 0.}])
first type mismatch at position: 1
required type for fs: openarray[proc (x: int){.closure, gcsafe, locks: 0.}]
required type for fs: openArray[proc (x: int){.closure, gcsafe, locks: 0.}]
but expression '[proc (x: int) {.gcsafe, locks: 0.} = echo [x]]' is of type: array[0..0, proc (x: int){.gcsafe, locks: 0.}]
expression: takesFuncs([proc (x: int) {.gcsafe, locks: 0.} = echo [x]])

View file

@ -6,7 +6,7 @@ twrong_at_operator.nim(22, 30) Error: type mismatch: got <array[0..0, type int]>
but expected one of:
proc `@`[T](a: openArray[T]): seq[T]
first type mismatch at position: 1
required type for a: openarray[T]
required type for a: openArray[T]
but expression '[int]' is of type: array[0..0, type int]
proc `@`[IDX, T](a: sink array[IDX, T]): seq[T]
first type mismatch at position: 1

View file

@ -14,3 +14,32 @@ block: # isNamedTuple
doAssert not Foo3.isNamedTuple
doAssert not Foo4.isNamedTuple
doAssert not (1,).type.isNamedTuple
proc typeToString*(t: typedesc, prefer = "preferTypeName"): string {.magic: "TypeTrait".}
## Returns the name of the given type, with more flexibility than `name`,
## and avoiding the potential clash with a variable named `name`.
## prefer = "preferResolved" will resolve type aliases recursively.
# Move to typetraits.nim once api stabilized.
block: # typeToString
type MyInt = int
type
C[T0, T1] = object
type C2=C # alias => will resolve as C
type C2b=C # alias => will resolve as C (recursively)
type C3[U,V] = C[V,U]
type C4[X] = C[X,X]
template name2(T): string = typeToString(T, "preferResolved")
doAssert MyInt.name2 == "int"
doAssert C3[MyInt, C2b].name2 == "C3[int, C]"
# C3 doesn't get resolved to C, not an alias (nor does C4)
doAssert C2b[MyInt, C4[cstring]].name2 == "C[int, C4[cstring]]"
doAssert C4[MyInt].name2 == "C4[int]"
when BiggestFloat is float and cint is int:
doAssert C2b[cint, BiggestFloat].name2 == "C3[int, C3[float, int32]]"
template name3(T): string = typeToString(T, "preferMixed")
doAssert MyInt.name3 == "MyInt{int}"
doAssert (tuple[a: MyInt, b: float]).name3 == "tuple[a: MyInt{int}, b: float]"
doAssert (tuple[a: C2b[MyInt, C4[cstring]], b: cint, c: float]).name3 ==
"tuple[a: C2b{C}[MyInt{int}, C4[cstring]], b: cint{int32}, c: float]"

View file

@ -1,5 +1,5 @@
discard """
errormsg: "invalid type: 'openarray[int]' for result"
errormsg: "invalid type: 'openArray[int]' for result"
line: 6
"""