tvarseq_caching.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. discard """
  2. output: '''@[1, 2, 3]
  3. @[4.0, 5.0, 6.0]
  4. @[1, 2, 3]
  5. @[4.0, 5.0, 6.0]
  6. @[1, 2, 3]
  7. @[4, 5, 6]'''
  8. """
  9. # bug #3476
  10. proc foo[T]: var seq[T] =
  11. ## Problem! Bug with generics makes every call to this proc generate
  12. ## a new seq[T] instead of retrieving the `items {.global.}` variable.
  13. var items {.global.}: seq[T]
  14. return items
  15. proc foo2[T]: ptr seq[T] =
  16. ## Workaround! By returning by `ptr` instead of `var` we can get access to
  17. ## the `items` variable, but that means we have to explicitly deref at callsite.
  18. var items {.global.}: seq[T]
  19. return addr items
  20. proc bar[T]: var seq[int] =
  21. ## Proof. This proc correctly retrieves the `items` variable. Notice the only thing
  22. ## that's changed from `foo` is that it returns `seq[int]` instead of `seq[T]`.
  23. var items {.global.}: seq[int]
  24. return items
  25. foo[int]() = @[1, 2, 3]
  26. foo[float]() = @[4.0, 5.0, 6.0]
  27. foo2[int]()[] = @[1, 2, 3]
  28. foo2[float]()[] = @[4.0, 5.0, 6.0]
  29. bar[int]() = @[1, 2, 3]
  30. bar[float]() = @[4, 5, 6]
  31. echo foo[int]() # prints 'nil' - BUG!
  32. echo foo[float]() # prints 'nil' - BUG!
  33. echo foo2[int]()[] # prints '@[1, 2, 3]'
  34. echo foo2[float]()[] # prints '@[4.0, 5.0, 6.0]'
  35. echo bar[int]() # prints '@[1, 2, 3]'
  36. echo bar[float]() # prints '@[4, 5, 6]'