# Inference bug when using nested generators?

**URL:** <https://discourse.julialang.org/t/inference-bug-when-using-nested-generators/82991>\
**Category:** General Usage\
**Created:** [June 19, 2022, 12:51am UTC](https://discourse.julialang.org/t/inference-bug-when-using-nested-generators/82991 "2022-06-19T00:51:28Z")\
**Posts on this page:** 2\
**Page:** 2

<div class="post-metadata">

**Author:** ![N5N3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/n5n3/32/17663_2.png) [@N5N3](https://discourse.julialang.org/u/N5N3)\
**Post date:** [June 21, 2022, 8:53am UTC](https://discourse.julialang.org/t/inference-bug-when-using-nested-generators/82991/21 "2022-06-21T08:53:10Z")

</div>

`@descend` shows that our compiler fails to inference `Base._xfadjoint` in this case.

```julia
_xfadjoint(op, itr::Generator) =
    if itr.f === identity
        _xfadjoint(op, itr.iter)
    else
        _xfadjoint(MappingRF(itr.f, op), itr.iter)
    end

```

It unwraps the nested `Generator` recursively and forms the new `MappingRF`.

```julia
julia> a = (-i for i in 1:3); b = (-i for i in a); c = (-i for i in b);

julia> Base.return_types(Base._xfadjoint, Base.typesof(+, c))
1-element Vector{Any}:
 Tuple{Base.MappingRF{var"#7#8"}, UnitRange{Int64}}

julia> Base.return_types(Base._xfadjoint, Base.typesof(+, b))
1-element Vector{Any}:
 Tuple{Base.MappingRF{var"#7#8", Base.MappingRF{var"#9#10", typeof(+)}}, UnitRange{Int64}}

```

Failure starts with `c` (three nested layers), which matches our inference constraint on recursion.

---

<div class="post-metadata">

**Author:** ![N5N3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/n5n3/32/17663_2.png) [@N5N3](https://discourse.julialang.org/u/N5N3)\
**Post date:** [June 23, 2022, 6:44am UTC](https://discourse.julialang.org/t/inference-bug-when-using-nested-generators/82991/22 "2022-06-23T06:44:02Z")

</div>

I think this modified version would make our compiler much happier

```julia
function _xfadjoint(op, itr)
    itr′, wrap = _xfadjoint_unwrap(itr)
    wrap(op), itr′
end

_xfadjoint_unwrap(itr) = itr, identity
function _xfadjoint_unwrap(itr::Generator)
    itr′, wrap = _xfadjoint_unwrap(itr.iter)
    itr.f === identity && return itr′, wrap
    return itr′, wrap ∘ Fix1(MappingRF, itr.f)
end
function _xfadjoint_unwrap(itr::Filter)
    itr′, wrap = _xfadjoint_unwrap(itr.itr)
    return itr′, wrap ∘ Fix1(FilteringRF, itr.flt)
end
function _xfadjoint_unwrap(itr::Flatten)
    itr′, wrap = _xfadjoint_unwrap(itr.it)
    return itr′, wrap ∘ FlatteningRF
end

```

But we need to fix [ComposedFunction type inference regression from v1.6 LTS · Issue #45715 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/45715) and make `Base.Fix1(f, Int)` stable first.

[Previous page](https://discourse.julialang.org/t/inference-bug-when-using-nested-generators/82991.md?page=1)
