blob: d4a83fb0c9c389813fb7a7d4a849a17263c54083 [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//===----------------------------------------------------------------------===//
13
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
Chris Lattner29375652006-12-04 18:06:35 +000024using namespace clang;
25
Richard Smith55858492011-04-14 21:45:45 +000026static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
27 switch (Kind) {
28 case tok::kw_template: return 0;
29 case tok::kw_const_cast: return 1;
30 case tok::kw_dynamic_cast: return 2;
31 case tok::kw_reinterpret_cast: return 3;
32 case tok::kw_static_cast: return 4;
33 default:
David Blaikie83d382b2011-09-23 05:06:16 +000034 llvm_unreachable("Unknown type for digraph error message.");
Richard Smith55858492011-04-14 21:45:45 +000035 }
36}
37
38// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000039bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000040 SourceManager &SM = PP.getSourceManager();
41 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000042 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000043 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
44}
45
46// Suggest fixit for "<::" after a cast.
47static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
48 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
49 // Pull '<:' and ':' off token stream.
50 if (!AtDigraph)
51 PP.Lex(DigraphToken);
52 PP.Lex(ColonToken);
53
54 SourceRange Range;
55 Range.setBegin(DigraphToken.getLocation());
56 Range.setEnd(ColonToken.getLocation());
57 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
58 << SelectDigraphErrorMessage(Kind)
59 << FixItHint::CreateReplacement(Range, "< ::");
60
61 // Update token information to reflect their change in token type.
62 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000063 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000064 ColonToken.setLength(2);
65 DigraphToken.setKind(tok::less);
66 DigraphToken.setLength(1);
67
68 // Push new tokens back to token stream.
69 PP.EnterToken(ColonToken);
70 if (!AtDigraph)
71 PP.EnterToken(DigraphToken);
72}
73
Richard Trieu01fc0012011-09-19 19:01:00 +000074// Check for '<::' which should be '< ::' instead of '[:' when following
75// a template name.
76void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
77 bool EnteringContext,
78 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000079 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000080 return;
81
82 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000083 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000084 return;
85
86 TemplateTy Template;
87 UnqualifiedId TemplateName;
88 TemplateName.setIdentifier(&II, Tok.getLocation());
89 bool MemberOfUnknownSpecialization;
90 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
91 TemplateName, ObjectType, EnteringContext,
92 Template, MemberOfUnknownSpecialization))
93 return;
94
95 FixDigraph(*this, PP, Next, SecondToken, tok::kw_template,
96 /*AtDigraph*/false);
97}
98
Richard Trieu1f3ea7b2012-11-02 01:08:58 +000099/// \brief Emits an error for a left parentheses after a double colon.
100///
101/// When a '(' is found after a '::', emit an error. Attempt to fix the token
Nico Weber6be9b252012-11-29 05:29:23 +0000102/// stream by removing the '(', and the matching ')' if found.
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000103void Parser::CheckForLParenAfterColonColon() {
104 if (!Tok.is(tok::l_paren))
105 return;
106
107 SourceLocation l_parenLoc = ConsumeParen(), r_parenLoc;
108 Token Tok1 = getCurToken();
109 if (!Tok1.is(tok::identifier) && !Tok1.is(tok::star))
110 return;
111
112 if (Tok1.is(tok::identifier)) {
113 Token Tok2 = GetLookAheadToken(1);
114 if (Tok2.is(tok::r_paren)) {
115 ConsumeToken();
116 PP.EnterToken(Tok1);
117 r_parenLoc = ConsumeParen();
118 }
119 } else if (Tok1.is(tok::star)) {
120 Token Tok2 = GetLookAheadToken(1);
121 if (Tok2.is(tok::identifier)) {
122 Token Tok3 = GetLookAheadToken(2);
123 if (Tok3.is(tok::r_paren)) {
124 ConsumeToken();
125 ConsumeToken();
126 PP.EnterToken(Tok2);
127 PP.EnterToken(Tok1);
128 r_parenLoc = ConsumeParen();
129 }
130 }
131 }
132
133 Diag(l_parenLoc, diag::err_paren_after_colon_colon)
134 << FixItHint::CreateRemoval(l_parenLoc)
135 << FixItHint::CreateRemoval(r_parenLoc);
136}
137
Mike Stump11289f42009-09-09 15:08:12 +0000138/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000139///
140/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000141/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000142/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000143///
144/// '::'[opt] nested-name-specifier
145/// '::'
146///
147/// nested-name-specifier:
148/// type-name '::'
149/// namespace-name '::'
150/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000151/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000152///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000153///
Mike Stump11289f42009-09-09 15:08:12 +0000154/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000155/// nested-name-specifier (or empty)
156///
Mike Stump11289f42009-09-09 15:08:12 +0000157/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158/// the "." or "->" of a member access expression, this parameter provides the
159/// type of the object whose members are being accessed.
160///
161/// \param EnteringContext whether we will be entering into the context of
162/// the nested-name-specifier after parsing it.
163///
Douglas Gregore610ada2010-02-24 18:44:31 +0000164/// \param MayBePseudoDestructor When non-NULL, points to a flag that
165/// indicates whether this nested-name-specifier may be part of a
166/// pseudo-destructor name. In this case, the flag will be set false
167/// if we don't actually end up parsing a destructor name. Moreorover,
168/// if we do end up determining that we are parsing a destructor name,
169/// the last component of the nested-name-specifier is not parsed as
170/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000171///
172/// \param IsTypename If \c true, this nested-name-specifier is known to be
173/// part of a type name. This is used to improve error recovery.
174///
175/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
176/// filled in with the leading identifier in the last component of the
177/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000178///
John McCall1f476a12010-02-26 08:45:28 +0000179/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000180bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000181 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000182 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000183 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000184 bool IsTypename,
185 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000186 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000187 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000188
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000189 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000190 assert(!LastII && "want last identifier but have already annotated scope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000191 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
192 Tok.getAnnotationRange(),
193 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000194 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000195 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000196 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000197
Richard Smith7447af42013-03-26 01:15:19 +0000198 if (LastII)
199 *LastII = 0;
200
Douglas Gregor7f741122009-02-25 19:37:18 +0000201 bool HasScopeSpecifier = false;
202
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000203 if (Tok.is(tok::coloncolon)) {
204 // ::new and ::delete aren't nested-name-specifiers.
205 tok::TokenKind NextKind = NextToken().getKind();
206 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
207 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000208
Chris Lattner45ddec32009-01-05 00:13:00 +0000209 // '::' - Global scope qualifier.
Douglas Gregor90c99722011-02-24 00:17:56 +0000210 if (Actions.ActOnCXXGlobalScopeSpecifier(getCurScope(), ConsumeToken(), SS))
211 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000212
213 CheckForLParenAfterColonColon();
214
Douglas Gregor7f741122009-02-25 19:37:18 +0000215 HasScopeSpecifier = true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000216 }
217
Douglas Gregore610ada2010-02-24 18:44:31 +0000218 bool CheckForDestructor = false;
219 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
220 CheckForDestructor = true;
221 *MayBePseudoDestructor = false;
222 }
223
David Blaikie15a430a2011-12-04 05:04:18 +0000224 if (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype)) {
225 DeclSpec DS(AttrFactory);
226 SourceLocation DeclLoc = Tok.getLocation();
227 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
228 if (Tok.isNot(tok::coloncolon)) {
229 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
230 return false;
231 }
232
233 SourceLocation CCLoc = ConsumeToken();
234 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
235 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
236
237 HasScopeSpecifier = true;
238 }
239
Douglas Gregor7f741122009-02-25 19:37:18 +0000240 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000241 if (HasScopeSpecifier) {
242 // C++ [basic.lookup.classref]p5:
243 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000244 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000245 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000246 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000247 // the class-name-or-namespace-name is looked up in global scope as a
248 // class-name or namespace-name.
249 //
250 // To implement this, we clear out the object type as soon as we've
251 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000252 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000253
254 if (Tok.is(tok::code_completion)) {
255 // Code completion for a nested-name-specifier, where the code
256 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000257 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000258 // Include code completion token into the range of the scope otherwise
259 // when we try to annotate the scope tokens the dangling code completion
260 // token will cause assertion in
261 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000262 SS.setEndLoc(Tok.getLocation());
263 cutOffParsing();
264 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000265 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000266 }
Mike Stump11289f42009-09-09 15:08:12 +0000267
Douglas Gregor7f741122009-02-25 19:37:18 +0000268 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000269 // nested-name-specifier 'template'[opt] simple-template-id '::'
270
271 // Parse the optional 'template' keyword, then make sure we have
272 // 'identifier <' after it.
273 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000274 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000275 // nested-name-specifier, since they aren't allowed to start with
276 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000277 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000278 break;
279
Douglas Gregor120635b2009-11-11 16:39:34 +0000280 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000281 SourceLocation TemplateKWLoc = ConsumeToken();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000282
283 UnqualifiedId TemplateName;
284 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000285 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000286 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000287 ConsumeToken();
288 } else if (Tok.is(tok::kw_operator)) {
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000290 TemplateName)) {
291 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000292 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000293 }
Douglas Gregor71395fa2009-11-04 00:56:37 +0000294
Alexis Hunted0530f2009-11-28 08:58:14 +0000295 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000300 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000301 break;
302 }
303 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000304 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000305 break;
306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307
Douglas Gregor120635b2009-11-11 16:39:34 +0000308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
310 // template-id.
311 if (Tok.isNot(tok::less)) {
312 TPA.Revert();
313 break;
314 }
315
316 // Commit to parsing the template-id.
317 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000318 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000319 if (TemplateNameKind TNK
320 = Actions.ActOnDependentTemplateName(getCurScope(),
321 SS, TemplateKWLoc, TemplateName,
322 ObjectType, EnteringContext,
323 Template)) {
324 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
325 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000326 return true;
327 } else
John McCall1f476a12010-02-26 08:45:28 +0000328 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000329
Chris Lattner0eed3a62009-06-26 03:47:46 +0000330 continue;
331 }
Mike Stump11289f42009-09-09 15:08:12 +0000332
Douglas Gregor7f741122009-02-25 19:37:18 +0000333 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000334 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000335 //
336 // simple-template-id '::'
337 //
338 // So we need to check whether the simple-template-id is of the
Douglas Gregorb67535d2009-03-31 00:43:58 +0000339 // right kind (it should name a type or be dependent), and then
340 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000341 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000342 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
343 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000344 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000345 }
346
Richard Smith7447af42013-03-26 01:15:19 +0000347 if (LastII)
348 *LastII = TemplateId->Name;
349
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000350 // Consume the template-id token.
351 ConsumeToken();
352
353 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
354 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000355
David Blaikie8c045bc2011-11-07 03:30:03 +0000356 HasScopeSpecifier = true;
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000357
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000358 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000359 TemplateId->NumArgs);
360
361 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000362 SS,
363 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000364 TemplateId->Template,
365 TemplateId->TemplateNameLoc,
366 TemplateId->LAngleLoc,
367 TemplateArgsPtr,
368 TemplateId->RAngleLoc,
369 CCLoc,
370 EnteringContext)) {
371 SourceLocation StartLoc
372 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
373 : TemplateId->TemplateNameLoc;
374 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000375 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000376
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000377 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000378 }
379
Chris Lattnere2355f72009-06-26 03:52:38 +0000380
381 // The rest of the nested-name-specifier possibilities start with
382 // tok::identifier.
383 if (Tok.isNot(tok::identifier))
384 break;
385
386 IdentifierInfo &II = *Tok.getIdentifierInfo();
387
388 // nested-name-specifier:
389 // type-name '::'
390 // namespace-name '::'
391 // nested-name-specifier identifier '::'
392 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000393
394 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
395 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000396 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000397 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
398 Tok.getLocation(),
399 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000400 EnteringContext) &&
401 // If the token after the colon isn't an identifier, it's still an
402 // error, but they probably meant something else strange so don't
403 // recover like this.
404 PP.LookAhead(1).is(tok::identifier)) {
405 Diag(Next, diag::err_unexected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000406 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000407
408 // Recover as if the user wrote '::'.
409 Next.setKind(tok::coloncolon);
410 }
Chris Lattner1c428032009-12-07 01:36:53 +0000411 }
412
Chris Lattnere2355f72009-06-26 03:52:38 +0000413 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000414 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Douglas Gregor0be31a22010-07-02 17:43:08 +0000415 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, Tok.getLocation(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000416 II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000417 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000418 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000419 }
420
Richard Smith7447af42013-03-26 01:15:19 +0000421 if (LastII)
422 *LastII = &II;
423
Chris Lattnere2355f72009-06-26 03:52:38 +0000424 // We have an identifier followed by a '::'. Lookup this name
425 // as the name in a nested-name-specifier.
426 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000427 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
428 "NextToken() not working properly!");
Chris Lattnere2355f72009-06-26 03:52:38 +0000429 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000430
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000431 CheckForLParenAfterColonColon();
432
Douglas Gregor90c99722011-02-24 00:17:56 +0000433 HasScopeSpecifier = true;
434 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
435 ObjectType, EnteringContext, SS))
436 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
437
Chris Lattnere2355f72009-06-26 03:52:38 +0000438 continue;
439 }
Mike Stump11289f42009-09-09 15:08:12 +0000440
Richard Trieu01fc0012011-09-19 19:01:00 +0000441 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000442
Chris Lattnere2355f72009-06-26 03:52:38 +0000443 // nested-name-specifier:
444 // type-name '<'
445 if (Next.is(tok::less)) {
446 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000447 UnqualifiedId TemplateName;
448 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000449 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000450 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000451 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000452 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000453 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000454 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000455 Template,
456 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000457 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000458 // with a template-id annotation. We do not permit the
459 // template-id to be translated into a type annotation,
460 // because some clients (e.g., the parsing of class template
461 // specializations) still want to see the original template-id
462 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000463 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000464 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
465 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000466 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000467 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000468 }
469
Douglas Gregor20c38a72010-05-21 23:43:39 +0000470 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000471 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000472 // We have something like t::getAs<T>, where getAs is a
473 // member of an unknown specialization. However, this will only
474 // parse correctly as a template, so suggest the keyword 'template'
475 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000476 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000477 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000478 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000479
480 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000481 << II.getName()
482 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
483
Douglas Gregorbb119652010-06-16 23:00:59 +0000484 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000485 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000486 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000487 TemplateName, ObjectType,
488 EnteringContext, Template)) {
489 // Consume the identifier.
490 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000491 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
492 TemplateName, false))
493 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000494 }
495 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000496 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000497
Douglas Gregor20c38a72010-05-21 23:43:39 +0000498 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000499 }
500 }
501
Douglas Gregor7f741122009-02-25 19:37:18 +0000502 // We don't have any tokens that form the beginning of a
503 // nested-name-specifier, so we're done.
504 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Douglas Gregore610ada2010-02-24 18:44:31 +0000507 // Even if we didn't see any pieces of a nested-name-specifier, we
508 // still check whether there is a tilde in this position, which
509 // indicates a potential pseudo-destructor.
510 if (CheckForDestructor && Tok.is(tok::tilde))
511 *MayBePseudoDestructor = true;
512
John McCall1f476a12010-02-26 08:45:28 +0000513 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000514}
515
516/// ParseCXXIdExpression - Handle id-expression.
517///
518/// id-expression:
519/// unqualified-id
520/// qualified-id
521///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000522/// qualified-id:
523/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
524/// '::' identifier
525/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000526/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000527///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000528/// NOTE: The standard specifies that, for qualified-id, the parser does not
529/// expect:
530///
531/// '::' conversion-function-id
532/// '::' '~' class-name
533///
534/// This may cause a slight inconsistency on diagnostics:
535///
536/// class C {};
537/// namespace A {}
538/// void f() {
539/// :: A :: ~ C(); // Some Sema error about using destructor with a
540/// // namespace.
541/// :: ~ C(); // Some Parser error like 'unexpected ~'.
542/// }
543///
544/// We simplify the parser a bit and make it work like:
545///
546/// qualified-id:
547/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
548/// '::' unqualified-id
549///
550/// That way Sema can handle and report similar errors for namespaces and the
551/// global scope.
552///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000553/// The isAddressOfOperand parameter indicates that this id-expression is a
554/// direct operand of the address-of operator. This is, besides member contexts,
555/// the only place where a qualified-id naming a non-static class member may
556/// appear.
557///
John McCalldadc5752010-08-24 06:29:42 +0000558ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000559 // qualified-id:
560 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
561 // '::' unqualified-id
562 //
563 CXXScopeSpec SS;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000564 if (Tok.getKind() == tok::annot_template_id) {
565 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
566 // FIXME: This is a hack for now. It may need to be done from within
567 // ParseUnqualifiedId(), or most likely ParseOptionalCXXScopeSpecifier();
568 SS = TemplateId->SS;
569 }
Douglas Gregordf593fb2011-11-07 17:33:42 +0000570 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000571
572 SourceLocation TemplateKWLoc;
Douglas Gregora121b752009-11-03 16:56:39 +0000573 UnqualifiedId Name;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000574 if (ParseUnqualifiedId(SS,
575 /*EnteringContext=*/false,
576 /*AllowDestructorName=*/false,
577 /*AllowConstructorName=*/false,
John McCallba7bf592010-08-24 05:47:05 +0000578 /*ObjectType=*/ ParsedType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000579 TemplateKWLoc,
Douglas Gregora121b752009-11-03 16:56:39 +0000580 Name))
581 return ExprError();
John McCalla9ee3252009-11-22 02:49:43 +0000582
583 // This is only the direct operand of an & operator if it is not
584 // followed by a postfix-expression suffix.
John McCall8d08b9b2010-08-27 09:08:28 +0000585 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
586 isAddressOfOperand = false;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000587
588 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
589 Tok.is(tok::l_paren), isAddressOfOperand);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000590}
591
Richard Smith21b3ab42013-05-09 21:36:41 +0000592/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000593///
594/// lambda-expression:
595/// lambda-introducer lambda-declarator[opt] compound-statement
596///
597/// lambda-introducer:
598/// '[' lambda-capture[opt] ']'
599///
600/// lambda-capture:
601/// capture-default
602/// capture-list
603/// capture-default ',' capture-list
604///
605/// capture-default:
606/// '&'
607/// '='
608///
609/// capture-list:
610/// capture
611/// capture-list ',' capture
612///
613/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000614/// simple-capture
615/// init-capture [C++1y]
616///
617/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000618/// identifier
619/// '&' identifier
620/// 'this'
621///
Richard Smith21b3ab42013-05-09 21:36:41 +0000622/// init-capture: [C++1y]
623/// identifier initializer
624/// '&' identifier initializer
625///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000626/// lambda-declarator:
627/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
628/// 'mutable'[opt] exception-specification[opt]
629/// trailing-return-type[opt]
630///
631ExprResult Parser::ParseLambdaExpression() {
632 // Parse lambda-introducer.
633 LambdaIntroducer Intro;
634
David Blaikie05785d12013-02-20 22:23:23 +0000635 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000636 if (DiagID) {
637 Diag(Tok, DiagID.getValue());
638 SkipUntil(tok::r_square);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000639 SkipUntil(tok::l_brace);
640 SkipUntil(tok::r_brace);
641 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000642 }
643
644 return ParseLambdaExpressionAfterIntroducer(Intro);
645}
646
647/// TryParseLambdaExpression - Use lookahead and potentially tentative
648/// parsing to determine if we are looking at a C++0x lambda expression, and parse
649/// it if we are.
650///
651/// If we are not looking at a lambda expression, returns ExprError().
652ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000653 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000654 && Tok.is(tok::l_square)
655 && "Not at the start of a possible lambda expression.");
656
657 const Token Next = NextToken(), After = GetLookAheadToken(2);
658
659 // If lookahead indicates this is a lambda...
660 if (Next.is(tok::r_square) || // []
661 Next.is(tok::equal) || // [=
662 (Next.is(tok::amp) && // [&] or [&,
663 (After.is(tok::r_square) ||
664 After.is(tok::comma))) ||
665 (Next.is(tok::identifier) && // [identifier]
666 After.is(tok::r_square))) {
667 return ParseLambdaExpression();
668 }
669
Eli Friedmanc7c97142012-01-04 02:40:39 +0000670 // If lookahead indicates an ObjC message send...
671 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000672 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000673 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000674 }
675
Eli Friedmanc7c97142012-01-04 02:40:39 +0000676 // Here, we're stuck: lambda introducers and Objective-C message sends are
677 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
678 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
679 // writing two routines to parse a lambda introducer, just try to parse
680 // a lambda introducer first, and fall back if that fails.
681 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000682 LambdaIntroducer Intro;
683 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000684 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000685 return ParseLambdaExpressionAfterIntroducer(Intro);
686}
687
Richard Smithf44d2a82013-05-21 22:21:19 +0000688/// \brief Parse a lambda introducer.
689/// \param Intro A LambdaIntroducer filled in with information about the
690/// contents of the lambda-introducer.
691/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
692/// message send and a lambda expression. In this mode, we will
693/// sometimes skip the initializers for init-captures and not fully
694/// populate \p Intro. This flag will be set to \c true if we do so.
695/// \return A DiagnosticID if it hit something unexpected. The location for
696/// for the diagnostic is that of the current token.
697Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
698 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000699 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000700
701 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000702 BalancedDelimiterTracker T(*this, tok::l_square);
703 T.consumeOpen();
704
705 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000706
707 bool first = true;
708
709 // Parse capture-default.
710 if (Tok.is(tok::amp) &&
711 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
712 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000713 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000714 first = false;
715 } else if (Tok.is(tok::equal)) {
716 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000717 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000718 first = false;
719 }
720
721 while (Tok.isNot(tok::r_square)) {
722 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000723 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000724 // Provide a completion for a lambda introducer here. Except
725 // in Objective-C, where this is Almost Surely meant to be a message
726 // send. In that case, fail here and let the ObjC message
727 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000728 if (Tok.is(tok::code_completion) &&
729 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
730 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000731 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
732 /*AfterAmpersand=*/false);
733 ConsumeCodeCompletionToken();
734 break;
735 }
736
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000737 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000738 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000739 ConsumeToken();
740 }
741
Douglas Gregord8c61782012-02-15 15:34:24 +0000742 if (Tok.is(tok::code_completion)) {
743 // If we're in Objective-C++ and we have a bare '[', then this is more
744 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000745 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000746 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
747 else
748 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
749 /*AfterAmpersand=*/false);
750 ConsumeCodeCompletionToken();
751 break;
752 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000753
Douglas Gregord8c61782012-02-15 15:34:24 +0000754 first = false;
755
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000756 // Parse capture.
757 LambdaCaptureKind Kind = LCK_ByCopy;
758 SourceLocation Loc;
759 IdentifierInfo* Id = 0;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000760 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000761 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000762
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000763 if (Tok.is(tok::kw_this)) {
764 Kind = LCK_This;
765 Loc = ConsumeToken();
766 } else {
767 if (Tok.is(tok::amp)) {
768 Kind = LCK_ByRef;
769 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000770
771 if (Tok.is(tok::code_completion)) {
772 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
773 /*AfterAmpersand=*/true);
774 ConsumeCodeCompletionToken();
775 break;
776 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000777 }
778
779 if (Tok.is(tok::identifier)) {
780 Id = Tok.getIdentifierInfo();
781 Loc = ConsumeToken();
782 } else if (Tok.is(tok::kw_this)) {
783 // FIXME: If we want to suggest a fixit here, will need to return more
784 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
785 // Clear()ed to prevent emission in case of tentative parsing?
786 return DiagResult(diag::err_this_captured_by_reference);
787 } else {
788 return DiagResult(diag::err_expected_capture);
789 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000790
791 if (Tok.is(tok::l_paren)) {
792 BalancedDelimiterTracker Parens(*this, tok::l_paren);
793 Parens.consumeOpen();
794
795 ExprVector Exprs;
796 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000797 if (SkippedInits) {
798 Parens.skipToEnd();
799 *SkippedInits = true;
800 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000801 Parens.skipToEnd();
802 Init = ExprError();
803 } else {
804 Parens.consumeClose();
805 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
806 Parens.getCloseLocation(),
807 Exprs);
808 }
809 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
810 if (Tok.is(tok::equal))
811 ConsumeToken();
812
Richard Smithf44d2a82013-05-21 22:21:19 +0000813 if (!SkippedInits)
814 Init = ParseInitializer();
815 else if (Tok.is(tok::l_brace)) {
816 BalancedDelimiterTracker Braces(*this, tok::l_brace);
817 Braces.consumeOpen();
818 Braces.skipToEnd();
819 *SkippedInits = true;
820 } else {
821 // We're disambiguating this:
822 //
823 // [..., x = expr
824 //
825 // We need to find the end of the following expression in order to
826 // determine whether this is an Obj-C message send's receiver, or a
827 // lambda init-capture.
828 //
829 // Parse the expression to find where it ends, and annotate it back
830 // onto the tokens. We would have parsed this expression the same way
831 // in either case: both the RHS of an init-capture and the RHS of an
832 // assignment expression are parsed as an initializer-clause, and in
833 // neither case can anything be added to the scope between the '[' and
834 // here.
835 //
836 // FIXME: This is horrible. Adding a mechanism to skip an expression
837 // would be much cleaner.
838 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
839 // that instead. (And if we see a ':' with no matching '?', we can
840 // classify this as an Obj-C message send.)
841 SourceLocation StartLoc = Tok.getLocation();
842 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
843 Init = ParseInitializer();
844
845 if (Tok.getLocation() != StartLoc) {
846 // Back out the lexing of the token after the initializer.
847 PP.RevertCachedTokens(1);
848
849 // Replace the consumed tokens with an appropriate annotation.
850 Tok.setLocation(StartLoc);
851 Tok.setKind(tok::annot_primary_expr);
852 setExprAnnotation(Tok, Init);
853 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
854 PP.AnnotateCachedTokens(Tok);
855
856 // Consume the annotated initializer.
857 ConsumeToken();
858 }
859 }
Richard Smithba71c082013-05-16 06:20:58 +0000860 } else if (Tok.is(tok::ellipsis))
861 EllipsisLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000862 }
863
Richard Smith21b3ab42013-05-09 21:36:41 +0000864 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000865 }
866
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000867 T.consumeClose();
868 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000869
870 return DiagResult();
871}
872
Douglas Gregord8c61782012-02-15 15:34:24 +0000873/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000874///
875/// Returns true if it hit something unexpected.
876bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
877 TentativeParsingAction PA(*this);
878
Richard Smithf44d2a82013-05-21 22:21:19 +0000879 bool SkippedInits = false;
880 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000881
882 if (DiagID) {
883 PA.Revert();
884 return true;
885 }
886
Richard Smithf44d2a82013-05-21 22:21:19 +0000887 if (SkippedInits) {
888 // Parse it again, but this time parse the init-captures too.
889 PA.Revert();
890 Intro = LambdaIntroducer();
891 DiagID = ParseLambdaIntroducer(Intro);
892 assert(!DiagID && "parsing lambda-introducer failed on reparse");
893 return false;
894 }
895
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000896 PA.Commit();
897 return false;
898}
899
900/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
901/// expression.
902ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
903 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000904 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
905 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
906
907 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
908 "lambda expression parsing");
909
Richard Smith21b3ab42013-05-09 21:36:41 +0000910 // FIXME: Call into Actions to add any init-capture declarations to the
911 // scope while parsing the lambda-declarator and compound-statement.
912
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000913 // Parse lambda-declarator[opt].
914 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +0000915 Declarator D(DS, Declarator::LambdaExprContext);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000916
917 if (Tok.is(tok::l_paren)) {
918 ParseScope PrototypeScope(this,
919 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +0000920 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000921 Scope::DeclScope);
922
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000923 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000924 BalancedDelimiterTracker T(*this, tok::l_paren);
925 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000926 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000927
928 // Parse parameter-declaration-clause.
929 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000930 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000931 SourceLocation EllipsisLoc;
932
933 if (Tok.isNot(tok::r_paren))
934 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
935
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000936 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000937 SourceLocation RParenLoc = T.getCloseLocation();
938 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000939
940 // Parse 'mutable'[opt].
941 SourceLocation MutableLoc;
942 if (Tok.is(tok::kw_mutable)) {
943 MutableLoc = ConsumeToken();
944 DeclEndLoc = MutableLoc;
945 }
946
947 // Parse exception-specification[opt].
948 ExceptionSpecificationType ESpecType = EST_None;
949 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000950 SmallVector<ParsedType, 2> DynamicExceptions;
951 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000952 ExprResult NoexceptExpr;
Richard Smith2331bbf2012-05-02 22:22:32 +0000953 ESpecType = tryParseExceptionSpecification(ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +0000954 DynamicExceptions,
955 DynamicExceptionRanges,
Richard Smith2331bbf2012-05-02 22:22:32 +0000956 NoexceptExpr);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000957
958 if (ESpecType != EST_None)
959 DeclEndLoc = ESpecRange.getEnd();
960
961 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +0000962 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000963
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000964 SourceLocation FunLocalRangeEnd = DeclEndLoc;
965
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000966 // Parse trailing-return-type[opt].
Richard Smith700537c2012-06-12 01:51:59 +0000967 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000968 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000969 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000970 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +0000971 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000972 if (Range.getEnd().isValid())
973 DeclEndLoc = Range.getEnd();
974 }
975
976 PrototypeScope.Exit();
977
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000978 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000979 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000980 /*isAmbiguous=*/false,
981 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000982 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000983 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000984 DS.getTypeQualifiers(),
985 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000986 /*RefQualifierLoc=*/NoLoc,
987 /*ConstQualifierLoc=*/NoLoc,
988 /*VolatileQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000989 MutableLoc,
990 ESpecType, ESpecRange.getBegin(),
991 DynamicExceptions.data(),
992 DynamicExceptionRanges.data(),
993 DynamicExceptions.size(),
994 NoexceptExpr.isUsable() ?
995 NoexceptExpr.get() : 0,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +0000996 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000997 TrailingReturnType),
998 Attr, DeclEndLoc);
Douglas Gregor6746c5d2012-02-16 21:53:36 +0000999 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow)) {
1000 // It's common to forget that one needs '()' before 'mutable' or the
1001 // result type. Deal with this.
1002 Diag(Tok, diag::err_lambda_missing_parens)
1003 << Tok.is(tok::arrow)
1004 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1005 SourceLocation DeclLoc = Tok.getLocation();
1006 SourceLocation DeclEndLoc = DeclLoc;
1007
1008 // Parse 'mutable', if it's there.
1009 SourceLocation MutableLoc;
1010 if (Tok.is(tok::kw_mutable)) {
1011 MutableLoc = ConsumeToken();
1012 DeclEndLoc = MutableLoc;
1013 }
1014
1015 // Parse the return type, if there is one.
Richard Smith700537c2012-06-12 01:51:59 +00001016 TypeResult TrailingReturnType;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001017 if (Tok.is(tok::arrow)) {
1018 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001019 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001020 if (Range.getEnd().isValid())
1021 DeclEndLoc = Range.getEnd();
1022 }
1023
1024 ParsedAttributes Attr(AttrFactory);
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001025 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001026 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001027 /*isAmbiguous=*/false,
1028 /*LParenLoc=*/NoLoc,
1029 /*Params=*/0,
1030 /*NumParams=*/0,
1031 /*EllipsisLoc=*/NoLoc,
1032 /*RParenLoc=*/NoLoc,
1033 /*TypeQuals=*/0,
1034 /*RefQualifierIsLValueRef=*/true,
1035 /*RefQualifierLoc=*/NoLoc,
1036 /*ConstQualifierLoc=*/NoLoc,
1037 /*VolatileQualifierLoc=*/NoLoc,
1038 MutableLoc,
1039 EST_None,
1040 /*ESpecLoc=*/NoLoc,
1041 /*Exceptions=*/0,
1042 /*ExceptionRanges=*/0,
1043 /*NumExceptions=*/0,
1044 /*NoexceptExpr=*/0,
1045 DeclLoc, DeclEndLoc, D,
1046 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001047 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001048 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001049
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001050
Eli Friedman4817cf72012-01-06 03:05:34 +00001051 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1052 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001053 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001054 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001055
Eli Friedman71c80552012-01-05 03:35:19 +00001056 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1057
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001058 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001059 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001060 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001061 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1062 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001063 }
1064
Eli Friedmanc7c97142012-01-04 02:40:39 +00001065 StmtResult Stmt(ParseCompoundStatementBody());
1066 BodyScope.Exit();
1067
Eli Friedman898caf82012-01-04 02:46:53 +00001068 if (!Stmt.isInvalid())
Douglas Gregor63798542012-02-20 19:44:39 +00001069 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.take(), getCurScope());
Eli Friedmanc7c97142012-01-04 02:40:39 +00001070
Eli Friedman898caf82012-01-04 02:46:53 +00001071 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1072 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001073}
1074
Chris Lattner29375652006-12-04 18:06:35 +00001075/// ParseCXXCasts - This handles the various ways to cast expressions to another
1076/// type.
1077///
1078/// postfix-expression: [C++ 5.2p1]
1079/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1080/// 'static_cast' '<' type-name '>' '(' expression ')'
1081/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1082/// 'const_cast' '<' type-name '>' '(' expression ')'
1083///
John McCalldadc5752010-08-24 06:29:42 +00001084ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001085 tok::TokenKind Kind = Tok.getKind();
1086 const char *CastName = 0; // For error messages
1087
1088 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001089 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001090 case tok::kw_const_cast: CastName = "const_cast"; break;
1091 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1092 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1093 case tok::kw_static_cast: CastName = "static_cast"; break;
1094 }
1095
1096 SourceLocation OpLoc = ConsumeToken();
1097 SourceLocation LAngleBracketLoc = Tok.getLocation();
1098
Richard Smith55858492011-04-14 21:45:45 +00001099 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1100 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001101 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1102 Token Next = NextToken();
1103 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1104 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1105 }
Richard Smith55858492011-04-14 21:45:45 +00001106
Chris Lattner29375652006-12-04 18:06:35 +00001107 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001108 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001109
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001110 // Parse the common declaration-specifiers piece.
1111 DeclSpec DS(AttrFactory);
1112 ParseSpecifierQualifierList(DS);
1113
1114 // Parse the abstract-declarator, if present.
1115 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1116 ParseDeclarator(DeclaratorInfo);
1117
Chris Lattner29375652006-12-04 18:06:35 +00001118 SourceLocation RAngleBracketLoc = Tok.getLocation();
1119
Chris Lattner6d29c102008-11-18 07:48:38 +00001120 if (ExpectAndConsume(tok::greater, diag::err_expected_greater))
Sebastian Redld65cea82008-12-11 22:51:44 +00001121 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << "<");
Chris Lattner29375652006-12-04 18:06:35 +00001122
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001123 SourceLocation LParenLoc, RParenLoc;
1124 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001125
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001126 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001127 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001128
John McCalldadc5752010-08-24 06:29:42 +00001129 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001130
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001131 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001132 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001133
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001134 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001135 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001136 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001137 RAngleBracketLoc,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001138 T.getOpenLocation(), Result.take(),
1139 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001140
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001141 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001142}
Bill Wendling4073ed52007-02-13 01:51:42 +00001143
Sebastian Redlc4704762008-11-11 11:37:55 +00001144/// ParseCXXTypeid - This handles the C++ typeid expression.
1145///
1146/// postfix-expression: [C++ 5.2p1]
1147/// 'typeid' '(' expression ')'
1148/// 'typeid' '(' type-id ')'
1149///
John McCalldadc5752010-08-24 06:29:42 +00001150ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001151 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1152
1153 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001154 SourceLocation LParenLoc, RParenLoc;
1155 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001156
1157 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001158 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001159 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001160 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001161
John McCalldadc5752010-08-24 06:29:42 +00001162 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001163
Richard Smith4f605af2012-08-18 00:55:03 +00001164 // C++0x [expr.typeid]p3:
1165 // When typeid is applied to an expression other than an lvalue of a
1166 // polymorphic class type [...] The expression is an unevaluated
1167 // operand (Clause 5).
1168 //
1169 // Note that we can't tell whether the expression is an lvalue of a
1170 // polymorphic class type until after we've parsed the expression; we
1171 // speculatively assume the subexpression is unevaluated, and fix it up
1172 // later.
1173 //
1174 // We enter the unevaluated context before trying to determine whether we
1175 // have a type-id, because the tentative parse logic will try to resolve
1176 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001177 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1178 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001179
Sebastian Redlc4704762008-11-11 11:37:55 +00001180 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001181 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001182
1183 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001184 T.consumeClose();
1185 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001186 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001187 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001188
1189 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001190 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001191 } else {
1192 Result = ParseExpression();
1193
1194 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001195 if (Result.isInvalid())
Sebastian Redlc4704762008-11-11 11:37:55 +00001196 SkipUntil(tok::r_paren);
1197 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001198 T.consumeClose();
1199 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001200 if (RParenLoc.isInvalid())
1201 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001202
Sebastian Redlc4704762008-11-11 11:37:55 +00001203 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001204 Result.release(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001205 }
1206 }
1207
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001208 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001209}
1210
Francois Pichet9f4f2072010-09-08 12:20:18 +00001211/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1212///
1213/// '__uuidof' '(' expression ')'
1214/// '__uuidof' '(' type-id ')'
1215///
1216ExprResult Parser::ParseCXXUuidof() {
1217 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1218
1219 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001220 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001221
1222 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001223 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001224 return ExprError();
1225
1226 ExprResult Result;
1227
1228 if (isTypeIdInParens()) {
1229 TypeResult Ty = ParseTypeName();
1230
1231 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001232 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001233
1234 if (Ty.isInvalid())
1235 return ExprError();
1236
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001237 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1238 Ty.get().getAsOpaquePtr(),
1239 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001240 } else {
1241 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1242 Result = ParseExpression();
1243
1244 // Match the ')'.
1245 if (Result.isInvalid())
1246 SkipUntil(tok::r_paren);
1247 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001248 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001249
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001250 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1251 /*isType=*/false,
1252 Result.release(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001253 }
1254 }
1255
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001256 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001257}
1258
Douglas Gregore610ada2010-02-24 18:44:31 +00001259/// \brief Parse a C++ pseudo-destructor expression after the base,
1260/// . or -> operator, and nested-name-specifier have already been
1261/// parsed.
1262///
1263/// postfix-expression: [C++ 5.2]
1264/// postfix-expression . pseudo-destructor-name
1265/// postfix-expression -> pseudo-destructor-name
1266///
1267/// pseudo-destructor-name:
1268/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1269/// ::[opt] nested-name-specifier template simple-template-id ::
1270/// ~type-name
1271/// ::[opt] nested-name-specifier[opt] ~type-name
1272///
John McCalldadc5752010-08-24 06:29:42 +00001273ExprResult
Douglas Gregore610ada2010-02-24 18:44:31 +00001274Parser::ParseCXXPseudoDestructor(ExprArg Base, SourceLocation OpLoc,
1275 tok::TokenKind OpKind,
1276 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001277 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001278 // We're parsing either a pseudo-destructor-name or a dependent
1279 // member access that has the same form as a
1280 // pseudo-destructor-name. We parse both in the same way and let
1281 // the action model sort them out.
1282 //
1283 // Note that the ::[opt] nested-name-specifier[opt] has already
1284 // been parsed, and if there was a simple-template-id, it has
1285 // been coalesced into a template-id annotation token.
1286 UnqualifiedId FirstTypeName;
1287 SourceLocation CCLoc;
1288 if (Tok.is(tok::identifier)) {
1289 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1290 ConsumeToken();
1291 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1292 CCLoc = ConsumeToken();
1293 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001294 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1295 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001296 FirstTypeName.setTemplateId(
1297 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1298 ConsumeToken();
1299 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1300 CCLoc = ConsumeToken();
1301 } else {
1302 FirstTypeName.setIdentifier(0, SourceLocation());
1303 }
1304
1305 // Parse the tilde.
1306 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1307 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001308
1309 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1310 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001311 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001312 if (DS.getTypeSpecType() == TST_error)
1313 return ExprError();
1314 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1315 OpKind, TildeLoc, DS,
1316 Tok.is(tok::l_paren));
1317 }
1318
Douglas Gregore610ada2010-02-24 18:44:31 +00001319 if (!Tok.is(tok::identifier)) {
1320 Diag(Tok, diag::err_destructor_tilde_identifier);
1321 return ExprError();
1322 }
1323
1324 // Parse the second type.
1325 UnqualifiedId SecondTypeName;
1326 IdentifierInfo *Name = Tok.getIdentifierInfo();
1327 SourceLocation NameLoc = ConsumeToken();
1328 SecondTypeName.setIdentifier(Name, NameLoc);
1329
1330 // If there is a '<', the second type name is a template-id. Parse
1331 // it as such.
1332 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001333 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1334 Name, NameLoc,
1335 false, ObjectType, SecondTypeName,
1336 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001337 return ExprError();
1338
John McCallb268a282010-08-23 23:25:46 +00001339 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1340 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001341 SS, FirstTypeName, CCLoc,
1342 TildeLoc, SecondTypeName,
1343 Tok.is(tok::l_paren));
1344}
1345
Bill Wendling4073ed52007-02-13 01:51:42 +00001346/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1347///
1348/// boolean-literal: [C++ 2.13.5]
1349/// 'true'
1350/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001351ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001352 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001353 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001354}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001355
1356/// ParseThrowExpression - This handles the C++ throw expression.
1357///
1358/// throw-expression: [C++ 15]
1359/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001360ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001361 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001362 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001363
Chris Lattner65dd8432008-04-06 06:02:23 +00001364 // If the current token isn't the start of an assignment-expression,
1365 // then the expression is not present. This handles things like:
1366 // "C ? throw : (void)42", which is crazy but legal.
1367 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1368 case tok::semi:
1369 case tok::r_paren:
1370 case tok::r_square:
1371 case tok::r_brace:
1372 case tok::colon:
1373 case tok::comma:
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001374 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, 0);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001375
Chris Lattner65dd8432008-04-06 06:02:23 +00001376 default:
John McCalldadc5752010-08-24 06:29:42 +00001377 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001378 if (Expr.isInvalid()) return Expr;
Douglas Gregor53e191ed2011-07-06 22:04:06 +00001379 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.take());
Chris Lattner65dd8432008-04-06 06:02:23 +00001380 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001381}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001382
1383/// ParseCXXThis - This handles the C++ 'this' pointer.
1384///
1385/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1386/// a non-lvalue expression whose value is the address of the object for which
1387/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001388ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001389 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1390 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001391 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001392}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001393
1394/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1395/// Can be interpreted either as function-style casting ("int(x)")
1396/// or class type construction ("ClassType(x,y,z)")
1397/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001398/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001399///
1400/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001401/// simple-type-specifier '(' expression-list[opt] ')'
1402/// [C++0x] simple-type-specifier braced-init-list
1403/// typename-specifier '(' expression-list[opt] ')'
1404/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001405///
John McCalldadc5752010-08-24 06:29:42 +00001406ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001407Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001408 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001409 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001410
Sebastian Redl3da34892011-06-05 12:23:16 +00001411 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001412 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001413 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001414
Sebastian Redl3da34892011-06-05 12:23:16 +00001415 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001416 ExprResult Init = ParseBraceInitializer();
1417 if (Init.isInvalid())
1418 return Init;
1419 Expr *InitList = Init.take();
1420 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1421 MultiExprArg(&InitList, 1),
1422 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001423 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001424 BalancedDelimiterTracker T(*this, tok::l_paren);
1425 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001426
Benjamin Kramerf0623432012-08-23 22:51:59 +00001427 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001428 CommaLocsTy CommaLocs;
1429
1430 if (Tok.isNot(tok::r_paren)) {
1431 if (ParseExpressionList(Exprs, CommaLocs)) {
1432 SkipUntil(tok::r_paren);
1433 return ExprError();
1434 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001435 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001436
1437 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001438 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001439
1440 // TypeRep could be null, if it references an invalid typedef.
1441 if (!TypeRep)
1442 return ExprError();
1443
1444 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1445 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001446 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001447 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001448 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001449 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001450}
1451
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001452/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001453///
1454/// condition:
1455/// expression
1456/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001457/// [C++11] type-specifier-seq declarator '=' initializer-clause
1458/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001459/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1460/// '=' assignment-expression
1461///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001462/// \param ExprOut if the condition was parsed as an expression, the parsed
1463/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001464///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001465/// \param DeclOut if the condition was parsed as a declaration, the parsed
1466/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001467///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001468/// \param Loc The location of the start of the statement that requires this
1469/// condition, e.g., the "for" in a for loop.
1470///
1471/// \param ConvertToBoolean Whether the condition expression should be
1472/// converted to a boolean value.
1473///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001474/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001475bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1476 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001477 SourceLocation Loc,
1478 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001479 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001480 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001481 cutOffParsing();
1482 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001483 }
1484
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001485 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001486 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001487
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001488 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001489 ProhibitAttributes(attrs);
1490
Douglas Gregore60e41a2010-05-06 17:25:47 +00001491 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001492 ExprOut = ParseExpression(); // expression
1493 DeclOut = 0;
1494 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001495 return true;
1496
1497 // If required, convert to a boolean value.
1498 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001499 ExprOut
1500 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1501 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001502 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001503
1504 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001505 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001506 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001507 ParseSpecifierQualifierList(DS);
1508
1509 // declarator
1510 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1511 ParseDeclarator(DeclaratorInfo);
1512
1513 // simple-asm-expr[opt]
1514 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001515 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001516 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001517 if (AsmLabel.isInvalid()) {
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001518 SkipUntil(tok::semi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001519 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001520 }
Sebastian Redld9f7b1c2008-12-10 00:02:53 +00001521 DeclaratorInfo.setAsmLabel(AsmLabel.release());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001522 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001523 }
1524
1525 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001526 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001527
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001528 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001529 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001530 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001531 DeclOut = Dcl.get();
1532 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001533
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001534 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001535 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001536 bool CopyInitialization = isTokenEqualOrEqualTypo();
1537 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001538 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001539
1540 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001541 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001542 Diag(Tok.getLocation(),
1543 diag::warn_cxx98_compat_generalized_initializer_lists);
1544 InitExpr = ParseBraceInitializer();
1545 } else if (CopyInitialization) {
1546 InitExpr = ParseAssignmentExpression();
1547 } else if (Tok.is(tok::l_paren)) {
1548 // This was probably an attempt to initialize the variable.
1549 SourceLocation LParen = ConsumeParen(), RParen = LParen;
1550 if (SkipUntil(tok::r_paren, true, /*DontConsume=*/true))
1551 RParen = ConsumeParen();
1552 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1553 diag::err_expected_init_in_condition_lparen)
1554 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001555 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001556 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1557 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001558 }
Richard Smith2a15b742012-02-22 06:49:09 +00001559
1560 if (!InitExpr.isInvalid())
1561 Actions.AddInitializerToDecl(DeclOut, InitExpr.take(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001562 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001563 else
1564 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001565
Douglas Gregore60e41a2010-05-06 17:25:47 +00001566 // FIXME: Build a reference to this declaration? Convert it to bool?
1567 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001568
1569 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001570
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001571 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001572}
1573
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001574/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1575/// This should only be called when the current token is known to be part of
1576/// simple-type-specifier.
1577///
1578/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001579/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001580/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1581/// char
1582/// wchar_t
1583/// bool
1584/// short
1585/// int
1586/// long
1587/// signed
1588/// unsigned
1589/// float
1590/// double
1591/// void
1592/// [GNU] typeof-specifier
1593/// [C++0x] auto [TODO]
1594///
1595/// type-name:
1596/// class-name
1597/// enum-name
1598/// typedef-name
1599///
1600void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1601 DS.SetRangeStart(Tok.getLocation());
1602 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001603 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001604 SourceLocation Loc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001605
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001606 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001607 case tok::identifier: // foo::bar
1608 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001609 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001610 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001611 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001612
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001613 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001614 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001615 if (getTypeAnnotation(Tok))
1616 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
1617 getTypeAnnotation(Tok));
1618 else
1619 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001620
1621 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1622 ConsumeToken();
1623
1624 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1625 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1626 // Objective-C interface. If we don't have Objective-C or a '<', this is
1627 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001628 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001629 ParseObjCProtocolQualifiers(DS);
1630
1631 DS.Finish(Diags, PP);
1632 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001633 }
Mike Stump11289f42009-09-09 15:08:12 +00001634
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001635 // builtin types
1636 case tok::kw_short:
John McCall49bfce42009-08-03 20:12:06 +00001637 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001638 break;
1639 case tok::kw_long:
John McCall49bfce42009-08-03 20:12:06 +00001640 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001641 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001642 case tok::kw___int64:
1643 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID);
1644 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001645 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001646 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001647 break;
1648 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001649 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001650 break;
1651 case tok::kw_void:
John McCall49bfce42009-08-03 20:12:06 +00001652 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001653 break;
1654 case tok::kw_char:
John McCall49bfce42009-08-03 20:12:06 +00001655 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001656 break;
1657 case tok::kw_int:
John McCall49bfce42009-08-03 20:12:06 +00001658 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001659 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001660 case tok::kw___int128:
1661 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID);
1662 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001663 case tok::kw_half:
1664 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID);
1665 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001666 case tok::kw_float:
John McCall49bfce42009-08-03 20:12:06 +00001667 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001668 break;
1669 case tok::kw_double:
John McCall49bfce42009-08-03 20:12:06 +00001670 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001671 break;
1672 case tok::kw_wchar_t:
John McCall49bfce42009-08-03 20:12:06 +00001673 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001674 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001675 case tok::kw_char16_t:
John McCall49bfce42009-08-03 20:12:06 +00001676 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001677 break;
1678 case tok::kw_char32_t:
John McCall49bfce42009-08-03 20:12:06 +00001679 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001680 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001681 case tok::kw_bool:
John McCall49bfce42009-08-03 20:12:06 +00001682 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001683 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001684 case tok::annot_decltype:
1685 case tok::kw_decltype:
1686 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
1687 return DS.Finish(Diags, PP);
Mike Stump11289f42009-09-09 15:08:12 +00001688
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001689 // GNU typeof support.
1690 case tok::kw_typeof:
1691 ParseTypeofSpecifier(DS);
Douglas Gregore3e01a22009-04-01 22:41:11 +00001692 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001693 return;
1694 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001695 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001696 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1697 else
1698 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001699 ConsumeToken();
Douglas Gregore3e01a22009-04-01 22:41:11 +00001700 DS.Finish(Diags, PP);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001701}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001702
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001703/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1704/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1705/// e.g., "const short int". Note that the DeclSpec is *not* finished
1706/// by parsing the type-specifier-seq, because these sequences are
1707/// typically followed by some form of declarator. Returns true and
1708/// emits diagnostics if this is not a type-specifier-seq, false
1709/// otherwise.
1710///
1711/// type-specifier-seq: [C++ 8.1]
1712/// type-specifier type-specifier-seq[opt]
1713///
1714bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001715 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Douglas Gregor40d732f2010-02-24 23:13:13 +00001716 DS.Finish(Diags, PP);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001717 return false;
1718}
1719
Douglas Gregor7861a802009-11-03 01:35:08 +00001720/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1721/// some form.
1722///
1723/// This routine is invoked when a '<' is encountered after an identifier or
1724/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1725/// whether the unqualified-id is actually a template-id. This routine will
1726/// then parse the template arguments and form the appropriate template-id to
1727/// return to the caller.
1728///
1729/// \param SS the nested-name-specifier that precedes this template-id, if
1730/// we're actually parsing a qualified-id.
1731///
1732/// \param Name for constructor and destructor names, this is the actual
1733/// identifier that may be a template-name.
1734///
1735/// \param NameLoc the location of the class-name in a constructor or
1736/// destructor.
1737///
1738/// \param EnteringContext whether we're entering the scope of the
1739/// nested-name-specifier.
1740///
Douglas Gregor127ea592009-11-03 21:24:04 +00001741/// \param ObjectType if this unqualified-id occurs within a member access
1742/// expression, the type of the base object whose member is being accessed.
1743///
Douglas Gregor7861a802009-11-03 01:35:08 +00001744/// \param Id as input, describes the template-name or operator-function-id
1745/// that precedes the '<'. If template arguments were parsed successfully,
1746/// will be updated with the template-id.
1747///
Douglas Gregore610ada2010-02-24 18:44:31 +00001748/// \param AssumeTemplateId When true, this routine will assume that the name
1749/// refers to a template without performing name lookup to verify.
1750///
Douglas Gregor7861a802009-11-03 01:35:08 +00001751/// \returns true if a parse error occurred, false otherwise.
1752bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001753 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001754 IdentifierInfo *Name,
1755 SourceLocation NameLoc,
1756 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001757 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001758 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001759 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001760 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1761 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001762
1763 TemplateTy Template;
1764 TemplateNameKind TNK = TNK_Non_template;
1765 switch (Id.getKind()) {
1766 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001767 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001768 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001769 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001770 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001771 Id, ObjectType, EnteringContext,
1772 Template);
1773 if (TNK == TNK_Non_template)
1774 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001775 } else {
1776 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001777 TNK = Actions.isTemplateName(getCurScope(), SS,
1778 TemplateKWLoc.isValid(), Id,
1779 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001780 MemberOfUnknownSpecialization);
1781
1782 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1783 ObjectType && IsTemplateArgumentList()) {
1784 // We have something like t->getAs<T>(), where getAs is a
1785 // member of an unknown specialization. However, this will only
1786 // parse correctly as a template, so suggest the keyword 'template'
1787 // before 'getAs' and treat this as a dependent template name.
1788 std::string Name;
1789 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1790 Name = Id.Identifier->getName();
1791 else {
1792 Name = "operator ";
1793 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1794 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1795 else
1796 Name += Id.Identifier->getName();
1797 }
1798 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1799 << Name
1800 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001801 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1802 SS, TemplateKWLoc, Id,
1803 ObjectType, EnteringContext,
1804 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001805 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001806 return true;
1807 }
1808 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001809 break;
1810
Douglas Gregor3cf81312009-11-03 23:16:33 +00001811 case UnqualifiedId::IK_ConstructorName: {
1812 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001813 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001814 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001815 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1816 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001817 EnteringContext, Template,
1818 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001819 break;
1820 }
1821
Douglas Gregor3cf81312009-11-03 23:16:33 +00001822 case UnqualifiedId::IK_DestructorName: {
1823 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001824 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001825 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001826 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001827 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1828 SS, TemplateKWLoc, TemplateName,
1829 ObjectType, EnteringContext,
1830 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001831 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001832 return true;
1833 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001834 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1835 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001836 EnteringContext, Template,
1837 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001838
John McCallba7bf592010-08-24 05:47:05 +00001839 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001840 Diag(NameLoc, diag::err_destructor_template_id)
1841 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001842 return true;
1843 }
1844 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001845 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001846 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001847
1848 default:
1849 return false;
1850 }
1851
1852 if (TNK == TNK_Non_template)
1853 return false;
1854
1855 // Parse the enclosed template argument list.
1856 SourceLocation LAngleLoc, RAngleLoc;
1857 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00001858 if (Tok.is(tok::less) &&
1859 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00001860 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001861 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00001862 RAngleLoc))
1863 return true;
1864
1865 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00001866 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
1867 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00001868 // Form a parsed representation of the template-id to be stored in the
1869 // UnqualifiedId.
1870 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00001871 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00001872
1873 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
1874 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001875 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00001876 TemplateId->TemplateNameLoc = Id.StartLocation;
1877 } else {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001878 TemplateId->Name = 0;
1879 TemplateId->Operator = Id.OperatorFunctionId.Operator;
1880 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00001881 }
1882
Douglas Gregore7c20652011-03-02 00:47:37 +00001883 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00001884 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00001885 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00001886 TemplateId->Kind = TNK;
1887 TemplateId->LAngleLoc = LAngleLoc;
1888 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001889 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00001890 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001891 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00001892 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00001893
1894 Id.setTemplateId(TemplateId);
1895 return false;
1896 }
1897
1898 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00001899 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00001900
Douglas Gregor7861a802009-11-03 01:35:08 +00001901 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00001902 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00001903 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
1904 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00001905 LAngleLoc, TemplateArgsPtr, RAngleLoc,
1906 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00001907 if (Type.isInvalid())
1908 return true;
1909
1910 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
1911 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
1912 else
1913 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
1914
1915 return false;
1916}
1917
Douglas Gregor71395fa2009-11-04 00:56:37 +00001918/// \brief Parse an operator-function-id or conversion-function-id as part
1919/// of a C++ unqualified-id.
1920///
1921/// This routine is responsible only for parsing the operator-function-id or
1922/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00001923///
1924/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00001925/// operator-function-id: [C++ 13.5]
1926/// 'operator' operator
1927///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001928/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00001929/// new delete new[] delete[]
1930/// + - * / % ^ & | ~
1931/// ! = < > += -= *= /= %=
1932/// ^= &= |= << >> >>= <<= == !=
1933/// <= >= && || ++ -- , ->* ->
1934/// () []
1935///
1936/// conversion-function-id: [C++ 12.3.2]
1937/// operator conversion-type-id
1938///
1939/// conversion-type-id:
1940/// type-specifier-seq conversion-declarator[opt]
1941///
1942/// conversion-declarator:
1943/// ptr-operator conversion-declarator[opt]
1944/// \endcode
1945///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001946/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00001947/// non-empty, then we are parsing the unqualified-id of a qualified-id.
1948///
1949/// \param EnteringContext whether we are entering the scope of the
1950/// nested-name-specifier.
1951///
Douglas Gregor71395fa2009-11-04 00:56:37 +00001952/// \param ObjectType if this unqualified-id occurs within a member access
1953/// expression, the type of the base object whose member is being accessed.
1954///
1955/// \param Result on a successful parse, contains the parsed unqualified-id.
1956///
1957/// \returns true if parsing fails, false otherwise.
1958bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001959 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00001960 UnqualifiedId &Result) {
1961 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
1962
1963 // Consume the 'operator' keyword.
1964 SourceLocation KeywordLoc = ConsumeToken();
1965
1966 // Determine what kind of operator name we have.
1967 unsigned SymbolIdx = 0;
1968 SourceLocation SymbolLocations[3];
1969 OverloadedOperatorKind Op = OO_None;
1970 switch (Tok.getKind()) {
1971 case tok::kw_new:
1972 case tok::kw_delete: {
1973 bool isNew = Tok.getKind() == tok::kw_new;
1974 // Consume the 'new' or 'delete'.
1975 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00001976 // Check for array new/delete.
1977 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001978 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001979 // Consume the '[' and ']'.
1980 BalancedDelimiterTracker T(*this, tok::l_square);
1981 T.consumeOpen();
1982 T.consumeClose();
1983 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00001984 return true;
1985
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001986 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
1987 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00001988 Op = isNew? OO_Array_New : OO_Array_Delete;
1989 } else {
1990 Op = isNew? OO_New : OO_Delete;
1991 }
1992 break;
1993 }
1994
1995#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1996 case tok::Token: \
1997 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
1998 Op = OO_##Name; \
1999 break;
2000#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2001#include "clang/Basic/OperatorKinds.def"
2002
2003 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002004 // Consume the '(' and ')'.
2005 BalancedDelimiterTracker T(*this, tok::l_paren);
2006 T.consumeOpen();
2007 T.consumeClose();
2008 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002009 return true;
2010
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002011 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2012 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002013 Op = OO_Call;
2014 break;
2015 }
2016
2017 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002018 // Consume the '[' and ']'.
2019 BalancedDelimiterTracker T(*this, tok::l_square);
2020 T.consumeOpen();
2021 T.consumeClose();
2022 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002023 return true;
2024
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002025 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2026 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002027 Op = OO_Subscript;
2028 break;
2029 }
2030
2031 case tok::code_completion: {
2032 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002033 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002034 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002035 // Don't try to parse any further.
2036 return true;
2037 }
2038
2039 default:
2040 break;
2041 }
2042
2043 if (Op != OO_None) {
2044 // We have parsed an operator-function-id.
2045 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2046 return false;
2047 }
Alexis Hunt34458502009-11-28 04:44:28 +00002048
2049 // Parse a literal-operator-id.
2050 //
Richard Smith6f212062012-10-20 08:41:10 +00002051 // literal-operator-id: C++11 [over.literal]
2052 // operator string-literal identifier
2053 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002054
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002055 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002056 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002057
Richard Smith7d182a72012-03-08 23:06:02 +00002058 SourceLocation DiagLoc;
2059 unsigned DiagId = 0;
2060
2061 // We're past translation phase 6, so perform string literal concatenation
2062 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002063 SmallVector<Token, 4> Toks;
2064 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002065 while (isTokenStringLiteral()) {
2066 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002067 // C++11 [over.literal]p1:
2068 // The string-literal or user-defined-string-literal in a
2069 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002070 DiagLoc = Tok.getLocation();
2071 DiagId = diag::err_literal_operator_string_prefix;
2072 }
2073 Toks.push_back(Tok);
2074 TokLocs.push_back(ConsumeStringToken());
2075 }
2076
2077 StringLiteralParser Literal(Toks.data(), Toks.size(), PP);
2078 if (Literal.hadError)
2079 return true;
2080
2081 // Grab the literal operator's suffix, which will be either the next token
2082 // or a ud-suffix from the string literal.
2083 IdentifierInfo *II = 0;
2084 SourceLocation SuffixLoc;
2085 if (!Literal.getUDSuffix().empty()) {
2086 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2087 SuffixLoc =
2088 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2089 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002090 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002091 } else if (Tok.is(tok::identifier)) {
2092 II = Tok.getIdentifierInfo();
2093 SuffixLoc = ConsumeToken();
2094 TokLocs.push_back(SuffixLoc);
2095 } else {
Alexis Hunt34458502009-11-28 04:44:28 +00002096 Diag(Tok.getLocation(), diag::err_expected_ident);
2097 return true;
2098 }
2099
Richard Smith7d182a72012-03-08 23:06:02 +00002100 // The string literal must be empty.
2101 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002102 // C++11 [over.literal]p1:
2103 // The string-literal or user-defined-string-literal in a
2104 // literal-operator-id shall [...] contain no characters
2105 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002106 DiagLoc = TokLocs.front();
2107 DiagId = diag::err_literal_operator_string_not_empty;
2108 }
2109
2110 if (DiagId) {
2111 // This isn't a valid literal-operator-id, but we think we know
2112 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002113 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002114 Str += "\"\" ";
2115 Str += II->getName();
2116 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2117 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2118 }
2119
2120 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Alexis Hunt3d221f22009-11-29 07:34:05 +00002121 return false;
Alexis Hunt34458502009-11-28 04:44:28 +00002122 }
Douglas Gregor71395fa2009-11-04 00:56:37 +00002123
2124 // Parse a conversion-function-id.
2125 //
2126 // conversion-function-id: [C++ 12.3.2]
2127 // operator conversion-type-id
2128 //
2129 // conversion-type-id:
2130 // type-specifier-seq conversion-declarator[opt]
2131 //
2132 // conversion-declarator:
2133 // ptr-operator conversion-declarator[opt]
2134
2135 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002136 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002137 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002138 return true;
2139
2140 // Parse the conversion-declarator, which is merely a sequence of
2141 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002142 Declarator D(DS, Declarator::ConversionIdContext);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002143 ParseDeclaratorInternal(D, /*DirectDeclParser=*/0);
2144
2145 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002146 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002147 if (Ty.isInvalid())
2148 return true;
2149
2150 // Note that this is a conversion-function-id.
2151 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2152 D.getSourceRange().getEnd());
2153 return false;
2154}
2155
2156/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2157/// name of an entity.
2158///
2159/// \code
2160/// unqualified-id: [C++ expr.prim.general]
2161/// identifier
2162/// operator-function-id
2163/// conversion-function-id
2164/// [C++0x] literal-operator-id [TODO]
2165/// ~ class-name
2166/// template-id
2167///
2168/// \endcode
2169///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002170/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002171/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2172///
2173/// \param EnteringContext whether we are entering the scope of the
2174/// nested-name-specifier.
2175///
Douglas Gregor7861a802009-11-03 01:35:08 +00002176/// \param AllowDestructorName whether we allow parsing of a destructor name.
2177///
2178/// \param AllowConstructorName whether we allow parsing a constructor name.
2179///
Douglas Gregor127ea592009-11-03 21:24:04 +00002180/// \param ObjectType if this unqualified-id occurs within a member access
2181/// expression, the type of the base object whose member is being accessed.
2182///
Douglas Gregor7861a802009-11-03 01:35:08 +00002183/// \param Result on a successful parse, contains the parsed unqualified-id.
2184///
2185/// \returns true if parsing fails, false otherwise.
2186bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2187 bool AllowDestructorName,
2188 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002189 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002190 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002191 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002192
2193 // Handle 'A::template B'. This is for template-ids which have not
2194 // already been annotated by ParseOptionalCXXScopeSpecifier().
2195 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002196 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002197 (ObjectType || SS.isSet())) {
2198 TemplateSpecified = true;
2199 TemplateKWLoc = ConsumeToken();
2200 }
2201
Douglas Gregor7861a802009-11-03 01:35:08 +00002202 // unqualified-id:
2203 // identifier
2204 // template-id (when it hasn't already been annotated)
2205 if (Tok.is(tok::identifier)) {
2206 // Consume the identifier.
2207 IdentifierInfo *Id = Tok.getIdentifierInfo();
2208 SourceLocation IdLoc = ConsumeToken();
2209
David Blaikiebbafb8a2012-03-11 07:00:24 +00002210 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002211 // If we're not in C++, only identifiers matter. Record the
2212 // identifier and return.
2213 Result.setIdentifier(Id, IdLoc);
2214 return false;
2215 }
2216
Douglas Gregor7861a802009-11-03 01:35:08 +00002217 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002218 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002219 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002220 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2221 &SS, false, false,
2222 ParsedType(),
2223 /*IsCtorOrDtorName=*/true,
2224 /*NonTrivialTypeSourceInfo=*/true);
2225 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002226 } else {
2227 // We have parsed an identifier.
2228 Result.setIdentifier(Id, IdLoc);
2229 }
2230
2231 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002232 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002233 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2234 EnteringContext, ObjectType,
2235 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002236
2237 return false;
2238 }
2239
2240 // unqualified-id:
2241 // template-id (already parsed and annotated)
2242 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002243 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002244
2245 // If the template-name names the current class, then this is a constructor
2246 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002247 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002248 if (SS.isSet()) {
2249 // C++ [class.qual]p2 specifies that a qualified template-name
2250 // is taken as the constructor name where a constructor can be
2251 // declared. Thus, the template arguments are extraneous, so
2252 // complain about them and remove them entirely.
2253 Diag(TemplateId->TemplateNameLoc,
2254 diag::err_out_of_line_constructor_template_id)
2255 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002256 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002257 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002258 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2259 TemplateId->TemplateNameLoc,
2260 getCurScope(),
2261 &SS, false, false,
2262 ParsedType(),
2263 /*IsCtorOrDtorName=*/true,
2264 /*NontrivialTypeSourceInfo=*/true);
2265 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002266 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002267 ConsumeToken();
2268 return false;
2269 }
2270
2271 Result.setConstructorTemplateId(TemplateId);
2272 ConsumeToken();
2273 return false;
2274 }
2275
Douglas Gregor7861a802009-11-03 01:35:08 +00002276 // We have already parsed a template-id; consume the annotation token as
2277 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002278 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002279 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002280 ConsumeToken();
2281 return false;
2282 }
2283
2284 // unqualified-id:
2285 // operator-function-id
2286 // conversion-function-id
2287 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002288 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002289 return true;
2290
Alexis Hunted0530f2009-11-28 08:58:14 +00002291 // If we have an operator-function-id or a literal-operator-id and the next
2292 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002293 //
2294 // template-id:
2295 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002296 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2297 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002298 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002299 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2300 0, SourceLocation(),
2301 EnteringContext, ObjectType,
2302 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002303
Douglas Gregor7861a802009-11-03 01:35:08 +00002304 return false;
2305 }
2306
David Blaikiebbafb8a2012-03-11 07:00:24 +00002307 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002308 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002309 // C++ [expr.unary.op]p10:
2310 // There is an ambiguity in the unary-expression ~X(), where X is a
2311 // class-name. The ambiguity is resolved in favor of treating ~ as a
2312 // unary complement rather than treating ~X as referring to a destructor.
2313
2314 // Parse the '~'.
2315 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002316
2317 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2318 DeclSpec DS(AttrFactory);
2319 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2320 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2321 Result.setDestructorName(TildeLoc, Type, EndLoc);
2322 return false;
2323 }
2324 return true;
2325 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002326
2327 // Parse the class-name.
2328 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002329 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002330 return true;
2331 }
2332
2333 // Parse the class-name (or template-name in a simple-template-id).
2334 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2335 SourceLocation ClassNameLoc = ConsumeToken();
2336
Douglas Gregorb22ee882010-05-05 05:58:24 +00002337 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002338 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002339 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2340 ClassName, ClassNameLoc,
2341 EnteringContext, ObjectType,
2342 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002343 }
2344
Douglas Gregor7861a802009-11-03 01:35:08 +00002345 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002346 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2347 ClassNameLoc, getCurScope(),
2348 SS, ObjectType,
2349 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002350 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002351 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002352
Douglas Gregor7861a802009-11-03 01:35:08 +00002353 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002354 return false;
2355 }
2356
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002357 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002358 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002359 return true;
2360}
2361
Sebastian Redlbd150f42008-11-21 19:14:01 +00002362/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2363/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002364///
Chris Lattner109faf22009-01-04 21:25:24 +00002365/// This method is called to parse the new expression after the optional :: has
2366/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2367/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002368///
2369/// new-expression:
2370/// '::'[opt] 'new' new-placement[opt] new-type-id
2371/// new-initializer[opt]
2372/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2373/// new-initializer[opt]
2374///
2375/// new-placement:
2376/// '(' expression-list ')'
2377///
Sebastian Redl351bb782008-12-02 14:43:59 +00002378/// new-type-id:
2379/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002380/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002381///
2382/// new-declarator:
2383/// ptr-operator new-declarator[opt]
2384/// direct-new-declarator
2385///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002386/// new-initializer:
2387/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002388/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002389///
John McCalldadc5752010-08-24 06:29:42 +00002390ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002391Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2392 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2393 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002394
2395 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2396 // second form of new-expression. It can't be a new-type-id.
2397
Benjamin Kramerf0623432012-08-23 22:51:59 +00002398 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002399 SourceLocation PlacementLParen, PlacementRParen;
2400
Douglas Gregorf2753b32010-07-13 15:54:32 +00002401 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002402 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002403 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002404 if (Tok.is(tok::l_paren)) {
2405 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002406 BalancedDelimiterTracker T(*this, tok::l_paren);
2407 T.consumeOpen();
2408 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002409 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
2410 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002411 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002412 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002413
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002414 T.consumeClose();
2415 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002416 if (PlacementRParen.isInvalid()) {
2417 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002418 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002419 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002420
Sebastian Redl351bb782008-12-02 14:43:59 +00002421 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002422 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002423 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002424 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002425 } else {
2426 // We still need the type.
2427 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002428 BalancedDelimiterTracker T(*this, tok::l_paren);
2429 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002430 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002431 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002432 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002433 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002434 T.consumeClose();
2435 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002436 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002437 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002438 if (ParseCXXTypeSpecifierSeq(DS))
2439 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002440 else {
2441 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002442 ParseDeclaratorInternal(DeclaratorInfo,
2443 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002444 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002445 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002446 }
2447 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002448 // A new-type-id is a simplified type-id, where essentially the
2449 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002450 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002451 if (ParseCXXTypeSpecifierSeq(DS))
2452 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002453 else {
2454 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002455 ParseDeclaratorInternal(DeclaratorInfo,
2456 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002457 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002458 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002459 if (DeclaratorInfo.isInvalidType()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002460 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002461 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002462 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002463
Sebastian Redl6047f072012-02-16 12:22:20 +00002464 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002465
2466 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002467 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002468 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002469 BalancedDelimiterTracker T(*this, tok::l_paren);
2470 T.consumeOpen();
2471 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002472 if (Tok.isNot(tok::r_paren)) {
2473 CommaLocsTy CommaLocs;
Sebastian Redl351bb782008-12-02 14:43:59 +00002474 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
2475 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002476 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002477 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002478 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002479 T.consumeClose();
2480 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002481 if (ConstructorRParen.isInvalid()) {
2482 SkipUntil(tok::semi, /*StopAtSemi=*/true, /*DontConsume=*/true);
Sebastian Redld65cea82008-12-11 22:51:44 +00002483 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002484 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002485 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2486 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002487 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002488 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002489 Diag(Tok.getLocation(),
2490 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002491 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002492 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002493 if (Initializer.isInvalid())
2494 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002495
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002496 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002497 PlacementArgs, PlacementRParen,
Sebastian Redl6047f072012-02-16 12:22:20 +00002498 TypeIdParens, DeclaratorInfo, Initializer.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002499}
2500
Sebastian Redlbd150f42008-11-21 19:14:01 +00002501/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2502/// passed to ParseDeclaratorInternal.
2503///
2504/// direct-new-declarator:
2505/// '[' expression ']'
2506/// direct-new-declarator '[' constant-expression ']'
2507///
Chris Lattner109faf22009-01-04 21:25:24 +00002508void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002509 // Parse the array dimensions.
2510 bool first = true;
2511 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002512 // An array-size expression can't start with a lambda.
2513 if (CheckProhibitedCXX11Attribute())
2514 continue;
2515
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002516 BalancedDelimiterTracker T(*this, tok::l_square);
2517 T.consumeOpen();
2518
John McCalldadc5752010-08-24 06:29:42 +00002519 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002520 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002521 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002522 // Recover
2523 SkipUntil(tok::r_square);
2524 return;
2525 }
2526 first = false;
2527
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002528 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002529
Bill Wendling44426052012-12-20 19:22:21 +00002530 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002531 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002532 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002533
John McCall084e83d2011-03-24 11:26:52 +00002534 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002535 /*static=*/false, /*star=*/false,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002536 Size.release(),
2537 T.getOpenLocation(),
2538 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002539 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002540
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002541 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002542 return;
2543 }
2544}
2545
2546/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2547/// This ambiguity appears in the syntax of the C++ new operator.
2548///
2549/// new-expression:
2550/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2551/// new-initializer[opt]
2552///
2553/// new-placement:
2554/// '(' expression-list ')'
2555///
John McCall37ad5512010-08-23 06:44:23 +00002556bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002557 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002558 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002559 // The '(' was already consumed.
2560 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002561 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002562 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002563 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002564 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002565 }
2566
2567 // It's not a type, it has to be an expression list.
2568 // Discard the comma locations - ActOnCXXNew has enough parameters.
2569 CommaLocsTy CommaLocs;
2570 return ParseExpressionList(PlacementArgs, CommaLocs);
2571}
2572
2573/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2574/// to free memory allocated by new.
2575///
Chris Lattner109faf22009-01-04 21:25:24 +00002576/// This method is called to parse the 'delete' expression after the optional
2577/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2578/// and "Start" is its location. Otherwise, "Start" is the location of the
2579/// 'delete' token.
2580///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002581/// delete-expression:
2582/// '::'[opt] 'delete' cast-expression
2583/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002584ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002585Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2586 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2587 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002588
2589 // Array delete?
2590 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002591 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002592 // C++11 [expr.delete]p1:
2593 // Whenever the delete keyword is followed by empty square brackets, it
2594 // shall be interpreted as [array delete].
2595 // [Footnote: A lambda expression with a lambda-introducer that consists
2596 // of empty square brackets can follow the delete keyword if
2597 // the lambda expression is enclosed in parentheses.]
2598 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2599 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002600 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002601 BalancedDelimiterTracker T(*this, tok::l_square);
2602
2603 T.consumeOpen();
2604 T.consumeClose();
2605 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002606 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002607 }
2608
John McCalldadc5752010-08-24 06:29:42 +00002609 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002610 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002611 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002612
John McCallb268a282010-08-23 23:25:46 +00002613 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.take());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002614}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002615
Mike Stump11289f42009-09-09 15:08:12 +00002616static UnaryTypeTrait UnaryTypeTraitFromTokKind(tok::TokenKind kind) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002617 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002618 default: llvm_unreachable("Not a known unary type trait.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002619 case tok::kw___has_nothrow_assign: return UTT_HasNothrowAssign;
Joao Matosc9523d42013-03-27 01:34:16 +00002620 case tok::kw___has_nothrow_move_assign: return UTT_HasNothrowMoveAssign;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002621 case tok::kw___has_nothrow_constructor: return UTT_HasNothrowConstructor;
John Wiegley65497cc2011-04-27 23:09:49 +00002622 case tok::kw___has_nothrow_copy: return UTT_HasNothrowCopy;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002623 case tok::kw___has_trivial_assign: return UTT_HasTrivialAssign;
Joao Matosc9523d42013-03-27 01:34:16 +00002624 case tok::kw___has_trivial_move_assign: return UTT_HasTrivialMoveAssign;
Alexis Huntf479f1b2011-05-09 18:22:59 +00002625 case tok::kw___has_trivial_constructor:
2626 return UTT_HasTrivialDefaultConstructor;
Joao Matosc9523d42013-03-27 01:34:16 +00002627 case tok::kw___has_trivial_move_constructor:
2628 return UTT_HasTrivialMoveConstructor;
John Wiegley65497cc2011-04-27 23:09:49 +00002629 case tok::kw___has_trivial_copy: return UTT_HasTrivialCopy;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002630 case tok::kw___has_trivial_destructor: return UTT_HasTrivialDestructor;
2631 case tok::kw___has_virtual_destructor: return UTT_HasVirtualDestructor;
2632 case tok::kw___is_abstract: return UTT_IsAbstract;
John Wiegley65497cc2011-04-27 23:09:49 +00002633 case tok::kw___is_arithmetic: return UTT_IsArithmetic;
2634 case tok::kw___is_array: return UTT_IsArray;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002635 case tok::kw___is_class: return UTT_IsClass;
John Wiegley65497cc2011-04-27 23:09:49 +00002636 case tok::kw___is_complete_type: return UTT_IsCompleteType;
2637 case tok::kw___is_compound: return UTT_IsCompound;
2638 case tok::kw___is_const: return UTT_IsConst;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002639 case tok::kw___is_empty: return UTT_IsEmpty;
2640 case tok::kw___is_enum: return UTT_IsEnum;
Douglas Gregordca70af2011-12-03 18:14:24 +00002641 case tok::kw___is_final: return UTT_IsFinal;
John Wiegley65497cc2011-04-27 23:09:49 +00002642 case tok::kw___is_floating_point: return UTT_IsFloatingPoint;
2643 case tok::kw___is_function: return UTT_IsFunction;
2644 case tok::kw___is_fundamental: return UTT_IsFundamental;
2645 case tok::kw___is_integral: return UTT_IsIntegral;
John McCallbf4a7d72012-09-25 07:32:49 +00002646 case tok::kw___is_interface_class: return UTT_IsInterfaceClass;
John Wiegley65497cc2011-04-27 23:09:49 +00002647 case tok::kw___is_lvalue_reference: return UTT_IsLvalueReference;
2648 case tok::kw___is_member_function_pointer: return UTT_IsMemberFunctionPointer;
2649 case tok::kw___is_member_object_pointer: return UTT_IsMemberObjectPointer;
2650 case tok::kw___is_member_pointer: return UTT_IsMemberPointer;
2651 case tok::kw___is_object: return UTT_IsObject;
Chandler Carruth79803482011-04-23 10:47:20 +00002652 case tok::kw___is_literal: return UTT_IsLiteral;
Chandler Carruth65fa1fd2011-04-24 02:49:28 +00002653 case tok::kw___is_literal_type: return UTT_IsLiteral;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002654 case tok::kw___is_pod: return UTT_IsPOD;
John Wiegley65497cc2011-04-27 23:09:49 +00002655 case tok::kw___is_pointer: return UTT_IsPointer;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002656 case tok::kw___is_polymorphic: return UTT_IsPolymorphic;
John Wiegley65497cc2011-04-27 23:09:49 +00002657 case tok::kw___is_reference: return UTT_IsReference;
John Wiegley65497cc2011-04-27 23:09:49 +00002658 case tok::kw___is_rvalue_reference: return UTT_IsRvalueReference;
2659 case tok::kw___is_scalar: return UTT_IsScalar;
2660 case tok::kw___is_signed: return UTT_IsSigned;
2661 case tok::kw___is_standard_layout: return UTT_IsStandardLayout;
2662 case tok::kw___is_trivial: return UTT_IsTrivial;
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002663 case tok::kw___is_trivially_copyable: return UTT_IsTriviallyCopyable;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002664 case tok::kw___is_union: return UTT_IsUnion;
John Wiegley65497cc2011-04-27 23:09:49 +00002665 case tok::kw___is_unsigned: return UTT_IsUnsigned;
2666 case tok::kw___is_void: return UTT_IsVoid;
2667 case tok::kw___is_volatile: return UTT_IsVolatile;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002668 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002669}
2670
2671static BinaryTypeTrait BinaryTypeTraitFromTokKind(tok::TokenKind kind) {
2672 switch(kind) {
Francois Pichet347c4c72010-12-07 00:55:57 +00002673 default: llvm_unreachable("Not a known binary type trait");
Francois Pichet34b21132010-12-08 22:35:30 +00002674 case tok::kw___is_base_of: return BTT_IsBaseOf;
John Wiegley65497cc2011-04-27 23:09:49 +00002675 case tok::kw___is_convertible: return BTT_IsConvertible;
2676 case tok::kw___is_same: return BTT_IsSame;
Francois Pichet34b21132010-12-08 22:35:30 +00002677 case tok::kw___builtin_types_compatible_p: return BTT_TypeCompatible;
Douglas Gregor8006e762011-01-27 20:28:01 +00002678 case tok::kw___is_convertible_to: return BTT_IsConvertibleTo;
Douglas Gregor1be329d2012-02-23 07:33:15 +00002679 case tok::kw___is_trivially_assignable: return BTT_IsTriviallyAssignable;
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002680 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002681}
2682
Douglas Gregor29c42f22012-02-24 07:38:34 +00002683static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2684 switch (kind) {
2685 default: llvm_unreachable("Not a known type trait");
2686 case tok::kw___is_trivially_constructible:
2687 return TT_IsTriviallyConstructible;
2688 }
2689}
2690
John Wiegley6242b6a2011-04-28 00:16:57 +00002691static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2692 switch(kind) {
2693 default: llvm_unreachable("Not a known binary type trait");
2694 case tok::kw___array_rank: return ATT_ArrayRank;
2695 case tok::kw___array_extent: return ATT_ArrayExtent;
2696 }
2697}
2698
John Wiegleyf9f65842011-04-25 06:54:41 +00002699static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2700 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002701 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002702 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2703 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2704 }
2705}
2706
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002707/// ParseUnaryTypeTrait - Parse the built-in unary type-trait
2708/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2709/// templates.
2710///
2711/// primary-expression:
2712/// [GNU] unary-type-trait '(' type-id ')'
2713///
John McCalldadc5752010-08-24 06:29:42 +00002714ExprResult Parser::ParseUnaryTypeTrait() {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002715 UnaryTypeTrait UTT = UnaryTypeTraitFromTokKind(Tok.getKind());
2716 SourceLocation Loc = ConsumeToken();
2717
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002718 BalancedDelimiterTracker T(*this, tok::l_paren);
2719 if (T.expectAndConsume(diag::err_expected_lparen))
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002720 return ExprError();
2721
2722 // FIXME: Error reporting absolutely sucks! If the this fails to parse a type
2723 // there will be cryptic errors about mismatched parentheses and missing
2724 // specifiers.
Douglas Gregor220cac52009-02-18 17:45:20 +00002725 TypeResult Ty = ParseTypeName();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002726
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002727 T.consumeClose();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002728
Douglas Gregor220cac52009-02-18 17:45:20 +00002729 if (Ty.isInvalid())
2730 return ExprError();
2731
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002732 return Actions.ActOnUnaryTypeTrait(UTT, Loc, Ty.get(), T.getCloseLocation());
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002733}
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002734
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002735/// ParseBinaryTypeTrait - Parse the built-in binary type-trait
2736/// pseudo-functions that allow implementation of the TR1/C++0x type traits
2737/// templates.
2738///
2739/// primary-expression:
2740/// [GNU] binary-type-trait '(' type-id ',' type-id ')'
2741///
2742ExprResult Parser::ParseBinaryTypeTrait() {
2743 BinaryTypeTrait BTT = BinaryTypeTraitFromTokKind(Tok.getKind());
2744 SourceLocation Loc = ConsumeToken();
2745
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002746 BalancedDelimiterTracker T(*this, tok::l_paren);
2747 if (T.expectAndConsume(diag::err_expected_lparen))
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002748 return ExprError();
2749
2750 TypeResult LhsTy = ParseTypeName();
2751 if (LhsTy.isInvalid()) {
2752 SkipUntil(tok::r_paren);
2753 return ExprError();
2754 }
2755
2756 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2757 SkipUntil(tok::r_paren);
2758 return ExprError();
2759 }
2760
2761 TypeResult RhsTy = ParseTypeName();
2762 if (RhsTy.isInvalid()) {
2763 SkipUntil(tok::r_paren);
2764 return ExprError();
2765 }
2766
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002767 T.consumeClose();
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002768
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002769 return Actions.ActOnBinaryTypeTrait(BTT, Loc, LhsTy.get(), RhsTy.get(),
2770 T.getCloseLocation());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002771}
2772
Douglas Gregor29c42f22012-02-24 07:38:34 +00002773/// \brief Parse the built-in type-trait pseudo-functions that allow
2774/// implementation of the TR1/C++11 type traits templates.
2775///
2776/// primary-expression:
2777/// type-trait '(' type-id-seq ')'
2778///
2779/// type-id-seq:
2780/// type-id ...[opt] type-id-seq[opt]
2781///
2782ExprResult Parser::ParseTypeTrait() {
2783 TypeTrait Kind = TypeTraitFromTokKind(Tok.getKind());
2784 SourceLocation Loc = ConsumeToken();
2785
2786 BalancedDelimiterTracker Parens(*this, tok::l_paren);
2787 if (Parens.expectAndConsume(diag::err_expected_lparen))
2788 return ExprError();
2789
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002790 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002791 do {
2792 // Parse the next type.
2793 TypeResult Ty = ParseTypeName();
2794 if (Ty.isInvalid()) {
2795 Parens.skipToEnd();
2796 return ExprError();
2797 }
2798
2799 // Parse the ellipsis, if present.
2800 if (Tok.is(tok::ellipsis)) {
2801 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2802 if (Ty.isInvalid()) {
2803 Parens.skipToEnd();
2804 return ExprError();
2805 }
2806 }
2807
2808 // Add this type to the list of arguments.
2809 Args.push_back(Ty.get());
2810
2811 if (Tok.is(tok::comma)) {
2812 ConsumeToken();
2813 continue;
2814 }
2815
2816 break;
2817 } while (true);
2818
2819 if (Parens.consumeClose())
2820 return ExprError();
2821
2822 return Actions.ActOnTypeTrait(Kind, Loc, Args, Parens.getCloseLocation());
2823}
2824
John Wiegley6242b6a2011-04-28 00:16:57 +00002825/// ParseArrayTypeTrait - Parse the built-in array type-trait
2826/// pseudo-functions.
2827///
2828/// primary-expression:
2829/// [Embarcadero] '__array_rank' '(' type-id ')'
2830/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2831///
2832ExprResult Parser::ParseArrayTypeTrait() {
2833 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2834 SourceLocation Loc = ConsumeToken();
2835
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002836 BalancedDelimiterTracker T(*this, tok::l_paren);
2837 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegley6242b6a2011-04-28 00:16:57 +00002838 return ExprError();
2839
2840 TypeResult Ty = ParseTypeName();
2841 if (Ty.isInvalid()) {
2842 SkipUntil(tok::comma);
2843 SkipUntil(tok::r_paren);
2844 return ExprError();
2845 }
2846
2847 switch (ATT) {
2848 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002849 T.consumeClose();
2850 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), NULL,
2851 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002852 }
2853 case ATT_ArrayExtent: {
2854 if (ExpectAndConsume(tok::comma, diag::err_expected_comma)) {
2855 SkipUntil(tok::r_paren);
2856 return ExprError();
2857 }
2858
2859 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002860 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002861
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002862 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2863 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002864 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002865 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002866 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002867}
2868
John Wiegleyf9f65842011-04-25 06:54:41 +00002869/// ParseExpressionTrait - Parse built-in expression-trait
2870/// pseudo-functions like __is_lvalue_expr( xxx ).
2871///
2872/// primary-expression:
2873/// [Embarcadero] expression-trait '(' expression ')'
2874///
2875ExprResult Parser::ParseExpressionTrait() {
2876 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2877 SourceLocation Loc = ConsumeToken();
2878
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002879 BalancedDelimiterTracker T(*this, tok::l_paren);
2880 if (T.expectAndConsume(diag::err_expected_lparen))
John Wiegleyf9f65842011-04-25 06:54:41 +00002881 return ExprError();
2882
2883 ExprResult Expr = ParseExpression();
2884
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002885 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002886
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002887 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2888 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002889}
2890
2891
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002892/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2893/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2894/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002895ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002896Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002897 ParsedType &CastTy,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002898 BalancedDelimiterTracker &Tracker) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002899 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002900 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2901 assert(isTypeIdInParens() && "Not a type-id!");
2902
John McCalldadc5752010-08-24 06:29:42 +00002903 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00002904 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002905
2906 // We need to disambiguate a very ugly part of the C++ syntax:
2907 //
2908 // (T())x; - type-id
2909 // (T())*x; - type-id
2910 // (T())/x; - expression
2911 // (T()); - expression
2912 //
2913 // The bad news is that we cannot use the specialized tentative parser, since
2914 // it can only verify that the thing inside the parens can be parsed as
2915 // type-id, it is not useful for determining the context past the parens.
2916 //
2917 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00002918 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002919 //
2920 // It uses a scheme similar to parsing inline methods. The parenthesized
2921 // tokens are cached, the context that follows is determined (possibly by
2922 // parsing a cast-expression), and then we re-introduce the cached tokens
2923 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002924
Mike Stump11289f42009-09-09 15:08:12 +00002925 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002926 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002927
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002928 // Store the tokens of the parentheses. We will parse them after we determine
2929 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00002930 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002931 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002932 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002933 return ExprError();
2934 }
2935
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002936 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002937 ParseAs = CompoundLiteral;
2938 } else {
2939 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00002940 // FIXME: Special-case ++ and --: "(S())++;" is not a cast-expression
2941 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
2942 NotCastExpr = true;
2943 } else {
2944 // Try parsing the cast-expression that may follow.
2945 // If it is not a cast-expression, NotCastExpr will be true and no token
2946 // will be consumed.
2947 Result = ParseCastExpression(false/*isUnaryExpression*/,
2948 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00002949 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002950 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00002951 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00002952 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002953
2954 // If we parsed a cast-expression, it's really a type-id, otherwise it's
2955 // an expression.
2956 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002957 }
2958
Mike Stump11289f42009-09-09 15:08:12 +00002959 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002960 Toks.push_back(Tok);
2961 // Re-enter the stored parenthesized tokens into the token stream, so we may
2962 // parse them now.
2963 PP.EnterTokenStream(Toks.data(), Toks.size(),
2964 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
2965 // Drop the current token and bring the first cached one. It's the same token
2966 // as when we entered this function.
2967 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002968
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002969 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002970 // Parse the type declarator.
2971 DeclSpec DS(AttrFactory);
2972 ParseSpecifierQualifierList(DS);
2973 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
2974 ParseDeclarator(DeclaratorInfo);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002975
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002976 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002977 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002978
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002979 if (ParseAs == CompoundLiteral) {
2980 ExprType = CompoundLiteral;
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002981 TypeResult Ty = ParseTypeName();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002982 return ParseCompoundLiteralExpression(Ty.get(),
2983 Tracker.getOpenLocation(),
2984 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002987 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
2988 assert(ParseAs == CastExpr);
2989
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00002990 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002991 return ExprError();
2992
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002993 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002994 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002995 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
2996 DeclaratorInfo, CastTy,
2997 Tracker.getCloseLocation(), Result.take());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002998 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002999 }
Mike Stump11289f42009-09-09 15:08:12 +00003000
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003001 // Not a compound literal, and not followed by a cast-expression.
3002 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003003
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003004 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003005 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003006 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003007 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
3008 Tok.getLocation(), Result.take());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003009
3010 // Match the ')'.
3011 if (Result.isInvalid()) {
3012 SkipUntil(tok::r_paren);
3013 return ExprError();
3014 }
Mike Stump11289f42009-09-09 15:08:12 +00003015
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003016 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003017 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003018}