Julia: Using reserved words as NamedTuple field names

Created on 16 Apr 2018  路  4Comments  路  Source: JuliaLang/julia

Followup to #26507.

This works:

julia> a = NamedTuple{(:function,)}((1,))
(function = 1,)

julia> a.function
1

However, direct construction does not work.

julia> a = (function = 1,)
ERROR: syntax: unexpected "="

There are also (at least) two different failure modes for different reserved words.

julia> a = (end = 1,)
ERROR: syntax: unexpected "end"

Would it be mad to allow this? Alternatively, could it give a uniform and more specific error about bad use of reserved word in named tuple?

display and printing

Most helpful comment

In a language with elaborate (non-s-expression) syntax it is unavoidable that some surface syntax forms won't be able to express everything the underlying object model can represent. And I don't think we can or should allow parsing function = 1.

One thing we could do is fix the printing of NamedTuple{(:function,)}((1,)) to use that syntax rather than (function = 1,).

All 4 comments

In a language with elaborate (non-s-expression) syntax it is unavoidable that some surface syntax forms won't be able to express everything the underlying object model can represent. And I don't think we can or should allow parsing function = 1.

One thing we could do is fix the printing of NamedTuple{(:function,)}((1,)) to use that syntax rather than (function = 1,).

I wonder if some of @c42f's work on expression parsing and such would facilitate the requested change in printing here (i.e. printing the long-form NamedTuple instead of (function = 1,))

@quinnj I assume you refer to #32408? With the current syntax from that PR I think we could have (var"function" = 1,) in principle and that would be quite a general way of distinguishing between identifiers and keywords.

I think this would require additional changes to the parser in addition to #32408 and the pretty printer would definitely need more work. But it's a neat connection.

With #32408 merged we now have

julia> a = (var"function" = 1,)
(function = 1,)

So one part of this is solved.

The second part would be to detect reserved words when showing Exprs and print them with the var syntax so that this can be parsed again.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yurivish picture yurivish  路  3Comments

musm picture musm  路  3Comments

omus picture omus  路  3Comments

manor picture manor  路  3Comments

TotalVerb picture TotalVerb  路  3Comments