Switch statement: default label has to be last (according to specification)
Currently the default label of switch statement can be used in any order within the other labels. The frontend only treats this as warning: https://github.com/p4lang/p4c/blame/def92ac0a02318834f959cc7b4aa5d27efa82ae7/frontends/p4/validateParsedProgram.cpp#L197
However, according to the specification: "It is optional to have a switch case with the default label, but if one is present, it must be the last one in the switch statement."
So should this be elevated to error?
I think someone else can tackle this. I don't plan to work on it. In some cases it's fine for a compiler to be more liberal than the spec.
In some cases it's fine for a compiler to be more liberal than the spec.
I am strongly of the opinion this is not a case for that. Let me explain:
-
There are two possible acceptable semantics for this:
- everything after
defaultis dead code; - order does not matter,
defaultis the "last resort" option.
This on itself makes this tricky as there is a risk different backend will implement this differently!
- everything after
But there is more:
switchis modeled to be similar to the C-style switch, except for thebreak/fallthroughsemantics, which is improved. Overall, the similarities between C and P4 make it easy to expect the semantics will be the same, with P4 being more cauctius. The C semantics is the "order does not matter" one.- But
switchis very similar toselectand forselectthe order clearly matters. Anything afterdefault/_is dead code. This is even explicitly mentioned in the spec ("Note that this implies that all cases after adefaultor_label are unreachable"). - The only way to be somewhat consistent both between
switchandselectand between P4switchand Cswitchis to disallowcase-after-defaultfor the P4switch. I'm not sure if we can disallow it forselecttoo, that might be unexpected.