[cfe-commits] [PATCH] C++0x range-based for loop

Richard Smith richard at metafoo.co.uk
Sun Mar 20 16:56:34 PDT 2011


Hi,

The attached patch adds support for C++0x's range-based for loops to
clang, according to the current draft (N3242). Specifically:

A new Stmt subclass, CXXForRangeStmt, has been added. This class provides
two views of the for-statement: a partially-desugared representation (just
enough desugaring is done to be able to perform the semantic checks
needed), and an implicit source-as-written representation (extracted from
the partially-desugared representation).

In order to avoid tentative parsing, the parsing of the
for-range-declaration is performed by ParseSimpleDeclaration. The
for-range-initializer is parsed there too, in order to ensure that the
for-range-declaration is not in scope in the initializer: "int a =
{1,2,3}; for (auto a : a)" appears to be legal.

Most of the semantic analysis for a for-range statement is performed
before the body is parsed, so that the type of the loop variable can be
deduced (in case it contains 'auto'). Attaching the body is performed as a
separate finalization step.

For a dependently-typed range expression, much of the semantic analysis is
deferred until template instantiation time. A new flag has been added to
VarDecl to indicate whether it's a for-range-declarator. This flag is used
to skip ActOnUninitializedDecl (specifically, while instantiating a
template containing a dependent for-range statement); such declarators are
never actually uninitialized, but appear that way in the AST if the
required semantic analysis could not be performed.

As a small extension, this implementation allows the deduced 'begin' and
'end' iterators to be of differing types; this allows for-range to be used
for iterators where it's easy to determine whether an iterator is at the
end, but difficult or expensive to construct an explicit iterator object
representing the 'end', or to compare general iterators.

The wording for for-range statements seems likely to change at the
upcoming WG21 meeting in Madrid (per N3257). Resolution 2 for this change
can be implemented by changing the NeedsADL flag from true to false in
BuildForRangeBeginEndCall in SemaStmt.cpp.

Please review!

Thanks,
Richard
-------------- next part --------------
A non-text attachment was scrubbed...
Name: clang-for-range.diff
Type: text/x-patch
Size: 82171 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20110320/52466365/attachment.bin>


More information about the cfe-commits mailing list