p4c icon indicating copy to clipboard operation
p4c copied to clipboard

Switch statement: default label has to be last (according to specification)

Open MichalKekely opened this issue 2 years ago • 1 comments

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?

MichalKekely avatar Dec 13 '23 15:12 MichalKekely

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.

mihaibudiu avatar Dec 13 '23 17:12 mihaibudiu

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:

    1. everything after default is dead code;
    2. order does not matter, default is the "last resort" option.

    This on itself makes this tricky as there is a risk different backend will implement this differently!

But there is more:

  • switch is modeled to be similar to the C-style switch, except for the break/fallthrough semantics, 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 switch is very similar to select and for select the order clearly matters. Anything after default/_ is dead code. This is even explicitly mentioned in the spec ("Note that this implies that all cases after a default or _ label are unreachable").
  • The only way to be somewhat consistent both between switch and select and between P4 switch and C switch is to disallow case-after-default for the P4 switch. I'm not sure if we can disallow it for select too, that might be unexpected.

vlstill avatar Jul 23 '24 06:07 vlstill