blob: 9c2cfcc490ead66cbb74a1318d3201329c7b82b8 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Faisal Vali2b391ab2013-09-26 19:54:12 +000013#include "clang/AST/DeclTemplate.h"
Chris Lattner29375652006-12-04 18:06:35 +000014#include "clang/Parse/Parser.h"
Douglas Gregor94a32472011-01-11 00:33:19 +000015#include "RAIIObjectsForParser.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
John McCall8b0666c2010-08-20 18:27:03 +000019#include "clang/Sema/DeclSpec.h"
20#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000022#include "llvm/Support/ErrorHandling.h"
23
Faisal Vali2b391ab2013-09-26 19:54:12 +000024
Chris Lattner29375652006-12-04 18:06:35 +000025using namespace clang;
26
Richard Smith55858492011-04-14 21:45:45 +000027static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
28 switch (Kind) {
29 case tok::kw_template: return 0;
30 case tok::kw_const_cast: return 1;
31 case tok::kw_dynamic_cast: return 2;
32 case tok::kw_reinterpret_cast: return 3;
33 case tok::kw_static_cast: return 4;
34 default:
David Blaikie83d382b2011-09-23 05:06:16 +000035 llvm_unreachable("Unknown type for digraph error message.");
Richard Smith55858492011-04-14 21:45:45 +000036 }
37}
38
39// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000040bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000041 SourceManager &SM = PP.getSourceManager();
42 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000043 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000044 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
45}
46
47// Suggest fixit for "<::" after a cast.
48static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
49 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
50 // Pull '<:' and ':' off token stream.
51 if (!AtDigraph)
52 PP.Lex(DigraphToken);
53 PP.Lex(ColonToken);
54
55 SourceRange Range;
56 Range.setBegin(DigraphToken.getLocation());
57 Range.setEnd(ColonToken.getLocation());
58 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
59 << SelectDigraphErrorMessage(Kind)
60 << FixItHint::CreateReplacement(Range, "< ::");
61
62 // Update token information to reflect their change in token type.
63 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000064 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000065 ColonToken.setLength(2);
66 DigraphToken.setKind(tok::less);
67 DigraphToken.setLength(1);
68
69 // Push new tokens back to token stream.
70 PP.EnterToken(ColonToken);
71 if (!AtDigraph)
72 PP.EnterToken(DigraphToken);
73}
74
Richard Trieu01fc0012011-09-19 19:01:00 +000075// Check for '<::' which should be '< ::' instead of '[:' when following
76// a template name.
77void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
78 bool EnteringContext,
79 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000080 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000081 return;
82
83 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000084 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000085 return;
86
87 TemplateTy Template;
88 UnqualifiedId TemplateName;
89 TemplateName.setIdentifier(&II, Tok.getLocation());
90 bool MemberOfUnknownSpecialization;
91 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
92 TemplateName, ObjectType, EnteringContext,
93 Template, MemberOfUnknownSpecialization))
94 return;
95
96 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
97 /*AtDigraph*/false);
98}
99
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000100/// \brief Emits an error for a left parentheses after a double colon.
101///
102/// When a '(' is found after a '::', emit an error. Attempt to fix the token
Nico Weber6be9b252012-11-29 05:29:23 +0000103/// stream by removing the '(', and the matching ')' if found.
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000104void Parser::CheckForLParenAfterColonColon() {
105 if (!Tok.is(tok::l_paren))
106 return;
107
108 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
109 Token Tok1 = getCurToken();
110 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
111 return;
112
113 if (Tok1.is(tok::identifier)) {
114 Token Tok2 = GetLookAheadToken(1);
115 if (Tok2.is(tok::r_paren)) {
116 ConsumeToken();
117 PP.EnterToken(Tok1);
118 r_parenLoc = ConsumeParen();
119 }
120 } else if (Tok1.is(tok::star)) {
121 Token Tok2 = GetLookAheadToken(1);
122 if (Tok2.is(tok::identifier)) {
123 Token Tok3 = GetLookAheadToken(2);
124 if (Tok3.is(tok::r_paren)) {
125 ConsumeToken();
126 ConsumeToken();
127 PP.EnterToken(Tok2);
128 PP.EnterToken(Tok1);
129 r_parenLoc = ConsumeParen();
130 }
131 }
132 }
133
134 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
135 << FixItHint::CreateRemoval(l_parenLoc)
136 << FixItHint::CreateRemoval(r_parenLoc);
137}
138
Mike Stump11289f42009-09-09 15:08:12 +0000139/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000140///
141/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000142/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000143/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000144///
145/// '::'[opt] nested-name-specifier
146/// '::'
147///
148/// nested-name-specifier:
149/// type-name '::'
150/// namespace-name '::'
151/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000152/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000153///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000154///
Mike Stump11289f42009-09-09 15:08:12 +0000155/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000156/// nested-name-specifier (or empty)
157///
Mike Stump11289f42009-09-09 15:08:12 +0000158/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000159/// the "." or "->" of a member access expression, this parameter provides the
160/// type of the object whose members are being accessed.
161///
162/// \param EnteringContext whether we will be entering into the context of
163/// the nested-name-specifier after parsing it.
164///
Douglas Gregore610ada2010-02-24 18:44:31 +0000165/// \param MayBePseudoDestructor When non-NULL, points to a flag that
166/// indicates whether this nested-name-specifier may be part of a
167/// pseudo-destructor name. In this case, the flag will be set false
168/// if we don't actually end up parsing a destructor name. Moreorover,
169/// if we do end up determining that we are parsing a destructor name,
170/// the last component of the nested-name-specifier is not parsed as
171/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000172///
173/// \param IsTypename If \c true, this nested-name-specifier is known to be
174/// part of a type name. This is used to improve error recovery.
175///
176/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
177/// filled in with the leading identifier in the last component of the
178/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000179///
John McCall1f476a12010-02-26 08:45:28 +0000180/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000181bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000182 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000183 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000184 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000185 bool IsTypename,
186 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000187 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000188 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000189
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000190 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000191 assert(!LastII && "want last identifier but have already annotated scope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000192 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
193 Tok.getAnnotationRange(),
194 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000195 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000196 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000197 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000198
Larisse Voufob959c3c2013-08-06 05:49:26 +0000199 if (Tok.is(tok::annot_template_id)) {
200 // If the current token is an annotated template id, it may already have
201 // a scope specifier. Restore it.
202 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
203 SS = TemplateId->SS;
204 }
205
Richard Smith7447af42013-03-26 01:15:19 +0000206 if (LastII)
207 *LastII = 0;
208
Douglas Gregor7f741122009-02-25 19:37:18 +0000209 bool HasScopeSpecifier = false;
210
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000211 if (Tok.is(tok::coloncolon)) {
212 // ::new and ::delete aren't nested-name-specifiers.
213 tok::TokenKind NextKind = NextToken().getKind();
214 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
215 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner45ddec32009-01-05 00:13:00 +0000217 // '::' - Global scope qualifier.
Douglas Gregor90c99722011-02-24 00:17:56 +0000218 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
219 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000220
221 CheckForLParenAfterColonColon();
222
Douglas Gregor7f741122009-02-25 19:37:18 +0000223 HasScopeSpecifier = true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000224 }
225
Douglas Gregore610ada2010-02-24 18:44:31 +0000226 bool CheckForDestructor = false;
227 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
228 CheckForDestructor = true;
229 *MayBePseudoDestructor = false;
230 }
231
David Blaikie15a430a2011-12-04 05:04:18 +0000232 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
233 DeclSpec DS(AttrFactory);
234 SourceLocation DeclLoc = Tok.getLocation();
235 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
236 if (Tok.isNot(tok::coloncolon)) {
237 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
238 return false;
239 }
240
241 SourceLocation CCLoc = ConsumeToken();
242 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
243 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
244
245 HasScopeSpecifier = true;
246 }
247
Douglas Gregor7f741122009-02-25 19:37:18 +0000248 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000249 if (HasScopeSpecifier) {
250 // C++ [basic.lookup.classref]p5:
251 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000252 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000253 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000254 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000255 // the class-name-or-namespace-name is looked up in global scope as a
256 // class-name or namespace-name.
257 //
258 // To implement this, we clear out the object type as soon as we've
259 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000260 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000261
262 if (Tok.is(tok::code_completion)) {
263 // Code completion for a nested-name-specifier, where the code
264 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000265 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000266 // Include code completion token into the range of the scope otherwise
267 // when we try to annotate the scope tokens the dangling code completion
268 // token will cause assertion in
269 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000270 SS.setEndLoc(Tok.getLocation());
271 cutOffParsing();
272 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000273 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000274 }
Mike Stump11289f42009-09-09 15:08:12 +0000275
Douglas Gregor7f741122009-02-25 19:37:18 +0000276 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000277 // nested-name-specifier 'template'[opt] simple-template-id '::'
278
279 // Parse the optional 'template' keyword, then make sure we have
280 // 'identifier <' after it.
281 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000282 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000283 // nested-name-specifier, since they aren't allowed to start with
284 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000285 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000286 break;
287
Douglas Gregor120635b2009-11-11 16:39:34 +0000288 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000289 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000290
Douglas Gregor71395fa2009-11-04 00:56:37 +0000291 UnqualifiedId TemplateName;
292 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000293 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000294 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000295 ConsumeToken();
296 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000297 // We don't need to actually parse the unqualified-id in this case,
298 // because a simple-template-id cannot start with 'operator', but
299 // go ahead and parse it anyway for consistency with the case where
300 // we already annotated the template-id.
301 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000302 TemplateName)) {
303 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000304 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000305 }
Richard Smithd091dc12013-12-05 00:58:33 +0000306
Alexis Hunted0530f2009-11-28 08:58:14 +0000307 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
308 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000309 Diag(TemplateName.getSourceRange().getBegin(),
310 diag::err_id_after_template_in_nested_name_spec)
311 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000312 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000313 break;
314 }
315 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000316 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000317 break;
318 }
Mike Stump11289f42009-09-09 15:08:12 +0000319
Douglas Gregor120635b2009-11-11 16:39:34 +0000320 // If the next token is not '<', we have a qualified-id that refers
321 // to a template name, such as T::template apply, but is not a
322 // template-id.
323 if (Tok.isNot(tok::less)) {
324 TPA.Revert();
325 break;
326 }
327
328 // Commit to parsing the template-id.
329 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000330 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000331 if (TemplateNameKind TNK
332 = Actions.ActOnDependentTemplateName(getCurScope(),
333 SS, TemplateKWLoc, TemplateName,
334 ObjectType, EnteringContext,
335 Template)) {
336 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
337 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000338 return true;
339 } else
John McCall1f476a12010-02-26 08:45:28 +0000340 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattner0eed3a62009-06-26 03:47:46 +0000342 continue;
343 }
Mike Stump11289f42009-09-09 15:08:12 +0000344
Douglas Gregor7f741122009-02-25 19:37:18 +0000345 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000346 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000347 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000348 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000349 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000350 // So we need to check whether the template-id is a simple-template-id of
351 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000352 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000353 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000354 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
355 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000356 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000357 }
358
Richard Smith7447af42013-03-26 01:15:19 +0000359 if (LastII)
360 *LastII = TemplateId->Name;
361
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000362 // Consume the template-id token.
363 ConsumeToken();
364
365 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
366 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000367
David Blaikie8c045bc2011-11-07 03:30:03 +0000368 HasScopeSpecifier = true;
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000369
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000370 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000371 TemplateId->NumArgs);
372
373 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000374 SS,
375 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000376 TemplateId->Template,
377 TemplateId->TemplateNameLoc,
378 TemplateId->LAngleLoc,
379 TemplateArgsPtr,
380 TemplateId->RAngleLoc,
381 CCLoc,
382 EnteringContext)) {
383 SourceLocation StartLoc
384 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
385 : TemplateId->TemplateNameLoc;
386 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000387 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000388
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000389 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000390 }
391
Chris Lattnere2355f72009-06-26 03:52:38 +0000392
393 // The rest of the nested-name-specifier possibilities start with
394 // tok::identifier.
395 if (Tok.isNot(tok::identifier))
396 break;
397
398 IdentifierInfo &II = *Tok.getIdentifierInfo();
399
400 // nested-name-specifier:
401 // type-name '::'
402 // namespace-name '::'
403 // nested-name-specifier identifier '::'
404 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000405
406 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
407 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000408 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000409 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
410 Tok.getLocation(),
411 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000412 EnteringContext) &&
413 // If the token after the colon isn't an identifier, it's still an
414 // error, but they probably meant something else strange so don't
415 // recover like this.
416 PP.LookAhead(1).is(tok::identifier)) {
417 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000418 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000419
420 // Recover as if the user wrote '::'.
421 Next.setKind(tok::coloncolon);
422 }
Chris Lattner1c428032009-12-07 01:36:53 +0000423 }
424
Chris Lattnere2355f72009-06-26 03:52:38 +0000425 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000426 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor0be31a22010-07-02 17:43:08 +0000427 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000428 II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000429 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000430 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000431 }
432
Richard Smith7447af42013-03-26 01:15:19 +0000433 if (LastII)
434 *LastII = &II;
435
Chris Lattnere2355f72009-06-26 03:52:38 +0000436 // We have an identifier followed by a '::'. Lookup this name
437 // as the name in a nested-name-specifier.
438 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000439 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
440 "NextToken() not working properly!");
Chris Lattnere2355f72009-06-26 03:52:38 +0000441 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000442
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000443 CheckForLParenAfterColonColon();
444
Douglas Gregor90c99722011-02-24 00:17:56 +0000445 HasScopeSpecifier = true;
446 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
447 ObjectType, EnteringContext, SS))
448 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
449
Chris Lattnere2355f72009-06-26 03:52:38 +0000450 continue;
451 }
Mike Stump11289f42009-09-09 15:08:12 +0000452
Richard Trieu01fc0012011-09-19 19:01:00 +0000453 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000454
Chris Lattnere2355f72009-06-26 03:52:38 +0000455 // nested-name-specifier:
456 // type-name '<'
457 if (Next.is(tok::less)) {
458 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000459 UnqualifiedId TemplateName;
460 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000461 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000462 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000463 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000464 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000465 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000466 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000467 Template,
468 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000469 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000470 // with a template-id annotation. We do not permit the
471 // template-id to be translated into a type annotation,
472 // because some clients (e.g., the parsing of class template
473 // specializations) still want to see the original template-id
474 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000475 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000476 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
477 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000478 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000479 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000480 }
481
Douglas Gregor20c38a72010-05-21 23:43:39 +0000482 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000483 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000484 // We have something like t::getAs<T>, where getAs is a
485 // member of an unknown specialization. However, this will only
486 // parse correctly as a template, so suggest the keyword 'template'
487 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000488 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000489 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000490 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000491
492 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000493 << II.getName()
494 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
495
Douglas Gregorbb119652010-06-16 23:00:59 +0000496 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000497 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000498 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000499 TemplateName, ObjectType,
500 EnteringContext, Template)) {
501 // Consume the identifier.
502 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000503 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
504 TemplateName, false))
505 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000506 }
507 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000508 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000509
Douglas Gregor20c38a72010-05-21 23:43:39 +0000510 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000511 }
512 }
513
Douglas Gregor7f741122009-02-25 19:37:18 +0000514 // We don't have any tokens that form the beginning of a
515 // nested-name-specifier, so we're done.
516 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Douglas Gregore610ada2010-02-24 18:44:31 +0000519 // Even if we didn't see any pieces of a nested-name-specifier, we
520 // still check whether there is a tilde in this position, which
521 // indicates a potential pseudo-destructor.
522 if (CheckForDestructor && Tok.is(tok::tilde))
523 *MayBePseudoDestructor = true;
524
John McCall1f476a12010-02-26 08:45:28 +0000525 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000526}
527
528/// ParseCXXIdExpression - Handle id-expression.
529///
530/// id-expression:
531/// unqualified-id
532/// qualified-id
533///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000534/// qualified-id:
535/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
536/// '::' identifier
537/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000538/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000539///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000540/// NOTE: The standard specifies that, for qualified-id, the parser does not
541/// expect:
542///
543/// '::' conversion-function-id
544/// '::' '~' class-name
545///
546/// This may cause a slight inconsistency on diagnostics:
547///
548/// class C {};
549/// namespace A {}
550/// void f() {
551/// :: A :: ~ C(); // Some Sema error about using destructor with a
552/// // namespace.
553/// :: ~ C(); // Some Parser error like 'unexpected ~'.
554/// }
555///
556/// We simplify the parser a bit and make it work like:
557///
558/// qualified-id:
559/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
560/// '::' unqualified-id
561///
562/// That way Sema can handle and report similar errors for namespaces and the
563/// global scope.
564///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000565/// The isAddressOfOperand parameter indicates that this id-expression is a
566/// direct operand of the address-of operator. This is, besides member contexts,
567/// the only place where a qualified-id naming a non-static class member may
568/// appear.
569///
John McCalldadc5752010-08-24 06:29:42 +0000570ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000571 // qualified-id:
572 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
573 // '::' unqualified-id
574 //
575 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000576 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000577
578 SourceLocation TemplateKWLoc;
Douglas Gregora121b752009-11-03 16:56:39 +0000579 UnqualifiedId Name;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000580 if (ParseUnqualifiedId(SS,
581 /*EnteringContext=*/false,
582 /*AllowDestructorName=*/false,
583 /*AllowConstructorName=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000584 /*ObjectType=*/ ParsedType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000585 TemplateKWLoc,
Douglas Gregora121b752009-11-03 16:56:39 +0000586 Name))
587 return ExprError();
John McCalla9ee3252009-11-22 02:49:43 +0000588
589 // This is only the direct operand of an & operator if it is not
590 // followed by a postfix-expression suffix.
John McCall8d08b9b2010-08-27 09:08:28 +0000591 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
592 isAddressOfOperand = false;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000593
594 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
595 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000596}
597
Richard Smith21b3ab42013-05-09 21:36:41 +0000598/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000599///
600/// lambda-expression:
601/// lambda-introducer lambda-declarator[opt] compound-statement
602///
603/// lambda-introducer:
604/// '[' lambda-capture[opt] ']'
605///
606/// lambda-capture:
607/// capture-default
608/// capture-list
609/// capture-default ',' capture-list
610///
611/// capture-default:
612/// '&'
613/// '='
614///
615/// capture-list:
616/// capture
617/// capture-list ',' capture
618///
619/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000620/// simple-capture
621/// init-capture [C++1y]
622///
623/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000624/// identifier
625/// '&' identifier
626/// 'this'
627///
Richard Smith21b3ab42013-05-09 21:36:41 +0000628/// init-capture: [C++1y]
629/// identifier initializer
630/// '&' identifier initializer
631///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000632/// lambda-declarator:
633/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
634/// 'mutable'[opt] exception-specification[opt]
635/// trailing-return-type[opt]
636///
637ExprResult Parser::ParseLambdaExpression() {
638 // Parse lambda-introducer.
639 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000640 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000641 if (DiagID) {
642 Diag(Tok, DiagID.getValue());
Alexey Bataevee6507d2013-11-18 08:17:37 +0000643 SkipUntil(tok::r_square, StopAtSemi);
644 SkipUntil(tok::l_brace, StopAtSemi);
645 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000646 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000647 }
648
649 return ParseLambdaExpressionAfterIntroducer(Intro);
650}
651
652/// TryParseLambdaExpression - Use lookahead and potentially tentative
653/// parsing to determine if we are looking at a C++0x lambda expression, and parse
654/// it if we are.
655///
656/// If we are not looking at a lambda expression, returns ExprError().
657ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000658 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000659 && Tok.is(tok::l_square)
660 && "Not at the start of a possible lambda expression.");
661
662 const Token Next = NextToken(), After = GetLookAheadToken(2);
663
664 // If lookahead indicates this is a lambda...
665 if (Next.is(tok::r_square) || // []
666 Next.is(tok::equal) || // [=
667 (Next.is(tok::amp) && // [&] or [&,
668 (After.is(tok::r_square) ||
669 After.is(tok::comma))) ||
670 (Next.is(tok::identifier) && // [identifier]
671 After.is(tok::r_square))) {
672 return ParseLambdaExpression();
673 }
674
Eli Friedmanc7c97142012-01-04 02:40:39 +0000675 // If lookahead indicates an ObjC message send...
676 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000677 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000678 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000679 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000680
Eli Friedmanc7c97142012-01-04 02:40:39 +0000681 // Here, we're stuck: lambda introducers and Objective-C message sends are
682 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
683 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
684 // writing two routines to parse a lambda introducer, just try to parse
685 // a lambda introducer first, and fall back if that fails.
686 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000687 LambdaIntroducer Intro;
688 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000689 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000690
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000691 return ParseLambdaExpressionAfterIntroducer(Intro);
692}
693
Richard Smithf44d2a82013-05-21 22:21:19 +0000694/// \brief Parse a lambda introducer.
695/// \param Intro A LambdaIntroducer filled in with information about the
696/// contents of the lambda-introducer.
697/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
698/// message send and a lambda expression. In this mode, we will
699/// sometimes skip the initializers for init-captures and not fully
700/// populate \p Intro. This flag will be set to \c true if we do so.
701/// \return A DiagnosticID if it hit something unexpected. The location for
702/// for the diagnostic is that of the current token.
703Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
704 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000705 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000706
707 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000708 BalancedDelimiterTracker T(*this, tok::l_square);
709 T.consumeOpen();
710
711 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000712
713 bool first = true;
714
715 // Parse capture-default.
716 if (Tok.is(tok::amp) &&
717 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
718 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000719 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000720 first = false;
721 } else if (Tok.is(tok::equal)) {
722 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000723 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000724 first = false;
725 }
726
727 while (Tok.isNot(tok::r_square)) {
728 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000729 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000730 // Provide a completion for a lambda introducer here. Except
731 // in Objective-C, where this is Almost Surely meant to be a message
732 // send. In that case, fail here and let the ObjC message
733 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000734 if (Tok.is(tok::code_completion) &&
735 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
736 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000737 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
738 /*AfterAmpersand=*/false);
739 ConsumeCodeCompletionToken();
740 break;
741 }
742
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000743 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000744 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745 ConsumeToken();
746 }
747
Douglas Gregord8c61782012-02-15 15:34:24 +0000748 if (Tok.is(tok::code_completion)) {
749 // If we're in Objective-C++ and we have a bare '[', then this is more
750 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000751 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000752 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
753 else
754 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
755 /*AfterAmpersand=*/false);
756 ConsumeCodeCompletionToken();
757 break;
758 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000759
Douglas Gregord8c61782012-02-15 15:34:24 +0000760 first = false;
761
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000762 // Parse capture.
763 LambdaCaptureKind Kind = LCK_ByCopy;
764 SourceLocation Loc;
765 IdentifierInfo* Id = 0;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000766 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000767 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000768
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000769 if (Tok.is(tok::kw_this)) {
770 Kind = LCK_This;
771 Loc = ConsumeToken();
772 } else {
773 if (Tok.is(tok::amp)) {
774 Kind = LCK_ByRef;
775 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000776
777 if (Tok.is(tok::code_completion)) {
778 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
779 /*AfterAmpersand=*/true);
780 ConsumeCodeCompletionToken();
781 break;
782 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000783 }
784
785 if (Tok.is(tok::identifier)) {
786 Id = Tok.getIdentifierInfo();
787 Loc = ConsumeToken();
788 } else if (Tok.is(tok::kw_this)) {
789 // FIXME: If we want to suggest a fixit here, will need to return more
790 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
791 // Clear()ed to prevent emission in case of tentative parsing?
792 return DiagResult(diag::err_this_captured_by_reference);
793 } else {
794 return DiagResult(diag::err_expected_capture);
795 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000796
797 if (Tok.is(tok::l_paren)) {
798 BalancedDelimiterTracker Parens(*this, tok::l_paren);
799 Parens.consumeOpen();
800
801 ExprVector Exprs;
802 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000803 if (SkippedInits) {
804 Parens.skipToEnd();
805 *SkippedInits = true;
806 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000807 Parens.skipToEnd();
808 Init = ExprError();
809 } else {
810 Parens.consumeClose();
811 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
812 Parens.getCloseLocation(),
813 Exprs);
814 }
815 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000816 // Each lambda init-capture forms its own full expression, which clears
817 // Actions.MaybeODRUseExprs. So create an expression evaluation context
818 // to save the necessary state, and restore it later.
819 EnterExpressionEvaluationContext EC(Actions,
820 Sema::PotentiallyEvaluated);
Richard Smith21b3ab42013-05-09 21:36:41 +0000821 if (Tok.is(tok::equal))
822 ConsumeToken();
823
Richard Smithf44d2a82013-05-21 22:21:19 +0000824 if (!SkippedInits)
825 Init = ParseInitializer();
826 else if (Tok.is(tok::l_brace)) {
827 BalancedDelimiterTracker Braces(*this, tok::l_brace);
828 Braces.consumeOpen();
829 Braces.skipToEnd();
830 *SkippedInits = true;
831 } else {
832 // We're disambiguating this:
833 //
834 // [..., x = expr
835 //
836 // We need to find the end of the following expression in order to
837 // determine whether this is an Obj-C message send's receiver, or a
838 // lambda init-capture.
839 //
840 // Parse the expression to find where it ends, and annotate it back
841 // onto the tokens. We would have parsed this expression the same way
842 // in either case: both the RHS of an init-capture and the RHS of an
843 // assignment expression are parsed as an initializer-clause, and in
844 // neither case can anything be added to the scope between the '[' and
845 // here.
846 //
847 // FIXME: This is horrible. Adding a mechanism to skip an expression
848 // would be much cleaner.
849 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
850 // that instead. (And if we see a ':' with no matching '?', we can
851 // classify this as an Obj-C message send.)
852 SourceLocation StartLoc = Tok.getLocation();
853 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
854 Init = ParseInitializer();
855
856 if (Tok.getLocation() != StartLoc) {
857 // Back out the lexing of the token after the initializer.
858 PP.RevertCachedTokens(1);
859
860 // Replace the consumed tokens with an appropriate annotation.
861 Tok.setLocation(StartLoc);
862 Tok.setKind(tok::annot_primary_expr);
863 setExprAnnotation(Tok, Init);
864 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
865 PP.AnnotateCachedTokens(Tok);
866
867 // Consume the annotated initializer.
868 ConsumeToken();
869 }
870 }
Richard Smithba71c082013-05-16 06:20:58 +0000871 } else if (Tok.is(tok::ellipsis))
872 EllipsisLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000873 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000874 // If this is an init capture, process the initialization expression
875 // right away. For lambda init-captures such as the following:
876 // const int x = 10;
877 // auto L = [i = x+1](int a) {
878 // return [j = x+2,
879 // &k = x](char b) { };
880 // };
881 // keep in mind that each lambda init-capture has to have:
882 // - its initialization expression executed in the context
883 // of the enclosing/parent decl-context.
884 // - but the variable itself has to be 'injected' into the
885 // decl-context of its lambda's call-operator (which has
886 // not yet been created).
887 // Each init-expression is a full-expression that has to get
888 // Sema-analyzed (for capturing etc.) before its lambda's
889 // call-operator's decl-context, scope & scopeinfo are pushed on their
890 // respective stacks. Thus if any variable is odr-used in the init-capture
891 // it will correctly get captured in the enclosing lambda, if one exists.
892 // The init-variables above are created later once the lambdascope and
893 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000894
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000895 // Since the lambda init-capture's initializer expression occurs in the
896 // context of the enclosing function or lambda, therefore we can not wait
897 // till a lambda scope has been pushed on before deciding whether the
898 // variable needs to be captured. We also need to process all
899 // lvalue-to-rvalue conversions and discarded-value conversions,
900 // so that we can avoid capturing certain constant variables.
901 // For e.g.,
902 // void test() {
903 // const int x = 10;
904 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
905 // return [y = x](int i) { <-- don't capture by enclosing lambda
906 // return y;
907 // }
908 // };
909 // If x was not const, the second use would require 'L' to capture, and
910 // that would be an error.
911
912 ParsedType InitCaptureParsedType;
913 if (Init.isUsable()) {
914 // Get the pointer and store it in an lvalue, so we can use it as an
915 // out argument.
916 Expr *InitExpr = Init.get();
917 // This performs any lvalue-to-rvalue conversions if necessary, which
918 // can affect what gets captured in the containing decl-context.
919 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
920 Loc, Kind == LCK_ByRef, Id, InitExpr);
921 Init = InitExpr;
922 InitCaptureParsedType.set(InitCaptureType);
923 }
924 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000925 }
926
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000927 T.consumeClose();
928 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000929 return DiagResult();
930}
931
Douglas Gregord8c61782012-02-15 15:34:24 +0000932/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000933///
934/// Returns true if it hit something unexpected.
935bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
936 TentativeParsingAction PA(*this);
937
Richard Smithf44d2a82013-05-21 22:21:19 +0000938 bool SkippedInits = false;
939 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000940
941 if (DiagID) {
942 PA.Revert();
943 return true;
944 }
945
Richard Smithf44d2a82013-05-21 22:21:19 +0000946 if (SkippedInits) {
947 // Parse it again, but this time parse the init-captures too.
948 PA.Revert();
949 Intro = LambdaIntroducer();
950 DiagID = ParseLambdaIntroducer(Intro);
951 assert(!DiagID && "parsing lambda-introducer failed on reparse");
952 return false;
953 }
954
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000955 PA.Commit();
956 return false;
957}
958
959/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
960/// expression.
961ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
962 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000963 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
964 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
965
966 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
967 "lambda expression parsing");
968
Faisal Vali2b391ab2013-09-26 19:54:12 +0000969
970
Richard Smith21b3ab42013-05-09 21:36:41 +0000971 // FIXME: Call into Actions to add any init-capture declarations to the
972 // scope while parsing the lambda-declarator and compound-statement.
973
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000974 // Parse lambda-declarator[opt].
975 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +0000976 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000977 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
978 Actions.PushLambdaScope();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000979
980 if (Tok.is(tok::l_paren)) {
981 ParseScope PrototypeScope(this,
982 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +0000983 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000984 Scope::DeclScope);
985
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000986 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000987 BalancedDelimiterTracker T(*this, tok::l_paren);
988 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000989 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000990
991 // Parse parameter-declaration-clause.
992 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000993 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000994 SourceLocation EllipsisLoc;
995
Faisal Vali2b391ab2013-09-26 19:54:12 +0000996
997 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000998 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000999 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001000 // For a generic lambda, each 'auto' within the parameter declaration
1001 // clause creates a template type parameter, so increment the depth.
1002 if (Actions.getCurGenericLambda())
1003 ++CurTemplateDepthTracker;
1004 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001005 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001006 SourceLocation RParenLoc = T.getCloseLocation();
1007 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001008
1009 // Parse 'mutable'[opt].
1010 SourceLocation MutableLoc;
1011 if (Tok.is(tok::kw_mutable)) {
1012 MutableLoc = ConsumeToken();
1013 DeclEndLoc = MutableLoc;
1014 }
1015
1016 // Parse exception-specification[opt].
1017 ExceptionSpecificationType ESpecType = EST_None;
1018 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001019 SmallVector<ParsedType, 2> DynamicExceptions;
1020 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001021 ExprResult NoexceptExpr;
Richard Smith2331bbf2012-05-02 22:22:32 +00001022 ESpecType = tryParseExceptionSpecification(ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001023 DynamicExceptions,
1024 DynamicExceptionRanges,
Richard Smith2331bbf2012-05-02 22:22:32 +00001025 NoexceptExpr);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001026
1027 if (ESpecType != EST_None)
1028 DeclEndLoc = ESpecRange.getEnd();
1029
1030 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001031 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001032
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001033 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1034
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001035 // Parse trailing-return-type[opt].
Richard Smith700537c2012-06-12 01:51:59 +00001036 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001037 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001038 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001039 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001040 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001041 if (Range.getEnd().isValid())
1042 DeclEndLoc = Range.getEnd();
1043 }
1044
1045 PrototypeScope.Exit();
1046
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001047 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001048 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001049 /*isAmbiguous=*/false,
1050 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001051 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001052 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001053 DS.getTypeQualifiers(),
1054 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001055 /*RefQualifierLoc=*/NoLoc,
1056 /*ConstQualifierLoc=*/NoLoc,
1057 /*VolatileQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001058 MutableLoc,
1059 ESpecType, ESpecRange.getBegin(),
1060 DynamicExceptions.data(),
1061 DynamicExceptionRanges.data(),
1062 DynamicExceptions.size(),
1063 NoexceptExpr.isUsable() ?
1064 NoexceptExpr.get() : 0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001065 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001066 TrailingReturnType),
1067 Attr, DeclEndLoc);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001068 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
1069 // It's common to forget that one needs '()' before 'mutable' or the
1070 // result type. Deal with this.
1071 Diag(Tok, diag::err_lambda_missing_parens)
1072 << Tok.is(tok::arrow)
1073 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1074 SourceLocation DeclLoc = Tok.getLocation();
1075 SourceLocation DeclEndLoc = DeclLoc;
1076
1077 // Parse 'mutable', if it's there.
1078 SourceLocation MutableLoc;
1079 if (Tok.is(tok::kw_mutable)) {
1080 MutableLoc = ConsumeToken();
1081 DeclEndLoc = MutableLoc;
1082 }
1083
1084 // Parse the return type, if there is one.
Richard Smith700537c2012-06-12 01:51:59 +00001085 TypeResult TrailingReturnType;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001086 if (Tok.is(tok::arrow)) {
1087 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001088 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001089 if (Range.getEnd().isValid())
1090 DeclEndLoc = Range.getEnd();
1091 }
1092
1093 ParsedAttributes Attr(AttrFactory);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001094 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001095 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001096 /*isAmbiguous=*/false,
1097 /*LParenLoc=*/NoLoc,
1098 /*Params=*/0,
1099 /*NumParams=*/0,
1100 /*EllipsisLoc=*/NoLoc,
1101 /*RParenLoc=*/NoLoc,
1102 /*TypeQuals=*/0,
1103 /*RefQualifierIsLValueRef=*/true,
1104 /*RefQualifierLoc=*/NoLoc,
1105 /*ConstQualifierLoc=*/NoLoc,
1106 /*VolatileQualifierLoc=*/NoLoc,
1107 MutableLoc,
1108 EST_None,
1109 /*ESpecLoc=*/NoLoc,
1110 /*Exceptions=*/0,
1111 /*ExceptionRanges=*/0,
1112 /*NumExceptions=*/0,
1113 /*NoexceptExpr=*/0,
1114 DeclLoc, DeclEndLoc, D,
1115 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001116 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001117 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001118
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001119
Eli Friedman4817cf72012-01-06 03:05:34 +00001120 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1121 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001122 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001123 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001124
Eli Friedman71c80552012-01-05 03:35:19 +00001125 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1126
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001127 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001128 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001129 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001130 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1131 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001132 }
1133
Eli Friedmanc7c97142012-01-04 02:40:39 +00001134 StmtResult Stmt(ParseCompoundStatementBody());
1135 BodyScope.Exit();
1136
Eli Friedman898caf82012-01-04 02:46:53 +00001137 if (!Stmt.isInvalid())
Douglas Gregor63798542012-02-20 19:44:39 +00001138 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
Eli Friedmanc7c97142012-01-04 02:40:39 +00001139
Eli Friedman898caf82012-01-04 02:46:53 +00001140 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1141 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001142}
1143
Chris Lattner29375652006-12-04 18:06:35 +00001144/// ParseCXXCasts - This handles the various ways to cast expressions to another
1145/// type.
1146///
1147/// postfix-expression: [C++ 5.2p1]
1148/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1149/// 'static_cast' '<' type-name '>' '(' expression ')'
1150/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1151/// 'const_cast' '<' type-name '>' '(' expression ')'
1152///
John McCalldadc5752010-08-24 06:29:42 +00001153ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001154 tok::TokenKind Kind = Tok.getKind();
1155 const char *CastName = 0; // For error messages
1156
1157 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001158 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001159 case tok::kw_const_cast: CastName = "const_cast"; break;
1160 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1161 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1162 case tok::kw_static_cast: CastName = "static_cast"; break;
1163 }
1164
1165 SourceLocation OpLoc = ConsumeToken();
1166 SourceLocation LAngleBracketLoc = Tok.getLocation();
1167
Richard Smith55858492011-04-14 21:45:45 +00001168 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1169 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001170 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1171 Token Next = NextToken();
1172 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1173 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1174 }
Richard Smith55858492011-04-14 21:45:45 +00001175
Chris Lattner29375652006-12-04 18:06:35 +00001176 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001177 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001178
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001179 // Parse the common declaration-specifiers piece.
1180 DeclSpec DS(AttrFactory);
1181 ParseSpecifierQualifierList(DS);
1182
1183 // Parse the abstract-declarator, if present.
1184 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1185 ParseDeclarator(DeclaratorInfo);
1186
Chris Lattner29375652006-12-04 18:06:35 +00001187 SourceLocation RAngleBracketLoc = Tok.getLocation();
1188
Chris Lattner6d29c102008-11-18 07:48:38 +00001189 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redld65cea82008-12-11 22:51:44 +00001190 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Chris Lattner29375652006-12-04 18:06:35 +00001191
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001192 SourceLocation LParenLoc, RParenLoc;
1193 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001194
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001195 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001196 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001197
John McCalldadc5752010-08-24 06:29:42 +00001198 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001199
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001200 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001201 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001202
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001203 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001204 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001205 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001206 RAngleBracketLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001207 T.getOpenLocation(), Result.take(),
1208 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001209
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001210 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001211}
Bill Wendling4073ed52007-02-13 01:51:42 +00001212
Sebastian Redlc4704762008-11-11 11:37:55 +00001213/// ParseCXXTypeid - This handles the C++ typeid expression.
1214///
1215/// postfix-expression: [C++ 5.2p1]
1216/// 'typeid' '(' expression ')'
1217/// 'typeid' '(' type-id ')'
1218///
John McCalldadc5752010-08-24 06:29:42 +00001219ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001220 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1221
1222 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001223 SourceLocation LParenLoc, RParenLoc;
1224 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001225
1226 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001227 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001228 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001229 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001230
John McCalldadc5752010-08-24 06:29:42 +00001231 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001232
Richard Smith4f605af2012-08-18 00:55:03 +00001233 // C++0x [expr.typeid]p3:
1234 // When typeid is applied to an expression other than an lvalue of a
1235 // polymorphic class type [...] The expression is an unevaluated
1236 // operand (Clause 5).
1237 //
1238 // Note that we can't tell whether the expression is an lvalue of a
1239 // polymorphic class type until after we've parsed the expression; we
1240 // speculatively assume the subexpression is unevaluated, and fix it up
1241 // later.
1242 //
1243 // We enter the unevaluated context before trying to determine whether we
1244 // have a type-id, because the tentative parse logic will try to resolve
1245 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001246 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1247 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001248
Sebastian Redlc4704762008-11-11 11:37:55 +00001249 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001250 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001251
1252 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001253 T.consumeClose();
1254 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001255 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001256 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001257
1258 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001259 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001260 } else {
1261 Result = ParseExpression();
1262
1263 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001264 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001265 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001266 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001267 T.consumeClose();
1268 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001269 if (RParenLoc.isInvalid())
1270 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001271
Sebastian Redlc4704762008-11-11 11:37:55 +00001272 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001273 Result.release(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001274 }
1275 }
1276
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001277 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001278}
1279
Francois Pichet9f4f2072010-09-08 12:20:18 +00001280/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1281///
1282/// '__uuidof' '(' expression ')'
1283/// '__uuidof' '(' type-id ')'
1284///
1285ExprResult Parser::ParseCXXUuidof() {
1286 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1287
1288 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001289 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001290
1291 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001292 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001293 return ExprError();
1294
1295 ExprResult Result;
1296
1297 if (isTypeIdInParens()) {
1298 TypeResult Ty = ParseTypeName();
1299
1300 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001301 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001302
1303 if (Ty.isInvalid())
1304 return ExprError();
1305
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001306 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1307 Ty.get().getAsOpaquePtr(),
1308 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001309 } else {
1310 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1311 Result = ParseExpression();
1312
1313 // Match the ')'.
1314 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001315 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001316 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001317 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001318
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001319 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1320 /*isType=*/false,
1321 Result.release(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001322 }
1323 }
1324
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001325 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001326}
1327
Douglas Gregore610ada2010-02-24 18:44:31 +00001328/// \brief Parse a C++ pseudo-destructor expression after the base,
1329/// . or -> operator, and nested-name-specifier have already been
1330/// parsed.
1331///
1332/// postfix-expression: [C++ 5.2]
1333/// postfix-expression . pseudo-destructor-name
1334/// postfix-expression -> pseudo-destructor-name
1335///
1336/// pseudo-destructor-name:
1337/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1338/// ::[opt] nested-name-specifier template simple-template-id ::
1339/// ~type-name
1340/// ::[opt] nested-name-specifier[opt] ~type-name
1341///
John McCalldadc5752010-08-24 06:29:42 +00001342ExprResult
Douglas Gregore610ada2010-02-24 18:44:31 +00001343Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1344 tok::TokenKind OpKind,
1345 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001346 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001347 // We're parsing either a pseudo-destructor-name or a dependent
1348 // member access that has the same form as a
1349 // pseudo-destructor-name. We parse both in the same way and let
1350 // the action model sort them out.
1351 //
1352 // Note that the ::[opt] nested-name-specifier[opt] has already
1353 // been parsed, and if there was a simple-template-id, it has
1354 // been coalesced into a template-id annotation token.
1355 UnqualifiedId FirstTypeName;
1356 SourceLocation CCLoc;
1357 if (Tok.is(tok::identifier)) {
1358 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1359 ConsumeToken();
1360 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1361 CCLoc = ConsumeToken();
1362 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001363 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1364 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001365 FirstTypeName.setTemplateId(
1366 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1367 ConsumeToken();
1368 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1369 CCLoc = ConsumeToken();
1370 } else {
1371 FirstTypeName.setIdentifier(0, SourceLocation());
1372 }
1373
1374 // Parse the tilde.
1375 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1376 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001377
1378 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1379 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001380 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001381 if (DS.getTypeSpecType() == TST_error)
1382 return ExprError();
1383 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1384 OpKind, TildeLoc, DS,
1385 Tok.is(tok::l_paren));
1386 }
1387
Douglas Gregore610ada2010-02-24 18:44:31 +00001388 if (!Tok.is(tok::identifier)) {
1389 Diag(Tok, diag::err_destructor_tilde_identifier);
1390 return ExprError();
1391 }
1392
1393 // Parse the second type.
1394 UnqualifiedId SecondTypeName;
1395 IdentifierInfo *Name = Tok.getIdentifierInfo();
1396 SourceLocation NameLoc = ConsumeToken();
1397 SecondTypeName.setIdentifier(Name, NameLoc);
1398
1399 // If there is a '<', the second type name is a template-id. Parse
1400 // it as such.
1401 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001402 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1403 Name, NameLoc,
1404 false, ObjectType, SecondTypeName,
1405 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001406 return ExprError();
1407
John McCallb268a282010-08-23 23:25:46 +00001408 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1409 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001410 SS, FirstTypeName, CCLoc,
1411 TildeLoc, SecondTypeName,
1412 Tok.is(tok::l_paren));
1413}
1414
Bill Wendling4073ed52007-02-13 01:51:42 +00001415/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1416///
1417/// boolean-literal: [C++ 2.13.5]
1418/// 'true'
1419/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001420ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001421 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001422 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001423}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001424
1425/// ParseThrowExpression - This handles the C++ throw expression.
1426///
1427/// throw-expression: [C++ 15]
1428/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001429ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001430 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001431 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001432
Chris Lattner65dd8432008-04-06 06:02:23 +00001433 // If the current token isn't the start of an assignment-expression,
1434 // then the expression is not present. This handles things like:
1435 // "C ? throw : (void)42", which is crazy but legal.
1436 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1437 case tok::semi:
1438 case tok::r_paren:
1439 case tok::r_square:
1440 case tok::r_brace:
1441 case tok::colon:
1442 case tok::comma:
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001443 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001444
Chris Lattner65dd8432008-04-06 06:02:23 +00001445 default:
John McCalldadc5752010-08-24 06:29:42 +00001446 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001447 if (Expr.isInvalid()) return Expr;
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001448 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner65dd8432008-04-06 06:02:23 +00001449 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001450}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001451
1452/// ParseCXXThis - This handles the C++ 'this' pointer.
1453///
1454/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1455/// a non-lvalue expression whose value is the address of the object for which
1456/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001457ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001458 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1459 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001460 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001461}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001462
1463/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1464/// Can be interpreted either as function-style casting ("int(x)")
1465/// or class type construction ("ClassType(x,y,z)")
1466/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001467/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001468///
1469/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001470/// simple-type-specifier '(' expression-list[opt] ')'
1471/// [C++0x] simple-type-specifier braced-init-list
1472/// typename-specifier '(' expression-list[opt] ')'
1473/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001474///
John McCalldadc5752010-08-24 06:29:42 +00001475ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001476Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001477 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001478 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001479
Sebastian Redl3da34892011-06-05 12:23:16 +00001480 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001481 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001482 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001483
Sebastian Redl3da34892011-06-05 12:23:16 +00001484 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001485 ExprResult Init = ParseBraceInitializer();
1486 if (Init.isInvalid())
1487 return Init;
1488 Expr *InitList = Init.take();
1489 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1490 MultiExprArg(&InitList, 1),
1491 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001492 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001493 BalancedDelimiterTracker T(*this, tok::l_paren);
1494 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001495
Benjamin Kramerf0623432012-08-23 22:51:59 +00001496 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001497 CommaLocsTy CommaLocs;
1498
1499 if (Tok.isNot(tok::r_paren)) {
1500 if (ParseExpressionList(Exprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001501 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001502 return ExprError();
1503 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001504 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001505
1506 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001507 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001508
1509 // TypeRep could be null, if it references an invalid typedef.
1510 if (!TypeRep)
1511 return ExprError();
1512
1513 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1514 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001515 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001516 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001517 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001518 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001519}
1520
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001521/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001522///
1523/// condition:
1524/// expression
1525/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001526/// [C++11] type-specifier-seq declarator '=' initializer-clause
1527/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001528/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1529/// '=' assignment-expression
1530///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001531/// \param ExprOut if the condition was parsed as an expression, the parsed
1532/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001533///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001534/// \param DeclOut if the condition was parsed as a declaration, the parsed
1535/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001536///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001537/// \param Loc The location of the start of the statement that requires this
1538/// condition, e.g., the "for" in a for loop.
1539///
1540/// \param ConvertToBoolean Whether the condition expression should be
1541/// converted to a boolean value.
1542///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001543/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001544bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1545 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001546 SourceLocation Loc,
1547 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001548 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001549 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001550 cutOffParsing();
1551 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001552 }
1553
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001554 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001555 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001556
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001557 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001558 ProhibitAttributes(attrs);
1559
Douglas Gregore60e41a2010-05-06 17:25:47 +00001560 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001561 ExprOut = ParseExpression(); // expression
1562 DeclOut = 0;
1563 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001564 return true;
1565
1566 // If required, convert to a boolean value.
1567 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001568 ExprOut
1569 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1570 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001571 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001572
1573 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001574 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001575 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001576 ParseSpecifierQualifierList(DS);
1577
1578 // declarator
1579 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1580 ParseDeclarator(DeclaratorInfo);
1581
1582 // simple-asm-expr[opt]
1583 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001584 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001585 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001586 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001587 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001588 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001589 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001590 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001591 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001592 }
1593
1594 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001595 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001596
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001597 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001598 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001599 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001600 DeclOut = Dcl.get();
1601 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001602
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001603 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001604 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001605 bool CopyInitialization = isTokenEqualOrEqualTypo();
1606 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001607 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001608
1609 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001610 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001611 Diag(Tok.getLocation(),
1612 diag::warn_cxx98_compat_generalized_initializer_lists);
1613 InitExpr = ParseBraceInitializer();
1614 } else if (CopyInitialization) {
1615 InitExpr = ParseAssignmentExpression();
1616 } else if (Tok.is(tok::l_paren)) {
1617 // This was probably an attempt to initialize the variable.
1618 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001619 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001620 RParen = ConsumeParen();
1621 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1622 diag::err_expected_init_in_condition_lparen)
1623 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001624 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001625 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1626 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001627 }
Richard Smith2a15b742012-02-22 06:49:09 +00001628
1629 if (!InitExpr.isInvalid())
1630 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001631 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001632 else
1633 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001634
Douglas Gregore60e41a2010-05-06 17:25:47 +00001635 // FIXME: Build a reference to this declaration? Convert it to bool?
1636 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001637
1638 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001639
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001640 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001641}
1642
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001643/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1644/// This should only be called when the current token is known to be part of
1645/// simple-type-specifier.
1646///
1647/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001648/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001649/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1650/// char
1651/// wchar_t
1652/// bool
1653/// short
1654/// int
1655/// long
1656/// signed
1657/// unsigned
1658/// float
1659/// double
1660/// void
1661/// [GNU] typeof-specifier
1662/// [C++0x] auto [TODO]
1663///
1664/// type-name:
1665/// class-name
1666/// enum-name
1667/// typedef-name
1668///
1669void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1670 DS.SetRangeStart(Tok.getLocation());
1671 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001672 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001673 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001674
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001675 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001676 case tok::identifier: // foo::bar
1677 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001678 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001679 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001680 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001681
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001682 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001683 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001684 if (getTypeAnnotation(Tok))
1685 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1686 getTypeAnnotation(Tok));
1687 else
1688 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001689
1690 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1691 ConsumeToken();
1692
1693 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1694 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1695 // Objective-C interface. If we don't have Objective-C or a '<', this is
1696 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001697 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001698 ParseObjCProtocolQualifiers(DS);
1699
1700 DS.Finish(Diags, PP);
1701 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001702 }
Mike Stump11289f42009-09-09 15:08:12 +00001703
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001704 // builtin types
1705 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00001706 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001707 break;
1708 case tok::kw_long:
John McCall49bfce42009-08-03 20:12:06 +00001709 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001710 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001711 case tok::kw___int64:
1712 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1713 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001714 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001715 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001716 break;
1717 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001718 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001719 break;
1720 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00001721 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001722 break;
1723 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00001724 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001725 break;
1726 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00001727 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001728 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001729 case tok::kw___int128:
1730 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1731 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001732 case tok::kw_half:
1733 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1734 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001735 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00001736 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001737 break;
1738 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00001739 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001740 break;
1741 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00001742 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001743 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001744 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00001745 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001746 break;
1747 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00001748 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001749 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001750 case tok::kw_bool:
John McCall49bfce42009-08-03 20:12:06 +00001751 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001752 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001753 case tok::annot_decltype:
1754 case tok::kw_decltype:
1755 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1756 return DS.Finish(Diags, PP);
Mike Stump11289f42009-09-09 15:08:12 +00001757
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001758 // GNU typeof support.
1759 case tok::kw_typeof:
1760 ParseTypeofSpecifier(DS);
Douglas Gregore3e01a22009-04-01 22:41:11 +00001761 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001762 return;
1763 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001764 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001765 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1766 else
1767 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001768 ConsumeToken();
Douglas Gregore3e01a22009-04-01 22:41:11 +00001769 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001770}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001771
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001772/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1773/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1774/// e.g., "const short int". Note that the DeclSpec is *not* finished
1775/// by parsing the type-specifier-seq, because these sequences are
1776/// typically followed by some form of declarator. Returns true and
1777/// emits diagnostics if this is not a type-specifier-seq, false
1778/// otherwise.
1779///
1780/// type-specifier-seq: [C++ 8.1]
1781/// type-specifier type-specifier-seq[opt]
1782///
1783bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001784 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Douglas Gregor40d732f2010-02-24 23:13:13 +00001785 DS.Finish(Diags, PP);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001786 return false;
1787}
1788
Douglas Gregor7861a802009-11-03 01:35:08 +00001789/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1790/// some form.
1791///
1792/// This routine is invoked when a '<' is encountered after an identifier or
1793/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1794/// whether the unqualified-id is actually a template-id. This routine will
1795/// then parse the template arguments and form the appropriate template-id to
1796/// return to the caller.
1797///
1798/// \param SS the nested-name-specifier that precedes this template-id, if
1799/// we're actually parsing a qualified-id.
1800///
1801/// \param Name for constructor and destructor names, this is the actual
1802/// identifier that may be a template-name.
1803///
1804/// \param NameLoc the location of the class-name in a constructor or
1805/// destructor.
1806///
1807/// \param EnteringContext whether we're entering the scope of the
1808/// nested-name-specifier.
1809///
Douglas Gregor127ea592009-11-03 21:24:04 +00001810/// \param ObjectType if this unqualified-id occurs within a member access
1811/// expression, the type of the base object whose member is being accessed.
1812///
Douglas Gregor7861a802009-11-03 01:35:08 +00001813/// \param Id as input, describes the template-name or operator-function-id
1814/// that precedes the '<'. If template arguments were parsed successfully,
1815/// will be updated with the template-id.
1816///
Douglas Gregore610ada2010-02-24 18:44:31 +00001817/// \param AssumeTemplateId When true, this routine will assume that the name
1818/// refers to a template without performing name lookup to verify.
1819///
Douglas Gregor7861a802009-11-03 01:35:08 +00001820/// \returns true if a parse error occurred, false otherwise.
1821bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001822 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001823 IdentifierInfo *Name,
1824 SourceLocation NameLoc,
1825 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001826 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001827 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001828 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001829 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1830 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001831
1832 TemplateTy Template;
1833 TemplateNameKind TNK = TNK_Non_template;
1834 switch (Id.getKind()) {
1835 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001836 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001837 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001838 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001839 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001840 Id, ObjectType, EnteringContext,
1841 Template);
1842 if (TNK == TNK_Non_template)
1843 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001844 } else {
1845 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001846 TNK = Actions.isTemplateName(getCurScope(), SS,
1847 TemplateKWLoc.isValid(), Id,
1848 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001849 MemberOfUnknownSpecialization);
1850
1851 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1852 ObjectType && IsTemplateArgumentList()) {
1853 // We have something like t->getAs<T>(), where getAs is a
1854 // member of an unknown specialization. However, this will only
1855 // parse correctly as a template, so suggest the keyword 'template'
1856 // before 'getAs' and treat this as a dependent template name.
1857 std::string Name;
1858 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1859 Name = Id.Identifier->getName();
1860 else {
1861 Name = "operator ";
1862 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1863 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1864 else
1865 Name += Id.Identifier->getName();
1866 }
1867 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1868 << Name
1869 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001870 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1871 SS, TemplateKWLoc, Id,
1872 ObjectType, EnteringContext,
1873 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001874 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001875 return true;
1876 }
1877 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001878 break;
1879
Douglas Gregor3cf81312009-11-03 23:16:33 +00001880 case UnqualifiedId::IK_ConstructorName: {
1881 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001882 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001883 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001884 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1885 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001886 EnteringContext, Template,
1887 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001888 break;
1889 }
1890
Douglas Gregor3cf81312009-11-03 23:16:33 +00001891 case UnqualifiedId::IK_DestructorName: {
1892 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001893 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001894 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001895 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001896 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1897 SS, TemplateKWLoc, TemplateName,
1898 ObjectType, EnteringContext,
1899 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001900 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001901 return true;
1902 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001903 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1904 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001905 EnteringContext, Template,
1906 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001907
John McCallba7bf592010-08-24 05:47:05 +00001908 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001909 Diag(NameLoc, diag::err_destructor_template_id)
1910 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001911 return true;
1912 }
1913 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001914 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001915 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001916
1917 default:
1918 return false;
1919 }
1920
1921 if (TNK == TNK_Non_template)
1922 return false;
1923
1924 // Parse the enclosed template argument list.
1925 SourceLocation LAngleLoc, RAngleLoc;
1926 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00001927 if (Tok.is(tok::less) &&
1928 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00001929 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001930 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00001931 RAngleLoc))
1932 return true;
1933
1934 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00001935 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1936 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001937 // Form a parsed representation of the template-id to be stored in the
1938 // UnqualifiedId.
1939 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00001940 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00001941
Richard Smith72bfbd82013-12-04 00:28:23 +00001942 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00001943 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1944 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001945 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00001946 TemplateId->TemplateNameLoc = Id.StartLocation;
1947 } else {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001948 TemplateId->Name = 0;
1949 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1950 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00001951 }
1952
Douglas Gregore7c20652011-03-02 00:47:37 +00001953 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00001954 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00001955 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00001956 TemplateId->Kind = TNK;
1957 TemplateId->LAngleLoc = LAngleLoc;
1958 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001959 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00001960 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001961 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00001962 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00001963
1964 Id.setTemplateId(TemplateId);
1965 return false;
1966 }
1967
1968 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001969 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00001970
Douglas Gregor7861a802009-11-03 01:35:08 +00001971 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00001972 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001973 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1974 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00001975 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1976 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00001977 if (Type.isInvalid())
1978 return true;
1979
1980 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1981 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1982 else
1983 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1984
1985 return false;
1986}
1987
Douglas Gregor71395fa2009-11-04 00:56:37 +00001988/// \brief Parse an operator-function-id or conversion-function-id as part
1989/// of a C++ unqualified-id.
1990///
1991/// This routine is responsible only for parsing the operator-function-id or
1992/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00001993///
1994/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00001995/// operator-function-id: [C++ 13.5]
1996/// 'operator' operator
1997///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001998/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00001999/// new delete new[] delete[]
2000/// + - * / % ^ & | ~
2001/// ! = < > += -= *= /= %=
2002/// ^= &= |= << >> >>= <<= == !=
2003/// <= >= && || ++ -- , ->* ->
2004/// () []
2005///
2006/// conversion-function-id: [C++ 12.3.2]
2007/// operator conversion-type-id
2008///
2009/// conversion-type-id:
2010/// type-specifier-seq conversion-declarator[opt]
2011///
2012/// conversion-declarator:
2013/// ptr-operator conversion-declarator[opt]
2014/// \endcode
2015///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002016/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002017/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2018///
2019/// \param EnteringContext whether we are entering the scope of the
2020/// nested-name-specifier.
2021///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002022/// \param ObjectType if this unqualified-id occurs within a member access
2023/// expression, the type of the base object whose member is being accessed.
2024///
2025/// \param Result on a successful parse, contains the parsed unqualified-id.
2026///
2027/// \returns true if parsing fails, false otherwise.
2028bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002029 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002030 UnqualifiedId &Result) {
2031 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2032
2033 // Consume the 'operator' keyword.
2034 SourceLocation KeywordLoc = ConsumeToken();
2035
2036 // Determine what kind of operator name we have.
2037 unsigned SymbolIdx = 0;
2038 SourceLocation SymbolLocations[3];
2039 OverloadedOperatorKind Op = OO_None;
2040 switch (Tok.getKind()) {
2041 case tok::kw_new:
2042 case tok::kw_delete: {
2043 bool isNew = Tok.getKind() == tok::kw_new;
2044 // Consume the 'new' or 'delete'.
2045 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002046 // Check for array new/delete.
2047 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002048 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002049 // Consume the '[' and ']'.
2050 BalancedDelimiterTracker T(*this, tok::l_square);
2051 T.consumeOpen();
2052 T.consumeClose();
2053 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002054 return true;
2055
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002056 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2057 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002058 Op = isNew? OO_Array_New : OO_Array_Delete;
2059 } else {
2060 Op = isNew? OO_New : OO_Delete;
2061 }
2062 break;
2063 }
2064
2065#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2066 case tok::Token: \
2067 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2068 Op = OO_##Name; \
2069 break;
2070#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2071#include "clang/Basic/OperatorKinds.def"
2072
2073 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002074 // Consume the '(' and ')'.
2075 BalancedDelimiterTracker T(*this, tok::l_paren);
2076 T.consumeOpen();
2077 T.consumeClose();
2078 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002079 return true;
2080
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002081 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2082 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002083 Op = OO_Call;
2084 break;
2085 }
2086
2087 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002088 // Consume the '[' and ']'.
2089 BalancedDelimiterTracker T(*this, tok::l_square);
2090 T.consumeOpen();
2091 T.consumeClose();
2092 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002093 return true;
2094
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002095 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2096 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002097 Op = OO_Subscript;
2098 break;
2099 }
2100
2101 case tok::code_completion: {
2102 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002103 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002104 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002105 // Don't try to parse any further.
2106 return true;
2107 }
2108
2109 default:
2110 break;
2111 }
2112
2113 if (Op != OO_None) {
2114 // We have parsed an operator-function-id.
2115 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2116 return false;
2117 }
Alexis Hunt34458502009-11-28 04:44:28 +00002118
2119 // Parse a literal-operator-id.
2120 //
Richard Smith6f212062012-10-20 08:41:10 +00002121 // literal-operator-id: C++11 [over.literal]
2122 // operator string-literal identifier
2123 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002124
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002125 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002126 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002127
Richard Smith7d182a72012-03-08 23:06:02 +00002128 SourceLocation DiagLoc;
2129 unsigned DiagId = 0;
2130
2131 // We're past translation phase 6, so perform string literal concatenation
2132 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002133 SmallVector<Token, 4> Toks;
2134 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002135 while (isTokenStringLiteral()) {
2136 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002137 // C++11 [over.literal]p1:
2138 // The string-literal or user-defined-string-literal in a
2139 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002140 DiagLoc = Tok.getLocation();
2141 DiagId = diag::err_literal_operator_string_prefix;
2142 }
2143 Toks.push_back(Tok);
2144 TokLocs.push_back(ConsumeStringToken());
2145 }
2146
2147 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
2148 if (Literal.hadError)
2149 return true;
2150
2151 // Grab the literal operator's suffix, which will be either the next token
2152 // or a ud-suffix from the string literal.
2153 IdentifierInfo *II = 0;
2154 SourceLocation SuffixLoc;
2155 if (!Literal.getUDSuffix().empty()) {
2156 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2157 SuffixLoc =
2158 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2159 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002160 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002161 } else if (Tok.is(tok::identifier)) {
2162 II = Tok.getIdentifierInfo();
2163 SuffixLoc = ConsumeToken();
2164 TokLocs.push_back(SuffixLoc);
2165 } else {
Alexis Hunt34458502009-11-28 04:44:28 +00002166 Diag(Tok.getLocation(), diag::err_expected_ident);
2167 return true;
2168 }
2169
Richard Smith7d182a72012-03-08 23:06:02 +00002170 // The string literal must be empty.
2171 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002172 // C++11 [over.literal]p1:
2173 // The string-literal or user-defined-string-literal in a
2174 // literal-operator-id shall [...] contain no characters
2175 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002176 DiagLoc = TokLocs.front();
2177 DiagId = diag::err_literal_operator_string_not_empty;
2178 }
2179
2180 if (DiagId) {
2181 // This isn't a valid literal-operator-id, but we think we know
2182 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002183 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002184 Str += "\"\" ";
2185 Str += II->getName();
2186 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2187 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2188 }
2189
2190 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002191
2192 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002193 }
Richard Smithd091dc12013-12-05 00:58:33 +00002194
Douglas Gregor71395fa2009-11-04 00:56:37 +00002195 // Parse a conversion-function-id.
2196 //
2197 // conversion-function-id: [C++ 12.3.2]
2198 // operator conversion-type-id
2199 //
2200 // conversion-type-id:
2201 // type-specifier-seq conversion-declarator[opt]
2202 //
2203 // conversion-declarator:
2204 // ptr-operator conversion-declarator[opt]
2205
2206 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002207 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002208 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002209 return true;
2210
2211 // Parse the conversion-declarator, which is merely a sequence of
2212 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002213 Declarator D(DS, Declarator::ConversionIdContext);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002214 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2215
2216 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002217 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002218 if (Ty.isInvalid())
2219 return true;
2220
2221 // Note that this is a conversion-function-id.
2222 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2223 D.getSourceRange().getEnd());
2224 return false;
2225}
2226
2227/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2228/// name of an entity.
2229///
2230/// \code
2231/// unqualified-id: [C++ expr.prim.general]
2232/// identifier
2233/// operator-function-id
2234/// conversion-function-id
2235/// [C++0x] literal-operator-id [TODO]
2236/// ~ class-name
2237/// template-id
2238///
2239/// \endcode
2240///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002241/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002242/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2243///
2244/// \param EnteringContext whether we are entering the scope of the
2245/// nested-name-specifier.
2246///
Douglas Gregor7861a802009-11-03 01:35:08 +00002247/// \param AllowDestructorName whether we allow parsing of a destructor name.
2248///
2249/// \param AllowConstructorName whether we allow parsing a constructor name.
2250///
Douglas Gregor127ea592009-11-03 21:24:04 +00002251/// \param ObjectType if this unqualified-id occurs within a member access
2252/// expression, the type of the base object whose member is being accessed.
2253///
Douglas Gregor7861a802009-11-03 01:35:08 +00002254/// \param Result on a successful parse, contains the parsed unqualified-id.
2255///
2256/// \returns true if parsing fails, false otherwise.
2257bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2258 bool AllowDestructorName,
2259 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002260 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002261 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002262 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002263
2264 // Handle 'A::template B'. This is for template-ids which have not
2265 // already been annotated by ParseOptionalCXXScopeSpecifier().
2266 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002267 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002268 (ObjectType || SS.isSet())) {
2269 TemplateSpecified = true;
2270 TemplateKWLoc = ConsumeToken();
2271 }
2272
Douglas Gregor7861a802009-11-03 01:35:08 +00002273 // unqualified-id:
2274 // identifier
2275 // template-id (when it hasn't already been annotated)
2276 if (Tok.is(tok::identifier)) {
2277 // Consume the identifier.
2278 IdentifierInfo *Id = Tok.getIdentifierInfo();
2279 SourceLocation IdLoc = ConsumeToken();
2280
David Blaikiebbafb8a2012-03-11 07:00:24 +00002281 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002282 // If we're not in C++, only identifiers matter. Record the
2283 // identifier and return.
2284 Result.setIdentifier(Id, IdLoc);
2285 return false;
2286 }
2287
Douglas Gregor7861a802009-11-03 01:35:08 +00002288 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002289 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002290 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002291 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2292 &SS, false, false,
2293 ParsedType(),
2294 /*IsCtorOrDtorName=*/true,
2295 /*NonTrivialTypeSourceInfo=*/true);
2296 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002297 } else {
2298 // We have parsed an identifier.
2299 Result.setIdentifier(Id, IdLoc);
2300 }
2301
2302 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002303 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002304 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2305 EnteringContext, ObjectType,
2306 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002307
2308 return false;
2309 }
2310
2311 // unqualified-id:
2312 // template-id (already parsed and annotated)
2313 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002314 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002315
2316 // If the template-name names the current class, then this is a constructor
2317 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002318 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002319 if (SS.isSet()) {
2320 // C++ [class.qual]p2 specifies that a qualified template-name
2321 // is taken as the constructor name where a constructor can be
2322 // declared. Thus, the template arguments are extraneous, so
2323 // complain about them and remove them entirely.
2324 Diag(TemplateId->TemplateNameLoc,
2325 diag::err_out_of_line_constructor_template_id)
2326 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002327 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002328 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002329 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2330 TemplateId->TemplateNameLoc,
2331 getCurScope(),
2332 &SS, false, false,
2333 ParsedType(),
2334 /*IsCtorOrDtorName=*/true,
2335 /*NontrivialTypeSourceInfo=*/true);
2336 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002337 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002338 ConsumeToken();
2339 return false;
2340 }
2341
2342 Result.setConstructorTemplateId(TemplateId);
2343 ConsumeToken();
2344 return false;
2345 }
2346
Douglas Gregor7861a802009-11-03 01:35:08 +00002347 // We have already parsed a template-id; consume the annotation token as
2348 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002349 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002350 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002351 ConsumeToken();
2352 return false;
2353 }
2354
2355 // unqualified-id:
2356 // operator-function-id
2357 // conversion-function-id
2358 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002359 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002360 return true;
2361
Alexis Hunted0530f2009-11-28 08:58:14 +00002362 // If we have an operator-function-id or a literal-operator-id and the next
2363 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002364 //
2365 // template-id:
2366 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002367 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2368 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002369 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002370 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2371 0, SourceLocation(),
2372 EnteringContext, ObjectType,
2373 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002374
Douglas Gregor7861a802009-11-03 01:35:08 +00002375 return false;
2376 }
2377
David Blaikiebbafb8a2012-03-11 07:00:24 +00002378 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002379 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002380 // C++ [expr.unary.op]p10:
2381 // There is an ambiguity in the unary-expression ~X(), where X is a
2382 // class-name. The ambiguity is resolved in favor of treating ~ as a
2383 // unary complement rather than treating ~X as referring to a destructor.
2384
2385 // Parse the '~'.
2386 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002387
2388 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2389 DeclSpec DS(AttrFactory);
2390 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2391 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2392 Result.setDestructorName(TildeLoc, Type, EndLoc);
2393 return false;
2394 }
2395 return true;
2396 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002397
2398 // Parse the class-name.
2399 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002400 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002401 return true;
2402 }
2403
2404 // Parse the class-name (or template-name in a simple-template-id).
2405 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2406 SourceLocation ClassNameLoc = ConsumeToken();
2407
Douglas Gregorb22ee882010-05-05 05:58:24 +00002408 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002409 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002410 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2411 ClassName, ClassNameLoc,
2412 EnteringContext, ObjectType,
2413 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002414 }
2415
Douglas Gregor7861a802009-11-03 01:35:08 +00002416 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002417 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2418 ClassNameLoc, getCurScope(),
2419 SS, ObjectType,
2420 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002421 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002422 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002423
Douglas Gregor7861a802009-11-03 01:35:08 +00002424 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002425 return false;
2426 }
2427
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002428 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002429 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002430 return true;
2431}
2432
Sebastian Redlbd150f42008-11-21 19:14:01 +00002433/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2434/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002435///
Chris Lattner109faf22009-01-04 21:25:24 +00002436/// This method is called to parse the new expression after the optional :: has
2437/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2438/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002439///
2440/// new-expression:
2441/// '::'[opt] 'new' new-placement[opt] new-type-id
2442/// new-initializer[opt]
2443/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2444/// new-initializer[opt]
2445///
2446/// new-placement:
2447/// '(' expression-list ')'
2448///
Sebastian Redl351bb782008-12-02 14:43:59 +00002449/// new-type-id:
2450/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002451/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002452///
2453/// new-declarator:
2454/// ptr-operator new-declarator[opt]
2455/// direct-new-declarator
2456///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002457/// new-initializer:
2458/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002459/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002460///
John McCalldadc5752010-08-24 06:29:42 +00002461ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002462Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2463 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2464 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002465
2466 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2467 // second form of new-expression. It can't be a new-type-id.
2468
Benjamin Kramerf0623432012-08-23 22:51:59 +00002469 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002470 SourceLocation PlacementLParen, PlacementRParen;
2471
Douglas Gregorf2753b32010-07-13 15:54:32 +00002472 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002473 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002474 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002475 if (Tok.is(tok::l_paren)) {
2476 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002477 BalancedDelimiterTracker T(*this, tok::l_paren);
2478 T.consumeOpen();
2479 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002480 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002481 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002482 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002483 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002484
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002485 T.consumeClose();
2486 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002487 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002488 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002489 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002490 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002491
Sebastian Redl351bb782008-12-02 14:43:59 +00002492 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002493 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002494 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002495 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002496 } else {
2497 // We still need the type.
2498 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002499 BalancedDelimiterTracker T(*this, tok::l_paren);
2500 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002501 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002502 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002503 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002504 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002505 T.consumeClose();
2506 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002507 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002508 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002509 if (ParseCXXTypeSpecifierSeq(DS))
2510 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002511 else {
2512 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002513 ParseDeclaratorInternal(DeclaratorInfo,
2514 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002515 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002516 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002517 }
2518 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002519 // A new-type-id is a simplified type-id, where essentially the
2520 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002521 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002522 if (ParseCXXTypeSpecifierSeq(DS))
2523 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002524 else {
2525 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002526 ParseDeclaratorInternal(DeclaratorInfo,
2527 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002528 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002529 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002530 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002531 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002532 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002533 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002534
Sebastian Redl6047f072012-02-16 12:22:20 +00002535 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002536
2537 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002538 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002539 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002540 BalancedDelimiterTracker T(*this, tok::l_paren);
2541 T.consumeOpen();
2542 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002543 if (Tok.isNot(tok::r_paren)) {
2544 CommaLocsTy CommaLocs;
Sebastian Redl351bb782008-12-02 14:43:59 +00002545 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002546 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002547 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002548 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002549 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002550 T.consumeClose();
2551 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002552 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002553 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002554 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002555 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002556 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2557 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002558 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002559 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002560 Diag(Tok.getLocation(),
2561 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002562 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002563 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002564 if (Initializer.isInvalid())
2565 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002566
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002567 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002568 PlacementArgs, PlacementRParen,
Sebastian Redl6047f072012-02-16 12:22:20 +00002569 TypeIdParens, DeclaratorInfo, Initializer.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002570}
2571
Sebastian Redlbd150f42008-11-21 19:14:01 +00002572/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2573/// passed to ParseDeclaratorInternal.
2574///
2575/// direct-new-declarator:
2576/// '[' expression ']'
2577/// direct-new-declarator '[' constant-expression ']'
2578///
Chris Lattner109faf22009-01-04 21:25:24 +00002579void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002580 // Parse the array dimensions.
2581 bool first = true;
2582 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002583 // An array-size expression can't start with a lambda.
2584 if (CheckProhibitedCXX11Attribute())
2585 continue;
2586
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002587 BalancedDelimiterTracker T(*this, tok::l_square);
2588 T.consumeOpen();
2589
John McCalldadc5752010-08-24 06:29:42 +00002590 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002591 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002592 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002593 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002594 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002595 return;
2596 }
2597 first = false;
2598
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002599 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002600
Bill Wendling44426052012-12-20 19:22:21 +00002601 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002602 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002603 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002604
John McCall084e83d2011-03-24 11:26:52 +00002605 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002606 /*static=*/false, /*star=*/false,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002607 Size.release(),
2608 T.getOpenLocation(),
2609 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002610 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002611
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002612 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002613 return;
2614 }
2615}
2616
2617/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2618/// This ambiguity appears in the syntax of the C++ new operator.
2619///
2620/// new-expression:
2621/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2622/// new-initializer[opt]
2623///
2624/// new-placement:
2625/// '(' expression-list ')'
2626///
John McCall37ad5512010-08-23 06:44:23 +00002627bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002628 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002629 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002630 // The '(' was already consumed.
2631 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002632 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002633 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002634 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002635 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002636 }
2637
2638 // It's not a type, it has to be an expression list.
2639 // Discard the comma locations - ActOnCXXNew has enough parameters.
2640 CommaLocsTy CommaLocs;
2641 return ParseExpressionList(PlacementArgs, CommaLocs);
2642}
2643
2644/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2645/// to free memory allocated by new.
2646///
Chris Lattner109faf22009-01-04 21:25:24 +00002647/// This method is called to parse the 'delete' expression after the optional
2648/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2649/// and "Start" is its location. Otherwise, "Start" is the location of the
2650/// 'delete' token.
2651///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002652/// delete-expression:
2653/// '::'[opt] 'delete' cast-expression
2654/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002655ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002656Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2657 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2658 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002659
2660 // Array delete?
2661 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002662 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002663 // C++11 [expr.delete]p1:
2664 // Whenever the delete keyword is followed by empty square brackets, it
2665 // shall be interpreted as [array delete].
2666 // [Footnote: A lambda expression with a lambda-introducer that consists
2667 // of empty square brackets can follow the delete keyword if
2668 // the lambda expression is enclosed in parentheses.]
2669 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2670 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002671 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002672 BalancedDelimiterTracker T(*this, tok::l_square);
2673
2674 T.consumeOpen();
2675 T.consumeClose();
2676 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002677 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002678 }
2679
John McCalldadc5752010-08-24 06:29:42 +00002680 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002681 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002682 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002683
John McCallb268a282010-08-23 23:25:46 +00002684 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002685}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002686
Mike Stump11289f42009-09-09 15:08:12 +00002687static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002688 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002689 default: llvm_unreachable("Not a known unary type trait.");
Alp Toker40f9b1c2013-12-12 21:23:03 +00002690#define TYPE_TRAIT_1(Spelling, Name, Key) \
2691 case tok::kw_ ## Spelling: return UTT_ ## Name;
2692#include "clang/Basic/TokenKinds.def"
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002693 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002694}
2695
Douglas Gregor29c42f22012-02-24 07:38:34 +00002696static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2697 switch (kind) {
2698 default: llvm_unreachable("Not a known type trait");
Alp Tokercbb90342013-12-13 20:49:58 +00002699#define TYPE_TRAIT_2(Spelling, Name, Key) \
2700case tok::kw_ ## Spelling: return BTT_ ## Name;
2701#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002702#define TYPE_TRAIT_N(Spelling, Name, Key) \
2703 case tok::kw_ ## Spelling: return TT_ ## Name;
2704#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002705 }
2706}
2707
John Wiegley6242b6a2011-04-28 00:16:57 +00002708static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2709 switch(kind) {
2710 default: llvm_unreachable("Not a known binary type trait");
2711 case tok::kw___array_rank: return ATT_ArrayRank;
2712 case tok::kw___array_extent: return ATT_ArrayExtent;
2713 }
2714}
2715
John Wiegleyf9f65842011-04-25 06:54:41 +00002716static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2717 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002718 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002719 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2720 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2721 }
2722}
2723
Alp Toker40f9b1c2013-12-12 21:23:03 +00002724static unsigned TypeTraitArity(tok::TokenKind kind) {
2725 switch (kind) {
2726 default: llvm_unreachable("Not a known type trait");
2727#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2728#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002729 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002730}
2731
Douglas Gregor29c42f22012-02-24 07:38:34 +00002732/// \brief Parse the built-in type-trait pseudo-functions that allow
2733/// implementation of the TR1/C++11 type traits templates.
2734///
2735/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002736/// unary-type-trait '(' type-id ')'
2737/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002738/// type-trait '(' type-id-seq ')'
2739///
2740/// type-id-seq:
2741/// type-id ...[opt] type-id-seq[opt]
2742///
2743ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002744 tok::TokenKind Kind = Tok.getKind();
2745 unsigned Arity = TypeTraitArity(Kind);
2746
Douglas Gregor29c42f22012-02-24 07:38:34 +00002747 SourceLocation Loc = ConsumeToken();
2748
2749 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2750 if (Parens.expectAndConsume(diag::err_expected_lparen))
2751 return ExprError();
2752
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002753 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002754 do {
2755 // Parse the next type.
2756 TypeResult Ty = ParseTypeName();
2757 if (Ty.isInvalid()) {
2758 Parens.skipToEnd();
2759 return ExprError();
2760 }
2761
2762 // Parse the ellipsis, if present.
2763 if (Tok.is(tok::ellipsis)) {
2764 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2765 if (Ty.isInvalid()) {
2766 Parens.skipToEnd();
2767 return ExprError();
2768 }
2769 }
2770
2771 // Add this type to the list of arguments.
2772 Args.push_back(Ty.get());
2773
2774 if (Tok.is(tok::comma)) {
2775 ConsumeToken();
2776 continue;
2777 }
2778
2779 break;
2780 } while (true);
2781
2782 if (Parens.consumeClose())
2783 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002784
2785 SourceLocation EndLoc = Parens.getCloseLocation();
2786
2787 if (Arity && Args.size() != Arity) {
2788 Diag(EndLoc, diag::err_type_trait_arity)
2789 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2790 return ExprError();
2791 }
2792
2793 if (!Arity && Args.empty()) {
2794 Diag(EndLoc, diag::err_type_trait_arity)
2795 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2796 return ExprError();
2797 }
2798
2799 if (Arity == 1)
2800 return Actions.ActOnUnaryTypeTrait(UnaryTypeTraitFromTokKind(Kind), Loc,
2801 Args[0], EndLoc);
Alp Toker40f9b1c2013-12-12 21:23:03 +00002802
Alp Tokercbb90342013-12-13 20:49:58 +00002803 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Arity, Loc, Args,
2804 EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00002805}
2806
John Wiegley6242b6a2011-04-28 00:16:57 +00002807/// ParseArrayTypeTrait - Parse the built-in array type-trait
2808/// pseudo-functions.
2809///
2810/// primary-expression:
2811/// [Embarcadero] '__array_rank' '(' type-id ')'
2812/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2813///
2814ExprResult Parser::ParseArrayTypeTrait() {
2815 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2816 SourceLocation Loc = ConsumeToken();
2817
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002818 BalancedDelimiterTracker T(*this, tok::l_paren);
2819 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegley6242b6a2011-04-28 00:16:57 +00002820 return ExprError();
2821
2822 TypeResult Ty = ParseTypeName();
2823 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002824 SkipUntil(tok::comma, StopAtSemi);
2825 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002826 return ExprError();
2827 }
2828
2829 switch (ATT) {
2830 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002831 T.consumeClose();
2832 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2833 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002834 }
2835 case ATT_ArrayExtent: {
2836 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002837 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002838 return ExprError();
2839 }
2840
2841 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002842 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002843
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002844 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2845 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002846 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002847 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002848 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002849}
2850
John Wiegleyf9f65842011-04-25 06:54:41 +00002851/// ParseExpressionTrait - Parse built-in expression-trait
2852/// pseudo-functions like __is_lvalue_expr( xxx ).
2853///
2854/// primary-expression:
2855/// [Embarcadero] expression-trait '(' expression ')'
2856///
2857ExprResult Parser::ParseExpressionTrait() {
2858 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2859 SourceLocation Loc = ConsumeToken();
2860
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002861 BalancedDelimiterTracker T(*this, tok::l_paren);
2862 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegleyf9f65842011-04-25 06:54:41 +00002863 return ExprError();
2864
2865 ExprResult Expr = ParseExpression();
2866
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002867 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002868
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002869 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2870 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002871}
2872
2873
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002874/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2875/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2876/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002877ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002878Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002879 ParsedType &CastTy,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002880 BalancedDelimiterTracker &Tracker) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002881 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002882 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2883 assert(isTypeIdInParens() && "Not a type-id!");
2884
John McCalldadc5752010-08-24 06:29:42 +00002885 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00002886 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002887
2888 // We need to disambiguate a very ugly part of the C++ syntax:
2889 //
2890 // (T())x; - type-id
2891 // (T())*x; - type-id
2892 // (T())/x; - expression
2893 // (T()); - expression
2894 //
2895 // The bad news is that we cannot use the specialized tentative parser, since
2896 // it can only verify that the thing inside the parens can be parsed as
2897 // type-id, it is not useful for determining the context past the parens.
2898 //
2899 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00002900 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002901 //
2902 // It uses a scheme similar to parsing inline methods. The parenthesized
2903 // tokens are cached, the context that follows is determined (possibly by
2904 // parsing a cast-expression), and then we re-introduce the cached tokens
2905 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002906
Mike Stump11289f42009-09-09 15:08:12 +00002907 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002908 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002909
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002910 // Store the tokens of the parentheses. We will parse them after we determine
2911 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00002912 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002913 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002914 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002915 return ExprError();
2916 }
2917
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002918 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002919 ParseAs = CompoundLiteral;
2920 } else {
2921 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00002922 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2923 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2924 NotCastExpr = true;
2925 } else {
2926 // Try parsing the cast-expression that may follow.
2927 // If it is not a cast-expression, NotCastExpr will be true and no token
2928 // will be consumed.
2929 Result = ParseCastExpression(false/*isUnaryExpression*/,
2930 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00002931 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002932 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00002933 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00002934 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002935
2936 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2937 // an expression.
2938 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002939 }
2940
Mike Stump11289f42009-09-09 15:08:12 +00002941 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002942 Toks.push_back(Tok);
2943 // Re-enter the stored parenthesized tokens into the token stream, so we may
2944 // parse them now.
2945 PP.EnterTokenStream(Toks.data(), Toks.size(),
2946 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2947 // Drop the current token and bring the first cached one. It's the same token
2948 // as when we entered this function.
2949 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002950
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002951 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002952 // Parse the type declarator.
2953 DeclSpec DS(AttrFactory);
2954 ParseSpecifierQualifierList(DS);
2955 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2956 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002957
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002958 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002959 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002960
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002961 if (ParseAs == CompoundLiteral) {
2962 ExprType = CompoundLiteral;
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002963 TypeResult Ty = ParseTypeName();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002964 return ParseCompoundLiteralExpression(Ty.get(),
2965 Tracker.getOpenLocation(),
2966 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002967 }
Mike Stump11289f42009-09-09 15:08:12 +00002968
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002969 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2970 assert(ParseAs == CastExpr);
2971
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002972 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002973 return ExprError();
2974
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002975 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002976 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002977 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2978 DeclaratorInfo, CastTy,
2979 Tracker.getCloseLocation(), Result.take());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002980 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002981 }
Mike Stump11289f42009-09-09 15:08:12 +00002982
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002983 // Not a compound literal, and not followed by a cast-expression.
2984 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002985
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002986 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002987 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002988 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002989 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2990 Tok.getLocation(), Result.take());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002991
2992 // Match the ')'.
2993 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002994 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002995 return ExprError();
2996 }
Mike Stump11289f42009-09-09 15:08:12 +00002997
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002998 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002999 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003000}