Is metaprogramming useful?

Georg Wrede georg.wrede at nospam.org
Thu Nov 30 03:05:35 PST 2006


Jarrett Billingsley wrote:
> "Georg Wrede" <georg.wrede at nospam.org> wrote in message 
> news:456E1768.7090504 at nospam.org...
> 
> 
>>If we had Perfect Metaprogramming(TM) in D, then I could do the following:
>>
>>  I'm coding some stuff and I notice that what I'd really want
>>  is a new keyword, "unless", that would make it so much easier
>>  for me to write this application clearly. I decide to create it.
>>
>>  I want to use it like this
>>
>>    unless (fullMoonTonight) { doRegularStuff() }
>>
>>  So, to create such a thing in D, I'd write something like
>>
>>    define("unless", "(", BooleanExpression, ")", BlockStatement)
>>    {
>>      if(!BooleanExpression) BlockSTatement;
>>    }
>>
>>Now, if I'd made errors in writing the meta code, then the compiler would 
>>error me, of course. No biggie. And since the D compiler would understand 
>>what's going on (as opposed to the C preprosessor or compiler), the error 
>>messages would be what we're used to in D.
>>
>>Later, when I actually use the "unless" construct, again the error 
>>messages would be normal because D now understands what "unless" is all 
>>about.
> 
> Unfortunately, that then breaks the separation of the 
> lexical/syntactic/semantic passes.  The define statements have to be 
> syntaxed and semantic'ed before any other code can be even syntaxed.

Not necessarily.

If we wanted the metalanguage to let us do a hairy definition that, say, 
lets us use ][ as an operator, then yes, it breaks the separation.

But if we restrict ourselves to the kind of things done in the "unless" 
example, then there is no risk of this breakage.

You can think of it like this: had Walter wanted to implement "unless" 
last week in D, we'd have no problem today with the separation, right? 
So, if our metalanguage lets us do only things "Walter could have done 
without touching the parser", then this separation issue doesn't exist.

> One way around this would be to have some kind of "d metamodule" file which 
> would define all the metacode.  Those metamodules would be compiled first, 
> allowing the compiler to compile the normal D code.  Scary. 

It doesn't have to be scary. All it means is that some things (like 
"unless" above) are valid somewhere in the code, and not valid somewhere 
else. The word for that is scope. We do it currently with functions, and 
nobody complains.

So you could look at the meta definition like just an ordinary function 
definition. I honestly think that if we'd had this in D all along, folks 
would hardly notice.



More information about the Digitalmars-d mailing list