c2compiler icon indicating copy to clipboard operation
c2compiler copied to clipboard

Support usage of function types without aliasing

Open Dandigit opened this issue 7 years ago • 4 comments

C2 currently supports function pointer types through aliasing:

type HandlerFunc func bool(char*);

func void passHello(HandlerFunc handler) {
    handler("hello");
}

This is great, and it's a big improvement over C. However, currently, it's not possible to do the following:

func void passHello(func bool(char*) handler) {
    handler("hello");
}

Just using the function type without aliasing is not currently supported. I believe that it should be added for consistency's sake.

Dandigit avatar Jan 14 '19 00:01 Dandigit

Yeah, I think that makes sense too although might be difficult to read as a return type?

lerno avatar Jan 14 '19 01:01 lerno

Agreed. It'd be considered best practice to alias the type for better readability, however if you are just using it trivially, you have the freedom not to.

Dandigit avatar Jan 14 '19 01:01 Dandigit

If it's to be in the lang then it needs to parse correctly, so I wonder if that might be an issue. Consider:

func func bool(char*)* return_a_hello_function()

It's a bit better with mandatory ():

func (func bool(char*))* return_a_hello_function()

Still... I'm on the fence about this. Not using an alias does reduce readability quite a bit. It might be good to actually "force" the alias.

lerno avatar Jan 14 '19 10:01 lerno

There are a few cases where function pointer declarations are needed:

  • function argument (your example)
  • variable/struct member
  • return type

What I don't like in C is that you have to change the prototype in several places if you want to change the prototype of the function. This is especially nasty in the case of function argument and return type. For the case of the struct member, you often only specify the prototype in 1 place, like: (C-code)

typedef struct Mystruct {
   int (*handler)(char*);
}

In this case, the C2 solution requires more typing because it becomes:

type Handler func i32(char*);
type Mystruct struct {
    Handler handler;
}

This get worse if your code uses a lot of different function pointers in a struct.

What I also don't like about C is the syntax for function pointers. The name is hidden in the middle instead of type name.

So I understand your argument and agree, but I think the alternative is worse in my opinion..

bvdberg avatar Jan 16 '19 10:01 bvdberg