JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.73k stars 5.48k forks source link

Stack overflow in `vect` / `promote_typeof` #45454

Closed nystrom closed 6 months ago

nystrom commented 2 years ago

vect has a stack overflow when trying to compute the element type of the vector.

julia> abstract type A end
julia> struct B <: A end
julia> struct C <: A end
julia> xs = [B() for i in 1:100000];
julia> ys = [C() for i in 1:100000];
julia> [xs..., ys...]
ERROR: StackOverflowError:
Stacktrace:
 [1] promote_typeof(::B, ::B, ::Vararg{Any}) (repeats 29076 times)
   @ Base ./promotion.jl:330
 [2] vect(::B, ::Vararg{Any})
   @ Base ./array.jl:144

The workaround is to use vcat, but it would be good if the compiler could figure this out given that the two inputs are known to be vectors. At least to avoid the overflow, promote_typeof could be written:

promote_typeof(x) = typeof(x)
promote_typeof(x, xs...) = afoldl((t, x) -> promote_type(t, typeof(x)), typeof(x), xs...)

This occurs on 1.7.2:

Julia Version 1.7.2
Commit bf53498635 (2022-02-06 15:21 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin19.5.0)
  CPU: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-12.0.1 (ORCJIT, skylake)
Environment:
  JULIA_DEPOT_PATH = /Users/nystrom/.julia-depots:/Users/nystrom/.julia
  JULIA_NUM_THREADS = 4
  JULIA_PROJECT = /Users/nystrom/rai
  JULIA_EDITOR = code
gbaraldi commented 2 years ago

I believe the issue is with how we handle massive splats like these

nsajko commented 6 months ago

Seems fixed.