summary refs log tree commit diff stats
path: root/tests/gensym/tgensymgeneric.nim
blob: 6e1df4842fd7bf8842593c4e482559d57c329215 (plain) (blame)
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
discard """
  output: '''true'''
"""

# We need to open the gensym'ed symbol again so that the instantiation
# creates a fresh copy; but this is wrong the very first reason for gensym
# is that scope rules cannot be used! So simply removing 'sfGenSym' does
# not work. Copying the symbol does not work either because we're already
# the owner of the symbol! What we need to do is to copy the symbol
# in the generic instantiation process...

type
  TA = object
    x: int
  TB = object
    x: string

template genImpl() =
  var gensymed: T
  when T is TB:
    gensymed.x = "abc"
  else:
    gensymed.x = 123
  result = move gensymed

proc gen[T](x: T): T =
  genImpl()

var
  a: TA
  b: TB
let x = gen(a)
let y = gen(b)

doAssert x.x == 123
doAssert y.x == "abc"

# test symbol equality

import macros

static:
  let sym1 = genSym()
  let sym2 = genSym()
  let sym3 = sym1
  let nimsym = sym1.symbol
  doAssert sym1 == sym1
  doAssert sym2 != sym3
  doAssert sym2.symbol != sym3.symbol
  doAssert sym3 == sym1
  doAssert sym1.symbol == sym1.symbol
  doAssert nimsym == nimsym

echo "true"