Boost logo

Boost :

Subject: Re: [boost] compile time parser generator
From: Dave Abrahams (dave_at_[hidden])
Date: 2012-01-09 09:36:49


on Mon Jan 09 2012, Ábel Sinkovics <abel-AT-elte.hu> wrote:

> Hi Dave,
>
>> constexpr is somewhat crippled: although a constexpr function
>> executes at compile-time, it has to obey the same rules as any other
>> function. For example, its return type can depend on the type, but
>> never on the *value*, of its arguments, and once you're inside the
>> function, the contents of the argument are not treated as
>> compile-time constants. So, I think constexpr actually doesn't
>> promise it.
> A constexpr can still be used to access the characters of a string at
> compile-time. Having access to each character we can build an MPL list
> of characters. Here is an example of what I'm thinking of:
>
> ----
>
> using namespace boost::mpl;
>
> template <int N>
> constexpr char nth(const char s[N], int n)
> {
> return n >= N ? 0 : s[n];
> }
>
> #define S "cool"
>
> typedef
> push_back<
> push_back<
> push_back<
> push_back<
> push_back<
> push_back<
> string<>,
> char_<nth<sizeof(S)>(S, 0)>
>>::type,
> char_<nth<sizeof(S)>(S, 1)>
>>::type,
> char_<nth<sizeof(S)>(S, 2)>
>>::type,
> char_<nth<sizeof(S)>(S, 3)>
>>::type,
> char_<nth<sizeof(S)>(S, 4)>
>>::type,
> char_<nth<sizeof(S)>(S, 5)>
>>::type
> str;
>
> int main()
> {
> std::cout << c_str<str>::type::value << std::endl;
> }
>
> ----

Yeah, what you can't do is:

1. generate that type based on the /value/ of a function argument (yes,
   you can deduce the length of the string, and thus that type, from the
   /type/ of a string literal argument).

2. Generate any types or choose template specializations based on the
   actual characters used in the string literal. I don't see how you're
   going to generate anything other than a table-based regexp recognizer
   if you can't do that.

The fundamental limitation with constexpr functions is that the function
you're calling must be valid even if its arguments are /not/
compile-time constants. Combine that with the lack of raw user-defined
string literals, and, well... we're cooked.

> The code getting the characters one by one and building the MPL list
> (or string in the above example) can be generated by a macros - I know
> it is not that nice and the length of the string will be tricky, but
> we'll have something. The above code snippet compiles with gcc 4.6.

If you can demonstrate something that works, I'll be really excited.

-- 
Dave Abrahams
BoostPro Computing
http://www.boostpro.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk