5 ms·
What's more curious than the irreducability issue is, how on earth does the syntax ever get accepted by the parser? I mean the lex/yacc syntax has to reflect t
by oneoff14326 5y ago
What's more curious than the irreducability issue is, how on earth does the syntax ever get accepted by the parser?
I mean the lex/yacc syntax has to reflect the nestability of the while/switch [1], ditto if you do recursive descent, so how is it possible this even parses?
[1] original and weirder version here https://en.wikipedia.org/wiki/Duff%27s_device#Original_version https://en.wikipedia.org/wiki/Duff%27s_device#Original_versi...
- mananaysiempre 5y agoBecause the switch statement is not multiple conditions with a funny syntax, it is a computed goto with funny labels. Those labels are permitted to be anywhere at all inside its associated statement, including perverse things like switch (x) default: { if (y) case 1: case 2: return; /* more stuff with more labels */ }
- Joker_vD 5y agoUgh, very simply? Any STATEMENT is allowed to be, among other things, a LABELED_STATEMENT which is (<ident> ":" STATEMENT | "case" <constexpr> ":" STATEMENT | "default" ":" STATEMENT). Then in the semantic pass it's checked that labeled statements starting with case/default must be inside some switch. That's it.
- Sharlin 5y agoThis is a good question. The grammar of the C switch statement is not context-free. In practice this is easiest to resolve by just allowing case labels (which in the end are just decorated goto labels!) to appear anywhere, when it comes to parsing, and only check the existence of an enclosing switch during semantic analysis, which is necessarily context-sensitive anyway.
- mananaysiempre 5y agoWhere’s the problem for context-freeness here? Just have two copies of every statement production, one that doesn’t allow for case labels and one that does, have function bodies start as the former and switch bodies unconditionally switch to the latter. It’d be thoroughly unpleasant to deal with in an implementation and not very helpful for the eventual user, but as a pure existence proof I don’t see any problems.
- Sharlin 5y agoYes, that's true. Maybe I should say that it's effectively context-sensitive. In any case, the grammar as specified by the standard is context-free and the restriction of where case labels can occur is a separate semantic requirement.