julia icon indicating copy to clipboard operation
julia copied to clipboard

Comma in struct definition leads to error & defined singleton struct

Open Seelengrab opened this issue 2 years ago • 1 comments

julia> struct Foo
           value::Int,
           name::Int
       end
ERROR: UndefVarError: value not defined
Stacktrace:
 [1] top-level scope
   @ REPL[1]:1

julia> Foo
Foo

julia> Base.issingletontype(Foo)
true

julia> fieldtypes(Foo)
()

julia> fieldnames(Foo)
()

That , isn't valid there in any form, so shouldn't this throw a syntax error? Or any better error at all, instead of defining a singleton type?

Also probably related:

julia> struct Bar{T}
           value::Union{Nothing, T},
           name::T
       end
ERROR: UndefVarError: T not defined
Stacktrace:
 [1] top-level scope
   @ REPL[2]:1

which leads to Bar being a defined singleton as well.

Seelengrab avatar Aug 08 '22 08:08 Seelengrab

Even worse, it doesn't always error:

julia> value = 1
1

julia> name = 2
2

julia> struct Foo
           value::Int,
           name::Int
       end

I imagine that if a struct has a body other than field definitions, it is assumed to be a list of inner constructors and executed at the top-level, replacing the default inner constructor. In this case, the body is a tuple which is a valid top-level expression. Many syntax errors in a struct definition will result in a body which is not exclusively well-formed field declarations, so many syntax errors will trigger evaluation at top-level, a behavior users likely don't expect.

I'd like to fix this by making anything but a field declaration or a function declaration an error in a type definition, but it may break the following cases:

struct Unconstructable 1+1 end # This struct cannot be instantiated
struct DivisableByThree
    value::Int    
    false || (three = 1 + 1 + 1)
    function DivisableByThree(x)
        iszero(x % three) || throw(ArgumentError("Not divisable by three"))
        new(x)
    end
end

LilithHafner avatar Aug 08 '22 14:08 LilithHafner

wow. oops.

oscardssmith avatar Aug 19 '22 20:08 oscardssmith

Why close?

KristofferC avatar Aug 19 '22 21:08 KristofferC

because I closed the wrong one as a duplicate.

oscardssmith avatar Aug 20 '22 00:08 oscardssmith

just ran into this

but it may break the following cases:

is that supposed to be allowed? 😳

adienes avatar Jan 15 '24 23:01 adienes