[fpc-devel] Data flow analysis (dfa) and "case ... of"

Juha Manninen juha.manninen62 at gmail.com
Fri Jun 9 08:20:11 CEST 2017


On Thu, Jun 8, 2017 at 3:22 AM, Denis Kozlov <dezlov at gmail.com> wrote:
> I can't control what values other users/developers may supply, nor I
> restrict the use of different compiler versions and build flags.

Compiler flags have nothing to do with the fundamental issue here.
If other developers supply buggy code to you, then they have to fix it
obviously. This holds true for any bugs.

> It is because "TConvertType(-1)" and the likes are an acceptable statement for
> compiler, I make it my responsibility to handle all possible input values,
> no matter how illogical and invalid they may be. This is a design pattern
> that I follow.

You have good intentions but somehow your logic slipped to a wrong track.
You must prevent invalid data entering an enum variable in the first place.
So, if you get integer data from eg. stream or user input and convert
to enum, you must ensure the integer is within range _before_
typecasting it.
Like:
  if (i<0) or (i>Integer(High(TConvertType))) then
    raise Exception.CreateFmt('Invalid convert value (%d)', [i]);
  ctvar := TConvertType(i);

Typecast is always a "serious" thing. It means the original type is
wrong and must be forced to something else.
Obviously you need a sanity check there!
There is only a limited number of places where you set an enum
variable. It is rather easy to make sure the value is sane. After that
you don't need to worry about it, the value is valid always.

Your extra checks for enum values are like a desperate band-aid for a
bug that happened already elsewhere. No, a bug must be fixed where it
is.

Juha



More information about the fpc-devel mailing list