blob: f0b81024fe67fd962ed4d0ef33da160e165aa527 [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//===----------------------------------------------------------------------===//
Erik Verbruggen888d52a2014-01-15 09:15:43 +000013#include "clang/AST/ASTContext.h"
Douglas Gregor94a32472011-01-11 00:33:19 +000014#include "RAIIObjectsForParser.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "clang/Parse/Parser.h"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Vali2b391ab2013-09-26 19:54:12 +000025
Chris Lattner29375652006-12-04 18:06:35 +000026using namespace clang;
27
Alp Tokerf990cef2014-01-07 02:35:33 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
30 // template name
31 case tok::unknown: return 0;
32 // casts
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
37 default:
38 llvm_unreachable("Unknown type for digraph error message.");
39 }
40}
41
Richard Smith55858492011-04-14 21:45:45 +000042// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000047 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48}
49
50// Suggest fixit for "<::" after a cast.
51static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
54 if (!AtDigraph)
55 PP.Lex(DigraphToken);
56 PP.Lex(ColonToken);
57
58 SourceRange Range;
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
Alp Tokerf990cef2014-01-07 02:35:33 +000062 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
Richard Smith55858492011-04-14 21:45:45 +000064
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000068 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
71
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
74 if (!AtDigraph)
75 PP.EnterToken(DigraphToken);
76}
77
Richard Trieu01fc0012011-09-19 19:01:00 +000078// Check for '<::' which should be '< ::' instead of '[:' when following
79// a template name.
80void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 bool EnteringContext,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000088 return;
89
90 TemplateTy Template;
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
97 return;
98
Alp Tokerf990cef2014-01-07 02:35:33 +000099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100 /*AtDigraph*/false);
Richard Trieu01fc0012011-09-19 19:01:00 +0000101}
102
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000103/// \brief Emits an error for a left parentheses after a double colon.
104///
105/// When a '(' is found after a '::', emit an error. Attempt to fix the token
Nico Weber6be9b252012-11-29 05:29:23 +0000106/// stream by removing the '(', and the matching ')' if found.
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000107void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
109 return;
110
David Majnemer6ca445e2014-12-17 01:39:22 +0000111 Token LParen = Tok;
112 Token NextTok = GetLookAheadToken(1);
113 Token StarTok = NextTok;
114 // Check for (identifier or (*identifier
115 Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
116 if (IdentifierTok.isNot(tok::identifier))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000117 return;
David Majnemer6ca445e2014-12-17 01:39:22 +0000118 // Eat the '('.
119 ConsumeParen();
120 Token RParen;
Benjamin Kramerd503c1c2015-03-08 18:11:59 +0000121 RParen.setLocation(SourceLocation());
David Majnemer6ca445e2014-12-17 01:39:22 +0000122 // Do we have a ')' ?
123 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
124 if (NextTok.is(tok::r_paren)) {
125 RParen = NextTok;
126 // Eat the '*' if it is present.
127 if (StarTok.is(tok::star))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000128 ConsumeToken();
David Majnemer6ca445e2014-12-17 01:39:22 +0000129 // Eat the identifier.
130 ConsumeToken();
131 // Add the identifier token back.
132 PP.EnterToken(IdentifierTok);
133 // Add the '*' back if it was present.
134 if (StarTok.is(tok::star))
135 PP.EnterToken(StarTok);
136 // Eat the ')'.
137 ConsumeParen();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000138 }
139
David Majnemer6ca445e2014-12-17 01:39:22 +0000140 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
141 << FixItHint::CreateRemoval(LParen.getLocation())
142 << FixItHint::CreateRemoval(RParen.getLocation());
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000143}
144
Mike Stump11289f42009-09-09 15:08:12 +0000145/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000146///
147/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000148/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000149/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000150///
151/// '::'[opt] nested-name-specifier
152/// '::'
153///
154/// nested-name-specifier:
155/// type-name '::'
156/// namespace-name '::'
157/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000158/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000159///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000160///
Mike Stump11289f42009-09-09 15:08:12 +0000161/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000162/// nested-name-specifier (or empty)
163///
Mike Stump11289f42009-09-09 15:08:12 +0000164/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000165/// the "." or "->" of a member access expression, this parameter provides the
166/// type of the object whose members are being accessed.
167///
168/// \param EnteringContext whether we will be entering into the context of
169/// the nested-name-specifier after parsing it.
170///
Douglas Gregore610ada2010-02-24 18:44:31 +0000171/// \param MayBePseudoDestructor When non-NULL, points to a flag that
172/// indicates whether this nested-name-specifier may be part of a
173/// pseudo-destructor name. In this case, the flag will be set false
174/// if we don't actually end up parsing a destructor name. Moreorover,
175/// if we do end up determining that we are parsing a destructor name,
176/// the last component of the nested-name-specifier is not parsed as
177/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000178///
179/// \param IsTypename If \c true, this nested-name-specifier is known to be
180/// part of a type name. This is used to improve error recovery.
181///
182/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
183/// filled in with the leading identifier in the last component of the
184/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000185///
John McCall1f476a12010-02-26 08:45:28 +0000186/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000187bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000188 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000189 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000190 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000191 bool IsTypename,
192 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000193 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000194 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000195
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000196 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000197 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000198 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000199 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
200 Tok.getAnnotationRange(),
201 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000202 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000203 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000204 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000205
Larisse Voufob959c3c2013-08-06 05:49:26 +0000206 if (Tok.is(tok::annot_template_id)) {
207 // If the current token is an annotated template id, it may already have
208 // a scope specifier. Restore it.
209 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
210 SS = TemplateId->SS;
211 }
212
Nico Weberc60aa712015-02-16 22:32:46 +0000213 // Has to happen before any "return false"s in this function.
214 bool CheckForDestructor = false;
215 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
216 CheckForDestructor = true;
217 *MayBePseudoDestructor = false;
218 }
219
Richard Smith7447af42013-03-26 01:15:19 +0000220 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000221 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000222
Douglas Gregor7f741122009-02-25 19:37:18 +0000223 bool HasScopeSpecifier = false;
224
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000225 if (Tok.is(tok::coloncolon)) {
226 // ::new and ::delete aren't nested-name-specifiers.
227 tok::TokenKind NextKind = NextToken().getKind();
228 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
229 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000230
David Majnemere8fb28f2014-12-29 19:19:18 +0000231 if (NextKind == tok::l_brace) {
232 // It is invalid to have :: {, consume the scope qualifier and pretend
233 // like we never saw it.
234 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
235 } else {
236 // '::' - Global scope qualifier.
237 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
238 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000239
David Majnemere8fb28f2014-12-29 19:19:18 +0000240 CheckForLParenAfterColonColon();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000241
David Majnemere8fb28f2014-12-29 19:19:18 +0000242 HasScopeSpecifier = true;
243 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000244 }
245
Nikola Smiljanic67860242014-09-26 00:28:20 +0000246 if (Tok.is(tok::kw___super)) {
247 SourceLocation SuperLoc = ConsumeToken();
248 if (!Tok.is(tok::coloncolon)) {
249 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
250 return true;
251 }
252
253 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
254 }
255
Richard Smitha9d10012014-10-04 01:57:39 +0000256 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000257 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000258 DeclSpec DS(AttrFactory);
259 SourceLocation DeclLoc = Tok.getLocation();
260 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000261
262 SourceLocation CCLoc;
263 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000264 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
265 return false;
266 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000267
David Blaikie15a430a2011-12-04 05:04:18 +0000268 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
269 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
270
271 HasScopeSpecifier = true;
272 }
273
Douglas Gregor7f741122009-02-25 19:37:18 +0000274 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000275 if (HasScopeSpecifier) {
276 // C++ [basic.lookup.classref]p5:
277 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000278 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000279 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000280 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000281 // the class-name-or-namespace-name is looked up in global scope as a
282 // class-name or namespace-name.
283 //
284 // To implement this, we clear out the object type as soon as we've
285 // seen a leading '::' or part of a nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000286 ObjectType = nullptr;
287
Douglas Gregor2436e712009-09-17 21:32:03 +0000288 if (Tok.is(tok::code_completion)) {
289 // Code completion for a nested-name-specifier, where the code
290 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000291 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000292 // Include code completion token into the range of the scope otherwise
293 // when we try to annotate the scope tokens the dangling code completion
294 // token will cause assertion in
295 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000296 SS.setEndLoc(Tok.getLocation());
297 cutOffParsing();
298 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000299 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000300 }
Mike Stump11289f42009-09-09 15:08:12 +0000301
Douglas Gregor7f741122009-02-25 19:37:18 +0000302 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000303 // nested-name-specifier 'template'[opt] simple-template-id '::'
304
305 // Parse the optional 'template' keyword, then make sure we have
306 // 'identifier <' after it.
307 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000308 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000309 // nested-name-specifier, since they aren't allowed to start with
310 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000311 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000312 break;
313
Douglas Gregor120635b2009-11-11 16:39:34 +0000314 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000315 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000316
Douglas Gregor71395fa2009-11-04 00:56:37 +0000317 UnqualifiedId TemplateName;
318 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000319 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000320 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000321 ConsumeToken();
322 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000323 // We don't need to actually parse the unqualified-id in this case,
324 // because a simple-template-id cannot start with 'operator', but
325 // go ahead and parse it anyway for consistency with the case where
326 // we already annotated the template-id.
327 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000328 TemplateName)) {
329 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000330 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000331 }
Richard Smithd091dc12013-12-05 00:58:33 +0000332
Alexis Hunted0530f2009-11-28 08:58:14 +0000333 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
334 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000335 Diag(TemplateName.getSourceRange().getBegin(),
336 diag::err_id_after_template_in_nested_name_spec)
337 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000338 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000339 break;
340 }
341 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000342 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000343 break;
344 }
Mike Stump11289f42009-09-09 15:08:12 +0000345
Douglas Gregor120635b2009-11-11 16:39:34 +0000346 // If the next token is not '<', we have a qualified-id that refers
347 // to a template name, such as T::template apply, but is not a
348 // template-id.
349 if (Tok.isNot(tok::less)) {
350 TPA.Revert();
351 break;
352 }
353
354 // Commit to parsing the template-id.
355 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000356 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000357 if (TemplateNameKind TNK
358 = Actions.ActOnDependentTemplateName(getCurScope(),
359 SS, TemplateKWLoc, TemplateName,
360 ObjectType, EnteringContext,
361 Template)) {
362 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
363 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000364 return true;
365 } else
John McCall1f476a12010-02-26 08:45:28 +0000366 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000367
Chris Lattner0eed3a62009-06-26 03:47:46 +0000368 continue;
369 }
Mike Stump11289f42009-09-09 15:08:12 +0000370
Douglas Gregor7f741122009-02-25 19:37:18 +0000371 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000372 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000373 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000374 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000375 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000376 // So we need to check whether the template-id is a simple-template-id of
377 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000378 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000379 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000380 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
381 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000382 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000383 }
384
Richard Smith7447af42013-03-26 01:15:19 +0000385 if (LastII)
386 *LastII = TemplateId->Name;
387
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000388 // Consume the template-id token.
389 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000390
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000391 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
392 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000393
David Blaikie8c045bc2011-11-07 03:30:03 +0000394 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000395
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000396 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000397 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000398
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000399 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000400 SS,
401 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000402 TemplateId->Template,
403 TemplateId->TemplateNameLoc,
404 TemplateId->LAngleLoc,
405 TemplateArgsPtr,
406 TemplateId->RAngleLoc,
407 CCLoc,
408 EnteringContext)) {
409 SourceLocation StartLoc
410 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
411 : TemplateId->TemplateNameLoc;
412 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000413 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000414
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000415 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000416 }
417
Chris Lattnere2355f72009-06-26 03:52:38 +0000418 // The rest of the nested-name-specifier possibilities start with
419 // tok::identifier.
420 if (Tok.isNot(tok::identifier))
421 break;
422
423 IdentifierInfo &II = *Tok.getIdentifierInfo();
424
425 // nested-name-specifier:
426 // type-name '::'
427 // namespace-name '::'
428 // nested-name-specifier identifier '::'
429 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000430
431 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
432 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000433 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000434 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
435 Tok.getLocation(),
436 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000437 EnteringContext) &&
438 // If the token after the colon isn't an identifier, it's still an
439 // error, but they probably meant something else strange so don't
440 // recover like this.
441 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000442 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000443 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000444 // Recover as if the user wrote '::'.
445 Next.setKind(tok::coloncolon);
446 }
Chris Lattner1c428032009-12-07 01:36:53 +0000447 }
David Majnemerf58efd92014-12-29 23:12:23 +0000448
449 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
450 // It is invalid to have :: {, consume the scope qualifier and pretend
451 // like we never saw it.
452 Token Identifier = Tok; // Stash away the identifier.
453 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000454 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
455 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000456 UnconsumeToken(Identifier); // Stick the identifier back.
457 Next = NextToken(); // Point Next at the '{' token.
458 }
459
Chris Lattnere2355f72009-06-26 03:52:38 +0000460 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000461 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Nico Weber61281fa2014-07-26 22:15:25 +0000462 !Actions.isNonTypeNestedNameSpecifier(
463 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000464 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000465 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000466 }
467
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000468 if (ColonIsSacred) {
469 const Token &Next2 = GetLookAheadToken(2);
470 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
471 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
472 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
473 << Next2.getName()
474 << FixItHint::CreateReplacement(Next.getLocation(), ":");
475 Token ColonColon;
476 PP.Lex(ColonColon);
477 ColonColon.setKind(tok::colon);
478 PP.EnterToken(ColonColon);
479 break;
480 }
481 }
482
Richard Smith7447af42013-03-26 01:15:19 +0000483 if (LastII)
484 *LastII = &II;
485
Chris Lattnere2355f72009-06-26 03:52:38 +0000486 // We have an identifier followed by a '::'. Lookup this name
487 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000488 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000489 SourceLocation IdLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000490 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
Chris Lattner1c428032009-12-07 01:36:53 +0000491 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000492 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000493 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000495 CheckForLParenAfterColonColon();
496
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000497 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000498 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor90c99722011-02-24 00:17:56 +0000499 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000500 ObjectType, EnteringContext, SS,
501 false, CorrectionFlagPtr)) {
502 // Identifier is not recognized as a nested name, but we can have
503 // mistyped '::' instead of ':'.
504 if (CorrectionFlagPtr && IsCorrectedToColon) {
505 ColonColon.setKind(tok::colon);
506 PP.EnterToken(Tok);
507 PP.EnterToken(ColonColon);
508 Tok = Identifier;
509 break;
510 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000511 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000512 }
513 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000514 continue;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Richard Trieu01fc0012011-09-19 19:01:00 +0000517 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000518
Chris Lattnere2355f72009-06-26 03:52:38 +0000519 // nested-name-specifier:
520 // type-name '<'
521 if (Next.is(tok::less)) {
522 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000523 UnqualifiedId TemplateName;
524 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000525 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000526 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000527 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000528 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000529 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000530 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000531 Template,
532 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000533 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000534 // with a template-id annotation. We do not permit the
535 // template-id to be translated into a type annotation,
536 // because some clients (e.g., the parsing of class template
537 // specializations) still want to see the original template-id
538 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000539 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000540 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
541 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000542 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000543 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000544 }
545
Douglas Gregor20c38a72010-05-21 23:43:39 +0000546 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000547 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000548 // We have something like t::getAs<T>, where getAs is a
549 // member of an unknown specialization. However, this will only
550 // parse correctly as a template, so suggest the keyword 'template'
551 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000552 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000553 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000554 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000555
556 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000557 << II.getName()
558 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
559
Douglas Gregorbb119652010-06-16 23:00:59 +0000560 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000561 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000562 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000563 TemplateName, ObjectType,
564 EnteringContext, Template)) {
565 // Consume the identifier.
566 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000567 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
568 TemplateName, false))
569 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000570 }
571 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000572 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000573
Douglas Gregor20c38a72010-05-21 23:43:39 +0000574 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000575 }
576 }
577
Douglas Gregor7f741122009-02-25 19:37:18 +0000578 // We don't have any tokens that form the beginning of a
579 // nested-name-specifier, so we're done.
580 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Douglas Gregore610ada2010-02-24 18:44:31 +0000583 // Even if we didn't see any pieces of a nested-name-specifier, we
584 // still check whether there is a tilde in this position, which
585 // indicates a potential pseudo-destructor.
586 if (CheckForDestructor && Tok.is(tok::tilde))
587 *MayBePseudoDestructor = true;
588
John McCall1f476a12010-02-26 08:45:28 +0000589 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000590}
591
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000592ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
593 Token &Replacement) {
594 SourceLocation TemplateKWLoc;
595 UnqualifiedId Name;
596 if (ParseUnqualifiedId(SS,
597 /*EnteringContext=*/false,
598 /*AllowDestructorName=*/false,
599 /*AllowConstructorName=*/false,
David Blaikieefdccaa2016-01-15 23:43:34 +0000600 /*ObjectType=*/nullptr, TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000601 return ExprError();
602
603 // This is only the direct operand of an & operator if it is not
604 // followed by a postfix-expression suffix.
605 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
606 isAddressOfOperand = false;
607
608 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
609 Tok.is(tok::l_paren), isAddressOfOperand,
610 nullptr, /*IsInlineAsmIdentifier=*/false,
611 &Replacement);
612}
613
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000614/// ParseCXXIdExpression - Handle id-expression.
615///
616/// id-expression:
617/// unqualified-id
618/// qualified-id
619///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000620/// qualified-id:
621/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
622/// '::' identifier
623/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000624/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000625///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000626/// NOTE: The standard specifies that, for qualified-id, the parser does not
627/// expect:
628///
629/// '::' conversion-function-id
630/// '::' '~' class-name
631///
632/// This may cause a slight inconsistency on diagnostics:
633///
634/// class C {};
635/// namespace A {}
636/// void f() {
637/// :: A :: ~ C(); // Some Sema error about using destructor with a
638/// // namespace.
639/// :: ~ C(); // Some Parser error like 'unexpected ~'.
640/// }
641///
642/// We simplify the parser a bit and make it work like:
643///
644/// qualified-id:
645/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
646/// '::' unqualified-id
647///
648/// That way Sema can handle and report similar errors for namespaces and the
649/// global scope.
650///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000651/// The isAddressOfOperand parameter indicates that this id-expression is a
652/// direct operand of the address-of operator. This is, besides member contexts,
653/// the only place where a qualified-id naming a non-static class member may
654/// appear.
655///
John McCalldadc5752010-08-24 06:29:42 +0000656ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000657 // qualified-id:
658 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
659 // '::' unqualified-id
660 //
661 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000662 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000663
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000664 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000665 ExprResult Result =
666 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000667 if (Result.isUnset()) {
668 // If the ExprResult is valid but null, then typo correction suggested a
669 // keyword replacement that needs to be reparsed.
670 UnconsumeToken(Replacement);
671 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
672 }
673 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
674 "for a previous keyword suggestion");
675 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000676}
677
Richard Smith21b3ab42013-05-09 21:36:41 +0000678/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000679///
680/// lambda-expression:
681/// lambda-introducer lambda-declarator[opt] compound-statement
682///
683/// lambda-introducer:
684/// '[' lambda-capture[opt] ']'
685///
686/// lambda-capture:
687/// capture-default
688/// capture-list
689/// capture-default ',' capture-list
690///
691/// capture-default:
692/// '&'
693/// '='
694///
695/// capture-list:
696/// capture
697/// capture-list ',' capture
698///
699/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000700/// simple-capture
701/// init-capture [C++1y]
702///
703/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000704/// identifier
705/// '&' identifier
706/// 'this'
707///
Richard Smith21b3ab42013-05-09 21:36:41 +0000708/// init-capture: [C++1y]
709/// identifier initializer
710/// '&' identifier initializer
711///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000712/// lambda-declarator:
713/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
714/// 'mutable'[opt] exception-specification[opt]
715/// trailing-return-type[opt]
716///
717ExprResult Parser::ParseLambdaExpression() {
718 // Parse lambda-introducer.
719 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000720 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000721 if (DiagID) {
722 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000723 SkipUntil(tok::r_square, StopAtSemi);
724 SkipUntil(tok::l_brace, StopAtSemi);
725 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000726 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000727 }
728
729 return ParseLambdaExpressionAfterIntroducer(Intro);
730}
731
732/// TryParseLambdaExpression - Use lookahead and potentially tentative
733/// parsing to determine if we are looking at a C++0x lambda expression, and parse
734/// it if we are.
735///
736/// If we are not looking at a lambda expression, returns ExprError().
737ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000738 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000739 && Tok.is(tok::l_square)
740 && "Not at the start of a possible lambda expression.");
741
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000742 const Token Next = NextToken();
743 if (Next.is(tok::eof)) // Nothing else to lookup here...
744 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000746 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000747 // If lookahead indicates this is a lambda...
748 if (Next.is(tok::r_square) || // []
749 Next.is(tok::equal) || // [=
750 (Next.is(tok::amp) && // [&] or [&,
751 (After.is(tok::r_square) ||
752 After.is(tok::comma))) ||
753 (Next.is(tok::identifier) && // [identifier]
754 After.is(tok::r_square))) {
755 return ParseLambdaExpression();
756 }
757
Eli Friedmanc7c97142012-01-04 02:40:39 +0000758 // If lookahead indicates an ObjC message send...
759 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000760 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000761 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000762 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000763
Eli Friedmanc7c97142012-01-04 02:40:39 +0000764 // Here, we're stuck: lambda introducers and Objective-C message sends are
765 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
766 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
767 // writing two routines to parse a lambda introducer, just try to parse
768 // a lambda introducer first, and fall back if that fails.
769 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000770 LambdaIntroducer Intro;
771 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000772 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000773
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000774 return ParseLambdaExpressionAfterIntroducer(Intro);
775}
776
Richard Smithf44d2a82013-05-21 22:21:19 +0000777/// \brief Parse a lambda introducer.
778/// \param Intro A LambdaIntroducer filled in with information about the
779/// contents of the lambda-introducer.
780/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
781/// message send and a lambda expression. In this mode, we will
782/// sometimes skip the initializers for init-captures and not fully
783/// populate \p Intro. This flag will be set to \c true if we do so.
784/// \return A DiagnosticID if it hit something unexpected. The location for
785/// for the diagnostic is that of the current token.
786Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
787 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000788 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000789
790 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000791 BalancedDelimiterTracker T(*this, tok::l_square);
792 T.consumeOpen();
793
794 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000795
796 bool first = true;
797
798 // Parse capture-default.
799 if (Tok.is(tok::amp) &&
800 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
801 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000802 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000803 first = false;
804 } else if (Tok.is(tok::equal)) {
805 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000806 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000807 first = false;
808 }
809
810 while (Tok.isNot(tok::r_square)) {
811 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000812 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000813 // Provide a completion for a lambda introducer here. Except
814 // in Objective-C, where this is Almost Surely meant to be a message
815 // send. In that case, fail here and let the ObjC message
816 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000817 if (Tok.is(tok::code_completion) &&
818 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
819 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000820 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
821 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000822 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000823 break;
824 }
825
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000826 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000827 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000828 ConsumeToken();
829 }
830
Douglas Gregord8c61782012-02-15 15:34:24 +0000831 if (Tok.is(tok::code_completion)) {
832 // If we're in Objective-C++ and we have a bare '[', then this is more
833 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000834 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000835 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
836 else
837 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
838 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000839 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000840 break;
841 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000842
Douglas Gregord8c61782012-02-15 15:34:24 +0000843 first = false;
844
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000845 // Parse capture.
846 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000847 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000848 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000849 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000850 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000851 ExprResult Init;
Faisal Validc6b5962016-03-21 09:25:37 +0000852
853 if (Tok.is(tok::star)) {
854 Loc = ConsumeToken();
855 if (Tok.is(tok::kw_this)) {
856 ConsumeToken();
857 Kind = LCK_StarThis;
858 } else {
859 return DiagResult(diag::err_expected_star_this_capture);
860 }
861 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000862 Kind = LCK_This;
863 Loc = ConsumeToken();
864 } else {
865 if (Tok.is(tok::amp)) {
866 Kind = LCK_ByRef;
867 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000868
869 if (Tok.is(tok::code_completion)) {
870 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
871 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000872 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000873 break;
874 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000875 }
876
877 if (Tok.is(tok::identifier)) {
878 Id = Tok.getIdentifierInfo();
879 Loc = ConsumeToken();
880 } else if (Tok.is(tok::kw_this)) {
881 // FIXME: If we want to suggest a fixit here, will need to return more
882 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
883 // Clear()ed to prevent emission in case of tentative parsing?
884 return DiagResult(diag::err_this_captured_by_reference);
885 } else {
886 return DiagResult(diag::err_expected_capture);
887 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000888
889 if (Tok.is(tok::l_paren)) {
890 BalancedDelimiterTracker Parens(*this, tok::l_paren);
891 Parens.consumeOpen();
892
Richard Smith42b10572015-11-11 01:36:17 +0000893 InitKind = LambdaCaptureInitKind::DirectInit;
894
Richard Smith21b3ab42013-05-09 21:36:41 +0000895 ExprVector Exprs;
896 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000897 if (SkippedInits) {
898 Parens.skipToEnd();
899 *SkippedInits = true;
900 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000901 Parens.skipToEnd();
902 Init = ExprError();
903 } else {
904 Parens.consumeClose();
905 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
906 Parens.getCloseLocation(),
907 Exprs);
908 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000909 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000910 // Each lambda init-capture forms its own full expression, which clears
911 // Actions.MaybeODRUseExprs. So create an expression evaluation context
912 // to save the necessary state, and restore it later.
913 EnterExpressionEvaluationContext EC(Actions,
914 Sema::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000915
916 if (TryConsumeToken(tok::equal))
917 InitKind = LambdaCaptureInitKind::CopyInit;
918 else
919 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000920
Richard Smith215f4232015-02-11 02:41:33 +0000921 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000922 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000923 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000924 BalancedDelimiterTracker Braces(*this, tok::l_brace);
925 Braces.consumeOpen();
926 Braces.skipToEnd();
927 *SkippedInits = true;
928 } else {
929 // We're disambiguating this:
930 //
931 // [..., x = expr
932 //
933 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000934 // determine whether this is an Obj-C message send's receiver, a
935 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000936 //
937 // Parse the expression to find where it ends, and annotate it back
938 // onto the tokens. We would have parsed this expression the same way
939 // in either case: both the RHS of an init-capture and the RHS of an
940 // assignment expression are parsed as an initializer-clause, and in
941 // neither case can anything be added to the scope between the '[' and
942 // here.
943 //
944 // FIXME: This is horrible. Adding a mechanism to skip an expression
945 // would be much cleaner.
946 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
947 // that instead. (And if we see a ':' with no matching '?', we can
948 // classify this as an Obj-C message send.)
949 SourceLocation StartLoc = Tok.getLocation();
950 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
951 Init = ParseInitializer();
952
953 if (Tok.getLocation() != StartLoc) {
954 // Back out the lexing of the token after the initializer.
955 PP.RevertCachedTokens(1);
956
957 // Replace the consumed tokens with an appropriate annotation.
958 Tok.setLocation(StartLoc);
959 Tok.setKind(tok::annot_primary_expr);
960 setExprAnnotation(Tok, Init);
961 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
962 PP.AnnotateCachedTokens(Tok);
963
964 // Consume the annotated initializer.
965 ConsumeToken();
966 }
967 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000968 } else
969 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000970 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000971 // If this is an init capture, process the initialization expression
972 // right away. For lambda init-captures such as the following:
973 // const int x = 10;
974 // auto L = [i = x+1](int a) {
975 // return [j = x+2,
976 // &k = x](char b) { };
977 // };
978 // keep in mind that each lambda init-capture has to have:
979 // - its initialization expression executed in the context
980 // of the enclosing/parent decl-context.
981 // - but the variable itself has to be 'injected' into the
982 // decl-context of its lambda's call-operator (which has
983 // not yet been created).
984 // Each init-expression is a full-expression that has to get
985 // Sema-analyzed (for capturing etc.) before its lambda's
986 // call-operator's decl-context, scope & scopeinfo are pushed on their
987 // respective stacks. Thus if any variable is odr-used in the init-capture
988 // it will correctly get captured in the enclosing lambda, if one exists.
989 // The init-variables above are created later once the lambdascope and
990 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000991
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000992 // Since the lambda init-capture's initializer expression occurs in the
993 // context of the enclosing function or lambda, therefore we can not wait
994 // till a lambda scope has been pushed on before deciding whether the
995 // variable needs to be captured. We also need to process all
996 // lvalue-to-rvalue conversions and discarded-value conversions,
997 // so that we can avoid capturing certain constant variables.
998 // For e.g.,
999 // void test() {
1000 // const int x = 10;
1001 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
1002 // return [y = x](int i) { <-- don't capture by enclosing lambda
1003 // return y;
1004 // }
1005 // };
Richard Smithbdb84f32016-07-22 23:36:59 +00001006 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001007 // If x was not const, the second use would require 'L' to capture, and
1008 // that would be an error.
1009
Richard Smith42b10572015-11-11 01:36:17 +00001010 ParsedType InitCaptureType;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001011 if (Init.isUsable()) {
1012 // Get the pointer and store it in an lvalue, so we can use it as an
1013 // out argument.
1014 Expr *InitExpr = Init.get();
1015 // This performs any lvalue-to-rvalue conversions if necessary, which
1016 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +00001017 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
1018 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001019 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001020 }
Richard Smith42b10572015-11-11 01:36:17 +00001021 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
1022 InitCaptureType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001023 }
1024
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001025 T.consumeClose();
1026 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001027 return DiagResult();
1028}
1029
Douglas Gregord8c61782012-02-15 15:34:24 +00001030/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001031///
1032/// Returns true if it hit something unexpected.
1033bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1034 TentativeParsingAction PA(*this);
1035
Richard Smithf44d2a82013-05-21 22:21:19 +00001036 bool SkippedInits = false;
1037 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001038
1039 if (DiagID) {
1040 PA.Revert();
1041 return true;
1042 }
1043
Richard Smithf44d2a82013-05-21 22:21:19 +00001044 if (SkippedInits) {
1045 // Parse it again, but this time parse the init-captures too.
1046 PA.Revert();
1047 Intro = LambdaIntroducer();
1048 DiagID = ParseLambdaIntroducer(Intro);
1049 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1050 return false;
1051 }
1052
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001053 PA.Commit();
1054 return false;
1055}
1056
Faisal Valia734ab92016-03-26 16:11:37 +00001057static void
1058tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1059 SourceLocation &ConstexprLoc,
1060 SourceLocation &DeclEndLoc) {
1061 assert(MutableLoc.isInvalid());
1062 assert(ConstexprLoc.isInvalid());
1063 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1064 // to the final of those locations. Emit an error if we have multiple
1065 // copies of those keywords and recover.
1066
1067 while (true) {
1068 switch (P.getCurToken().getKind()) {
1069 case tok::kw_mutable: {
1070 if (MutableLoc.isValid()) {
1071 P.Diag(P.getCurToken().getLocation(),
1072 diag::err_lambda_decl_specifier_repeated)
1073 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1074 }
1075 MutableLoc = P.ConsumeToken();
1076 DeclEndLoc = MutableLoc;
1077 break /*switch*/;
1078 }
1079 case tok::kw_constexpr:
1080 if (ConstexprLoc.isValid()) {
1081 P.Diag(P.getCurToken().getLocation(),
1082 diag::err_lambda_decl_specifier_repeated)
1083 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1084 }
1085 ConstexprLoc = P.ConsumeToken();
1086 DeclEndLoc = ConstexprLoc;
1087 break /*switch*/;
1088 default:
1089 return;
1090 }
1091 }
1092}
1093
1094static void
1095addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1096 DeclSpec &DS) {
1097 if (ConstexprLoc.isValid()) {
1098 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
1099 ? diag::ext_constexpr_on_lambda_cxx1z
1100 : diag::warn_cxx14_compat_constexpr_on_lambda);
1101 const char *PrevSpec = nullptr;
1102 unsigned DiagID = 0;
1103 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1104 assert(PrevSpec == nullptr && DiagID == 0 &&
1105 "Constexpr cannot have been set previously!");
1106 }
1107}
1108
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001109/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1110/// expression.
1111ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1112 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001113 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1114 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1115
1116 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1117 "lambda expression parsing");
1118
Faisal Vali2b391ab2013-09-26 19:54:12 +00001119
1120
Richard Smith21b3ab42013-05-09 21:36:41 +00001121 // FIXME: Call into Actions to add any init-capture declarations to the
1122 // scope while parsing the lambda-declarator and compound-statement.
1123
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001124 // Parse lambda-declarator[opt].
1125 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001126 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001127 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1128 Actions.PushLambdaScope();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001129
David Majnemere01c4662015-01-09 05:10:55 +00001130 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001131 if (Tok.is(tok::l_paren)) {
1132 ParseScope PrototypeScope(this,
1133 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001134 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001135 Scope::DeclScope);
1136
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001137 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001138 BalancedDelimiterTracker T(*this, tok::l_paren);
1139 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001140 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001141
1142 // Parse parameter-declaration-clause.
1143 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001144 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001145 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001146
1147 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001148 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001149 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001150 // For a generic lambda, each 'auto' within the parameter declaration
1151 // clause creates a template type parameter, so increment the depth.
1152 if (Actions.getCurGenericLambda())
1153 ++CurTemplateDepthTracker;
1154 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001155 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001156 SourceLocation RParenLoc = T.getCloseLocation();
1157 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001158
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001159 // GNU-style attributes must be parsed before the mutable specifier to be
1160 // compatible with GCC.
1161 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1162
David Majnemerbda86322015-02-04 08:22:46 +00001163 // MSVC-style attributes must be parsed before the mutable specifier to be
1164 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001165 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001166
Faisal Valia734ab92016-03-26 16:11:37 +00001167 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001168 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001169 SourceLocation ConstexprLoc;
1170 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1171 DeclEndLoc);
1172
1173 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001174
1175 // Parse exception-specification[opt].
1176 ExceptionSpecificationType ESpecType = EST_None;
1177 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001178 SmallVector<ParsedType, 2> DynamicExceptions;
1179 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001180 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001181 CachedTokens *ExceptionSpecTokens;
1182 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1183 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001184 DynamicExceptions,
1185 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001186 NoexceptExpr,
1187 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001188
1189 if (ESpecType != EST_None)
1190 DeclEndLoc = ESpecRange.getEnd();
1191
1192 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001193 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001194
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001195 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1196
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001197 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001198 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001199 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001200 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001201 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001202 if (Range.getEnd().isValid())
1203 DeclEndLoc = Range.getEnd();
1204 }
1205
1206 PrototypeScope.Exit();
1207
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001208 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001209 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001210 /*isAmbiguous=*/false,
1211 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001212 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001213 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001214 DS.getTypeQualifiers(),
1215 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001216 /*RefQualifierLoc=*/NoLoc,
1217 /*ConstQualifierLoc=*/NoLoc,
1218 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001219 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001220 MutableLoc,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001221 ESpecType, ESpecRange,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001222 DynamicExceptions.data(),
1223 DynamicExceptionRanges.data(),
1224 DynamicExceptions.size(),
1225 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001226 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001227 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001228 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001229 TrailingReturnType),
1230 Attr, DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001231 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1232 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001233 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1234 // It's common to forget that one needs '()' before 'mutable', an attribute
1235 // specifier, or the result type. Deal with this.
1236 unsigned TokKind = 0;
1237 switch (Tok.getKind()) {
1238 case tok::kw_mutable: TokKind = 0; break;
1239 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001240 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001241 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001242 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001243 default: llvm_unreachable("Unknown token kind");
1244 }
1245
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001246 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001247 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001248 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1249 SourceLocation DeclLoc = Tok.getLocation();
1250 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001251
1252 // GNU-style attributes must be parsed before the mutable specifier to be
1253 // compatible with GCC.
1254 ParsedAttributes Attr(AttrFactory);
1255 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1256
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001257 // Parse 'mutable', if it's there.
1258 SourceLocation MutableLoc;
1259 if (Tok.is(tok::kw_mutable)) {
1260 MutableLoc = ConsumeToken();
1261 DeclEndLoc = MutableLoc;
1262 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001263
1264 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001265 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1266
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001267 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001268 if (Tok.is(tok::arrow)) {
1269 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001270 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001271 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001272 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001273 }
1274
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001275 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001276 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001277 /*isAmbiguous=*/false,
1278 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001279 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001280 /*NumParams=*/0,
1281 /*EllipsisLoc=*/NoLoc,
1282 /*RParenLoc=*/NoLoc,
1283 /*TypeQuals=*/0,
1284 /*RefQualifierIsLValueRef=*/true,
1285 /*RefQualifierLoc=*/NoLoc,
1286 /*ConstQualifierLoc=*/NoLoc,
1287 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001288 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001289 MutableLoc,
1290 EST_None,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001291 /*ESpecRange=*/SourceRange(),
Craig Topper161e4db2014-05-21 06:02:52 +00001292 /*Exceptions=*/nullptr,
1293 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001294 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001295 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001296 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001297 DeclLoc, DeclEndLoc, D,
1298 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001299 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001300 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001301
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001302
Eli Friedman4817cf72012-01-06 03:05:34 +00001303 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1304 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001305 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001306 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001307
Eli Friedman71c80552012-01-05 03:35:19 +00001308 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1309
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001310 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001311 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001312 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001313 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1314 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001315 }
1316
Eli Friedmanc7c97142012-01-04 02:40:39 +00001317 StmtResult Stmt(ParseCompoundStatementBody());
1318 BodyScope.Exit();
1319
David Majnemere01c4662015-01-09 05:10:55 +00001320 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001321 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001322
Eli Friedman898caf82012-01-04 02:46:53 +00001323 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1324 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001325}
1326
Chris Lattner29375652006-12-04 18:06:35 +00001327/// ParseCXXCasts - This handles the various ways to cast expressions to another
1328/// type.
1329///
1330/// postfix-expression: [C++ 5.2p1]
1331/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1332/// 'static_cast' '<' type-name '>' '(' expression ')'
1333/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1334/// 'const_cast' '<' type-name '>' '(' expression ')'
1335///
John McCalldadc5752010-08-24 06:29:42 +00001336ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001337 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001338 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001339
1340 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001341 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001342 case tok::kw_const_cast: CastName = "const_cast"; break;
1343 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1344 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1345 case tok::kw_static_cast: CastName = "static_cast"; break;
1346 }
1347
1348 SourceLocation OpLoc = ConsumeToken();
1349 SourceLocation LAngleBracketLoc = Tok.getLocation();
1350
Richard Smith55858492011-04-14 21:45:45 +00001351 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1352 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001353 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1354 Token Next = NextToken();
1355 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1356 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1357 }
Richard Smith55858492011-04-14 21:45:45 +00001358
Chris Lattner29375652006-12-04 18:06:35 +00001359 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001360 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001361
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001362 // Parse the common declaration-specifiers piece.
1363 DeclSpec DS(AttrFactory);
1364 ParseSpecifierQualifierList(DS);
1365
1366 // Parse the abstract-declarator, if present.
1367 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1368 ParseDeclarator(DeclaratorInfo);
1369
Chris Lattner29375652006-12-04 18:06:35 +00001370 SourceLocation RAngleBracketLoc = Tok.getLocation();
1371
Alp Toker383d2c42014-01-01 03:08:43 +00001372 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001373 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001374
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001375 SourceLocation LParenLoc, RParenLoc;
1376 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001377
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001378 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001379 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001380
John McCalldadc5752010-08-24 06:29:42 +00001381 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001382
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001383 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001384 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001385
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001386 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001387 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001388 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001389 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001390 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001391 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001392
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001393 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001394}
Bill Wendling4073ed52007-02-13 01:51:42 +00001395
Sebastian Redlc4704762008-11-11 11:37:55 +00001396/// ParseCXXTypeid - This handles the C++ typeid expression.
1397///
1398/// postfix-expression: [C++ 5.2p1]
1399/// 'typeid' '(' expression ')'
1400/// 'typeid' '(' type-id ')'
1401///
John McCalldadc5752010-08-24 06:29:42 +00001402ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001403 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1404
1405 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001406 SourceLocation LParenLoc, RParenLoc;
1407 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001408
1409 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001410 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001411 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001412 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001413
John McCalldadc5752010-08-24 06:29:42 +00001414 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001415
Richard Smith4f605af2012-08-18 00:55:03 +00001416 // C++0x [expr.typeid]p3:
1417 // When typeid is applied to an expression other than an lvalue of a
1418 // polymorphic class type [...] The expression is an unevaluated
1419 // operand (Clause 5).
1420 //
1421 // Note that we can't tell whether the expression is an lvalue of a
1422 // polymorphic class type until after we've parsed the expression; we
1423 // speculatively assume the subexpression is unevaluated, and fix it up
1424 // later.
1425 //
1426 // We enter the unevaluated context before trying to determine whether we
1427 // have a type-id, because the tentative parse logic will try to resolve
1428 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001429 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1430 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001431
Sebastian Redlc4704762008-11-11 11:37:55 +00001432 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001433 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001434
1435 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001436 T.consumeClose();
1437 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001438 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001439 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001440
1441 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001442 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001443 } else {
1444 Result = ParseExpression();
1445
1446 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001447 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001448 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001449 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001450 T.consumeClose();
1451 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001452 if (RParenLoc.isInvalid())
1453 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001454
Sebastian Redlc4704762008-11-11 11:37:55 +00001455 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001456 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001457 }
1458 }
1459
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001460 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001461}
1462
Francois Pichet9f4f2072010-09-08 12:20:18 +00001463/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1464///
1465/// '__uuidof' '(' expression ')'
1466/// '__uuidof' '(' type-id ')'
1467///
1468ExprResult Parser::ParseCXXUuidof() {
1469 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1470
1471 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001472 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001473
1474 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001475 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001476 return ExprError();
1477
1478 ExprResult Result;
1479
1480 if (isTypeIdInParens()) {
1481 TypeResult Ty = ParseTypeName();
1482
1483 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001484 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001485
1486 if (Ty.isInvalid())
1487 return ExprError();
1488
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001489 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1490 Ty.get().getAsOpaquePtr(),
1491 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001492 } else {
1493 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1494 Result = ParseExpression();
1495
1496 // Match the ')'.
1497 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001498 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001499 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001500 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001501
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001502 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1503 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001504 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001505 }
1506 }
1507
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001508 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001509}
1510
Douglas Gregore610ada2010-02-24 18:44:31 +00001511/// \brief Parse a C++ pseudo-destructor expression after the base,
1512/// . or -> operator, and nested-name-specifier have already been
1513/// parsed.
1514///
1515/// postfix-expression: [C++ 5.2]
1516/// postfix-expression . pseudo-destructor-name
1517/// postfix-expression -> pseudo-destructor-name
1518///
1519/// pseudo-destructor-name:
1520/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1521/// ::[opt] nested-name-specifier template simple-template-id ::
1522/// ~type-name
1523/// ::[opt] nested-name-specifier[opt] ~type-name
1524///
John McCalldadc5752010-08-24 06:29:42 +00001525ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001526Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001527 tok::TokenKind OpKind,
1528 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001529 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001530 // We're parsing either a pseudo-destructor-name or a dependent
1531 // member access that has the same form as a
1532 // pseudo-destructor-name. We parse both in the same way and let
1533 // the action model sort them out.
1534 //
1535 // Note that the ::[opt] nested-name-specifier[opt] has already
1536 // been parsed, and if there was a simple-template-id, it has
1537 // been coalesced into a template-id annotation token.
1538 UnqualifiedId FirstTypeName;
1539 SourceLocation CCLoc;
1540 if (Tok.is(tok::identifier)) {
1541 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1542 ConsumeToken();
1543 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1544 CCLoc = ConsumeToken();
1545 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001546 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1547 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001548 FirstTypeName.setTemplateId(
1549 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1550 ConsumeToken();
1551 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1552 CCLoc = ConsumeToken();
1553 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001554 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001555 }
1556
1557 // Parse the tilde.
1558 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1559 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001560
1561 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1562 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001563 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001564 if (DS.getTypeSpecType() == TST_error)
1565 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001566 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1567 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001568 }
1569
Douglas Gregore610ada2010-02-24 18:44:31 +00001570 if (!Tok.is(tok::identifier)) {
1571 Diag(Tok, diag::err_destructor_tilde_identifier);
1572 return ExprError();
1573 }
1574
1575 // Parse the second type.
1576 UnqualifiedId SecondTypeName;
1577 IdentifierInfo *Name = Tok.getIdentifierInfo();
1578 SourceLocation NameLoc = ConsumeToken();
1579 SecondTypeName.setIdentifier(Name, NameLoc);
1580
1581 // If there is a '<', the second type name is a template-id. Parse
1582 // it as such.
1583 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001584 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1585 Name, NameLoc,
1586 false, ObjectType, SecondTypeName,
1587 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001588 return ExprError();
1589
David Majnemerced8bdf2015-02-25 17:36:15 +00001590 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1591 SS, FirstTypeName, CCLoc, TildeLoc,
1592 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001593}
1594
Bill Wendling4073ed52007-02-13 01:51:42 +00001595/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1596///
1597/// boolean-literal: [C++ 2.13.5]
1598/// 'true'
1599/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001600ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001601 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001602 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001603}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001604
1605/// ParseThrowExpression - This handles the C++ throw expression.
1606///
1607/// throw-expression: [C++ 15]
1608/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001609ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001610 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001611 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001612
Chris Lattner65dd8432008-04-06 06:02:23 +00001613 // If the current token isn't the start of an assignment-expression,
1614 // then the expression is not present. This handles things like:
1615 // "C ? throw : (void)42", which is crazy but legal.
1616 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1617 case tok::semi:
1618 case tok::r_paren:
1619 case tok::r_square:
1620 case tok::r_brace:
1621 case tok::colon:
1622 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001623 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001624
Chris Lattner65dd8432008-04-06 06:02:23 +00001625 default:
John McCalldadc5752010-08-24 06:29:42 +00001626 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001627 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001629 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001630}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001631
Richard Smith0e304ea2015-10-22 04:46:14 +00001632/// \brief Parse the C++ Coroutines co_yield expression.
1633///
1634/// co_yield-expression:
1635/// 'co_yield' assignment-expression[opt]
1636ExprResult Parser::ParseCoyieldExpression() {
1637 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1638
1639 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001640 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1641 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001642 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001643 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001644 return Expr;
1645}
1646
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001647/// ParseCXXThis - This handles the C++ 'this' pointer.
1648///
1649/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1650/// a non-lvalue expression whose value is the address of the object for which
1651/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001652ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001653 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1654 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001655 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001656}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001657
1658/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1659/// Can be interpreted either as function-style casting ("int(x)")
1660/// or class type construction ("ClassType(x,y,z)")
1661/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001662/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001663///
1664/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001665/// simple-type-specifier '(' expression-list[opt] ')'
1666/// [C++0x] simple-type-specifier braced-init-list
1667/// typename-specifier '(' expression-list[opt] ')'
1668/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001669///
John McCalldadc5752010-08-24 06:29:42 +00001670ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001671Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001672 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001673 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001674
Sebastian Redl3da34892011-06-05 12:23:16 +00001675 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001676 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001677 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001678
Sebastian Redl3da34892011-06-05 12:23:16 +00001679 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001680 ExprResult Init = ParseBraceInitializer();
1681 if (Init.isInvalid())
1682 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001683 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001684 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1685 MultiExprArg(&InitList, 1),
1686 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001687 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001688 BalancedDelimiterTracker T(*this, tok::l_paren);
1689 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001690
Benjamin Kramerf0623432012-08-23 22:51:59 +00001691 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001692 CommaLocsTy CommaLocs;
1693
1694 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001695 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1696 Actions.CodeCompleteConstructor(getCurScope(),
1697 TypeRep.get()->getCanonicalTypeInternal(),
1698 DS.getLocEnd(), Exprs);
1699 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001700 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001701 return ExprError();
1702 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001703 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001704
1705 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001706 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001707
1708 // TypeRep could be null, if it references an invalid typedef.
1709 if (!TypeRep)
1710 return ExprError();
1711
1712 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1713 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001714 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001715 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001716 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001717 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001718}
1719
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001720/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001721///
1722/// condition:
1723/// expression
1724/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001725/// [C++11] type-specifier-seq declarator '=' initializer-clause
1726/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001727/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1728/// '=' assignment-expression
1729///
Richard Smithc7a05a92016-06-29 21:17:59 +00001730/// In C++1z, a condition may in some contexts be preceded by an
1731/// optional init-statement. This function will parse that too.
1732///
1733/// \param InitStmt If non-null, an init-statement is permitted, and if present
1734/// will be parsed and stored here.
1735///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001736/// \param Loc The location of the start of the statement that requires this
1737/// condition, e.g., the "for" in a for loop.
1738///
Richard Smith03a4aa32016-06-23 19:02:52 +00001739/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001740Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1741 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001742 Sema::ConditionKind CK) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001743 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001744 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001745 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001746 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001747 }
1748
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001749 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001750 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001751
Richard Smithc7a05a92016-06-29 21:17:59 +00001752 // Determine what kind of thing we have.
1753 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1754 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001755 ProhibitAttributes(attrs);
1756
Douglas Gregore60e41a2010-05-06 17:25:47 +00001757 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001758 ExprResult Expr = ParseExpression(); // expression
1759 if (Expr.isInvalid())
1760 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001761
Richard Smithc7a05a92016-06-29 21:17:59 +00001762 if (InitStmt && Tok.is(tok::semi)) {
1763 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1764 ConsumeToken();
1765 return ParseCXXCondition(nullptr, Loc, CK);
1766 }
1767
Richard Smith03a4aa32016-06-23 19:02:52 +00001768 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001769 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001770
Richard Smithc7a05a92016-06-29 21:17:59 +00001771 case ConditionOrInitStatement::InitStmtDecl: {
1772 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1773 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1774 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1775 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1776 return ParseCXXCondition(nullptr, Loc, CK);
1777 }
1778
1779 case ConditionOrInitStatement::ConditionDecl:
1780 case ConditionOrInitStatement::Error:
1781 break;
1782 }
1783
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001784 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001785 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001786 DS.takeAttributesFrom(attrs);
Meador Ingef0af05c2015-06-25 22:06:40 +00001787 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001788
1789 // declarator
1790 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1791 ParseDeclarator(DeclaratorInfo);
1792
1793 // simple-asm-expr[opt]
1794 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001795 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001796 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001797 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001798 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001799 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001800 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001801 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001802 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001803 }
1804
1805 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001806 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001807
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001808 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001809 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001810 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001811 if (Dcl.isInvalid())
1812 return Sema::ConditionError();
1813 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001814
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001815 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001816 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001817 bool CopyInitialization = isTokenEqualOrEqualTypo();
1818 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001819 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001820
1821 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001822 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001823 Diag(Tok.getLocation(),
1824 diag::warn_cxx98_compat_generalized_initializer_lists);
1825 InitExpr = ParseBraceInitializer();
1826 } else if (CopyInitialization) {
1827 InitExpr = ParseAssignmentExpression();
1828 } else if (Tok.is(tok::l_paren)) {
1829 // This was probably an attempt to initialize the variable.
1830 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001831 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001832 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001833 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001834 diag::err_expected_init_in_condition_lparen)
1835 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001836 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001837 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001838 }
Richard Smith2a15b742012-02-22 06:49:09 +00001839
1840 if (!InitExpr.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001841 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001842 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001843 else
1844 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001845
Richard Smithb2bc2e62011-02-21 20:05:19 +00001846 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001847 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001848}
1849
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001850/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1851/// This should only be called when the current token is known to be part of
1852/// simple-type-specifier.
1853///
1854/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001855/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001856/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1857/// char
1858/// wchar_t
1859/// bool
1860/// short
1861/// int
1862/// long
1863/// signed
1864/// unsigned
1865/// float
1866/// double
1867/// void
1868/// [GNU] typeof-specifier
1869/// [C++0x] auto [TODO]
1870///
1871/// type-name:
1872/// class-name
1873/// enum-name
1874/// typedef-name
1875///
1876void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1877 DS.SetRangeStart(Tok.getLocation());
1878 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001879 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001880 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001881 const clang::PrintingPolicy &Policy =
1882 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001883
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001884 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001885 case tok::identifier: // foo::bar
1886 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001887 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001888 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001889 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001890
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001891 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001892 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001893 if (getTypeAnnotation(Tok))
1894 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001895 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001896 else
1897 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001898
1899 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1900 ConsumeToken();
1901
Craig Topper25122412015-11-15 03:32:11 +00001902 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001903 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001906 // builtin types
1907 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001908 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001909 break;
1910 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001911 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001912 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001913 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001914 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001915 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001916 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001917 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001918 break;
1919 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001920 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001921 break;
1922 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001923 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001924 break;
1925 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001926 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001927 break;
1928 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001929 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001930 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001931 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001932 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001933 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001934 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001935 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001936 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001937 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001938 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001939 break;
1940 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001941 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001942 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001943 case tok::kw___float128:
1944 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1945 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001946 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001947 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001948 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001949 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001950 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001951 break;
1952 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001953 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001954 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001955 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001956 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001957 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001958 case tok::annot_decltype:
1959 case tok::kw_decltype:
1960 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00001961 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001962
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001963 // GNU typeof support.
1964 case tok::kw_typeof:
1965 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00001966 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001967 return;
1968 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001969 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001970 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1971 else
1972 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001973 ConsumeToken();
Craig Topper25122412015-11-15 03:32:11 +00001974 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001975}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001976
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001977/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1978/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1979/// e.g., "const short int". Note that the DeclSpec is *not* finished
1980/// by parsing the type-specifier-seq, because these sequences are
1981/// typically followed by some form of declarator. Returns true and
1982/// emits diagnostics if this is not a type-specifier-seq, false
1983/// otherwise.
1984///
1985/// type-specifier-seq: [C++ 8.1]
1986/// type-specifier type-specifier-seq[opt]
1987///
1988bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001989 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00001990 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001991 return false;
1992}
1993
Douglas Gregor7861a802009-11-03 01:35:08 +00001994/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1995/// some form.
1996///
1997/// This routine is invoked when a '<' is encountered after an identifier or
1998/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1999/// whether the unqualified-id is actually a template-id. This routine will
2000/// then parse the template arguments and form the appropriate template-id to
2001/// return to the caller.
2002///
2003/// \param SS the nested-name-specifier that precedes this template-id, if
2004/// we're actually parsing a qualified-id.
2005///
2006/// \param Name for constructor and destructor names, this is the actual
2007/// identifier that may be a template-name.
2008///
2009/// \param NameLoc the location of the class-name in a constructor or
2010/// destructor.
2011///
2012/// \param EnteringContext whether we're entering the scope of the
2013/// nested-name-specifier.
2014///
Douglas Gregor127ea592009-11-03 21:24:04 +00002015/// \param ObjectType if this unqualified-id occurs within a member access
2016/// expression, the type of the base object whose member is being accessed.
2017///
Douglas Gregor7861a802009-11-03 01:35:08 +00002018/// \param Id as input, describes the template-name or operator-function-id
2019/// that precedes the '<'. If template arguments were parsed successfully,
2020/// will be updated with the template-id.
2021///
Douglas Gregore610ada2010-02-24 18:44:31 +00002022/// \param AssumeTemplateId When true, this routine will assume that the name
2023/// refers to a template without performing name lookup to verify.
2024///
Douglas Gregor7861a802009-11-03 01:35:08 +00002025/// \returns true if a parse error occurred, false otherwise.
2026bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002027 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002028 IdentifierInfo *Name,
2029 SourceLocation NameLoc,
2030 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002031 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002032 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002033 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002034 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2035 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00002036
2037 TemplateTy Template;
2038 TemplateNameKind TNK = TNK_Non_template;
2039 switch (Id.getKind()) {
2040 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00002041 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00002042 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002043 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00002044 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00002045 Id, ObjectType, EnteringContext,
2046 Template);
2047 if (TNK == TNK_Non_template)
2048 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002049 } else {
2050 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002051 TNK = Actions.isTemplateName(getCurScope(), SS,
2052 TemplateKWLoc.isValid(), Id,
2053 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002054 MemberOfUnknownSpecialization);
2055
2056 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2057 ObjectType && IsTemplateArgumentList()) {
2058 // We have something like t->getAs<T>(), where getAs is a
2059 // member of an unknown specialization. However, this will only
2060 // parse correctly as a template, so suggest the keyword 'template'
2061 // before 'getAs' and treat this as a dependent template name.
2062 std::string Name;
2063 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2064 Name = Id.Identifier->getName();
2065 else {
2066 Name = "operator ";
2067 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2068 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2069 else
2070 Name += Id.Identifier->getName();
2071 }
2072 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2073 << Name
2074 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00002075 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2076 SS, TemplateKWLoc, Id,
2077 ObjectType, EnteringContext,
2078 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00002079 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00002080 return true;
2081 }
2082 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002083 break;
2084
Douglas Gregor3cf81312009-11-03 23:16:33 +00002085 case UnqualifiedId::IK_ConstructorName: {
2086 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002087 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002088 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002089 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2090 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002091 EnteringContext, Template,
2092 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002093 break;
2094 }
2095
Douglas Gregor3cf81312009-11-03 23:16:33 +00002096 case UnqualifiedId::IK_DestructorName: {
2097 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002098 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002099 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002100 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00002101 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2102 SS, TemplateKWLoc, TemplateName,
2103 ObjectType, EnteringContext,
2104 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00002105 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002106 return true;
2107 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002108 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2109 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002110 EnteringContext, Template,
2111 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002112
John McCallba7bf592010-08-24 05:47:05 +00002113 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002114 Diag(NameLoc, diag::err_destructor_template_id)
2115 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002116 return true;
2117 }
2118 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002119 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002120 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002121
2122 default:
2123 return false;
2124 }
2125
2126 if (TNK == TNK_Non_template)
2127 return false;
2128
2129 // Parse the enclosed template argument list.
2130 SourceLocation LAngleLoc, RAngleLoc;
2131 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002132 if (Tok.is(tok::less) &&
2133 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002134 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002135 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002136 RAngleLoc))
2137 return true;
2138
2139 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002140 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2141 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002142 // Form a parsed representation of the template-id to be stored in the
2143 // UnqualifiedId.
2144 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002145 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002146
Richard Smith72bfbd82013-12-04 00:28:23 +00002147 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002148 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2149 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002150 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002151 TemplateId->TemplateNameLoc = Id.StartLocation;
2152 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002153 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002154 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2155 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002156 }
2157
Douglas Gregore7c20652011-03-02 00:47:37 +00002158 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002159 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002160 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002161 TemplateId->Kind = TNK;
2162 TemplateId->LAngleLoc = LAngleLoc;
2163 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002164 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002165 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002166 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002167 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002168
2169 Id.setTemplateId(TemplateId);
2170 return false;
2171 }
2172
2173 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002174 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002175
Douglas Gregor7861a802009-11-03 01:35:08 +00002176 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002177 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002178 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2179 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002180 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2181 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002182 if (Type.isInvalid())
2183 return true;
2184
2185 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2186 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2187 else
2188 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2189
2190 return false;
2191}
2192
Douglas Gregor71395fa2009-11-04 00:56:37 +00002193/// \brief Parse an operator-function-id or conversion-function-id as part
2194/// of a C++ unqualified-id.
2195///
2196/// This routine is responsible only for parsing the operator-function-id or
2197/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002198///
2199/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002200/// operator-function-id: [C++ 13.5]
2201/// 'operator' operator
2202///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002203/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002204/// new delete new[] delete[]
2205/// + - * / % ^ & | ~
2206/// ! = < > += -= *= /= %=
2207/// ^= &= |= << >> >>= <<= == !=
2208/// <= >= && || ++ -- , ->* ->
2209/// () []
2210///
2211/// conversion-function-id: [C++ 12.3.2]
2212/// operator conversion-type-id
2213///
2214/// conversion-type-id:
2215/// type-specifier-seq conversion-declarator[opt]
2216///
2217/// conversion-declarator:
2218/// ptr-operator conversion-declarator[opt]
2219/// \endcode
2220///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002221/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002222/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2223///
2224/// \param EnteringContext whether we are entering the scope of the
2225/// nested-name-specifier.
2226///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002227/// \param ObjectType if this unqualified-id occurs within a member access
2228/// expression, the type of the base object whose member is being accessed.
2229///
2230/// \param Result on a successful parse, contains the parsed unqualified-id.
2231///
2232/// \returns true if parsing fails, false otherwise.
2233bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002234 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002235 UnqualifiedId &Result) {
2236 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2237
2238 // Consume the 'operator' keyword.
2239 SourceLocation KeywordLoc = ConsumeToken();
2240
2241 // Determine what kind of operator name we have.
2242 unsigned SymbolIdx = 0;
2243 SourceLocation SymbolLocations[3];
2244 OverloadedOperatorKind Op = OO_None;
2245 switch (Tok.getKind()) {
2246 case tok::kw_new:
2247 case tok::kw_delete: {
2248 bool isNew = Tok.getKind() == tok::kw_new;
2249 // Consume the 'new' or 'delete'.
2250 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002251 // Check for array new/delete.
2252 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002253 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002254 // Consume the '[' and ']'.
2255 BalancedDelimiterTracker T(*this, tok::l_square);
2256 T.consumeOpen();
2257 T.consumeClose();
2258 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002259 return true;
2260
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002261 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2262 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002263 Op = isNew? OO_Array_New : OO_Array_Delete;
2264 } else {
2265 Op = isNew? OO_New : OO_Delete;
2266 }
2267 break;
2268 }
2269
2270#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2271 case tok::Token: \
2272 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2273 Op = OO_##Name; \
2274 break;
2275#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2276#include "clang/Basic/OperatorKinds.def"
2277
2278 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002279 // Consume the '(' and ')'.
2280 BalancedDelimiterTracker T(*this, tok::l_paren);
2281 T.consumeOpen();
2282 T.consumeClose();
2283 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002284 return true;
2285
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002286 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2287 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002288 Op = OO_Call;
2289 break;
2290 }
2291
2292 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002293 // Consume the '[' and ']'.
2294 BalancedDelimiterTracker T(*this, tok::l_square);
2295 T.consumeOpen();
2296 T.consumeClose();
2297 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002298 return true;
2299
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002300 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2301 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002302 Op = OO_Subscript;
2303 break;
2304 }
2305
2306 case tok::code_completion: {
2307 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002308 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002309 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002310 // Don't try to parse any further.
2311 return true;
2312 }
2313
2314 default:
2315 break;
2316 }
2317
2318 if (Op != OO_None) {
2319 // We have parsed an operator-function-id.
2320 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2321 return false;
2322 }
Alexis Hunt34458502009-11-28 04:44:28 +00002323
2324 // Parse a literal-operator-id.
2325 //
Richard Smith6f212062012-10-20 08:41:10 +00002326 // literal-operator-id: C++11 [over.literal]
2327 // operator string-literal identifier
2328 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002329
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002330 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002331 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002332
Richard Smith7d182a72012-03-08 23:06:02 +00002333 SourceLocation DiagLoc;
2334 unsigned DiagId = 0;
2335
2336 // We're past translation phase 6, so perform string literal concatenation
2337 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002338 SmallVector<Token, 4> Toks;
2339 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002340 while (isTokenStringLiteral()) {
2341 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002342 // C++11 [over.literal]p1:
2343 // The string-literal or user-defined-string-literal in a
2344 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002345 DiagLoc = Tok.getLocation();
2346 DiagId = diag::err_literal_operator_string_prefix;
2347 }
2348 Toks.push_back(Tok);
2349 TokLocs.push_back(ConsumeStringToken());
2350 }
2351
Craig Topper9d5583e2014-06-26 04:58:39 +00002352 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002353 if (Literal.hadError)
2354 return true;
2355
2356 // Grab the literal operator's suffix, which will be either the next token
2357 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002358 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002359 SourceLocation SuffixLoc;
2360 if (!Literal.getUDSuffix().empty()) {
2361 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2362 SuffixLoc =
2363 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2364 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002365 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002366 } else if (Tok.is(tok::identifier)) {
2367 II = Tok.getIdentifierInfo();
2368 SuffixLoc = ConsumeToken();
2369 TokLocs.push_back(SuffixLoc);
2370 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002371 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002372 return true;
2373 }
2374
Richard Smith7d182a72012-03-08 23:06:02 +00002375 // The string literal must be empty.
2376 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002377 // C++11 [over.literal]p1:
2378 // The string-literal or user-defined-string-literal in a
2379 // literal-operator-id shall [...] contain no characters
2380 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002381 DiagLoc = TokLocs.front();
2382 DiagId = diag::err_literal_operator_string_not_empty;
2383 }
2384
2385 if (DiagId) {
2386 // This isn't a valid literal-operator-id, but we think we know
2387 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002388 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002389 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002390 Str += II->getName();
2391 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2392 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2393 }
2394
2395 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002396
2397 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002398 }
Richard Smithd091dc12013-12-05 00:58:33 +00002399
Douglas Gregor71395fa2009-11-04 00:56:37 +00002400 // Parse a conversion-function-id.
2401 //
2402 // conversion-function-id: [C++ 12.3.2]
2403 // operator conversion-type-id
2404 //
2405 // conversion-type-id:
2406 // type-specifier-seq conversion-declarator[opt]
2407 //
2408 // conversion-declarator:
2409 // ptr-operator conversion-declarator[opt]
2410
2411 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002412 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002413 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002414 return true;
2415
2416 // Parse the conversion-declarator, which is merely a sequence of
2417 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002418 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002419 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2420
Douglas Gregor71395fa2009-11-04 00:56:37 +00002421 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002422 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002423 if (Ty.isInvalid())
2424 return true;
2425
2426 // Note that this is a conversion-function-id.
2427 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2428 D.getSourceRange().getEnd());
2429 return false;
2430}
2431
2432/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2433/// name of an entity.
2434///
2435/// \code
2436/// unqualified-id: [C++ expr.prim.general]
2437/// identifier
2438/// operator-function-id
2439/// conversion-function-id
2440/// [C++0x] literal-operator-id [TODO]
2441/// ~ class-name
2442/// template-id
2443///
2444/// \endcode
2445///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002446/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002447/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2448///
2449/// \param EnteringContext whether we are entering the scope of the
2450/// nested-name-specifier.
2451///
Douglas Gregor7861a802009-11-03 01:35:08 +00002452/// \param AllowDestructorName whether we allow parsing of a destructor name.
2453///
2454/// \param AllowConstructorName whether we allow parsing a constructor name.
2455///
Douglas Gregor127ea592009-11-03 21:24:04 +00002456/// \param ObjectType if this unqualified-id occurs within a member access
2457/// expression, the type of the base object whose member is being accessed.
2458///
Douglas Gregor7861a802009-11-03 01:35:08 +00002459/// \param Result on a successful parse, contains the parsed unqualified-id.
2460///
2461/// \returns true if parsing fails, false otherwise.
2462bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2463 bool AllowDestructorName,
2464 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002465 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002466 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002467 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002468
2469 // Handle 'A::template B'. This is for template-ids which have not
2470 // already been annotated by ParseOptionalCXXScopeSpecifier().
2471 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002473 (ObjectType || SS.isSet())) {
2474 TemplateSpecified = true;
2475 TemplateKWLoc = ConsumeToken();
2476 }
2477
Douglas Gregor7861a802009-11-03 01:35:08 +00002478 // unqualified-id:
2479 // identifier
2480 // template-id (when it hasn't already been annotated)
2481 if (Tok.is(tok::identifier)) {
2482 // Consume the identifier.
2483 IdentifierInfo *Id = Tok.getIdentifierInfo();
2484 SourceLocation IdLoc = ConsumeToken();
2485
David Blaikiebbafb8a2012-03-11 07:00:24 +00002486 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002487 // If we're not in C++, only identifiers matter. Record the
2488 // identifier and return.
2489 Result.setIdentifier(Id, IdLoc);
2490 return false;
2491 }
2492
Douglas Gregor7861a802009-11-03 01:35:08 +00002493 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002494 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002495 // We have parsed a constructor name.
David Blaikieefdccaa2016-01-15 23:43:34 +00002496 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2497 false, nullptr,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002498 /*IsCtorOrDtorName=*/true,
2499 /*NonTrivialTypeSourceInfo=*/true);
2500 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002501 } else {
2502 // We have parsed an identifier.
2503 Result.setIdentifier(Id, IdLoc);
2504 }
2505
2506 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002507 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002508 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2509 EnteringContext, ObjectType,
2510 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002511
2512 return false;
2513 }
2514
2515 // unqualified-id:
2516 // template-id (already parsed and annotated)
2517 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002518 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002519
2520 // If the template-name names the current class, then this is a constructor
2521 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002522 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002523 if (SS.isSet()) {
2524 // C++ [class.qual]p2 specifies that a qualified template-name
2525 // is taken as the constructor name where a constructor can be
2526 // declared. Thus, the template arguments are extraneous, so
2527 // complain about them and remove them entirely.
2528 Diag(TemplateId->TemplateNameLoc,
2529 diag::err_out_of_line_constructor_template_id)
2530 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002531 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002532 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
David Blaikieefdccaa2016-01-15 23:43:34 +00002533 ParsedType Ty =
2534 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2535 getCurScope(), &SS, false, false, nullptr,
2536 /*IsCtorOrDtorName=*/true,
2537 /*NontrivialTypeSourceInfo=*/true);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002538 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002539 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002540 ConsumeToken();
2541 return false;
2542 }
2543
2544 Result.setConstructorTemplateId(TemplateId);
2545 ConsumeToken();
2546 return false;
2547 }
2548
Douglas Gregor7861a802009-11-03 01:35:08 +00002549 // We have already parsed a template-id; consume the annotation token as
2550 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002551 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002552 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002553 ConsumeToken();
2554 return false;
2555 }
2556
2557 // unqualified-id:
2558 // operator-function-id
2559 // conversion-function-id
2560 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002561 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002562 return true;
2563
Alexis Hunted0530f2009-11-28 08:58:14 +00002564 // If we have an operator-function-id or a literal-operator-id and the next
2565 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002566 //
2567 // template-id:
2568 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002569 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2570 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002571 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002572 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002573 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002574 EnteringContext, ObjectType,
2575 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002576
Douglas Gregor7861a802009-11-03 01:35:08 +00002577 return false;
2578 }
2579
David Blaikiebbafb8a2012-03-11 07:00:24 +00002580 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002581 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002582 // C++ [expr.unary.op]p10:
2583 // There is an ambiguity in the unary-expression ~X(), where X is a
2584 // class-name. The ambiguity is resolved in favor of treating ~ as a
2585 // unary complement rather than treating ~X as referring to a destructor.
2586
2587 // Parse the '~'.
2588 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002589
2590 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2591 DeclSpec DS(AttrFactory);
2592 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2593 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2594 Result.setDestructorName(TildeLoc, Type, EndLoc);
2595 return false;
2596 }
2597 return true;
2598 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002599
2600 // Parse the class-name.
2601 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002602 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002603 return true;
2604 }
2605
Richard Smithefa6f732014-09-06 02:06:12 +00002606 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002607 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002608 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002609 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2610 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2611 // it will confuse this recovery logic.
2612 ColonProtectionRAIIObject ColonRAII(*this, false);
2613
Richard Smithefa6f732014-09-06 02:06:12 +00002614 if (SS.isSet()) {
2615 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2616 SS.clear();
2617 }
2618 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2619 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002620 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002621 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002622 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002623 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002624 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2625 return true;
2626 }
2627
2628 // Recover as if the tilde had been written before the identifier.
2629 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2630 << FixItHint::CreateRemoval(TildeLoc)
2631 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002632
2633 // Temporarily enter the scope for the rest of this function.
2634 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2635 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002636 }
2637
Douglas Gregor7861a802009-11-03 01:35:08 +00002638 // Parse the class-name (or template-name in a simple-template-id).
2639 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2640 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002641
Douglas Gregorb22ee882010-05-05 05:58:24 +00002642 if (TemplateSpecified || Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002643 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002644 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2645 ClassName, ClassNameLoc,
2646 EnteringContext, ObjectType,
2647 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002648 }
Richard Smithefa6f732014-09-06 02:06:12 +00002649
Douglas Gregor7861a802009-11-03 01:35:08 +00002650 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002651 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2652 ClassNameLoc, getCurScope(),
2653 SS, ObjectType,
2654 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002655 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002656 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002657
Douglas Gregor7861a802009-11-03 01:35:08 +00002658 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002659 return false;
2660 }
2661
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002662 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002663 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002664 return true;
2665}
2666
Sebastian Redlbd150f42008-11-21 19:14:01 +00002667/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2668/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002669///
Chris Lattner109faf22009-01-04 21:25:24 +00002670/// This method is called to parse the new expression after the optional :: has
2671/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2672/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002673///
2674/// new-expression:
2675/// '::'[opt] 'new' new-placement[opt] new-type-id
2676/// new-initializer[opt]
2677/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2678/// new-initializer[opt]
2679///
2680/// new-placement:
2681/// '(' expression-list ')'
2682///
Sebastian Redl351bb782008-12-02 14:43:59 +00002683/// new-type-id:
2684/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002685/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002686///
2687/// new-declarator:
2688/// ptr-operator new-declarator[opt]
2689/// direct-new-declarator
2690///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002691/// new-initializer:
2692/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002693/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002694///
John McCalldadc5752010-08-24 06:29:42 +00002695ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002696Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2697 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2698 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002699
2700 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2701 // second form of new-expression. It can't be a new-type-id.
2702
Benjamin Kramerf0623432012-08-23 22:51:59 +00002703 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002704 SourceLocation PlacementLParen, PlacementRParen;
2705
Douglas Gregorf2753b32010-07-13 15:54:32 +00002706 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002707 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002708 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002709 if (Tok.is(tok::l_paren)) {
2710 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002711 BalancedDelimiterTracker T(*this, tok::l_paren);
2712 T.consumeOpen();
2713 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002714 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002715 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002716 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002717 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002718
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002719 T.consumeClose();
2720 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002721 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002722 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002723 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002724 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002725
Sebastian Redl351bb782008-12-02 14:43:59 +00002726 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002727 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002728 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002729 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002730 } else {
2731 // We still need the type.
2732 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002733 BalancedDelimiterTracker T(*this, tok::l_paren);
2734 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002735 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002736 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002737 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002738 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002739 T.consumeClose();
2740 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002741 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002742 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002743 if (ParseCXXTypeSpecifierSeq(DS))
2744 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002745 else {
2746 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002747 ParseDeclaratorInternal(DeclaratorInfo,
2748 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002749 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002750 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002751 }
2752 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002753 // A new-type-id is a simplified type-id, where essentially the
2754 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002755 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002756 if (ParseCXXTypeSpecifierSeq(DS))
2757 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002758 else {
2759 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002760 ParseDeclaratorInternal(DeclaratorInfo,
2761 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002762 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002763 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002764 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002765 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002766 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002767 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002768
Sebastian Redl6047f072012-02-16 12:22:20 +00002769 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002770
2771 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002772 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002773 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002774 BalancedDelimiterTracker T(*this, tok::l_paren);
2775 T.consumeOpen();
2776 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002777 if (Tok.isNot(tok::r_paren)) {
2778 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002779 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2780 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2781 DeclaratorInfo).get();
2782 Actions.CodeCompleteConstructor(getCurScope(),
2783 TypeRep.get()->getCanonicalTypeInternal(),
2784 DeclaratorInfo.getLocEnd(),
2785 ConstructorArgs);
2786 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002787 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002788 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002789 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002790 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002791 T.consumeClose();
2792 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002793 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002794 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002795 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002796 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002797 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2798 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002799 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002800 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002801 Diag(Tok.getLocation(),
2802 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002803 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002804 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002805 if (Initializer.isInvalid())
2806 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002807
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002808 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002809 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002810 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002811}
2812
Sebastian Redlbd150f42008-11-21 19:14:01 +00002813/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2814/// passed to ParseDeclaratorInternal.
2815///
2816/// direct-new-declarator:
2817/// '[' expression ']'
2818/// direct-new-declarator '[' constant-expression ']'
2819///
Chris Lattner109faf22009-01-04 21:25:24 +00002820void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002821 // Parse the array dimensions.
2822 bool first = true;
2823 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002824 // An array-size expression can't start with a lambda.
2825 if (CheckProhibitedCXX11Attribute())
2826 continue;
2827
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002828 BalancedDelimiterTracker T(*this, tok::l_square);
2829 T.consumeOpen();
2830
John McCalldadc5752010-08-24 06:29:42 +00002831 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002832 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002833 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002834 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002835 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002836 return;
2837 }
2838 first = false;
2839
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002840 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002841
Bill Wendling44426052012-12-20 19:22:21 +00002842 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002843 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002844 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002845
John McCall084e83d2011-03-24 11:26:52 +00002846 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002847 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002848 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002849 T.getOpenLocation(),
2850 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002851 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002852
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002853 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002854 return;
2855 }
2856}
2857
2858/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2859/// This ambiguity appears in the syntax of the C++ new operator.
2860///
2861/// new-expression:
2862/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2863/// new-initializer[opt]
2864///
2865/// new-placement:
2866/// '(' expression-list ')'
2867///
John McCall37ad5512010-08-23 06:44:23 +00002868bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002869 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002870 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002871 // The '(' was already consumed.
2872 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002873 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002874 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002875 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002876 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002877 }
2878
2879 // It's not a type, it has to be an expression list.
2880 // Discard the comma locations - ActOnCXXNew has enough parameters.
2881 CommaLocsTy CommaLocs;
2882 return ParseExpressionList(PlacementArgs, CommaLocs);
2883}
2884
2885/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2886/// to free memory allocated by new.
2887///
Chris Lattner109faf22009-01-04 21:25:24 +00002888/// This method is called to parse the 'delete' expression after the optional
2889/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2890/// and "Start" is its location. Otherwise, "Start" is the location of the
2891/// 'delete' token.
2892///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002893/// delete-expression:
2894/// '::'[opt] 'delete' cast-expression
2895/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002896ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002897Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2898 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2899 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002900
2901 // Array delete?
2902 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002903 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002904 // C++11 [expr.delete]p1:
2905 // Whenever the delete keyword is followed by empty square brackets, it
2906 // shall be interpreted as [array delete].
2907 // [Footnote: A lambda expression with a lambda-introducer that consists
2908 // of empty square brackets can follow the delete keyword if
2909 // the lambda expression is enclosed in parentheses.]
2910 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2911 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002912 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002913 BalancedDelimiterTracker T(*this, tok::l_square);
2914
2915 T.consumeOpen();
2916 T.consumeClose();
2917 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002918 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002919 }
2920
John McCalldadc5752010-08-24 06:29:42 +00002921 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002922 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002923 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002924
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002925 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002926}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002927
Douglas Gregor29c42f22012-02-24 07:38:34 +00002928static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2929 switch (kind) {
2930 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002931#define TYPE_TRAIT_1(Spelling, Name, Key) \
2932case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002933#define TYPE_TRAIT_2(Spelling, Name, Key) \
2934case tok::kw_ ## Spelling: return BTT_ ## Name;
2935#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002936#define TYPE_TRAIT_N(Spelling, Name, Key) \
2937 case tok::kw_ ## Spelling: return TT_ ## Name;
2938#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002939 }
2940}
2941
John Wiegley6242b6a2011-04-28 00:16:57 +00002942static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2943 switch(kind) {
2944 default: llvm_unreachable("Not a known binary type trait");
2945 case tok::kw___array_rank: return ATT_ArrayRank;
2946 case tok::kw___array_extent: return ATT_ArrayExtent;
2947 }
2948}
2949
John Wiegleyf9f65842011-04-25 06:54:41 +00002950static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2951 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002952 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002953 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2954 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2955 }
2956}
2957
Alp Toker40f9b1c2013-12-12 21:23:03 +00002958static unsigned TypeTraitArity(tok::TokenKind kind) {
2959 switch (kind) {
2960 default: llvm_unreachable("Not a known type trait");
2961#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2962#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002963 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002964}
2965
Douglas Gregor29c42f22012-02-24 07:38:34 +00002966/// \brief Parse the built-in type-trait pseudo-functions that allow
2967/// implementation of the TR1/C++11 type traits templates.
2968///
2969/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002970/// unary-type-trait '(' type-id ')'
2971/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002972/// type-trait '(' type-id-seq ')'
2973///
2974/// type-id-seq:
2975/// type-id ...[opt] type-id-seq[opt]
2976///
2977ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002978 tok::TokenKind Kind = Tok.getKind();
2979 unsigned Arity = TypeTraitArity(Kind);
2980
Douglas Gregor29c42f22012-02-24 07:38:34 +00002981 SourceLocation Loc = ConsumeToken();
2982
2983 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002984 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002985 return ExprError();
2986
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002987 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002988 do {
2989 // Parse the next type.
2990 TypeResult Ty = ParseTypeName();
2991 if (Ty.isInvalid()) {
2992 Parens.skipToEnd();
2993 return ExprError();
2994 }
2995
2996 // Parse the ellipsis, if present.
2997 if (Tok.is(tok::ellipsis)) {
2998 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2999 if (Ty.isInvalid()) {
3000 Parens.skipToEnd();
3001 return ExprError();
3002 }
3003 }
3004
3005 // Add this type to the list of arguments.
3006 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003007 } while (TryConsumeToken(tok::comma));
3008
Douglas Gregor29c42f22012-02-24 07:38:34 +00003009 if (Parens.consumeClose())
3010 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003011
3012 SourceLocation EndLoc = Parens.getCloseLocation();
3013
3014 if (Arity && Args.size() != Arity) {
3015 Diag(EndLoc, diag::err_type_trait_arity)
3016 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3017 return ExprError();
3018 }
3019
3020 if (!Arity && Args.empty()) {
3021 Diag(EndLoc, diag::err_type_trait_arity)
3022 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3023 return ExprError();
3024 }
3025
Alp Toker88f64e62013-12-13 21:19:30 +00003026 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003027}
3028
John Wiegley6242b6a2011-04-28 00:16:57 +00003029/// ParseArrayTypeTrait - Parse the built-in array type-trait
3030/// pseudo-functions.
3031///
3032/// primary-expression:
3033/// [Embarcadero] '__array_rank' '(' type-id ')'
3034/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3035///
3036ExprResult Parser::ParseArrayTypeTrait() {
3037 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3038 SourceLocation Loc = ConsumeToken();
3039
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003040 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003041 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003042 return ExprError();
3043
3044 TypeResult Ty = ParseTypeName();
3045 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003046 SkipUntil(tok::comma, StopAtSemi);
3047 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003048 return ExprError();
3049 }
3050
3051 switch (ATT) {
3052 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003053 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003054 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003055 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003056 }
3057 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003058 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003059 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003060 return ExprError();
3061 }
3062
3063 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003064 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003065
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003066 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3067 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003068 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003069 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003070 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003071}
3072
John Wiegleyf9f65842011-04-25 06:54:41 +00003073/// ParseExpressionTrait - Parse built-in expression-trait
3074/// pseudo-functions like __is_lvalue_expr( xxx ).
3075///
3076/// primary-expression:
3077/// [Embarcadero] expression-trait '(' expression ')'
3078///
3079ExprResult Parser::ParseExpressionTrait() {
3080 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3081 SourceLocation Loc = ConsumeToken();
3082
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003083 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003084 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003085 return ExprError();
3086
3087 ExprResult Expr = ParseExpression();
3088
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003089 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003090
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003091 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3092 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003093}
3094
3095
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003096/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3097/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3098/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003099ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003100Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003101 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003102 BalancedDelimiterTracker &Tracker,
3103 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003104 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003105 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3106 assert(isTypeIdInParens() && "Not a type-id!");
3107
John McCalldadc5752010-08-24 06:29:42 +00003108 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003109 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003110
3111 // We need to disambiguate a very ugly part of the C++ syntax:
3112 //
3113 // (T())x; - type-id
3114 // (T())*x; - type-id
3115 // (T())/x; - expression
3116 // (T()); - expression
3117 //
3118 // The bad news is that we cannot use the specialized tentative parser, since
3119 // it can only verify that the thing inside the parens can be parsed as
3120 // type-id, it is not useful for determining the context past the parens.
3121 //
3122 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003123 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003124 //
3125 // It uses a scheme similar to parsing inline methods. The parenthesized
3126 // tokens are cached, the context that follows is determined (possibly by
3127 // parsing a cast-expression), and then we re-introduce the cached tokens
3128 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003129
Mike Stump11289f42009-09-09 15:08:12 +00003130 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003131 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003132
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003133 // Store the tokens of the parentheses. We will parse them after we determine
3134 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003135 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003136 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003137 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003138 return ExprError();
3139 }
3140
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003141 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003142 ParseAs = CompoundLiteral;
3143 } else {
3144 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003145 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3146 NotCastExpr = true;
3147 } else {
3148 // Try parsing the cast-expression that may follow.
3149 // If it is not a cast-expression, NotCastExpr will be true and no token
3150 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003151 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003152 Result = ParseCastExpression(false/*isUnaryExpression*/,
3153 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003154 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003155 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003156 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003157 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003158
3159 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3160 // an expression.
3161 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003162 }
3163
Alexey Bataev703a93c2016-02-04 04:22:09 +00003164 // Create a fake EOF to mark end of Toks buffer.
3165 Token AttrEnd;
3166 AttrEnd.startToken();
3167 AttrEnd.setKind(tok::eof);
3168 AttrEnd.setLocation(Tok.getLocation());
3169 AttrEnd.setEofData(Toks.data());
3170 Toks.push_back(AttrEnd);
3171
Mike Stump11289f42009-09-09 15:08:12 +00003172 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003173 Toks.push_back(Tok);
3174 // Re-enter the stored parenthesized tokens into the token stream, so we may
3175 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003176 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003177 // Drop the current token and bring the first cached one. It's the same token
3178 // as when we entered this function.
3179 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003180
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003181 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003182 // Parse the type declarator.
3183 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003184 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003185 {
3186 ColonProtectionRAIIObject InnerColonProtection(*this);
3187 ParseSpecifierQualifierList(DS);
3188 ParseDeclarator(DeclaratorInfo);
3189 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003190
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003191 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003192 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003193 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003194
Alexey Bataev703a93c2016-02-04 04:22:09 +00003195 // Consume EOF marker for Toks buffer.
3196 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3197 ConsumeAnyToken();
3198
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003199 if (ParseAs == CompoundLiteral) {
3200 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003201 if (DeclaratorInfo.isInvalidType())
3202 return ExprError();
3203
3204 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003205 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003206 Tracker.getOpenLocation(),
3207 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003208 }
Mike Stump11289f42009-09-09 15:08:12 +00003209
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003210 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3211 assert(ParseAs == CastExpr);
3212
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003213 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003214 return ExprError();
3215
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003216 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003217 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003218 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3219 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003220 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003221 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003222 }
Mike Stump11289f42009-09-09 15:08:12 +00003223
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003224 // Not a compound literal, and not followed by a cast-expression.
3225 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003226
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003227 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003228 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003229 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003230 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003231 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003232
3233 // Match the ')'.
3234 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003235 while (Tok.isNot(tok::eof))
3236 ConsumeAnyToken();
3237 assert(Tok.getEofData() == AttrEnd.getEofData());
3238 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003239 return ExprError();
3240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003242 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003243 // Consume EOF marker for Toks buffer.
3244 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3245 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003246 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003247}