[BUG] iter(), enumerate() and zip() reject an iterator that carries an interior origin

オープン
#7,604 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 2 日以内に返信

まだ誰も着手していません。

評価

難易度
5/5
見積もり時間
1週間以上
初心者へのやさしさ
8/100
issue の種類
バグ
明瞭さ
おおむね明確
活発さ
活発
領域
compilers

調査の方向性

Start from the repro in the issue: BufIter and Buf stand in for a container whose iterator carries an interior origin, and plain_for_loop, through_iter, through_enumerate, through_zip and loop_then_enumerate show which calls fail. The fix belongs in the lifetime checker, where interior origins are established when the caller invokes __iter__ directly but not through the generic iter(), enumerate() or zip(). Done means all five functions compile and a mutation followed by use of an iterator is still rejected.

索引モデルが issue の本文から書いたものです。

説明

bug_feature_triaged Team: Mojo Compiler
Bug description

Interior origins let the lifetime checker reject a reference that is used after its container is mutated. The standard library would like List's iterator to carry the list's interior origin, so that this program becomes a compile error instead of writing into freed memory:

var b: List[Int] = [1, 2, 3]
for ref x in b:
    b.append(0)
    x = 99  # writes into the buffer that `append` freed

A prototype of that change does catch this program. It also breaks every enumerate(list) and zip(a, b) over a list, which makes it impossible to land. The problem is in the lifetime checker, not in List: the repro below shows it on main with a small stand-in container.

Actual behavior

A container whose iterator type carries an interior origin works in a plain for loop. Passing the same container through iter(), enumerate() or zip() fails:

error: use of a never-initialized interior reference 'b["element"]'
    for i, x in enumerate(b):
                         ^

If a plain for loop over b runs first, a following enumerate(b) fails differently, even though nothing mutates b:

error: use of invalidated interior reference 'b["element"]'
    for i, x in enumerate(b):
                         ^
note: origin was invalidated here

The note points at the enumerate(b) call itself.

It looks like the checker treats an interior origin as established only when the caller itself calls the method that creates it. Here __iter__ is called inside the generic iter(), so the caller only sees a result type that names b["element"], and the generic call is counted as a mutation of b.

Expected behavior

iter(b), enumerate(b) and zip(a, b) compile, the same as a plain for loop. Using one of their iterators after b is mutated is still rejected.

Steps to reproduce

Run mojo run repro.mojo:

# `Buf` stands in for a container whose iterator carries an interior origin,
# the way `List`'s element references already do.


@fieldwise_init
struct BufIter[mut: Bool, //, origin: Origin[mut=mut]](
    ImplicitlyCopyable, Iterable, Iterator
):
    comptime Element = Int
    comptime IteratorType[
        iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
    ]: Iterator = Self

    var _data: Pointer[Int, Self.origin]
    var _i: Int
    var _n: Int

    def __iter__(ref self) -> Self.IteratorType[origin_of(self)]:
        return self.copy()

    def __next__(mut self) raises StopIteration -> ref[Self.origin] Int:
        if self._i >= self._n:
            raise StopIteration()
        self._i += 1
        return self._data[unsafe_offset=self._i - 1]

    def bounds(self) -> Tuple[Int, Optional[Int]]:
        return (self._n - self._i, {self._n - self._i})


struct Buf(Iterable, Movable):
    comptime IteratorType[
        iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]
    ]: Iterator = BufIter[iterable_origin._get_owned_interior["element"]]

    var _list: List[Int]

    def __init__(out self):
        self._list = [1, 2, 3]

    @__unsafe_nested_origins_read_only
    def __iter__(ref self) -> Self.IteratorType[origin_of(self)]:
        return BufIter(
            Pointer(
                to=self._list.unsafe_ptr()._get_ref_with_unsafe_interior_origin[
                    "element", origin_of(self)
                ]()
            ),
            0,
            len(self._list),
        )


def plain_for_loop():
    var b = Buf()
    for x in b:  # OK
        print(x)


def through_iter():
    var b = Buf()
    var it = iter(b)
    for x in it:  # error: never-initialized interior reference
        print(x)


def through_enumerate():
    var b = Buf()
    for i, x in enumerate(b):  # error: never-initialized interior reference
        print(i, x)


def through_zip():
    var a = Buf()
    var b = Buf()
    for x, y in zip(a, b):  # error: never-initialized interior reference
        print(x, y)


def loop_then_enumerate():
    var b = Buf()
    for x in b:
        print(x)
    for i, x in enumerate(b):  # error: invalidated interior reference
        print(i, x)


def main():
    plain_for_loop()
    through_iter()
    through_enumerate()
    through_zip()
    loop_then_enumerate()
System information

Reproduces on main built from source (Linux x86_64).

主要言語
Mojo
スター
30.2k
フォーク
3.2k
平均マージ
5日 18時間
マージ済み PR(30日)
27

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

modular/modular のほかの issue

modular/modular の issue をすべて見る

似ている issue

Compilers の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。