www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - feature idea: function enumeration

While talking to an ex-professor of mine (he's still a proof, just not mine) 
he made the clam that the use of function pointers make it hard, if not
impossible, 
to engineer high assurance programs. The problem is that function pointers 
result in code that can go from just about anywhere to just about anywhere. 
The idea of allowing function pointers but restricting the values that they 
could take on (as with an enumeration) came up. His response was that such 
a system would be almost as good as totally avoiding function pointers all 
together. The advantage would be that the type could only be assigned a value 
from another variable of the same type of from a constant from the type it's 
self. This would (barring pointer magic and unions) allow strong clams about 
what calling such a variable could do. In one sense it would get a lot of 
the benefits of virtual functions.

enum fn_enum: int function(Stream)
{
	foo = DoFoo;
	bar = DoBar
	baz = int function(Stream str){return str.writef("Hello world");}
};

fn_enum fe = fn_enum.foo, other;

fe = null; //error
fe = int function(String s){return 0;} //error

other(new File("foo")); // ?? don't known what should be done here

other = fe; // ok


An even better system would be to have a construct that didn't carry the 
function pointer its self but carried a key that references the pointer, 
it would be a lot like an AA:

int function()[enum]

It would be a type that is always stored as a key, but when used as a value, 
undergoes a range check and table look-up. with a little care it could even 
be used convey actions from one system to another.

This could be safe:

keydef KeyValue : DataObject function(Stream)
{
	ReadV1File = ReadVertion1File;
	ReadV2File = ReadVertion2File;
}

KeyValue var;

Stream str = new File(filename);

// get key value from file
str.read(var);

// call function value (does a lookup and range check)
auto data = var(str);

If this were implemented, there would be no reason to limit it to function 
pointers.

All of this could be done with AA's (if AA literals ever work) or normal 
arrays and enums. However the "fully static" nature of it and the syntactic 
sugar appeals to me.`
Feb 01 2007