I recently found out that gcc allows the definition of nested function. In my opinion, this is a cool feature, but I wonder how to implement it.
While it is certainly not difficult to implement direct calls of nested functions by passing a context pointer as a hidden argument, gcc also allows to take a pointer to a nested function and pass this pointer to an arbitrary other function that in turn can call the nested function of the context. Because the function that calls the nested function has only the type of the nested function to call, it obviously can't pass a context pointer.
I know, that other languages like Haskell that have a more convoluted calling convention allow partial application to support such stuff, but I see no way to do that in C. How is it possible to implement this?
Here is a small example of a case that illustrates the problem:
int foo(int x,int(*f)(int,int(*)(void))) {
int counter = 0;
int g(void) { return counter++; }
return f(x,g);
}
This function calls a function that calls a function that returns a counter from the context and increments it at the same time.