blob: 10339fc96b5c7a6c2d250917815efd7d03d82991 [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///
Matthias Gehredc01bb42017-03-17 21:41:20 +0000144/// \param OnlyNamespace If true, only considers namespaces in lookup.
145///
John McCall1f476a12010-02-26 08:45:28 +0000146/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000147bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000148 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000149 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000150 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000151 bool IsTypename,
Matthias Gehredc01bb42017-03-17 21:41:20 +0000152 IdentifierInfo **LastII,
153 bool OnlyNamespace) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000154 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000155 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000156
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000157 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000158 assert(!LastII && "want last identifier but have already annotated scope");
Nico Weberc60aa712015-02-16 22:32:46 +0000159 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000160 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
161 Tok.getAnnotationRange(),
162 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000163 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000164 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000165 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000166
Larisse Voufob959c3c2013-08-06 05:49:26 +0000167 if (Tok.is(tok::annot_template_id)) {
168 // If the current token is an annotated template id, it may already have
169 // a scope specifier. Restore it.
170 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
171 SS = TemplateId->SS;
172 }
173
Nico Weberc60aa712015-02-16 22:32:46 +0000174 // Has to happen before any "return false"s in this function.
175 bool CheckForDestructor = false;
176 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
177 CheckForDestructor = true;
178 *MayBePseudoDestructor = false;
179 }
180
Richard Smith7447af42013-03-26 01:15:19 +0000181 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000182 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000183
Douglas Gregor7f741122009-02-25 19:37:18 +0000184 bool HasScopeSpecifier = false;
185
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000186 if (Tok.is(tok::coloncolon)) {
187 // ::new and ::delete aren't nested-name-specifiers.
188 tok::TokenKind NextKind = NextToken().getKind();
189 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
190 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000191
David Majnemere8fb28f2014-12-29 19:19:18 +0000192 if (NextKind == tok::l_brace) {
193 // It is invalid to have :: {, consume the scope qualifier and pretend
194 // like we never saw it.
195 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
196 } else {
197 // '::' - Global scope qualifier.
198 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
199 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000200
David Majnemere8fb28f2014-12-29 19:19:18 +0000201 HasScopeSpecifier = true;
202 }
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000203 }
204
Nikola Smiljanic67860242014-09-26 00:28:20 +0000205 if (Tok.is(tok::kw___super)) {
206 SourceLocation SuperLoc = ConsumeToken();
207 if (!Tok.is(tok::coloncolon)) {
208 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
209 return true;
210 }
211
212 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
213 }
214
Richard Smitha9d10012014-10-04 01:57:39 +0000215 if (!HasScopeSpecifier &&
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000216 Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000217 DeclSpec DS(AttrFactory);
218 SourceLocation DeclLoc = Tok.getLocation();
219 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000220
221 SourceLocation CCLoc;
Richard Smith3f846bd2017-02-08 19:58:48 +0000222 // Work around a standard defect: 'decltype(auto)::' is not a
223 // nested-name-specifier.
224 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto ||
225 !TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000226 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
227 return false;
228 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000229
David Blaikie15a430a2011-12-04 05:04:18 +0000230 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
231 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
232
233 HasScopeSpecifier = true;
234 }
235
Douglas Gregor7f741122009-02-25 19:37:18 +0000236 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000237 if (HasScopeSpecifier) {
238 // C++ [basic.lookup.classref]p5:
239 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000240 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000241 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000242 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000243 // the class-name-or-namespace-name is looked up in global scope as a
244 // class-name or namespace-name.
245 //
246 // To implement this, we clear out the object type as soon as we've
247 // seen a leading '::' or part of a nested-name-specifier.
David Blaikieefdccaa2016-01-15 23:43:34 +0000248 ObjectType = nullptr;
249
Douglas Gregor2436e712009-09-17 21:32:03 +0000250 if (Tok.is(tok::code_completion)) {
251 // Code completion for a nested-name-specifier, where the code
252 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000253 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000254 // Include code completion token into the range of the scope otherwise
255 // when we try to annotate the scope tokens the dangling code completion
256 // token will cause assertion in
257 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000258 SS.setEndLoc(Tok.getLocation());
259 cutOffParsing();
260 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000261 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000262 }
Mike Stump11289f42009-09-09 15:08:12 +0000263
Douglas Gregor7f741122009-02-25 19:37:18 +0000264 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000265 // nested-name-specifier 'template'[opt] simple-template-id '::'
266
267 // Parse the optional 'template' keyword, then make sure we have
268 // 'identifier <' after it.
269 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000270 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000271 // nested-name-specifier, since they aren't allowed to start with
272 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000273 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000274 break;
275
Douglas Gregor120635b2009-11-11 16:39:34 +0000276 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000277 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000278
Douglas Gregor71395fa2009-11-04 00:56:37 +0000279 UnqualifiedId TemplateName;
280 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000281 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000282 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000283 ConsumeToken();
284 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000285 // We don't need to actually parse the unqualified-id in this case,
286 // because a simple-template-id cannot start with 'operator', but
287 // go ahead and parse it anyway for consistency with the case where
288 // we already annotated the template-id.
289 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000290 TemplateName)) {
291 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000292 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000293 }
Richard Smithd091dc12013-12-05 00:58:33 +0000294
Alexis Hunted0530f2009-11-28 08:58:14 +0000295 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
296 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000297 Diag(TemplateName.getSourceRange().getBegin(),
298 diag::err_id_after_template_in_nested_name_spec)
299 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000300 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000301 break;
302 }
303 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000304 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000305 break;
306 }
Mike Stump11289f42009-09-09 15:08:12 +0000307
Douglas Gregor120635b2009-11-11 16:39:34 +0000308 // If the next token is not '<', we have a qualified-id that refers
309 // to a template name, such as T::template apply, but is not a
310 // template-id.
311 if (Tok.isNot(tok::less)) {
312 TPA.Revert();
313 break;
314 }
315
316 // Commit to parsing the template-id.
317 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000318 TemplateTy Template;
Richard Smithfd3dae02017-01-20 00:20:39 +0000319 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
320 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
321 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +0000322 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
323 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000324 return true;
325 } else
John McCall1f476a12010-02-26 08:45:28 +0000326 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner0eed3a62009-06-26 03:47:46 +0000328 continue;
329 }
Mike Stump11289f42009-09-09 15:08:12 +0000330
Douglas Gregor7f741122009-02-25 19:37:18 +0000331 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000332 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000333 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000334 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000335 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000336 // So we need to check whether the template-id is a simple-template-id of
337 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000338 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000339 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000340 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
341 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000342 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000343 }
344
Richard Smith7447af42013-03-26 01:15:19 +0000345 if (LastII)
346 *LastII = TemplateId->Name;
347
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000348 // Consume the template-id token.
349 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000350
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000351 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
352 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000353
David Blaikie8c045bc2011-11-07 03:30:03 +0000354 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000355
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000356 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000357 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000358
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000359 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000360 SS,
361 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000362 TemplateId->Template,
363 TemplateId->TemplateNameLoc,
364 TemplateId->LAngleLoc,
365 TemplateArgsPtr,
366 TemplateId->RAngleLoc,
367 CCLoc,
368 EnteringContext)) {
369 SourceLocation StartLoc
370 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
371 : TemplateId->TemplateNameLoc;
372 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000373 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000374
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000375 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000376 }
377
Chris Lattnere2355f72009-06-26 03:52:38 +0000378 // The rest of the nested-name-specifier possibilities start with
379 // tok::identifier.
380 if (Tok.isNot(tok::identifier))
381 break;
382
383 IdentifierInfo &II = *Tok.getIdentifierInfo();
384
385 // nested-name-specifier:
386 // type-name '::'
387 // namespace-name '::'
388 // nested-name-specifier identifier '::'
389 Token Next = NextToken();
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000390 Sema::NestedNameSpecInfo IdInfo(&II, Tok.getLocation(), Next.getLocation(),
391 ObjectType);
392
Chris Lattner1c428032009-12-07 01:36:53 +0000393 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
394 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000395 if (Next.is(tok::colon) && !ColonIsSacred) {
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000396 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, IdInfo,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000397 EnteringContext) &&
398 // If the token after the colon isn't an identifier, it's still an
399 // error, but they probably meant something else strange so don't
400 // recover like this.
401 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000402 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000403 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000404 // Recover as if the user wrote '::'.
405 Next.setKind(tok::coloncolon);
406 }
Chris Lattner1c428032009-12-07 01:36:53 +0000407 }
David Majnemerf58efd92014-12-29 23:12:23 +0000408
409 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
410 // It is invalid to have :: {, consume the scope qualifier and pretend
411 // like we never saw it.
412 Token Identifier = Tok; // Stash away the identifier.
413 ConsumeToken(); // Eat the identifier, current token is now '::'.
David Majnemerec3f49d2014-12-29 23:24:27 +0000414 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
415 << tok::identifier;
David Majnemerf58efd92014-12-29 23:12:23 +0000416 UnconsumeToken(Identifier); // Stick the identifier back.
417 Next = NextToken(); // Point Next at the '{' token.
418 }
419
Chris Lattnere2355f72009-06-26 03:52:38 +0000420 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000421 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Serge Pavlovd931b9f2016-08-08 04:02:15 +0000422 !Actions.isNonTypeNestedNameSpecifier(getCurScope(), SS, IdInfo)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000423 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000424 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000425 }
426
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000427 if (ColonIsSacred) {
428 const Token &Next2 = GetLookAheadToken(2);
429 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
430 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
431 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
432 << Next2.getName()
433 << FixItHint::CreateReplacement(Next.getLocation(), ":");
434 Token ColonColon;
435 PP.Lex(ColonColon);
436 ColonColon.setKind(tok::colon);
437 PP.EnterToken(ColonColon);
438 break;
439 }
440 }
441
Richard Smith7447af42013-03-26 01:15:19 +0000442 if (LastII)
443 *LastII = &II;
444
Chris Lattnere2355f72009-06-26 03:52:38 +0000445 // We have an identifier followed by a '::'. Lookup this name
446 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000447 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000448 SourceLocation IdLoc = ConsumeToken();
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000449 assert(Tok.isOneOf(tok::coloncolon, tok::colon) &&
Chris Lattner1c428032009-12-07 01:36:53 +0000450 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000451 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000452 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000453
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000454 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000455 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Matthias Gehredc01bb42017-03-17 21:41:20 +0000456 if (Actions.ActOnCXXNestedNameSpecifier(
457 getCurScope(), IdInfo, EnteringContext, SS, false,
458 CorrectionFlagPtr, OnlyNamespace)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000459 // Identifier is not recognized as a nested name, but we can have
460 // mistyped '::' instead of ':'.
461 if (CorrectionFlagPtr && IsCorrectedToColon) {
462 ColonColon.setKind(tok::colon);
463 PP.EnterToken(Tok);
464 PP.EnterToken(ColonColon);
465 Tok = Identifier;
466 break;
467 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000468 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000469 }
470 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000471 continue;
472 }
Mike Stump11289f42009-09-09 15:08:12 +0000473
Richard Trieu01fc0012011-09-19 19:01:00 +0000474 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000475
Chris Lattnere2355f72009-06-26 03:52:38 +0000476 // nested-name-specifier:
477 // type-name '<'
478 if (Next.is(tok::less)) {
479 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000480 UnqualifiedId TemplateName;
481 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000482 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000483 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000484 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000485 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000486 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000487 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000488 Template,
489 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000490 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000491 // with a template-id annotation. We do not permit the
492 // template-id to be translated into a type annotation,
493 // because some clients (e.g., the parsing of class template
494 // specializations) still want to see the original template-id
495 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000496 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000497 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
498 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000499 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000500 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000501 }
502
Douglas Gregor20c38a72010-05-21 23:43:39 +0000503 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000504 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000505 // We have something like t::getAs<T>, where getAs is a
506 // member of an unknown specialization. However, this will only
507 // parse correctly as a template, so suggest the keyword 'template'
508 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000509 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000510 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000511 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000512
513 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000514 << II.getName()
515 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +0000516
517 if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(
518 getCurScope(), SS, SourceLocation(), TemplateName, ObjectType,
519 EnteringContext, Template, /*AllowInjectedClassName*/ true)) {
Douglas Gregorbb119652010-06-16 23:00:59 +0000520 // Consume the identifier.
521 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000522 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
523 TemplateName, false))
524 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000525 }
526 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000527 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000528
Douglas Gregor20c38a72010-05-21 23:43:39 +0000529 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000530 }
531 }
532
Douglas Gregor7f741122009-02-25 19:37:18 +0000533 // We don't have any tokens that form the beginning of a
534 // nested-name-specifier, so we're done.
535 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregore610ada2010-02-24 18:44:31 +0000538 // Even if we didn't see any pieces of a nested-name-specifier, we
539 // still check whether there is a tilde in this position, which
540 // indicates a potential pseudo-destructor.
541 if (CheckForDestructor && Tok.is(tok::tilde))
542 *MayBePseudoDestructor = true;
543
John McCall1f476a12010-02-26 08:45:28 +0000544 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000545}
546
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000547ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
548 Token &Replacement) {
549 SourceLocation TemplateKWLoc;
550 UnqualifiedId Name;
551 if (ParseUnqualifiedId(SS,
552 /*EnteringContext=*/false,
553 /*AllowDestructorName=*/false,
554 /*AllowConstructorName=*/false,
Richard Smith35845152017-02-07 01:37:30 +0000555 /*AllowDeductionGuide=*/false,
David Blaikieefdccaa2016-01-15 23:43:34 +0000556 /*ObjectType=*/nullptr, TemplateKWLoc, Name))
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000557 return ExprError();
558
559 // This is only the direct operand of an & operator if it is not
560 // followed by a postfix-expression suffix.
561 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
562 isAddressOfOperand = false;
563
564 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
565 Tok.is(tok::l_paren), isAddressOfOperand,
566 nullptr, /*IsInlineAsmIdentifier=*/false,
567 &Replacement);
568}
569
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000570/// ParseCXXIdExpression - Handle id-expression.
571///
572/// id-expression:
573/// unqualified-id
574/// qualified-id
575///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000576/// qualified-id:
577/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
578/// '::' identifier
579/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000580/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000581///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000582/// NOTE: The standard specifies that, for qualified-id, the parser does not
583/// expect:
584///
585/// '::' conversion-function-id
586/// '::' '~' class-name
587///
588/// This may cause a slight inconsistency on diagnostics:
589///
590/// class C {};
591/// namespace A {}
592/// void f() {
593/// :: A :: ~ C(); // Some Sema error about using destructor with a
594/// // namespace.
595/// :: ~ C(); // Some Parser error like 'unexpected ~'.
596/// }
597///
598/// We simplify the parser a bit and make it work like:
599///
600/// qualified-id:
601/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602/// '::' unqualified-id
603///
604/// That way Sema can handle and report similar errors for namespaces and the
605/// global scope.
606///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000607/// The isAddressOfOperand parameter indicates that this id-expression is a
608/// direct operand of the address-of operator. This is, besides member contexts,
609/// the only place where a qualified-id naming a non-static class member may
610/// appear.
611///
John McCalldadc5752010-08-24 06:29:42 +0000612ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000613 // qualified-id:
614 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
615 // '::' unqualified-id
616 //
617 CXXScopeSpec SS;
David Blaikieefdccaa2016-01-15 23:43:34 +0000618 ParseOptionalCXXScopeSpecifier(SS, nullptr, /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000619
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000620 Token Replacement;
Nico Weber01a46ad2015-02-15 06:15:40 +0000621 ExprResult Result =
622 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000623 if (Result.isUnset()) {
624 // If the ExprResult is valid but null, then typo correction suggested a
625 // keyword replacement that needs to be reparsed.
626 UnconsumeToken(Replacement);
627 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
628 }
629 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
630 "for a previous keyword suggestion");
631 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000632}
633
Richard Smith21b3ab42013-05-09 21:36:41 +0000634/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000635///
636/// lambda-expression:
637/// lambda-introducer lambda-declarator[opt] compound-statement
638///
639/// lambda-introducer:
640/// '[' lambda-capture[opt] ']'
641///
642/// lambda-capture:
643/// capture-default
644/// capture-list
645/// capture-default ',' capture-list
646///
647/// capture-default:
648/// '&'
649/// '='
650///
651/// capture-list:
652/// capture
653/// capture-list ',' capture
654///
655/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000656/// simple-capture
657/// init-capture [C++1y]
658///
659/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000660/// identifier
661/// '&' identifier
662/// 'this'
663///
Richard Smith21b3ab42013-05-09 21:36:41 +0000664/// init-capture: [C++1y]
665/// identifier initializer
666/// '&' identifier initializer
667///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000668/// lambda-declarator:
669/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
670/// 'mutable'[opt] exception-specification[opt]
671/// trailing-return-type[opt]
672///
673ExprResult Parser::ParseLambdaExpression() {
674 // Parse lambda-introducer.
675 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000676 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000677 if (DiagID) {
678 Diag(Tok, DiagID.getValue());
David Majnemer234b8182015-01-12 03:36:37 +0000679 SkipUntil(tok::r_square, StopAtSemi);
680 SkipUntil(tok::l_brace, StopAtSemi);
681 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000682 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000683 }
684
685 return ParseLambdaExpressionAfterIntroducer(Intro);
686}
687
688/// TryParseLambdaExpression - Use lookahead and potentially tentative
689/// parsing to determine if we are looking at a C++0x lambda expression, and parse
690/// it if we are.
691///
692/// If we are not looking at a lambda expression, returns ExprError().
693ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000694 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000695 && Tok.is(tok::l_square)
696 && "Not at the start of a possible lambda expression.");
697
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000698 const Token Next = NextToken();
699 if (Next.is(tok::eof)) // Nothing else to lookup here...
700 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000701
Bruno Cardoso Lopes29b34232016-05-31 18:46:31 +0000702 const Token After = GetLookAheadToken(2);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000703 // If lookahead indicates this is a lambda...
704 if (Next.is(tok::r_square) || // []
705 Next.is(tok::equal) || // [=
706 (Next.is(tok::amp) && // [&] or [&,
707 (After.is(tok::r_square) ||
708 After.is(tok::comma))) ||
709 (Next.is(tok::identifier) && // [identifier]
710 After.is(tok::r_square))) {
711 return ParseLambdaExpression();
712 }
713
Eli Friedmanc7c97142012-01-04 02:40:39 +0000714 // If lookahead indicates an ObjC message send...
715 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000716 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000717 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000718 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000719
Eli Friedmanc7c97142012-01-04 02:40:39 +0000720 // Here, we're stuck: lambda introducers and Objective-C message sends are
721 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
722 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
723 // writing two routines to parse a lambda introducer, just try to parse
724 // a lambda introducer first, and fall back if that fails.
725 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000726 LambdaIntroducer Intro;
727 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000728 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000729
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000730 return ParseLambdaExpressionAfterIntroducer(Intro);
731}
732
Richard Smithf44d2a82013-05-21 22:21:19 +0000733/// \brief Parse a lambda introducer.
734/// \param Intro A LambdaIntroducer filled in with information about the
735/// contents of the lambda-introducer.
736/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
737/// message send and a lambda expression. In this mode, we will
738/// sometimes skip the initializers for init-captures and not fully
739/// populate \p Intro. This flag will be set to \c true if we do so.
740/// \return A DiagnosticID if it hit something unexpected. The location for
Malcolm Parsonsffd21d32017-01-11 11:23:22 +0000741/// the diagnostic is that of the current token.
Richard Smithf44d2a82013-05-21 22:21:19 +0000742Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
743 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000744 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000745
746 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000747 BalancedDelimiterTracker T(*this, tok::l_square);
748 T.consumeOpen();
749
750 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000751
752 bool first = true;
753
754 // Parse capture-default.
755 if (Tok.is(tok::amp) &&
756 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
757 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000758 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000759 first = false;
760 } else if (Tok.is(tok::equal)) {
761 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000762 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000763 first = false;
764 }
765
766 while (Tok.isNot(tok::r_square)) {
767 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000768 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000769 // Provide a completion for a lambda introducer here. Except
770 // in Objective-C, where this is Almost Surely meant to be a message
771 // send. In that case, fail here and let the ObjC message
772 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000773 if (Tok.is(tok::code_completion) &&
774 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
775 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000776 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
777 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000778 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000779 break;
780 }
781
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000782 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000783 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000784 ConsumeToken();
785 }
786
Douglas Gregord8c61782012-02-15 15:34:24 +0000787 if (Tok.is(tok::code_completion)) {
788 // If we're in Objective-C++ and we have a bare '[', then this is more
789 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000790 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000791 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
792 else
793 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
794 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000795 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000796 break;
797 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000798
Douglas Gregord8c61782012-02-15 15:34:24 +0000799 first = false;
800
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000801 // Parse capture.
802 LambdaCaptureKind Kind = LCK_ByCopy;
Richard Smith42b10572015-11-11 01:36:17 +0000803 LambdaCaptureInitKind InitKind = LambdaCaptureInitKind::NoInit;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000805 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000806 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000807 ExprResult Init;
Faisal Validc6b5962016-03-21 09:25:37 +0000808
809 if (Tok.is(tok::star)) {
810 Loc = ConsumeToken();
811 if (Tok.is(tok::kw_this)) {
812 ConsumeToken();
813 Kind = LCK_StarThis;
814 } else {
815 return DiagResult(diag::err_expected_star_this_capture);
816 }
817 } else if (Tok.is(tok::kw_this)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000818 Kind = LCK_This;
819 Loc = ConsumeToken();
820 } else {
821 if (Tok.is(tok::amp)) {
822 Kind = LCK_ByRef;
823 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000824
825 if (Tok.is(tok::code_completion)) {
826 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
827 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000828 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000829 break;
830 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000831 }
832
833 if (Tok.is(tok::identifier)) {
834 Id = Tok.getIdentifierInfo();
835 Loc = ConsumeToken();
836 } else if (Tok.is(tok::kw_this)) {
837 // FIXME: If we want to suggest a fixit here, will need to return more
838 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
839 // Clear()ed to prevent emission in case of tentative parsing?
840 return DiagResult(diag::err_this_captured_by_reference);
841 } else {
842 return DiagResult(diag::err_expected_capture);
843 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000844
845 if (Tok.is(tok::l_paren)) {
846 BalancedDelimiterTracker Parens(*this, tok::l_paren);
847 Parens.consumeOpen();
848
Richard Smith42b10572015-11-11 01:36:17 +0000849 InitKind = LambdaCaptureInitKind::DirectInit;
850
Richard Smith21b3ab42013-05-09 21:36:41 +0000851 ExprVector Exprs;
852 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000853 if (SkippedInits) {
854 Parens.skipToEnd();
855 *SkippedInits = true;
856 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000857 Parens.skipToEnd();
858 Init = ExprError();
859 } else {
860 Parens.consumeClose();
861 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
862 Parens.getCloseLocation(),
863 Exprs);
864 }
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000865 } else if (Tok.isOneOf(tok::l_brace, tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000866 // Each lambda init-capture forms its own full expression, which clears
867 // Actions.MaybeODRUseExprs. So create an expression evaluation context
868 // to save the necessary state, and restore it later.
869 EnterExpressionEvaluationContext EC(Actions,
870 Sema::PotentiallyEvaluated);
Richard Smith42b10572015-11-11 01:36:17 +0000871
872 if (TryConsumeToken(tok::equal))
873 InitKind = LambdaCaptureInitKind::CopyInit;
874 else
875 InitKind = LambdaCaptureInitKind::ListInit;
Richard Smith21b3ab42013-05-09 21:36:41 +0000876
Richard Smith215f4232015-02-11 02:41:33 +0000877 if (!SkippedInits) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000878 Init = ParseInitializer();
Richard Smith215f4232015-02-11 02:41:33 +0000879 } else if (Tok.is(tok::l_brace)) {
Richard Smithf44d2a82013-05-21 22:21:19 +0000880 BalancedDelimiterTracker Braces(*this, tok::l_brace);
881 Braces.consumeOpen();
882 Braces.skipToEnd();
883 *SkippedInits = true;
884 } else {
885 // We're disambiguating this:
886 //
887 // [..., x = expr
888 //
889 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000890 // determine whether this is an Obj-C message send's receiver, a
891 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000892 //
893 // Parse the expression to find where it ends, and annotate it back
894 // onto the tokens. We would have parsed this expression the same way
895 // in either case: both the RHS of an init-capture and the RHS of an
896 // assignment expression are parsed as an initializer-clause, and in
897 // neither case can anything be added to the scope between the '[' and
898 // here.
899 //
900 // FIXME: This is horrible. Adding a mechanism to skip an expression
901 // would be much cleaner.
902 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
903 // that instead. (And if we see a ':' with no matching '?', we can
904 // classify this as an Obj-C message send.)
905 SourceLocation StartLoc = Tok.getLocation();
906 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
907 Init = ParseInitializer();
Akira Hatanaka51e60f92016-12-20 02:11:29 +0000908 if (!Init.isInvalid())
909 Init = Actions.CorrectDelayedTyposInExpr(Init.get());
Richard Smithf44d2a82013-05-21 22:21:19 +0000910
911 if (Tok.getLocation() != StartLoc) {
912 // Back out the lexing of the token after the initializer.
913 PP.RevertCachedTokens(1);
914
915 // Replace the consumed tokens with an appropriate annotation.
916 Tok.setLocation(StartLoc);
917 Tok.setKind(tok::annot_primary_expr);
918 setExprAnnotation(Tok, Init);
919 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
920 PP.AnnotateCachedTokens(Tok);
921
922 // Consume the annotated initializer.
923 ConsumeToken();
924 }
925 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000926 } else
927 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000928 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000929 // If this is an init capture, process the initialization expression
930 // right away. For lambda init-captures such as the following:
931 // const int x = 10;
932 // auto L = [i = x+1](int a) {
933 // return [j = x+2,
934 // &k = x](char b) { };
935 // };
936 // keep in mind that each lambda init-capture has to have:
937 // - its initialization expression executed in the context
938 // of the enclosing/parent decl-context.
939 // - but the variable itself has to be 'injected' into the
940 // decl-context of its lambda's call-operator (which has
941 // not yet been created).
942 // Each init-expression is a full-expression that has to get
943 // Sema-analyzed (for capturing etc.) before its lambda's
944 // call-operator's decl-context, scope & scopeinfo are pushed on their
945 // respective stacks. Thus if any variable is odr-used in the init-capture
946 // it will correctly get captured in the enclosing lambda, if one exists.
947 // The init-variables above are created later once the lambdascope and
948 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000949
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000950 // Since the lambda init-capture's initializer expression occurs in the
951 // context of the enclosing function or lambda, therefore we can not wait
952 // till a lambda scope has been pushed on before deciding whether the
953 // variable needs to be captured. We also need to process all
954 // lvalue-to-rvalue conversions and discarded-value conversions,
955 // so that we can avoid capturing certain constant variables.
956 // For e.g.,
957 // void test() {
958 // const int x = 10;
959 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
960 // return [y = x](int i) { <-- don't capture by enclosing lambda
961 // return y;
962 // }
963 // };
Richard Smithbdb84f32016-07-22 23:36:59 +0000964 // }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000965 // If x was not const, the second use would require 'L' to capture, and
966 // that would be an error.
967
Richard Smith42b10572015-11-11 01:36:17 +0000968 ParsedType InitCaptureType;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000969 if (Init.isUsable()) {
970 // Get the pointer and store it in an lvalue, so we can use it as an
971 // out argument.
972 Expr *InitExpr = Init.get();
973 // This performs any lvalue-to-rvalue conversions if necessary, which
974 // can affect what gets captured in the containing decl-context.
Richard Smith42b10572015-11-11 01:36:17 +0000975 InitCaptureType = Actions.actOnLambdaInitCaptureInitialization(
976 Loc, Kind == LCK_ByRef, Id, InitKind, InitExpr);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000977 Init = InitExpr;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000978 }
Richard Smith42b10572015-11-11 01:36:17 +0000979 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init,
980 InitCaptureType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000981 }
982
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000983 T.consumeClose();
984 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000985 return DiagResult();
986}
987
Douglas Gregord8c61782012-02-15 15:34:24 +0000988/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000989///
990/// Returns true if it hit something unexpected.
991bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
992 TentativeParsingAction PA(*this);
993
Richard Smithf44d2a82013-05-21 22:21:19 +0000994 bool SkippedInits = false;
995 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000996
997 if (DiagID) {
998 PA.Revert();
999 return true;
1000 }
1001
Richard Smithf44d2a82013-05-21 22:21:19 +00001002 if (SkippedInits) {
1003 // Parse it again, but this time parse the init-captures too.
1004 PA.Revert();
1005 Intro = LambdaIntroducer();
1006 DiagID = ParseLambdaIntroducer(Intro);
1007 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1008 return false;
1009 }
1010
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001011 PA.Commit();
1012 return false;
1013}
1014
Faisal Valia734ab92016-03-26 16:11:37 +00001015static void
1016tryConsumeMutableOrConstexprToken(Parser &P, SourceLocation &MutableLoc,
1017 SourceLocation &ConstexprLoc,
1018 SourceLocation &DeclEndLoc) {
1019 assert(MutableLoc.isInvalid());
1020 assert(ConstexprLoc.isInvalid());
1021 // Consume constexpr-opt mutable-opt in any sequence, and set the DeclEndLoc
1022 // to the final of those locations. Emit an error if we have multiple
1023 // copies of those keywords and recover.
1024
1025 while (true) {
1026 switch (P.getCurToken().getKind()) {
1027 case tok::kw_mutable: {
1028 if (MutableLoc.isValid()) {
1029 P.Diag(P.getCurToken().getLocation(),
1030 diag::err_lambda_decl_specifier_repeated)
1031 << 0 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1032 }
1033 MutableLoc = P.ConsumeToken();
1034 DeclEndLoc = MutableLoc;
1035 break /*switch*/;
1036 }
1037 case tok::kw_constexpr:
1038 if (ConstexprLoc.isValid()) {
1039 P.Diag(P.getCurToken().getLocation(),
1040 diag::err_lambda_decl_specifier_repeated)
1041 << 1 << FixItHint::CreateRemoval(P.getCurToken().getLocation());
1042 }
1043 ConstexprLoc = P.ConsumeToken();
1044 DeclEndLoc = ConstexprLoc;
1045 break /*switch*/;
1046 default:
1047 return;
1048 }
1049 }
1050}
1051
1052static void
1053addConstexprToLambdaDeclSpecifier(Parser &P, SourceLocation ConstexprLoc,
1054 DeclSpec &DS) {
1055 if (ConstexprLoc.isValid()) {
1056 P.Diag(ConstexprLoc, !P.getLangOpts().CPlusPlus1z
1057 ? diag::ext_constexpr_on_lambda_cxx1z
1058 : diag::warn_cxx14_compat_constexpr_on_lambda);
1059 const char *PrevSpec = nullptr;
1060 unsigned DiagID = 0;
1061 DS.SetConstexprSpec(ConstexprLoc, PrevSpec, DiagID);
1062 assert(PrevSpec == nullptr && DiagID == 0 &&
1063 "Constexpr cannot have been set previously!");
1064 }
1065}
1066
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001067/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1068/// expression.
1069ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1070 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001071 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1072 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1073
1074 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1075 "lambda expression parsing");
1076
Faisal Vali2b391ab2013-09-26 19:54:12 +00001077
1078
Richard Smith21b3ab42013-05-09 21:36:41 +00001079 // FIXME: Call into Actions to add any init-capture declarations to the
1080 // scope while parsing the lambda-declarator and compound-statement.
1081
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001082 // Parse lambda-declarator[opt].
1083 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001084 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001085 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001086 Actions.PushLambdaScope();
1087
1088 ParsedAttributes Attr(AttrFactory);
1089 SourceLocation DeclLoc = Tok.getLocation();
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001090 if (getLangOpts().CUDA) {
1091 // In CUDA code, GNU attributes are allowed to appear immediately after the
1092 // "[...]", even if there is no "(...)" before the lambda body.
Justin Lebar0139a5d2016-09-30 19:55:48 +00001093 MaybeParseGNUAttributes(D);
Justin Lebar0fad0ba2016-09-30 17:14:48 +00001094 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001095
Justin Lebare46ea722016-09-30 19:55:55 +00001096 // Helper to emit a warning if we see a CUDA host/device/global attribute
1097 // after '(...)'. nvcc doesn't accept this.
1098 auto WarnIfHasCUDATargetAttr = [&] {
1099 if (getLangOpts().CUDA)
1100 for (auto *A = Attr.getList(); A != nullptr; A = A->getNext())
1101 if (A->getKind() == AttributeList::AT_CUDADevice ||
1102 A->getKind() == AttributeList::AT_CUDAHost ||
1103 A->getKind() == AttributeList::AT_CUDAGlobal)
1104 Diag(A->getLoc(), diag::warn_cuda_attr_lambda_position)
1105 << A->getName()->getName();
1106 };
1107
David Majnemere01c4662015-01-09 05:10:55 +00001108 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001109 if (Tok.is(tok::l_paren)) {
1110 ParseScope PrototypeScope(this,
1111 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001112 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001113 Scope::DeclScope);
1114
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001115 BalancedDelimiterTracker T(*this, tok::l_paren);
1116 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001117 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001118
1119 // Parse parameter-declaration-clause.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001120 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001121 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001122
1123 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001124 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001125 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001126 // For a generic lambda, each 'auto' within the parameter declaration
1127 // clause creates a template type parameter, so increment the depth.
1128 if (Actions.getCurGenericLambda())
1129 ++CurTemplateDepthTracker;
1130 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001131 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001132 SourceLocation RParenLoc = T.getCloseLocation();
Justin Lebar0139a5d2016-09-30 19:55:48 +00001133 SourceLocation DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001134
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001135 // GNU-style attributes must be parsed before the mutable specifier to be
1136 // compatible with GCC.
1137 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1138
David Majnemerbda86322015-02-04 08:22:46 +00001139 // MSVC-style attributes must be parsed before the mutable specifier to be
1140 // compatible with MSVC.
Aaron Ballman068aa512015-05-20 20:58:33 +00001141 MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc);
David Majnemerbda86322015-02-04 08:22:46 +00001142
Faisal Valia734ab92016-03-26 16:11:37 +00001143 // Parse mutable-opt and/or constexpr-opt, and update the DeclEndLoc.
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001144 SourceLocation MutableLoc;
Faisal Valia734ab92016-03-26 16:11:37 +00001145 SourceLocation ConstexprLoc;
1146 tryConsumeMutableOrConstexprToken(*this, MutableLoc, ConstexprLoc,
1147 DeclEndLoc);
1148
1149 addConstexprToLambdaDeclSpecifier(*this, ConstexprLoc, DS);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001150
1151 // Parse exception-specification[opt].
1152 ExceptionSpecificationType ESpecType = EST_None;
1153 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001154 SmallVector<ParsedType, 2> DynamicExceptions;
1155 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001156 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001157 CachedTokens *ExceptionSpecTokens;
1158 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1159 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001160 DynamicExceptions,
1161 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001162 NoexceptExpr,
1163 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001164
1165 if (ESpecType != EST_None)
1166 DeclEndLoc = ESpecRange.getEnd();
1167
1168 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001169 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001170
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001171 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1172
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001173 // Parse trailing-return-type[opt].
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001174 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001175 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001176 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001177 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001178 if (Range.getEnd().isValid())
1179 DeclEndLoc = Range.getEnd();
1180 }
1181
1182 PrototypeScope.Exit();
1183
Justin Lebare46ea722016-09-30 19:55:55 +00001184 WarnIfHasCUDATargetAttr();
1185
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001186 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001187 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001188 /*isAmbiguous=*/false,
1189 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001190 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001191 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001192 DS.getTypeQualifiers(),
1193 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001194 /*RefQualifierLoc=*/NoLoc,
1195 /*ConstQualifierLoc=*/NoLoc,
1196 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001197 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001198 MutableLoc,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001199 ESpecType, ESpecRange,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001200 DynamicExceptions.data(),
1201 DynamicExceptionRanges.data(),
1202 DynamicExceptions.size(),
1203 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001204 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001205 /*ExceptionSpecTokens*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001206 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001207 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001208 TrailingReturnType),
1209 Attr, DeclEndLoc);
Faisal Valia734ab92016-03-26 16:11:37 +00001210 } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute,
1211 tok::kw_constexpr) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001212 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1213 // It's common to forget that one needs '()' before 'mutable', an attribute
1214 // specifier, or the result type. Deal with this.
1215 unsigned TokKind = 0;
1216 switch (Tok.getKind()) {
1217 case tok::kw_mutable: TokKind = 0; break;
1218 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001219 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001220 case tok::l_square: TokKind = 2; break;
Faisal Valia734ab92016-03-26 16:11:37 +00001221 case tok::kw_constexpr: TokKind = 3; break;
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001222 default: llvm_unreachable("Unknown token kind");
1223 }
1224
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001225 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001226 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001227 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
Justin Lebar0139a5d2016-09-30 19:55:48 +00001228 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001229
1230 // GNU-style attributes must be parsed before the mutable specifier to be
1231 // compatible with GCC.
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001232 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1233
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001234 // Parse 'mutable', if it's there.
1235 SourceLocation MutableLoc;
1236 if (Tok.is(tok::kw_mutable)) {
1237 MutableLoc = ConsumeToken();
1238 DeclEndLoc = MutableLoc;
1239 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001240
1241 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001242 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1243
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001244 // Parse the return type, if there is one.
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001245 if (Tok.is(tok::arrow)) {
1246 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001247 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001248 if (Range.getEnd().isValid())
David Majnemere01c4662015-01-09 05:10:55 +00001249 DeclEndLoc = Range.getEnd();
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001250 }
1251
Justin Lebare46ea722016-09-30 19:55:55 +00001252 WarnIfHasCUDATargetAttr();
1253
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001254 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001255 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001256 /*isAmbiguous=*/false,
1257 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001258 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001259 /*NumParams=*/0,
1260 /*EllipsisLoc=*/NoLoc,
1261 /*RParenLoc=*/NoLoc,
1262 /*TypeQuals=*/0,
1263 /*RefQualifierIsLValueRef=*/true,
1264 /*RefQualifierLoc=*/NoLoc,
1265 /*ConstQualifierLoc=*/NoLoc,
1266 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001267 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001268 MutableLoc,
1269 EST_None,
Nathan Wilsone23a9a42015-08-26 04:19:36 +00001270 /*ESpecRange=*/SourceRange(),
Craig Topper161e4db2014-05-21 06:02:52 +00001271 /*Exceptions=*/nullptr,
1272 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001273 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001274 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001275 /*ExceptionSpecTokens=*/nullptr,
Reid Kleckner078aea92016-12-09 17:14:05 +00001276 /*DeclsInPrototype=*/None,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001277 DeclLoc, DeclEndLoc, D,
1278 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001279 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001280 }
1281
Eli Friedman4817cf72012-01-06 03:05:34 +00001282 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1283 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001284 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001285 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001286
Eli Friedman71c80552012-01-05 03:35:19 +00001287 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1288
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001289 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001290 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001291 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001292 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1293 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001294 }
1295
Eli Friedmanc7c97142012-01-04 02:40:39 +00001296 StmtResult Stmt(ParseCompoundStatementBody());
1297 BodyScope.Exit();
1298
David Majnemere01c4662015-01-09 05:10:55 +00001299 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001300 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
David Majnemere01c4662015-01-09 05:10:55 +00001301
Eli Friedman898caf82012-01-04 02:46:53 +00001302 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1303 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001304}
1305
Chris Lattner29375652006-12-04 18:06:35 +00001306/// ParseCXXCasts - This handles the various ways to cast expressions to another
1307/// type.
1308///
1309/// postfix-expression: [C++ 5.2p1]
1310/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1311/// 'static_cast' '<' type-name '>' '(' expression ')'
1312/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1313/// 'const_cast' '<' type-name '>' '(' expression ')'
1314///
John McCalldadc5752010-08-24 06:29:42 +00001315ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001316 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001317 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001318
1319 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001320 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001321 case tok::kw_const_cast: CastName = "const_cast"; break;
1322 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1323 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1324 case tok::kw_static_cast: CastName = "static_cast"; break;
1325 }
1326
1327 SourceLocation OpLoc = ConsumeToken();
1328 SourceLocation LAngleBracketLoc = Tok.getLocation();
1329
Richard Smith55858492011-04-14 21:45:45 +00001330 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1331 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001332 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1333 Token Next = NextToken();
1334 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1335 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1336 }
Richard Smith55858492011-04-14 21:45:45 +00001337
Chris Lattner29375652006-12-04 18:06:35 +00001338 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001339 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001340
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001341 // Parse the common declaration-specifiers piece.
1342 DeclSpec DS(AttrFactory);
1343 ParseSpecifierQualifierList(DS);
1344
1345 // Parse the abstract-declarator, if present.
1346 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1347 ParseDeclarator(DeclaratorInfo);
1348
Chris Lattner29375652006-12-04 18:06:35 +00001349 SourceLocation RAngleBracketLoc = Tok.getLocation();
1350
Alp Toker383d2c42014-01-01 03:08:43 +00001351 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001352 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001353
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001354 SourceLocation LParenLoc, RParenLoc;
1355 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001356
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001357 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001358 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001359
John McCalldadc5752010-08-24 06:29:42 +00001360 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001361
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001362 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001363 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001364
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001365 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001366 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001367 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001368 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001369 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001370 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001371
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001372 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001373}
Bill Wendling4073ed52007-02-13 01:51:42 +00001374
Sebastian Redlc4704762008-11-11 11:37:55 +00001375/// ParseCXXTypeid - This handles the C++ typeid expression.
1376///
1377/// postfix-expression: [C++ 5.2p1]
1378/// 'typeid' '(' expression ')'
1379/// 'typeid' '(' type-id ')'
1380///
John McCalldadc5752010-08-24 06:29:42 +00001381ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001382 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1383
1384 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001385 SourceLocation LParenLoc, RParenLoc;
1386 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001387
1388 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001389 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001390 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001391 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001392
John McCalldadc5752010-08-24 06:29:42 +00001393 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001394
Richard Smith4f605af2012-08-18 00:55:03 +00001395 // C++0x [expr.typeid]p3:
1396 // When typeid is applied to an expression other than an lvalue of a
1397 // polymorphic class type [...] The expression is an unevaluated
1398 // operand (Clause 5).
1399 //
1400 // Note that we can't tell whether the expression is an lvalue of a
1401 // polymorphic class type until after we've parsed the expression; we
1402 // speculatively assume the subexpression is unevaluated, and fix it up
1403 // later.
1404 //
1405 // We enter the unevaluated context before trying to determine whether we
1406 // have a type-id, because the tentative parse logic will try to resolve
1407 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001408 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1409 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001410
Sebastian Redlc4704762008-11-11 11:37:55 +00001411 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001412 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001413
1414 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001415 T.consumeClose();
1416 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001417 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001418 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001419
1420 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001421 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001422 } else {
1423 Result = ParseExpression();
1424
1425 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001426 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001427 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001428 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001429 T.consumeClose();
1430 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001431 if (RParenLoc.isInvalid())
1432 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001433
Sebastian Redlc4704762008-11-11 11:37:55 +00001434 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001435 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001436 }
1437 }
1438
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001439 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001440}
1441
Francois Pichet9f4f2072010-09-08 12:20:18 +00001442/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1443///
1444/// '__uuidof' '(' expression ')'
1445/// '__uuidof' '(' type-id ')'
1446///
1447ExprResult Parser::ParseCXXUuidof() {
1448 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1449
1450 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001451 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001452
1453 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001454 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001455 return ExprError();
1456
1457 ExprResult Result;
1458
1459 if (isTypeIdInParens()) {
1460 TypeResult Ty = ParseTypeName();
1461
1462 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001463 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001464
1465 if (Ty.isInvalid())
1466 return ExprError();
1467
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001468 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1469 Ty.get().getAsOpaquePtr(),
1470 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001471 } else {
1472 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1473 Result = ParseExpression();
1474
1475 // Match the ')'.
1476 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001477 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001478 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001479 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001480
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001481 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1482 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001483 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001484 }
1485 }
1486
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001487 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001488}
1489
Douglas Gregore610ada2010-02-24 18:44:31 +00001490/// \brief Parse a C++ pseudo-destructor expression after the base,
1491/// . or -> operator, and nested-name-specifier have already been
1492/// parsed.
1493///
1494/// postfix-expression: [C++ 5.2]
1495/// postfix-expression . pseudo-destructor-name
1496/// postfix-expression -> pseudo-destructor-name
1497///
1498/// pseudo-destructor-name:
1499/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1500/// ::[opt] nested-name-specifier template simple-template-id ::
1501/// ~type-name
1502/// ::[opt] nested-name-specifier[opt] ~type-name
1503///
John McCalldadc5752010-08-24 06:29:42 +00001504ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001505Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001506 tok::TokenKind OpKind,
1507 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001508 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001509 // We're parsing either a pseudo-destructor-name or a dependent
1510 // member access that has the same form as a
1511 // pseudo-destructor-name. We parse both in the same way and let
1512 // the action model sort them out.
1513 //
1514 // Note that the ::[opt] nested-name-specifier[opt] has already
1515 // been parsed, and if there was a simple-template-id, it has
1516 // been coalesced into a template-id annotation token.
1517 UnqualifiedId FirstTypeName;
1518 SourceLocation CCLoc;
1519 if (Tok.is(tok::identifier)) {
1520 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1521 ConsumeToken();
1522 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1523 CCLoc = ConsumeToken();
1524 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001525 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1526 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001527 FirstTypeName.setTemplateId(
1528 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1529 ConsumeToken();
1530 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1531 CCLoc = ConsumeToken();
1532 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001533 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001534 }
1535
1536 // Parse the tilde.
1537 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1538 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001539
1540 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1541 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001542 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001543 if (DS.getTypeSpecType() == TST_error)
1544 return ExprError();
David Majnemerced8bdf2015-02-25 17:36:15 +00001545 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1546 TildeLoc, DS);
David Blaikie1d578782011-12-16 16:03:09 +00001547 }
1548
Douglas Gregore610ada2010-02-24 18:44:31 +00001549 if (!Tok.is(tok::identifier)) {
1550 Diag(Tok, diag::err_destructor_tilde_identifier);
1551 return ExprError();
1552 }
1553
1554 // Parse the second type.
1555 UnqualifiedId SecondTypeName;
1556 IdentifierInfo *Name = Tok.getIdentifierInfo();
1557 SourceLocation NameLoc = ConsumeToken();
1558 SecondTypeName.setIdentifier(Name, NameLoc);
1559
1560 // If there is a '<', the second type name is a template-id. Parse
1561 // it as such.
1562 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001563 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1564 Name, NameLoc,
1565 false, ObjectType, SecondTypeName,
1566 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001567 return ExprError();
1568
David Majnemerced8bdf2015-02-25 17:36:15 +00001569 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1570 SS, FirstTypeName, CCLoc, TildeLoc,
1571 SecondTypeName);
Douglas Gregore610ada2010-02-24 18:44:31 +00001572}
1573
Bill Wendling4073ed52007-02-13 01:51:42 +00001574/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1575///
1576/// boolean-literal: [C++ 2.13.5]
1577/// 'true'
1578/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001579ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001580 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001581 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001582}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001583
1584/// ParseThrowExpression - This handles the C++ throw expression.
1585///
1586/// throw-expression: [C++ 15]
1587/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001588ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001589 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001590 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001591
Chris Lattner65dd8432008-04-06 06:02:23 +00001592 // If the current token isn't the start of an assignment-expression,
1593 // then the expression is not present. This handles things like:
1594 // "C ? throw : (void)42", which is crazy but legal.
1595 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1596 case tok::semi:
1597 case tok::r_paren:
1598 case tok::r_square:
1599 case tok::r_brace:
1600 case tok::colon:
1601 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001602 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001603
Chris Lattner65dd8432008-04-06 06:02:23 +00001604 default:
John McCalldadc5752010-08-24 06:29:42 +00001605 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001606 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001607 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001608 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001609}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001610
Richard Smith0e304ea2015-10-22 04:46:14 +00001611/// \brief Parse the C++ Coroutines co_yield expression.
1612///
1613/// co_yield-expression:
1614/// 'co_yield' assignment-expression[opt]
1615ExprResult Parser::ParseCoyieldExpression() {
1616 assert(Tok.is(tok::kw_co_yield) && "Not co_yield!");
1617
1618 SourceLocation Loc = ConsumeToken();
Richard Smithae3d1472015-11-20 22:47:10 +00001619 ExprResult Expr = Tok.is(tok::l_brace) ? ParseBraceInitializer()
1620 : ParseAssignmentExpression();
Richard Smithcfd53b42015-10-22 06:13:50 +00001621 if (!Expr.isInvalid())
Richard Smith9f690bd2015-10-27 06:02:45 +00001622 Expr = Actions.ActOnCoyieldExpr(getCurScope(), Loc, Expr.get());
Richard Smith0e304ea2015-10-22 04:46:14 +00001623 return Expr;
1624}
1625
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001626/// ParseCXXThis - This handles the C++ 'this' pointer.
1627///
1628/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1629/// a non-lvalue expression whose value is the address of the object for which
1630/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001631ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001632 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1633 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001634 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001635}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001636
1637/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1638/// Can be interpreted either as function-style casting ("int(x)")
1639/// or class type construction ("ClassType(x,y,z)")
1640/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001641/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001642///
1643/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001644/// simple-type-specifier '(' expression-list[opt] ')'
1645/// [C++0x] simple-type-specifier braced-init-list
1646/// typename-specifier '(' expression-list[opt] ')'
1647/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001648///
Richard Smith600b5262017-01-26 20:40:47 +00001649/// In C++1z onwards, the type specifier can also be a template-name.
John McCalldadc5752010-08-24 06:29:42 +00001650ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001651Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Richard Smith600b5262017-01-26 20:40:47 +00001652 Declarator DeclaratorInfo(DS, Declarator::FunctionalCastContext);
John McCallba7bf592010-08-24 05:47:05 +00001653 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001654
Sebastian Redl3da34892011-06-05 12:23:16 +00001655 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001656 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001657 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001658
Sebastian Redl3da34892011-06-05 12:23:16 +00001659 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001660 ExprResult Init = ParseBraceInitializer();
1661 if (Init.isInvalid())
1662 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001663 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001664 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1665 MultiExprArg(&InitList, 1),
1666 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001667 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001668 BalancedDelimiterTracker T(*this, tok::l_paren);
1669 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001670
Benjamin Kramerf0623432012-08-23 22:51:59 +00001671 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001672 CommaLocsTy CommaLocs;
1673
1674 if (Tok.isNot(tok::r_paren)) {
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00001675 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1676 Actions.CodeCompleteConstructor(getCurScope(),
1677 TypeRep.get()->getCanonicalTypeInternal(),
1678 DS.getLocEnd(), Exprs);
1679 })) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001680 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001681 return ExprError();
1682 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001683 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001684
1685 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001686 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001687
1688 // TypeRep could be null, if it references an invalid typedef.
1689 if (!TypeRep)
1690 return ExprError();
1691
1692 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1693 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001694 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001695 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001696 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001697 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001698}
1699
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001700/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001701///
1702/// condition:
1703/// expression
1704/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001705/// [C++11] type-specifier-seq declarator '=' initializer-clause
1706/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001707/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1708/// '=' assignment-expression
1709///
Richard Smithc7a05a92016-06-29 21:17:59 +00001710/// In C++1z, a condition may in some contexts be preceded by an
1711/// optional init-statement. This function will parse that too.
1712///
1713/// \param InitStmt If non-null, an init-statement is permitted, and if present
1714/// will be parsed and stored here.
1715///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001716/// \param Loc The location of the start of the statement that requires this
1717/// condition, e.g., the "for" in a for loop.
1718///
Richard Smith03a4aa32016-06-23 19:02:52 +00001719/// \returns The parsed condition.
Richard Smithc7a05a92016-06-29 21:17:59 +00001720Sema::ConditionResult Parser::ParseCXXCondition(StmtResult *InitStmt,
1721 SourceLocation Loc,
Richard Smith03a4aa32016-06-23 19:02:52 +00001722 Sema::ConditionKind CK) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001723 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001724 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001725 cutOffParsing();
Richard Smith03a4aa32016-06-23 19:02:52 +00001726 return Sema::ConditionError();
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001727 }
1728
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001729 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001730 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001731
Richard Smithc7a05a92016-06-29 21:17:59 +00001732 // Determine what kind of thing we have.
1733 switch (isCXXConditionDeclarationOrInitStatement(InitStmt)) {
1734 case ConditionOrInitStatement::Expression: {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001735 ProhibitAttributes(attrs);
1736
Douglas Gregore60e41a2010-05-06 17:25:47 +00001737 // Parse the expression.
Richard Smith03a4aa32016-06-23 19:02:52 +00001738 ExprResult Expr = ParseExpression(); // expression
1739 if (Expr.isInvalid())
1740 return Sema::ConditionError();
Douglas Gregore60e41a2010-05-06 17:25:47 +00001741
Richard Smithc7a05a92016-06-29 21:17:59 +00001742 if (InitStmt && Tok.is(tok::semi)) {
1743 *InitStmt = Actions.ActOnExprStmt(Expr.get());
1744 ConsumeToken();
1745 return ParseCXXCondition(nullptr, Loc, CK);
1746 }
1747
Richard Smith03a4aa32016-06-23 19:02:52 +00001748 return Actions.ActOnCondition(getCurScope(), Loc, Expr.get(), CK);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001749 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001750
Richard Smithc7a05a92016-06-29 21:17:59 +00001751 case ConditionOrInitStatement::InitStmtDecl: {
Richard Smithfccb5122016-10-18 20:27:16 +00001752 Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z
1753 ? diag::warn_cxx14_compat_init_statement
1754 : diag::ext_init_statement)
1755 << (CK == Sema::ConditionKind::Switch);
Richard Smithc7a05a92016-06-29 21:17:59 +00001756 SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
1757 DeclGroupPtrTy DG = ParseSimpleDeclaration(
1758 Declarator::InitStmtContext, DeclEnd, attrs, /*RequireSemi=*/true);
1759 *InitStmt = Actions.ActOnDeclStmt(DG, DeclStart, DeclEnd);
1760 return ParseCXXCondition(nullptr, Loc, CK);
1761 }
1762
1763 case ConditionOrInitStatement::ConditionDecl:
1764 case ConditionOrInitStatement::Error:
1765 break;
1766 }
1767
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001768 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001769 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001770 DS.takeAttributesFrom(attrs);
Meador Ingef0af05c2015-06-25 22:06:40 +00001771 ParseSpecifierQualifierList(DS, AS_none, DSC_condition);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001772
1773 // declarator
1774 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1775 ParseDeclarator(DeclaratorInfo);
1776
1777 // simple-asm-expr[opt]
1778 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001779 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001780 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001781 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001782 SkipUntil(tok::semi, StopAtSemi);
Richard Smith03a4aa32016-06-23 19:02:52 +00001783 return Sema::ConditionError();
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001784 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001785 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001786 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001787 }
1788
1789 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001790 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001791
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001792 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001793 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001794 DeclaratorInfo);
Richard Smith03a4aa32016-06-23 19:02:52 +00001795 if (Dcl.isInvalid())
1796 return Sema::ConditionError();
1797 Decl *DeclOut = Dcl.get();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001798
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001799 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001800 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001801 bool CopyInitialization = isTokenEqualOrEqualTypo();
1802 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001803 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001804
1805 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001806 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001807 Diag(Tok.getLocation(),
1808 diag::warn_cxx98_compat_generalized_initializer_lists);
1809 InitExpr = ParseBraceInitializer();
1810 } else if (CopyInitialization) {
1811 InitExpr = ParseAssignmentExpression();
1812 } else if (Tok.is(tok::l_paren)) {
1813 // This was probably an attempt to initialize the variable.
1814 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001815 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001816 RParen = ConsumeParen();
Richard Smith03a4aa32016-06-23 19:02:52 +00001817 Diag(DeclOut->getLocation(),
Richard Smith2a15b742012-02-22 06:49:09 +00001818 diag::err_expected_init_in_condition_lparen)
1819 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001820 } else {
Richard Smith03a4aa32016-06-23 19:02:52 +00001821 Diag(DeclOut->getLocation(), diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001822 }
Richard Smith2a15b742012-02-22 06:49:09 +00001823
1824 if (!InitExpr.isInvalid())
Richard Smith3beb7c62017-01-12 02:27:38 +00001825 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization);
Richard Smith27d807c2013-04-30 13:56:41 +00001826 else
1827 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001828
Richard Smithb2bc2e62011-02-21 20:05:19 +00001829 Actions.FinalizeDeclaration(DeclOut);
Richard Smith03a4aa32016-06-23 19:02:52 +00001830 return Actions.ActOnConditionVariable(DeclOut, Loc, CK);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001831}
1832
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001833/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1834/// This should only be called when the current token is known to be part of
1835/// simple-type-specifier.
1836///
1837/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001838/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001839/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1840/// char
1841/// wchar_t
1842/// bool
1843/// short
1844/// int
1845/// long
1846/// signed
1847/// unsigned
1848/// float
1849/// double
1850/// void
1851/// [GNU] typeof-specifier
1852/// [C++0x] auto [TODO]
1853///
1854/// type-name:
1855/// class-name
1856/// enum-name
1857/// typedef-name
1858///
1859void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1860 DS.SetRangeStart(Tok.getLocation());
1861 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001862 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001863 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001864 const clang::PrintingPolicy &Policy =
1865 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001866
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001867 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001868 case tok::identifier: // foo::bar
1869 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001870 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001871 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001872 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001873
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001874 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001875 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001876 if (getTypeAnnotation(Tok))
1877 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001878 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001879 else
1880 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001881
1882 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1883 ConsumeToken();
1884
Craig Topper25122412015-11-15 03:32:11 +00001885 DS.Finish(Actions, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001886 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001887 }
Mike Stump11289f42009-09-09 15:08:12 +00001888
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001889 // builtin types
1890 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001891 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001892 break;
1893 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001894 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001895 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001896 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001897 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001898 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001899 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001900 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001901 break;
1902 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001903 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001904 break;
1905 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001906 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001907 break;
1908 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001909 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001910 break;
1911 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001912 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001913 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001914 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001915 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001916 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001917 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001918 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001919 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001920 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001921 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001922 break;
1923 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001924 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001925 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00001926 case tok::kw___float128:
1927 DS.SetTypeSpecType(DeclSpec::TST_float128, Loc, PrevSpec, DiagID, Policy);
1928 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001929 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001930 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001931 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001932 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001933 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001934 break;
1935 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001936 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001937 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001938 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001939 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001940 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001941 case tok::annot_decltype:
1942 case tok::kw_decltype:
1943 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Craig Topper25122412015-11-15 03:32:11 +00001944 return DS.Finish(Actions, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001945
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001946 // GNU typeof support.
1947 case tok::kw_typeof:
1948 ParseTypeofSpecifier(DS);
Craig Topper25122412015-11-15 03:32:11 +00001949 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001950 return;
1951 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001952 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001953 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1954 else
1955 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001956 ConsumeToken();
Craig Topper25122412015-11-15 03:32:11 +00001957 DS.Finish(Actions, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001958}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001959
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001960/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1961/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1962/// e.g., "const short int". Note that the DeclSpec is *not* finished
1963/// by parsing the type-specifier-seq, because these sequences are
1964/// typically followed by some form of declarator. Returns true and
1965/// emits diagnostics if this is not a type-specifier-seq, false
1966/// otherwise.
1967///
1968/// type-specifier-seq: [C++ 8.1]
1969/// type-specifier type-specifier-seq[opt]
1970///
1971bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001972 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Craig Topper25122412015-11-15 03:32:11 +00001973 DS.Finish(Actions, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001974 return false;
1975}
1976
Douglas Gregor7861a802009-11-03 01:35:08 +00001977/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1978/// some form.
1979///
1980/// This routine is invoked when a '<' is encountered after an identifier or
1981/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1982/// whether the unqualified-id is actually a template-id. This routine will
1983/// then parse the template arguments and form the appropriate template-id to
1984/// return to the caller.
1985///
1986/// \param SS the nested-name-specifier that precedes this template-id, if
1987/// we're actually parsing a qualified-id.
1988///
1989/// \param Name for constructor and destructor names, this is the actual
1990/// identifier that may be a template-name.
1991///
1992/// \param NameLoc the location of the class-name in a constructor or
1993/// destructor.
1994///
1995/// \param EnteringContext whether we're entering the scope of the
1996/// nested-name-specifier.
1997///
Douglas Gregor127ea592009-11-03 21:24:04 +00001998/// \param ObjectType if this unqualified-id occurs within a member access
1999/// expression, the type of the base object whose member is being accessed.
2000///
Douglas Gregor7861a802009-11-03 01:35:08 +00002001/// \param Id as input, describes the template-name or operator-function-id
2002/// that precedes the '<'. If template arguments were parsed successfully,
2003/// will be updated with the template-id.
2004///
Douglas Gregore610ada2010-02-24 18:44:31 +00002005/// \param AssumeTemplateId When true, this routine will assume that the name
2006/// refers to a template without performing name lookup to verify.
2007///
Douglas Gregor7861a802009-11-03 01:35:08 +00002008/// \returns true if a parse error occurred, false otherwise.
2009bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002010 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002011 IdentifierInfo *Name,
2012 SourceLocation NameLoc,
2013 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002014 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00002015 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002016 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002017 assert((AssumeTemplateId || Tok.is(tok::less)) &&
2018 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00002019
2020 TemplateTy Template;
2021 TemplateNameKind TNK = TNK_Non_template;
2022 switch (Id.getKind()) {
2023 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00002024 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00002025 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00002026 if (AssumeTemplateId) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002027 // We defer the injected-class-name checks until we've found whether
2028 // this template-id is used to form a nested-name-specifier or not.
2029 TNK = Actions.ActOnDependentTemplateName(
2030 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2031 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002032 if (TNK == TNK_Non_template)
2033 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00002034 } else {
2035 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002036 TNK = Actions.isTemplateName(getCurScope(), SS,
2037 TemplateKWLoc.isValid(), Id,
2038 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00002039 MemberOfUnknownSpecialization);
2040
2041 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
2042 ObjectType && IsTemplateArgumentList()) {
2043 // We have something like t->getAs<T>(), where getAs is a
2044 // member of an unknown specialization. However, this will only
2045 // parse correctly as a template, so suggest the keyword 'template'
2046 // before 'getAs' and treat this as a dependent template name.
2047 std::string Name;
2048 if (Id.getKind() == UnqualifiedId::IK_Identifier)
2049 Name = Id.Identifier->getName();
2050 else {
2051 Name = "operator ";
2052 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
2053 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
2054 else
2055 Name += Id.Identifier->getName();
2056 }
2057 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
2058 << Name
2059 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Richard Smithfd3dae02017-01-20 00:20:39 +00002060 TNK = Actions.ActOnDependentTemplateName(
2061 getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext,
2062 Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002063 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00002064 return true;
2065 }
2066 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002067 break;
2068
Douglas Gregor3cf81312009-11-03 23:16:33 +00002069 case UnqualifiedId::IK_ConstructorName: {
2070 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002071 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002072 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002073 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2074 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002075 EnteringContext, Template,
2076 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00002077 break;
2078 }
2079
Douglas Gregor3cf81312009-11-03 23:16:33 +00002080 case UnqualifiedId::IK_DestructorName: {
2081 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00002082 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002083 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002084 if (ObjectType) {
Richard Smithfd3dae02017-01-20 00:20:39 +00002085 TNK = Actions.ActOnDependentTemplateName(
2086 getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType,
2087 EnteringContext, Template, /*AllowInjectedClassName*/ true);
Douglas Gregorbb119652010-06-16 23:00:59 +00002088 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002089 return true;
2090 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00002091 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2092 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00002093 EnteringContext, Template,
2094 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002095
John McCallba7bf592010-08-24 05:47:05 +00002096 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002097 Diag(NameLoc, diag::err_destructor_template_id)
2098 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002099 return true;
2100 }
2101 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002102 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002103 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002104
2105 default:
2106 return false;
2107 }
2108
2109 if (TNK == TNK_Non_template)
2110 return false;
2111
2112 // Parse the enclosed template argument list.
2113 SourceLocation LAngleLoc, RAngleLoc;
2114 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002115 if (Tok.is(tok::less) &&
2116 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002117 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002118 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002119 RAngleLoc))
2120 return true;
2121
2122 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002123 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2124 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002125 // Form a parsed representation of the template-id to be stored in the
2126 // UnqualifiedId.
2127 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002128 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002129
Richard Smith72bfbd82013-12-04 00:28:23 +00002130 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002131 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2132 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002133 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002134 TemplateId->TemplateNameLoc = Id.StartLocation;
2135 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002136 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002137 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2138 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002139 }
2140
Douglas Gregore7c20652011-03-02 00:47:37 +00002141 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002142 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002143 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002144 TemplateId->Kind = TNK;
2145 TemplateId->LAngleLoc = LAngleLoc;
2146 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002147 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002148 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002149 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002150 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002151
2152 Id.setTemplateId(TemplateId);
2153 return false;
2154 }
2155
2156 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002157 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002158
Douglas Gregor7861a802009-11-03 01:35:08 +00002159 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002160 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002161 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
Richard Smith74f02342017-01-19 21:00:13 +00002162 Template, Name, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002163 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2164 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002165 if (Type.isInvalid())
2166 return true;
2167
2168 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2169 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2170 else
2171 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2172
2173 return false;
2174}
2175
Douglas Gregor71395fa2009-11-04 00:56:37 +00002176/// \brief Parse an operator-function-id or conversion-function-id as part
2177/// of a C++ unqualified-id.
2178///
2179/// This routine is responsible only for parsing the operator-function-id or
2180/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002181///
2182/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002183/// operator-function-id: [C++ 13.5]
2184/// 'operator' operator
2185///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002186/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002187/// new delete new[] delete[]
2188/// + - * / % ^ & | ~
2189/// ! = < > += -= *= /= %=
2190/// ^= &= |= << >> >>= <<= == !=
2191/// <= >= && || ++ -- , ->* ->
2192/// () []
2193///
2194/// conversion-function-id: [C++ 12.3.2]
2195/// operator conversion-type-id
2196///
2197/// conversion-type-id:
2198/// type-specifier-seq conversion-declarator[opt]
2199///
2200/// conversion-declarator:
2201/// ptr-operator conversion-declarator[opt]
2202/// \endcode
2203///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002204/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002205/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2206///
2207/// \param EnteringContext whether we are entering the scope of the
2208/// nested-name-specifier.
2209///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002210/// \param ObjectType if this unqualified-id occurs within a member access
2211/// expression, the type of the base object whose member is being accessed.
2212///
2213/// \param Result on a successful parse, contains the parsed unqualified-id.
2214///
2215/// \returns true if parsing fails, false otherwise.
2216bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002217 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002218 UnqualifiedId &Result) {
2219 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2220
2221 // Consume the 'operator' keyword.
2222 SourceLocation KeywordLoc = ConsumeToken();
2223
2224 // Determine what kind of operator name we have.
2225 unsigned SymbolIdx = 0;
2226 SourceLocation SymbolLocations[3];
2227 OverloadedOperatorKind Op = OO_None;
2228 switch (Tok.getKind()) {
2229 case tok::kw_new:
2230 case tok::kw_delete: {
2231 bool isNew = Tok.getKind() == tok::kw_new;
2232 // Consume the 'new' or 'delete'.
2233 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002234 // Check for array new/delete.
2235 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002236 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002237 // Consume the '[' and ']'.
2238 BalancedDelimiterTracker T(*this, tok::l_square);
2239 T.consumeOpen();
2240 T.consumeClose();
2241 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002242 return true;
2243
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002244 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2245 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002246 Op = isNew? OO_Array_New : OO_Array_Delete;
2247 } else {
2248 Op = isNew? OO_New : OO_Delete;
2249 }
2250 break;
2251 }
2252
2253#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2254 case tok::Token: \
2255 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2256 Op = OO_##Name; \
2257 break;
2258#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2259#include "clang/Basic/OperatorKinds.def"
2260
2261 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002262 // Consume the '(' and ')'.
2263 BalancedDelimiterTracker T(*this, tok::l_paren);
2264 T.consumeOpen();
2265 T.consumeClose();
2266 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002267 return true;
2268
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002269 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2270 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002271 Op = OO_Call;
2272 break;
2273 }
2274
2275 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002276 // Consume the '[' and ']'.
2277 BalancedDelimiterTracker T(*this, tok::l_square);
2278 T.consumeOpen();
2279 T.consumeClose();
2280 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002281 return true;
2282
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002283 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2284 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002285 Op = OO_Subscript;
2286 break;
2287 }
2288
2289 case tok::code_completion: {
2290 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002291 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002292 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002293 // Don't try to parse any further.
2294 return true;
2295 }
2296
2297 default:
2298 break;
2299 }
2300
2301 if (Op != OO_None) {
2302 // We have parsed an operator-function-id.
2303 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2304 return false;
2305 }
Alexis Hunt34458502009-11-28 04:44:28 +00002306
2307 // Parse a literal-operator-id.
2308 //
Richard Smith6f212062012-10-20 08:41:10 +00002309 // literal-operator-id: C++11 [over.literal]
2310 // operator string-literal identifier
2311 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002312
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002313 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002314 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002315
Richard Smith7d182a72012-03-08 23:06:02 +00002316 SourceLocation DiagLoc;
2317 unsigned DiagId = 0;
2318
2319 // We're past translation phase 6, so perform string literal concatenation
2320 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002321 SmallVector<Token, 4> Toks;
2322 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002323 while (isTokenStringLiteral()) {
2324 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002325 // C++11 [over.literal]p1:
2326 // The string-literal or user-defined-string-literal in a
2327 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002328 DiagLoc = Tok.getLocation();
2329 DiagId = diag::err_literal_operator_string_prefix;
2330 }
2331 Toks.push_back(Tok);
2332 TokLocs.push_back(ConsumeStringToken());
2333 }
2334
Craig Topper9d5583e2014-06-26 04:58:39 +00002335 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002336 if (Literal.hadError)
2337 return true;
2338
2339 // Grab the literal operator's suffix, which will be either the next token
2340 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002341 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002342 SourceLocation SuffixLoc;
2343 if (!Literal.getUDSuffix().empty()) {
2344 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2345 SuffixLoc =
2346 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2347 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002348 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002349 } else if (Tok.is(tok::identifier)) {
2350 II = Tok.getIdentifierInfo();
2351 SuffixLoc = ConsumeToken();
2352 TokLocs.push_back(SuffixLoc);
2353 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002354 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002355 return true;
2356 }
2357
Richard Smith7d182a72012-03-08 23:06:02 +00002358 // The string literal must be empty.
2359 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002360 // C++11 [over.literal]p1:
2361 // The string-literal or user-defined-string-literal in a
2362 // literal-operator-id shall [...] contain no characters
2363 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002364 DiagLoc = TokLocs.front();
2365 DiagId = diag::err_literal_operator_string_not_empty;
2366 }
2367
2368 if (DiagId) {
2369 // This isn't a valid literal-operator-id, but we think we know
2370 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002371 SmallString<32> Str;
Richard Smithe87aeb32015-10-08 00:17:59 +00002372 Str += "\"\"";
Richard Smith7d182a72012-03-08 23:06:02 +00002373 Str += II->getName();
2374 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2375 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2376 }
2377
2378 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002379
2380 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002381 }
Richard Smithd091dc12013-12-05 00:58:33 +00002382
Douglas Gregor71395fa2009-11-04 00:56:37 +00002383 // Parse a conversion-function-id.
2384 //
2385 // conversion-function-id: [C++ 12.3.2]
2386 // operator conversion-type-id
2387 //
2388 // conversion-type-id:
2389 // type-specifier-seq conversion-declarator[opt]
2390 //
2391 // conversion-declarator:
2392 // ptr-operator conversion-declarator[opt]
2393
2394 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002395 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002396 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002397 return true;
2398
2399 // Parse the conversion-declarator, which is merely a sequence of
2400 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002401 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002402 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2403
Douglas Gregor71395fa2009-11-04 00:56:37 +00002404 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002405 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002406 if (Ty.isInvalid())
2407 return true;
2408
2409 // Note that this is a conversion-function-id.
2410 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2411 D.getSourceRange().getEnd());
2412 return false;
2413}
2414
2415/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2416/// name of an entity.
2417///
2418/// \code
2419/// unqualified-id: [C++ expr.prim.general]
2420/// identifier
2421/// operator-function-id
2422/// conversion-function-id
2423/// [C++0x] literal-operator-id [TODO]
2424/// ~ class-name
2425/// template-id
2426///
2427/// \endcode
2428///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002429/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002430/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2431///
2432/// \param EnteringContext whether we are entering the scope of the
2433/// nested-name-specifier.
2434///
Douglas Gregor7861a802009-11-03 01:35:08 +00002435/// \param AllowDestructorName whether we allow parsing of a destructor name.
2436///
2437/// \param AllowConstructorName whether we allow parsing a constructor name.
2438///
Richard Smith35845152017-02-07 01:37:30 +00002439/// \param AllowDeductionGuide whether we allow parsing a deduction guide name.
2440///
Douglas Gregor127ea592009-11-03 21:24:04 +00002441/// \param ObjectType if this unqualified-id occurs within a member access
2442/// expression, the type of the base object whose member is being accessed.
2443///
Douglas Gregor7861a802009-11-03 01:35:08 +00002444/// \param Result on a successful parse, contains the parsed unqualified-id.
2445///
2446/// \returns true if parsing fails, false otherwise.
2447bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2448 bool AllowDestructorName,
2449 bool AllowConstructorName,
Richard Smith35845152017-02-07 01:37:30 +00002450 bool AllowDeductionGuide,
John McCallba7bf592010-08-24 05:47:05 +00002451 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002452 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002453 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002454
2455 // Handle 'A::template B'. This is for template-ids which have not
2456 // already been annotated by ParseOptionalCXXScopeSpecifier().
2457 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002458 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002459 (ObjectType || SS.isSet())) {
2460 TemplateSpecified = true;
2461 TemplateKWLoc = ConsumeToken();
2462 }
2463
Douglas Gregor7861a802009-11-03 01:35:08 +00002464 // unqualified-id:
2465 // identifier
2466 // template-id (when it hasn't already been annotated)
2467 if (Tok.is(tok::identifier)) {
2468 // Consume the identifier.
2469 IdentifierInfo *Id = Tok.getIdentifierInfo();
2470 SourceLocation IdLoc = ConsumeToken();
2471
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002473 // If we're not in C++, only identifiers matter. Record the
2474 // identifier and return.
2475 Result.setIdentifier(Id, IdLoc);
2476 return false;
2477 }
2478
Richard Smith35845152017-02-07 01:37:30 +00002479 ParsedTemplateTy TemplateName;
Douglas Gregor7861a802009-11-03 01:35:08 +00002480 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002481 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002482 // We have parsed a constructor name.
David Blaikieefdccaa2016-01-15 23:43:34 +00002483 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false,
2484 false, nullptr,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002485 /*IsCtorOrDtorName=*/true,
2486 /*NonTrivialTypeSourceInfo=*/true);
2487 Result.setConstructorName(Ty, IdLoc, IdLoc);
Richard Smith35845152017-02-07 01:37:30 +00002488 } else if (getLangOpts().CPlusPlus1z &&
2489 AllowDeductionGuide && SS.isEmpty() &&
2490 Actions.isDeductionGuideName(getCurScope(), *Id, IdLoc,
2491 &TemplateName)) {
2492 // We have parsed a template-name naming a deduction guide.
2493 Result.setDeductionGuideName(TemplateName, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002494 } else {
2495 // We have parsed an identifier.
2496 Result.setIdentifier(Id, IdLoc);
2497 }
2498
2499 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002500 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002501 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2502 EnteringContext, ObjectType,
2503 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002504
2505 return false;
2506 }
2507
2508 // unqualified-id:
2509 // template-id (already parsed and annotated)
2510 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002511 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002512
2513 // If the template-name names the current class, then this is a constructor
2514 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002515 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002516 if (SS.isSet()) {
2517 // C++ [class.qual]p2 specifies that a qualified template-name
2518 // is taken as the constructor name where a constructor can be
2519 // declared. Thus, the template arguments are extraneous, so
2520 // complain about them and remove them entirely.
2521 Diag(TemplateId->TemplateNameLoc,
2522 diag::err_out_of_line_constructor_template_id)
2523 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002524 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002525 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
David Blaikieefdccaa2016-01-15 23:43:34 +00002526 ParsedType Ty =
2527 Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc,
2528 getCurScope(), &SS, false, false, nullptr,
2529 /*IsCtorOrDtorName=*/true,
2530 /*NontrivialTypeSourceInfo=*/true);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002531 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002532 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002533 ConsumeToken();
2534 return false;
2535 }
2536
2537 Result.setConstructorTemplateId(TemplateId);
2538 ConsumeToken();
2539 return false;
2540 }
2541
Douglas Gregor7861a802009-11-03 01:35:08 +00002542 // We have already parsed a template-id; consume the annotation token as
2543 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002544 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002545 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002546 ConsumeToken();
2547 return false;
2548 }
2549
2550 // unqualified-id:
2551 // operator-function-id
2552 // conversion-function-id
2553 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002554 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002555 return true;
2556
Alexis Hunted0530f2009-11-28 08:58:14 +00002557 // If we have an operator-function-id or a literal-operator-id and the next
2558 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002559 //
2560 // template-id:
2561 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002562 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2563 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002564 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002565 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002566 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002567 EnteringContext, ObjectType,
2568 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002569
Douglas Gregor7861a802009-11-03 01:35:08 +00002570 return false;
2571 }
2572
David Blaikiebbafb8a2012-03-11 07:00:24 +00002573 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002574 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002575 // C++ [expr.unary.op]p10:
2576 // There is an ambiguity in the unary-expression ~X(), where X is a
2577 // class-name. The ambiguity is resolved in favor of treating ~ as a
2578 // unary complement rather than treating ~X as referring to a destructor.
2579
2580 // Parse the '~'.
2581 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002582
2583 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2584 DeclSpec DS(AttrFactory);
2585 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Richard Smithef2cd8f2017-02-08 20:39:08 +00002586 if (ParsedType Type =
2587 Actions.getDestructorTypeForDecltype(DS, ObjectType)) {
David Blaikieecd8a942011-12-08 16:13:53 +00002588 Result.setDestructorName(TildeLoc, Type, EndLoc);
2589 return false;
2590 }
2591 return true;
2592 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002593
2594 // Parse the class-name.
2595 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002596 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002597 return true;
2598 }
2599
Richard Smithefa6f732014-09-06 02:06:12 +00002600 // If the user wrote ~T::T, correct it to T::~T.
Richard Smith64e033f2015-01-15 00:48:52 +00002601 DeclaratorScopeObj DeclScopeObj(*this, SS);
Nico Weber10d02b52015-02-02 04:18:38 +00002602 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Nico Weberf9e37be2015-01-30 16:53:11 +00002603 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2604 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2605 // it will confuse this recovery logic.
2606 ColonProtectionRAIIObject ColonRAII(*this, false);
2607
Richard Smithefa6f732014-09-06 02:06:12 +00002608 if (SS.isSet()) {
2609 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2610 SS.clear();
2611 }
2612 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2613 return true;
Nico Weber7f8ec522015-02-02 05:33:50 +00002614 if (SS.isNotEmpty())
David Blaikieefdccaa2016-01-15 23:43:34 +00002615 ObjectType = nullptr;
Nico Weberd0045862015-01-30 04:05:15 +00002616 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
Benjamin Kramer3012e592015-03-29 14:35:39 +00002617 !SS.isSet()) {
Richard Smithefa6f732014-09-06 02:06:12 +00002618 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2619 return true;
2620 }
2621
2622 // Recover as if the tilde had been written before the identifier.
2623 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2624 << FixItHint::CreateRemoval(TildeLoc)
2625 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Richard Smith64e033f2015-01-15 00:48:52 +00002626
2627 // Temporarily enter the scope for the rest of this function.
2628 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2629 DeclScopeObj.EnterDeclaratorScope();
Richard Smithefa6f732014-09-06 02:06:12 +00002630 }
2631
Douglas Gregor7861a802009-11-03 01:35:08 +00002632 // Parse the class-name (or template-name in a simple-template-id).
2633 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2634 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002635
Douglas Gregorb22ee882010-05-05 05:58:24 +00002636 if (TemplateSpecified || Tok.is(tok::less)) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002637 Result.setDestructorName(TildeLoc, nullptr, ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002638 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2639 ClassName, ClassNameLoc,
2640 EnteringContext, ObjectType,
2641 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002642 }
Richard Smithefa6f732014-09-06 02:06:12 +00002643
Douglas Gregor7861a802009-11-03 01:35:08 +00002644 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002645 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2646 ClassNameLoc, getCurScope(),
2647 SS, ObjectType,
2648 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002649 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002650 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002651
Douglas Gregor7861a802009-11-03 01:35:08 +00002652 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002653 return false;
2654 }
2655
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002656 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002657 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002658 return true;
2659}
2660
Sebastian Redlbd150f42008-11-21 19:14:01 +00002661/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2662/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002663///
Chris Lattner109faf22009-01-04 21:25:24 +00002664/// This method is called to parse the new expression after the optional :: has
2665/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2666/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002667///
2668/// new-expression:
2669/// '::'[opt] 'new' new-placement[opt] new-type-id
2670/// new-initializer[opt]
2671/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2672/// new-initializer[opt]
2673///
2674/// new-placement:
2675/// '(' expression-list ')'
2676///
Sebastian Redl351bb782008-12-02 14:43:59 +00002677/// new-type-id:
2678/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002679/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002680///
2681/// new-declarator:
2682/// ptr-operator new-declarator[opt]
2683/// direct-new-declarator
2684///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002685/// new-initializer:
2686/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002687/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002688///
John McCalldadc5752010-08-24 06:29:42 +00002689ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002690Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2691 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2692 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002693
2694 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2695 // second form of new-expression. It can't be a new-type-id.
2696
Benjamin Kramerf0623432012-08-23 22:51:59 +00002697 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002698 SourceLocation PlacementLParen, PlacementRParen;
2699
Douglas Gregorf2753b32010-07-13 15:54:32 +00002700 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002701 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002702 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002703 if (Tok.is(tok::l_paren)) {
2704 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002705 BalancedDelimiterTracker T(*this, tok::l_paren);
2706 T.consumeOpen();
2707 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002708 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
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
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002713 T.consumeClose();
2714 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002715 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002716 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002717 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002718 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002719
Sebastian Redl351bb782008-12-02 14:43:59 +00002720 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002721 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002722 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002723 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002724 } else {
2725 // We still need the type.
2726 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002727 BalancedDelimiterTracker T(*this, tok::l_paren);
2728 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002729 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002730 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002731 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002732 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002733 T.consumeClose();
2734 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002735 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002736 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002737 if (ParseCXXTypeSpecifierSeq(DS))
2738 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002739 else {
2740 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002741 ParseDeclaratorInternal(DeclaratorInfo,
2742 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002743 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002744 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002745 }
2746 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002747 // A new-type-id is a simplified type-id, where essentially the
2748 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002749 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002750 if (ParseCXXTypeSpecifierSeq(DS))
2751 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002752 else {
2753 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002754 ParseDeclaratorInternal(DeclaratorInfo,
2755 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002756 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002757 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002758 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002759 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002760 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002761 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002762
Sebastian Redl6047f072012-02-16 12:22:20 +00002763 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002764
2765 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002766 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002767 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002768 BalancedDelimiterTracker T(*this, tok::l_paren);
2769 T.consumeOpen();
2770 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002771 if (Tok.isNot(tok::r_paren)) {
2772 CommaLocsTy CommaLocs;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00002773 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2774 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2775 DeclaratorInfo).get();
2776 Actions.CodeCompleteConstructor(getCurScope(),
2777 TypeRep.get()->getCanonicalTypeInternal(),
2778 DeclaratorInfo.getLocEnd(),
2779 ConstructorArgs);
2780 })) {
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 Redlbd150f42008-11-21 19:14:01 +00002784 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002785 T.consumeClose();
2786 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002787 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002788 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002789 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002790 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002791 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2792 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002793 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002794 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002795 Diag(Tok.getLocation(),
2796 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002797 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002798 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002799 if (Initializer.isInvalid())
2800 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002801
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002802 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002803 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002804 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002805}
2806
Sebastian Redlbd150f42008-11-21 19:14:01 +00002807/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2808/// passed to ParseDeclaratorInternal.
2809///
2810/// direct-new-declarator:
2811/// '[' expression ']'
2812/// direct-new-declarator '[' constant-expression ']'
2813///
Chris Lattner109faf22009-01-04 21:25:24 +00002814void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002815 // Parse the array dimensions.
2816 bool first = true;
2817 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002818 // An array-size expression can't start with a lambda.
2819 if (CheckProhibitedCXX11Attribute())
2820 continue;
2821
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002822 BalancedDelimiterTracker T(*this, tok::l_square);
2823 T.consumeOpen();
2824
John McCalldadc5752010-08-24 06:29:42 +00002825 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002826 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002827 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002828 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002829 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002830 return;
2831 }
2832 first = false;
2833
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002834 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002835
Bill Wendling44426052012-12-20 19:22:21 +00002836 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002837 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002838 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002839
John McCall084e83d2011-03-24 11:26:52 +00002840 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002841 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002842 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002843 T.getOpenLocation(),
2844 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002845 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002846
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002847 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002848 return;
2849 }
2850}
2851
2852/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2853/// This ambiguity appears in the syntax of the C++ new operator.
2854///
2855/// new-expression:
2856/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2857/// new-initializer[opt]
2858///
2859/// new-placement:
2860/// '(' expression-list ')'
2861///
John McCall37ad5512010-08-23 06:44:23 +00002862bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002863 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002864 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002865 // The '(' was already consumed.
2866 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002867 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002868 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002869 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002870 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002871 }
2872
2873 // It's not a type, it has to be an expression list.
2874 // Discard the comma locations - ActOnCXXNew has enough parameters.
2875 CommaLocsTy CommaLocs;
2876 return ParseExpressionList(PlacementArgs, CommaLocs);
2877}
2878
2879/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2880/// to free memory allocated by new.
2881///
Chris Lattner109faf22009-01-04 21:25:24 +00002882/// This method is called to parse the 'delete' expression after the optional
2883/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2884/// and "Start" is its location. Otherwise, "Start" is the location of the
2885/// 'delete' token.
2886///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002887/// delete-expression:
2888/// '::'[opt] 'delete' cast-expression
2889/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002890ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002891Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2892 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2893 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002894
2895 // Array delete?
2896 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002897 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002898 // C++11 [expr.delete]p1:
2899 // Whenever the delete keyword is followed by empty square brackets, it
2900 // shall be interpreted as [array delete].
2901 // [Footnote: A lambda expression with a lambda-introducer that consists
2902 // of empty square brackets can follow the delete keyword if
2903 // the lambda expression is enclosed in parentheses.]
2904 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2905 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002906 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002907 BalancedDelimiterTracker T(*this, tok::l_square);
2908
2909 T.consumeOpen();
2910 T.consumeClose();
2911 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002912 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002913 }
2914
John McCalldadc5752010-08-24 06:29:42 +00002915 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002916 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002917 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002918
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002919 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002920}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002921
Douglas Gregor29c42f22012-02-24 07:38:34 +00002922static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2923 switch (kind) {
2924 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002925#define TYPE_TRAIT_1(Spelling, Name, Key) \
2926case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002927#define TYPE_TRAIT_2(Spelling, Name, Key) \
2928case tok::kw_ ## Spelling: return BTT_ ## Name;
2929#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002930#define TYPE_TRAIT_N(Spelling, Name, Key) \
2931 case tok::kw_ ## Spelling: return TT_ ## Name;
2932#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002933 }
2934}
2935
John Wiegley6242b6a2011-04-28 00:16:57 +00002936static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2937 switch(kind) {
2938 default: llvm_unreachable("Not a known binary type trait");
2939 case tok::kw___array_rank: return ATT_ArrayRank;
2940 case tok::kw___array_extent: return ATT_ArrayExtent;
2941 }
2942}
2943
John Wiegleyf9f65842011-04-25 06:54:41 +00002944static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2945 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002946 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002947 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2948 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2949 }
2950}
2951
Alp Toker40f9b1c2013-12-12 21:23:03 +00002952static unsigned TypeTraitArity(tok::TokenKind kind) {
2953 switch (kind) {
2954 default: llvm_unreachable("Not a known type trait");
2955#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2956#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002957 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002958}
2959
Douglas Gregor29c42f22012-02-24 07:38:34 +00002960/// \brief Parse the built-in type-trait pseudo-functions that allow
2961/// implementation of the TR1/C++11 type traits templates.
2962///
2963/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002964/// unary-type-trait '(' type-id ')'
2965/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002966/// type-trait '(' type-id-seq ')'
2967///
2968/// type-id-seq:
2969/// type-id ...[opt] type-id-seq[opt]
2970///
2971ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002972 tok::TokenKind Kind = Tok.getKind();
2973 unsigned Arity = TypeTraitArity(Kind);
2974
Douglas Gregor29c42f22012-02-24 07:38:34 +00002975 SourceLocation Loc = ConsumeToken();
2976
2977 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002978 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002979 return ExprError();
2980
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002981 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002982 do {
2983 // Parse the next type.
2984 TypeResult Ty = ParseTypeName();
2985 if (Ty.isInvalid()) {
2986 Parens.skipToEnd();
2987 return ExprError();
2988 }
2989
2990 // Parse the ellipsis, if present.
2991 if (Tok.is(tok::ellipsis)) {
2992 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2993 if (Ty.isInvalid()) {
2994 Parens.skipToEnd();
2995 return ExprError();
2996 }
2997 }
2998
2999 // Add this type to the list of arguments.
3000 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00003001 } while (TryConsumeToken(tok::comma));
3002
Douglas Gregor29c42f22012-02-24 07:38:34 +00003003 if (Parens.consumeClose())
3004 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00003005
3006 SourceLocation EndLoc = Parens.getCloseLocation();
3007
3008 if (Arity && Args.size() != Arity) {
3009 Diag(EndLoc, diag::err_type_trait_arity)
3010 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
3011 return ExprError();
3012 }
3013
3014 if (!Arity && Args.empty()) {
3015 Diag(EndLoc, diag::err_type_trait_arity)
3016 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
3017 return ExprError();
3018 }
3019
Alp Toker88f64e62013-12-13 21:19:30 +00003020 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00003021}
3022
John Wiegley6242b6a2011-04-28 00:16:57 +00003023/// ParseArrayTypeTrait - Parse the built-in array type-trait
3024/// pseudo-functions.
3025///
3026/// primary-expression:
3027/// [Embarcadero] '__array_rank' '(' type-id ')'
3028/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
3029///
3030ExprResult Parser::ParseArrayTypeTrait() {
3031 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
3032 SourceLocation Loc = ConsumeToken();
3033
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003034 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003035 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00003036 return ExprError();
3037
3038 TypeResult Ty = ParseTypeName();
3039 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003040 SkipUntil(tok::comma, StopAtSemi);
3041 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003042 return ExprError();
3043 }
3044
3045 switch (ATT) {
3046 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003047 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00003048 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003049 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003050 }
3051 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00003052 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003053 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00003054 return ExprError();
3055 }
3056
3057 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003058 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00003059
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003060 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
3061 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00003062 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003063 }
David Blaikiee4d798f2012-01-20 21:50:17 +00003064 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00003065}
3066
John Wiegleyf9f65842011-04-25 06:54:41 +00003067/// ParseExpressionTrait - Parse built-in expression-trait
3068/// pseudo-functions like __is_lvalue_expr( xxx ).
3069///
3070/// primary-expression:
3071/// [Embarcadero] expression-trait '(' expression ')'
3072///
3073ExprResult Parser::ParseExpressionTrait() {
3074 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
3075 SourceLocation Loc = ConsumeToken();
3076
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003077 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00003078 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00003079 return ExprError();
3080
3081 ExprResult Expr = ParseExpression();
3082
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003083 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00003084
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003085 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3086 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00003087}
3088
3089
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003090/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3091/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3092/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00003093ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003094Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00003095 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00003096 BalancedDelimiterTracker &Tracker,
3097 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003098 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003099 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3100 assert(isTypeIdInParens() && "Not a type-id!");
3101
John McCalldadc5752010-08-24 06:29:42 +00003102 ExprResult Result(true);
David Blaikieefdccaa2016-01-15 23:43:34 +00003103 CastTy = nullptr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003104
3105 // We need to disambiguate a very ugly part of the C++ syntax:
3106 //
3107 // (T())x; - type-id
3108 // (T())*x; - type-id
3109 // (T())/x; - expression
3110 // (T()); - expression
3111 //
3112 // The bad news is that we cannot use the specialized tentative parser, since
3113 // it can only verify that the thing inside the parens can be parsed as
3114 // type-id, it is not useful for determining the context past the parens.
3115 //
3116 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00003117 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003118 //
3119 // It uses a scheme similar to parsing inline methods. The parenthesized
3120 // tokens are cached, the context that follows is determined (possibly by
3121 // parsing a cast-expression), and then we re-introduce the cached tokens
3122 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003123
Mike Stump11289f42009-09-09 15:08:12 +00003124 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003125 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003126
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003127 // Store the tokens of the parentheses. We will parse them after we determine
3128 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00003129 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003130 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003131 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003132 return ExprError();
3133 }
3134
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003135 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003136 ParseAs = CompoundLiteral;
3137 } else {
3138 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003139 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3140 NotCastExpr = true;
3141 } else {
3142 // Try parsing the cast-expression that may follow.
3143 // If it is not a cast-expression, NotCastExpr will be true and no token
3144 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003145 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003146 Result = ParseCastExpression(false/*isUnaryExpression*/,
3147 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003148 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003149 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003150 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003151 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003152
3153 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3154 // an expression.
3155 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003156 }
3157
Alexey Bataev703a93c2016-02-04 04:22:09 +00003158 // Create a fake EOF to mark end of Toks buffer.
3159 Token AttrEnd;
3160 AttrEnd.startToken();
3161 AttrEnd.setKind(tok::eof);
3162 AttrEnd.setLocation(Tok.getLocation());
3163 AttrEnd.setEofData(Toks.data());
3164 Toks.push_back(AttrEnd);
3165
Mike Stump11289f42009-09-09 15:08:12 +00003166 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003167 Toks.push_back(Tok);
3168 // Re-enter the stored parenthesized tokens into the token stream, so we may
3169 // parse them now.
David Blaikie2eabcc92016-02-09 18:52:09 +00003170 PP.EnterTokenStream(Toks, true /*DisableMacroExpansion*/);
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003171 // Drop the current token and bring the first cached one. It's the same token
3172 // as when we entered this function.
3173 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003174
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003175 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003176 // Parse the type declarator.
3177 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003178 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003179 {
3180 ColonProtectionRAIIObject InnerColonProtection(*this);
3181 ParseSpecifierQualifierList(DS);
3182 ParseDeclarator(DeclaratorInfo);
3183 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003184
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003185 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003186 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003187 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003188
Alexey Bataev703a93c2016-02-04 04:22:09 +00003189 // Consume EOF marker for Toks buffer.
3190 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3191 ConsumeAnyToken();
3192
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003193 if (ParseAs == CompoundLiteral) {
3194 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003195 if (DeclaratorInfo.isInvalidType())
3196 return ExprError();
3197
3198 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003199 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003200 Tracker.getOpenLocation(),
3201 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003202 }
Mike Stump11289f42009-09-09 15:08:12 +00003203
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003204 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3205 assert(ParseAs == CastExpr);
3206
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003207 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003208 return ExprError();
3209
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003210 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003211 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003212 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3213 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003214 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003215 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003218 // Not a compound literal, and not followed by a cast-expression.
3219 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003220
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003221 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003222 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003223 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003224 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003225 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003226
3227 // Match the ')'.
3228 if (Result.isInvalid()) {
Alexey Bataev703a93c2016-02-04 04:22:09 +00003229 while (Tok.isNot(tok::eof))
3230 ConsumeAnyToken();
3231 assert(Tok.getEofData() == AttrEnd.getEofData());
3232 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003233 return ExprError();
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003236 Tracker.consumeClose();
Alexey Bataev703a93c2016-02-04 04:22:09 +00003237 // Consume EOF marker for Toks buffer.
3238 assert(Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData());
3239 ConsumeAnyToken();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003240 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003241}