DIP 50 - AST macros

IgorStepanov wazar at mail.ru
Mon Nov 18 13:08:11 PST 2013


On Monday, 18 November 2013 at 19:21:35 UTC, Kapps wrote:
> On Monday, 18 November 2013 at 16:03:54 UTC, IgorStepanov wrote:
>>
>> How macros implemented in C#?
>> I know, that C# have linq which can translate lambda 
>> expression to SQL WHERE condition. For example s => s.Number > 
>> 2 && s.Number < 20 can be translated to ... WHERE s.Number > 2 
>> AND s.Number < 20
>>
>> It is interesting function, because it allow to write hard 
>> code in preferred language (C#, D) instead of unpreferred 
>> (SQL). Also this code hides poorly standardized SQL for the 
>> well-standardized language.
>>
>> And С# still not sinking under tons of macro. May be C# has 
>> some limitations for ast macros. May be they allowed only for 
>> lambda?
>>
>> This is a general macro-feature which I had like to see in D.
>
> C# doesn't have macros. Linq to Sql is implemented using 
> expression trees. Essentially, it allows the compiler to 
> generate an expression tree of the lambda expression which your 
> library parses to do some work. It doesn't inject any code, and 
> it's done at runtime. I could be wrong about the exact details, 
> but essentially it comes down to the compiler passing in an 
> expression tree into your method, and then your method parsing 
> it at runtime and doing something with the results; it can't be 
> used to generate new code.

May be this way is good for D? And CTFE allow to parse this tree
at compile-time.
Something like:

@property Collection where(alias cond, Collection)(Collection c)
{
      enum ast = cond.astof;
      static if(is(Collection : DBResultSet))
      {
         string where_cond = generateCondition!(ast, Collection);
         return c.doWhere(where_cond);
      }
      else
      {
         ...
      }
}

...

auto result = db.myItems.where!(x => x.Count > 10);


More information about the Digitalmars-d mailing list