opa icon indicating copy to clipboard operation
opa copied to clipboard

New "if" keyword does not work for else conditions

Open anderseknert opened this issue 3 years ago • 7 comments

I would expect if to work the same following an else condition as it works for any other conditional assignment:

package play

import future.keywords.if

foo := true if {
	input.foo
} else := true if {
	input.bar
} else := false

Alternatively, without explicit assignment of true:

foo if {
	input.foo
} else if {
	input.bar
} else := false

Actual outcome:

1 error occurred: policy.rego:7: rego_parse_error: unexpected if keyword: expected else value term or rule body
	} else if {
	       ^

anderseknert avatar Aug 11 '22 12:08 anderseknert

I would expect if to work the same following an else condition as it works for any other conditional assignment

Hmm I wouldn't. 😅 I suppose it depends on whether you see the else as "attached" to the if or not. 🤔

srenatus avatar Aug 15 '22 11:08 srenatus

Interesting 😄 To me it's just another form of (ordered) conditional assignment, ie. "... else foo is true if { ... }" If not read that way, how is it supposed to be read? 🙂

anderseknert avatar Aug 15 '22 11:08 anderseknert

"foo is true if ...; else it is true [if] ...; else it is false"

Hmm yeah it reads weird without the if.

srenatus avatar Aug 15 '22 12:08 srenatus

This issue has been automatically marked as inactive because it has not had any activity in the last 30 days.

stale[bot] avatar Sep 14 '22 12:09 stale[bot]

I would expect if to work the same following an else condition as it works for any other conditional assignment

Same expectation. I was very happy when the "if" keyword was added to the grammar (it especially helps improve readability for those new to Rego), but the lack of "else if" leaves a gap here.

aarcamp avatar Sep 18 '22 14:09 aarcamp

🤔 The tricky thing here is forward compatibility: old OPA versions compiling new Rego policies. So far, we've been able to say that if an opa version knows the if future keyword, feeding it policies using that import is OK. If we introduce the else if construct without any new guard, we lose that: policies that use else+if would fail on some OPA versions with future kw capability for if and succeed with others (the more recent ones).

srenatus avatar Sep 19 '22 10:09 srenatus

That's a good point. I guess something like import future.keywords.elseif could be a way forward, but it would certainly be more ergonomic to skip that requirement. I guess we could also consider having more advanced conditions be part of an import, perhaps when looking into https://github.com/open-policy-agent/opa/issues/5105

anderseknert avatar Sep 19 '22 11:09 anderseknert