>> Ah, yes.  So we should share the parsing of the decl-specifier-seq with the
>> C-style for loop, which allows us to avoid the tentative parsing.
>
> That was my original idea, but the C-style loop calls
> cp_parser_simple_declaration(), that shouts at the ':'. So we should
> either modify it to accept the ':' or split it in two. Both options
> are well beyond my intentions.

I just implemented "fast enumeration" (ie, "for (object in array) { ... }")
for Objective-C, and I was now planning on doing it for Objective-C++ too. ;-)

If you're doing range-based for-loops for C++, we may as well share ideas ;-)

What I've done for Objective-C fast enumeration (and what Apple did before me 
as well)
is implemented your idea of modifying the declaration parsing to accept ':' 
(well, 'in'
in the ObjC case) to terminate a declaration in that context:

 * when you start parsing the 'for', a flag is turned on in the parser that 
means that
we are "maybe in a fast enumeration"

 * then, you go on parsing your usual C for loop, but the code that parses 
expressions/declarations
has a special case for when it's "maybe in a fast enumeration", in which case 
it accepts
"in" as terminating the expression/declaration (as well as ";"), and moreover 
if it finds "in" in
there, it will save the declaration specially and make sure to communicate back 
to the for
parsing code that we are "really" in a fast enumeration

 * when the initial expression/declaration has been parsed, the for parsing 
code turns off the 
"maybe in a fast enumeration" flag; it now knows whether it's a normal for loop 
or a fast enumeration 
one and everything is easy from there on

It sounds like the same could apply to C++ range-based for-loops ?  Except you 
use ':' instead 
of 'in' ?  We could almost share the code - ie, set a single flag in the 
C++/ObjC++ parser to say we are
at the beginning of a 'for' loop, and have that flag turn on recognizing ':' 
(for range-based loops) 
and 'in' (only if (dialect_objc()), for fast ObjC++ enumeration) as terminating 
declarations.

The main disadvantage of doing things this way is making sure you won't 
misunderstand a ':' (or 'in')
as meaning a range-based for-loop (or fast enumeration loop) when it isn't.  
The best defense IMO is to
make sure ":" is only recognized in this way at the end of a declaration (where 
normally a ';' would be)
(this is harder in Objective-C, but should be easier in Objective-C++).

It's worth trying to think of valid cases where you'd use a ":" inside a C for 
loop though.

Anyway, let me know if this makes any sense or if I missed everything.  Am I 
right that the beginning
of a C++ range-based for-loop is identical to a standard C for loop up until 
the ':' ?  If not, obviously
this technique won't work. ;-)

Thanks

Reply via email to