blob: 1ba1695800f543935d356728223b5afebaef6c4a [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
Mike Stump11289f42009-09-09 15:08:12 +0000103/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000104///
105/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000106/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000107/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000108///
109/// '::'[opt] nested-name-specifier
110/// '::'
111///
112/// nested-name-specifier:
113/// type-name '::'
114/// namespace-name '::'
115/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000116/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000117///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000118///
Mike Stump11289f42009-09-09 15:08:12 +0000119/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000120/// nested-name-specifier (or empty)
121///
Mike Stump11289f42009-09-09 15:08:12 +0000122/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000123/// the "." or "->" of a member access expression, this parameter provides the
124/// type of the object whose members are being accessed.
125///
126/// \param EnteringContext whether we will be entering into the context of
127/// the nested-name-specifier after parsing it.
128///
Douglas Gregore610ada2010-02-24 18:44:31 +0000129/// \param MayBePseudoDestructor When non-NULL, points to a flag that
130/// indicates whether this nested-name-specifier may be part of a
131/// pseudo-destructor name. In this case, the flag will be set false
132/// if we don't actually end up parsing a destructor name. Moreorover,
133/// if we do end up determining that we are parsing a destructor name,
134/// the last component of the nested-name-specifier is not parsed as
135/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000136///
137/// \param IsTypename If \c true, this nested-name-specifier is known to be
138/// part of a type name. This is used to improve error recovery.
139///
140/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
141/// filled in with the leading identifier in the last component of the
142/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000143///
John McCall1f476a12010-02-26 08:45:28 +0000144/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000145bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000146 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000147 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000148 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000149 bool IsTypename,
150 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000151 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000152 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000153
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000154 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000155 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000156 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000157 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
158 Tok.getAnnotationRange(),
159 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000160 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000161 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000162 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000163
Larisse Voufob959c3c2013-08-06 05:49:26 +0000164 if (Tok.is(tok::annot_template_id)) {
165 // If the current token is an annotated template id, it may already have
166 // a scope specifier. Restore it.
167 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
168 SS = TemplateId->SS;
169 }
170
Nico Weberc60aa712015-02-16 22:32:46 +0000171 // Has to happen before any "return false"s in this function.
172 bool CheckForDestructor = false;
173 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
174 CheckForDestructor = true;
175 *MayBePseudoDestructor = false;
176 }
177
Richard Smith7447af42013-03-26 01:15:19 +0000178 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000179 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000180
Douglas Gregor7f741122009-02-25 19:37:18 +0000181 bool HasScopeSpecifier = false;
182
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000183 if (Tok.is(tok::coloncolon)) {
184 // ::new and ::delete aren't nested-name-specifiers.
185 tok::TokenKind NextKind = NextToken().getKind();
186 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
187 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000188
David Majnemere8fb28f2014-12-29 19:19:18 +0000189 if (NextKind == tok::l_brace) {
190 // It is invalid to have :: {, consume the scope qualifier and pretend
191 // like we never saw it.
192 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
193 } else {
194 // '::' - Global scope qualifier.
195 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
196 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000197
David Majnemere8fb28f2014-12-29 19:19:18 +0000198 HasScopeSpecifier = true;
199 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000200 }
201
Nikola Smiljanic67860242014-09-26 00:28:20 +0000202 if (Tok.is(tok::kw___super)) {
203 SourceLocation SuperLoc = ConsumeToken();
204 if (!Tok.is(tok::coloncolon)) {
205 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
206 return true;
207 }
208
209 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
210 }
211
Richard Smitha9d10012014-10-04 01:57:39 +0000212 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000213 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000214 DeclSpec DS(AttrFactory);
215 SourceLocation DeclLoc = Tok.getLocation();
216 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000217
218 SourceLocation CCLoc;
219 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000220 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
221 return false;
222 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000223
David Blaikie15a430a2011-12-04 05:04:18 +0000224 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
225 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
226
227 HasScopeSpecifier = true;
228 }
229
Douglas Gregor7f741122009-02-25 19:37:18 +0000230 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000231 if (HasScopeSpecifier) {
232 // C++ [basic.lookup.classref]p5:
233 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000234 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000235 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000236 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000237 // the class-name-or-namespace-name is looked up in global scope as a
238 // class-name or namespace-name.
239 //
240 // To implement this, we clear out the object type as soon as we've
241 // seen a leading '::' or part of a nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000242 ObjectType = nullptr;
243
Douglas Gregor2436e712009-09-17 21:32:03 +0000244 if (Tok.is(tok::code_completion)) {
245 // Code completion for a nested-name-specifier, where the code
246 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000247 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000248 // Include code completion token into the range of the scope otherwise
249 // when we try to annotate the scope tokens the dangling code completion
250 // token will cause assertion in
251 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000252 SS.setEndLoc(Tok.getLocation());
253 cutOffParsing();
254 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000255 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Douglas Gregor7f741122009-02-25 19:37:18 +0000258 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000259 // nested-name-specifier 'template'[opt] simple-template-id '::'
260
261 // Parse the optional 'template' keyword, then make sure we have
262 // 'identifier <' after it.
263 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000264 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000265 // nested-name-specifier, since they aren't allowed to start with
266 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000267 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000268 break;
269
Douglas Gregor120635b2009-11-11 16:39:34 +0000270 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000271 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000272
Douglas Gregor71395fa2009-11-04 00:56:37 +0000273 UnqualifiedId TemplateName;
274 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000275 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000276 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000277 ConsumeToken();
278 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000279 // We don't need to actually parse the unqualified-id in this case,
280 // because a simple-template-id cannot start with 'operator', but
281 // go ahead and parse it anyway for consistency with the case where
282 // we already annotated the template-id.
283 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000284 TemplateName)) {
285 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000286 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000287 }
Richard Smithd091dc12013-12-05 00:58:33 +0000288
Alexis Hunted0530f2009-11-28 08:58:14 +0000289 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
290 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000291 Diag(TemplateName.getSourceRange().getBegin(),
292 diag::err_id_after_template_in_nested_name_spec)
293 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000294 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000295 break;
296 }
297 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000298 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000299 break;
300 }
Mike Stump11289f42009-09-09 15:08:12 +0000301
Douglas Gregor120635b2009-11-11 16:39:34 +0000302 // If the next token is not '<', we have a qualified-id that refers
303 // to a template name, such as T::template apply, but is not a
304 // template-id.
305 if (Tok.isNot(tok::less)) {
306 TPA.Revert();
307 break;
308 }
309
310 // Commit to parsing the template-id.
311 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000312 TemplateTy Template;
Richard Smithfd3dae02017-01-20 00:20:39 +0000313 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
314 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
315 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000316 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
317 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000318 return true;
319 } else
John McCall1f476a12010-02-26 08:45:28 +0000320 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000321
Chris Lattner0eed3a62009-06-26 03:47:46 +0000322 continue;
323 }
Mike Stump11289f42009-09-09 15:08:12 +0000324
Douglas Gregor7f741122009-02-25 19:37:18 +0000325 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000326 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000327 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000328 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000329 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000330 // So we need to check whether the template-id is a simple-template-id of
331 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000332 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000333 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000334 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
335 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000336 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000337 }
338
Richard Smith7447af42013-03-26 01:15:19 +0000339 if (LastII)
340 *LastII = TemplateId->Name;
341
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000342 // Consume the template-id token.
343 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000344
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000345 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
346 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000347
David Blaikie8c045bc2011-11-07 03:30:03 +0000348 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000349
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000350 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000351 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000352
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000353 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000354 SS,
355 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000356 TemplateId->Template,
357 TemplateId->TemplateNameLoc,
358 TemplateId->LAngleLoc,
359 TemplateArgsPtr,
360 TemplateId->RAngleLoc,
361 CCLoc,
362 EnteringContext)) {
363 SourceLocation StartLoc
364 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
365 : TemplateId->TemplateNameLoc;
366 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000367 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000368
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000369 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000370 }
371
Chris Lattnere2355f72009-06-26 03:52:38 +0000372 // The rest of the nested-name-specifier possibilities start with
373 // tok::identifier.
374 if (Tok.isNot(tok::identifier))
375 break;
376
377 IdentifierInfo &II = *Tok.getIdentifierInfo();
378
379 // nested-name-specifier:
380 // type-name '::'
381 // namespace-name '::'
382 // nested-name-specifier identifier '::'
383 Token Next = NextToken();
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000384 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
385 ObjectType);
386
Chris Lattner1c428032009-12-07 01:36:53 +0000387 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
388 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000389 if (Next.is(tok::colon) && !ColonIsSacred) {
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000390 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000391 EnteringContext) &&
392 // If the token after the colon isn't an identifier, it's still an
393 // error, but they probably meant something else strange so don't
394 // recover like this.
395 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000396 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000397 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000398 // Recover as if the user wrote '::'.
399 Next.setKind(tok::coloncolon);
400 }
Chris Lattner1c428032009-12-07 01:36:53 +0000401 }
David Majnemerf58efd92014-12-29 23:12:23 +0000402
403 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
404 // It is invalid to have :: {, consume the scope qualifier and pretend
405 // like we never saw it.
406 Token Identifier = Tok; // Stash away the identifier.
407 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000408 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
409 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000410 UnconsumeToken(Identifier); // Stick the identifier back.
411 Next = NextToken(); // Point Next at the '{' token.
412 }
413
Chris Lattnere2355f72009-06-26 03:52:38 +0000414 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000415 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000416 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000417 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000418 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000419 }
420
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000421 if (ColonIsSacred) {
422 const Token &Next2 = GetLookAheadToken(2);
423 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
424 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
425 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
426 << Next2.getName()
427 << FixItHint::CreateReplacement(Next.getLocation(), ":");
428 Token ColonColon;
429 PP.Lex(ColonColon);
430 ColonColon.setKind(tok::colon);
431 PP.EnterToken(ColonColon);
432 break;
433 }
434 }
435
Richard Smith7447af42013-03-26 01:15:19 +0000436 if (LastII)
437 *LastII = &II;
438
Chris Lattnere2355f72009-06-26 03:52:38 +0000439 // We have an identifier followed by a '::'. Lookup this name
440 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000441 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000442 SourceLocation IdLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000443 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
Chris Lattner1c428032009-12-07 01:36:53 +0000444 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000445 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000446 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000447
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000448 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000449 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000450 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), IdInfo,
451 EnteringContext, SS,
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000452 false, CorrectionFlagPtr)) {
453 // Identifier is not recognized as a nested name, but we can have
454 // mistyped '::' instead of ':'.
455 if (CorrectionFlagPtr && IsCorrectedToColon) {
456 ColonColon.setKind(tok::colon);
457 PP.EnterToken(Tok);
458 PP.EnterToken(ColonColon);
459 Tok = Identifier;
460 break;
461 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000462 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000463 }
464 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000465 continue;
466 }
Mike Stump11289f42009-09-09 15:08:12 +0000467
Richard Trieu01fc0012011-09-19 19:01:00 +0000468 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000469
Chris Lattnere2355f72009-06-26 03:52:38 +0000470 // nested-name-specifier:
471 // type-name '<'
472 if (Next.is(tok::less)) {
473 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000474 UnqualifiedId TemplateName;
475 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000476 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000477 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000478 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000479 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000480 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000481 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000482 Template,
483 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000484 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000485 // with a template-id annotation. We do not permit the
486 // template-id to be translated into a type annotation,
487 // because some clients (e.g., the parsing of class template
488 // specializations) still want to see the original template-id
489 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000490 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000491 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
492 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000493 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000494 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000495 }
496
Douglas Gregor20c38a72010-05-21 23:43:39 +0000497 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000498 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000499 // We have something like t::getAs<T>, where getAs is a
500 // member of an unknown specialization. However, this will only
501 // parse correctly as a template, so suggest the keyword 'template'
502 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000503 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000505 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000506
507 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000508 << II.getName()
509 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +0000510
511 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
512 getCurScope(), SS, SourceLocation(), TemplateName, ObjectType,
513 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Douglas Gregorbb119652010-06-16 23:00:59 +0000514 // Consume the identifier.
515 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000516 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
517 TemplateName, false))
518 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000519 }
520 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000521 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000522
Douglas Gregor20c38a72010-05-21 23:43:39 +0000523 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000524 }
525 }
526
Douglas Gregor7f741122009-02-25 19:37:18 +0000527 // We don't have any tokens that form the beginning of a
528 // nested-name-specifier, so we're done.
529 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Douglas Gregore610ada2010-02-24 18:44:31 +0000532 // Even if we didn't see any pieces of a nested-name-specifier, we
533 // still check whether there is a tilde in this position, which
534 // indicates a potential pseudo-destructor.
535 if (CheckForDestructor && Tok.is(tok::tilde))
536 *MayBePseudoDestructor = true;
537
John McCall1f476a12010-02-26 08:45:28 +0000538 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000539}
540
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000541ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
542 Token &Replacement) {
543 SourceLocation TemplateKWLoc;
544 UnqualifiedId Name;
545 if (ParseUnqualifiedId(SS,
546 /*EnteringContext=*/false,
547 /*AllowDestructorName=*/false,
548 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000549 /*AllowDeductionGuide=*/false,
David Blaikieefdccaa2016-01-15 23:43:34 +0000550 /*ObjectType=*/nullptr, TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000551 return ExprError();
552
553 // This is only the direct operand of an & operator if it is not
554 // followed by a postfix-expression suffix.
555 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
556 isAddressOfOperand = false;
557
558 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
559 Tok.is(tok::l_paren), isAddressOfOperand,
560 nullptr, /*IsInlineAsmIdentifier=*/false,
561 &Replacement);
562}
563
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000564/// ParseCXXIdExpression - Handle id-expression.
565///
566/// id-expression:
567/// unqualified-id
568/// qualified-id
569///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000570/// qualified-id:
571/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
572/// '::' identifier
573/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000574/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000575///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000576/// NOTE: The standard specifies that, for qualified-id, the parser does not
577/// expect:
578///
579/// '::' conversion-function-id
580/// '::' '~' class-name
581///
582/// This may cause a slight inconsistency on diagnostics:
583///
584/// class C {};
585/// namespace A {}
586/// void f() {
587/// :: A :: ~ C(); // Some Sema error about using destructor with a
588/// // namespace.
589/// :: ~ C(); // Some Parser error like 'unexpected ~'.
590/// }
591///
592/// We simplify the parser a bit and make it work like:
593///
594/// qualified-id:
595/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
596/// '::' unqualified-id
597///
598/// That way Sema can handle and report similar errors for namespaces and the
599/// global scope.
600///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000601/// The isAddressOfOperand parameter indicates that this id-expression is a
602/// direct operand of the address-of operator. This is, besides member contexts,
603/// the only place where a qualified-id naming a non-static class member may
604/// appear.
605///
John McCalldadc5752010-08-24 06:29:42 +0000606ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000607 // qualified-id:
608 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
609 // '::' unqualified-id
610 //
611 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000612 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000613
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000614 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000615 ExprResult Result =
616 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000617 if (Result.isUnset()) {
618 // If the ExprResult is valid but null, then typo correction suggested a
619 // keyword replacement that needs to be reparsed.
620 UnconsumeToken(Replacement);
621 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
622 }
623 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
624 "for a previous keyword suggestion");
625 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000626}
627
Richard Smith21b3ab42013-05-09 21:36:41 +0000628/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000629///
630/// lambda-expression:
631/// lambda-introducer lambda-declarator[opt] compound-statement
632///
633/// lambda-introducer:
634/// '[' lambda-capture[opt] ']'
635///
636/// lambda-capture:
637/// capture-default
638/// capture-list
639/// capture-default ',' capture-list
640///
641/// capture-default:
642/// '&'
643/// '='
644///
645/// capture-list:
646/// capture
647/// capture-list ',' capture
648///
649/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000650/// simple-capture
651/// init-capture [C++1y]
652///
653/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000654/// identifier
655/// '&' identifier
656/// 'this'
657///
Richard Smith21b3ab42013-05-09 21:36:41 +0000658/// init-capture: [C++1y]
659/// identifier initializer
660/// '&' identifier initializer
661///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000662/// lambda-declarator:
663/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
664/// 'mutable'[opt] exception-specification[opt]
665/// trailing-return-type[opt]
666///
667ExprResult Parser::ParseLambdaExpression() {
668 // Parse lambda-introducer.
669 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000670 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000671 if (DiagID) {
672 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000673 SkipUntil(tok::r_square, StopAtSemi);
674 SkipUntil(tok::l_brace, StopAtSemi);
675 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000676 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000677 }
678
679 return ParseLambdaExpressionAfterIntroducer(Intro);
680}
681
682/// TryParseLambdaExpression - Use lookahead and potentially tentative
683/// parsing to determine if we are looking at a C++0x lambda expression, and parse
684/// it if we are.
685///
686/// If we are not looking at a lambda expression, returns ExprError().
687ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000688 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000689 && Tok.is(tok::l_square)
690 && "Not at the start of a possible lambda expression.");
691
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000692 const Token Next = NextToken();
693 if (Next.is(tok::eof)) // Nothing else to lookup here...
694 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000695
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000696 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000697 // If lookahead indicates this is a lambda...
698 if (Next.is(tok::r_square) || // []
699 Next.is(tok::equal) || // [=
700 (Next.is(tok::amp) && // [&] or [&,
701 (After.is(tok::r_square) ||
702 After.is(tok::comma))) ||
703 (Next.is(tok::identifier) && // [identifier]
704 After.is(tok::r_square))) {
705 return ParseLambdaExpression();
706 }
707
Eli Friedmanc7c97142012-01-04 02:40:39 +0000708 // If lookahead indicates an ObjC message send...
709 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000710 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000711 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000712 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000713
Eli Friedmanc7c97142012-01-04 02:40:39 +0000714 // Here, we're stuck: lambda introducers and Objective-C message sends are
715 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
716 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
717 // writing two routines to parse a lambda introducer, just try to parse
718 // a lambda introducer first, and fall back if that fails.
719 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000720 LambdaIntroducer Intro;
721 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000722 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000723
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000724 return ParseLambdaExpressionAfterIntroducer(Intro);
725}
726
Richard Smithf44d2a82013-05-21 22:21:19 +0000727/// \brief Parse a lambda introducer.
728/// \param Intro A LambdaIntroducer filled in with information about the
729/// contents of the lambda-introducer.
730/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
731/// message send and a lambda expression. In this mode, we will
732/// sometimes skip the initializers for init-captures and not fully
733/// populate \p Intro. This flag will be set to \c true if we do so.
734/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000735/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000736Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
737 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000738 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000739
740 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000741 BalancedDelimiterTracker T(*this, tok::l_square);
742 T.consumeOpen();
743
744 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745
746 bool first = true;
747
748 // Parse capture-default.
749 if (Tok.is(tok::amp) &&
750 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
751 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000752 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000753 first = false;
754 } else if (Tok.is(tok::equal)) {
755 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000756 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000757 first = false;
758 }
759
760 while (Tok.isNot(tok::r_square)) {
761 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000762 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000763 // Provide a completion for a lambda introducer here. Except
764 // in Objective-C, where this is Almost Surely meant to be a message
765 // send. In that case, fail here and let the ObjC message
766 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000767 if (Tok.is(tok::code_completion) &&
768 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
769 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000770 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
771 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000772 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000773 break;
774 }
775
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000776 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000777 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000778 ConsumeToken();
779 }
780
Douglas Gregord8c61782012-02-15 15:34:24 +0000781 if (Tok.is(tok::code_completion)) {
782 // If we're in Objective-C++ and we have a bare '[', then this is more
783 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000784 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000785 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
786 else
787 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
788 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000789 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000790 break;
791 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000792
Douglas Gregord8c61782012-02-15 15:34:24 +0000793 first = false;
794
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000795 // Parse capture.
796 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000797 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000798 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000799 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000800 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000801 ExprResult Init;
Faisal Validc6b5962016-03-21 09:25:37 +0000802
803 if (Tok.is(tok::star)) {
804 Loc = ConsumeToken();
805 if (Tok.is(tok::kw_this)) {
806 ConsumeToken();
807 Kind = LCK_StarThis;
808 } else {
809 return DiagResult(diag::err_expected_star_this_capture);
810 }
811 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000812 Kind = LCK_This;
813 Loc = ConsumeToken();
814 } else {
815 if (Tok.is(tok::amp)) {
816 Kind = LCK_ByRef;
817 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000818
819 if (Tok.is(tok::code_completion)) {
820 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
821 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000822 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000823 break;
824 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000825 }
826
827 if (Tok.is(tok::identifier)) {
828 Id = Tok.getIdentifierInfo();
829 Loc = ConsumeToken();
830 } else if (Tok.is(tok::kw_this)) {
831 // FIXME: If we want to suggest a fixit here, will need to return more
832 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
833 // Clear()ed to prevent emission in case of tentative parsing?
834 return DiagResult(diag::err_this_captured_by_reference);
835 } else {
836 return DiagResult(diag::err_expected_capture);
837 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000838
839 if (Tok.is(tok::l_paren)) {
840 BalancedDelimiterTracker Parens(*this, tok::l_paren);
841 Parens.consumeOpen();
842
Richard Smith42b10572015-11-11 01:36:17 +0000843 InitKind = LambdaCaptureInitKind::DirectInit;
844
Richard Smith21b3ab42013-05-09 21:36:41 +0000845 ExprVector Exprs;
846 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000847 if (SkippedInits) {
848 Parens.skipToEnd();
849 *SkippedInits = true;
850 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000851 Parens.skipToEnd();
852 Init = ExprError();
853 } else {
854 Parens.consumeClose();
855 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
856 Parens.getCloseLocation(),
857 Exprs);
858 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000859 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000860 // Each lambda init-capture forms its own full expression, which clears
861 // Actions.MaybeODRUseExprs. So create an expression evaluation context
862 // to save the necessary state, and restore it later.
863 EnterExpressionEvaluationContext EC(Actions,
864 Sema::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000865
866 if (TryConsumeToken(tok::equal))
867 InitKind = LambdaCaptureInitKind::CopyInit;
868 else
869 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000870
Richard Smith215f4232015-02-11 02:41:33 +0000871 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000872 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000873 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000874 BalancedDelimiterTracker Braces(*this, tok::l_brace);
875 Braces.consumeOpen();
876 Braces.skipToEnd();
877 *SkippedInits = true;
878 } else {
879 // We're disambiguating this:
880 //
881 // [..., x = expr
882 //
883 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000884 // determine whether this is an Obj-C message send's receiver, a
885 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000886 //
887 // Parse the expression to find where it ends, and annotate it back
888 // onto the tokens. We would have parsed this expression the same way
889 // in either case: both the RHS of an init-capture and the RHS of an
890 // assignment expression are parsed as an initializer-clause, and in
891 // neither case can anything be added to the scope between the '[' and
892 // here.
893 //
894 // FIXME: This is horrible. Adding a mechanism to skip an expression
895 // would be much cleaner.
896 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
897 // that instead. (And if we see a ':' with no matching '?', we can
898 // classify this as an Obj-C message send.)
899 SourceLocation StartLoc = Tok.getLocation();
900 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
901 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000902 if (!Init.isInvalid())
903 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000904
905 if (Tok.getLocation() != StartLoc) {
906 // Back out the lexing of the token after the initializer.
907 PP.RevertCachedTokens(1);
908
909 // Replace the consumed tokens with an appropriate annotation.
910 Tok.setLocation(StartLoc);
911 Tok.setKind(tok::annot_primary_expr);
912 setExprAnnotation(Tok, Init);
913 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
914 PP.AnnotateCachedTokens(Tok);
915
916 // Consume the annotated initializer.
917 ConsumeToken();
918 }
919 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000920 } else
921 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000922 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000923 // If this is an init capture, process the initialization expression
924 // right away. For lambda init-captures such as the following:
925 // const int x = 10;
926 // auto L = [i = x+1](int a) {
927 // return [j = x+2,
928 // &k = x](char b) { };
929 // };
930 // keep in mind that each lambda init-capture has to have:
931 // - its initialization expression executed in the context
932 // of the enclosing/parent decl-context.
933 // - but the variable itself has to be 'injected' into the
934 // decl-context of its lambda's call-operator (which has
935 // not yet been created).
936 // Each init-expression is a full-expression that has to get
937 // Sema-analyzed (for capturing etc.) before its lambda's
938 // call-operator's decl-context, scope & scopeinfo are pushed on their
939 // respective stacks. Thus if any variable is odr-used in the init-capture
940 // it will correctly get captured in the enclosing lambda, if one exists.
941 // The init-variables above are created later once the lambdascope and
942 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000943
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000944 // Since the lambda init-capture's initializer expression occurs in the
945 // context of the enclosing function or lambda, therefore we can not wait
946 // till a lambda scope has been pushed on before deciding whether the
947 // variable needs to be captured. We also need to process all
948 // lvalue-to-rvalue conversions and discarded-value conversions,
949 // so that we can avoid capturing certain constant variables.
950 // For e.g.,
951 // void test() {
952 // const int x = 10;
953 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
954 // return [y = x](int i) { <-- don't capture by enclosing lambda
955 // return y;
956 // }
957 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000958 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000959 // If x was not const, the second use would require 'L' to capture, and
960 // that would be an error.
961
Richard Smith42b10572015-11-11 01:36:17 +0000962 ParsedType InitCaptureType;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000963 if (Init.isUsable()) {
964 // Get the pointer and store it in an lvalue, so we can use it as an
965 // out argument.
966 Expr *InitExpr = Init.get();
967 // This performs any lvalue-to-rvalue conversions if necessary, which
968 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000969 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
970 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000971 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000972 }
Richard Smith42b10572015-11-11 01:36:17 +0000973 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
974 InitCaptureType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000975 }
976
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000977 T.consumeClose();
978 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000979 return DiagResult();
980}
981
Douglas Gregord8c61782012-02-15 15:34:24 +0000982/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000983///
984/// Returns true if it hit something unexpected.
985bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
986 TentativeParsingAction PA(*this);
987
Richard Smithf44d2a82013-05-21 22:21:19 +0000988 bool SkippedInits = false;
989 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000990
991 if (DiagID) {
992 PA.Revert();
993 return true;
994 }
995
Richard Smithf44d2a82013-05-21 22:21:19 +0000996 if (SkippedInits) {
997 // Parse it again, but this time parse the init-captures too.
998 PA.Revert();
999 Intro = LambdaIntroducer();
1000 DiagID = ParseLambdaIntroducer(Intro);
1001 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1002 return false;
1003 }
1004
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001005 PA.Commit();
1006 return false;
1007}
1008
Faisal Valia734ab92016-03-26 16:11:37 +00001009static void
1010tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1011 SourceLocation &ConstexprLoc,
1012 SourceLocation &DeclEndLoc) {
1013 assert(MutableLoc.isInvalid());
1014 assert(ConstexprLoc.isInvalid());
1015 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1016 // to the final of those locations. Emit an error if we have multiple
1017 // copies of those keywords and recover.
1018
1019 while (true) {
1020 switch (P.getCurToken().getKind()) {
1021 case tok::kw_mutable: {
1022 if (MutableLoc.isValid()) {
1023 P.Diag(P.getCurToken().getLocation(),
1024 diag::err_lambda_decl_specifier_repeated)
1025 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1026 }
1027 MutableLoc = P.ConsumeToken();
1028 DeclEndLoc = MutableLoc;
1029 break /*switch*/;
1030 }
1031 case tok::kw_constexpr:
1032 if (ConstexprLoc.isValid()) {
1033 P.Diag(P.getCurToken().getLocation(),
1034 diag::err_lambda_decl_specifier_repeated)
1035 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1036 }
1037 ConstexprLoc = P.ConsumeToken();
1038 DeclEndLoc = ConstexprLoc;
1039 break /*switch*/;
1040 default:
1041 return;
1042 }
1043 }
1044}
1045
1046static void
1047addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1048 DeclSpec &DS) {
1049 if (ConstexprLoc.isValid()) {
1050 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
1051 ? diag::ext_constexpr_on_lambda_cxx1z
1052 : diag::warn_cxx14_compat_constexpr_on_lambda);
1053 const char *PrevSpec = nullptr;
1054 unsigned DiagID = 0;
1055 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1056 assert(PrevSpec == nullptr && DiagID == 0 &&
1057 "Constexpr cannot have been set previously!");
1058 }
1059}
1060
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001061/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1062/// expression.
1063ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1064 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001065 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1066 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1067
1068 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1069 "lambda expression parsing");
1070
Faisal Vali2b391ab2013-09-26 19:54:12 +00001071
1072
Richard Smith21b3ab42013-05-09 21:36:41 +00001073 // FIXME: Call into Actions to add any init-capture declarations to the
1074 // scope while parsing the lambda-declarator and compound-statement.
1075
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001076 // Parse lambda-declarator[opt].
1077 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001078 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001079 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001080 Actions.PushLambdaScope();
1081
1082 ParsedAttributes Attr(AttrFactory);
1083 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001084 if (getLangOpts().CUDA) {
1085 // In CUDA code, GNU attributes are allowed to appear immediately after the
1086 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001087 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001088 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001089
Justin Lebare46ea722016-09-30 19:55:55 +00001090 // Helper to emit a warning if we see a CUDA host/device/global attribute
1091 // after '(...)'. nvcc doesn't accept this.
1092 auto WarnIfHasCUDATargetAttr = [&] {
1093 if (getLangOpts().CUDA)
1094 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1095 if (A->getKind() == AttributeList::AT_CUDADevice ||
1096 A->getKind() == AttributeList::AT_CUDAHost ||
1097 A->getKind() == AttributeList::AT_CUDAGlobal)
1098 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1099 << A->getName()->getName();
1100 };
1101
David Majnemere01c4662015-01-09 05:10:55 +00001102 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001103 if (Tok.is(tok::l_paren)) {
1104 ParseScope PrototypeScope(this,
1105 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001106 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001107 Scope::DeclScope);
1108
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001109 BalancedDelimiterTracker T(*this, tok::l_paren);
1110 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001111 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001112
1113 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001114 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001115 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001116
1117 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001118 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001119 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001120 // For a generic lambda, each 'auto' within the parameter declaration
1121 // clause creates a template type parameter, so increment the depth.
1122 if (Actions.getCurGenericLambda())
1123 ++CurTemplateDepthTracker;
1124 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001125 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001126 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001127 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001128
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001129 // GNU-style attributes must be parsed before the mutable specifier to be
1130 // compatible with GCC.
1131 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1132
David Majnemerbda86322015-02-04 08:22:46 +00001133 // MSVC-style attributes must be parsed before the mutable specifier to be
1134 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001135 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001136
Faisal Valia734ab92016-03-26 16:11:37 +00001137 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001138 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001139 SourceLocation ConstexprLoc;
1140 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1141 DeclEndLoc);
1142
1143 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001144
1145 // Parse exception-specification[opt].
1146 ExceptionSpecificationType ESpecType = EST_None;
1147 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001148 SmallVector<ParsedType, 2> DynamicExceptions;
1149 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001150 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001151 CachedTokens *ExceptionSpecTokens;
1152 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1153 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001154 DynamicExceptions,
1155 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001156 NoexceptExpr,
1157 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001158
1159 if (ESpecType != EST_None)
1160 DeclEndLoc = ESpecRange.getEnd();
1161
1162 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001163 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001164
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001165 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1166
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001167 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001168 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001169 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001170 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001171 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001172 if (Range.getEnd().isValid())
1173 DeclEndLoc = Range.getEnd();
1174 }
1175
1176 PrototypeScope.Exit();
1177
Justin Lebare46ea722016-09-30 19:55:55 +00001178 WarnIfHasCUDATargetAttr();
1179
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001180 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001181 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001182 /*isAmbiguous=*/false,
1183 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001184 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001185 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001186 DS.getTypeQualifiers(),
1187 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001188 /*RefQualifierLoc=*/NoLoc,
1189 /*ConstQualifierLoc=*/NoLoc,
1190 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001191 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001192 MutableLoc,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001193 ESpecType, ESpecRange,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001194 DynamicExceptions.data(),
1195 DynamicExceptionRanges.data(),
1196 DynamicExceptions.size(),
1197 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001198 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001199 /*ExceptionSpecTokens*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001200 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001201 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001202 TrailingReturnType),
1203 Attr, DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001204 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1205 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001206 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1207 // It's common to forget that one needs '()' before 'mutable', an attribute
1208 // specifier, or the result type. Deal with this.
1209 unsigned TokKind = 0;
1210 switch (Tok.getKind()) {
1211 case tok::kw_mutable: TokKind = 0; break;
1212 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001213 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001214 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001215 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001216 default: llvm_unreachable("Unknown token kind");
1217 }
1218
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001219 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001220 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001221 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001222 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001223
1224 // GNU-style attributes must be parsed before the mutable specifier to be
1225 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001226 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1227
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001228 // Parse 'mutable', if it's there.
1229 SourceLocation MutableLoc;
1230 if (Tok.is(tok::kw_mutable)) {
1231 MutableLoc = ConsumeToken();
1232 DeclEndLoc = MutableLoc;
1233 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001234
1235 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001236 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1237
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001238 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001239 if (Tok.is(tok::arrow)) {
1240 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001241 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001242 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001243 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001244 }
1245
Justin Lebare46ea722016-09-30 19:55:55 +00001246 WarnIfHasCUDATargetAttr();
1247
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001248 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001249 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001250 /*isAmbiguous=*/false,
1251 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001252 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001253 /*NumParams=*/0,
1254 /*EllipsisLoc=*/NoLoc,
1255 /*RParenLoc=*/NoLoc,
1256 /*TypeQuals=*/0,
1257 /*RefQualifierIsLValueRef=*/true,
1258 /*RefQualifierLoc=*/NoLoc,
1259 /*ConstQualifierLoc=*/NoLoc,
1260 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001261 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001262 MutableLoc,
1263 EST_None,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001264 /*ESpecRange=*/SourceRange(),
Craig Topper161e4db2014-05-21 06:02:52 +00001265 /*Exceptions=*/nullptr,
1266 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001267 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001268 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001269 /*ExceptionSpecTokens=*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001270 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001271 DeclLoc, DeclEndLoc, D,
1272 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001273 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001274 }
1275
Eli Friedman4817cf72012-01-06 03:05:34 +00001276 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1277 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001278 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001279 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001280
Eli Friedman71c80552012-01-05 03:35:19 +00001281 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1282
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001283 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001284 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001285 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001286 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1287 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001288 }
1289
Eli Friedmanc7c97142012-01-04 02:40:39 +00001290 StmtResult Stmt(ParseCompoundStatementBody());
1291 BodyScope.Exit();
1292
David Majnemere01c4662015-01-09 05:10:55 +00001293 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001294 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001295
Eli Friedman898caf82012-01-04 02:46:53 +00001296 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1297 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001298}
1299
Chris Lattner29375652006-12-04 18:06:35 +00001300/// ParseCXXCasts - This handles the various ways to cast expressions to another
1301/// type.
1302///
1303/// postfix-expression: [C++ 5.2p1]
1304/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1305/// 'static_cast' '<' type-name '>' '(' expression ')'
1306/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1307/// 'const_cast' '<' type-name '>' '(' expression ')'
1308///
John McCalldadc5752010-08-24 06:29:42 +00001309ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001310 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001311 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001312
1313 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001314 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001315 case tok::kw_const_cast: CastName = "const_cast"; break;
1316 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1317 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1318 case tok::kw_static_cast: CastName = "static_cast"; break;
1319 }
1320
1321 SourceLocation OpLoc = ConsumeToken();
1322 SourceLocation LAngleBracketLoc = Tok.getLocation();
1323
Richard Smith55858492011-04-14 21:45:45 +00001324 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1325 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001326 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1327 Token Next = NextToken();
1328 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1329 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1330 }
Richard Smith55858492011-04-14 21:45:45 +00001331
Chris Lattner29375652006-12-04 18:06:35 +00001332 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001333 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001334
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001335 // Parse the common declaration-specifiers piece.
1336 DeclSpec DS(AttrFactory);
1337 ParseSpecifierQualifierList(DS);
1338
1339 // Parse the abstract-declarator, if present.
1340 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1341 ParseDeclarator(DeclaratorInfo);
1342
Chris Lattner29375652006-12-04 18:06:35 +00001343 SourceLocation RAngleBracketLoc = Tok.getLocation();
1344
Alp Toker383d2c42014-01-01 03:08:43 +00001345 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001346 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001347
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001348 SourceLocation LParenLoc, RParenLoc;
1349 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001350
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001351 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001352 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001353
John McCalldadc5752010-08-24 06:29:42 +00001354 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001355
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001356 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001357 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001358
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001359 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001360 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001361 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001362 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001363 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001364 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001365
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001366 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001367}
Bill Wendling4073ed52007-02-13 01:51:42 +00001368
Sebastian Redlc4704762008-11-11 11:37:55 +00001369/// ParseCXXTypeid - This handles the C++ typeid expression.
1370///
1371/// postfix-expression: [C++ 5.2p1]
1372/// 'typeid' '(' expression ')'
1373/// 'typeid' '(' type-id ')'
1374///
John McCalldadc5752010-08-24 06:29:42 +00001375ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001376 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1377
1378 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001379 SourceLocation LParenLoc, RParenLoc;
1380 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001381
1382 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001383 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001384 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001385 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001386
John McCalldadc5752010-08-24 06:29:42 +00001387 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001388
Richard Smith4f605af2012-08-18 00:55:03 +00001389 // C++0x [expr.typeid]p3:
1390 // When typeid is applied to an expression other than an lvalue of a
1391 // polymorphic class type [...] The expression is an unevaluated
1392 // operand (Clause 5).
1393 //
1394 // Note that we can't tell whether the expression is an lvalue of a
1395 // polymorphic class type until after we've parsed the expression; we
1396 // speculatively assume the subexpression is unevaluated, and fix it up
1397 // later.
1398 //
1399 // We enter the unevaluated context before trying to determine whether we
1400 // have a type-id, because the tentative parse logic will try to resolve
1401 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001402 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1403 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001404
Sebastian Redlc4704762008-11-11 11:37:55 +00001405 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001406 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001407
1408 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001409 T.consumeClose();
1410 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001411 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001412 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001413
1414 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001415 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001416 } else {
1417 Result = ParseExpression();
1418
1419 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001420 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001421 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001422 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001423 T.consumeClose();
1424 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001425 if (RParenLoc.isInvalid())
1426 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001427
Sebastian Redlc4704762008-11-11 11:37:55 +00001428 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001429 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001430 }
1431 }
1432
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001433 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001434}
1435
Francois Pichet9f4f2072010-09-08 12:20:18 +00001436/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1437///
1438/// '__uuidof' '(' expression ')'
1439/// '__uuidof' '(' type-id ')'
1440///
1441ExprResult Parser::ParseCXXUuidof() {
1442 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1443
1444 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001445 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001446
1447 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001448 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001449 return ExprError();
1450
1451 ExprResult Result;
1452
1453 if (isTypeIdInParens()) {
1454 TypeResult Ty = ParseTypeName();
1455
1456 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001457 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001458
1459 if (Ty.isInvalid())
1460 return ExprError();
1461
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001462 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1463 Ty.get().getAsOpaquePtr(),
1464 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001465 } else {
1466 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1467 Result = ParseExpression();
1468
1469 // Match the ')'.
1470 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001471 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001472 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001473 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001474
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001475 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1476 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001477 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001478 }
1479 }
1480
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001481 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001482}
1483
Douglas Gregore610ada2010-02-24 18:44:31 +00001484/// \brief Parse a C++ pseudo-destructor expression after the base,
1485/// . or -> operator, and nested-name-specifier have already been
1486/// parsed.
1487///
1488/// postfix-expression: [C++ 5.2]
1489/// postfix-expression . pseudo-destructor-name
1490/// postfix-expression -> pseudo-destructor-name
1491///
1492/// pseudo-destructor-name:
1493/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1494/// ::[opt] nested-name-specifier template simple-template-id ::
1495/// ~type-name
1496/// ::[opt] nested-name-specifier[opt] ~type-name
1497///
John McCalldadc5752010-08-24 06:29:42 +00001498ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001499Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001500 tok::TokenKind OpKind,
1501 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001502 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001503 // We're parsing either a pseudo-destructor-name or a dependent
1504 // member access that has the same form as a
1505 // pseudo-destructor-name. We parse both in the same way and let
1506 // the action model sort them out.
1507 //
1508 // Note that the ::[opt] nested-name-specifier[opt] has already
1509 // been parsed, and if there was a simple-template-id, it has
1510 // been coalesced into a template-id annotation token.
1511 UnqualifiedId FirstTypeName;
1512 SourceLocation CCLoc;
1513 if (Tok.is(tok::identifier)) {
1514 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1515 ConsumeToken();
1516 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1517 CCLoc = ConsumeToken();
1518 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001519 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1520 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001521 FirstTypeName.setTemplateId(
1522 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1523 ConsumeToken();
1524 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1525 CCLoc = ConsumeToken();
1526 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001527 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001528 }
1529
1530 // Parse the tilde.
1531 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1532 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001533
1534 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1535 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001536 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001537 if (DS.getTypeSpecType() == TST_error)
1538 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001539 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1540 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001541 }
1542
Douglas Gregore610ada2010-02-24 18:44:31 +00001543 if (!Tok.is(tok::identifier)) {
1544 Diag(Tok, diag::err_destructor_tilde_identifier);
1545 return ExprError();
1546 }
1547
1548 // Parse the second type.
1549 UnqualifiedId SecondTypeName;
1550 IdentifierInfo *Name = Tok.getIdentifierInfo();
1551 SourceLocation NameLoc = ConsumeToken();
1552 SecondTypeName.setIdentifier(Name, NameLoc);
1553
1554 // If there is a '<', the second type name is a template-id. Parse
1555 // it as such.
1556 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001557 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1558 Name, NameLoc,
1559 false, ObjectType, SecondTypeName,
1560 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001561 return ExprError();
1562
David Majnemerced8bdf2015-02-25 17:36:15 +00001563 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1564 SS, FirstTypeName, CCLoc, TildeLoc,
1565 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001566}
1567
Bill Wendling4073ed52007-02-13 01:51:42 +00001568/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1569///
1570/// boolean-literal: [C++ 2.13.5]
1571/// 'true'
1572/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001573ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001574 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001575 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001576}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001577
1578/// ParseThrowExpression - This handles the C++ throw expression.
1579///
1580/// throw-expression: [C++ 15]
1581/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001582ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001583 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001584 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001585
Chris Lattner65dd8432008-04-06 06:02:23 +00001586 // If the current token isn't the start of an assignment-expression,
1587 // then the expression is not present. This handles things like:
1588 // "C ? throw : (void)42", which is crazy but legal.
1589 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1590 case tok::semi:
1591 case tok::r_paren:
1592 case tok::r_square:
1593 case tok::r_brace:
1594 case tok::colon:
1595 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001596 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001597
Chris Lattner65dd8432008-04-06 06:02:23 +00001598 default:
John McCalldadc5752010-08-24 06:29:42 +00001599 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001600 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001601 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001602 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001603}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001604
Richard Smith0e304ea2015-10-22 04:46:14 +00001605/// \brief Parse the C++ Coroutines co_yield expression.
1606///
1607/// co_yield-expression:
1608/// 'co_yield' assignment-expression[opt]
1609ExprResult Parser::ParseCoyieldExpression() {
1610 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1611
1612 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001613 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1614 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001615 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001616 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001617 return Expr;
1618}
1619
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001620/// ParseCXXThis - This handles the C++ 'this' pointer.
1621///
1622/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1623/// a non-lvalue expression whose value is the address of the object for which
1624/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001625ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001626 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1627 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001628 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001629}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001630
1631/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1632/// Can be interpreted either as function-style casting ("int(x)")
1633/// or class type construction ("ClassType(x,y,z)")
1634/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001635/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001636///
1637/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001638/// simple-type-specifier '(' expression-list[opt] ')'
1639/// [C++0x] simple-type-specifier braced-init-list
1640/// typename-specifier '(' expression-list[opt] ')'
1641/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001642///
Richard Smith600b5262017-01-26 20:40:47 +00001643/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001644ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001645Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Richard Smith600b5262017-01-26 20:40:47 +00001646 Declarator DeclaratorInfo(DS, Declarator::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001647 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001648
Sebastian Redl3da34892011-06-05 12:23:16 +00001649 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001650 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001651 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001652
Sebastian Redl3da34892011-06-05 12:23:16 +00001653 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001654 ExprResult Init = ParseBraceInitializer();
1655 if (Init.isInvalid())
1656 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001657 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001658 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1659 MultiExprArg(&InitList, 1),
1660 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001661 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001662 BalancedDelimiterTracker T(*this, tok::l_paren);
1663 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001664
Benjamin Kramerf0623432012-08-23 22:51:59 +00001665 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001666 CommaLocsTy CommaLocs;
1667
1668 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001669 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1670 Actions.CodeCompleteConstructor(getCurScope(),
1671 TypeRep.get()->getCanonicalTypeInternal(),
1672 DS.getLocEnd(), Exprs);
1673 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001674 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001675 return ExprError();
1676 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001677 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001678
1679 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001680 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001681
1682 // TypeRep could be null, if it references an invalid typedef.
1683 if (!TypeRep)
1684 return ExprError();
1685
1686 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1687 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001688 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001689 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001690 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001691 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001692}
1693
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001694/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001695///
1696/// condition:
1697/// expression
1698/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001699/// [C++11] type-specifier-seq declarator '=' initializer-clause
1700/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001701/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1702/// '=' assignment-expression
1703///
Richard Smithc7a05a92016-06-29 21:17:59 +00001704/// In C++1z, a condition may in some contexts be preceded by an
1705/// optional init-statement. This function will parse that too.
1706///
1707/// \param InitStmt If non-null, an init-statement is permitted, and if present
1708/// will be parsed and stored here.
1709///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001710/// \param Loc The location of the start of the statement that requires this
1711/// condition, e.g., the "for" in a for loop.
1712///
Richard Smith03a4aa32016-06-23 19:02:52 +00001713/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001714Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1715 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001716 Sema::ConditionKind CK) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001717 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001718 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001719 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001720 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001721 }
1722
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001723 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001724 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001725
Richard Smithc7a05a92016-06-29 21:17:59 +00001726 // Determine what kind of thing we have.
1727 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1728 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001729 ProhibitAttributes(attrs);
1730
Douglas Gregore60e41a2010-05-06 17:25:47 +00001731 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001732 ExprResult Expr = ParseExpression(); // expression
1733 if (Expr.isInvalid())
1734 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001735
Richard Smithc7a05a92016-06-29 21:17:59 +00001736 if (InitStmt && Tok.is(tok::semi)) {
1737 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1738 ConsumeToken();
1739 return ParseCXXCondition(nullptr, Loc, CK);
1740 }
1741
Richard Smith03a4aa32016-06-23 19:02:52 +00001742 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001743 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001744
Richard Smithc7a05a92016-06-29 21:17:59 +00001745 case ConditionOrInitStatement::InitStmtDecl: {
Richard Smithfccb5122016-10-18 20:27:16 +00001746 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
1747 ? diag::warn_cxx14_compat_init_statement
1748 : diag::ext_init_statement)
1749 << (CK == Sema::ConditionKind::Switch);
Richard Smithc7a05a92016-06-29 21:17:59 +00001750 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1751 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1752 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1753 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1754 return ParseCXXCondition(nullptr, Loc, CK);
1755 }
1756
1757 case ConditionOrInitStatement::ConditionDecl:
1758 case ConditionOrInitStatement::Error:
1759 break;
1760 }
1761
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001762 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001763 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001764 DS.takeAttributesFrom(attrs);
Meador Ingef0af05c2015-06-25 22:06:40 +00001765 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001766
1767 // declarator
1768 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1769 ParseDeclarator(DeclaratorInfo);
1770
1771 // simple-asm-expr[opt]
1772 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001773 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001774 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001775 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001776 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001777 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001778 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001779 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001780 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001781 }
1782
1783 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001784 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001785
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001786 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001787 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001788 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001789 if (Dcl.isInvalid())
1790 return Sema::ConditionError();
1791 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001792
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001793 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001794 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001795 bool CopyInitialization = isTokenEqualOrEqualTypo();
1796 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001797 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001798
1799 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001800 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001801 Diag(Tok.getLocation(),
1802 diag::warn_cxx98_compat_generalized_initializer_lists);
1803 InitExpr = ParseBraceInitializer();
1804 } else if (CopyInitialization) {
1805 InitExpr = ParseAssignmentExpression();
1806 } else if (Tok.is(tok::l_paren)) {
1807 // This was probably an attempt to initialize the variable.
1808 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001809 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001810 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001811 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001812 diag::err_expected_init_in_condition_lparen)
1813 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001814 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001815 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001816 }
Richard Smith2a15b742012-02-22 06:49:09 +00001817
1818 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001819 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001820 else
1821 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001822
Richard Smithb2bc2e62011-02-21 20:05:19 +00001823 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001824 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001825}
1826
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001827/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1828/// This should only be called when the current token is known to be part of
1829/// simple-type-specifier.
1830///
1831/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001832/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001833/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1834/// char
1835/// wchar_t
1836/// bool
1837/// short
1838/// int
1839/// long
1840/// signed
1841/// unsigned
1842/// float
1843/// double
1844/// void
1845/// [GNU] typeof-specifier
1846/// [C++0x] auto [TODO]
1847///
1848/// type-name:
1849/// class-name
1850/// enum-name
1851/// typedef-name
1852///
1853void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1854 DS.SetRangeStart(Tok.getLocation());
1855 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001856 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001857 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001858 const clang::PrintingPolicy &Policy =
1859 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001860
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001861 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001862 case tok::identifier: // foo::bar
1863 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001864 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001865 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001866 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001867
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001868 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001869 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001870 if (getTypeAnnotation(Tok))
1871 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001872 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001873 else
1874 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001875
1876 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1877 ConsumeToken();
1878
Craig Topper25122412015-11-15 03:32:11 +00001879 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001880 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001881 }
Mike Stump11289f42009-09-09 15:08:12 +00001882
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001883 // builtin types
1884 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001885 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001886 break;
1887 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001888 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001889 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001890 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001891 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001892 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001893 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001894 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001895 break;
1896 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001897 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001898 break;
1899 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001900 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001901 break;
1902 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001903 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001904 break;
1905 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001906 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001907 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001908 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001909 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001910 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001911 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001912 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001913 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001914 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001915 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001916 break;
1917 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001918 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001919 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001920 case tok::kw___float128:
1921 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1922 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001923 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001924 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001925 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001926 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001927 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001928 break;
1929 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001930 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001931 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001932 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001933 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001934 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001935 case tok::annot_decltype:
1936 case tok::kw_decltype:
1937 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00001938 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001939
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001940 // GNU typeof support.
1941 case tok::kw_typeof:
1942 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00001943 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001944 return;
1945 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001946 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001947 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1948 else
1949 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001950 ConsumeToken();
Craig Topper25122412015-11-15 03:32:11 +00001951 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001952}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001953
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001954/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1955/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1956/// e.g., "const short int". Note that the DeclSpec is *not* finished
1957/// by parsing the type-specifier-seq, because these sequences are
1958/// typically followed by some form of declarator. Returns true and
1959/// emits diagnostics if this is not a type-specifier-seq, false
1960/// otherwise.
1961///
1962/// type-specifier-seq: [C++ 8.1]
1963/// type-specifier type-specifier-seq[opt]
1964///
1965bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001966 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00001967 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001968 return false;
1969}
1970
Douglas Gregor7861a802009-11-03 01:35:08 +00001971/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1972/// some form.
1973///
1974/// This routine is invoked when a '<' is encountered after an identifier or
1975/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1976/// whether the unqualified-id is actually a template-id. This routine will
1977/// then parse the template arguments and form the appropriate template-id to
1978/// return to the caller.
1979///
1980/// \param SS the nested-name-specifier that precedes this template-id, if
1981/// we're actually parsing a qualified-id.
1982///
1983/// \param Name for constructor and destructor names, this is the actual
1984/// identifier that may be a template-name.
1985///
1986/// \param NameLoc the location of the class-name in a constructor or
1987/// destructor.
1988///
1989/// \param EnteringContext whether we're entering the scope of the
1990/// nested-name-specifier.
1991///
Douglas Gregor127ea592009-11-03 21:24:04 +00001992/// \param ObjectType if this unqualified-id occurs within a member access
1993/// expression, the type of the base object whose member is being accessed.
1994///
Douglas Gregor7861a802009-11-03 01:35:08 +00001995/// \param Id as input, describes the template-name or operator-function-id
1996/// that precedes the '<'. If template arguments were parsed successfully,
1997/// will be updated with the template-id.
1998///
Douglas Gregore610ada2010-02-24 18:44:31 +00001999/// \param AssumeTemplateId When true, this routine will assume that the name
2000/// refers to a template without performing name lookup to verify.
2001///
Douglas Gregor7861a802009-11-03 01:35:08 +00002002/// \returns true if a parse error occurred, false otherwise.
2003bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002004 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002005 IdentifierInfo *Name,
2006 SourceLocation NameLoc,
2007 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002008 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002009 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002010 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002011 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2012 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00002013
2014 TemplateTy Template;
2015 TemplateNameKind TNK = TNK_Non_template;
2016 switch (Id.getKind()) {
2017 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00002018 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00002019 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002020 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002021 // We defer the injected-class-name checks until we've found whether
2022 // this template-id is used to form a nested-name-specifier or not.
2023 TNK = Actions.ActOnDependentTemplateName(
2024 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2025 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002026 if (TNK == TNK_Non_template)
2027 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002028 } else {
2029 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002030 TNK = Actions.isTemplateName(getCurScope(), SS,
2031 TemplateKWLoc.isValid(), Id,
2032 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002033 MemberOfUnknownSpecialization);
2034
2035 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2036 ObjectType && IsTemplateArgumentList()) {
2037 // We have something like t->getAs<T>(), where getAs is a
2038 // member of an unknown specialization. However, this will only
2039 // parse correctly as a template, so suggest the keyword 'template'
2040 // before 'getAs' and treat this as a dependent template name.
2041 std::string Name;
2042 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2043 Name = Id.Identifier->getName();
2044 else {
2045 Name = "operator ";
2046 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2047 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2048 else
2049 Name += Id.Identifier->getName();
2050 }
2051 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2052 << Name
2053 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002054 TNK = Actions.ActOnDependentTemplateName(
2055 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2056 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002057 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00002058 return true;
2059 }
2060 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002061 break;
2062
Douglas Gregor3cf81312009-11-03 23:16:33 +00002063 case UnqualifiedId::IK_ConstructorName: {
2064 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002065 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002066 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002067 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2068 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002069 EnteringContext, Template,
2070 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002071 break;
2072 }
2073
Douglas Gregor3cf81312009-11-03 23:16:33 +00002074 case UnqualifiedId::IK_DestructorName: {
2075 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002076 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002077 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002078 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002079 TNK = Actions.ActOnDependentTemplateName(
2080 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2081 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002082 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002083 return true;
2084 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002085 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2086 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002087 EnteringContext, Template,
2088 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002089
John McCallba7bf592010-08-24 05:47:05 +00002090 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002091 Diag(NameLoc, diag::err_destructor_template_id)
2092 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002093 return true;
2094 }
2095 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002096 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002097 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002098
2099 default:
2100 return false;
2101 }
2102
2103 if (TNK == TNK_Non_template)
2104 return false;
2105
2106 // Parse the enclosed template argument list.
2107 SourceLocation LAngleLoc, RAngleLoc;
2108 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002109 if (Tok.is(tok::less) &&
2110 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002111 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002112 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002113 RAngleLoc))
2114 return true;
2115
2116 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002117 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2118 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002119 // Form a parsed representation of the template-id to be stored in the
2120 // UnqualifiedId.
2121 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002122 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002123
Richard Smith72bfbd82013-12-04 00:28:23 +00002124 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002125 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2126 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002127 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002128 TemplateId->TemplateNameLoc = Id.StartLocation;
2129 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002130 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002131 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2132 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002133 }
2134
Douglas Gregore7c20652011-03-02 00:47:37 +00002135 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002136 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002137 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002138 TemplateId->Kind = TNK;
2139 TemplateId->LAngleLoc = LAngleLoc;
2140 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002141 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002142 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002143 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002144 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002145
2146 Id.setTemplateId(TemplateId);
2147 return false;
2148 }
2149
2150 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002151 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002152
Douglas Gregor7861a802009-11-03 01:35:08 +00002153 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002154 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002155 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002156 Template, Name, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002157 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2158 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002159 if (Type.isInvalid())
2160 return true;
2161
2162 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2163 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2164 else
2165 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2166
2167 return false;
2168}
2169
Douglas Gregor71395fa2009-11-04 00:56:37 +00002170/// \brief Parse an operator-function-id or conversion-function-id as part
2171/// of a C++ unqualified-id.
2172///
2173/// This routine is responsible only for parsing the operator-function-id or
2174/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002175///
2176/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002177/// operator-function-id: [C++ 13.5]
2178/// 'operator' operator
2179///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002180/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002181/// new delete new[] delete[]
2182/// + - * / % ^ & | ~
2183/// ! = < > += -= *= /= %=
2184/// ^= &= |= << >> >>= <<= == !=
2185/// <= >= && || ++ -- , ->* ->
2186/// () []
2187///
2188/// conversion-function-id: [C++ 12.3.2]
2189/// operator conversion-type-id
2190///
2191/// conversion-type-id:
2192/// type-specifier-seq conversion-declarator[opt]
2193///
2194/// conversion-declarator:
2195/// ptr-operator conversion-declarator[opt]
2196/// \endcode
2197///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002198/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002199/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2200///
2201/// \param EnteringContext whether we are entering the scope of the
2202/// nested-name-specifier.
2203///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002204/// \param ObjectType if this unqualified-id occurs within a member access
2205/// expression, the type of the base object whose member is being accessed.
2206///
2207/// \param Result on a successful parse, contains the parsed unqualified-id.
2208///
2209/// \returns true if parsing fails, false otherwise.
2210bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002211 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002212 UnqualifiedId &Result) {
2213 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2214
2215 // Consume the 'operator' keyword.
2216 SourceLocation KeywordLoc = ConsumeToken();
2217
2218 // Determine what kind of operator name we have.
2219 unsigned SymbolIdx = 0;
2220 SourceLocation SymbolLocations[3];
2221 OverloadedOperatorKind Op = OO_None;
2222 switch (Tok.getKind()) {
2223 case tok::kw_new:
2224 case tok::kw_delete: {
2225 bool isNew = Tok.getKind() == tok::kw_new;
2226 // Consume the 'new' or 'delete'.
2227 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002228 // Check for array new/delete.
2229 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002230 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002231 // Consume the '[' and ']'.
2232 BalancedDelimiterTracker T(*this, tok::l_square);
2233 T.consumeOpen();
2234 T.consumeClose();
2235 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002236 return true;
2237
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002238 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2239 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002240 Op = isNew? OO_Array_New : OO_Array_Delete;
2241 } else {
2242 Op = isNew? OO_New : OO_Delete;
2243 }
2244 break;
2245 }
2246
2247#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2248 case tok::Token: \
2249 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2250 Op = OO_##Name; \
2251 break;
2252#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2253#include "clang/Basic/OperatorKinds.def"
2254
2255 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002256 // Consume the '(' and ')'.
2257 BalancedDelimiterTracker T(*this, tok::l_paren);
2258 T.consumeOpen();
2259 T.consumeClose();
2260 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002261 return true;
2262
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002263 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2264 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002265 Op = OO_Call;
2266 break;
2267 }
2268
2269 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002270 // Consume the '[' and ']'.
2271 BalancedDelimiterTracker T(*this, tok::l_square);
2272 T.consumeOpen();
2273 T.consumeClose();
2274 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002275 return true;
2276
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002277 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2278 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002279 Op = OO_Subscript;
2280 break;
2281 }
2282
2283 case tok::code_completion: {
2284 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002285 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002286 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002287 // Don't try to parse any further.
2288 return true;
2289 }
2290
2291 default:
2292 break;
2293 }
2294
2295 if (Op != OO_None) {
2296 // We have parsed an operator-function-id.
2297 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2298 return false;
2299 }
Alexis Hunt34458502009-11-28 04:44:28 +00002300
2301 // Parse a literal-operator-id.
2302 //
Richard Smith6f212062012-10-20 08:41:10 +00002303 // literal-operator-id: C++11 [over.literal]
2304 // operator string-literal identifier
2305 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002306
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002307 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002308 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002309
Richard Smith7d182a72012-03-08 23:06:02 +00002310 SourceLocation DiagLoc;
2311 unsigned DiagId = 0;
2312
2313 // We're past translation phase 6, so perform string literal concatenation
2314 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002315 SmallVector<Token, 4> Toks;
2316 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002317 while (isTokenStringLiteral()) {
2318 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002319 // C++11 [over.literal]p1:
2320 // The string-literal or user-defined-string-literal in a
2321 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002322 DiagLoc = Tok.getLocation();
2323 DiagId = diag::err_literal_operator_string_prefix;
2324 }
2325 Toks.push_back(Tok);
2326 TokLocs.push_back(ConsumeStringToken());
2327 }
2328
Craig Topper9d5583e2014-06-26 04:58:39 +00002329 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002330 if (Literal.hadError)
2331 return true;
2332
2333 // Grab the literal operator's suffix, which will be either the next token
2334 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002335 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002336 SourceLocation SuffixLoc;
2337 if (!Literal.getUDSuffix().empty()) {
2338 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2339 SuffixLoc =
2340 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2341 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002342 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002343 } else if (Tok.is(tok::identifier)) {
2344 II = Tok.getIdentifierInfo();
2345 SuffixLoc = ConsumeToken();
2346 TokLocs.push_back(SuffixLoc);
2347 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002348 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002349 return true;
2350 }
2351
Richard Smith7d182a72012-03-08 23:06:02 +00002352 // The string literal must be empty.
2353 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002354 // C++11 [over.literal]p1:
2355 // The string-literal or user-defined-string-literal in a
2356 // literal-operator-id shall [...] contain no characters
2357 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002358 DiagLoc = TokLocs.front();
2359 DiagId = diag::err_literal_operator_string_not_empty;
2360 }
2361
2362 if (DiagId) {
2363 // This isn't a valid literal-operator-id, but we think we know
2364 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002365 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002366 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002367 Str += II->getName();
2368 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2369 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2370 }
2371
2372 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002373
2374 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002375 }
Richard Smithd091dc12013-12-05 00:58:33 +00002376
Douglas Gregor71395fa2009-11-04 00:56:37 +00002377 // Parse a conversion-function-id.
2378 //
2379 // conversion-function-id: [C++ 12.3.2]
2380 // operator conversion-type-id
2381 //
2382 // conversion-type-id:
2383 // type-specifier-seq conversion-declarator[opt]
2384 //
2385 // conversion-declarator:
2386 // ptr-operator conversion-declarator[opt]
2387
2388 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002389 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002390 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002391 return true;
2392
2393 // Parse the conversion-declarator, which is merely a sequence of
2394 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002395 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002396 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2397
Douglas Gregor71395fa2009-11-04 00:56:37 +00002398 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002399 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002400 if (Ty.isInvalid())
2401 return true;
2402
2403 // Note that this is a conversion-function-id.
2404 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2405 D.getSourceRange().getEnd());
2406 return false;
2407}
2408
2409/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2410/// name of an entity.
2411///
2412/// \code
2413/// unqualified-id: [C++ expr.prim.general]
2414/// identifier
2415/// operator-function-id
2416/// conversion-function-id
2417/// [C++0x] literal-operator-id [TODO]
2418/// ~ class-name
2419/// template-id
2420///
2421/// \endcode
2422///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002423/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002424/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2425///
2426/// \param EnteringContext whether we are entering the scope of the
2427/// nested-name-specifier.
2428///
Douglas Gregor7861a802009-11-03 01:35:08 +00002429/// \param AllowDestructorName whether we allow parsing of a destructor name.
2430///
2431/// \param AllowConstructorName whether we allow parsing a constructor name.
2432///
Richard Smith35845152017-02-07 01:37:30 +00002433/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2434///
Douglas Gregor127ea592009-11-03 21:24:04 +00002435/// \param ObjectType if this unqualified-id occurs within a member access
2436/// expression, the type of the base object whose member is being accessed.
2437///
Douglas Gregor7861a802009-11-03 01:35:08 +00002438/// \param Result on a successful parse, contains the parsed unqualified-id.
2439///
2440/// \returns true if parsing fails, false otherwise.
2441bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2442 bool AllowDestructorName,
2443 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002444 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002445 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002446 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002447 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002448
2449 // Handle 'A::template B'. This is for template-ids which have not
2450 // already been annotated by ParseOptionalCXXScopeSpecifier().
2451 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002452 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002453 (ObjectType || SS.isSet())) {
2454 TemplateSpecified = true;
2455 TemplateKWLoc = ConsumeToken();
2456 }
2457
Douglas Gregor7861a802009-11-03 01:35:08 +00002458 // unqualified-id:
2459 // identifier
2460 // template-id (when it hasn't already been annotated)
2461 if (Tok.is(tok::identifier)) {
2462 // Consume the identifier.
2463 IdentifierInfo *Id = Tok.getIdentifierInfo();
2464 SourceLocation IdLoc = ConsumeToken();
2465
David Blaikiebbafb8a2012-03-11 07:00:24 +00002466 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002467 // If we're not in C++, only identifiers matter. Record the
2468 // identifier and return.
2469 Result.setIdentifier(Id, IdLoc);
2470 return false;
2471 }
2472
Richard Smith35845152017-02-07 01:37:30 +00002473 ParsedTemplateTy TemplateName;
Douglas Gregor7861a802009-11-03 01:35:08 +00002474 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002475 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002476 // We have parsed a constructor name.
David Blaikieefdccaa2016-01-15 23:43:34 +00002477 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2478 false, nullptr,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002479 /*IsCtorOrDtorName=*/true,
2480 /*NonTrivialTypeSourceInfo=*/true);
2481 Result.setConstructorName(Ty, IdLoc, IdLoc);
Richard Smith35845152017-02-07 01:37:30 +00002482 } else if (getLangOpts().CPlusPlus1z &&
2483 AllowDeductionGuide && SS.isEmpty() &&
2484 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2485 &TemplateName)) {
2486 // We have parsed a template-name naming a deduction guide.
2487 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002488 } else {
2489 // We have parsed an identifier.
2490 Result.setIdentifier(Id, IdLoc);
2491 }
2492
2493 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002494 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002495 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2496 EnteringContext, ObjectType,
2497 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002498
2499 return false;
2500 }
2501
2502 // unqualified-id:
2503 // template-id (already parsed and annotated)
2504 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002505 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002506
2507 // If the template-name names the current class, then this is a constructor
2508 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002509 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002510 if (SS.isSet()) {
2511 // C++ [class.qual]p2 specifies that a qualified template-name
2512 // is taken as the constructor name where a constructor can be
2513 // declared. Thus, the template arguments are extraneous, so
2514 // complain about them and remove them entirely.
2515 Diag(TemplateId->TemplateNameLoc,
2516 diag::err_out_of_line_constructor_template_id)
2517 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002518 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002519 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
David Blaikieefdccaa2016-01-15 23:43:34 +00002520 ParsedType Ty =
2521 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2522 getCurScope(), &SS, false, false, nullptr,
2523 /*IsCtorOrDtorName=*/true,
2524 /*NontrivialTypeSourceInfo=*/true);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002525 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002526 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002527 ConsumeToken();
2528 return false;
2529 }
2530
2531 Result.setConstructorTemplateId(TemplateId);
2532 ConsumeToken();
2533 return false;
2534 }
2535
Douglas Gregor7861a802009-11-03 01:35:08 +00002536 // We have already parsed a template-id; consume the annotation token as
2537 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002538 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002539 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002540 ConsumeToken();
2541 return false;
2542 }
2543
2544 // unqualified-id:
2545 // operator-function-id
2546 // conversion-function-id
2547 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002548 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002549 return true;
2550
Alexis Hunted0530f2009-11-28 08:58:14 +00002551 // If we have an operator-function-id or a literal-operator-id and the next
2552 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002553 //
2554 // template-id:
2555 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002556 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2557 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002558 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002559 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002560 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002561 EnteringContext, ObjectType,
2562 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002563
Douglas Gregor7861a802009-11-03 01:35:08 +00002564 return false;
2565 }
2566
David Blaikiebbafb8a2012-03-11 07:00:24 +00002567 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002568 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002569 // C++ [expr.unary.op]p10:
2570 // There is an ambiguity in the unary-expression ~X(), where X is a
2571 // class-name. The ambiguity is resolved in favor of treating ~ as a
2572 // unary complement rather than treating ~X as referring to a destructor.
2573
2574 // Parse the '~'.
2575 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002576
2577 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2578 DeclSpec DS(AttrFactory);
2579 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2580 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2581 Result.setDestructorName(TildeLoc, Type, EndLoc);
2582 return false;
2583 }
2584 return true;
2585 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002586
2587 // Parse the class-name.
2588 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002589 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002590 return true;
2591 }
2592
Richard Smithefa6f732014-09-06 02:06:12 +00002593 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002594 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002595 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002596 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2597 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2598 // it will confuse this recovery logic.
2599 ColonProtectionRAIIObject ColonRAII(*this, false);
2600
Richard Smithefa6f732014-09-06 02:06:12 +00002601 if (SS.isSet()) {
2602 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2603 SS.clear();
2604 }
2605 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2606 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002607 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002608 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002609 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002610 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002611 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2612 return true;
2613 }
2614
2615 // Recover as if the tilde had been written before the identifier.
2616 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2617 << FixItHint::CreateRemoval(TildeLoc)
2618 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002619
2620 // Temporarily enter the scope for the rest of this function.
2621 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2622 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002623 }
2624
Douglas Gregor7861a802009-11-03 01:35:08 +00002625 // Parse the class-name (or template-name in a simple-template-id).
2626 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2627 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002628
Douglas Gregorb22ee882010-05-05 05:58:24 +00002629 if (TemplateSpecified || Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002630 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002631 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2632 ClassName, ClassNameLoc,
2633 EnteringContext, ObjectType,
2634 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002635 }
Richard Smithefa6f732014-09-06 02:06:12 +00002636
Douglas Gregor7861a802009-11-03 01:35:08 +00002637 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002638 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2639 ClassNameLoc, getCurScope(),
2640 SS, ObjectType,
2641 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002642 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002643 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002644
Douglas Gregor7861a802009-11-03 01:35:08 +00002645 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002646 return false;
2647 }
2648
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002649 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002650 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002651 return true;
2652}
2653
Sebastian Redlbd150f42008-11-21 19:14:01 +00002654/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2655/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002656///
Chris Lattner109faf22009-01-04 21:25:24 +00002657/// This method is called to parse the new expression after the optional :: has
2658/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2659/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002660///
2661/// new-expression:
2662/// '::'[opt] 'new' new-placement[opt] new-type-id
2663/// new-initializer[opt]
2664/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2665/// new-initializer[opt]
2666///
2667/// new-placement:
2668/// '(' expression-list ')'
2669///
Sebastian Redl351bb782008-12-02 14:43:59 +00002670/// new-type-id:
2671/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002672/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002673///
2674/// new-declarator:
2675/// ptr-operator new-declarator[opt]
2676/// direct-new-declarator
2677///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002678/// new-initializer:
2679/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002680/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002681///
John McCalldadc5752010-08-24 06:29:42 +00002682ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002683Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2684 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2685 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002686
2687 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2688 // second form of new-expression. It can't be a new-type-id.
2689
Benjamin Kramerf0623432012-08-23 22:51:59 +00002690 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002691 SourceLocation PlacementLParen, PlacementRParen;
2692
Douglas Gregorf2753b32010-07-13 15:54:32 +00002693 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002694 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002695 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002696 if (Tok.is(tok::l_paren)) {
2697 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002698 BalancedDelimiterTracker T(*this, tok::l_paren);
2699 T.consumeOpen();
2700 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002701 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002702 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002703 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002704 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002705
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002706 T.consumeClose();
2707 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002708 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002709 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002710 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002711 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002712
Sebastian Redl351bb782008-12-02 14:43:59 +00002713 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002714 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002715 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002716 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002717 } else {
2718 // We still need the type.
2719 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002720 BalancedDelimiterTracker T(*this, tok::l_paren);
2721 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002722 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002723 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002724 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002725 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002726 T.consumeClose();
2727 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002728 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002729 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002730 if (ParseCXXTypeSpecifierSeq(DS))
2731 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002732 else {
2733 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002734 ParseDeclaratorInternal(DeclaratorInfo,
2735 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002736 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002737 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002738 }
2739 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002740 // A new-type-id is a simplified type-id, where essentially the
2741 // direct-declarator is replaced by a direct-new-declarator.
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 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002751 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002752 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002753 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002754 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002755
Sebastian Redl6047f072012-02-16 12:22:20 +00002756 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002757
2758 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002759 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002760 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002761 BalancedDelimiterTracker T(*this, tok::l_paren);
2762 T.consumeOpen();
2763 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002764 if (Tok.isNot(tok::r_paren)) {
2765 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002766 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2767 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2768 DeclaratorInfo).get();
2769 Actions.CodeCompleteConstructor(getCurScope(),
2770 TypeRep.get()->getCanonicalTypeInternal(),
2771 DeclaratorInfo.getLocEnd(),
2772 ConstructorArgs);
2773 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002774 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002775 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002776 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002777 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002778 T.consumeClose();
2779 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002780 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002781 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002782 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002783 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002784 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2785 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002786 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002787 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002788 Diag(Tok.getLocation(),
2789 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002790 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002791 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002792 if (Initializer.isInvalid())
2793 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002794
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002795 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002796 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002797 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002798}
2799
Sebastian Redlbd150f42008-11-21 19:14:01 +00002800/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2801/// passed to ParseDeclaratorInternal.
2802///
2803/// direct-new-declarator:
2804/// '[' expression ']'
2805/// direct-new-declarator '[' constant-expression ']'
2806///
Chris Lattner109faf22009-01-04 21:25:24 +00002807void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002808 // Parse the array dimensions.
2809 bool first = true;
2810 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002811 // An array-size expression can't start with a lambda.
2812 if (CheckProhibitedCXX11Attribute())
2813 continue;
2814
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002815 BalancedDelimiterTracker T(*this, tok::l_square);
2816 T.consumeOpen();
2817
John McCalldadc5752010-08-24 06:29:42 +00002818 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002819 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002820 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002821 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002822 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002823 return;
2824 }
2825 first = false;
2826
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002827 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002828
Bill Wendling44426052012-12-20 19:22:21 +00002829 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002830 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002831 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002832
John McCall084e83d2011-03-24 11:26:52 +00002833 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002834 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002835 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002836 T.getOpenLocation(),
2837 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002838 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002839
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002840 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002841 return;
2842 }
2843}
2844
2845/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2846/// This ambiguity appears in the syntax of the C++ new operator.
2847///
2848/// new-expression:
2849/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2850/// new-initializer[opt]
2851///
2852/// new-placement:
2853/// '(' expression-list ')'
2854///
John McCall37ad5512010-08-23 06:44:23 +00002855bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002856 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002857 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002858 // The '(' was already consumed.
2859 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002860 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002861 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002862 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002863 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002864 }
2865
2866 // It's not a type, it has to be an expression list.
2867 // Discard the comma locations - ActOnCXXNew has enough parameters.
2868 CommaLocsTy CommaLocs;
2869 return ParseExpressionList(PlacementArgs, CommaLocs);
2870}
2871
2872/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2873/// to free memory allocated by new.
2874///
Chris Lattner109faf22009-01-04 21:25:24 +00002875/// This method is called to parse the 'delete' expression after the optional
2876/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2877/// and "Start" is its location. Otherwise, "Start" is the location of the
2878/// 'delete' token.
2879///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002880/// delete-expression:
2881/// '::'[opt] 'delete' cast-expression
2882/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002883ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002884Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2885 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2886 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002887
2888 // Array delete?
2889 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002890 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002891 // C++11 [expr.delete]p1:
2892 // Whenever the delete keyword is followed by empty square brackets, it
2893 // shall be interpreted as [array delete].
2894 // [Footnote: A lambda expression with a lambda-introducer that consists
2895 // of empty square brackets can follow the delete keyword if
2896 // the lambda expression is enclosed in parentheses.]
2897 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2898 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002899 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002900 BalancedDelimiterTracker T(*this, tok::l_square);
2901
2902 T.consumeOpen();
2903 T.consumeClose();
2904 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002905 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002906 }
2907
John McCalldadc5752010-08-24 06:29:42 +00002908 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002909 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002910 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002911
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002912 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002913}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002914
Douglas Gregor29c42f22012-02-24 07:38:34 +00002915static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2916 switch (kind) {
2917 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002918#define TYPE_TRAIT_1(Spelling, Name, Key) \
2919case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002920#define TYPE_TRAIT_2(Spelling, Name, Key) \
2921case tok::kw_ ## Spelling: return BTT_ ## Name;
2922#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002923#define TYPE_TRAIT_N(Spelling, Name, Key) \
2924 case tok::kw_ ## Spelling: return TT_ ## Name;
2925#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002926 }
2927}
2928
John Wiegley6242b6a2011-04-28 00:16:57 +00002929static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2930 switch(kind) {
2931 default: llvm_unreachable("Not a known binary type trait");
2932 case tok::kw___array_rank: return ATT_ArrayRank;
2933 case tok::kw___array_extent: return ATT_ArrayExtent;
2934 }
2935}
2936
John Wiegleyf9f65842011-04-25 06:54:41 +00002937static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2938 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002939 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002940 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2941 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2942 }
2943}
2944
Alp Toker40f9b1c2013-12-12 21:23:03 +00002945static unsigned TypeTraitArity(tok::TokenKind kind) {
2946 switch (kind) {
2947 default: llvm_unreachable("Not a known type trait");
2948#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2949#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002950 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002951}
2952
Douglas Gregor29c42f22012-02-24 07:38:34 +00002953/// \brief Parse the built-in type-trait pseudo-functions that allow
2954/// implementation of the TR1/C++11 type traits templates.
2955///
2956/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002957/// unary-type-trait '(' type-id ')'
2958/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002959/// type-trait '(' type-id-seq ')'
2960///
2961/// type-id-seq:
2962/// type-id ...[opt] type-id-seq[opt]
2963///
2964ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002965 tok::TokenKind Kind = Tok.getKind();
2966 unsigned Arity = TypeTraitArity(Kind);
2967
Douglas Gregor29c42f22012-02-24 07:38:34 +00002968 SourceLocation Loc = ConsumeToken();
2969
2970 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002971 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002972 return ExprError();
2973
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002974 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002975 do {
2976 // Parse the next type.
2977 TypeResult Ty = ParseTypeName();
2978 if (Ty.isInvalid()) {
2979 Parens.skipToEnd();
2980 return ExprError();
2981 }
2982
2983 // Parse the ellipsis, if present.
2984 if (Tok.is(tok::ellipsis)) {
2985 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2986 if (Ty.isInvalid()) {
2987 Parens.skipToEnd();
2988 return ExprError();
2989 }
2990 }
2991
2992 // Add this type to the list of arguments.
2993 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00002994 } while (TryConsumeToken(tok::comma));
2995
Douglas Gregor29c42f22012-02-24 07:38:34 +00002996 if (Parens.consumeClose())
2997 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002998
2999 SourceLocation EndLoc = Parens.getCloseLocation();
3000
3001 if (Arity && Args.size() != Arity) {
3002 Diag(EndLoc, diag::err_type_trait_arity)
3003 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3004 return ExprError();
3005 }
3006
3007 if (!Arity && Args.empty()) {
3008 Diag(EndLoc, diag::err_type_trait_arity)
3009 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3010 return ExprError();
3011 }
3012
Alp Toker88f64e62013-12-13 21:19:30 +00003013 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003014}
3015
John Wiegley6242b6a2011-04-28 00:16:57 +00003016/// ParseArrayTypeTrait - Parse the built-in array type-trait
3017/// pseudo-functions.
3018///
3019/// primary-expression:
3020/// [Embarcadero] '__array_rank' '(' type-id ')'
3021/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3022///
3023ExprResult Parser::ParseArrayTypeTrait() {
3024 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3025 SourceLocation Loc = ConsumeToken();
3026
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003027 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003028 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003029 return ExprError();
3030
3031 TypeResult Ty = ParseTypeName();
3032 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003033 SkipUntil(tok::comma, StopAtSemi);
3034 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003035 return ExprError();
3036 }
3037
3038 switch (ATT) {
3039 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003040 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003041 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003042 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003043 }
3044 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003045 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003046 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003047 return ExprError();
3048 }
3049
3050 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003051 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003052
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003053 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3054 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003055 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003056 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003057 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003058}
3059
John Wiegleyf9f65842011-04-25 06:54:41 +00003060/// ParseExpressionTrait - Parse built-in expression-trait
3061/// pseudo-functions like __is_lvalue_expr( xxx ).
3062///
3063/// primary-expression:
3064/// [Embarcadero] expression-trait '(' expression ')'
3065///
3066ExprResult Parser::ParseExpressionTrait() {
3067 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3068 SourceLocation Loc = ConsumeToken();
3069
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003070 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003071 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003072 return ExprError();
3073
3074 ExprResult Expr = ParseExpression();
3075
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003076 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003077
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003078 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3079 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003080}
3081
3082
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003083/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3084/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3085/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003086ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003087Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003088 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003089 BalancedDelimiterTracker &Tracker,
3090 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003091 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003092 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3093 assert(isTypeIdInParens() && "Not a type-id!");
3094
John McCalldadc5752010-08-24 06:29:42 +00003095 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003096 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003097
3098 // We need to disambiguate a very ugly part of the C++ syntax:
3099 //
3100 // (T())x; - type-id
3101 // (T())*x; - type-id
3102 // (T())/x; - expression
3103 // (T()); - expression
3104 //
3105 // The bad news is that we cannot use the specialized tentative parser, since
3106 // it can only verify that the thing inside the parens can be parsed as
3107 // type-id, it is not useful for determining the context past the parens.
3108 //
3109 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003110 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003111 //
3112 // It uses a scheme similar to parsing inline methods. The parenthesized
3113 // tokens are cached, the context that follows is determined (possibly by
3114 // parsing a cast-expression), and then we re-introduce the cached tokens
3115 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003116
Mike Stump11289f42009-09-09 15:08:12 +00003117 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003118 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003119
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003120 // Store the tokens of the parentheses. We will parse them after we determine
3121 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003122 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003123 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003124 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003125 return ExprError();
3126 }
3127
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003128 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003129 ParseAs = CompoundLiteral;
3130 } else {
3131 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003132 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3133 NotCastExpr = true;
3134 } else {
3135 // Try parsing the cast-expression that may follow.
3136 // If it is not a cast-expression, NotCastExpr will be true and no token
3137 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003138 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003139 Result = ParseCastExpression(false/*isUnaryExpression*/,
3140 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003141 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003142 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003143 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003144 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003145
3146 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3147 // an expression.
3148 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003149 }
3150
Alexey Bataev703a93c2016-02-04 04:22:09 +00003151 // Create a fake EOF to mark end of Toks buffer.
3152 Token AttrEnd;
3153 AttrEnd.startToken();
3154 AttrEnd.setKind(tok::eof);
3155 AttrEnd.setLocation(Tok.getLocation());
3156 AttrEnd.setEofData(Toks.data());
3157 Toks.push_back(AttrEnd);
3158
Mike Stump11289f42009-09-09 15:08:12 +00003159 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003160 Toks.push_back(Tok);
3161 // Re-enter the stored parenthesized tokens into the token stream, so we may
3162 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003163 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003164 // Drop the current token and bring the first cached one. It's the same token
3165 // as when we entered this function.
3166 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003167
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003168 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003169 // Parse the type declarator.
3170 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003171 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003172 {
3173 ColonProtectionRAIIObject InnerColonProtection(*this);
3174 ParseSpecifierQualifierList(DS);
3175 ParseDeclarator(DeclaratorInfo);
3176 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003177
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003178 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003179 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003180 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003181
Alexey Bataev703a93c2016-02-04 04:22:09 +00003182 // Consume EOF marker for Toks buffer.
3183 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3184 ConsumeAnyToken();
3185
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003186 if (ParseAs == CompoundLiteral) {
3187 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003188 if (DeclaratorInfo.isInvalidType())
3189 return ExprError();
3190
3191 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003192 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003193 Tracker.getOpenLocation(),
3194 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003195 }
Mike Stump11289f42009-09-09 15:08:12 +00003196
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003197 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3198 assert(ParseAs == CastExpr);
3199
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003200 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003201 return ExprError();
3202
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003203 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003204 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003205 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3206 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003207 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003208 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003209 }
Mike Stump11289f42009-09-09 15:08:12 +00003210
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003211 // Not a compound literal, and not followed by a cast-expression.
3212 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003213
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003214 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003215 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003216 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003217 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003218 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003219
3220 // Match the ')'.
3221 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003222 while (Tok.isNot(tok::eof))
3223 ConsumeAnyToken();
3224 assert(Tok.getEofData() == AttrEnd.getEofData());
3225 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003226 return ExprError();
3227 }
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003229 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003230 // Consume EOF marker for Toks buffer.
3231 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3232 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003233 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003234}