blob: 68eff7cf5f84ce030151143403ed63f069fd720b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattner500d3292009-01-29 05:15:15 +000014#include "clang/Parse/ParseDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000015#include "clang/Parse/Parser.h"
Douglas Gregorbc61bd82011-01-11 00:33:19 +000016#include "RAIIObjectsForParser.h"
Eli Friedmandc3b7232012-01-04 02:40:39 +000017#include "clang/Basic/PrettyStackTrace.h"
Richard Smith33762772012-03-08 23:06:02 +000018#include "clang/Lex/LiteralSupport.h"
John McCall19510852010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
Douglas Gregorae7902c2011-08-04 15:30:47 +000020#include "clang/Sema/Scope.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor3f9a0562009-11-03 01:35:08 +000022#include "llvm/Support/ErrorHandling.h"
23
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25
Richard Smithea698b32011-04-14 21:45:45 +000026static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
27 switch (Kind) {
28 case tok::kw_template: return 0;
29 case tok::kw_const_cast: return 1;
30 case tok::kw_dynamic_cast: return 2;
31 case tok::kw_reinterpret_cast: return 3;
32 case tok::kw_static_cast: return 4;
33 default:
David Blaikieb219cfc2011-09-23 05:06:16 +000034 llvm_unreachable("Unknown type for digraph error message.");
Richard Smithea698b32011-04-14 21:45:45 +000035 }
36}
37
38// Are the two tokens adjacent in the same source file?
39static bool AreTokensAdjacent(Preprocessor &PP, Token &First, Token &Second) {
40 SourceManager &SM = PP.getSourceManager();
41 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000042 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smithea698b32011-04-14 21:45:45 +000043 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
44}
45
46// Suggest fixit for "<::" after a cast.
47static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
48 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
49 // Pull '<:' and ':' off token stream.
50 if (!AtDigraph)
51 PP.Lex(DigraphToken);
52 PP.Lex(ColonToken);
53
54 SourceRange Range;
55 Range.setBegin(DigraphToken.getLocation());
56 Range.setEnd(ColonToken.getLocation());
57 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
58 << SelectDigraphErrorMessage(Kind)
59 << FixItHint::CreateReplacement(Range, "< ::");
60
61 // Update token information to reflect their change in token type.
62 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000063 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smithea698b32011-04-14 21:45:45 +000064 ColonToken.setLength(2);
65 DigraphToken.setKind(tok::less);
66 DigraphToken.setLength(1);
67
68 // Push new tokens back to token stream.
69 PP.EnterToken(ColonToken);
70 if (!AtDigraph)
71 PP.EnterToken(DigraphToken);
72}
73
Richard Trieu950be712011-09-19 19:01:00 +000074// Check for '<::' which should be '< ::' instead of '[:' when following
75// a template name.
76void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
77 bool EnteringContext,
78 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieuc11030e2011-09-20 20:03:50 +000079 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu950be712011-09-19 19:01:00 +000080 return;
81
82 Token SecondToken = GetLookAheadToken(2);
83 if (!SecondToken.is(tok::colon) || !AreTokensAdjacent(PP, Next, SecondToken))
84 return;
85
86 TemplateTy Template;
87 UnqualifiedId TemplateName;
88 TemplateName.setIdentifier(&II, Tok.getLocation());
89 bool MemberOfUnknownSpecialization;
90 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
91 TemplateName, ObjectType, EnteringContext,
92 Template, MemberOfUnknownSpecialization))
93 return;
94
95 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
96 /*AtDigraph*/false);
97}
98
Mike Stump1eb44332009-09-09 15:08:12 +000099/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000100///
101/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump1eb44332009-09-09 15:08:12 +0000102/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000103/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000104///
105/// '::'[opt] nested-name-specifier
106/// '::'
107///
108/// nested-name-specifier:
109/// type-name '::'
110/// namespace-name '::'
111/// nested-name-specifier identifier '::'
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000112/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000113///
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000114///
Mike Stump1eb44332009-09-09 15:08:12 +0000115/// \param SS the scope specifier that will be set to the parsed
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000116/// nested-name-specifier (or empty)
117///
Mike Stump1eb44332009-09-09 15:08:12 +0000118/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000119/// the "." or "->" of a member access expression, this parameter provides the
120/// type of the object whose members are being accessed.
121///
122/// \param EnteringContext whether we will be entering into the context of
123/// the nested-name-specifier after parsing it.
124///
Douglas Gregord4dca082010-02-24 18:44:31 +0000125/// \param MayBePseudoDestructor When non-NULL, points to a flag that
126/// indicates whether this nested-name-specifier may be part of a
127/// pseudo-destructor name. In this case, the flag will be set false
128/// if we don't actually end up parsing a destructor name. Moreorover,
129/// if we do end up determining that we are parsing a destructor name,
130/// the last component of the nested-name-specifier is not parsed as
131/// part of the scope specifier.
132
Douglas Gregorb10cd042010-02-21 18:36:56 +0000133/// member access expression, e.g., the \p T:: in \p p->T::m.
134///
John McCall9ba61662010-02-26 08:45:28 +0000135/// \returns true if there was an error parsing a scope specifier
Douglas Gregor495c35d2009-08-25 22:51:20 +0000136bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +0000137 ParsedType ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000138 bool EnteringContext,
Francois Pichet4147d302011-03-27 19:41:34 +0000139 bool *MayBePseudoDestructor,
140 bool IsTypename) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000141 assert(getLangOpts().CPlusPlus &&
Chris Lattner7452c6f2009-01-05 01:24:05 +0000142 "Call sites of this function should be guarded by checking for C++");
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000144 if (Tok.is(tok::annot_cxxscope)) {
Douglas Gregorc34348a2011-02-24 17:54:50 +0000145 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
146 Tok.getAnnotationRange(),
147 SS);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000148 ConsumeToken();
John McCall9ba61662010-02-26 08:45:28 +0000149 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000150 }
Chris Lattnere607e802009-01-04 21:14:15 +0000151
Douglas Gregor39a8de12009-02-25 19:37:18 +0000152 bool HasScopeSpecifier = false;
153
Chris Lattner5b454732009-01-05 03:55:46 +0000154 if (Tok.is(tok::coloncolon)) {
155 // ::new and ::delete aren't nested-name-specifiers.
156 tok::TokenKind NextKind = NextToken().getKind();
157 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
158 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Chris Lattner55a7cef2009-01-05 00:13:00 +0000160 // '::' - Global scope qualifier.
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000161 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
162 return true;
163
Douglas Gregor39a8de12009-02-25 19:37:18 +0000164 HasScopeSpecifier = true;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000165 }
166
Douglas Gregord4dca082010-02-24 18:44:31 +0000167 bool CheckForDestructor = false;
168 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
169 CheckForDestructor = true;
170 *MayBePseudoDestructor = false;
171 }
172
David Blaikie42d6d0c2011-12-04 05:04:18 +0000173 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
174 DeclSpec DS(AttrFactory);
175 SourceLocation DeclLoc = Tok.getLocation();
176 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
177 if (Tok.isNot(tok::coloncolon)) {
178 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
179 return false;
180 }
181
182 SourceLocation CCLoc = ConsumeToken();
183 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
184 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
185
186 HasScopeSpecifier = true;
187 }
188
Douglas Gregor39a8de12009-02-25 19:37:18 +0000189 while (true) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000190 if (HasScopeSpecifier) {
191 // C++ [basic.lookup.classref]p5:
192 // If the qualified-id has the form
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000193 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000194 // ::class-name-or-namespace-name::...
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000195 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000196 // the class-name-or-namespace-name is looked up in global scope as a
197 // class-name or namespace-name.
198 //
199 // To implement this, we clear out the object type as soon as we've
200 // seen a leading '::' or part of a nested-name-specifier.
John McCallb3d87482010-08-24 05:47:05 +0000201 ObjectType = ParsedType();
Douglas Gregor81b747b2009-09-17 21:32:03 +0000202
203 if (Tok.is(tok::code_completion)) {
204 // Code completion for a nested-name-specifier, where the code
205 // code completion token follows the '::'.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000206 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidisb6b2b182011-04-23 01:04:12 +0000207 // Include code completion token into the range of the scope otherwise
208 // when we try to annotate the scope tokens the dangling code completion
209 // token will cause assertion in
210 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000211 SS.setEndLoc(Tok.getLocation());
212 cutOffParsing();
213 return true;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000214 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000215 }
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Douglas Gregor39a8de12009-02-25 19:37:18 +0000217 // nested-name-specifier:
Chris Lattner77cf72a2009-06-26 03:47:46 +0000218 // nested-name-specifier 'template'[opt] simple-template-id '::'
219
220 // Parse the optional 'template' keyword, then make sure we have
221 // 'identifier <' after it.
222 if (Tok.is(tok::kw_template)) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000223 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedmaneab975d2009-08-29 04:08:08 +0000224 // nested-name-specifier, since they aren't allowed to start with
225 // 'template'.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000226 if (!HasScopeSpecifier && !ObjectType)
Eli Friedmaneab975d2009-08-29 04:08:08 +0000227 break;
228
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000229 TentativeParsingAction TPA(*this);
Chris Lattner77cf72a2009-06-26 03:47:46 +0000230 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000231
232 UnqualifiedId TemplateName;
233 if (Tok.is(tok::identifier)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000234 // Consume the identifier.
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000235 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000236 ConsumeToken();
237 } else if (Tok.is(tok::kw_operator)) {
238 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000239 TemplateName)) {
240 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000241 break;
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000242 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000243
Sean Hunte6252d12009-11-28 08:58:14 +0000244 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
245 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000246 Diag(TemplateName.getSourceRange().getBegin(),
247 diag::err_id_after_template_in_nested_name_spec)
248 << TemplateName.getSourceRange();
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000249 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000250 break;
251 }
252 } else {
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000253 TPA.Revert();
Chris Lattner77cf72a2009-06-26 03:47:46 +0000254 break;
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000257 // If the next token is not '<', we have a qualified-id that refers
258 // to a template name, such as T::template apply, but is not a
259 // template-id.
260 if (Tok.isNot(tok::less)) {
261 TPA.Revert();
262 break;
263 }
264
265 // Commit to parsing the template-id.
266 TPA.Commit();
Douglas Gregord6ab2322010-06-16 23:00:59 +0000267 TemplateTy Template;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000268 if (TemplateNameKind TNK
269 = Actions.ActOnDependentTemplateName(getCurScope(),
270 SS, TemplateKWLoc, TemplateName,
271 ObjectType, EnteringContext,
272 Template)) {
273 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
274 TemplateName, false))
Douglas Gregord6ab2322010-06-16 23:00:59 +0000275 return true;
276 } else
John McCall9ba61662010-02-26 08:45:28 +0000277 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattner77cf72a2009-06-26 03:47:46 +0000279 continue;
280 }
Mike Stump1eb44332009-09-09 15:08:12 +0000281
Douglas Gregor39a8de12009-02-25 19:37:18 +0000282 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000283 // We have
Douglas Gregor39a8de12009-02-25 19:37:18 +0000284 //
285 // simple-template-id '::'
286 //
287 // So we need to check whether the simple-template-id is of the
Douglas Gregorc45c2322009-03-31 00:43:58 +0000288 // right kind (it should name a type or be dependent), and then
289 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000290 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregord4dca082010-02-24 18:44:31 +0000291 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
292 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000293 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000294 }
295
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000296 // Consume the template-id token.
297 ConsumeToken();
298
299 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
300 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000301
David Blaikie6796fc12011-11-07 03:30:03 +0000302 HasScopeSpecifier = true;
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000303
304 ASTTemplateArgsPtr TemplateArgsPtr(Actions,
305 TemplateId->getTemplateArgs(),
306 TemplateId->NumArgs);
307
308 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000309 SS,
310 TemplateId->TemplateKWLoc,
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000311 TemplateId->Template,
312 TemplateId->TemplateNameLoc,
313 TemplateId->LAngleLoc,
314 TemplateArgsPtr,
315 TemplateId->RAngleLoc,
316 CCLoc,
317 EnteringContext)) {
318 SourceLocation StartLoc
319 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
320 : TemplateId->TemplateNameLoc;
321 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner67b9e832009-06-26 03:45:46 +0000322 }
Argyrios Kyrtzidiseccce7e2011-05-03 18:45:38 +0000323
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000324 continue;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000325 }
326
Chris Lattner5c7f7862009-06-26 03:52:38 +0000327
328 // The rest of the nested-name-specifier possibilities start with
329 // tok::identifier.
330 if (Tok.isNot(tok::identifier))
331 break;
332
333 IdentifierInfo &II = *Tok.getIdentifierInfo();
334
335 // nested-name-specifier:
336 // type-name '::'
337 // namespace-name '::'
338 // nested-name-specifier identifier '::'
339 Token Next = NextToken();
Chris Lattner46646492009-12-07 01:36:53 +0000340
341 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
342 // and emit a fixit hint for it.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000343 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000344 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
345 Tok.getLocation(),
346 Next.getLocation(), ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000347 EnteringContext) &&
348 // If the token after the colon isn't an identifier, it's still an
349 // error, but they probably meant something else strange so don't
350 // recover like this.
351 PP.LookAhead(1).is(tok::identifier)) {
352 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregor849b2432010-03-31 17:46:05 +0000353 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregorb10cd042010-02-21 18:36:56 +0000354
355 // Recover as if the user wrote '::'.
356 Next.setKind(tok::coloncolon);
357 }
Chris Lattner46646492009-12-07 01:36:53 +0000358 }
359
Chris Lattner5c7f7862009-06-26 03:52:38 +0000360 if (Next.is(tok::coloncolon)) {
Douglas Gregor77549082010-02-24 21:29:12 +0000361 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor23c94db2010-07-02 17:43:08 +0000362 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor77549082010-02-24 21:29:12 +0000363 II, ObjectType)) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000364 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000365 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000366 }
367
Chris Lattner5c7f7862009-06-26 03:52:38 +0000368 // We have an identifier followed by a '::'. Lookup this name
369 // as the name in a nested-name-specifier.
370 SourceLocation IdLoc = ConsumeToken();
Chris Lattner46646492009-12-07 01:36:53 +0000371 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
372 "NextToken() not working properly!");
Chris Lattner5c7f7862009-06-26 03:52:38 +0000373 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000375 HasScopeSpecifier = true;
376 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
377 ObjectType, EnteringContext, SS))
378 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
379
Chris Lattner5c7f7862009-06-26 03:52:38 +0000380 continue;
381 }
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Richard Trieu950be712011-09-19 19:01:00 +0000383 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smithea698b32011-04-14 21:45:45 +0000384
Chris Lattner5c7f7862009-06-26 03:52:38 +0000385 // nested-name-specifier:
386 // type-name '<'
387 if (Next.is(tok::less)) {
388 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000389 UnqualifiedId TemplateName;
390 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000391 bool MemberOfUnknownSpecialization;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000392 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000393 /*hasTemplateKeyword=*/false,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000394 TemplateName,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000395 ObjectType,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000396 EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000397 Template,
398 MemberOfUnknownSpecialization)) {
David Blaikie6796fc12011-11-07 03:30:03 +0000399 // We have found a template name, so annotate this token
Chris Lattner5c7f7862009-06-26 03:52:38 +0000400 // with a template-id annotation. We do not permit the
401 // template-id to be translated into a type annotation,
402 // because some clients (e.g., the parsing of class template
403 // specializations) still want to see the original template-id
404 // token.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000405 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000406 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
407 TemplateName, false))
John McCall9ba61662010-02-26 08:45:28 +0000408 return true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000409 continue;
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000410 }
411
412 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4147d302011-03-27 19:41:34 +0000413 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000414 // We have something like t::getAs<T>, where getAs is a
415 // member of an unknown specialization. However, this will only
416 // parse correctly as a template, so suggest the keyword 'template'
417 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4147d302011-03-27 19:41:34 +0000418 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikie4e4d0842012-03-11 07:00:24 +0000419 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000420 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4147d302011-03-27 19:41:34 +0000421
422 Diag(Tok.getLocation(), DiagID)
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000423 << II.getName()
424 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
425
Douglas Gregord6ab2322010-06-16 23:00:59 +0000426 if (TemplateNameKind TNK
Douglas Gregor23c94db2010-07-02 17:43:08 +0000427 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000428 SS, SourceLocation(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000429 TemplateName, ObjectType,
430 EnteringContext, Template)) {
431 // Consume the identifier.
432 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000433 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
434 TemplateName, false))
435 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000436 }
437 else
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000438 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000439
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000440 continue;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000441 }
442 }
443
Douglas Gregor39a8de12009-02-25 19:37:18 +0000444 // We don't have any tokens that form the beginning of a
445 // nested-name-specifier, so we're done.
446 break;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000447 }
Mike Stump1eb44332009-09-09 15:08:12 +0000448
Douglas Gregord4dca082010-02-24 18:44:31 +0000449 // Even if we didn't see any pieces of a nested-name-specifier, we
450 // still check whether there is a tilde in this position, which
451 // indicates a potential pseudo-destructor.
452 if (CheckForDestructor && Tok.is(tok::tilde))
453 *MayBePseudoDestructor = true;
454
John McCall9ba61662010-02-26 08:45:28 +0000455 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000456}
457
458/// ParseCXXIdExpression - Handle id-expression.
459///
460/// id-expression:
461/// unqualified-id
462/// qualified-id
463///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000464/// qualified-id:
465/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
466/// '::' identifier
467/// '::' operator-function-id
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000468/// '::' template-id
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000469///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000470/// NOTE: The standard specifies that, for qualified-id, the parser does not
471/// expect:
472///
473/// '::' conversion-function-id
474/// '::' '~' class-name
475///
476/// This may cause a slight inconsistency on diagnostics:
477///
478/// class C {};
479/// namespace A {}
480/// void f() {
481/// :: A :: ~ C(); // Some Sema error about using destructor with a
482/// // namespace.
483/// :: ~ C(); // Some Parser error like 'unexpected ~'.
484/// }
485///
486/// We simplify the parser a bit and make it work like:
487///
488/// qualified-id:
489/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
490/// '::' unqualified-id
491///
492/// That way Sema can handle and report similar errors for namespaces and the
493/// global scope.
494///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000495/// The isAddressOfOperand parameter indicates that this id-expression is a
496/// direct operand of the address-of operator. This is, besides member contexts,
497/// the only place where a qualified-id naming a non-static class member may
498/// appear.
499///
John McCall60d7b3a2010-08-24 06:29:42 +0000500ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000501 // qualified-id:
502 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
503 // '::' unqualified-id
504 //
505 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +0000506 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000507
508 SourceLocation TemplateKWLoc;
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000509 UnqualifiedId Name;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000510 if (ParseUnqualifiedId(SS,
511 /*EnteringContext=*/false,
512 /*AllowDestructorName=*/false,
513 /*AllowConstructorName=*/false,
John McCallb3d87482010-08-24 05:47:05 +0000514 /*ObjectType=*/ ParsedType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000515 TemplateKWLoc,
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000516 Name))
517 return ExprError();
John McCallb681b612009-11-22 02:49:43 +0000518
519 // This is only the direct operand of an & operator if it is not
520 // followed by a postfix-expression suffix.
John McCall9c72c602010-08-27 09:08:28 +0000521 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
522 isAddressOfOperand = false;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000523
524 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
525 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000526}
527
Douglas Gregorae7902c2011-08-04 15:30:47 +0000528/// ParseLambdaExpression - Parse a C++0x lambda expression.
529///
530/// lambda-expression:
531/// lambda-introducer lambda-declarator[opt] compound-statement
532///
533/// lambda-introducer:
534/// '[' lambda-capture[opt] ']'
535///
536/// lambda-capture:
537/// capture-default
538/// capture-list
539/// capture-default ',' capture-list
540///
541/// capture-default:
542/// '&'
543/// '='
544///
545/// capture-list:
546/// capture
547/// capture-list ',' capture
548///
549/// capture:
550/// identifier
551/// '&' identifier
552/// 'this'
553///
554/// lambda-declarator:
555/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
556/// 'mutable'[opt] exception-specification[opt]
557/// trailing-return-type[opt]
558///
559ExprResult Parser::ParseLambdaExpression() {
560 // Parse lambda-introducer.
561 LambdaIntroducer Intro;
562
563 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
564 if (DiagID) {
565 Diag(Tok, DiagID.getValue());
566 SkipUntil(tok::r_square);
Eli Friedmandc3b7232012-01-04 02:40:39 +0000567 SkipUntil(tok::l_brace);
568 SkipUntil(tok::r_brace);
569 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000570 }
571
572 return ParseLambdaExpressionAfterIntroducer(Intro);
573}
574
575/// TryParseLambdaExpression - Use lookahead and potentially tentative
576/// parsing to determine if we are looking at a C++0x lambda expression, and parse
577/// it if we are.
578///
579/// If we are not looking at a lambda expression, returns ExprError().
580ExprResult Parser::TryParseLambdaExpression() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000581 assert(getLangOpts().CPlusPlus0x
Douglas Gregorae7902c2011-08-04 15:30:47 +0000582 && Tok.is(tok::l_square)
583 && "Not at the start of a possible lambda expression.");
584
585 const Token Next = NextToken(), After = GetLookAheadToken(2);
586
587 // If lookahead indicates this is a lambda...
588 if (Next.is(tok::r_square) || // []
589 Next.is(tok::equal) || // [=
590 (Next.is(tok::amp) && // [&] or [&,
591 (After.is(tok::r_square) ||
592 After.is(tok::comma))) ||
593 (Next.is(tok::identifier) && // [identifier]
594 After.is(tok::r_square))) {
595 return ParseLambdaExpression();
596 }
597
Eli Friedmandc3b7232012-01-04 02:40:39 +0000598 // If lookahead indicates an ObjC message send...
599 // [identifier identifier
Douglas Gregorae7902c2011-08-04 15:30:47 +0000600 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000601 return ExprEmpty();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000602 }
603
Eli Friedmandc3b7232012-01-04 02:40:39 +0000604 // Here, we're stuck: lambda introducers and Objective-C message sends are
605 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
606 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
607 // writing two routines to parse a lambda introducer, just try to parse
608 // a lambda introducer first, and fall back if that fails.
609 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregorae7902c2011-08-04 15:30:47 +0000610 LambdaIntroducer Intro;
611 if (TryParseLambdaIntroducer(Intro))
Eli Friedmandc3b7232012-01-04 02:40:39 +0000612 return ExprEmpty();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000613 return ParseLambdaExpressionAfterIntroducer(Intro);
614}
615
616/// ParseLambdaExpression - Parse a lambda introducer.
617///
618/// Returns a DiagnosticID if it hit something unexpected.
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000619llvm::Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro){
Douglas Gregorae7902c2011-08-04 15:30:47 +0000620 typedef llvm::Optional<unsigned> DiagResult;
621
622 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000623 BalancedDelimiterTracker T(*this, tok::l_square);
624 T.consumeOpen();
625
626 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000627
628 bool first = true;
629
630 // Parse capture-default.
631 if (Tok.is(tok::amp) &&
632 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
633 Intro.Default = LCD_ByRef;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000634 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000635 first = false;
636 } else if (Tok.is(tok::equal)) {
637 Intro.Default = LCD_ByCopy;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000638 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000639 first = false;
640 }
641
642 while (Tok.isNot(tok::r_square)) {
643 if (!first) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000644 if (Tok.isNot(tok::comma)) {
645 if (Tok.is(tok::code_completion)) {
646 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
647 /*AfterAmpersand=*/false);
648 ConsumeCodeCompletionToken();
649 break;
650 }
651
Douglas Gregorae7902c2011-08-04 15:30:47 +0000652 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000653 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000654 ConsumeToken();
655 }
656
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000657 if (Tok.is(tok::code_completion)) {
658 // If we're in Objective-C++ and we have a bare '[', then this is more
659 // likely to be a message receiver.
David Blaikie4e4d0842012-03-11 07:00:24 +0000660 if (getLangOpts().ObjC1 && first)
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000661 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
662 else
663 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
664 /*AfterAmpersand=*/false);
665 ConsumeCodeCompletionToken();
666 break;
667 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000668
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000669 first = false;
670
Douglas Gregorae7902c2011-08-04 15:30:47 +0000671 // Parse capture.
672 LambdaCaptureKind Kind = LCK_ByCopy;
673 SourceLocation Loc;
674 IdentifierInfo* Id = 0;
Douglas Gregora7365242012-02-14 19:27:52 +0000675 SourceLocation EllipsisLoc;
676
Douglas Gregorae7902c2011-08-04 15:30:47 +0000677 if (Tok.is(tok::kw_this)) {
678 Kind = LCK_This;
679 Loc = ConsumeToken();
680 } else {
681 if (Tok.is(tok::amp)) {
682 Kind = LCK_ByRef;
683 ConsumeToken();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000684
685 if (Tok.is(tok::code_completion)) {
686 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
687 /*AfterAmpersand=*/true);
688 ConsumeCodeCompletionToken();
689 break;
690 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000691 }
692
693 if (Tok.is(tok::identifier)) {
694 Id = Tok.getIdentifierInfo();
695 Loc = ConsumeToken();
Douglas Gregora7365242012-02-14 19:27:52 +0000696
697 if (Tok.is(tok::ellipsis))
698 EllipsisLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000699 } else if (Tok.is(tok::kw_this)) {
700 // FIXME: If we want to suggest a fixit here, will need to return more
701 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
702 // Clear()ed to prevent emission in case of tentative parsing?
703 return DiagResult(diag::err_this_captured_by_reference);
704 } else {
705 return DiagResult(diag::err_expected_capture);
706 }
707 }
708
Douglas Gregora7365242012-02-14 19:27:52 +0000709 Intro.addCapture(Kind, Loc, Id, EllipsisLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000710 }
711
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000712 T.consumeClose();
713 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000714
715 return DiagResult();
716}
717
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000718/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000719///
720/// Returns true if it hit something unexpected.
721bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
722 TentativeParsingAction PA(*this);
723
724 llvm::Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
725
726 if (DiagID) {
727 PA.Revert();
728 return true;
729 }
730
731 PA.Commit();
732 return false;
733}
734
735/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
736/// expression.
737ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
738 LambdaIntroducer &Intro) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000739 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
740 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
741
742 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
743 "lambda expression parsing");
744
Douglas Gregorae7902c2011-08-04 15:30:47 +0000745 // Parse lambda-declarator[opt].
746 DeclSpec DS(AttrFactory);
Eli Friedmanf88c4002012-01-04 04:41:38 +0000747 Declarator D(DS, Declarator::LambdaExprContext);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000748
749 if (Tok.is(tok::l_paren)) {
750 ParseScope PrototypeScope(this,
751 Scope::FunctionPrototypeScope |
752 Scope::DeclScope);
753
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000754 SourceLocation DeclLoc, DeclEndLoc;
755 BalancedDelimiterTracker T(*this, tok::l_paren);
756 T.consumeOpen();
757 DeclLoc = T.getOpenLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000758
759 // Parse parameter-declaration-clause.
760 ParsedAttributes Attr(AttrFactory);
761 llvm::SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
762 SourceLocation EllipsisLoc;
763
764 if (Tok.isNot(tok::r_paren))
765 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
766
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000767 T.consumeClose();
768 DeclEndLoc = T.getCloseLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000769
770 // Parse 'mutable'[opt].
771 SourceLocation MutableLoc;
772 if (Tok.is(tok::kw_mutable)) {
773 MutableLoc = ConsumeToken();
774 DeclEndLoc = MutableLoc;
775 }
776
777 // Parse exception-specification[opt].
778 ExceptionSpecificationType ESpecType = EST_None;
779 SourceRange ESpecRange;
780 llvm::SmallVector<ParsedType, 2> DynamicExceptions;
781 llvm::SmallVector<SourceRange, 2> DynamicExceptionRanges;
782 ExprResult NoexceptExpr;
Richard Smitha058fd42012-05-02 22:22:32 +0000783 ESpecType = tryParseExceptionSpecification(ESpecRange,
Douglas Gregor74e2fc32012-04-16 18:27:27 +0000784 DynamicExceptions,
785 DynamicExceptionRanges,
Richard Smitha058fd42012-05-02 22:22:32 +0000786 NoexceptExpr);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000787
788 if (ESpecType != EST_None)
789 DeclEndLoc = ESpecRange.getEnd();
790
791 // Parse attribute-specifier[opt].
792 MaybeParseCXX0XAttributes(Attr, &DeclEndLoc);
793
794 // Parse trailing-return-type[opt].
795 ParsedType TrailingReturnType;
796 if (Tok.is(tok::arrow)) {
797 SourceRange Range;
798 TrailingReturnType = ParseTrailingReturnType(Range).get();
799 if (Range.getEnd().isValid())
800 DeclEndLoc = Range.getEnd();
801 }
802
803 PrototypeScope.Exit();
804
805 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
806 /*isVariadic=*/EllipsisLoc.isValid(),
807 EllipsisLoc,
808 ParamInfo.data(), ParamInfo.size(),
809 DS.getTypeQualifiers(),
810 /*RefQualifierIsLValueRef=*/true,
811 /*RefQualifierLoc=*/SourceLocation(),
Douglas Gregor43f51032011-10-19 06:04:55 +0000812 /*ConstQualifierLoc=*/SourceLocation(),
813 /*VolatileQualifierLoc=*/SourceLocation(),
Douglas Gregorae7902c2011-08-04 15:30:47 +0000814 MutableLoc,
815 ESpecType, ESpecRange.getBegin(),
816 DynamicExceptions.data(),
817 DynamicExceptionRanges.data(),
818 DynamicExceptions.size(),
819 NoexceptExpr.isUsable() ?
820 NoexceptExpr.get() : 0,
821 DeclLoc, DeclEndLoc, D,
822 TrailingReturnType),
823 Attr, DeclEndLoc);
Douglas Gregorc9ecec42012-02-16 21:53:36 +0000824 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
825 // It's common to forget that one needs '()' before 'mutable' or the
826 // result type. Deal with this.
827 Diag(Tok, diag::err_lambda_missing_parens)
828 << Tok.is(tok::arrow)
829 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
830 SourceLocation DeclLoc = Tok.getLocation();
831 SourceLocation DeclEndLoc = DeclLoc;
832
833 // Parse 'mutable', if it's there.
834 SourceLocation MutableLoc;
835 if (Tok.is(tok::kw_mutable)) {
836 MutableLoc = ConsumeToken();
837 DeclEndLoc = MutableLoc;
838 }
839
840 // Parse the return type, if there is one.
841 ParsedType TrailingReturnType;
842 if (Tok.is(tok::arrow)) {
843 SourceRange Range;
844 TrailingReturnType = ParseTrailingReturnType(Range).get();
845 if (Range.getEnd().isValid())
846 DeclEndLoc = Range.getEnd();
847 }
848
849 ParsedAttributes Attr(AttrFactory);
850 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
851 /*isVariadic=*/false,
852 /*EllipsisLoc=*/SourceLocation(),
853 /*Params=*/0, /*NumParams=*/0,
854 /*TypeQuals=*/0,
855 /*RefQualifierIsLValueRef=*/true,
856 /*RefQualifierLoc=*/SourceLocation(),
857 /*ConstQualifierLoc=*/SourceLocation(),
858 /*VolatileQualifierLoc=*/SourceLocation(),
859 MutableLoc,
860 EST_None,
861 /*ESpecLoc=*/SourceLocation(),
862 /*Exceptions=*/0,
863 /*ExceptionRanges=*/0,
864 /*NumExceptions=*/0,
865 /*NoexceptExpr=*/0,
866 DeclLoc, DeclEndLoc, D,
867 TrailingReturnType),
868 Attr, DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000869 }
Douglas Gregorc9ecec42012-02-16 21:53:36 +0000870
Douglas Gregorae7902c2011-08-04 15:30:47 +0000871
Eli Friedman906a7e12012-01-06 03:05:34 +0000872 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
873 // it.
Douglas Gregorfccfb622012-02-21 22:51:27 +0000874 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorfccfb622012-02-21 22:51:27 +0000875 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman906a7e12012-01-06 03:05:34 +0000876
Eli Friedmanec9ea722012-01-05 03:35:19 +0000877 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
878
Douglas Gregorae7902c2011-08-04 15:30:47 +0000879 // Parse compound-statement.
Eli Friedmandc3b7232012-01-04 02:40:39 +0000880 if (!Tok.is(tok::l_brace)) {
Douglas Gregorae7902c2011-08-04 15:30:47 +0000881 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmandc3b7232012-01-04 02:40:39 +0000882 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
883 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000884 }
885
Eli Friedmandc3b7232012-01-04 02:40:39 +0000886 StmtResult Stmt(ParseCompoundStatementBody());
887 BodyScope.Exit();
888
Eli Friedmandeeab902012-01-04 02:46:53 +0000889 if (!Stmt.isInvalid())
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000890 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
Eli Friedmandc3b7232012-01-04 02:40:39 +0000891
Eli Friedmandeeab902012-01-04 02:46:53 +0000892 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
893 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000894}
895
Reid Spencer5f016e22007-07-11 17:01:13 +0000896/// ParseCXXCasts - This handles the various ways to cast expressions to another
897/// type.
898///
899/// postfix-expression: [C++ 5.2p1]
900/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
901/// 'static_cast' '<' type-name '>' '(' expression ')'
902/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
903/// 'const_cast' '<' type-name '>' '(' expression ')'
904///
John McCall60d7b3a2010-08-24 06:29:42 +0000905ExprResult Parser::ParseCXXCasts() {
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 tok::TokenKind Kind = Tok.getKind();
907 const char *CastName = 0; // For error messages
908
909 switch (Kind) {
David Blaikieeb2d1f12011-09-23 20:26:49 +0000910 default: llvm_unreachable("Unknown C++ cast!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 case tok::kw_const_cast: CastName = "const_cast"; break;
912 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
913 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
914 case tok::kw_static_cast: CastName = "static_cast"; break;
915 }
916
917 SourceLocation OpLoc = ConsumeToken();
918 SourceLocation LAngleBracketLoc = Tok.getLocation();
919
Richard Smithea698b32011-04-14 21:45:45 +0000920 // Check for "<::" which is parsed as "[:". If found, fix token stream,
921 // diagnose error, suggest fix, and recover parsing.
922 Token Next = NextToken();
923 if (Tok.is(tok::l_square) && Tok.getLength() == 2 && Next.is(tok::colon) &&
924 AreTokensAdjacent(PP, Tok, Next))
925 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
926
Reid Spencer5f016e22007-07-11 17:01:13 +0000927 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000928 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000929
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000930 // Parse the common declaration-specifiers piece.
931 DeclSpec DS(AttrFactory);
932 ParseSpecifierQualifierList(DS);
933
934 // Parse the abstract-declarator, if present.
935 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
936 ParseDeclarator(DeclaratorInfo);
937
Reid Spencer5f016e22007-07-11 17:01:13 +0000938 SourceLocation RAngleBracketLoc = Tok.getLocation();
939
Chris Lattner1ab3b962008-11-18 07:48:38 +0000940 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000941 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Reid Spencer5f016e22007-07-11 17:01:13 +0000942
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000943 SourceLocation LParenLoc, RParenLoc;
944 BalancedDelimiterTracker T(*this, tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +0000945
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000946 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +0000947 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000948
John McCall60d7b3a2010-08-24 06:29:42 +0000949 ExprResult Result = ParseExpression();
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +0000951 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000952 T.consumeClose();
Reid Spencer5f016e22007-07-11 17:01:13 +0000953
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000954 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregor49badde2008-10-27 19:41:14 +0000955 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +0000956 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor809070a2009-02-18 17:45:20 +0000957 RAngleBracketLoc,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000958 T.getOpenLocation(), Result.take(),
959 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000960
Sebastian Redl20df9b72008-12-11 22:51:44 +0000961 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +0000962}
963
Sebastian Redlc42e1182008-11-11 11:37:55 +0000964/// ParseCXXTypeid - This handles the C++ typeid expression.
965///
966/// postfix-expression: [C++ 5.2p1]
967/// 'typeid' '(' expression ')'
968/// 'typeid' '(' type-id ')'
969///
John McCall60d7b3a2010-08-24 06:29:42 +0000970ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc42e1182008-11-11 11:37:55 +0000971 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
972
973 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000974 SourceLocation LParenLoc, RParenLoc;
975 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000976
977 // typeid expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000978 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redl20df9b72008-12-11 22:51:44 +0000979 return ExprError();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000980 LParenLoc = T.getOpenLocation();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000981
John McCall60d7b3a2010-08-24 06:29:42 +0000982 ExprResult Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +0000983
984 if (isTypeIdInParens()) {
Douglas Gregor809070a2009-02-18 17:45:20 +0000985 TypeResult Ty = ParseTypeName();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000986
987 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000988 T.consumeClose();
989 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +0000990 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +0000991 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +0000992
993 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallb3d87482010-08-24 05:47:05 +0000994 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000995 } else {
Douglas Gregore0762c92009-06-19 23:52:42 +0000996 // C++0x [expr.typeid]p3:
Mike Stump1eb44332009-09-09 15:08:12 +0000997 // When typeid is applied to an expression other than an lvalue of a
998 // polymorphic class type [...] The expression is an unevaluated
Douglas Gregore0762c92009-06-19 23:52:42 +0000999 // operand (Clause 5).
1000 //
Mike Stump1eb44332009-09-09 15:08:12 +00001001 // Note that we can't tell whether the expression is an lvalue of a
Eli Friedmanef331b72012-01-20 01:26:23 +00001002 // polymorphic class type until after we've parsed the expression; we
1003 // speculatively assume the subexpression is unevaluated, and fix it up
1004 // later.
1005 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001006 Result = ParseExpression();
1007
1008 // Match the ')'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001009 if (Result.isInvalid())
Sebastian Redlc42e1182008-11-11 11:37:55 +00001010 SkipUntil(tok::r_paren);
1011 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001012 T.consumeClose();
1013 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001014 if (RParenLoc.isInvalid())
1015 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001016
Sebastian Redlc42e1182008-11-11 11:37:55 +00001017 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redleffa8d12008-12-10 00:02:53 +00001018 Result.release(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001019 }
1020 }
1021
Sebastian Redl20df9b72008-12-11 22:51:44 +00001022 return move(Result);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001023}
1024
Francois Pichet01b7c302010-09-08 12:20:18 +00001025/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1026///
1027/// '__uuidof' '(' expression ')'
1028/// '__uuidof' '(' type-id ')'
1029///
1030ExprResult Parser::ParseCXXUuidof() {
1031 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1032
1033 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001034 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet01b7c302010-09-08 12:20:18 +00001035
1036 // __uuidof expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001037 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet01b7c302010-09-08 12:20:18 +00001038 return ExprError();
1039
1040 ExprResult Result;
1041
1042 if (isTypeIdInParens()) {
1043 TypeResult Ty = ParseTypeName();
1044
1045 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001046 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001047
1048 if (Ty.isInvalid())
1049 return ExprError();
1050
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001051 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1052 Ty.get().getAsOpaquePtr(),
1053 T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001054 } else {
1055 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1056 Result = ParseExpression();
1057
1058 // Match the ')'.
1059 if (Result.isInvalid())
1060 SkipUntil(tok::r_paren);
1061 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001062 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001063
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001064 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1065 /*isType=*/false,
1066 Result.release(), T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001067 }
1068 }
1069
1070 return move(Result);
1071}
1072
Douglas Gregord4dca082010-02-24 18:44:31 +00001073/// \brief Parse a C++ pseudo-destructor expression after the base,
1074/// . or -> operator, and nested-name-specifier have already been
1075/// parsed.
1076///
1077/// postfix-expression: [C++ 5.2]
1078/// postfix-expression . pseudo-destructor-name
1079/// postfix-expression -> pseudo-destructor-name
1080///
1081/// pseudo-destructor-name:
1082/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1083/// ::[opt] nested-name-specifier template simple-template-id ::
1084/// ~type-name
1085/// ::[opt] nested-name-specifier[opt] ~type-name
1086///
John McCall60d7b3a2010-08-24 06:29:42 +00001087ExprResult
Douglas Gregord4dca082010-02-24 18:44:31 +00001088Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1089 tok::TokenKind OpKind,
1090 CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +00001091 ParsedType ObjectType) {
Douglas Gregord4dca082010-02-24 18:44:31 +00001092 // We're parsing either a pseudo-destructor-name or a dependent
1093 // member access that has the same form as a
1094 // pseudo-destructor-name. We parse both in the same way and let
1095 // the action model sort them out.
1096 //
1097 // Note that the ::[opt] nested-name-specifier[opt] has already
1098 // been parsed, and if there was a simple-template-id, it has
1099 // been coalesced into a template-id annotation token.
1100 UnqualifiedId FirstTypeName;
1101 SourceLocation CCLoc;
1102 if (Tok.is(tok::identifier)) {
1103 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1104 ConsumeToken();
1105 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1106 CCLoc = ConsumeToken();
1107 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001108 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1109 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregord4dca082010-02-24 18:44:31 +00001110 FirstTypeName.setTemplateId(
1111 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1112 ConsumeToken();
1113 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1114 CCLoc = ConsumeToken();
1115 } else {
1116 FirstTypeName.setIdentifier(0, SourceLocation());
1117 }
1118
1119 // Parse the tilde.
1120 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1121 SourceLocation TildeLoc = ConsumeToken();
David Blaikie91ec7892011-12-16 16:03:09 +00001122
1123 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1124 DeclSpec DS(AttrFactory);
Benjamin Kramer85c60db2011-12-18 12:18:02 +00001125 ParseDecltypeSpecifier(DS);
David Blaikie91ec7892011-12-16 16:03:09 +00001126 if (DS.getTypeSpecType() == TST_error)
1127 return ExprError();
1128 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1129 OpKind, TildeLoc, DS,
1130 Tok.is(tok::l_paren));
1131 }
1132
Douglas Gregord4dca082010-02-24 18:44:31 +00001133 if (!Tok.is(tok::identifier)) {
1134 Diag(Tok, diag::err_destructor_tilde_identifier);
1135 return ExprError();
1136 }
1137
1138 // Parse the second type.
1139 UnqualifiedId SecondTypeName;
1140 IdentifierInfo *Name = Tok.getIdentifierInfo();
1141 SourceLocation NameLoc = ConsumeToken();
1142 SecondTypeName.setIdentifier(Name, NameLoc);
1143
1144 // If there is a '<', the second type name is a template-id. Parse
1145 // it as such.
1146 if (Tok.is(tok::less) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001147 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1148 Name, NameLoc,
1149 false, ObjectType, SecondTypeName,
1150 /*AssumeTemplateName=*/true))
Douglas Gregord4dca082010-02-24 18:44:31 +00001151 return ExprError();
1152
John McCall9ae2f072010-08-23 23:25:46 +00001153 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1154 OpLoc, OpKind,
Douglas Gregord4dca082010-02-24 18:44:31 +00001155 SS, FirstTypeName, CCLoc,
1156 TildeLoc, SecondTypeName,
1157 Tok.is(tok::l_paren));
1158}
1159
Reid Spencer5f016e22007-07-11 17:01:13 +00001160/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1161///
1162/// boolean-literal: [C++ 2.13.5]
1163/// 'true'
1164/// 'false'
John McCall60d7b3a2010-08-24 06:29:42 +00001165ExprResult Parser::ParseCXXBoolLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001166 tok::TokenKind Kind = Tok.getKind();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001167 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001168}
Chris Lattner50dd2892008-02-26 00:51:44 +00001169
1170/// ParseThrowExpression - This handles the C++ throw expression.
1171///
1172/// throw-expression: [C++ 15]
1173/// 'throw' assignment-expression[opt]
John McCall60d7b3a2010-08-24 06:29:42 +00001174ExprResult Parser::ParseThrowExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +00001175 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattner50dd2892008-02-26 00:51:44 +00001176 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl20df9b72008-12-11 22:51:44 +00001177
Chris Lattner2a2819a2008-04-06 06:02:23 +00001178 // If the current token isn't the start of an assignment-expression,
1179 // then the expression is not present. This handles things like:
1180 // "C ? throw : (void)42", which is crazy but legal.
1181 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1182 case tok::semi:
1183 case tok::r_paren:
1184 case tok::r_square:
1185 case tok::r_brace:
1186 case tok::colon:
1187 case tok::comma:
Douglas Gregorbca01b42011-07-06 22:04:06 +00001188 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattner50dd2892008-02-26 00:51:44 +00001189
Chris Lattner2a2819a2008-04-06 06:02:23 +00001190 default:
John McCall60d7b3a2010-08-24 06:29:42 +00001191 ExprResult Expr(ParseAssignmentExpression());
Sebastian Redl20df9b72008-12-11 22:51:44 +00001192 if (Expr.isInvalid()) return move(Expr);
Douglas Gregorbca01b42011-07-06 22:04:06 +00001193 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner2a2819a2008-04-06 06:02:23 +00001194 }
Chris Lattner50dd2892008-02-26 00:51:44 +00001195}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001196
1197/// ParseCXXThis - This handles the C++ 'this' pointer.
1198///
1199/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1200/// a non-lvalue expression whose value is the address of the object for which
1201/// the function is called.
John McCall60d7b3a2010-08-24 06:29:42 +00001202ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001203 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1204 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001205 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001206}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001207
1208/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1209/// Can be interpreted either as function-style casting ("int(x)")
1210/// or class type construction ("ClassType(x,y,z)")
1211/// or creation of a value-initialized type ("int()").
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001212/// See [C++ 5.2.3].
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001213///
1214/// postfix-expression: [C++ 5.2p1]
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001215/// simple-type-specifier '(' expression-list[opt] ')'
1216/// [C++0x] simple-type-specifier braced-init-list
1217/// typename-specifier '(' expression-list[opt] ')'
1218/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001219///
John McCall60d7b3a2010-08-24 06:29:42 +00001220ExprResult
Sebastian Redl20df9b72008-12-11 22:51:44 +00001221Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001222 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallb3d87482010-08-24 05:47:05 +00001223 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001224
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001225 assert((Tok.is(tok::l_paren) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001226 (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)))
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001227 && "Expected '(' or '{'!");
Douglas Gregorbc61bd82011-01-11 00:33:19 +00001228
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001229 if (Tok.is(tok::l_brace)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001230 ExprResult Init = ParseBraceInitializer();
1231 if (Init.isInvalid())
1232 return Init;
1233 Expr *InitList = Init.take();
1234 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1235 MultiExprArg(&InitList, 1),
1236 SourceLocation());
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001237 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001238 BalancedDelimiterTracker T(*this, tok::l_paren);
1239 T.consumeOpen();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001240
1241 ExprVector Exprs(Actions);
1242 CommaLocsTy CommaLocs;
1243
1244 if (Tok.isNot(tok::r_paren)) {
1245 if (ParseExpressionList(Exprs, CommaLocs)) {
1246 SkipUntil(tok::r_paren);
1247 return ExprError();
1248 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001249 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001250
1251 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001252 T.consumeClose();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001253
1254 // TypeRep could be null, if it references an invalid typedef.
1255 if (!TypeRep)
1256 return ExprError();
1257
1258 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1259 "Unexpected number of commas!");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001260 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
1261 move_arg(Exprs),
1262 T.getCloseLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001263 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001264}
1265
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001266/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001267///
1268/// condition:
1269/// expression
1270/// type-specifier-seq declarator '=' assignment-expression
Richard Smith0635aa72012-02-22 06:49:09 +00001271/// [C++11] type-specifier-seq declarator '=' initializer-clause
1272/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001273/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1274/// '=' assignment-expression
1275///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001276/// \param ExprResult if the condition was parsed as an expression, the
1277/// parsed expression.
1278///
1279/// \param DeclResult if the condition was parsed as a declaration, the
1280/// parsed declaration.
1281///
Douglas Gregor586596f2010-05-06 17:25:47 +00001282/// \param Loc The location of the start of the statement that requires this
1283/// condition, e.g., the "for" in a for loop.
1284///
1285/// \param ConvertToBoolean Whether the condition expression should be
1286/// converted to a boolean value.
1287///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001288/// \returns true if there was a parsing, false otherwise.
John McCall60d7b3a2010-08-24 06:29:42 +00001289bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1290 Decl *&DeclOut,
Douglas Gregor586596f2010-05-06 17:25:47 +00001291 SourceLocation Loc,
1292 bool ConvertToBoolean) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001293 if (Tok.is(tok::code_completion)) {
John McCallf312b1e2010-08-26 23:41:50 +00001294 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001295 cutOffParsing();
1296 return true;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001297 }
1298
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001299 if (!isCXXConditionDeclaration()) {
Douglas Gregor586596f2010-05-06 17:25:47 +00001300 // Parse the expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001301 ExprOut = ParseExpression(); // expression
1302 DeclOut = 0;
1303 if (ExprOut.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001304 return true;
1305
1306 // If required, convert to a boolean value.
1307 if (ConvertToBoolean)
John McCall60d7b3a2010-08-24 06:29:42 +00001308 ExprOut
1309 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1310 return ExprOut.isInvalid();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001311 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001312
1313 // type-specifier-seq
John McCall0b7e6782011-03-24 11:26:52 +00001314 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001315 ParseSpecifierQualifierList(DS);
1316
1317 // declarator
1318 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1319 ParseDeclarator(DeclaratorInfo);
1320
1321 // simple-asm-expr[opt]
1322 if (Tok.is(tok::kw_asm)) {
Sebastian Redlab197ba2009-02-09 18:23:29 +00001323 SourceLocation Loc;
John McCall60d7b3a2010-08-24 06:29:42 +00001324 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001325 if (AsmLabel.isInvalid()) {
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001326 SkipUntil(tok::semi);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001327 return true;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001328 }
Sebastian Redleffa8d12008-12-10 00:02:53 +00001329 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlab197ba2009-02-09 18:23:29 +00001330 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001331 }
1332
1333 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001334 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001335
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001336 // Type-check the declaration itself.
John McCall60d7b3a2010-08-24 06:29:42 +00001337 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall7f040a92010-12-24 02:08:15 +00001338 DeclaratorInfo);
John McCall60d7b3a2010-08-24 06:29:42 +00001339 DeclOut = Dcl.get();
1340 ExprOut = ExprError();
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001341
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001342 // '=' assignment-expression
Richard Trieud6c7c672012-01-18 22:54:52 +00001343 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith0635aa72012-02-22 06:49:09 +00001344 bool CopyInitialization = isTokenEqualOrEqualTypo();
1345 if (CopyInitialization)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001346 ConsumeToken();
Richard Smith0635aa72012-02-22 06:49:09 +00001347
1348 ExprResult InitExpr = ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00001349 if (getLangOpts().CPlusPlus0x && Tok.is(tok::l_brace)) {
Richard Smith0635aa72012-02-22 06:49:09 +00001350 Diag(Tok.getLocation(),
1351 diag::warn_cxx98_compat_generalized_initializer_lists);
1352 InitExpr = ParseBraceInitializer();
1353 } else if (CopyInitialization) {
1354 InitExpr = ParseAssignmentExpression();
1355 } else if (Tok.is(tok::l_paren)) {
1356 // This was probably an attempt to initialize the variable.
1357 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1358 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1359 RParen = ConsumeParen();
1360 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1361 diag::err_expected_init_in_condition_lparen)
1362 << SourceRange(LParen, RParen);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001363 } else {
Richard Smith0635aa72012-02-22 06:49:09 +00001364 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1365 diag::err_expected_init_in_condition);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001366 }
Richard Smith0635aa72012-02-22 06:49:09 +00001367
1368 if (!InitExpr.isInvalid())
1369 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
1370 DS.getTypeSpecType() == DeclSpec::TST_auto);
1371
Douglas Gregor586596f2010-05-06 17:25:47 +00001372 // FIXME: Build a reference to this declaration? Convert it to bool?
1373 // (This is currently handled by Sema).
Richard Smith483b9f32011-02-21 20:05:19 +00001374
1375 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregor586596f2010-05-06 17:25:47 +00001376
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001377 return false;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001378}
1379
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001380/// \brief Determine whether the current token starts a C++
1381/// simple-type-specifier.
1382bool Parser::isCXXSimpleTypeSpecifier() const {
1383 switch (Tok.getKind()) {
1384 case tok::annot_typename:
1385 case tok::kw_short:
1386 case tok::kw_long:
Francois Pichet338d7f72011-04-28 01:59:37 +00001387 case tok::kw___int64:
Richard Smith5a5a9712012-04-04 06:24:32 +00001388 case tok::kw___int128:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001389 case tok::kw_signed:
1390 case tok::kw_unsigned:
1391 case tok::kw_void:
1392 case tok::kw_char:
1393 case tok::kw_int:
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001394 case tok::kw_half:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001395 case tok::kw_float:
1396 case tok::kw_double:
1397 case tok::kw_wchar_t:
1398 case tok::kw_char16_t:
1399 case tok::kw_char32_t:
1400 case tok::kw_bool:
Douglas Gregord9d75e52011-04-27 05:41:15 +00001401 case tok::kw_decltype:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001402 case tok::kw_typeof:
Sean Huntdb5d44b2011-05-19 05:37:45 +00001403 case tok::kw___underlying_type:
Douglas Gregor6aa14d82010-04-21 22:36:40 +00001404 return true;
1405
1406 default:
1407 break;
1408 }
1409
1410 return false;
1411}
1412
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001413/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1414/// This should only be called when the current token is known to be part of
1415/// simple-type-specifier.
1416///
1417/// simple-type-specifier:
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001418/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001419/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1420/// char
1421/// wchar_t
1422/// bool
1423/// short
1424/// int
1425/// long
1426/// signed
1427/// unsigned
1428/// float
1429/// double
1430/// void
1431/// [GNU] typeof-specifier
1432/// [C++0x] auto [TODO]
1433///
1434/// type-name:
1435/// class-name
1436/// enum-name
1437/// typedef-name
1438///
1439void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1440 DS.SetRangeStart(Tok.getLocation());
1441 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +00001442 unsigned DiagID;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001443 SourceLocation Loc = Tok.getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001445 switch (Tok.getKind()) {
Chris Lattner55a7cef2009-01-05 00:13:00 +00001446 case tok::identifier: // foo::bar
1447 case tok::coloncolon: // ::foo::bar
David Blaikieb219cfc2011-09-23 05:06:16 +00001448 llvm_unreachable("Annotation token should already be formed!");
Mike Stump1eb44332009-09-09 15:08:12 +00001449 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001450 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner55a7cef2009-01-05 00:13:00 +00001451
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001452 // type-name
Chris Lattnerb31757b2009-01-06 05:06:21 +00001453 case tok::annot_typename: {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001454 if (getTypeAnnotation(Tok))
1455 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1456 getTypeAnnotation(Tok));
1457 else
1458 DS.SetTypeSpecError();
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001459
1460 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1461 ConsumeToken();
1462
1463 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1464 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1465 // Objective-C interface. If we don't have Objective-C or a '<', this is
1466 // just a normal reference to a typedef name.
David Blaikie4e4d0842012-03-11 07:00:24 +00001467 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001468 ParseObjCProtocolQualifiers(DS);
1469
1470 DS.Finish(Diags, PP);
1471 return;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001472 }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001474 // builtin types
1475 case tok::kw_short:
John McCallfec54012009-08-03 20:12:06 +00001476 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001477 break;
1478 case tok::kw_long:
John McCallfec54012009-08-03 20:12:06 +00001479 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001480 break;
Francois Pichet338d7f72011-04-28 01:59:37 +00001481 case tok::kw___int64:
1482 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1483 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001484 case tok::kw_signed:
John McCallfec54012009-08-03 20:12:06 +00001485 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001486 break;
1487 case tok::kw_unsigned:
John McCallfec54012009-08-03 20:12:06 +00001488 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001489 break;
1490 case tok::kw_void:
John McCallfec54012009-08-03 20:12:06 +00001491 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001492 break;
1493 case tok::kw_char:
John McCallfec54012009-08-03 20:12:06 +00001494 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001495 break;
1496 case tok::kw_int:
John McCallfec54012009-08-03 20:12:06 +00001497 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001498 break;
Richard Smith5a5a9712012-04-04 06:24:32 +00001499 case tok::kw___int128:
1500 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1501 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001502 case tok::kw_half:
1503 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1504 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001505 case tok::kw_float:
John McCallfec54012009-08-03 20:12:06 +00001506 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001507 break;
1508 case tok::kw_double:
John McCallfec54012009-08-03 20:12:06 +00001509 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001510 break;
1511 case tok::kw_wchar_t:
John McCallfec54012009-08-03 20:12:06 +00001512 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001513 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001514 case tok::kw_char16_t:
John McCallfec54012009-08-03 20:12:06 +00001515 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001516 break;
1517 case tok::kw_char32_t:
John McCallfec54012009-08-03 20:12:06 +00001518 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001519 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001520 case tok::kw_bool:
John McCallfec54012009-08-03 20:12:06 +00001521 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001522 break;
David Blaikie5e089fe2012-01-24 05:47:35 +00001523 case tok::annot_decltype:
1524 case tok::kw_decltype:
1525 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1526 return DS.Finish(Diags, PP);
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001528 // GNU typeof support.
1529 case tok::kw_typeof:
1530 ParseTypeofSpecifier(DS);
Douglas Gregor9b3064b2009-04-01 22:41:11 +00001531 DS.Finish(Diags, PP);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001532 return;
1533 }
Chris Lattnerb31757b2009-01-06 05:06:21 +00001534 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001535 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1536 else
1537 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001538 ConsumeToken();
Douglas Gregor9b3064b2009-04-01 22:41:11 +00001539 DS.Finish(Diags, PP);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001540}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001541
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001542/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1543/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1544/// e.g., "const short int". Note that the DeclSpec is *not* finished
1545/// by parsing the type-specifier-seq, because these sequences are
1546/// typically followed by some form of declarator. Returns true and
1547/// emits diagnostics if this is not a type-specifier-seq, false
1548/// otherwise.
1549///
1550/// type-specifier-seq: [C++ 8.1]
1551/// type-specifier type-specifier-seq[opt]
1552///
1553bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smith69730c12012-03-12 07:56:15 +00001554 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Douglas Gregor396a9f22010-02-24 23:13:13 +00001555 DS.Finish(Diags, PP);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001556 return false;
1557}
1558
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001559/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1560/// some form.
1561///
1562/// This routine is invoked when a '<' is encountered after an identifier or
1563/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1564/// whether the unqualified-id is actually a template-id. This routine will
1565/// then parse the template arguments and form the appropriate template-id to
1566/// return to the caller.
1567///
1568/// \param SS the nested-name-specifier that precedes this template-id, if
1569/// we're actually parsing a qualified-id.
1570///
1571/// \param Name for constructor and destructor names, this is the actual
1572/// identifier that may be a template-name.
1573///
1574/// \param NameLoc the location of the class-name in a constructor or
1575/// destructor.
1576///
1577/// \param EnteringContext whether we're entering the scope of the
1578/// nested-name-specifier.
1579///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001580/// \param ObjectType if this unqualified-id occurs within a member access
1581/// expression, the type of the base object whose member is being accessed.
1582///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001583/// \param Id as input, describes the template-name or operator-function-id
1584/// that precedes the '<'. If template arguments were parsed successfully,
1585/// will be updated with the template-id.
1586///
Douglas Gregord4dca082010-02-24 18:44:31 +00001587/// \param AssumeTemplateId When true, this routine will assume that the name
1588/// refers to a template without performing name lookup to verify.
1589///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001590/// \returns true if a parse error occurred, false otherwise.
1591bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001592 SourceLocation TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001593 IdentifierInfo *Name,
1594 SourceLocation NameLoc,
1595 bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001596 ParsedType ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00001597 UnqualifiedId &Id,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001598 bool AssumeTemplateId) {
Douglas Gregor0278e122010-05-05 05:58:24 +00001599 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1600 "Expected '<' to finish parsing a template-id");
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001601
1602 TemplateTy Template;
1603 TemplateNameKind TNK = TNK_Non_template;
1604 switch (Id.getKind()) {
1605 case UnqualifiedId::IK_Identifier:
Douglas Gregor014e88d2009-11-03 23:16:33 +00001606 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunte6252d12009-11-28 08:58:14 +00001607 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregord4dca082010-02-24 18:44:31 +00001608 if (AssumeTemplateId) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001609 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001610 Id, ObjectType, EnteringContext,
1611 Template);
1612 if (TNK == TNK_Non_template)
1613 return true;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001614 } else {
1615 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001616 TNK = Actions.isTemplateName(getCurScope(), SS,
1617 TemplateKWLoc.isValid(), Id,
1618 ObjectType, EnteringContext, Template,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001619 MemberOfUnknownSpecialization);
1620
1621 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1622 ObjectType && IsTemplateArgumentList()) {
1623 // We have something like t->getAs<T>(), where getAs is a
1624 // member of an unknown specialization. However, this will only
1625 // parse correctly as a template, so suggest the keyword 'template'
1626 // before 'getAs' and treat this as a dependent template name.
1627 std::string Name;
1628 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1629 Name = Id.Identifier->getName();
1630 else {
1631 Name = "operator ";
1632 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1633 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1634 else
1635 Name += Id.Identifier->getName();
1636 }
1637 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1638 << Name
1639 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001640 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1641 SS, TemplateKWLoc, Id,
1642 ObjectType, EnteringContext,
1643 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001644 if (TNK == TNK_Non_template)
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001645 return true;
1646 }
1647 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001648 break;
1649
Douglas Gregor014e88d2009-11-03 23:16:33 +00001650 case UnqualifiedId::IK_ConstructorName: {
1651 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001652 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001653 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c153532010-08-06 12:11:11 +00001654 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1655 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001656 EnteringContext, Template,
1657 MemberOfUnknownSpecialization);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001658 break;
1659 }
1660
Douglas Gregor014e88d2009-11-03 23:16:33 +00001661 case UnqualifiedId::IK_DestructorName: {
1662 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001663 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001664 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001665 if (ObjectType) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001666 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1667 SS, TemplateKWLoc, TemplateName,
1668 ObjectType, EnteringContext,
1669 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001670 if (TNK == TNK_Non_template)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001671 return true;
1672 } else {
Abramo Bagnara7c153532010-08-06 12:11:11 +00001673 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1674 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001675 EnteringContext, Template,
1676 MemberOfUnknownSpecialization);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001677
John McCallb3d87482010-08-24 05:47:05 +00001678 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregor124b8782010-02-16 19:09:40 +00001679 Diag(NameLoc, diag::err_destructor_template_id)
1680 << Name << SS.getRange();
Douglas Gregor2d1c2142009-11-03 19:44:04 +00001681 return true;
1682 }
1683 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001684 break;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001685 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001686
1687 default:
1688 return false;
1689 }
1690
1691 if (TNK == TNK_Non_template)
1692 return false;
1693
1694 // Parse the enclosed template argument list.
1695 SourceLocation LAngleLoc, RAngleLoc;
1696 TemplateArgList TemplateArgs;
Douglas Gregor0278e122010-05-05 05:58:24 +00001697 if (Tok.is(tok::less) &&
1698 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregor059101f2011-03-02 00:47:37 +00001699 SS, true, LAngleLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001700 TemplateArgs,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001701 RAngleLoc))
1702 return true;
1703
1704 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Sean Hunte6252d12009-11-28 08:58:14 +00001705 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1706 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001707 // Form a parsed representation of the template-id to be stored in the
1708 // UnqualifiedId.
1709 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +00001710 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001711
1712 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1713 TemplateId->Name = Id.Identifier;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001714 TemplateId->Operator = OO_None;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001715 TemplateId->TemplateNameLoc = Id.StartLocation;
1716 } else {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001717 TemplateId->Name = 0;
1718 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1719 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001720 }
1721
Douglas Gregor059101f2011-03-02 00:47:37 +00001722 TemplateId->SS = SS;
Benjamin Kramer2b28bf12012-02-19 23:37:39 +00001723 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +00001724 TemplateId->Template = Template;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001725 TemplateId->Kind = TNK;
1726 TemplateId->LAngleLoc = LAngleLoc;
1727 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +00001728 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001729 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregor314b97f2009-11-10 19:49:08 +00001730 Arg != ArgEnd; ++Arg)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001731 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001732
1733 Id.setTemplateId(TemplateId);
1734 return false;
1735 }
1736
1737 // Bundle the template arguments together.
1738 ASTTemplateArgsPtr TemplateArgsPtr(Actions, TemplateArgs.data(),
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001739 TemplateArgs.size());
Abramo Bagnarafad03b72012-01-27 08:46:19 +00001740
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001741 // Constructor and destructor names.
John McCallf312b1e2010-08-26 23:41:50 +00001742 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +00001743 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1744 Template, NameLoc,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00001745 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1746 /*IsCtorOrDtorName=*/true);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001747 if (Type.isInvalid())
1748 return true;
1749
1750 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1751 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1752 else
1753 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1754
1755 return false;
1756}
1757
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001758/// \brief Parse an operator-function-id or conversion-function-id as part
1759/// of a C++ unqualified-id.
1760///
1761/// This routine is responsible only for parsing the operator-function-id or
1762/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001763///
1764/// \code
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001765/// operator-function-id: [C++ 13.5]
1766/// 'operator' operator
1767///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001768/// operator: one of
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001769/// new delete new[] delete[]
1770/// + - * / % ^ & | ~
1771/// ! = < > += -= *= /= %=
1772/// ^= &= |= << >> >>= <<= == !=
1773/// <= >= && || ++ -- , ->* ->
1774/// () []
1775///
1776/// conversion-function-id: [C++ 12.3.2]
1777/// operator conversion-type-id
1778///
1779/// conversion-type-id:
1780/// type-specifier-seq conversion-declarator[opt]
1781///
1782/// conversion-declarator:
1783/// ptr-operator conversion-declarator[opt]
1784/// \endcode
1785///
1786/// \param The nested-name-specifier that preceded this unqualified-id. If
1787/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1788///
1789/// \param EnteringContext whether we are entering the scope of the
1790/// nested-name-specifier.
1791///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001792/// \param ObjectType if this unqualified-id occurs within a member access
1793/// expression, the type of the base object whose member is being accessed.
1794///
1795/// \param Result on a successful parse, contains the parsed unqualified-id.
1796///
1797/// \returns true if parsing fails, false otherwise.
1798bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001799 ParsedType ObjectType,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001800 UnqualifiedId &Result) {
1801 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1802
1803 // Consume the 'operator' keyword.
1804 SourceLocation KeywordLoc = ConsumeToken();
1805
1806 // Determine what kind of operator name we have.
1807 unsigned SymbolIdx = 0;
1808 SourceLocation SymbolLocations[3];
1809 OverloadedOperatorKind Op = OO_None;
1810 switch (Tok.getKind()) {
1811 case tok::kw_new:
1812 case tok::kw_delete: {
1813 bool isNew = Tok.getKind() == tok::kw_new;
1814 // Consume the 'new' or 'delete'.
1815 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith6ee326a2012-04-10 01:32:12 +00001816 // Check for array new/delete.
1817 if (Tok.is(tok::l_square) &&
1818 (!getLangOpts().CPlusPlus0x || NextToken().isNot(tok::l_square))) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001819 // Consume the '[' and ']'.
1820 BalancedDelimiterTracker T(*this, tok::l_square);
1821 T.consumeOpen();
1822 T.consumeClose();
1823 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001824 return true;
1825
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001826 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1827 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001828 Op = isNew? OO_Array_New : OO_Array_Delete;
1829 } else {
1830 Op = isNew? OO_New : OO_Delete;
1831 }
1832 break;
1833 }
1834
1835#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1836 case tok::Token: \
1837 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1838 Op = OO_##Name; \
1839 break;
1840#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
1841#include "clang/Basic/OperatorKinds.def"
1842
1843 case tok::l_paren: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001844 // Consume the '(' and ')'.
1845 BalancedDelimiterTracker T(*this, tok::l_paren);
1846 T.consumeOpen();
1847 T.consumeClose();
1848 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001849 return true;
1850
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001851 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1852 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001853 Op = OO_Call;
1854 break;
1855 }
1856
1857 case tok::l_square: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001858 // Consume the '[' and ']'.
1859 BalancedDelimiterTracker T(*this, tok::l_square);
1860 T.consumeOpen();
1861 T.consumeClose();
1862 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001863 return true;
1864
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001865 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1866 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001867 Op = OO_Subscript;
1868 break;
1869 }
1870
1871 case tok::code_completion: {
1872 // Code completion for the operator name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00001873 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001874 cutOffParsing();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001875 // Don't try to parse any further.
1876 return true;
1877 }
1878
1879 default:
1880 break;
1881 }
1882
1883 if (Op != OO_None) {
1884 // We have parsed an operator-function-id.
1885 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
1886 return false;
1887 }
Sean Hunt0486d742009-11-28 04:44:28 +00001888
1889 // Parse a literal-operator-id.
1890 //
1891 // literal-operator-id: [C++0x 13.5.8]
1892 // operator "" identifier
1893
David Blaikie4e4d0842012-03-11 07:00:24 +00001894 if (getLangOpts().CPlusPlus0x && isTokenStringLiteral()) {
Richard Smith7fe62082011-10-15 05:09:34 +00001895 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Sean Hunt0486d742009-11-28 04:44:28 +00001896
Richard Smith33762772012-03-08 23:06:02 +00001897 SourceLocation DiagLoc;
1898 unsigned DiagId = 0;
1899
1900 // We're past translation phase 6, so perform string literal concatenation
1901 // before checking for "".
1902 llvm::SmallVector<Token, 4> Toks;
1903 llvm::SmallVector<SourceLocation, 4> TokLocs;
1904 while (isTokenStringLiteral()) {
1905 if (!Tok.is(tok::string_literal) && !DiagId) {
1906 DiagLoc = Tok.getLocation();
1907 DiagId = diag::err_literal_operator_string_prefix;
1908 }
1909 Toks.push_back(Tok);
1910 TokLocs.push_back(ConsumeStringToken());
1911 }
1912
1913 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
1914 if (Literal.hadError)
1915 return true;
1916
1917 // Grab the literal operator's suffix, which will be either the next token
1918 // or a ud-suffix from the string literal.
1919 IdentifierInfo *II = 0;
1920 SourceLocation SuffixLoc;
1921 if (!Literal.getUDSuffix().empty()) {
1922 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
1923 SuffixLoc =
1924 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
1925 Literal.getUDSuffixOffset(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001926 PP.getSourceManager(), getLangOpts());
Richard Smith33762772012-03-08 23:06:02 +00001927 // This form is not permitted by the standard (yet).
1928 DiagLoc = SuffixLoc;
1929 DiagId = diag::err_literal_operator_missing_space;
1930 } else if (Tok.is(tok::identifier)) {
1931 II = Tok.getIdentifierInfo();
1932 SuffixLoc = ConsumeToken();
1933 TokLocs.push_back(SuffixLoc);
1934 } else {
Sean Hunt0486d742009-11-28 04:44:28 +00001935 Diag(Tok.getLocation(), diag::err_expected_ident);
1936 return true;
1937 }
1938
Richard Smith33762772012-03-08 23:06:02 +00001939 // The string literal must be empty.
1940 if (!Literal.GetString().empty() || Literal.Pascal) {
1941 DiagLoc = TokLocs.front();
1942 DiagId = diag::err_literal_operator_string_not_empty;
1943 }
1944
1945 if (DiagId) {
1946 // This isn't a valid literal-operator-id, but we think we know
1947 // what the user meant. Tell them what they should have written.
1948 llvm::SmallString<32> Str;
1949 Str += "\"\" ";
1950 Str += II->getName();
1951 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
1952 SourceRange(TokLocs.front(), TokLocs.back()), Str);
1953 }
1954
1955 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Sean Hunt3e518bd2009-11-29 07:34:05 +00001956 return false;
Sean Hunt0486d742009-11-28 04:44:28 +00001957 }
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001958
1959 // Parse a conversion-function-id.
1960 //
1961 // conversion-function-id: [C++ 12.3.2]
1962 // operator conversion-type-id
1963 //
1964 // conversion-type-id:
1965 // type-specifier-seq conversion-declarator[opt]
1966 //
1967 // conversion-declarator:
1968 // ptr-operator conversion-declarator[opt]
1969
1970 // Parse the type-specifier-seq.
John McCall0b7e6782011-03-24 11:26:52 +00001971 DeclSpec DS(AttrFactory);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +00001972 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001973 return true;
1974
1975 // Parse the conversion-declarator, which is merely a sequence of
1976 // ptr-operators.
1977 Declarator D(DS, Declarator::TypeNameContext);
1978 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
1979
1980 // Finish up the type.
John McCallf312b1e2010-08-26 23:41:50 +00001981 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001982 if (Ty.isInvalid())
1983 return true;
1984
1985 // Note that this is a conversion-function-id.
1986 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
1987 D.getSourceRange().getEnd());
1988 return false;
1989}
1990
1991/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
1992/// name of an entity.
1993///
1994/// \code
1995/// unqualified-id: [C++ expr.prim.general]
1996/// identifier
1997/// operator-function-id
1998/// conversion-function-id
1999/// [C++0x] literal-operator-id [TODO]
2000/// ~ class-name
2001/// template-id
2002///
2003/// \endcode
2004///
2005/// \param The nested-name-specifier that preceded this unqualified-id. If
2006/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2007///
2008/// \param EnteringContext whether we are entering the scope of the
2009/// nested-name-specifier.
2010///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002011/// \param AllowDestructorName whether we allow parsing of a destructor name.
2012///
2013/// \param AllowConstructorName whether we allow parsing a constructor name.
2014///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00002015/// \param ObjectType if this unqualified-id occurs within a member access
2016/// expression, the type of the base object whose member is being accessed.
2017///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002018/// \param Result on a successful parse, contains the parsed unqualified-id.
2019///
2020/// \returns true if parsing fails, false otherwise.
2021bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2022 bool AllowDestructorName,
2023 bool AllowConstructorName,
John McCallb3d87482010-08-24 05:47:05 +00002024 ParsedType ObjectType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002025 SourceLocation& TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002026 UnqualifiedId &Result) {
Douglas Gregor0278e122010-05-05 05:58:24 +00002027
2028 // Handle 'A::template B'. This is for template-ids which have not
2029 // already been annotated by ParseOptionalCXXScopeSpecifier().
2030 bool TemplateSpecified = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00002031 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002032 (ObjectType || SS.isSet())) {
2033 TemplateSpecified = true;
2034 TemplateKWLoc = ConsumeToken();
2035 }
2036
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002037 // unqualified-id:
2038 // identifier
2039 // template-id (when it hasn't already been annotated)
2040 if (Tok.is(tok::identifier)) {
2041 // Consume the identifier.
2042 IdentifierInfo *Id = Tok.getIdentifierInfo();
2043 SourceLocation IdLoc = ConsumeToken();
2044
David Blaikie4e4d0842012-03-11 07:00:24 +00002045 if (!getLangOpts().CPlusPlus) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002046 // If we're not in C++, only identifiers matter. Record the
2047 // identifier and return.
2048 Result.setIdentifier(Id, IdLoc);
2049 return false;
2050 }
2051
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002052 if (AllowConstructorName &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002053 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002054 // We have parsed a constructor name.
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002055 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2056 &SS, false, false,
2057 ParsedType(),
2058 /*IsCtorOrDtorName=*/true,
2059 /*NonTrivialTypeSourceInfo=*/true);
2060 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002061 } else {
2062 // We have parsed an identifier.
2063 Result.setIdentifier(Id, IdLoc);
2064 }
2065
2066 // If the next token is a '<', we may have a template.
Douglas Gregor0278e122010-05-05 05:58:24 +00002067 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002068 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2069 EnteringContext, ObjectType,
2070 Result, TemplateSpecified);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002071
2072 return false;
2073 }
2074
2075 // unqualified-id:
2076 // template-id (already parsed and annotated)
2077 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00002078 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002079
2080 // If the template-name names the current class, then this is a constructor
2081 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002082 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002083 if (SS.isSet()) {
2084 // C++ [class.qual]p2 specifies that a qualified template-name
2085 // is taken as the constructor name where a constructor can be
2086 // declared. Thus, the template arguments are extraneous, so
2087 // complain about them and remove them entirely.
2088 Diag(TemplateId->TemplateNameLoc,
2089 diag::err_out_of_line_constructor_template_id)
2090 << TemplateId->Name
Douglas Gregor849b2432010-03-31 17:46:05 +00002091 << FixItHint::CreateRemoval(
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002092 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002093 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2094 TemplateId->TemplateNameLoc,
2095 getCurScope(),
2096 &SS, false, false,
2097 ParsedType(),
2098 /*IsCtorOrDtorName=*/true,
2099 /*NontrivialTypeSourceInfo=*/true);
2100 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002101 TemplateId->RAngleLoc);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002102 ConsumeToken();
2103 return false;
2104 }
2105
2106 Result.setConstructorTemplateId(TemplateId);
2107 ConsumeToken();
2108 return false;
2109 }
2110
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002111 // We have already parsed a template-id; consume the annotation token as
2112 // our unqualified-id.
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002113 Result.setTemplateId(TemplateId);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002114 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002115 ConsumeToken();
2116 return false;
2117 }
2118
2119 // unqualified-id:
2120 // operator-function-id
2121 // conversion-function-id
2122 if (Tok.is(tok::kw_operator)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002123 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002124 return true;
2125
Sean Hunte6252d12009-11-28 08:58:14 +00002126 // If we have an operator-function-id or a literal-operator-id and the next
2127 // token is a '<', we may have a
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002128 //
2129 // template-id:
2130 // operator-function-id < template-argument-list[opt] >
Sean Hunte6252d12009-11-28 08:58:14 +00002131 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2132 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002133 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002134 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2135 0, SourceLocation(),
2136 EnteringContext, ObjectType,
2137 Result, TemplateSpecified);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002138
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002139 return false;
2140 }
2141
David Blaikie4e4d0842012-03-11 07:00:24 +00002142 if (getLangOpts().CPlusPlus &&
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002143 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002144 // C++ [expr.unary.op]p10:
2145 // There is an ambiguity in the unary-expression ~X(), where X is a
2146 // class-name. The ambiguity is resolved in favor of treating ~ as a
2147 // unary complement rather than treating ~X as referring to a destructor.
2148
2149 // Parse the '~'.
2150 SourceLocation TildeLoc = ConsumeToken();
David Blaikie53a75c02011-12-08 16:13:53 +00002151
2152 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2153 DeclSpec DS(AttrFactory);
2154 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2155 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2156 Result.setDestructorName(TildeLoc, Type, EndLoc);
2157 return false;
2158 }
2159 return true;
2160 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002161
2162 // Parse the class-name.
2163 if (Tok.isNot(tok::identifier)) {
Douglas Gregor124b8782010-02-16 19:09:40 +00002164 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002165 return true;
2166 }
2167
2168 // Parse the class-name (or template-name in a simple-template-id).
2169 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2170 SourceLocation ClassNameLoc = ConsumeToken();
2171
Douglas Gregor0278e122010-05-05 05:58:24 +00002172 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallb3d87482010-08-24 05:47:05 +00002173 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002174 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2175 ClassName, ClassNameLoc,
2176 EnteringContext, ObjectType,
2177 Result, TemplateSpecified);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002178 }
2179
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002180 // Note that this is a destructor name.
John McCallb3d87482010-08-24 05:47:05 +00002181 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2182 ClassNameLoc, getCurScope(),
2183 SS, ObjectType,
2184 EnteringContext);
Douglas Gregor124b8782010-02-16 19:09:40 +00002185 if (!Ty)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002186 return true;
Douglas Gregor124b8782010-02-16 19:09:40 +00002187
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002188 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002189 return false;
2190 }
2191
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002192 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikie4e4d0842012-03-11 07:00:24 +00002193 << getLangOpts().CPlusPlus;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002194 return true;
2195}
2196
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002197/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2198/// memory in a typesafe manner and call constructors.
Mike Stump1eb44332009-09-09 15:08:12 +00002199///
Chris Lattner59232d32009-01-04 21:25:24 +00002200/// This method is called to parse the new expression after the optional :: has
2201/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2202/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002203///
2204/// new-expression:
2205/// '::'[opt] 'new' new-placement[opt] new-type-id
2206/// new-initializer[opt]
2207/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2208/// new-initializer[opt]
2209///
2210/// new-placement:
2211/// '(' expression-list ')'
2212///
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002213/// new-type-id:
2214/// type-specifier-seq new-declarator[opt]
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002215/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002216///
2217/// new-declarator:
2218/// ptr-operator new-declarator[opt]
2219/// direct-new-declarator
2220///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002221/// new-initializer:
2222/// '(' expression-list[opt] ')'
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002223/// [C++0x] braced-init-list
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002224///
John McCall60d7b3a2010-08-24 06:29:42 +00002225ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002226Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2227 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2228 ConsumeToken(); // Consume 'new'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002229
2230 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2231 // second form of new-expression. It can't be a new-type-id.
2232
Sebastian Redla55e52c2008-11-25 22:21:31 +00002233 ExprVector PlacementArgs(Actions);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002234 SourceLocation PlacementLParen, PlacementRParen;
2235
Douglas Gregor4bd40312010-07-13 15:54:32 +00002236 SourceRange TypeIdParens;
John McCall0b7e6782011-03-24 11:26:52 +00002237 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002238 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002239 if (Tok.is(tok::l_paren)) {
2240 // If it turns out to be a placement, we change the type location.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002241 BalancedDelimiterTracker T(*this, tok::l_paren);
2242 T.consumeOpen();
2243 PlacementLParen = T.getOpenLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002244 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2245 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002246 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002247 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002248
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002249 T.consumeClose();
2250 PlacementRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002251 if (PlacementRParen.isInvalid()) {
2252 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002253 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002254 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002255
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002256 if (PlacementArgs.empty()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002257 // Reset the placement locations. There was no placement.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002258 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002259 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002260 } else {
2261 // We still need the type.
2262 if (Tok.is(tok::l_paren)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002263 BalancedDelimiterTracker T(*this, tok::l_paren);
2264 T.consumeOpen();
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002265 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002266 ParseSpecifierQualifierList(DS);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002267 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002268 ParseDeclarator(DeclaratorInfo);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002269 T.consumeClose();
2270 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002271 } else {
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002272 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002273 if (ParseCXXTypeSpecifierSeq(DS))
2274 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002275 else {
2276 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002277 ParseDeclaratorInternal(DeclaratorInfo,
2278 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002279 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002280 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002281 }
2282 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002283 // A new-type-id is a simplified type-id, where essentially the
2284 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002285 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002286 if (ParseCXXTypeSpecifierSeq(DS))
2287 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002288 else {
2289 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002290 ParseDeclaratorInternal(DeclaratorInfo,
2291 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002292 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002293 }
Chris Lattnereaaebc72009-04-25 08:06:05 +00002294 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002295 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002296 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002297 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002298
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002299 ExprResult Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002300
2301 if (Tok.is(tok::l_paren)) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002302 SourceLocation ConstructorLParen, ConstructorRParen;
2303 ExprVector ConstructorArgs(Actions);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002304 BalancedDelimiterTracker T(*this, tok::l_paren);
2305 T.consumeOpen();
2306 ConstructorLParen = T.getOpenLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002307 if (Tok.isNot(tok::r_paren)) {
2308 CommaLocsTy CommaLocs;
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002309 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2310 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002311 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002312 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002313 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002314 T.consumeClose();
2315 ConstructorRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002316 if (ConstructorRParen.isInvalid()) {
2317 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002318 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002319 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002320 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2321 ConstructorRParen,
2322 move_arg(ConstructorArgs));
David Blaikie4e4d0842012-03-11 07:00:24 +00002323 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus0x) {
Richard Smith7fe62082011-10-15 05:09:34 +00002324 Diag(Tok.getLocation(),
2325 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002326 Initializer = ParseBraceInitializer();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002327 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002328 if (Initializer.isInvalid())
2329 return Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002330
Sebastian Redlf53597f2009-03-15 17:47:39 +00002331 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
2332 move_arg(PlacementArgs), PlacementRParen,
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002333 TypeIdParens, DeclaratorInfo, Initializer.take());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002334}
2335
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002336/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2337/// passed to ParseDeclaratorInternal.
2338///
2339/// direct-new-declarator:
2340/// '[' expression ']'
2341/// direct-new-declarator '[' constant-expression ']'
2342///
Chris Lattner59232d32009-01-04 21:25:24 +00002343void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002344 // Parse the array dimensions.
2345 bool first = true;
2346 while (Tok.is(tok::l_square)) {
Richard Smith6ee326a2012-04-10 01:32:12 +00002347 // An array-size expression can't start with a lambda.
2348 if (CheckProhibitedCXX11Attribute())
2349 continue;
2350
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002351 BalancedDelimiterTracker T(*this, tok::l_square);
2352 T.consumeOpen();
2353
John McCall60d7b3a2010-08-24 06:29:42 +00002354 ExprResult Size(first ? ParseExpression()
Sebastian Redl2f7ece72008-12-11 21:36:32 +00002355 : ParseConstantExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002356 if (Size.isInvalid()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002357 // Recover
2358 SkipUntil(tok::r_square);
2359 return;
2360 }
2361 first = false;
2362
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002363 T.consumeClose();
John McCall0b7e6782011-03-24 11:26:52 +00002364
Richard Smith6ee326a2012-04-10 01:32:12 +00002365 // Attributes here appertain to the array type. C++11 [expr.new]p5.
2366 ParsedAttributes Attrs(AttrFactory);
2367 MaybeParseCXX0XAttributes(Attrs);
2368
John McCall0b7e6782011-03-24 11:26:52 +00002369 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall7f040a92010-12-24 02:08:15 +00002370 /*static=*/false, /*star=*/false,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002371 Size.release(),
2372 T.getOpenLocation(),
2373 T.getCloseLocation()),
Richard Smith6ee326a2012-04-10 01:32:12 +00002374 Attrs, T.getCloseLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002375
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002376 if (T.getCloseLocation().isInvalid())
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002377 return;
2378 }
2379}
2380
2381/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2382/// This ambiguity appears in the syntax of the C++ new operator.
2383///
2384/// new-expression:
2385/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2386/// new-initializer[opt]
2387///
2388/// new-placement:
2389/// '(' expression-list ')'
2390///
John McCallca0408f2010-08-23 06:44:23 +00002391bool Parser::ParseExpressionListOrTypeId(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner59232d32009-01-04 21:25:24 +00002393 Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002394 // The '(' was already consumed.
2395 if (isTypeIdInParens()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002396 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlab197ba2009-02-09 18:23:29 +00002397 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002398 ParseDeclarator(D);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002399 return D.isInvalidType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002400 }
2401
2402 // It's not a type, it has to be an expression list.
2403 // Discard the comma locations - ActOnCXXNew has enough parameters.
2404 CommaLocsTy CommaLocs;
2405 return ParseExpressionList(PlacementArgs, CommaLocs);
2406}
2407
2408/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2409/// to free memory allocated by new.
2410///
Chris Lattner59232d32009-01-04 21:25:24 +00002411/// This method is called to parse the 'delete' expression after the optional
2412/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2413/// and "Start" is its location. Otherwise, "Start" is the location of the
2414/// 'delete' token.
2415///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002416/// delete-expression:
2417/// '::'[opt] 'delete' cast-expression
2418/// '::'[opt] 'delete' '[' ']' cast-expression
John McCall60d7b3a2010-08-24 06:29:42 +00002419ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002420Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2421 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2422 ConsumeToken(); // Consume 'delete'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002423
2424 // Array delete?
2425 bool ArrayDelete = false;
Richard Smith6ee326a2012-04-10 01:32:12 +00002426 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
2427 // FIXME: This could be the start of a lambda-expression. We should
2428 // disambiguate this, but that will require arbitrary lookahead if
2429 // the next token is '(':
2430 // delete [](int*){ /* ... */
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002431 ArrayDelete = true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002432 BalancedDelimiterTracker T(*this, tok::l_square);
2433
2434 T.consumeOpen();
2435 T.consumeClose();
2436 if (T.getCloseLocation().isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002437 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002438 }
2439
John McCall60d7b3a2010-08-24 06:29:42 +00002440 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002441 if (Operand.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002442 return move(Operand);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002443
John McCall9ae2f072010-08-23 23:25:46 +00002444 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002445}
Sebastian Redl64b45f72009-01-05 20:52:13 +00002446
Mike Stump1eb44332009-09-09 15:08:12 +00002447static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002448 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002449 default: llvm_unreachable("Not a known unary type trait.");
Sebastian Redl64b45f72009-01-05 20:52:13 +00002450 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002451 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
John Wiegley20c0da72011-04-27 23:09:49 +00002452 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002453 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
Sean Hunt023df372011-05-09 18:22:59 +00002454 case tok::kw___has_trivial_constructor:
2455 return UTT_HasTrivialDefaultConstructor;
John Wiegley20c0da72011-04-27 23:09:49 +00002456 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002457 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2458 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2459 case tok::kw___is_abstract: return UTT_IsAbstract;
John Wiegley20c0da72011-04-27 23:09:49 +00002460 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2461 case tok::kw___is_array: return UTT_IsArray;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002462 case tok::kw___is_class: return UTT_IsClass;
John Wiegley20c0da72011-04-27 23:09:49 +00002463 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2464 case tok::kw___is_compound: return UTT_IsCompound;
2465 case tok::kw___is_const: return UTT_IsConst;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002466 case tok::kw___is_empty: return UTT_IsEmpty;
2467 case tok::kw___is_enum: return UTT_IsEnum;
Douglas Gregor5e9392b2011-12-03 18:14:24 +00002468 case tok::kw___is_final: return UTT_IsFinal;
John Wiegley20c0da72011-04-27 23:09:49 +00002469 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2470 case tok::kw___is_function: return UTT_IsFunction;
2471 case tok::kw___is_fundamental: return UTT_IsFundamental;
2472 case tok::kw___is_integral: return UTT_IsIntegral;
John Wiegley20c0da72011-04-27 23:09:49 +00002473 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2474 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2475 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2476 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2477 case tok::kw___is_object: return UTT_IsObject;
Chandler Carruth4e61ddd2011-04-23 10:47:20 +00002478 case tok::kw___is_literal: return UTT_IsLiteral;
Chandler Carruth38402812011-04-24 02:49:28 +00002479 case tok::kw___is_literal_type: return UTT_IsLiteral;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002480 case tok::kw___is_pod: return UTT_IsPOD;
John Wiegley20c0da72011-04-27 23:09:49 +00002481 case tok::kw___is_pointer: return UTT_IsPointer;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002482 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
John Wiegley20c0da72011-04-27 23:09:49 +00002483 case tok::kw___is_reference: return UTT_IsReference;
John Wiegley20c0da72011-04-27 23:09:49 +00002484 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2485 case tok::kw___is_scalar: return UTT_IsScalar;
2486 case tok::kw___is_signed: return UTT_IsSigned;
2487 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2488 case tok::kw___is_trivial: return UTT_IsTrivial;
Sean Huntfeb375d2011-05-13 00:31:07 +00002489 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002490 case tok::kw___is_union: return UTT_IsUnion;
John Wiegley20c0da72011-04-27 23:09:49 +00002491 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2492 case tok::kw___is_void: return UTT_IsVoid;
2493 case tok::kw___is_volatile: return UTT_IsVolatile;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002494 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002495}
2496
2497static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2498 switch(kind) {
Francois Pichet38c2b732010-12-07 00:55:57 +00002499 default: llvm_unreachable("Not a known binary type trait");
Francois Pichetf1872372010-12-08 22:35:30 +00002500 case tok::kw___is_base_of: return BTT_IsBaseOf;
John Wiegley20c0da72011-04-27 23:09:49 +00002501 case tok::kw___is_convertible: return BTT_IsConvertible;
2502 case tok::kw___is_same: return BTT_IsSame;
Francois Pichetf1872372010-12-08 22:35:30 +00002503 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
Douglas Gregor9f361132011-01-27 20:28:01 +00002504 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
Douglas Gregor25d0a0f2012-02-23 07:33:15 +00002505 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
Francois Pichet6ad6f282010-12-07 00:08:36 +00002506 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002507}
2508
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002509static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2510 switch (kind) {
2511 default: llvm_unreachable("Not a known type trait");
2512 case tok::kw___is_trivially_constructible:
2513 return TT_IsTriviallyConstructible;
2514 }
2515}
2516
John Wiegley21ff2e52011-04-28 00:16:57 +00002517static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2518 switch(kind) {
2519 default: llvm_unreachable("Not a known binary type trait");
2520 case tok::kw___array_rank: return ATT_ArrayRank;
2521 case tok::kw___array_extent: return ATT_ArrayExtent;
2522 }
2523}
2524
John Wiegley55262202011-04-25 06:54:41 +00002525static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2526 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002527 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegley55262202011-04-25 06:54:41 +00002528 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2529 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2530 }
2531}
2532
Sebastian Redl64b45f72009-01-05 20:52:13 +00002533/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2534/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2535/// templates.
2536///
2537/// primary-expression:
2538/// [GNU] unary-type-trait '(' type-id ')'
2539///
John McCall60d7b3a2010-08-24 06:29:42 +00002540ExprResult Parser::ParseUnaryTypeTrait() {
Sebastian Redl64b45f72009-01-05 20:52:13 +00002541 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2542 SourceLocation Loc = ConsumeToken();
2543
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002544 BalancedDelimiterTracker T(*this, tok::l_paren);
2545 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redl64b45f72009-01-05 20:52:13 +00002546 return ExprError();
2547
2548 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2549 // there will be cryptic errors about mismatched parentheses and missing
2550 // specifiers.
Douglas Gregor809070a2009-02-18 17:45:20 +00002551 TypeResult Ty = ParseTypeName();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002552
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002553 T.consumeClose();
Sebastian Redl64b45f72009-01-05 20:52:13 +00002554
Douglas Gregor809070a2009-02-18 17:45:20 +00002555 if (Ty.isInvalid())
2556 return ExprError();
2557
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002558 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
Sebastian Redl64b45f72009-01-05 20:52:13 +00002559}
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002560
Francois Pichet6ad6f282010-12-07 00:08:36 +00002561/// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2562/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2563/// templates.
2564///
2565/// primary-expression:
2566/// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2567///
2568ExprResult Parser::ParseBinaryTypeTrait() {
2569 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2570 SourceLocation Loc = ConsumeToken();
2571
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002572 BalancedDelimiterTracker T(*this, tok::l_paren);
2573 if (T.expectAndConsume(diag::err_expected_lparen))
Francois Pichet6ad6f282010-12-07 00:08:36 +00002574 return ExprError();
2575
2576 TypeResult LhsTy = ParseTypeName();
2577 if (LhsTy.isInvalid()) {
2578 SkipUntil(tok::r_paren);
2579 return ExprError();
2580 }
2581
2582 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2583 SkipUntil(tok::r_paren);
2584 return ExprError();
2585 }
2586
2587 TypeResult RhsTy = ParseTypeName();
2588 if (RhsTy.isInvalid()) {
2589 SkipUntil(tok::r_paren);
2590 return ExprError();
2591 }
2592
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002593 T.consumeClose();
Francois Pichet6ad6f282010-12-07 00:08:36 +00002594
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002595 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2596 T.getCloseLocation());
Francois Pichet6ad6f282010-12-07 00:08:36 +00002597}
2598
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002599/// \brief Parse the built-in type-trait pseudo-functions that allow
2600/// implementation of the TR1/C++11 type traits templates.
2601///
2602/// primary-expression:
2603/// type-trait '(' type-id-seq ')'
2604///
2605/// type-id-seq:
2606/// type-id ...[opt] type-id-seq[opt]
2607///
2608ExprResult Parser::ParseTypeTrait() {
2609 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2610 SourceLocation Loc = ConsumeToken();
2611
2612 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2613 if (Parens.expectAndConsume(diag::err_expected_lparen))
2614 return ExprError();
2615
2616 llvm::SmallVector<ParsedType, 2> Args;
2617 do {
2618 // Parse the next type.
2619 TypeResult Ty = ParseTypeName();
2620 if (Ty.isInvalid()) {
2621 Parens.skipToEnd();
2622 return ExprError();
2623 }
2624
2625 // Parse the ellipsis, if present.
2626 if (Tok.is(tok::ellipsis)) {
2627 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2628 if (Ty.isInvalid()) {
2629 Parens.skipToEnd();
2630 return ExprError();
2631 }
2632 }
2633
2634 // Add this type to the list of arguments.
2635 Args.push_back(Ty.get());
2636
2637 if (Tok.is(tok::comma)) {
2638 ConsumeToken();
2639 continue;
2640 }
2641
2642 break;
2643 } while (true);
2644
2645 if (Parens.consumeClose())
2646 return ExprError();
2647
2648 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2649}
2650
John Wiegley21ff2e52011-04-28 00:16:57 +00002651/// ParseArrayTypeTrait - Parse the built-in array type-trait
2652/// pseudo-functions.
2653///
2654/// primary-expression:
2655/// [Embarcadero] '__array_rank' '(' type-id ')'
2656/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2657///
2658ExprResult Parser::ParseArrayTypeTrait() {
2659 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2660 SourceLocation Loc = ConsumeToken();
2661
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002662 BalancedDelimiterTracker T(*this, tok::l_paren);
2663 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegley21ff2e52011-04-28 00:16:57 +00002664 return ExprError();
2665
2666 TypeResult Ty = ParseTypeName();
2667 if (Ty.isInvalid()) {
2668 SkipUntil(tok::comma);
2669 SkipUntil(tok::r_paren);
2670 return ExprError();
2671 }
2672
2673 switch (ATT) {
2674 case ATT_ArrayRank: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002675 T.consumeClose();
2676 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2677 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002678 }
2679 case ATT_ArrayExtent: {
2680 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2681 SkipUntil(tok::r_paren);
2682 return ExprError();
2683 }
2684
2685 ExprResult DimExpr = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002686 T.consumeClose();
John Wiegley21ff2e52011-04-28 00:16:57 +00002687
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002688 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2689 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002690 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002691 }
David Blaikie30263482012-01-20 21:50:17 +00002692 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley21ff2e52011-04-28 00:16:57 +00002693}
2694
John Wiegley55262202011-04-25 06:54:41 +00002695/// ParseExpressionTrait - Parse built-in expression-trait
2696/// pseudo-functions like __is_lvalue_expr( xxx ).
2697///
2698/// primary-expression:
2699/// [Embarcadero] expression-trait '(' expression ')'
2700///
2701ExprResult Parser::ParseExpressionTrait() {
2702 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2703 SourceLocation Loc = ConsumeToken();
2704
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002705 BalancedDelimiterTracker T(*this, tok::l_paren);
2706 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegley55262202011-04-25 06:54:41 +00002707 return ExprError();
2708
2709 ExprResult Expr = ParseExpression();
2710
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002711 T.consumeClose();
John Wiegley55262202011-04-25 06:54:41 +00002712
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002713 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2714 T.getCloseLocation());
John Wiegley55262202011-04-25 06:54:41 +00002715}
2716
2717
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002718/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2719/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2720/// based on the context past the parens.
John McCall60d7b3a2010-08-24 06:29:42 +00002721ExprResult
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002722Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallb3d87482010-08-24 05:47:05 +00002723 ParsedType &CastTy,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002724 BalancedDelimiterTracker &Tracker) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002725 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002726 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2727 assert(isTypeIdInParens() && "Not a type-id!");
2728
John McCall60d7b3a2010-08-24 06:29:42 +00002729 ExprResult Result(true);
John McCallb3d87482010-08-24 05:47:05 +00002730 CastTy = ParsedType();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002731
2732 // We need to disambiguate a very ugly part of the C++ syntax:
2733 //
2734 // (T())x; - type-id
2735 // (T())*x; - type-id
2736 // (T())/x; - expression
2737 // (T()); - expression
2738 //
2739 // The bad news is that we cannot use the specialized tentative parser, since
2740 // it can only verify that the thing inside the parens can be parsed as
2741 // type-id, it is not useful for determining the context past the parens.
2742 //
2743 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidisa558a892009-05-22 15:12:46 +00002744 // making any unnecessary Action calls.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002745 //
2746 // It uses a scheme similar to parsing inline methods. The parenthesized
2747 // tokens are cached, the context that follows is determined (possibly by
2748 // parsing a cast-expression), and then we re-introduce the cached tokens
2749 // into the token stream and parse them appropriately.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002750
Mike Stump1eb44332009-09-09 15:08:12 +00002751 ParenParseOption ParseAs;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002752 CachedTokens Toks;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002753
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002754 // Store the tokens of the parentheses. We will parse them after we determine
2755 // the context that follows them.
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +00002756 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002757 // We didn't find the ')' we expected.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002758 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002759 return ExprError();
2760 }
2761
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002762 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002763 ParseAs = CompoundLiteral;
2764 } else {
2765 bool NotCastExpr;
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002766 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2767 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2768 NotCastExpr = true;
2769 } else {
2770 // Try parsing the cast-expression that may follow.
2771 // If it is not a cast-expression, NotCastExpr will be true and no token
2772 // will be consumed.
2773 Result = ParseCastExpression(false/*isUnaryExpression*/,
2774 false/*isAddressofOperand*/,
John McCallb3d87482010-08-24 05:47:05 +00002775 NotCastExpr,
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002776 // type-id has priority.
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00002777 IsTypeCast);
Eli Friedmanb53f08a2009-05-25 19:41:42 +00002778 }
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002779
2780 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2781 // an expression.
2782 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002783 }
2784
Mike Stump1eb44332009-09-09 15:08:12 +00002785 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002786 Toks.push_back(Tok);
2787 // Re-enter the stored parenthesized tokens into the token stream, so we may
2788 // parse them now.
2789 PP.EnterTokenStream(Toks.data(), Toks.size(),
2790 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2791 // Drop the current token and bring the first cached one. It's the same token
2792 // as when we entered this function.
2793 ConsumeAnyToken();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002794
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002795 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002796 // Parse the type declarator.
2797 DeclSpec DS(AttrFactory);
2798 ParseSpecifierQualifierList(DS);
2799 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2800 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002801
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002802 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002803 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002804
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002805 if (ParseAs == CompoundLiteral) {
2806 ExprType = CompoundLiteral;
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002807 TypeResult Ty = ParseTypeName();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002808 return ParseCompoundLiteralExpression(Ty.get(),
2809 Tracker.getOpenLocation(),
2810 Tracker.getCloseLocation());
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002811 }
Mike Stump1eb44332009-09-09 15:08:12 +00002812
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002813 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2814 assert(ParseAs == CastExpr);
2815
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00002816 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002817 return ExprError();
2818
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002819 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002820 if (!Result.isInvalid())
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002821 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2822 DeclaratorInfo, CastTy,
2823 Tracker.getCloseLocation(), Result.take());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002824 return move(Result);
2825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002827 // Not a compound literal, and not followed by a cast-expression.
2828 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002829
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002830 ExprType = SimpleExpr;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00002831 Result = ParseExpression();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002832 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002833 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2834 Tok.getLocation(), Result.take());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002835
2836 // Match the ')'.
2837 if (Result.isInvalid()) {
2838 SkipUntil(tok::r_paren);
2839 return ExprError();
2840 }
Mike Stump1eb44332009-09-09 15:08:12 +00002841
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002842 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00002843 return move(Result);
2844}