From e3dfe1a074855065c915924fc4987edae3bd629a Mon Sep 17 00:00:00 2001 From: Timothee Cour Date: Fri, 26 Mar 2021 10:11:24 -0700 Subject: [PATCH] items(array) now returns lent T --- lib/system/iterators.nim | 2 +- tests/types/tlent.nim | 67 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 tests/types/tlent.nim diff --git a/lib/system/iterators.nim b/lib/system/iterators.nim index d8af4eed56045..5c5bd8947a7f6 100644 --- a/lib/system/iterators.nim +++ b/lib/system/iterators.nim @@ -27,7 +27,7 @@ iterator mitems*[T](a: var openArray[T]): var T {.inline.} = yield a[i] inc(i) -iterator items*[IX, T](a: array[IX, T]): T {.inline.} = +iterator items*[IX, T](a: array[IX, T]): lent2 T {.inline.} = ## Iterates over each item of `a`. var i = low(IX) if i <= high(IX): diff --git a/tests/types/tlent.nim b/tests/types/tlent.nim new file mode 100644 index 0000000000000..7fae4c3852d08 --- /dev/null +++ b/tests/types/tlent.nim @@ -0,0 +1,67 @@ +discard """ + targets: "c cpp js" +""" + +#[ +xxx move at least some of those tests to here: +tests/lent/tbasic_lent_check.nim +tests/lent/tlent_from_var.nim +tests/lent/tnot_allowed_lent.nim +tests/lent/tnot_allowed_lent2.nim +tests/types/tlent.nim +tests/types/tlent_var.nim +]# + +type Foo = object + f0: int + f1: int + +proc fn1(a: auto): lent int = a[0] +proc fn2(a: Foo): lent int = a.f0 + +iterator it3(a: Foo): lent int = + yield a.f0 + +template sameAddr(a, b): bool = + when defined(js): + # we could probably do something smarter here + a == b + else: + let pa = cast[int](a.unsafeAddr) + let pb = cast[int](b.unsafeAddr) + pa == pb + +template main() = + block: + let a = @[10,11,12] + doAssert sameAddr(a[0], fn1(a)) + block: + let a = [10,11,12] + doAssert sameAddr(a[0], fn1(a)) + block: + let a = Foo(f0: 10) + doAssert sameAddr(a.f0, fn2(a)) + + block: + let a = @[10,11,12] + for ai in items(a): + doAssert sameAddr(a[0], ai) + break + block: + let a = [10,11,12] + for ai in items(a): + doAssert sameAddr(a[0], ai) + break + block: + let a = [[1,2],[1,2],[1,2]] + for ai in items(a): + doAssert sameAddr(a[0][0], ai[0]) + break + block: + let a = Foo(f0: 10) + for ai in it3(a): + doAssert sameAddr(a.f0, ai) + break + +static: main() +main()