blob: 42e737004b432985f90c4ed3616da54e091199eb [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);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000236
237 SourceLocation CCLoc;
238 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000239 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
240 return false;
241 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000242
David Blaikie15a430a2011-12-04 05:04:18 +0000243 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
244 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
245
246 HasScopeSpecifier = true;
247 }
248
Douglas Gregor7f741122009-02-25 19:37:18 +0000249 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000250 if (HasScopeSpecifier) {
251 // C++ [basic.lookup.classref]p5:
252 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000253 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000254 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000255 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000256 // the class-name-or-namespace-name is looked up in global scope as a
257 // class-name or namespace-name.
258 //
259 // To implement this, we clear out the object type as soon as we've
260 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000261 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000262
263 if (Tok.is(tok::code_completion)) {
264 // Code completion for a nested-name-specifier, where the code
265 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000266 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000267 // Include code completion token into the range of the scope otherwise
268 // when we try to annotate the scope tokens the dangling code completion
269 // token will cause assertion in
270 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000271 SS.setEndLoc(Tok.getLocation());
272 cutOffParsing();
273 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000274 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000275 }
Mike Stump11289f42009-09-09 15:08:12 +0000276
Douglas Gregor7f741122009-02-25 19:37:18 +0000277 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000278 // nested-name-specifier 'template'[opt] simple-template-id '::'
279
280 // Parse the optional 'template' keyword, then make sure we have
281 // 'identifier <' after it.
282 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000283 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000284 // nested-name-specifier, since they aren't allowed to start with
285 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000286 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000287 break;
288
Douglas Gregor120635b2009-11-11 16:39:34 +0000289 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000290 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000291
Douglas Gregor71395fa2009-11-04 00:56:37 +0000292 UnqualifiedId TemplateName;
293 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000294 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000295 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000296 ConsumeToken();
297 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000298 // We don't need to actually parse the unqualified-id in this case,
299 // because a simple-template-id cannot start with 'operator', but
300 // go ahead and parse it anyway for consistency with the case where
301 // we already annotated the template-id.
302 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000303 TemplateName)) {
304 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000305 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000306 }
Richard Smithd091dc12013-12-05 00:58:33 +0000307
Alexis Hunted0530f2009-11-28 08:58:14 +0000308 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
309 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000310 Diag(TemplateName.getSourceRange().getBegin(),
311 diag::err_id_after_template_in_nested_name_spec)
312 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000313 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000314 break;
315 }
316 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000317 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000318 break;
319 }
Mike Stump11289f42009-09-09 15:08:12 +0000320
Douglas Gregor120635b2009-11-11 16:39:34 +0000321 // If the next token is not '<', we have a qualified-id that refers
322 // to a template name, such as T::template apply, but is not a
323 // template-id.
324 if (Tok.isNot(tok::less)) {
325 TPA.Revert();
326 break;
327 }
328
329 // Commit to parsing the template-id.
330 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000331 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000332 if (TemplateNameKind TNK
333 = Actions.ActOnDependentTemplateName(getCurScope(),
334 SS, TemplateKWLoc, TemplateName,
335 ObjectType, EnteringContext,
336 Template)) {
337 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
338 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000339 return true;
340 } else
John McCall1f476a12010-02-26 08:45:28 +0000341 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000342
Chris Lattner0eed3a62009-06-26 03:47:46 +0000343 continue;
344 }
Mike Stump11289f42009-09-09 15:08:12 +0000345
Douglas Gregor7f741122009-02-25 19:37:18 +0000346 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000347 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000348 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000349 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000350 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000351 // So we need to check whether the template-id is a simple-template-id of
352 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000353 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000354 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000355 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
356 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000357 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000358 }
359
Richard Smith7447af42013-03-26 01:15:19 +0000360 if (LastII)
361 *LastII = TemplateId->Name;
362
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000363 // Consume the template-id token.
364 ConsumeToken();
365
366 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
367 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000368
David Blaikie8c045bc2011-11-07 03:30:03 +0000369 HasScopeSpecifier = true;
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000370
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000371 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000372 TemplateId->NumArgs);
373
374 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000375 SS,
376 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000377 TemplateId->Template,
378 TemplateId->TemplateNameLoc,
379 TemplateId->LAngleLoc,
380 TemplateArgsPtr,
381 TemplateId->RAngleLoc,
382 CCLoc,
383 EnteringContext)) {
384 SourceLocation StartLoc
385 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
386 : TemplateId->TemplateNameLoc;
387 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000388 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000389
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000390 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000391 }
392
Chris Lattnere2355f72009-06-26 03:52:38 +0000393
394 // The rest of the nested-name-specifier possibilities start with
395 // tok::identifier.
396 if (Tok.isNot(tok::identifier))
397 break;
398
399 IdentifierInfo &II = *Tok.getIdentifierInfo();
400
401 // nested-name-specifier:
402 // type-name '::'
403 // namespace-name '::'
404 // nested-name-specifier identifier '::'
405 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000406
407 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
408 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000409 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000410 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
411 Tok.getLocation(),
412 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000413 EnteringContext) &&
414 // If the token after the colon isn't an identifier, it's still an
415 // error, but they probably meant something else strange so don't
416 // recover like this.
417 PP.LookAhead(1).is(tok::identifier)) {
418 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000419 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000420
421 // Recover as if the user wrote '::'.
422 Next.setKind(tok::coloncolon);
423 }
Chris Lattner1c428032009-12-07 01:36:53 +0000424 }
425
Chris Lattnere2355f72009-06-26 03:52:38 +0000426 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000427 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor0be31a22010-07-02 17:43:08 +0000428 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000429 II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000430 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000431 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000432 }
433
Richard Smith7447af42013-03-26 01:15:19 +0000434 if (LastII)
435 *LastII = &II;
436
Chris Lattnere2355f72009-06-26 03:52:38 +0000437 // We have an identifier followed by a '::'. Lookup this name
438 // as the name in a nested-name-specifier.
439 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000440 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
441 "NextToken() not working properly!");
Chris Lattnere2355f72009-06-26 03:52:38 +0000442 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000443
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000444 CheckForLParenAfterColonColon();
445
Douglas Gregor90c99722011-02-24 00:17:56 +0000446 HasScopeSpecifier = true;
447 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
448 ObjectType, EnteringContext, SS))
449 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
450
Chris Lattnere2355f72009-06-26 03:52:38 +0000451 continue;
452 }
Mike Stump11289f42009-09-09 15:08:12 +0000453
Richard Trieu01fc0012011-09-19 19:01:00 +0000454 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000455
Chris Lattnere2355f72009-06-26 03:52:38 +0000456 // nested-name-specifier:
457 // type-name '<'
458 if (Next.is(tok::less)) {
459 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000460 UnqualifiedId TemplateName;
461 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000462 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000463 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000464 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000465 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000466 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000467 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000468 Template,
469 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000470 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000471 // with a template-id annotation. We do not permit the
472 // template-id to be translated into a type annotation,
473 // because some clients (e.g., the parsing of class template
474 // specializations) still want to see the original template-id
475 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000476 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000477 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
478 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000479 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000480 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000481 }
482
Douglas Gregor20c38a72010-05-21 23:43:39 +0000483 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000484 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000485 // We have something like t::getAs<T>, where getAs is a
486 // member of an unknown specialization. However, this will only
487 // parse correctly as a template, so suggest the keyword 'template'
488 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000489 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000491 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000492
493 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000494 << II.getName()
495 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
496
Douglas Gregorbb119652010-06-16 23:00:59 +0000497 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000498 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000499 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000500 TemplateName, ObjectType,
501 EnteringContext, Template)) {
502 // Consume the identifier.
503 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000504 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
505 TemplateName, false))
506 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000507 }
508 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000509 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000510
Douglas Gregor20c38a72010-05-21 23:43:39 +0000511 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000512 }
513 }
514
Douglas Gregor7f741122009-02-25 19:37:18 +0000515 // We don't have any tokens that form the beginning of a
516 // nested-name-specifier, so we're done.
517 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Douglas Gregore610ada2010-02-24 18:44:31 +0000520 // Even if we didn't see any pieces of a nested-name-specifier, we
521 // still check whether there is a tilde in this position, which
522 // indicates a potential pseudo-destructor.
523 if (CheckForDestructor && Tok.is(tok::tilde))
524 *MayBePseudoDestructor = true;
525
John McCall1f476a12010-02-26 08:45:28 +0000526 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000527}
528
529/// ParseCXXIdExpression - Handle id-expression.
530///
531/// id-expression:
532/// unqualified-id
533/// qualified-id
534///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000535/// qualified-id:
536/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
537/// '::' identifier
538/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000539/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000540///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000541/// NOTE: The standard specifies that, for qualified-id, the parser does not
542/// expect:
543///
544/// '::' conversion-function-id
545/// '::' '~' class-name
546///
547/// This may cause a slight inconsistency on diagnostics:
548///
549/// class C {};
550/// namespace A {}
551/// void f() {
552/// :: A :: ~ C(); // Some Sema error about using destructor with a
553/// // namespace.
554/// :: ~ C(); // Some Parser error like 'unexpected ~'.
555/// }
556///
557/// We simplify the parser a bit and make it work like:
558///
559/// qualified-id:
560/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
561/// '::' unqualified-id
562///
563/// That way Sema can handle and report similar errors for namespaces and the
564/// global scope.
565///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000566/// The isAddressOfOperand parameter indicates that this id-expression is a
567/// direct operand of the address-of operator. This is, besides member contexts,
568/// the only place where a qualified-id naming a non-static class member may
569/// appear.
570///
John McCalldadc5752010-08-24 06:29:42 +0000571ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000572 // qualified-id:
573 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
574 // '::' unqualified-id
575 //
576 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000577 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000578
579 SourceLocation TemplateKWLoc;
Douglas Gregora121b752009-11-03 16:56:39 +0000580 UnqualifiedId Name;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000581 if (ParseUnqualifiedId(SS,
582 /*EnteringContext=*/false,
583 /*AllowDestructorName=*/false,
584 /*AllowConstructorName=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000585 /*ObjectType=*/ ParsedType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000586 TemplateKWLoc,
Douglas Gregora121b752009-11-03 16:56:39 +0000587 Name))
588 return ExprError();
John McCalla9ee3252009-11-22 02:49:43 +0000589
590 // This is only the direct operand of an & operator if it is not
591 // followed by a postfix-expression suffix.
John McCall8d08b9b2010-08-27 09:08:28 +0000592 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
593 isAddressOfOperand = false;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000594
595 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
596 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000597}
598
Richard Smith21b3ab42013-05-09 21:36:41 +0000599/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000600///
601/// lambda-expression:
602/// lambda-introducer lambda-declarator[opt] compound-statement
603///
604/// lambda-introducer:
605/// '[' lambda-capture[opt] ']'
606///
607/// lambda-capture:
608/// capture-default
609/// capture-list
610/// capture-default ',' capture-list
611///
612/// capture-default:
613/// '&'
614/// '='
615///
616/// capture-list:
617/// capture
618/// capture-list ',' capture
619///
620/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000621/// simple-capture
622/// init-capture [C++1y]
623///
624/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000625/// identifier
626/// '&' identifier
627/// 'this'
628///
Richard Smith21b3ab42013-05-09 21:36:41 +0000629/// init-capture: [C++1y]
630/// identifier initializer
631/// '&' identifier initializer
632///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000633/// lambda-declarator:
634/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
635/// 'mutable'[opt] exception-specification[opt]
636/// trailing-return-type[opt]
637///
638ExprResult Parser::ParseLambdaExpression() {
639 // Parse lambda-introducer.
640 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000641 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000642 if (DiagID) {
643 Diag(Tok, DiagID.getValue());
Alexey Bataevee6507d2013-11-18 08:17:37 +0000644 SkipUntil(tok::r_square, StopAtSemi);
645 SkipUntil(tok::l_brace, StopAtSemi);
646 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000647 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000648 }
649
650 return ParseLambdaExpressionAfterIntroducer(Intro);
651}
652
653/// TryParseLambdaExpression - Use lookahead and potentially tentative
654/// parsing to determine if we are looking at a C++0x lambda expression, and parse
655/// it if we are.
656///
657/// If we are not looking at a lambda expression, returns ExprError().
658ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000659 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000660 && Tok.is(tok::l_square)
661 && "Not at the start of a possible lambda expression.");
662
663 const Token Next = NextToken(), After = GetLookAheadToken(2);
664
665 // If lookahead indicates this is a lambda...
666 if (Next.is(tok::r_square) || // []
667 Next.is(tok::equal) || // [=
668 (Next.is(tok::amp) && // [&] or [&,
669 (After.is(tok::r_square) ||
670 After.is(tok::comma))) ||
671 (Next.is(tok::identifier) && // [identifier]
672 After.is(tok::r_square))) {
673 return ParseLambdaExpression();
674 }
675
Eli Friedmanc7c97142012-01-04 02:40:39 +0000676 // If lookahead indicates an ObjC message send...
677 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000678 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000679 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000680 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000681
Eli Friedmanc7c97142012-01-04 02:40:39 +0000682 // Here, we're stuck: lambda introducers and Objective-C message sends are
683 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
684 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
685 // writing two routines to parse a lambda introducer, just try to parse
686 // a lambda introducer first, and fall back if that fails.
687 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000688 LambdaIntroducer Intro;
689 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000690 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000691
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000692 return ParseLambdaExpressionAfterIntroducer(Intro);
693}
694
Richard Smithf44d2a82013-05-21 22:21:19 +0000695/// \brief Parse a lambda introducer.
696/// \param Intro A LambdaIntroducer filled in with information about the
697/// contents of the lambda-introducer.
698/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
699/// message send and a lambda expression. In this mode, we will
700/// sometimes skip the initializers for init-captures and not fully
701/// populate \p Intro. This flag will be set to \c true if we do so.
702/// \return A DiagnosticID if it hit something unexpected. The location for
703/// for the diagnostic is that of the current token.
704Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
705 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000706 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000707
708 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000709 BalancedDelimiterTracker T(*this, tok::l_square);
710 T.consumeOpen();
711
712 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000713
714 bool first = true;
715
716 // Parse capture-default.
717 if (Tok.is(tok::amp) &&
718 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
719 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000720 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000721 first = false;
722 } else if (Tok.is(tok::equal)) {
723 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000724 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000725 first = false;
726 }
727
728 while (Tok.isNot(tok::r_square)) {
729 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000730 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000731 // Provide a completion for a lambda introducer here. Except
732 // in Objective-C, where this is Almost Surely meant to be a message
733 // send. In that case, fail here and let the ObjC message
734 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000735 if (Tok.is(tok::code_completion) &&
736 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
737 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000738 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
739 /*AfterAmpersand=*/false);
740 ConsumeCodeCompletionToken();
741 break;
742 }
743
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000744 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000745 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000746 ConsumeToken();
747 }
748
Douglas Gregord8c61782012-02-15 15:34:24 +0000749 if (Tok.is(tok::code_completion)) {
750 // If we're in Objective-C++ and we have a bare '[', then this is more
751 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000752 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000753 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
754 else
755 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
756 /*AfterAmpersand=*/false);
757 ConsumeCodeCompletionToken();
758 break;
759 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000760
Douglas Gregord8c61782012-02-15 15:34:24 +0000761 first = false;
762
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000763 // Parse capture.
764 LambdaCaptureKind Kind = LCK_ByCopy;
765 SourceLocation Loc;
766 IdentifierInfo* Id = 0;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000767 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000768 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000769
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000770 if (Tok.is(tok::kw_this)) {
771 Kind = LCK_This;
772 Loc = ConsumeToken();
773 } else {
774 if (Tok.is(tok::amp)) {
775 Kind = LCK_ByRef;
776 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000777
778 if (Tok.is(tok::code_completion)) {
779 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
780 /*AfterAmpersand=*/true);
781 ConsumeCodeCompletionToken();
782 break;
783 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000784 }
785
786 if (Tok.is(tok::identifier)) {
787 Id = Tok.getIdentifierInfo();
788 Loc = ConsumeToken();
789 } else if (Tok.is(tok::kw_this)) {
790 // FIXME: If we want to suggest a fixit here, will need to return more
791 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
792 // Clear()ed to prevent emission in case of tentative parsing?
793 return DiagResult(diag::err_this_captured_by_reference);
794 } else {
795 return DiagResult(diag::err_expected_capture);
796 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000797
798 if (Tok.is(tok::l_paren)) {
799 BalancedDelimiterTracker Parens(*this, tok::l_paren);
800 Parens.consumeOpen();
801
802 ExprVector Exprs;
803 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000804 if (SkippedInits) {
805 Parens.skipToEnd();
806 *SkippedInits = true;
807 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000808 Parens.skipToEnd();
809 Init = ExprError();
810 } else {
811 Parens.consumeClose();
812 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
813 Parens.getCloseLocation(),
814 Exprs);
815 }
816 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000817 // Each lambda init-capture forms its own full expression, which clears
818 // Actions.MaybeODRUseExprs. So create an expression evaluation context
819 // to save the necessary state, and restore it later.
820 EnterExpressionEvaluationContext EC(Actions,
821 Sema::PotentiallyEvaluated);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000822 TryConsumeToken(tok::equal);
Richard Smith21b3ab42013-05-09 21:36:41 +0000823
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 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000871 } else
872 TryConsumeToken(tok::ellipsis, EllipsisLoc);
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;
Alp Toker094e5212014-01-05 03:27:11 +00001011 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001012 DeclEndLoc = MutableLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001013
1014 // Parse exception-specification[opt].
1015 ExceptionSpecificationType ESpecType = EST_None;
1016 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001017 SmallVector<ParsedType, 2> DynamicExceptions;
1018 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001019 ExprResult NoexceptExpr;
Richard Smith2331bbf2012-05-02 22:22:32 +00001020 ESpecType = tryParseExceptionSpecification(ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001021 DynamicExceptions,
1022 DynamicExceptionRanges,
Richard Smith2331bbf2012-05-02 22:22:32 +00001023 NoexceptExpr);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001024
1025 if (ESpecType != EST_None)
1026 DeclEndLoc = ESpecRange.getEnd();
1027
1028 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001029 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001030
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001031 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1032
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001033 // Parse trailing-return-type[opt].
Richard Smith700537c2012-06-12 01:51:59 +00001034 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001035 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001036 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001037 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001038 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001039 if (Range.getEnd().isValid())
1040 DeclEndLoc = Range.getEnd();
1041 }
1042
1043 PrototypeScope.Exit();
1044
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001045 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001046 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001047 /*isAmbiguous=*/false,
1048 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001049 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001050 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001051 DS.getTypeQualifiers(),
1052 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001053 /*RefQualifierLoc=*/NoLoc,
1054 /*ConstQualifierLoc=*/NoLoc,
1055 /*VolatileQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001056 MutableLoc,
1057 ESpecType, ESpecRange.getBegin(),
1058 DynamicExceptions.data(),
1059 DynamicExceptionRanges.data(),
1060 DynamicExceptions.size(),
1061 NoexceptExpr.isUsable() ?
1062 NoexceptExpr.get() : 0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001063 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001064 TrailingReturnType),
1065 Attr, DeclEndLoc);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001066 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
1067 // It's common to forget that one needs '()' before 'mutable' or the
1068 // result type. Deal with this.
1069 Diag(Tok, diag::err_lambda_missing_parens)
1070 << Tok.is(tok::arrow)
1071 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1072 SourceLocation DeclLoc = Tok.getLocation();
1073 SourceLocation DeclEndLoc = DeclLoc;
1074
1075 // Parse 'mutable', if it's there.
1076 SourceLocation MutableLoc;
1077 if (Tok.is(tok::kw_mutable)) {
1078 MutableLoc = ConsumeToken();
1079 DeclEndLoc = MutableLoc;
1080 }
1081
1082 // Parse the return type, if there is one.
Richard Smith700537c2012-06-12 01:51:59 +00001083 TypeResult TrailingReturnType;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001084 if (Tok.is(tok::arrow)) {
1085 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001086 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001087 if (Range.getEnd().isValid())
1088 DeclEndLoc = Range.getEnd();
1089 }
1090
1091 ParsedAttributes Attr(AttrFactory);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001092 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001093 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001094 /*isAmbiguous=*/false,
1095 /*LParenLoc=*/NoLoc,
1096 /*Params=*/0,
1097 /*NumParams=*/0,
1098 /*EllipsisLoc=*/NoLoc,
1099 /*RParenLoc=*/NoLoc,
1100 /*TypeQuals=*/0,
1101 /*RefQualifierIsLValueRef=*/true,
1102 /*RefQualifierLoc=*/NoLoc,
1103 /*ConstQualifierLoc=*/NoLoc,
1104 /*VolatileQualifierLoc=*/NoLoc,
1105 MutableLoc,
1106 EST_None,
1107 /*ESpecLoc=*/NoLoc,
1108 /*Exceptions=*/0,
1109 /*ExceptionRanges=*/0,
1110 /*NumExceptions=*/0,
1111 /*NoexceptExpr=*/0,
1112 DeclLoc, DeclEndLoc, D,
1113 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001114 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001115 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001116
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001117
Eli Friedman4817cf72012-01-06 03:05:34 +00001118 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1119 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001120 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001121 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001122
Eli Friedman71c80552012-01-05 03:35:19 +00001123 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1124
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001125 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001126 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001127 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001128 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1129 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001130 }
1131
Eli Friedmanc7c97142012-01-04 02:40:39 +00001132 StmtResult Stmt(ParseCompoundStatementBody());
1133 BodyScope.Exit();
1134
Eli Friedman898caf82012-01-04 02:46:53 +00001135 if (!Stmt.isInvalid())
Douglas Gregor63798542012-02-20 19:44:39 +00001136 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
Eli Friedmanc7c97142012-01-04 02:40:39 +00001137
Eli Friedman898caf82012-01-04 02:46:53 +00001138 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1139 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001140}
1141
Chris Lattner29375652006-12-04 18:06:35 +00001142/// ParseCXXCasts - This handles the various ways to cast expressions to another
1143/// type.
1144///
1145/// postfix-expression: [C++ 5.2p1]
1146/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1147/// 'static_cast' '<' type-name '>' '(' expression ')'
1148/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1149/// 'const_cast' '<' type-name '>' '(' expression ')'
1150///
John McCalldadc5752010-08-24 06:29:42 +00001151ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001152 tok::TokenKind Kind = Tok.getKind();
1153 const char *CastName = 0; // For error messages
1154
1155 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001156 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001157 case tok::kw_const_cast: CastName = "const_cast"; break;
1158 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1159 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1160 case tok::kw_static_cast: CastName = "static_cast"; break;
1161 }
1162
1163 SourceLocation OpLoc = ConsumeToken();
1164 SourceLocation LAngleBracketLoc = Tok.getLocation();
1165
Richard Smith55858492011-04-14 21:45:45 +00001166 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1167 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001168 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1169 Token Next = NextToken();
1170 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1171 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1172 }
Richard Smith55858492011-04-14 21:45:45 +00001173
Chris Lattner29375652006-12-04 18:06:35 +00001174 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001175 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001176
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001177 // Parse the common declaration-specifiers piece.
1178 DeclSpec DS(AttrFactory);
1179 ParseSpecifierQualifierList(DS);
1180
1181 // Parse the abstract-declarator, if present.
1182 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1183 ParseDeclarator(DeclaratorInfo);
1184
Chris Lattner29375652006-12-04 18:06:35 +00001185 SourceLocation RAngleBracketLoc = Tok.getLocation();
1186
Alp Toker383d2c42014-01-01 03:08:43 +00001187 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001188 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001189
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001190 SourceLocation LParenLoc, RParenLoc;
1191 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001192
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001193 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001194 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001195
John McCalldadc5752010-08-24 06:29:42 +00001196 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001197
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001198 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001199 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001200
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001201 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001202 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001203 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001204 RAngleBracketLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001205 T.getOpenLocation(), Result.take(),
1206 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001207
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001208 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001209}
Bill Wendling4073ed52007-02-13 01:51:42 +00001210
Sebastian Redlc4704762008-11-11 11:37:55 +00001211/// ParseCXXTypeid - This handles the C++ typeid expression.
1212///
1213/// postfix-expression: [C++ 5.2p1]
1214/// 'typeid' '(' expression ')'
1215/// 'typeid' '(' type-id ')'
1216///
John McCalldadc5752010-08-24 06:29:42 +00001217ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001218 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1219
1220 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001221 SourceLocation LParenLoc, RParenLoc;
1222 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001223
1224 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001225 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001226 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001227 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001228
John McCalldadc5752010-08-24 06:29:42 +00001229 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001230
Richard Smith4f605af2012-08-18 00:55:03 +00001231 // C++0x [expr.typeid]p3:
1232 // When typeid is applied to an expression other than an lvalue of a
1233 // polymorphic class type [...] The expression is an unevaluated
1234 // operand (Clause 5).
1235 //
1236 // Note that we can't tell whether the expression is an lvalue of a
1237 // polymorphic class type until after we've parsed the expression; we
1238 // speculatively assume the subexpression is unevaluated, and fix it up
1239 // later.
1240 //
1241 // We enter the unevaluated context before trying to determine whether we
1242 // have a type-id, because the tentative parse logic will try to resolve
1243 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001244 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1245 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001246
Sebastian Redlc4704762008-11-11 11:37:55 +00001247 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001248 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001249
1250 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001251 T.consumeClose();
1252 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001253 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001254 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001255
1256 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001257 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001258 } else {
1259 Result = ParseExpression();
1260
1261 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001262 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001263 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001264 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001265 T.consumeClose();
1266 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001267 if (RParenLoc.isInvalid())
1268 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001269
Sebastian Redlc4704762008-11-11 11:37:55 +00001270 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001271 Result.release(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001272 }
1273 }
1274
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001275 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001276}
1277
Francois Pichet9f4f2072010-09-08 12:20:18 +00001278/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1279///
1280/// '__uuidof' '(' expression ')'
1281/// '__uuidof' '(' type-id ')'
1282///
1283ExprResult Parser::ParseCXXUuidof() {
1284 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1285
1286 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001287 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001288
1289 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001290 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001291 return ExprError();
1292
1293 ExprResult Result;
1294
1295 if (isTypeIdInParens()) {
1296 TypeResult Ty = ParseTypeName();
1297
1298 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001299 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001300
1301 if (Ty.isInvalid())
1302 return ExprError();
1303
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001304 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1305 Ty.get().getAsOpaquePtr(),
1306 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001307 } else {
1308 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1309 Result = ParseExpression();
1310
1311 // Match the ')'.
1312 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001313 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001314 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001315 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001316
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001317 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1318 /*isType=*/false,
1319 Result.release(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001320 }
1321 }
1322
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001323 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001324}
1325
Douglas Gregore610ada2010-02-24 18:44:31 +00001326/// \brief Parse a C++ pseudo-destructor expression after the base,
1327/// . or -> operator, and nested-name-specifier have already been
1328/// parsed.
1329///
1330/// postfix-expression: [C++ 5.2]
1331/// postfix-expression . pseudo-destructor-name
1332/// postfix-expression -> pseudo-destructor-name
1333///
1334/// pseudo-destructor-name:
1335/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1336/// ::[opt] nested-name-specifier template simple-template-id ::
1337/// ~type-name
1338/// ::[opt] nested-name-specifier[opt] ~type-name
1339///
John McCalldadc5752010-08-24 06:29:42 +00001340ExprResult
Douglas Gregore610ada2010-02-24 18:44:31 +00001341Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1342 tok::TokenKind OpKind,
1343 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001344 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001345 // We're parsing either a pseudo-destructor-name or a dependent
1346 // member access that has the same form as a
1347 // pseudo-destructor-name. We parse both in the same way and let
1348 // the action model sort them out.
1349 //
1350 // Note that the ::[opt] nested-name-specifier[opt] has already
1351 // been parsed, and if there was a simple-template-id, it has
1352 // been coalesced into a template-id annotation token.
1353 UnqualifiedId FirstTypeName;
1354 SourceLocation CCLoc;
1355 if (Tok.is(tok::identifier)) {
1356 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1357 ConsumeToken();
1358 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1359 CCLoc = ConsumeToken();
1360 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001361 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1362 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001363 FirstTypeName.setTemplateId(
1364 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1365 ConsumeToken();
1366 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1367 CCLoc = ConsumeToken();
1368 } else {
1369 FirstTypeName.setIdentifier(0, SourceLocation());
1370 }
1371
1372 // Parse the tilde.
1373 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1374 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001375
1376 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1377 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001378 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001379 if (DS.getTypeSpecType() == TST_error)
1380 return ExprError();
1381 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1382 OpKind, TildeLoc, DS,
1383 Tok.is(tok::l_paren));
1384 }
1385
Douglas Gregore610ada2010-02-24 18:44:31 +00001386 if (!Tok.is(tok::identifier)) {
1387 Diag(Tok, diag::err_destructor_tilde_identifier);
1388 return ExprError();
1389 }
1390
1391 // Parse the second type.
1392 UnqualifiedId SecondTypeName;
1393 IdentifierInfo *Name = Tok.getIdentifierInfo();
1394 SourceLocation NameLoc = ConsumeToken();
1395 SecondTypeName.setIdentifier(Name, NameLoc);
1396
1397 // If there is a '<', the second type name is a template-id. Parse
1398 // it as such.
1399 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001400 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1401 Name, NameLoc,
1402 false, ObjectType, SecondTypeName,
1403 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001404 return ExprError();
1405
John McCallb268a282010-08-23 23:25:46 +00001406 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1407 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001408 SS, FirstTypeName, CCLoc,
1409 TildeLoc, SecondTypeName,
1410 Tok.is(tok::l_paren));
1411}
1412
Bill Wendling4073ed52007-02-13 01:51:42 +00001413/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1414///
1415/// boolean-literal: [C++ 2.13.5]
1416/// 'true'
1417/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001418ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001419 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001420 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001421}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001422
1423/// ParseThrowExpression - This handles the C++ throw expression.
1424///
1425/// throw-expression: [C++ 15]
1426/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001427ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001428 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001429 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001430
Chris Lattner65dd8432008-04-06 06:02:23 +00001431 // If the current token isn't the start of an assignment-expression,
1432 // then the expression is not present. This handles things like:
1433 // "C ? throw : (void)42", which is crazy but legal.
1434 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1435 case tok::semi:
1436 case tok::r_paren:
1437 case tok::r_square:
1438 case tok::r_brace:
1439 case tok::colon:
1440 case tok::comma:
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001441 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001442
Chris Lattner65dd8432008-04-06 06:02:23 +00001443 default:
John McCalldadc5752010-08-24 06:29:42 +00001444 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001445 if (Expr.isInvalid()) return Expr;
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001446 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner65dd8432008-04-06 06:02:23 +00001447 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001448}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001449
1450/// ParseCXXThis - This handles the C++ 'this' pointer.
1451///
1452/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1453/// a non-lvalue expression whose value is the address of the object for which
1454/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001455ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001456 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1457 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001458 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001459}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001460
1461/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1462/// Can be interpreted either as function-style casting ("int(x)")
1463/// or class type construction ("ClassType(x,y,z)")
1464/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001465/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001466///
1467/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001468/// simple-type-specifier '(' expression-list[opt] ')'
1469/// [C++0x] simple-type-specifier braced-init-list
1470/// typename-specifier '(' expression-list[opt] ')'
1471/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001472///
John McCalldadc5752010-08-24 06:29:42 +00001473ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001474Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001475 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001476 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001477
Sebastian Redl3da34892011-06-05 12:23:16 +00001478 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001479 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001480 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001481
Sebastian Redl3da34892011-06-05 12:23:16 +00001482 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001483 ExprResult Init = ParseBraceInitializer();
1484 if (Init.isInvalid())
1485 return Init;
1486 Expr *InitList = Init.take();
1487 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1488 MultiExprArg(&InitList, 1),
1489 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001490 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001491 BalancedDelimiterTracker T(*this, tok::l_paren);
1492 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001493
Benjamin Kramerf0623432012-08-23 22:51:59 +00001494 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001495 CommaLocsTy CommaLocs;
1496
1497 if (Tok.isNot(tok::r_paren)) {
1498 if (ParseExpressionList(Exprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001499 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001500 return ExprError();
1501 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001502 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001503
1504 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001505 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001506
1507 // TypeRep could be null, if it references an invalid typedef.
1508 if (!TypeRep)
1509 return ExprError();
1510
1511 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1512 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001513 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001514 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001515 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001516 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001517}
1518
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001519/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001520///
1521/// condition:
1522/// expression
1523/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001524/// [C++11] type-specifier-seq declarator '=' initializer-clause
1525/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001526/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1527/// '=' assignment-expression
1528///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001529/// \param ExprOut if the condition was parsed as an expression, the parsed
1530/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001531///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001532/// \param DeclOut if the condition was parsed as a declaration, the parsed
1533/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001534///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001535/// \param Loc The location of the start of the statement that requires this
1536/// condition, e.g., the "for" in a for loop.
1537///
1538/// \param ConvertToBoolean Whether the condition expression should be
1539/// converted to a boolean value.
1540///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001541/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001542bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1543 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001544 SourceLocation Loc,
1545 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001546 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001547 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001548 cutOffParsing();
1549 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001550 }
1551
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001552 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001553 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001554
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001555 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001556 ProhibitAttributes(attrs);
1557
Douglas Gregore60e41a2010-05-06 17:25:47 +00001558 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001559 ExprOut = ParseExpression(); // expression
1560 DeclOut = 0;
1561 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001562 return true;
1563
1564 // If required, convert to a boolean value.
1565 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001566 ExprOut
1567 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1568 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001569 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001570
1571 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001572 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001573 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001574 ParseSpecifierQualifierList(DS);
1575
1576 // declarator
1577 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1578 ParseDeclarator(DeclaratorInfo);
1579
1580 // simple-asm-expr[opt]
1581 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001582 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001583 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001584 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001585 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001586 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001587 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001588 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001589 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001590 }
1591
1592 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001593 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001594
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001595 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001596 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001597 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001598 DeclOut = Dcl.get();
1599 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001600
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001601 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001602 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001603 bool CopyInitialization = isTokenEqualOrEqualTypo();
1604 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001605 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001606
1607 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001608 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001609 Diag(Tok.getLocation(),
1610 diag::warn_cxx98_compat_generalized_initializer_lists);
1611 InitExpr = ParseBraceInitializer();
1612 } else if (CopyInitialization) {
1613 InitExpr = ParseAssignmentExpression();
1614 } else if (Tok.is(tok::l_paren)) {
1615 // This was probably an attempt to initialize the variable.
1616 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001617 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001618 RParen = ConsumeParen();
1619 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1620 diag::err_expected_init_in_condition_lparen)
1621 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001622 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001623 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1624 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001625 }
Richard Smith2a15b742012-02-22 06:49:09 +00001626
1627 if (!InitExpr.isInvalid())
1628 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001629 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001630 else
1631 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001632
Douglas Gregore60e41a2010-05-06 17:25:47 +00001633 // FIXME: Build a reference to this declaration? Convert it to bool?
1634 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001635
1636 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001637
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001638 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001639}
1640
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001641/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1642/// This should only be called when the current token is known to be part of
1643/// simple-type-specifier.
1644///
1645/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001646/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001647/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1648/// char
1649/// wchar_t
1650/// bool
1651/// short
1652/// int
1653/// long
1654/// signed
1655/// unsigned
1656/// float
1657/// double
1658/// void
1659/// [GNU] typeof-specifier
1660/// [C++0x] auto [TODO]
1661///
1662/// type-name:
1663/// class-name
1664/// enum-name
1665/// typedef-name
1666///
1667void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1668 DS.SetRangeStart(Tok.getLocation());
1669 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001670 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001671 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001672
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001673 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001674 case tok::identifier: // foo::bar
1675 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001676 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001677 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001678 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001679
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001680 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001681 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001682 if (getTypeAnnotation(Tok))
1683 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1684 getTypeAnnotation(Tok));
1685 else
1686 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001687
1688 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1689 ConsumeToken();
1690
1691 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1692 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1693 // Objective-C interface. If we don't have Objective-C or a '<', this is
1694 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001695 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001696 ParseObjCProtocolQualifiers(DS);
1697
1698 DS.Finish(Diags, PP);
1699 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001702 // builtin types
1703 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00001704 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001705 break;
1706 case tok::kw_long:
John McCall49bfce42009-08-03 20:12:06 +00001707 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001708 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001709 case tok::kw___int64:
1710 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1711 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001712 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001713 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001714 break;
1715 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001716 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001717 break;
1718 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00001719 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001720 break;
1721 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00001722 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001723 break;
1724 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00001725 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001726 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001727 case tok::kw___int128:
1728 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1729 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001730 case tok::kw_half:
1731 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1732 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001733 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00001734 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001735 break;
1736 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00001737 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001738 break;
1739 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00001740 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001741 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001742 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00001743 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001744 break;
1745 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00001746 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001747 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001748 case tok::kw_bool:
John McCall49bfce42009-08-03 20:12:06 +00001749 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001750 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001751 case tok::annot_decltype:
1752 case tok::kw_decltype:
1753 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1754 return DS.Finish(Diags, PP);
Mike Stump11289f42009-09-09 15:08:12 +00001755
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001756 // GNU typeof support.
1757 case tok::kw_typeof:
1758 ParseTypeofSpecifier(DS);
Douglas Gregore3e01a22009-04-01 22:41:11 +00001759 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001760 return;
1761 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001762 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001763 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1764 else
1765 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001766 ConsumeToken();
Douglas Gregore3e01a22009-04-01 22:41:11 +00001767 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001768}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001769
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001770/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1771/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1772/// e.g., "const short int". Note that the DeclSpec is *not* finished
1773/// by parsing the type-specifier-seq, because these sequences are
1774/// typically followed by some form of declarator. Returns true and
1775/// emits diagnostics if this is not a type-specifier-seq, false
1776/// otherwise.
1777///
1778/// type-specifier-seq: [C++ 8.1]
1779/// type-specifier type-specifier-seq[opt]
1780///
1781bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001782 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Douglas Gregor40d732f2010-02-24 23:13:13 +00001783 DS.Finish(Diags, PP);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001784 return false;
1785}
1786
Douglas Gregor7861a802009-11-03 01:35:08 +00001787/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1788/// some form.
1789///
1790/// This routine is invoked when a '<' is encountered after an identifier or
1791/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1792/// whether the unqualified-id is actually a template-id. This routine will
1793/// then parse the template arguments and form the appropriate template-id to
1794/// return to the caller.
1795///
1796/// \param SS the nested-name-specifier that precedes this template-id, if
1797/// we're actually parsing a qualified-id.
1798///
1799/// \param Name for constructor and destructor names, this is the actual
1800/// identifier that may be a template-name.
1801///
1802/// \param NameLoc the location of the class-name in a constructor or
1803/// destructor.
1804///
1805/// \param EnteringContext whether we're entering the scope of the
1806/// nested-name-specifier.
1807///
Douglas Gregor127ea592009-11-03 21:24:04 +00001808/// \param ObjectType if this unqualified-id occurs within a member access
1809/// expression, the type of the base object whose member is being accessed.
1810///
Douglas Gregor7861a802009-11-03 01:35:08 +00001811/// \param Id as input, describes the template-name or operator-function-id
1812/// that precedes the '<'. If template arguments were parsed successfully,
1813/// will be updated with the template-id.
1814///
Douglas Gregore610ada2010-02-24 18:44:31 +00001815/// \param AssumeTemplateId When true, this routine will assume that the name
1816/// refers to a template without performing name lookup to verify.
1817///
Douglas Gregor7861a802009-11-03 01:35:08 +00001818/// \returns true if a parse error occurred, false otherwise.
1819bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001820 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001821 IdentifierInfo *Name,
1822 SourceLocation NameLoc,
1823 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001824 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001825 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001826 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001827 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1828 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001829
1830 TemplateTy Template;
1831 TemplateNameKind TNK = TNK_Non_template;
1832 switch (Id.getKind()) {
1833 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001834 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001835 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001836 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001837 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001838 Id, ObjectType, EnteringContext,
1839 Template);
1840 if (TNK == TNK_Non_template)
1841 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001842 } else {
1843 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001844 TNK = Actions.isTemplateName(getCurScope(), SS,
1845 TemplateKWLoc.isValid(), Id,
1846 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001847 MemberOfUnknownSpecialization);
1848
1849 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1850 ObjectType && IsTemplateArgumentList()) {
1851 // We have something like t->getAs<T>(), where getAs is a
1852 // member of an unknown specialization. However, this will only
1853 // parse correctly as a template, so suggest the keyword 'template'
1854 // before 'getAs' and treat this as a dependent template name.
1855 std::string Name;
1856 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1857 Name = Id.Identifier->getName();
1858 else {
1859 Name = "operator ";
1860 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1861 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1862 else
1863 Name += Id.Identifier->getName();
1864 }
1865 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1866 << Name
1867 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001868 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1869 SS, TemplateKWLoc, Id,
1870 ObjectType, EnteringContext,
1871 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001872 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001873 return true;
1874 }
1875 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001876 break;
1877
Douglas Gregor3cf81312009-11-03 23:16:33 +00001878 case UnqualifiedId::IK_ConstructorName: {
1879 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001880 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001881 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001882 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1883 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001884 EnteringContext, Template,
1885 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001886 break;
1887 }
1888
Douglas Gregor3cf81312009-11-03 23:16:33 +00001889 case UnqualifiedId::IK_DestructorName: {
1890 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001891 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001892 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001893 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001894 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1895 SS, TemplateKWLoc, TemplateName,
1896 ObjectType, EnteringContext,
1897 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001898 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001899 return true;
1900 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001901 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1902 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001903 EnteringContext, Template,
1904 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001905
John McCallba7bf592010-08-24 05:47:05 +00001906 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001907 Diag(NameLoc, diag::err_destructor_template_id)
1908 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001909 return true;
1910 }
1911 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001912 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001913 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001914
1915 default:
1916 return false;
1917 }
1918
1919 if (TNK == TNK_Non_template)
1920 return false;
1921
1922 // Parse the enclosed template argument list.
1923 SourceLocation LAngleLoc, RAngleLoc;
1924 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00001925 if (Tok.is(tok::less) &&
1926 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00001927 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001928 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00001929 RAngleLoc))
1930 return true;
1931
1932 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00001933 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1934 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001935 // Form a parsed representation of the template-id to be stored in the
1936 // UnqualifiedId.
1937 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00001938 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00001939
Richard Smith72bfbd82013-12-04 00:28:23 +00001940 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00001941 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1942 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001943 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00001944 TemplateId->TemplateNameLoc = Id.StartLocation;
1945 } else {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001946 TemplateId->Name = 0;
1947 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1948 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00001949 }
1950
Douglas Gregore7c20652011-03-02 00:47:37 +00001951 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00001952 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00001953 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00001954 TemplateId->Kind = TNK;
1955 TemplateId->LAngleLoc = LAngleLoc;
1956 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001957 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00001958 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001959 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00001960 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00001961
1962 Id.setTemplateId(TemplateId);
1963 return false;
1964 }
1965
1966 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001967 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00001968
Douglas Gregor7861a802009-11-03 01:35:08 +00001969 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00001970 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001971 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1972 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00001973 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1974 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00001975 if (Type.isInvalid())
1976 return true;
1977
1978 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1979 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1980 else
1981 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1982
1983 return false;
1984}
1985
Douglas Gregor71395fa2009-11-04 00:56:37 +00001986/// \brief Parse an operator-function-id or conversion-function-id as part
1987/// of a C++ unqualified-id.
1988///
1989/// This routine is responsible only for parsing the operator-function-id or
1990/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00001991///
1992/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00001993/// operator-function-id: [C++ 13.5]
1994/// 'operator' operator
1995///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001996/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00001997/// new delete new[] delete[]
1998/// + - * / % ^ & | ~
1999/// ! = < > += -= *= /= %=
2000/// ^= &= |= << >> >>= <<= == !=
2001/// <= >= && || ++ -- , ->* ->
2002/// () []
2003///
2004/// conversion-function-id: [C++ 12.3.2]
2005/// operator conversion-type-id
2006///
2007/// conversion-type-id:
2008/// type-specifier-seq conversion-declarator[opt]
2009///
2010/// conversion-declarator:
2011/// ptr-operator conversion-declarator[opt]
2012/// \endcode
2013///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002014/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002015/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2016///
2017/// \param EnteringContext whether we are entering the scope of the
2018/// nested-name-specifier.
2019///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002020/// \param ObjectType if this unqualified-id occurs within a member access
2021/// expression, the type of the base object whose member is being accessed.
2022///
2023/// \param Result on a successful parse, contains the parsed unqualified-id.
2024///
2025/// \returns true if parsing fails, false otherwise.
2026bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002027 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002028 UnqualifiedId &Result) {
2029 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2030
2031 // Consume the 'operator' keyword.
2032 SourceLocation KeywordLoc = ConsumeToken();
2033
2034 // Determine what kind of operator name we have.
2035 unsigned SymbolIdx = 0;
2036 SourceLocation SymbolLocations[3];
2037 OverloadedOperatorKind Op = OO_None;
2038 switch (Tok.getKind()) {
2039 case tok::kw_new:
2040 case tok::kw_delete: {
2041 bool isNew = Tok.getKind() == tok::kw_new;
2042 // Consume the 'new' or 'delete'.
2043 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002044 // Check for array new/delete.
2045 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002046 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002047 // Consume the '[' and ']'.
2048 BalancedDelimiterTracker T(*this, tok::l_square);
2049 T.consumeOpen();
2050 T.consumeClose();
2051 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002052 return true;
2053
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002054 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2055 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002056 Op = isNew? OO_Array_New : OO_Array_Delete;
2057 } else {
2058 Op = isNew? OO_New : OO_Delete;
2059 }
2060 break;
2061 }
2062
2063#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2064 case tok::Token: \
2065 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2066 Op = OO_##Name; \
2067 break;
2068#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2069#include "clang/Basic/OperatorKinds.def"
2070
2071 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002072 // Consume the '(' and ')'.
2073 BalancedDelimiterTracker T(*this, tok::l_paren);
2074 T.consumeOpen();
2075 T.consumeClose();
2076 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002077 return true;
2078
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002079 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2080 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002081 Op = OO_Call;
2082 break;
2083 }
2084
2085 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002086 // Consume the '[' and ']'.
2087 BalancedDelimiterTracker T(*this, tok::l_square);
2088 T.consumeOpen();
2089 T.consumeClose();
2090 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002091 return true;
2092
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002093 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2094 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002095 Op = OO_Subscript;
2096 break;
2097 }
2098
2099 case tok::code_completion: {
2100 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002101 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002102 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002103 // Don't try to parse any further.
2104 return true;
2105 }
2106
2107 default:
2108 break;
2109 }
2110
2111 if (Op != OO_None) {
2112 // We have parsed an operator-function-id.
2113 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2114 return false;
2115 }
Alexis Hunt34458502009-11-28 04:44:28 +00002116
2117 // Parse a literal-operator-id.
2118 //
Richard Smith6f212062012-10-20 08:41:10 +00002119 // literal-operator-id: C++11 [over.literal]
2120 // operator string-literal identifier
2121 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002122
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002123 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002124 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002125
Richard Smith7d182a72012-03-08 23:06:02 +00002126 SourceLocation DiagLoc;
2127 unsigned DiagId = 0;
2128
2129 // We're past translation phase 6, so perform string literal concatenation
2130 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002131 SmallVector<Token, 4> Toks;
2132 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002133 while (isTokenStringLiteral()) {
2134 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002135 // C++11 [over.literal]p1:
2136 // The string-literal or user-defined-string-literal in a
2137 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002138 DiagLoc = Tok.getLocation();
2139 DiagId = diag::err_literal_operator_string_prefix;
2140 }
2141 Toks.push_back(Tok);
2142 TokLocs.push_back(ConsumeStringToken());
2143 }
2144
2145 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
2146 if (Literal.hadError)
2147 return true;
2148
2149 // Grab the literal operator's suffix, which will be either the next token
2150 // or a ud-suffix from the string literal.
2151 IdentifierInfo *II = 0;
2152 SourceLocation SuffixLoc;
2153 if (!Literal.getUDSuffix().empty()) {
2154 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2155 SuffixLoc =
2156 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2157 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002158 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002159 } else if (Tok.is(tok::identifier)) {
2160 II = Tok.getIdentifierInfo();
2161 SuffixLoc = ConsumeToken();
2162 TokLocs.push_back(SuffixLoc);
2163 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002164 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002165 return true;
2166 }
2167
Richard Smith7d182a72012-03-08 23:06:02 +00002168 // The string literal must be empty.
2169 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002170 // C++11 [over.literal]p1:
2171 // The string-literal or user-defined-string-literal in a
2172 // literal-operator-id shall [...] contain no characters
2173 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002174 DiagLoc = TokLocs.front();
2175 DiagId = diag::err_literal_operator_string_not_empty;
2176 }
2177
2178 if (DiagId) {
2179 // This isn't a valid literal-operator-id, but we think we know
2180 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002181 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002182 Str += "\"\" ";
2183 Str += II->getName();
2184 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2185 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2186 }
2187
2188 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002189
2190 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002191 }
Richard Smithd091dc12013-12-05 00:58:33 +00002192
Douglas Gregor71395fa2009-11-04 00:56:37 +00002193 // Parse a conversion-function-id.
2194 //
2195 // conversion-function-id: [C++ 12.3.2]
2196 // operator conversion-type-id
2197 //
2198 // conversion-type-id:
2199 // type-specifier-seq conversion-declarator[opt]
2200 //
2201 // conversion-declarator:
2202 // ptr-operator conversion-declarator[opt]
2203
2204 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002205 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002206 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002207 return true;
2208
2209 // Parse the conversion-declarator, which is merely a sequence of
2210 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002211 Declarator D(DS, Declarator::ConversionIdContext);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002212 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2213
2214 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002215 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002216 if (Ty.isInvalid())
2217 return true;
2218
2219 // Note that this is a conversion-function-id.
2220 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2221 D.getSourceRange().getEnd());
2222 return false;
2223}
2224
2225/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2226/// name of an entity.
2227///
2228/// \code
2229/// unqualified-id: [C++ expr.prim.general]
2230/// identifier
2231/// operator-function-id
2232/// conversion-function-id
2233/// [C++0x] literal-operator-id [TODO]
2234/// ~ class-name
2235/// template-id
2236///
2237/// \endcode
2238///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002239/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002240/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2241///
2242/// \param EnteringContext whether we are entering the scope of the
2243/// nested-name-specifier.
2244///
Douglas Gregor7861a802009-11-03 01:35:08 +00002245/// \param AllowDestructorName whether we allow parsing of a destructor name.
2246///
2247/// \param AllowConstructorName whether we allow parsing a constructor name.
2248///
Douglas Gregor127ea592009-11-03 21:24:04 +00002249/// \param ObjectType if this unqualified-id occurs within a member access
2250/// expression, the type of the base object whose member is being accessed.
2251///
Douglas Gregor7861a802009-11-03 01:35:08 +00002252/// \param Result on a successful parse, contains the parsed unqualified-id.
2253///
2254/// \returns true if parsing fails, false otherwise.
2255bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2256 bool AllowDestructorName,
2257 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002258 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002259 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002260 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002261
2262 // Handle 'A::template B'. This is for template-ids which have not
2263 // already been annotated by ParseOptionalCXXScopeSpecifier().
2264 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002265 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002266 (ObjectType || SS.isSet())) {
2267 TemplateSpecified = true;
2268 TemplateKWLoc = ConsumeToken();
2269 }
2270
Douglas Gregor7861a802009-11-03 01:35:08 +00002271 // unqualified-id:
2272 // identifier
2273 // template-id (when it hasn't already been annotated)
2274 if (Tok.is(tok::identifier)) {
2275 // Consume the identifier.
2276 IdentifierInfo *Id = Tok.getIdentifierInfo();
2277 SourceLocation IdLoc = ConsumeToken();
2278
David Blaikiebbafb8a2012-03-11 07:00:24 +00002279 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002280 // If we're not in C++, only identifiers matter. Record the
2281 // identifier and return.
2282 Result.setIdentifier(Id, IdLoc);
2283 return false;
2284 }
2285
Douglas Gregor7861a802009-11-03 01:35:08 +00002286 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002287 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002288 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002289 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2290 &SS, false, false,
2291 ParsedType(),
2292 /*IsCtorOrDtorName=*/true,
2293 /*NonTrivialTypeSourceInfo=*/true);
2294 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002295 } else {
2296 // We have parsed an identifier.
2297 Result.setIdentifier(Id, IdLoc);
2298 }
2299
2300 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002301 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002302 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2303 EnteringContext, ObjectType,
2304 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002305
2306 return false;
2307 }
2308
2309 // unqualified-id:
2310 // template-id (already parsed and annotated)
2311 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002312 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002313
2314 // If the template-name names the current class, then this is a constructor
2315 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002316 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002317 if (SS.isSet()) {
2318 // C++ [class.qual]p2 specifies that a qualified template-name
2319 // is taken as the constructor name where a constructor can be
2320 // declared. Thus, the template arguments are extraneous, so
2321 // complain about them and remove them entirely.
2322 Diag(TemplateId->TemplateNameLoc,
2323 diag::err_out_of_line_constructor_template_id)
2324 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002325 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002326 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002327 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2328 TemplateId->TemplateNameLoc,
2329 getCurScope(),
2330 &SS, false, false,
2331 ParsedType(),
2332 /*IsCtorOrDtorName=*/true,
2333 /*NontrivialTypeSourceInfo=*/true);
2334 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002335 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002336 ConsumeToken();
2337 return false;
2338 }
2339
2340 Result.setConstructorTemplateId(TemplateId);
2341 ConsumeToken();
2342 return false;
2343 }
2344
Douglas Gregor7861a802009-11-03 01:35:08 +00002345 // We have already parsed a template-id; consume the annotation token as
2346 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002347 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002348 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002349 ConsumeToken();
2350 return false;
2351 }
2352
2353 // unqualified-id:
2354 // operator-function-id
2355 // conversion-function-id
2356 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002357 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002358 return true;
2359
Alexis Hunted0530f2009-11-28 08:58:14 +00002360 // If we have an operator-function-id or a literal-operator-id and the next
2361 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002362 //
2363 // template-id:
2364 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002365 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2366 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002367 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002368 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2369 0, SourceLocation(),
2370 EnteringContext, ObjectType,
2371 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002372
Douglas Gregor7861a802009-11-03 01:35:08 +00002373 return false;
2374 }
2375
David Blaikiebbafb8a2012-03-11 07:00:24 +00002376 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002377 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002378 // C++ [expr.unary.op]p10:
2379 // There is an ambiguity in the unary-expression ~X(), where X is a
2380 // class-name. The ambiguity is resolved in favor of treating ~ as a
2381 // unary complement rather than treating ~X as referring to a destructor.
2382
2383 // Parse the '~'.
2384 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002385
2386 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2387 DeclSpec DS(AttrFactory);
2388 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2389 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2390 Result.setDestructorName(TildeLoc, Type, EndLoc);
2391 return false;
2392 }
2393 return true;
2394 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002395
2396 // Parse the class-name.
2397 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002398 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002399 return true;
2400 }
2401
2402 // Parse the class-name (or template-name in a simple-template-id).
2403 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2404 SourceLocation ClassNameLoc = ConsumeToken();
2405
Douglas Gregorb22ee882010-05-05 05:58:24 +00002406 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002407 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002408 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2409 ClassName, ClassNameLoc,
2410 EnteringContext, ObjectType,
2411 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002412 }
2413
Douglas Gregor7861a802009-11-03 01:35:08 +00002414 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002415 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2416 ClassNameLoc, getCurScope(),
2417 SS, ObjectType,
2418 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002419 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002420 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002421
Douglas Gregor7861a802009-11-03 01:35:08 +00002422 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002423 return false;
2424 }
2425
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002426 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002427 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002428 return true;
2429}
2430
Sebastian Redlbd150f42008-11-21 19:14:01 +00002431/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2432/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002433///
Chris Lattner109faf22009-01-04 21:25:24 +00002434/// This method is called to parse the new expression after the optional :: has
2435/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2436/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002437///
2438/// new-expression:
2439/// '::'[opt] 'new' new-placement[opt] new-type-id
2440/// new-initializer[opt]
2441/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2442/// new-initializer[opt]
2443///
2444/// new-placement:
2445/// '(' expression-list ')'
2446///
Sebastian Redl351bb782008-12-02 14:43:59 +00002447/// new-type-id:
2448/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002449/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002450///
2451/// new-declarator:
2452/// ptr-operator new-declarator[opt]
2453/// direct-new-declarator
2454///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002455/// new-initializer:
2456/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002457/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002458///
John McCalldadc5752010-08-24 06:29:42 +00002459ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002460Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2461 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2462 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002463
2464 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2465 // second form of new-expression. It can't be a new-type-id.
2466
Benjamin Kramerf0623432012-08-23 22:51:59 +00002467 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002468 SourceLocation PlacementLParen, PlacementRParen;
2469
Douglas Gregorf2753b32010-07-13 15:54:32 +00002470 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002471 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002472 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002473 if (Tok.is(tok::l_paren)) {
2474 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002475 BalancedDelimiterTracker T(*this, tok::l_paren);
2476 T.consumeOpen();
2477 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002478 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002479 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002480 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002481 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002482
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002483 T.consumeClose();
2484 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002485 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002486 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002487 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002488 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002489
Sebastian Redl351bb782008-12-02 14:43:59 +00002490 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002491 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002492 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002493 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002494 } else {
2495 // We still need the type.
2496 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002497 BalancedDelimiterTracker T(*this, tok::l_paren);
2498 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002499 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002500 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002501 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002502 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002503 T.consumeClose();
2504 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002505 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002506 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002507 if (ParseCXXTypeSpecifierSeq(DS))
2508 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002509 else {
2510 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002511 ParseDeclaratorInternal(DeclaratorInfo,
2512 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002513 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002514 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002515 }
2516 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002517 // A new-type-id is a simplified type-id, where essentially the
2518 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002519 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002520 if (ParseCXXTypeSpecifierSeq(DS))
2521 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002522 else {
2523 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002524 ParseDeclaratorInternal(DeclaratorInfo,
2525 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002526 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002527 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002528 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002529 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002530 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002531 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002532
Sebastian Redl6047f072012-02-16 12:22:20 +00002533 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002534
2535 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002536 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002537 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002538 BalancedDelimiterTracker T(*this, tok::l_paren);
2539 T.consumeOpen();
2540 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002541 if (Tok.isNot(tok::r_paren)) {
2542 CommaLocsTy CommaLocs;
Sebastian Redl351bb782008-12-02 14:43:59 +00002543 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002544 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002545 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002546 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002547 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002548 T.consumeClose();
2549 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002550 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002551 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002552 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002553 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002554 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2555 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002556 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002557 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002558 Diag(Tok.getLocation(),
2559 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002560 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002561 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002562 if (Initializer.isInvalid())
2563 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002564
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002565 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002566 PlacementArgs, PlacementRParen,
Sebastian Redl6047f072012-02-16 12:22:20 +00002567 TypeIdParens, DeclaratorInfo, Initializer.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002568}
2569
Sebastian Redlbd150f42008-11-21 19:14:01 +00002570/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2571/// passed to ParseDeclaratorInternal.
2572///
2573/// direct-new-declarator:
2574/// '[' expression ']'
2575/// direct-new-declarator '[' constant-expression ']'
2576///
Chris Lattner109faf22009-01-04 21:25:24 +00002577void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002578 // Parse the array dimensions.
2579 bool first = true;
2580 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002581 // An array-size expression can't start with a lambda.
2582 if (CheckProhibitedCXX11Attribute())
2583 continue;
2584
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002585 BalancedDelimiterTracker T(*this, tok::l_square);
2586 T.consumeOpen();
2587
John McCalldadc5752010-08-24 06:29:42 +00002588 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002589 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002590 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002591 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002592 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002593 return;
2594 }
2595 first = false;
2596
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002597 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002598
Bill Wendling44426052012-12-20 19:22:21 +00002599 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002600 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002601 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002602
John McCall084e83d2011-03-24 11:26:52 +00002603 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002604 /*static=*/false, /*star=*/false,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002605 Size.release(),
2606 T.getOpenLocation(),
2607 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002608 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002609
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002610 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002611 return;
2612 }
2613}
2614
2615/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2616/// This ambiguity appears in the syntax of the C++ new operator.
2617///
2618/// new-expression:
2619/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2620/// new-initializer[opt]
2621///
2622/// new-placement:
2623/// '(' expression-list ')'
2624///
John McCall37ad5512010-08-23 06:44:23 +00002625bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002627 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002628 // The '(' was already consumed.
2629 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002630 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002631 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002632 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002633 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002634 }
2635
2636 // It's not a type, it has to be an expression list.
2637 // Discard the comma locations - ActOnCXXNew has enough parameters.
2638 CommaLocsTy CommaLocs;
2639 return ParseExpressionList(PlacementArgs, CommaLocs);
2640}
2641
2642/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2643/// to free memory allocated by new.
2644///
Chris Lattner109faf22009-01-04 21:25:24 +00002645/// This method is called to parse the 'delete' expression after the optional
2646/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2647/// and "Start" is its location. Otherwise, "Start" is the location of the
2648/// 'delete' token.
2649///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002650/// delete-expression:
2651/// '::'[opt] 'delete' cast-expression
2652/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002653ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002654Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2655 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2656 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002657
2658 // Array delete?
2659 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002660 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002661 // C++11 [expr.delete]p1:
2662 // Whenever the delete keyword is followed by empty square brackets, it
2663 // shall be interpreted as [array delete].
2664 // [Footnote: A lambda expression with a lambda-introducer that consists
2665 // of empty square brackets can follow the delete keyword if
2666 // the lambda expression is enclosed in parentheses.]
2667 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2668 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002669 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002670 BalancedDelimiterTracker T(*this, tok::l_square);
2671
2672 T.consumeOpen();
2673 T.consumeClose();
2674 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002675 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002676 }
2677
John McCalldadc5752010-08-24 06:29:42 +00002678 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002679 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002680 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002681
John McCallb268a282010-08-23 23:25:46 +00002682 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002683}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002684
Douglas Gregor29c42f22012-02-24 07:38:34 +00002685static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2686 switch (kind) {
2687 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002688#define TYPE_TRAIT_1(Spelling, Name, Key) \
2689case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002690#define TYPE_TRAIT_2(Spelling, Name, Key) \
2691case tok::kw_ ## Spelling: return BTT_ ## Name;
2692#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002693#define TYPE_TRAIT_N(Spelling, Name, Key) \
2694 case tok::kw_ ## Spelling: return TT_ ## Name;
2695#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002696 }
2697}
2698
John Wiegley6242b6a2011-04-28 00:16:57 +00002699static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2700 switch(kind) {
2701 default: llvm_unreachable("Not a known binary type trait");
2702 case tok::kw___array_rank: return ATT_ArrayRank;
2703 case tok::kw___array_extent: return ATT_ArrayExtent;
2704 }
2705}
2706
John Wiegleyf9f65842011-04-25 06:54:41 +00002707static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2708 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002709 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002710 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2711 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2712 }
2713}
2714
Alp Toker40f9b1c2013-12-12 21:23:03 +00002715static unsigned TypeTraitArity(tok::TokenKind kind) {
2716 switch (kind) {
2717 default: llvm_unreachable("Not a known type trait");
2718#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2719#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002720 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002721}
2722
Douglas Gregor29c42f22012-02-24 07:38:34 +00002723/// \brief Parse the built-in type-trait pseudo-functions that allow
2724/// implementation of the TR1/C++11 type traits templates.
2725///
2726/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002727/// unary-type-trait '(' type-id ')'
2728/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002729/// type-trait '(' type-id-seq ')'
2730///
2731/// type-id-seq:
2732/// type-id ...[opt] type-id-seq[opt]
2733///
2734ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002735 tok::TokenKind Kind = Tok.getKind();
2736 unsigned Arity = TypeTraitArity(Kind);
2737
Douglas Gregor29c42f22012-02-24 07:38:34 +00002738 SourceLocation Loc = ConsumeToken();
2739
2740 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002741 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002742 return ExprError();
2743
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002744 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002745 do {
2746 // Parse the next type.
2747 TypeResult Ty = ParseTypeName();
2748 if (Ty.isInvalid()) {
2749 Parens.skipToEnd();
2750 return ExprError();
2751 }
2752
2753 // Parse the ellipsis, if present.
2754 if (Tok.is(tok::ellipsis)) {
2755 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2756 if (Ty.isInvalid()) {
2757 Parens.skipToEnd();
2758 return ExprError();
2759 }
2760 }
2761
2762 // Add this type to the list of arguments.
2763 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00002764 } while (TryConsumeToken(tok::comma));
2765
Douglas Gregor29c42f22012-02-24 07:38:34 +00002766 if (Parens.consumeClose())
2767 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002768
2769 SourceLocation EndLoc = Parens.getCloseLocation();
2770
2771 if (Arity && Args.size() != Arity) {
2772 Diag(EndLoc, diag::err_type_trait_arity)
2773 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2774 return ExprError();
2775 }
2776
2777 if (!Arity && Args.empty()) {
2778 Diag(EndLoc, diag::err_type_trait_arity)
2779 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2780 return ExprError();
2781 }
2782
Alp Toker88f64e62013-12-13 21:19:30 +00002783 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00002784}
2785
John Wiegley6242b6a2011-04-28 00:16:57 +00002786/// ParseArrayTypeTrait - Parse the built-in array type-trait
2787/// pseudo-functions.
2788///
2789/// primary-expression:
2790/// [Embarcadero] '__array_rank' '(' type-id ')'
2791/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2792///
2793ExprResult Parser::ParseArrayTypeTrait() {
2794 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2795 SourceLocation Loc = ConsumeToken();
2796
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002797 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002798 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00002799 return ExprError();
2800
2801 TypeResult Ty = ParseTypeName();
2802 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002803 SkipUntil(tok::comma, StopAtSemi);
2804 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002805 return ExprError();
2806 }
2807
2808 switch (ATT) {
2809 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002810 T.consumeClose();
2811 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2812 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002813 }
2814 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00002815 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002816 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002817 return ExprError();
2818 }
2819
2820 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002821 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002822
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002823 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2824 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002825 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002826 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002827 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002828}
2829
John Wiegleyf9f65842011-04-25 06:54:41 +00002830/// ParseExpressionTrait - Parse built-in expression-trait
2831/// pseudo-functions like __is_lvalue_expr( xxx ).
2832///
2833/// primary-expression:
2834/// [Embarcadero] expression-trait '(' expression ')'
2835///
2836ExprResult Parser::ParseExpressionTrait() {
2837 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2838 SourceLocation Loc = ConsumeToken();
2839
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002840 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002841 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00002842 return ExprError();
2843
2844 ExprResult Expr = ParseExpression();
2845
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002846 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002847
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002848 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2849 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002850}
2851
2852
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002853/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2854/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2855/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002856ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002857Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002858 ParsedType &CastTy,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002859 BalancedDelimiterTracker &Tracker) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002860 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002861 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2862 assert(isTypeIdInParens() && "Not a type-id!");
2863
John McCalldadc5752010-08-24 06:29:42 +00002864 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00002865 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002866
2867 // We need to disambiguate a very ugly part of the C++ syntax:
2868 //
2869 // (T())x; - type-id
2870 // (T())*x; - type-id
2871 // (T())/x; - expression
2872 // (T()); - expression
2873 //
2874 // The bad news is that we cannot use the specialized tentative parser, since
2875 // it can only verify that the thing inside the parens can be parsed as
2876 // type-id, it is not useful for determining the context past the parens.
2877 //
2878 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00002879 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002880 //
2881 // It uses a scheme similar to parsing inline methods. The parenthesized
2882 // tokens are cached, the context that follows is determined (possibly by
2883 // parsing a cast-expression), and then we re-introduce the cached tokens
2884 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002885
Mike Stump11289f42009-09-09 15:08:12 +00002886 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002887 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002888
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002889 // Store the tokens of the parentheses. We will parse them after we determine
2890 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00002891 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002892 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002893 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002894 return ExprError();
2895 }
2896
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002897 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002898 ParseAs = CompoundLiteral;
2899 } else {
2900 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00002901 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2902 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2903 NotCastExpr = true;
2904 } else {
2905 // Try parsing the cast-expression that may follow.
2906 // If it is not a cast-expression, NotCastExpr will be true and no token
2907 // will be consumed.
2908 Result = ParseCastExpression(false/*isUnaryExpression*/,
2909 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00002910 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002911 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00002912 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00002913 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002914
2915 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2916 // an expression.
2917 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002918 }
2919
Mike Stump11289f42009-09-09 15:08:12 +00002920 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002921 Toks.push_back(Tok);
2922 // Re-enter the stored parenthesized tokens into the token stream, so we may
2923 // parse them now.
2924 PP.EnterTokenStream(Toks.data(), Toks.size(),
2925 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2926 // Drop the current token and bring the first cached one. It's the same token
2927 // as when we entered this function.
2928 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002929
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002930 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002931 // Parse the type declarator.
2932 DeclSpec DS(AttrFactory);
2933 ParseSpecifierQualifierList(DS);
2934 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2935 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002936
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002937 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002938 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002939
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002940 if (ParseAs == CompoundLiteral) {
2941 ExprType = CompoundLiteral;
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002942 TypeResult Ty = ParseTypeName();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002943 return ParseCompoundLiteralExpression(Ty.get(),
2944 Tracker.getOpenLocation(),
2945 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002946 }
Mike Stump11289f42009-09-09 15:08:12 +00002947
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002948 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2949 assert(ParseAs == CastExpr);
2950
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002951 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002952 return ExprError();
2953
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002954 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002955 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002956 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2957 DeclaratorInfo, CastTy,
2958 Tracker.getCloseLocation(), Result.take());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002959 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002960 }
Mike Stump11289f42009-09-09 15:08:12 +00002961
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002962 // Not a compound literal, and not followed by a cast-expression.
2963 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002964
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002965 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002966 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002967 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002968 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
2969 Tok.getLocation(), Result.take());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002970
2971 // Match the ')'.
2972 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002973 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002974 return ExprError();
2975 }
Mike Stump11289f42009-09-09 15:08:12 +00002976
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002977 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002978 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002979}