Subject: Switching the Emacs build to -Wswitch-enum in src/

From: Pip Cet <[email-masked]>
Date: Fri, 31 Jan 2025 09:39:45 +0000

I'm proposing to enable -Wswitch-enum as a warning option when compiling
Emacs C sources in src/, and to modify those source files to make good
use of it.

GCC's -Wswitch-enum will warn about a switch statement of the form

enum ABC { A, B, C };

enum ABC x = ...;

switch (x)
{
  case A:
  case B:
    return 1;
  default:
    return 0;
}

The reason is that the "default" branch covers both case C and the case
that the value of x isn't A, B, or, C.  C allows this latter case and
requires compilers to support it, and some Emacs code relies on
non-enumerated values to be valid.

Instead, with -Wswitch-enum, one should write:

enum ABC { A, B, C };

enum ABC x = ...;

switch (x)
{
  case A:
  case B:
    return 1;
  case C:
    return 0;
  default: eassume (false);
}

assuming x is known never to have a non-enumerated value (this is almost
always the case in Emacs).

The limitations of other approaches have become quite apparent in
previous threads discussing this.  Let's try this one.

While I think we can and should argue about the best way to write a
switch statement over an enum, I want to state one personal opinion:
replacing switch statements by if constructs, array lookups, or even
array lookups of function pointers is the wrong approach here.

Some preliminary patches to follow once this has a bug number.

Pip