tborrow.nim 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. discard """
  2. output: '''4887 true
  3. 0.5'''
  4. """
  5. # test the new borrow feature that works with generics:
  6. proc `++`*[T: int | float](a, b: T): T =
  7. result = a + b
  8. type
  9. DI = distinct int
  10. DF = distinct float
  11. DS = distinct string
  12. proc `++`(x, y: DI): DI {.borrow.}
  13. proc `++`(x, y: DF): DF {.borrow.}
  14. proc `$`(x: DI): string {.borrow.}
  15. proc `$`(x: DF): string {.borrow.}
  16. echo 4544.DI ++ 343.DI, " ", (4.5.DF ++ 0.5.DF).float == 5.0
  17. # issue #14440
  18. type Radians = distinct float64
  19. func `-=`(a: var Radians, b: Radians) {.borrow.}
  20. var a = Radians(1.5)
  21. let b = Radians(1.0)
  22. a -= b
  23. echo a.float64
  24. block: #14449
  25. type
  26. Foo[T] = object
  27. foo: T
  28. Bar[T] {.borrow:`.`.} = distinct Foo[T]
  29. SomeThing {.borrow:`.`.} = distinct Foo[float]
  30. OtherThing {.borrow:`.`.} = distinct SomeThing
  31. var
  32. a: Bar[int]
  33. b: SomeThing
  34. c: OtherThing
  35. a.foo = 300
  36. b.foo = 400
  37. c.foo = 42
  38. assert a.foo == 300
  39. assert b.foo == 400d
  40. assert c.foo == 42d
  41. block: # Borrow from muliple aliasses #16666
  42. type
  43. AImpl = object
  44. i: int
  45. A = AImpl
  46. B {.borrow: `.`.} = distinct A
  47. C = B
  48. D {.borrow: `.`.} = distinct C
  49. E {.borrow: `.`.} = distinct D
  50. let
  51. b = default(B)
  52. d = default(D)
  53. e = default(E)
  54. assert b.i == 0
  55. assert d.i == 0
  56. assert e.i == 0
  57. block: # Borrow from generic alias
  58. type
  59. AImpl[T] = object
  60. i: T
  61. B[T] = AImpl[T]
  62. C {.borrow: `.`.} = distinct B[int]
  63. D = B[float]
  64. E {.borrow: `.`.} = distinct D
  65. let
  66. c = default(C)
  67. e = default(E)
  68. assert c.i == int(0)
  69. assert e.i == 0d