Template-based Preprocessing

Kirk McDonald kirklin.mcdonald at gmail.com
Mon Sep 4 13:17:19 PDT 2006


Don Clugston wrote:
> Garett Bass wrote:
> 
>> Don Clugston wrote:
>>
>>> I've previously suggested the 'identifier' keyword for string pasting.
>>> Stringizing is already possible, you can find the code for 
>>> symbolnameof!() in dsource/ddl/meta, together with qualifiednameof!() 
>>> which is significantly more powerful than anything in C++.
>>
>>
>> Thanks, Don!  I now recall your suggestion from a thread I prompted 
>> about a year ago.  I've updated my example to use your suggested 
>> 'identifier' keyword, as this obviates the need for my suggested 
>> 'token' keyword:
>>
>>    template Serializable(T, char[] I) {
>>        T identifier(I);
>>           string identifier("serialize_" ~ I)() {
>>            return toString(identifier(I));
>>        }
>>    }
>>
>>    class Foo {
>>        mixin Serializable!(int, "i");
>>    }
>>
>> Foo should expand to the equivalent of:
>>
>>    class Foo {
>>        int i;
>>
>>        string serialize_i() {
>>            return toString(i);
>>        }
>>    }
>>
>> Do you have any idea what's involved in implementing the 'identifier' 
>> keyword as described here?
> 
> 
> I don't know. It's clearly easy to get through the syntactic pass. But 
> does it cause problems during name lookup?
> 
> More importantly, would it encourage bad coding styles? IMHO, it needs 
> some convincing use cases -- or, if Walter gets more experimental 
> post-1.0, this would be an extremely cool thing to try out. (It would 
> kill one of the last metaprogramming things C++ still has compared to D).

I have a use-case. In the Python/C API, a module must have an init 
function named "init" ~ module_name. This function is called by Python 
when the module is imported. The init function must furthermore contain 
a call to the Py_InitModule function (or one of its variants), which 
takes the name of the module as a string argument. If we have a module 
named "foo", we might say:

extern(C)
export void initfoo() {
     Py_InitModule("foo", null);
}

Boost.Python wraps this business with some preprocessor tricks. The 
following is more or less equivalent to the above code:

BOOST_PYTHON_MODULE(foo) {
}

I cannot do this in Pyd. The only difference between Pyd code and the 
first example above is that the user must call Pyd's module_init 
function rather than Python's Py_InitModule. With the proposed 
"identifier" keyword, I could get rid of the burdensome "init" function 
definition, and the redundancy of specifying "foo" twice (both in the 
function name and in the call to the init function).

More generally, this syntax would help D interface with other C 
libraries that expect special function names like this.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org



More information about the Digitalmars-d mailing list