another idea for compile time functions

janderson askme at me.com
Thu Feb 8 22:18:36 PST 2007


Andrei Alexandrescu (See Website For Email) wrote:
> Hasan Aljudy wrote:
> [snip]
>> The trick may lie in letting the compiler recognize these kind of 
>> functions. A simple solution might me to come up with a new attribute; 
>> let's call it "meta":
>> # meta int add( int x, int y ) { return x + y; }
>> This attribute will assist the compiler in recognizing that this 
>> function can be computed at compile time if it's given constant 
>> arguments.
> 
> This is much in keep with my idea on how metaprogramming should be done, 
> with the little semantic nit that "meta" should be "dual" as add has 
> dual functionality.
> 
> The attribute is not even needed if meta-code is flagged as such. My 
> thoughts currently gravitate around the idea of using mixin as an escape 
> into compile-time world. Anything that's printed to standard output in 
> compile-time world becomes code, e.g. (using your function):
> 
> mixin
> {
>   writefln("int x = ", add(10, 20), ";");
> }
> 
> is entirely equivalent to:
> 
> int x = 30;
> 
> No annotation is needed on add because mixin clarifies that it's called 
> during compilation. The compiler will complain if add cannot be user 
> dually.
> 
> Using mixin and write as separation devices makes it very clear what is 
> to be done when; otherwise, it quickly becomes confusing what code is 
> meant to actually get evaluated eagerly, and what code is to actually be 
> "output" for compilation.
> 
> The not-so-nice thing is that we get to manipulate numbers, strings, and 
> arrays, not trees like in LISP.
> 
> 
> Andrei

Although I like this idea, I fear it will not work for anything hidden 
in a library (if you are using something that is moved to a .lib, your 
code will stop working).  Maybe that's ok.  Actually now I think about 
it, that would be safer, because even if the D compiler could put an 
"ok" signatures in a library, someone could create fake signatures.

It could get confusing if you don't know which functions will work and 
which won't.  Perhaps the compiler could help there (spit out a list of 
functions u can use or something).

I think the compiler would compile these commands on demand and cache 
them so it doesn't need to do them every time.  That would help a lot. 
It could even cache results so it only needs to compute them once.

Anyways, there i think there is so much possibility with compile time 
coding.

-joel



More information about the Digitalmars-d mailing list