Compile time function execution...

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Thu Feb 15 13:54:58 PST 2007


Walter Bright wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>> There is a need for a couple of ancillary features. Most importantly, 
>> a constant must be distinguishable from a variable. Consider the 
>> example of regex from our correspondence:
>>
>> bool b = regexmatch(a, "\n$");
>>
>> vs.
>>
>> char[] pattern = argv[1];
>> bool b = regexmatch(a, pattern);
>>
>> You'd want to dispatch regexmatch differently: the first match should 
>> be passed to compile-time code that at the end of the day yields:
>>
>> bool b = (a[$-1] == '\n');
>>
>> while the second should invoke the full-general dynamic pattern 
>> matching algorithm since a dynamic pattern is used.
> 
> I think that can be done with an improvement to the existing compile 
> time regex library.

The answer is correct, but does not address the issue I raised.

A simple question is: what is the signature of regexmatch? A
runtime-only version is:

bool regexmatch_1(char[] input, char[] pattern);

A compile-time-only version is:

bool regexmatch_2(pattern : char[])(char[] input);

Notice how the two cannot be called the same way. So the burden is on
the user to specify different syntaxes for the two cases:

bool b1 = regexmatch_1(a, ".* = .*"); // forced runtime
bool b2 = regexmatch_2!(".* = .*")(a); // forced compile-time

Notice that b2 is NOT computed at compile time!!! This is because "a" is
a regular variable. It's just that the code for computing b2 is
radically different from the code for computing b1 because the former
uses static knowledge of the pattern.

The problem is that what's really needed is this:

bool b = regexmatch(string, pattern);

and have regexmatch dispatch to regexmatch_1 if pattern is a variable,
or to regexmatch_2 if pattern is a compile-time constant.

Do you feel me?

What we need is allow a means to overload a function with a template, in
a way that ensures unified invocation syntax, e.g.:

bool regexmatch(char[] str, char[] pat); // 1
bool regexmatch(char[] pat)(char[] str, pat); // 2
bool regexmatch(char[] pat, char[] str)(str, pat); // 3

void main(int argc, char[][] argv)
{
   regexmatch(argv[0], argv[1]); // goes to (1)
   regexmatch(argv[0], ".+"); // goes to (2)
   regexmatch("yah", ".+"); // goes to (3)
}

Notice how the invocation syntax is identical --- an essential artifact.


Andrei



More information about the Digitalmars-d mailing list