Stream: t-compiler/wg-rls-2.0

Topic: Rust vs Internal iterators


matklad (Jun 25 2019 at 13:38, on Zulip):

I've been looking into simiplifing https://github.com/rust-analyzer/rust-analyzer/blob/4b0c37bd6e4cb3d47614ec6b42fb1deef9bc9324/crates/ra_hir/src/ty/method_resolution.rs#L255-L275.

It was mostly a failure, but let me dump here my thoughts in case anyone has a better idea!

The fundamental problem here is that we want an internal iterator abstraction, to avoid returning references to local variables.

I went as far as

    pub fn iterate_impl_items<T>(
        self,
        db: &impl HirDatabase,
        krate: Crate,
        mut callback: impl FnMut(ImplItem) -> Option<T>,
    ) -> Option<T> {
        self.collect_impl_items(db, krate)(FindMap(callback)).some()
    }

    pub fn collect_impl_items<E: Extend<ImplItem>>(
        self,
        db: &impl HirDatabase,
        krate: Crate,
    ) -> impl FnOnce(E) -> E  + '_ {
        move |mut sink| {
            sink.extend(
                def_crate(db, krate, &self)
                    .map(|krate| db.impls_in_crate(krate))
                    .as_ref()
                    .into_iter()
                    .flat_map(|impls| impls.lookup_impl_blocks(&self))
                    .flat_map(|it| it.items(db)),
            );
            sink
        }
    }

Using std::iter::Extend as an Internal Iterator trait is nice! However, I failed to further abstract this, due to the lack of generic lambdas

matklad (Jun 25 2019 at 13:38, on Zulip):

This, unfortunatelly, is not valid Rust yet: https://gist.github.com/matklad/8c3a413f5e2cc144eeb0da2dc761abd7 :-(

Florian Diebold (Jun 25 2019 at 14:09, on Zulip):

I'm still holding out for generators to make this easy ;)

matklad (Jun 25 2019 at 14:11, on Zulip):

Not sure that generators help in this case: the problem is, we have two nested loops, where the inner loop borrows from the outer. This can't be represented as an std::iter::Iterator, because, once you turned the outer loop, inner references from the previous iteration become invalid

matklad (Jun 25 2019 at 14:11, on Zulip):

Hm, OTOH, we are not returning those references and use them only internally...

Last update: Nov 19 2019 at 17:40UTC