File: tgettype2.nim

package info (click to toggle)
nim 0.19.4-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 462,356 kB
  • sloc: sh: 11,089; ansic: 4,699; makefile: 706; python: 309; sql: 297; asm: 141; xml: 13
file content (67 lines) | stat: -rw-r--r-- 2,073 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

import macros, typetraits

type Foo = distinct int
type Bar = distinct int
type Baz = int

let foo = 0.Foo
let bar = 1.Bar
let baz = 2.Baz

type MyType[T] = distinct tuple[a,b:T]
type MySimpleType = distinct tuple[a,b: int]

var v: seq[int]
var vv: seq[float]
var t: MyType[int]
var tt: MyType[float]
var s: MySimpleType

echo "############"
echo "#### gt ####"
echo "############"

macro gt(a: typed): string =
  let b = a.getType
  var str = "gt(" & $a & "):\t" & b.repr
  if b.kind == nnkSym: # bad predicat to check weather the type has an implementation
    str = str & ", " & b.getType.repr  # append the implementation to the result
  result = newLit(str)

echo gt(Foo) # typeDesc[Foo]
echo gt(Bar) # typeDesc[Bar]
echo gt(Baz) # typeDesc[int]     shouldn't it be typeDesc[Baz]?
echo gt(foo) # distinct[int]     I would prefer Foo, distinct[int]
echo gt(bar) # distinct[int]     I would prefer Bar, distinct[int]
echo gt(baz) # int, int          I would prefer Baz, int

echo gt(v)   # seq[int], ok
echo gt(vv)  # seq[float], ok
echo gt(t)   # MyType, distinct[tuple[int, int]]      I would prefer MyType[int],   distinct[tuple[int, int]]
echo gt(tt)  # MyType, distinct[tuple[float, float]]  I would prefer MyType[float], distinct[tuple[int, int]]
echo gt(s)   # distinct[tuple[int, int]]              I would prefer MySimpleType, distinct[tuple[int,int]]

echo "#############"
echo "#### gt2 ####"
echo "#############"

# get type name via typetraits

macro gt2(a: typed): string =
  let prefix = "gt2(" & $a & "): \t"
  result = quote do:
    `prefix` & `a`.type.name

echo gt2(Foo) # Foo  shouldn't this be typeDesc[Foo] ?
echo gt2(Bar) # Bar  shouldn't this be typeDesc[Bar] ?
echo gt2(Baz) # Baz  shouldn't this be typeDesc[Baz] ?
echo gt2(foo) # Foo
echo gt2(bar) # Bar
echo gt2(baz) # Baz

echo gt2(v)   # seq[int]
echo gt2(vv)  # seq[float]
echo gt2(t)   # MyType[system.int]      why is it system.int and not just int like in seq?
echo gt2(tt)  # MyType[system.float]    why is it system.float and not just float like in seq?
echo gt2(s)   # MySimpleType