revives: Move typetraits.$ to system. Fixes #5827 (#10071)

* Move typetraits.`$` to system. Fixes #5827.
* revive PR; adjust code to make sure everything works and add tests
* fix tests/concepts/tstackconcept.nim
* address comments
This commit is contained in:
Timothee Cour
2018-12-29 16:09:47 -08:00
committed by Andreas Rumpf
parent eba8ffcf70
commit 0831292863
4 changed files with 44 additions and 25 deletions

View File

@@ -136,7 +136,7 @@ proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym)
return typeWithSonsResult(tyAnd, @[operand, operand2])
of "not":
return typeWithSonsResult(tyNot, @[operand])
of "name":
of "name", "$":
result = newStrNode(nkStrLit, operand.typeToString(preferTypeName))
result.typ = newType(tyString, context)
result.info = traitCall.info

View File

@@ -11,29 +11,7 @@
## working with types
proc name*(t: typedesc): string {.magic: "TypeTrait".}
## Returns the name of the given type.
##
## Example:
##
## .. code-block::
##
## import typetraits
##
## proc `$`*(T: typedesc): string = name(T)
##
## template test(x): typed =
## echo "type: ", type(x), ", value: ", x
##
## test 42
## # --> type: int, value: 42
## test "Foo"
## # --> type: string, value: Foo
## test(@['A','B'])
## # --> type: seq[char], value: @[A, B]
proc `$`*(t: typedesc): string =
## An alias for `name`.
name(t)
## Alias for system.`$`(t) since Nim v0.20.0.
proc arity*(t: typedesc): int {.magic: "TypeTrait".} =
## Returns the arity of the given type. This is the number of "type" components or
@@ -64,4 +42,22 @@ proc supportsCopyMem*(t: typedesc): bool {.magic: "TypeTrait".}
when isMainModule:
doAssert $type(42) == "int"
static:
doAssert $type(42) == "int"
doAssert int.name == "int"
const a1 = name(int)
const a2 = $(int)
const a3 = $int
doAssert a1 == "int"
doAssert a2 == "int"
doAssert a3 == "int"
proc fun[T: typedesc](t: T) =
const a1 = name(t)
const a2 = $(t)
const a3 = $t
doAssert a1 == "int"
doAssert a2 == "int"
doAssert a3 == "int"
fun(int)

View File

@@ -4431,3 +4431,12 @@ when defined(genode):
componentConstructHook(env)
# Perform application initialization
# and return to thread entrypoint.
proc `$`*(t: typedesc): string {.magic: "TypeTrait".} =
## Returns the name of the given type.
##
## For more procedures dealing with ``typedesc``, see ``typetraits.nim``.
runnableExamples:
doAssert $(type(42)) == "int"
doAssert $(type("Foo")) == "string"
static: doAssert $(type(@['A', 'B'])) == "seq[char]"

View File

@@ -30,6 +30,20 @@ discard """
'''
"""
block:
const a2 = $(int)
const a3 = $int
doAssert a2 == "int"
doAssert a3 == "int"
proc fun[T: typedesc](t: T) =
const a2 = $(t)
const a3 = $t
doAssert a2 == "int"
doAssert a3 == "int"
fun(int)
# check high/low implementations
doAssert high(int) > low(int)
doAssert high(int8) > low(int8)