Bug #18883
closedparse.y: trailing comma cannot coexist with star
Description
The following code is a syntax error:
*x, y, = 1, 2 # syntax error, unexpected '='
although the following:
x, y = 1, 2 # OK
x, y, = 1, 2 # OK
*x, y = 1, 2 # OK
# *x, y, = 1, 2
In my understanding, the trailing comma does nothing unless the lhs becomes otherwise a single assignment.
Therefore it is natural to allow the trailing comma whether *
exists or not.
Updated by zverok (Victor Shepelev) over 2 years ago
As far as I understand, trailing comma is an equivalent of *_
(unpack the rest and drop it):
x, = [1, 2, 3]
# is the same as
x, *_ = [1, 2, 3]
# put 1 in x, ignore the rest, it is the shortest way to do it
So the fact that it is prohibited syntactically is in line with the fact that *x, y, *z = ...
are also prohibited: Ruby can't handle two unpacks in one assignment.
If this would be allowed, what would be the semantics of it?..
*x, y, = 1, 2, 3
*x, y, *z = 1, 2, 3
What it should put in x
and y
?..
Updated by jeremyevans0 (Jeremy Evans) over 2 years ago
zverok (Victor Shepelev) wrote in #note-1:
As far as I understand, trailing comma is an equivalent of
*_
(unpack the rest and drop it):x, = [1, 2, 3] # is the same as x, *_ = [1, 2, 3] # put 1 in x, ignore the rest, it is the shortest way to do it
Close. *_
will set a local variable, and allocate an extra array. x, = [1, 2, 3]
is actually the same as x, * = [1, 2, 3]
(same VM instructions). However, this doesn't fully explain the issue, because x =
(single assignment) and x, =
(multiple assignment) are significantly different. It would be better to compare with:
x, a = [1, 2, 3]
x, a, = [1, 2, 3]
x, a, * = [1, 2, 3]
All of these result in the same VM instructions, indicating that a trailing comma shouldn't make a difference.
That being said, I don't think this is a bug, but I wouldn't be opposed to modifying the parser to support this as a feature, assuming it is doable.
Updated by jeremyevans0 (Jeremy Evans) over 2 years ago
- Status changed from Open to Rejected
After giving this some more thought, I am fairly sure this is not a bug, and I'm rejecting this. @zverok (Victor Shepelev) is correct, a trailing comma is an implicit splat, and you cannot have multiple splats in a multiple assignment, so a syntax error is the correct behavior in this case.