Thread overview
Get and add to function body
Oct 13, 2017
Jonathan M Davis
October 12, 2017
Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog).

Is any of this possible in D?
October 12, 2017
I'd also like to be able to save and store delegates, functions, and lambdas. One can't store the pointer to the function because it will be invalid, so another means is required, any ideas?

Save("f", (int){ ... }); // Saves to disk
auto f = Load("f"); // Loads from disk
f(3);






October 12, 2017
On Thursday, October 12, 2017 23:33:39 Psychological Cleanup via Digitalmars-d-learn wrote:
> Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog).
>
> Is any of this possible in D?

You can introspect on symbols in D using __traits, std.traits, and is expressions, and that will allow you to get a function's signature, but it is not possible to get at the function's body. If you want to extend a function by wrapping it, you can certainly generate a wrapper, but that will mean generating a new function that calls the original and not doing anything with the code inside of the original function. You cannot alter existing code when generating code at compile time. You can just examine existing code and generate new code.

- Jonathan M Davis

October 13, 2017
On 10/12/17 7:33 PM, Psychological Cleanup wrote:
> Is there any way to get the function body of a function, delegate, and lambda? I'd also like to extend functions by "wrapping" them at compile time generically. For example, I'd like to get all the properties of a class and add some code to them(sort of like adding a scope, prolog, and/or epilog).
> 
> Is any of this possible in D?

Something like this may work:

struct S(T)
{
   private T obj;
   auto ref opDispatch(string item, Args...)(auto ref Args args) {
       prolog();
       scope(exit) epilog();
       mixin("return obj." ~ item ~ args.length == 0 ? ";" : "(args);");
   }
}

Probably needs some more machinery to work for everything.

-Steve