google/skylark

multiple `if` filters in list comprehension does not work

Closed this issue · 1 comments

nicks commented

Consider the following code:

$ skylark
Welcome to Skylark (github.com/google/skylark)
>>> x = ["a"]
>>> [f for f in x if x == "a" if x == "b"]
... 
<stdin>:1:27: conditional expression without else clause

According to the Skylark spec, this should be valid. The skylark spec defines list comprehensions like this:

ListComp = '[' Test {CompClause} ']'.
CompClause = 'for' LoopVariables 'in' Test
           | 'if' Test .

So the second if clause should be parsed as a CompClause. Instead, it appears to be trying to parse the second if clause as a IfExpr

Arguably, this is a bug in the grammar. The Python3 grammar has a workaround for this issue, defining list comprehensions like this:

comprehension ::=  expression comp_for
comp_for      ::=  "for" target_list "in" or_test [comp_iter]
comp_iter     ::=  comp_for | comp_if
comp_if       ::=  "if" expression_nocond [comp_iter]

Thanks for reporting this. See #55