compile-time access to parsed code

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Sun Feb 11 11:23:55 PST 2007


Hasan Aljudy wrote:
> alot of ideas for DSL that are coming up are really just additions of 
> feature to already existing concepts in D.
> 
> For example, mapping a DB table/row to a D class/object.
> One would probably do something like:
> mixin( Model!(
>    "Person:
>      char[100] name;
>      int       age;
>      ForeignKey(Car)  car;
>    "
> ))

I don't think so. The underlying motivation for mapping DB structure to 
D code is to "not repeat yourself". Here you are repeating yourself, 
because you specify a snippet of what looks like SQL, but inside D code 
so you'll need to write that somewhere in the database itself.

The DRY approach is to have the D code peek the database structure 
directly and generate the appropriate code. Then you benefit of keeping 
the two in sync without effort.

> and then one would have to write a parser for that, which will 
> essentially produce a regular D class, with the same attributes, plus 
> some additional magic:
> 
> class Person
> {
>      char[100] name;
>      int       age;
>      ForeignKey!(Car)  car;
> 
>      //magic
>      load( ... );
>      save( ... );
>      query( ... );
>      //etc
> }
> 
> 
> Here, one is essentially adding magic features to classes, but there's a 
> lot of re-invention of the wheel going on here.
> 
> Wouldn't it be much better if we simply write the code in D, and get 
> access to its parsed form at compile-time and modify it?
> 
> like, just write:
> class Person
> {
>      char[100] name;
>      int       age;
>      ForeignKey!(Car)  car;
> 
>      mixin(DBMagic!( typeof(this) ));
> }
> 
> then, somewhere else, we define DBMagic as a template or function or 
> whatever, and this function would recieve a paramter of type Class which 
> would have all the attributes of the Person class, the function can read 
> those attributes and figure out how to return a string containing 
> definitions of magic methods.
> 
> A better alternative is reading the class at compile-time and /changing/ 
> the class (without emitting code) by adding attributes and methods to 
> it, using something like:
> class.addAttribute( Type, name );
> class.addMethod( Type, name, params, ..... )
> 
> That would be much more robust than emitting strings .. no?

I don't think so. This is pretty much getting back to the old way of 
doing things - writing things twice and crossing fingers that they'll 
stay in sync.


Andrei



More information about the Digitalmars-d mailing list