blob: dad1f0da2ef306c4a3ef839bbbd0dfc4f91e0845 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Erik Verbruggen888d52a2014-01-15 09:15:43 +000013#include "clang/AST/ASTContext.h"
Douglas Gregor94a32472011-01-11 00:33:19 +000014#include "RAIIObjectsForParser.h"
Chandler Carruth757fcd62014-03-04 10:05:20 +000015#include "clang/AST/DeclTemplate.h"
Eli Friedmanc7c97142012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith7d182a72012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "clang/Parse/Parser.h"
John McCall8b0666c2010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor7861a802009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Vali2b391ab2013-09-26 19:54:12 +000025
Chris Lattner29375652006-12-04 18:06:35 +000026using namespace clang;
27
Alp Tokerf990cef2014-01-07 02:35:33 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
30 // template name
31 case tok::unknown: return 0;
32 // casts
33 case tok::kw_const_cast: return 1;
34 case tok::kw_dynamic_cast: return 2;
35 case tok::kw_reinterpret_cast: return 3;
36 case tok::kw_static_cast: return 4;
37 default:
38 llvm_unreachable("Unknown type for digraph error message.");
39 }
40}
41
Richard Smith55858492011-04-14 21:45:45 +000042// Are the two tokens adjacent in the same source file?
Richard Smith7b3f3222012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smith55858492011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smith55858492011-04-14 21:45:45 +000047 return FirstEnd == SM.getSpellingLoc(Second.getLocation());
48}
49
50// Suggest fixit for "<::" after a cast.
51static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken,
52 Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) {
53 // Pull '<:' and ':' off token stream.
54 if (!AtDigraph)
55 PP.Lex(DigraphToken);
56 PP.Lex(ColonToken);
57
58 SourceRange Range;
59 Range.setBegin(DigraphToken.getLocation());
60 Range.setEnd(ColonToken.getLocation());
61 P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph)
Alp Tokerf990cef2014-01-07 02:35:33 +000062 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
Richard Smith55858492011-04-14 21:45:45 +000064
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smith55858492011-04-14 21:45:45 +000068 ColonToken.setLength(2);
69 DigraphToken.setKind(tok::less);
70 DigraphToken.setLength(1);
71
72 // Push new tokens back to token stream.
73 PP.EnterToken(ColonToken);
74 if (!AtDigraph)
75 PP.EnterToken(DigraphToken);
76}
77
Richard Trieu01fc0012011-09-19 19:01:00 +000078// Check for '<::' which should be '< ::' instead of '[:' when following
79// a template name.
80void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType,
81 bool EnteringContext,
82 IdentifierInfo &II, CXXScopeSpec &SS) {
Richard Trieu02e25db2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu01fc0012011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith7b3f3222012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu01fc0012011-09-19 19:01:00 +000088 return;
89
90 TemplateTy Template;
91 UnqualifiedId TemplateName;
92 TemplateName.setIdentifier(&II, Tok.getLocation());
93 bool MemberOfUnknownSpecialization;
94 if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false,
95 TemplateName, ObjectType, EnteringContext,
96 Template, MemberOfUnknownSpecialization))
97 return;
98
Alp Tokerf990cef2014-01-07 02:35:33 +000099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
100 /*AtDigraph*/false);
Richard Trieu01fc0012011-09-19 19:01:00 +0000101}
102
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000103/// \brief Emits an error for a left parentheses after a double colon.
104///
105/// When a '(' is found after a '::', emit an error. Attempt to fix the token
Nico Weber6be9b252012-11-29 05:29:23 +0000106/// stream by removing the '(', and the matching ')' if found.
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000107void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
109 return;
110
David Majnemer6ca445e2014-12-17 01:39:22 +0000111 Token LParen = Tok;
112 Token NextTok = GetLookAheadToken(1);
113 Token StarTok = NextTok;
114 // Check for (identifier or (*identifier
115 Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok;
116 if (IdentifierTok.isNot(tok::identifier))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000117 return;
David Majnemer6ca445e2014-12-17 01:39:22 +0000118 // Eat the '('.
119 ConsumeParen();
120 Token RParen;
121 // Do we have a ')' ?
122 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
123 if (NextTok.is(tok::r_paren)) {
124 RParen = NextTok;
125 // Eat the '*' if it is present.
126 if (StarTok.is(tok::star))
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000127 ConsumeToken();
David Majnemer6ca445e2014-12-17 01:39:22 +0000128 // Eat the identifier.
129 ConsumeToken();
130 // Add the identifier token back.
131 PP.EnterToken(IdentifierTok);
132 // Add the '*' back if it was present.
133 if (StarTok.is(tok::star))
134 PP.EnterToken(StarTok);
135 // Eat the ')'.
136 ConsumeParen();
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000137 }
138
David Majnemer6ca445e2014-12-17 01:39:22 +0000139 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
140 << FixItHint::CreateRemoval(LParen.getLocation())
141 << FixItHint::CreateRemoval(RParen.getLocation());
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000142}
143
Mike Stump11289f42009-09-09 15:08:12 +0000144/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000145///
146/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump11289f42009-09-09 15:08:12 +0000147/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000148/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000149///
150/// '::'[opt] nested-name-specifier
151/// '::'
152///
153/// nested-name-specifier:
154/// type-name '::'
155/// namespace-name '::'
156/// nested-name-specifier identifier '::'
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000157/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000158///
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000159///
Mike Stump11289f42009-09-09 15:08:12 +0000160/// \param SS the scope specifier that will be set to the parsed
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000161/// nested-name-specifier (or empty)
162///
Mike Stump11289f42009-09-09 15:08:12 +0000163/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164/// the "." or "->" of a member access expression, this parameter provides the
165/// type of the object whose members are being accessed.
166///
167/// \param EnteringContext whether we will be entering into the context of
168/// the nested-name-specifier after parsing it.
169///
Douglas Gregore610ada2010-02-24 18:44:31 +0000170/// \param MayBePseudoDestructor When non-NULL, points to a flag that
171/// indicates whether this nested-name-specifier may be part of a
172/// pseudo-destructor name. In this case, the flag will be set false
173/// if we don't actually end up parsing a destructor name. Moreorover,
174/// if we do end up determining that we are parsing a destructor name,
175/// the last component of the nested-name-specifier is not parsed as
176/// part of the scope specifier.
Richard Smith7447af42013-03-26 01:15:19 +0000177///
178/// \param IsTypename If \c true, this nested-name-specifier is known to be
179/// part of a type name. This is used to improve error recovery.
180///
181/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
182/// filled in with the leading identifier in the last component of the
183/// nested-name-specifier, if any.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000184///
John McCall1f476a12010-02-26 08:45:28 +0000185/// \returns true if there was an error parsing a scope specifier
Douglas Gregore861bac2009-08-25 22:51:20 +0000186bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +0000187 ParsedType ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000188 bool EnteringContext,
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000189 bool *MayBePseudoDestructor,
Richard Smith7447af42013-03-26 01:15:19 +0000190 bool IsTypename,
191 IdentifierInfo **LastII) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000192 assert(getLangOpts().CPlusPlus &&
Chris Lattnerb5134c02009-01-05 01:24:05 +0000193 "Call sites of this function should be guarded by checking for C++");
Mike Stump11289f42009-09-09 15:08:12 +0000194
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000195 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith7447af42013-03-26 01:15:19 +0000196 assert(!LastII && "want last identifier but have already annotated scope");
Douglas Gregor869ad452011-02-24 17:54:50 +0000197 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
198 Tok.getAnnotationRange(),
199 SS);
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000200 ConsumeToken();
John McCall1f476a12010-02-26 08:45:28 +0000201 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000202 }
Chris Lattnerf9b2cd42009-01-04 21:14:15 +0000203
Larisse Voufob959c3c2013-08-06 05:49:26 +0000204 if (Tok.is(tok::annot_template_id)) {
205 // If the current token is an annotated template id, it may already have
206 // a scope specifier. Restore it.
207 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
208 SS = TemplateId->SS;
209 }
210
Richard Smith7447af42013-03-26 01:15:19 +0000211 if (LastII)
Craig Topper161e4db2014-05-21 06:02:52 +0000212 *LastII = nullptr;
Richard Smith7447af42013-03-26 01:15:19 +0000213
Douglas Gregor7f741122009-02-25 19:37:18 +0000214 bool HasScopeSpecifier = false;
215
Chris Lattner8a7d10d2009-01-05 03:55:46 +0000216 if (Tok.is(tok::coloncolon)) {
217 // ::new and ::delete aren't nested-name-specifiers.
218 tok::TokenKind NextKind = NextToken().getKind();
219 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
220 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000221
Chris Lattner45ddec32009-01-05 00:13:00 +0000222 // '::' - Global scope qualifier.
Nikola Smiljanic67860242014-09-26 00:28:20 +0000223 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
Douglas Gregor90c99722011-02-24 00:17:56 +0000224 return true;
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000225
226 CheckForLParenAfterColonColon();
227
Douglas Gregor7f741122009-02-25 19:37:18 +0000228 HasScopeSpecifier = true;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000229 }
230
Nikola Smiljanic67860242014-09-26 00:28:20 +0000231 if (Tok.is(tok::kw___super)) {
232 SourceLocation SuperLoc = ConsumeToken();
233 if (!Tok.is(tok::coloncolon)) {
234 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
235 return true;
236 }
237
238 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
239 }
240
Douglas Gregore610ada2010-02-24 18:44:31 +0000241 bool CheckForDestructor = false;
242 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
243 CheckForDestructor = true;
244 *MayBePseudoDestructor = false;
245 }
246
Richard Smitha9d10012014-10-04 01:57:39 +0000247 if (!HasScopeSpecifier &&
248 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
David Blaikie15a430a2011-12-04 05:04:18 +0000249 DeclSpec DS(AttrFactory);
250 SourceLocation DeclLoc = Tok.getLocation();
251 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000252
253 SourceLocation CCLoc;
254 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie15a430a2011-12-04 05:04:18 +0000255 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
256 return false;
257 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000258
David Blaikie15a430a2011-12-04 05:04:18 +0000259 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
260 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
261
262 HasScopeSpecifier = true;
263 }
264
Douglas Gregor7f741122009-02-25 19:37:18 +0000265 while (true) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000266 if (HasScopeSpecifier) {
267 // C++ [basic.lookup.classref]p5:
268 // If the qualified-id has the form
Douglas Gregor308047d2009-09-09 00:23:06 +0000269 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000270 // ::class-name-or-namespace-name::...
Douglas Gregor308047d2009-09-09 00:23:06 +0000271 //
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000272 // the class-name-or-namespace-name is looked up in global scope as a
273 // class-name or namespace-name.
274 //
275 // To implement this, we clear out the object type as soon as we've
276 // seen a leading '::' or part of a nested-name-specifier.
John McCallba7bf592010-08-24 05:47:05 +0000277 ObjectType = ParsedType();
Douglas Gregor2436e712009-09-17 21:32:03 +0000278
279 if (Tok.is(tok::code_completion)) {
280 // Code completion for a nested-name-specifier, where the code
281 // code completion token follows the '::'.
Douglas Gregor0be31a22010-07-02 17:43:08 +0000282 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidis7d94c922011-04-23 01:04:12 +0000283 // Include code completion token into the range of the scope otherwise
284 // when we try to annotate the scope tokens the dangling code completion
285 // token will cause assertion in
286 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000287 SS.setEndLoc(Tok.getLocation());
288 cutOffParsing();
289 return true;
Douglas Gregor2436e712009-09-17 21:32:03 +0000290 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000291 }
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor7f741122009-02-25 19:37:18 +0000293 // nested-name-specifier:
Chris Lattner0eed3a62009-06-26 03:47:46 +0000294 // nested-name-specifier 'template'[opt] simple-template-id '::'
295
296 // Parse the optional 'template' keyword, then make sure we have
297 // 'identifier <' after it.
298 if (Tok.is(tok::kw_template)) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000299 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedman2624be42009-08-29 04:08:08 +0000300 // nested-name-specifier, since they aren't allowed to start with
301 // 'template'.
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000302 if (!HasScopeSpecifier && !ObjectType)
Eli Friedman2624be42009-08-29 04:08:08 +0000303 break;
304
Douglas Gregor120635b2009-11-11 16:39:34 +0000305 TentativeParsingAction TPA(*this);
Chris Lattner0eed3a62009-06-26 03:47:46 +0000306 SourceLocation TemplateKWLoc = ConsumeToken();
Richard Smithd091dc12013-12-05 00:58:33 +0000307
Douglas Gregor71395fa2009-11-04 00:56:37 +0000308 UnqualifiedId TemplateName;
309 if (Tok.is(tok::identifier)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000310 // Consume the identifier.
Douglas Gregor120635b2009-11-11 16:39:34 +0000311 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregor71395fa2009-11-04 00:56:37 +0000312 ConsumeToken();
313 } else if (Tok.is(tok::kw_operator)) {
Richard Smithd091dc12013-12-05 00:58:33 +0000314 // We don't need to actually parse the unqualified-id in this case,
315 // because a simple-template-id cannot start with 'operator', but
316 // go ahead and parse it anyway for consistency with the case where
317 // we already annotated the template-id.
318 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor120635b2009-11-11 16:39:34 +0000319 TemplateName)) {
320 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000321 break;
Douglas Gregor120635b2009-11-11 16:39:34 +0000322 }
Richard Smithd091dc12013-12-05 00:58:33 +0000323
Alexis Hunted0530f2009-11-28 08:58:14 +0000324 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
325 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor71395fa2009-11-04 00:56:37 +0000326 Diag(TemplateName.getSourceRange().getBegin(),
327 diag::err_id_after_template_in_nested_name_spec)
328 << TemplateName.getSourceRange();
Douglas Gregor120635b2009-11-11 16:39:34 +0000329 TPA.Commit();
Douglas Gregor71395fa2009-11-04 00:56:37 +0000330 break;
331 }
332 } else {
Douglas Gregor120635b2009-11-11 16:39:34 +0000333 TPA.Revert();
Chris Lattner0eed3a62009-06-26 03:47:46 +0000334 break;
335 }
Mike Stump11289f42009-09-09 15:08:12 +0000336
Douglas Gregor120635b2009-11-11 16:39:34 +0000337 // If the next token is not '<', we have a qualified-id that refers
338 // to a template name, such as T::template apply, but is not a
339 // template-id.
340 if (Tok.isNot(tok::less)) {
341 TPA.Revert();
342 break;
343 }
344
345 // Commit to parsing the template-id.
346 TPA.Commit();
Douglas Gregorbb119652010-06-16 23:00:59 +0000347 TemplateTy Template;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000348 if (TemplateNameKind TNK
349 = Actions.ActOnDependentTemplateName(getCurScope(),
350 SS, TemplateKWLoc, TemplateName,
351 ObjectType, EnteringContext,
352 Template)) {
353 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
354 TemplateName, false))
Douglas Gregorbb119652010-06-16 23:00:59 +0000355 return true;
356 } else
John McCall1f476a12010-02-26 08:45:28 +0000357 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000358
Chris Lattner0eed3a62009-06-26 03:47:46 +0000359 continue;
360 }
Mike Stump11289f42009-09-09 15:08:12 +0000361
Douglas Gregor7f741122009-02-25 19:37:18 +0000362 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump11289f42009-09-09 15:08:12 +0000363 // We have
Douglas Gregor7f741122009-02-25 19:37:18 +0000364 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000365 // template-id '::'
Douglas Gregor7f741122009-02-25 19:37:18 +0000366 //
Richard Smith72bfbd82013-12-04 00:28:23 +0000367 // So we need to check whether the template-id is a simple-template-id of
368 // the right kind (it should name a type or be dependent), and then
Douglas Gregorb67535d2009-03-31 00:43:58 +0000369 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +0000370 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregore610ada2010-02-24 18:44:31 +0000371 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
372 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000373 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000374 }
375
Richard Smith7447af42013-03-26 01:15:19 +0000376 if (LastII)
377 *LastII = TemplateId->Name;
378
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000379 // Consume the template-id token.
380 ConsumeToken();
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000381
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000382 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
383 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000384
David Blaikie8c045bc2011-11-07 03:30:03 +0000385 HasScopeSpecifier = true;
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000386
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000387 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000388 TemplateId->NumArgs);
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000389
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000390 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000391 SS,
392 TemplateId->TemplateKWLoc,
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000393 TemplateId->Template,
394 TemplateId->TemplateNameLoc,
395 TemplateId->LAngleLoc,
396 TemplateArgsPtr,
397 TemplateId->RAngleLoc,
398 CCLoc,
399 EnteringContext)) {
400 SourceLocation StartLoc
401 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
402 : TemplateId->TemplateNameLoc;
403 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner704edfb2009-06-26 03:45:46 +0000404 }
Argyrios Kyrtzidis13935672011-05-03 18:45:38 +0000405
Douglas Gregor8b6070b2011-03-04 21:37:14 +0000406 continue;
Douglas Gregor7f741122009-02-25 19:37:18 +0000407 }
408
Chris Lattnere2355f72009-06-26 03:52:38 +0000409 // The rest of the nested-name-specifier possibilities start with
410 // tok::identifier.
411 if (Tok.isNot(tok::identifier))
412 break;
413
414 IdentifierInfo &II = *Tok.getIdentifierInfo();
415
416 // nested-name-specifier:
417 // type-name '::'
418 // namespace-name '::'
419 // nested-name-specifier identifier '::'
420 Token Next = NextToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000421
422 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
423 // and emit a fixit hint for it.
Douglas Gregor90d554e2010-02-21 18:36:56 +0000424 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor90c99722011-02-24 00:17:56 +0000425 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
426 Tok.getLocation(),
427 Next.getLocation(), ObjectType,
Douglas Gregor90d554e2010-02-21 18:36:56 +0000428 EnteringContext) &&
429 // If the token after the colon isn't an identifier, it's still an
430 // error, but they probably meant something else strange so don't
431 // recover like this.
432 PP.LookAhead(1).is(tok::identifier)) {
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000433 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregora771f462010-03-31 17:46:05 +0000434 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregor90d554e2010-02-21 18:36:56 +0000435 // Recover as if the user wrote '::'.
436 Next.setKind(tok::coloncolon);
437 }
Chris Lattner1c428032009-12-07 01:36:53 +0000438 }
439
Chris Lattnere2355f72009-06-26 03:52:38 +0000440 if (Next.is(tok::coloncolon)) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +0000441 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Nico Weber61281fa2014-07-26 22:15:25 +0000442 !Actions.isNonTypeNestedNameSpecifier(
443 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregore610ada2010-02-24 18:44:31 +0000444 *MayBePseudoDestructor = true;
John McCall1f476a12010-02-26 08:45:28 +0000445 return false;
Douglas Gregore610ada2010-02-24 18:44:31 +0000446 }
447
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000448 if (ColonIsSacred) {
449 const Token &Next2 = GetLookAheadToken(2);
450 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
451 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
452 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
453 << Next2.getName()
454 << FixItHint::CreateReplacement(Next.getLocation(), ":");
455 Token ColonColon;
456 PP.Lex(ColonColon);
457 ColonColon.setKind(tok::colon);
458 PP.EnterToken(ColonColon);
459 break;
460 }
461 }
462
Richard Smith7447af42013-03-26 01:15:19 +0000463 if (LastII)
464 *LastII = &II;
465
Chris Lattnere2355f72009-06-26 03:52:38 +0000466 // We have an identifier followed by a '::'. Lookup this name
467 // as the name in a nested-name-specifier.
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000468 Token Identifier = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000469 SourceLocation IdLoc = ConsumeToken();
Chris Lattner1c428032009-12-07 01:36:53 +0000470 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
471 "NextToken() not working properly!");
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000472 Token ColonColon = Tok;
Chris Lattnere2355f72009-06-26 03:52:38 +0000473 SourceLocation CCLoc = ConsumeToken();
Mike Stump11289f42009-09-09 15:08:12 +0000474
Richard Trieu1f3ea7b2012-11-02 01:08:58 +0000475 CheckForLParenAfterColonColon();
476
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000477 bool IsCorrectedToColon = false;
Craig Topper161e4db2014-05-21 06:02:52 +0000478 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor90c99722011-02-24 00:17:56 +0000479 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000480 ObjectType, EnteringContext, SS,
481 false, CorrectionFlagPtr)) {
482 // Identifier is not recognized as a nested name, but we can have
483 // mistyped '::' instead of ':'.
484 if (CorrectionFlagPtr && IsCorrectedToColon) {
485 ColonColon.setKind(tok::colon);
486 PP.EnterToken(Tok);
487 PP.EnterToken(ColonColon);
488 Tok = Identifier;
489 break;
490 }
Douglas Gregor90c99722011-02-24 00:17:56 +0000491 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Serge Pavlov6a7ffbe2014-04-13 16:52:03 +0000492 }
493 HasScopeSpecifier = true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000494 continue;
495 }
Mike Stump11289f42009-09-09 15:08:12 +0000496
Richard Trieu01fc0012011-09-19 19:01:00 +0000497 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smith55858492011-04-14 21:45:45 +0000498
Chris Lattnere2355f72009-06-26 03:52:38 +0000499 // nested-name-specifier:
500 // type-name '<'
501 if (Next.is(tok::less)) {
502 TemplateTy Template;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000503 UnqualifiedId TemplateName;
504 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor786123d2010-05-21 23:18:07 +0000505 bool MemberOfUnknownSpecialization;
Douglas Gregor0be31a22010-07-02 17:43:08 +0000506 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c5dee42010-08-06 12:11:11 +0000507 /*hasTemplateKeyword=*/false,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000508 TemplateName,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000509 ObjectType,
Douglas Gregore861bac2009-08-25 22:51:20 +0000510 EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000511 Template,
512 MemberOfUnknownSpecialization)) {
David Blaikie8c045bc2011-11-07 03:30:03 +0000513 // We have found a template name, so annotate this token
Chris Lattnere2355f72009-06-26 03:52:38 +0000514 // with a template-id annotation. We do not permit the
515 // template-id to be translated into a type annotation,
516 // because some clients (e.g., the parsing of class template
517 // specializations) still want to see the original template-id
518 // token.
Douglas Gregor71395fa2009-11-04 00:56:37 +0000519 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000520 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
521 TemplateName, false))
John McCall1f476a12010-02-26 08:45:28 +0000522 return true;
Chris Lattnere2355f72009-06-26 03:52:38 +0000523 continue;
Larisse Voufo39a1e502013-08-06 01:03:05 +0000524 }
525
Douglas Gregor20c38a72010-05-21 23:43:39 +0000526 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000527 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregor20c38a72010-05-21 23:43:39 +0000528 // We have something like t::getAs<T>, where getAs is a
529 // member of an unknown specialization. However, this will only
530 // parse correctly as a template, so suggest the keyword 'template'
531 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000532 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000533 if (getLangOpts().MicrosoftExt)
Francois Pichet93921652011-04-22 08:25:24 +0000534 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4e7a2c02011-03-27 19:41:34 +0000535
536 Diag(Tok.getLocation(), DiagID)
Douglas Gregor20c38a72010-05-21 23:43:39 +0000537 << II.getName()
538 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
539
Douglas Gregorbb119652010-06-16 23:00:59 +0000540 if (TemplateNameKind TNK
Douglas Gregor0be31a22010-07-02 17:43:08 +0000541 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000542 SS, SourceLocation(),
Douglas Gregorbb119652010-06-16 23:00:59 +0000543 TemplateName, ObjectType,
544 EnteringContext, Template)) {
545 // Consume the identifier.
546 ConsumeToken();
Abramo Bagnara7945c982012-01-27 09:46:47 +0000547 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
548 TemplateName, false))
549 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000550 }
551 else
Douglas Gregor20c38a72010-05-21 23:43:39 +0000552 return true;
Douglas Gregorbb119652010-06-16 23:00:59 +0000553
Douglas Gregor20c38a72010-05-21 23:43:39 +0000554 continue;
Chris Lattnere2355f72009-06-26 03:52:38 +0000555 }
556 }
557
Douglas Gregor7f741122009-02-25 19:37:18 +0000558 // We don't have any tokens that form the beginning of a
559 // nested-name-specifier, so we're done.
560 break;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000561 }
Mike Stump11289f42009-09-09 15:08:12 +0000562
Douglas Gregore610ada2010-02-24 18:44:31 +0000563 // Even if we didn't see any pieces of a nested-name-specifier, we
564 // still check whether there is a tilde in this position, which
565 // indicates a potential pseudo-destructor.
566 if (CheckForDestructor && Tok.is(tok::tilde))
567 *MayBePseudoDestructor = true;
568
John McCall1f476a12010-02-26 08:45:28 +0000569 return false;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000570}
571
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000572ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
573 Token &Replacement) {
574 SourceLocation TemplateKWLoc;
575 UnqualifiedId Name;
576 if (ParseUnqualifiedId(SS,
577 /*EnteringContext=*/false,
578 /*AllowDestructorName=*/false,
579 /*AllowConstructorName=*/false,
580 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
581 return ExprError();
582
583 // This is only the direct operand of an & operator if it is not
584 // followed by a postfix-expression suffix.
585 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
586 isAddressOfOperand = false;
587
588 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
589 Tok.is(tok::l_paren), isAddressOfOperand,
590 nullptr, /*IsInlineAsmIdentifier=*/false,
591 &Replacement);
592}
593
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000594/// ParseCXXIdExpression - Handle id-expression.
595///
596/// id-expression:
597/// unqualified-id
598/// qualified-id
599///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000600/// qualified-id:
601/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
602/// '::' identifier
603/// '::' operator-function-id
Douglas Gregora727cb92009-06-30 22:34:41 +0000604/// '::' template-id
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000605///
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000606/// NOTE: The standard specifies that, for qualified-id, the parser does not
607/// expect:
608///
609/// '::' conversion-function-id
610/// '::' '~' class-name
611///
612/// This may cause a slight inconsistency on diagnostics:
613///
614/// class C {};
615/// namespace A {}
616/// void f() {
617/// :: A :: ~ C(); // Some Sema error about using destructor with a
618/// // namespace.
619/// :: ~ C(); // Some Parser error like 'unexpected ~'.
620/// }
621///
622/// We simplify the parser a bit and make it work like:
623///
624/// qualified-id:
625/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
626/// '::' unqualified-id
627///
628/// That way Sema can handle and report similar errors for namespaces and the
629/// global scope.
630///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000631/// The isAddressOfOperand parameter indicates that this id-expression is a
632/// direct operand of the address-of operator. This is, besides member contexts,
633/// the only place where a qualified-id naming a non-static class member may
634/// appear.
635///
John McCalldadc5752010-08-24 06:29:42 +0000636ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000637 // qualified-id:
638 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
639 // '::' unqualified-id
640 //
641 CXXScopeSpec SS;
Douglas Gregordf593fb2011-11-07 17:33:42 +0000642 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnara7945c982012-01-27 09:46:47 +0000643
Kaelyn Takatab16e6322014-11-20 22:06:40 +0000644 Token Replacement;
645 ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
646 if (Result.isUnset()) {
647 // If the ExprResult is valid but null, then typo correction suggested a
648 // keyword replacement that needs to be reparsed.
649 UnconsumeToken(Replacement);
650 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
651 }
652 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
653 "for a previous keyword suggestion");
654 return Result;
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000655}
656
Richard Smith21b3ab42013-05-09 21:36:41 +0000657/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000658///
659/// lambda-expression:
660/// lambda-introducer lambda-declarator[opt] compound-statement
661///
662/// lambda-introducer:
663/// '[' lambda-capture[opt] ']'
664///
665/// lambda-capture:
666/// capture-default
667/// capture-list
668/// capture-default ',' capture-list
669///
670/// capture-default:
671/// '&'
672/// '='
673///
674/// capture-list:
675/// capture
676/// capture-list ',' capture
677///
678/// capture:
Richard Smith21b3ab42013-05-09 21:36:41 +0000679/// simple-capture
680/// init-capture [C++1y]
681///
682/// simple-capture:
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000683/// identifier
684/// '&' identifier
685/// 'this'
686///
Richard Smith21b3ab42013-05-09 21:36:41 +0000687/// init-capture: [C++1y]
688/// identifier initializer
689/// '&' identifier initializer
690///
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000691/// lambda-declarator:
692/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
693/// 'mutable'[opt] exception-specification[opt]
694/// trailing-return-type[opt]
695///
696ExprResult Parser::ParseLambdaExpression() {
697 // Parse lambda-introducer.
698 LambdaIntroducer Intro;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000699 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000700 if (DiagID) {
701 Diag(Tok, DiagID.getValue());
Alexey Bataevee6507d2013-11-18 08:17:37 +0000702 SkipUntil(tok::r_square, StopAtSemi);
703 SkipUntil(tok::l_brace, StopAtSemi);
704 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmanc7c97142012-01-04 02:40:39 +0000705 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000706 }
707
708 return ParseLambdaExpressionAfterIntroducer(Intro);
709}
710
711/// TryParseLambdaExpression - Use lookahead and potentially tentative
712/// parsing to determine if we are looking at a C++0x lambda expression, and parse
713/// it if we are.
714///
715/// If we are not looking at a lambda expression, returns ExprError().
716ExprResult Parser::TryParseLambdaExpression() {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000717 assert(getLangOpts().CPlusPlus11
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000718 && Tok.is(tok::l_square)
719 && "Not at the start of a possible lambda expression.");
720
721 const Token Next = NextToken(), After = GetLookAheadToken(2);
722
723 // If lookahead indicates this is a lambda...
724 if (Next.is(tok::r_square) || // []
725 Next.is(tok::equal) || // [=
726 (Next.is(tok::amp) && // [&] or [&,
727 (After.is(tok::r_square) ||
728 After.is(tok::comma))) ||
729 (Next.is(tok::identifier) && // [identifier]
730 After.is(tok::r_square))) {
731 return ParseLambdaExpression();
732 }
733
Eli Friedmanc7c97142012-01-04 02:40:39 +0000734 // If lookahead indicates an ObjC message send...
735 // [identifier identifier
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000736 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmanc7c97142012-01-04 02:40:39 +0000737 return ExprEmpty();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000738 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000739
Eli Friedmanc7c97142012-01-04 02:40:39 +0000740 // Here, we're stuck: lambda introducers and Objective-C message sends are
741 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
742 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
743 // writing two routines to parse a lambda introducer, just try to parse
744 // a lambda introducer first, and fall back if that fails.
745 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000746 LambdaIntroducer Intro;
747 if (TryParseLambdaIntroducer(Intro))
Eli Friedmanc7c97142012-01-04 02:40:39 +0000748 return ExprEmpty();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000749
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000750 return ParseLambdaExpressionAfterIntroducer(Intro);
751}
752
Richard Smithf44d2a82013-05-21 22:21:19 +0000753/// \brief Parse a lambda introducer.
754/// \param Intro A LambdaIntroducer filled in with information about the
755/// contents of the lambda-introducer.
756/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
757/// message send and a lambda expression. In this mode, we will
758/// sometimes skip the initializers for init-captures and not fully
759/// populate \p Intro. This flag will be set to \c true if we do so.
760/// \return A DiagnosticID if it hit something unexpected. The location for
761/// for the diagnostic is that of the current token.
762Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
763 bool *SkippedInits) {
David Blaikie05785d12013-02-20 22:23:23 +0000764 typedef Optional<unsigned> DiagResult;
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000765
766 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000767 BalancedDelimiterTracker T(*this, tok::l_square);
768 T.consumeOpen();
769
770 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000771
772 bool first = true;
773
774 // Parse capture-default.
775 if (Tok.is(tok::amp) &&
776 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
777 Intro.Default = LCD_ByRef;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000778 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000779 first = false;
780 } else if (Tok.is(tok::equal)) {
781 Intro.Default = LCD_ByCopy;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000782 Intro.DefaultLoc = ConsumeToken();
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000783 first = false;
784 }
785
786 while (Tok.isNot(tok::r_square)) {
787 if (!first) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000788 if (Tok.isNot(tok::comma)) {
Douglas Gregor721b14d2012-07-31 00:50:07 +0000789 // Provide a completion for a lambda introducer here. Except
790 // in Objective-C, where this is Almost Surely meant to be a message
791 // send. In that case, fail here and let the ObjC message
792 // expression parser perform the completion.
Douglas Gregor2d8db8f2012-07-31 15:27:48 +0000793 if (Tok.is(tok::code_completion) &&
794 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
795 !Intro.Captures.empty())) {
Douglas Gregord8c61782012-02-15 15:34:24 +0000796 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
797 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000798 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000799 break;
800 }
801
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000802 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregord8c61782012-02-15 15:34:24 +0000803 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000804 ConsumeToken();
805 }
806
Douglas Gregord8c61782012-02-15 15:34:24 +0000807 if (Tok.is(tok::code_completion)) {
808 // If we're in Objective-C++ and we have a bare '[', then this is more
809 // likely to be a message receiver.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000810 if (getLangOpts().ObjC1 && first)
Douglas Gregord8c61782012-02-15 15:34:24 +0000811 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
812 else
813 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
814 /*AfterAmpersand=*/false);
Alp Toker1c583cc2014-05-02 03:43:14 +0000815 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000816 break;
817 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000818
Douglas Gregord8c61782012-02-15 15:34:24 +0000819 first = false;
820
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000821 // Parse capture.
822 LambdaCaptureKind Kind = LCK_ByCopy;
823 SourceLocation Loc;
Craig Topper161e4db2014-05-21 06:02:52 +0000824 IdentifierInfo *Id = nullptr;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000825 SourceLocation EllipsisLoc;
Richard Smith21b3ab42013-05-09 21:36:41 +0000826 ExprResult Init;
Douglas Gregor3e308b12012-02-14 19:27:52 +0000827
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000828 if (Tok.is(tok::kw_this)) {
829 Kind = LCK_This;
830 Loc = ConsumeToken();
831 } else {
832 if (Tok.is(tok::amp)) {
833 Kind = LCK_ByRef;
834 ConsumeToken();
Douglas Gregord8c61782012-02-15 15:34:24 +0000835
836 if (Tok.is(tok::code_completion)) {
837 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
838 /*AfterAmpersand=*/true);
Alp Toker1c583cc2014-05-02 03:43:14 +0000839 cutOffParsing();
Douglas Gregord8c61782012-02-15 15:34:24 +0000840 break;
841 }
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000842 }
843
844 if (Tok.is(tok::identifier)) {
845 Id = Tok.getIdentifierInfo();
846 Loc = ConsumeToken();
847 } else if (Tok.is(tok::kw_this)) {
848 // FIXME: If we want to suggest a fixit here, will need to return more
849 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
850 // Clear()ed to prevent emission in case of tentative parsing?
851 return DiagResult(diag::err_this_captured_by_reference);
852 } else {
853 return DiagResult(diag::err_expected_capture);
854 }
Richard Smith21b3ab42013-05-09 21:36:41 +0000855
856 if (Tok.is(tok::l_paren)) {
857 BalancedDelimiterTracker Parens(*this, tok::l_paren);
858 Parens.consumeOpen();
859
860 ExprVector Exprs;
861 CommaLocsTy Commas;
Richard Smithf44d2a82013-05-21 22:21:19 +0000862 if (SkippedInits) {
863 Parens.skipToEnd();
864 *SkippedInits = true;
865 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith21b3ab42013-05-09 21:36:41 +0000866 Parens.skipToEnd();
867 Init = ExprError();
868 } else {
869 Parens.consumeClose();
870 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
871 Parens.getCloseLocation(),
872 Exprs);
873 }
874 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000875 // Each lambda init-capture forms its own full expression, which clears
876 // Actions.MaybeODRUseExprs. So create an expression evaluation context
877 // to save the necessary state, and restore it later.
878 EnterExpressionEvaluationContext EC(Actions,
879 Sema::PotentiallyEvaluated);
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000880 TryConsumeToken(tok::equal);
Richard Smith21b3ab42013-05-09 21:36:41 +0000881
Richard Smithf44d2a82013-05-21 22:21:19 +0000882 if (!SkippedInits)
883 Init = ParseInitializer();
884 else if (Tok.is(tok::l_brace)) {
885 BalancedDelimiterTracker Braces(*this, tok::l_brace);
886 Braces.consumeOpen();
887 Braces.skipToEnd();
888 *SkippedInits = true;
889 } else {
890 // We're disambiguating this:
891 //
892 // [..., x = expr
893 //
894 // We need to find the end of the following expression in order to
Richard Smith9e2f0a42014-04-13 04:31:48 +0000895 // determine whether this is an Obj-C message send's receiver, a
896 // C99 designator, or a lambda init-capture.
Richard Smithf44d2a82013-05-21 22:21:19 +0000897 //
898 // Parse the expression to find where it ends, and annotate it back
899 // onto the tokens. We would have parsed this expression the same way
900 // in either case: both the RHS of an init-capture and the RHS of an
901 // assignment expression are parsed as an initializer-clause, and in
902 // neither case can anything be added to the scope between the '[' and
903 // here.
904 //
905 // FIXME: This is horrible. Adding a mechanism to skip an expression
906 // would be much cleaner.
907 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
908 // that instead. (And if we see a ':' with no matching '?', we can
909 // classify this as an Obj-C message send.)
910 SourceLocation StartLoc = Tok.getLocation();
911 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
912 Init = ParseInitializer();
913
914 if (Tok.getLocation() != StartLoc) {
915 // Back out the lexing of the token after the initializer.
916 PP.RevertCachedTokens(1);
917
918 // Replace the consumed tokens with an appropriate annotation.
919 Tok.setLocation(StartLoc);
920 Tok.setKind(tok::annot_primary_expr);
921 setExprAnnotation(Tok, Init);
922 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
923 PP.AnnotateCachedTokens(Tok);
924
925 // Consume the annotated initializer.
926 ConsumeToken();
927 }
928 }
Alp Tokera3ebe6e2013-12-17 14:12:37 +0000929 } else
930 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000931 }
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000932 // If this is an init capture, process the initialization expression
933 // right away. For lambda init-captures such as the following:
934 // const int x = 10;
935 // auto L = [i = x+1](int a) {
936 // return [j = x+2,
937 // &k = x](char b) { };
938 // };
939 // keep in mind that each lambda init-capture has to have:
940 // - its initialization expression executed in the context
941 // of the enclosing/parent decl-context.
942 // - but the variable itself has to be 'injected' into the
943 // decl-context of its lambda's call-operator (which has
944 // not yet been created).
945 // Each init-expression is a full-expression that has to get
946 // Sema-analyzed (for capturing etc.) before its lambda's
947 // call-operator's decl-context, scope & scopeinfo are pushed on their
948 // respective stacks. Thus if any variable is odr-used in the init-capture
949 // it will correctly get captured in the enclosing lambda, if one exists.
950 // The init-variables above are created later once the lambdascope and
951 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000952
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000953 // Since the lambda init-capture's initializer expression occurs in the
954 // context of the enclosing function or lambda, therefore we can not wait
955 // till a lambda scope has been pushed on before deciding whether the
956 // variable needs to be captured. We also need to process all
957 // lvalue-to-rvalue conversions and discarded-value conversions,
958 // so that we can avoid capturing certain constant variables.
959 // For e.g.,
960 // void test() {
961 // const int x = 10;
962 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
963 // return [y = x](int i) { <-- don't capture by enclosing lambda
964 // return y;
965 // }
966 // };
967 // If x was not const, the second use would require 'L' to capture, and
968 // that would be an error.
969
970 ParsedType InitCaptureParsedType;
971 if (Init.isUsable()) {
972 // Get the pointer and store it in an lvalue, so we can use it as an
973 // out argument.
974 Expr *InitExpr = Init.get();
975 // This performs any lvalue-to-rvalue conversions if necessary, which
976 // can affect what gets captured in the containing decl-context.
977 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
978 Loc, Kind == LCK_ByRef, Id, InitExpr);
979 Init = InitExpr;
980 InitCaptureParsedType.set(InitCaptureType);
981 }
982 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000983 }
984
Douglas Gregore7a8e3b2011-10-12 16:37:45 +0000985 T.consumeClose();
986 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000987 return DiagResult();
988}
989
Douglas Gregord8c61782012-02-15 15:34:24 +0000990/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000991///
992/// Returns true if it hit something unexpected.
993bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
994 TentativeParsingAction PA(*this);
995
Richard Smithf44d2a82013-05-21 22:21:19 +0000996 bool SkippedInits = false;
997 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregordb0b9f12011-08-04 15:30:47 +0000998
999 if (DiagID) {
1000 PA.Revert();
1001 return true;
1002 }
1003
Richard Smithf44d2a82013-05-21 22:21:19 +00001004 if (SkippedInits) {
1005 // Parse it again, but this time parse the init-captures too.
1006 PA.Revert();
1007 Intro = LambdaIntroducer();
1008 DiagID = ParseLambdaIntroducer(Intro);
1009 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1010 return false;
1011 }
1012
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001013 PA.Commit();
1014 return false;
1015}
1016
1017/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1018/// expression.
1019ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1020 LambdaIntroducer &Intro) {
Eli Friedmanc7c97142012-01-04 02:40:39 +00001021 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1022 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1023
1024 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1025 "lambda expression parsing");
1026
Faisal Vali2b391ab2013-09-26 19:54:12 +00001027
1028
Richard Smith21b3ab42013-05-09 21:36:41 +00001029 // FIXME: Call into Actions to add any init-capture declarations to the
1030 // scope while parsing the lambda-declarator and compound-statement.
1031
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001032 // Parse lambda-declarator[opt].
1033 DeclSpec DS(AttrFactory);
Eli Friedman36d12942012-01-04 04:41:38 +00001034 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001035 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1036 Actions.PushLambdaScope();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001037
1038 if (Tok.is(tok::l_paren)) {
1039 ParseScope PrototypeScope(this,
1040 Scope::FunctionPrototypeScope |
Richard Smithe233fbf2013-01-28 22:42:45 +00001041 Scope::FunctionDeclarationScope |
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001042 Scope::DeclScope);
1043
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001044 SourceLocation DeclEndLoc;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001045 BalancedDelimiterTracker T(*this, tok::l_paren);
1046 T.consumeOpen();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001047 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001048
1049 // Parse parameter-declaration-clause.
1050 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001051 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001052 SourceLocation EllipsisLoc;
Faisal Vali2b391ab2013-09-26 19:54:12 +00001053
1054 if (Tok.isNot(tok::r_paren)) {
Faisal Vali2b391ab2013-09-26 19:54:12 +00001055 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001056 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001057 // For a generic lambda, each 'auto' within the parameter declaration
1058 // clause creates a template type parameter, so increment the depth.
1059 if (Actions.getCurGenericLambda())
1060 ++CurTemplateDepthTracker;
1061 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001062 T.consumeClose();
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001063 SourceLocation RParenLoc = T.getCloseLocation();
1064 DeclEndLoc = RParenLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001065
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001066 // GNU-style attributes must be parsed before the mutable specifier to be
1067 // compatible with GCC.
1068 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1069
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001070 // Parse 'mutable'[opt].
1071 SourceLocation MutableLoc;
Alp Toker094e5212014-01-05 03:27:11 +00001072 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001073 DeclEndLoc = MutableLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001074
1075 // Parse exception-specification[opt].
1076 ExceptionSpecificationType ESpecType = EST_None;
1077 SourceRange ESpecRange;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001078 SmallVector<ParsedType, 2> DynamicExceptions;
1079 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001080 ExprResult NoexceptExpr;
Richard Smith0b3a4622014-11-13 20:01:57 +00001081 CachedTokens *ExceptionSpecTokens;
1082 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1083 ESpecRange,
Douglas Gregor433e0532012-04-16 18:27:27 +00001084 DynamicExceptions,
1085 DynamicExceptionRanges,
Richard Smith0b3a4622014-11-13 20:01:57 +00001086 NoexceptExpr,
1087 ExceptionSpecTokens);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001088
1089 if (ESpecType != EST_None)
1090 DeclEndLoc = ESpecRange.getEnd();
1091
1092 // Parse attribute-specifier[opt].
Richard Smith89645bc2013-01-02 12:01:23 +00001093 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001094
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001095 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1096
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001097 // Parse trailing-return-type[opt].
Richard Smith700537c2012-06-12 01:51:59 +00001098 TypeResult TrailingReturnType;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001099 if (Tok.is(tok::arrow)) {
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001100 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001101 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001102 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001103 if (Range.getEnd().isValid())
1104 DeclEndLoc = Range.getEnd();
1105 }
1106
1107 PrototypeScope.Exit();
1108
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001109 SourceLocation NoLoc;
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001110 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001111 /*isAmbiguous=*/false,
1112 LParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001113 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001114 EllipsisLoc, RParenLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001115 DS.getTypeQualifiers(),
1116 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001117 /*RefQualifierLoc=*/NoLoc,
1118 /*ConstQualifierLoc=*/NoLoc,
1119 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001120 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001121 MutableLoc,
1122 ESpecType, ESpecRange.getBegin(),
1123 DynamicExceptions.data(),
1124 DynamicExceptionRanges.data(),
1125 DynamicExceptions.size(),
1126 NoexceptExpr.isUsable() ?
Craig Topper161e4db2014-05-21 06:02:52 +00001127 NoexceptExpr.get() : nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001128 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001129 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001130 TrailingReturnType),
1131 Attr, DeclEndLoc);
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001132 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001133 Tok.is(tok::kw___attribute) ||
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001134 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1135 // It's common to forget that one needs '()' before 'mutable', an attribute
1136 // specifier, or the result type. Deal with this.
1137 unsigned TokKind = 0;
1138 switch (Tok.getKind()) {
1139 case tok::kw_mutable: TokKind = 0; break;
1140 case tok::arrow: TokKind = 1; break;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001141 case tok::kw___attribute:
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001142 case tok::l_square: TokKind = 2; break;
1143 default: llvm_unreachable("Unknown token kind");
1144 }
1145
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001146 Diag(Tok, diag::err_lambda_missing_parens)
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001147 << TokKind
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001148 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1149 SourceLocation DeclLoc = Tok.getLocation();
1150 SourceLocation DeclEndLoc = DeclLoc;
Aaron Ballmane8d69b72014-03-12 00:01:07 +00001151
1152 // GNU-style attributes must be parsed before the mutable specifier to be
1153 // compatible with GCC.
1154 ParsedAttributes Attr(AttrFactory);
1155 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1156
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001157 // Parse 'mutable', if it's there.
1158 SourceLocation MutableLoc;
1159 if (Tok.is(tok::kw_mutable)) {
1160 MutableLoc = ConsumeToken();
1161 DeclEndLoc = MutableLoc;
1162 }
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001163
1164 // Parse attribute-specifier[opt].
Aaron Ballmanb5c59f52014-03-11 13:03:15 +00001165 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1166
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001167 // Parse the return type, if there is one.
Richard Smith700537c2012-06-12 01:51:59 +00001168 TypeResult TrailingReturnType;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001169 if (Tok.is(tok::arrow)) {
1170 SourceRange Range;
Richard Smith700537c2012-06-12 01:51:59 +00001171 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001172 if (Range.getEnd().isValid())
1173 DeclEndLoc = Range.getEnd();
1174 }
1175
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001176 SourceLocation NoLoc;
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001177 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001178 /*isAmbiguous=*/false,
1179 /*LParenLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001180 /*Params=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001181 /*NumParams=*/0,
1182 /*EllipsisLoc=*/NoLoc,
1183 /*RParenLoc=*/NoLoc,
1184 /*TypeQuals=*/0,
1185 /*RefQualifierIsLValueRef=*/true,
1186 /*RefQualifierLoc=*/NoLoc,
1187 /*ConstQualifierLoc=*/NoLoc,
1188 /*VolatileQualifierLoc=*/NoLoc,
Hal Finkel23a07392014-10-20 17:32:04 +00001189 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001190 MutableLoc,
1191 EST_None,
1192 /*ESpecLoc=*/NoLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00001193 /*Exceptions=*/nullptr,
1194 /*ExceptionRanges=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001195 /*NumExceptions=*/0,
Craig Topper161e4db2014-05-21 06:02:52 +00001196 /*NoexceptExpr=*/nullptr,
Richard Smith0b3a4622014-11-13 20:01:57 +00001197 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnaraaeeb9892012-10-04 21:42:10 +00001198 DeclLoc, DeclEndLoc, D,
1199 TrailingReturnType),
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001200 Attr, DeclEndLoc);
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001201 }
Douglas Gregor6746c5d2012-02-16 21:53:36 +00001202
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001203
Eli Friedman4817cf72012-01-06 03:05:34 +00001204 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1205 // it.
Douglas Gregorb8389972012-02-21 22:51:27 +00001206 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorb8389972012-02-21 22:51:27 +00001207 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman4817cf72012-01-06 03:05:34 +00001208
Eli Friedman71c80552012-01-05 03:35:19 +00001209 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1210
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001211 // Parse compound-statement.
Eli Friedmanc7c97142012-01-04 02:40:39 +00001212 if (!Tok.is(tok::l_brace)) {
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001213 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmanc7c97142012-01-04 02:40:39 +00001214 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1215 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001216 }
1217
Eli Friedmanc7c97142012-01-04 02:40:39 +00001218 StmtResult Stmt(ParseCompoundStatementBody());
1219 BodyScope.Exit();
1220
Eli Friedman898caf82012-01-04 02:46:53 +00001221 if (!Stmt.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001222 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
Eli Friedmanc7c97142012-01-04 02:40:39 +00001223
Eli Friedman898caf82012-01-04 02:46:53 +00001224 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1225 return ExprError();
Douglas Gregordb0b9f12011-08-04 15:30:47 +00001226}
1227
Chris Lattner29375652006-12-04 18:06:35 +00001228/// ParseCXXCasts - This handles the various ways to cast expressions to another
1229/// type.
1230///
1231/// postfix-expression: [C++ 5.2p1]
1232/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1233/// 'static_cast' '<' type-name '>' '(' expression ')'
1234/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1235/// 'const_cast' '<' type-name '>' '(' expression ')'
1236///
John McCalldadc5752010-08-24 06:29:42 +00001237ExprResult Parser::ParseCXXCasts() {
Chris Lattner29375652006-12-04 18:06:35 +00001238 tok::TokenKind Kind = Tok.getKind();
Craig Topper161e4db2014-05-21 06:02:52 +00001239 const char *CastName = nullptr; // For error messages
Chris Lattner29375652006-12-04 18:06:35 +00001240
1241 switch (Kind) {
David Blaikieaa347f92011-09-23 20:26:49 +00001242 default: llvm_unreachable("Unknown C++ cast!");
Chris Lattner29375652006-12-04 18:06:35 +00001243 case tok::kw_const_cast: CastName = "const_cast"; break;
1244 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1245 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1246 case tok::kw_static_cast: CastName = "static_cast"; break;
1247 }
1248
1249 SourceLocation OpLoc = ConsumeToken();
1250 SourceLocation LAngleBracketLoc = Tok.getLocation();
1251
Richard Smith55858492011-04-14 21:45:45 +00001252 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1253 // diagnose error, suggest fix, and recover parsing.
Richard Smith62e66302012-08-20 17:37:52 +00001254 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1255 Token Next = NextToken();
1256 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1257 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1258 }
Richard Smith55858492011-04-14 21:45:45 +00001259
Chris Lattner29375652006-12-04 18:06:35 +00001260 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redld65cea82008-12-11 22:51:44 +00001261 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001262
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001263 // Parse the common declaration-specifiers piece.
1264 DeclSpec DS(AttrFactory);
1265 ParseSpecifierQualifierList(DS);
1266
1267 // Parse the abstract-declarator, if present.
1268 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1269 ParseDeclarator(DeclaratorInfo);
1270
Chris Lattner29375652006-12-04 18:06:35 +00001271 SourceLocation RAngleBracketLoc = Tok.getLocation();
1272
Alp Toker383d2c42014-01-01 03:08:43 +00001273 if (ExpectAndConsume(tok::greater))
Alp Tokerec543272013-12-24 09:48:30 +00001274 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Chris Lattner29375652006-12-04 18:06:35 +00001275
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001276 SourceLocation LParenLoc, RParenLoc;
1277 BalancedDelimiterTracker T(*this, tok::l_paren);
Chris Lattner29375652006-12-04 18:06:35 +00001278
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001279 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001280 return ExprError();
Chris Lattner29375652006-12-04 18:06:35 +00001281
John McCalldadc5752010-08-24 06:29:42 +00001282 ExprResult Result = ParseExpression();
Mike Stump11289f42009-09-09 15:08:12 +00001283
Argyrios Kyrtzidis387a3342009-05-22 10:23:16 +00001284 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001285 T.consumeClose();
Chris Lattner29375652006-12-04 18:06:35 +00001286
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001287 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregore200adc2008-10-27 19:41:14 +00001288 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis7451d1c2011-07-01 22:22:50 +00001289 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor220cac52009-02-18 17:45:20 +00001290 RAngleBracketLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001291 T.getOpenLocation(), Result.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001292 T.getCloseLocation());
Chris Lattner29375652006-12-04 18:06:35 +00001293
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001294 return Result;
Chris Lattner29375652006-12-04 18:06:35 +00001295}
Bill Wendling4073ed52007-02-13 01:51:42 +00001296
Sebastian Redlc4704762008-11-11 11:37:55 +00001297/// ParseCXXTypeid - This handles the C++ typeid expression.
1298///
1299/// postfix-expression: [C++ 5.2p1]
1300/// 'typeid' '(' expression ')'
1301/// 'typeid' '(' type-id ')'
1302///
John McCalldadc5752010-08-24 06:29:42 +00001303ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc4704762008-11-11 11:37:55 +00001304 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1305
1306 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001307 SourceLocation LParenLoc, RParenLoc;
1308 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc4704762008-11-11 11:37:55 +00001309
1310 // typeid expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001311 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redld65cea82008-12-11 22:51:44 +00001312 return ExprError();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001313 LParenLoc = T.getOpenLocation();
Sebastian Redlc4704762008-11-11 11:37:55 +00001314
John McCalldadc5752010-08-24 06:29:42 +00001315 ExprResult Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001316
Richard Smith4f605af2012-08-18 00:55:03 +00001317 // C++0x [expr.typeid]p3:
1318 // When typeid is applied to an expression other than an lvalue of a
1319 // polymorphic class type [...] The expression is an unevaluated
1320 // operand (Clause 5).
1321 //
1322 // Note that we can't tell whether the expression is an lvalue of a
1323 // polymorphic class type until after we've parsed the expression; we
1324 // speculatively assume the subexpression is unevaluated, and fix it up
1325 // later.
1326 //
1327 // We enter the unevaluated context before trying to determine whether we
1328 // have a type-id, because the tentative parse logic will try to resolve
1329 // names, and must treat them as unevaluated.
Eli Friedman15681d62012-09-26 04:34:21 +00001330 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1331 Sema::ReuseLambdaContextDecl);
Richard Smith4f605af2012-08-18 00:55:03 +00001332
Sebastian Redlc4704762008-11-11 11:37:55 +00001333 if (isTypeIdInParens()) {
Douglas Gregor220cac52009-02-18 17:45:20 +00001334 TypeResult Ty = ParseTypeName();
Sebastian Redlc4704762008-11-11 11:37:55 +00001335
1336 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001337 T.consumeClose();
1338 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001339 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00001340 return ExprError();
Sebastian Redlc4704762008-11-11 11:37:55 +00001341
1342 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallba7bf592010-08-24 05:47:05 +00001343 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001344 } else {
1345 Result = ParseExpression();
1346
1347 // Match the ')'.
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001348 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001349 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc4704762008-11-11 11:37:55 +00001350 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001351 T.consumeClose();
1352 RParenLoc = T.getCloseLocation();
Douglas Gregor4c7c1092010-09-08 23:14:30 +00001353 if (RParenLoc.isInvalid())
1354 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00001355
Sebastian Redlc4704762008-11-11 11:37:55 +00001356 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001357 Result.get(), RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +00001358 }
1359 }
1360
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001361 return Result;
Sebastian Redlc4704762008-11-11 11:37:55 +00001362}
1363
Francois Pichet9f4f2072010-09-08 12:20:18 +00001364/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1365///
1366/// '__uuidof' '(' expression ')'
1367/// '__uuidof' '(' type-id ')'
1368///
1369ExprResult Parser::ParseCXXUuidof() {
1370 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1371
1372 SourceLocation OpLoc = ConsumeToken();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001373 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001374
1375 // __uuidof expressions are always parenthesized.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001376 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet9f4f2072010-09-08 12:20:18 +00001377 return ExprError();
1378
1379 ExprResult Result;
1380
1381 if (isTypeIdInParens()) {
1382 TypeResult Ty = ParseTypeName();
1383
1384 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001385 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001386
1387 if (Ty.isInvalid())
1388 return ExprError();
1389
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001390 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1391 Ty.get().getAsOpaquePtr(),
1392 T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001393 } else {
1394 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1395 Result = ParseExpression();
1396
1397 // Match the ')'.
1398 if (Result.isInvalid())
Alexey Bataevee6507d2013-11-18 08:17:37 +00001399 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet9f4f2072010-09-08 12:20:18 +00001400 else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001401 T.consumeClose();
Francois Pichet9f4f2072010-09-08 12:20:18 +00001402
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001403 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1404 /*isType=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001405 Result.get(), T.getCloseLocation());
Francois Pichet9f4f2072010-09-08 12:20:18 +00001406 }
1407 }
1408
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001409 return Result;
Francois Pichet9f4f2072010-09-08 12:20:18 +00001410}
1411
Douglas Gregore610ada2010-02-24 18:44:31 +00001412/// \brief Parse a C++ pseudo-destructor expression after the base,
1413/// . or -> operator, and nested-name-specifier have already been
1414/// parsed.
1415///
1416/// postfix-expression: [C++ 5.2]
1417/// postfix-expression . pseudo-destructor-name
1418/// postfix-expression -> pseudo-destructor-name
1419///
1420/// pseudo-destructor-name:
1421/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1422/// ::[opt] nested-name-specifier template simple-template-id ::
1423/// ~type-name
1424/// ::[opt] nested-name-specifier[opt] ~type-name
1425///
John McCalldadc5752010-08-24 06:29:42 +00001426ExprResult
Craig Toppera2c51532014-10-30 05:30:05 +00001427Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregore610ada2010-02-24 18:44:31 +00001428 tok::TokenKind OpKind,
1429 CXXScopeSpec &SS,
John McCallba7bf592010-08-24 05:47:05 +00001430 ParsedType ObjectType) {
Douglas Gregore610ada2010-02-24 18:44:31 +00001431 // We're parsing either a pseudo-destructor-name or a dependent
1432 // member access that has the same form as a
1433 // pseudo-destructor-name. We parse both in the same way and let
1434 // the action model sort them out.
1435 //
1436 // Note that the ::[opt] nested-name-specifier[opt] has already
1437 // been parsed, and if there was a simple-template-id, it has
1438 // been coalesced into a template-id annotation token.
1439 UnqualifiedId FirstTypeName;
1440 SourceLocation CCLoc;
1441 if (Tok.is(tok::identifier)) {
1442 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1443 ConsumeToken();
1444 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1445 CCLoc = ConsumeToken();
1446 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001447 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1448 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregore610ada2010-02-24 18:44:31 +00001449 FirstTypeName.setTemplateId(
1450 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1451 ConsumeToken();
1452 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1453 CCLoc = ConsumeToken();
1454 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00001455 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregore610ada2010-02-24 18:44:31 +00001456 }
1457
1458 // Parse the tilde.
1459 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1460 SourceLocation TildeLoc = ConsumeToken();
David Blaikie1d578782011-12-16 16:03:09 +00001461
1462 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1463 DeclSpec DS(AttrFactory);
Benjamin Kramer198e0832011-12-18 12:18:02 +00001464 ParseDecltypeSpecifier(DS);
David Blaikie1d578782011-12-16 16:03:09 +00001465 if (DS.getTypeSpecType() == TST_error)
1466 return ExprError();
1467 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc,
1468 OpKind, TildeLoc, DS,
1469 Tok.is(tok::l_paren));
1470 }
1471
Douglas Gregore610ada2010-02-24 18:44:31 +00001472 if (!Tok.is(tok::identifier)) {
1473 Diag(Tok, diag::err_destructor_tilde_identifier);
1474 return ExprError();
1475 }
1476
1477 // Parse the second type.
1478 UnqualifiedId SecondTypeName;
1479 IdentifierInfo *Name = Tok.getIdentifierInfo();
1480 SourceLocation NameLoc = ConsumeToken();
1481 SecondTypeName.setIdentifier(Name, NameLoc);
1482
1483 // If there is a '<', the second type name is a template-id. Parse
1484 // it as such.
1485 if (Tok.is(tok::less) &&
Abramo Bagnara7945c982012-01-27 09:46:47 +00001486 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1487 Name, NameLoc,
1488 false, ObjectType, SecondTypeName,
1489 /*AssumeTemplateName=*/true))
Douglas Gregore610ada2010-02-24 18:44:31 +00001490 return ExprError();
1491
John McCallb268a282010-08-23 23:25:46 +00001492 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base,
1493 OpLoc, OpKind,
Douglas Gregore610ada2010-02-24 18:44:31 +00001494 SS, FirstTypeName, CCLoc,
1495 TildeLoc, SecondTypeName,
1496 Tok.is(tok::l_paren));
1497}
1498
Bill Wendling4073ed52007-02-13 01:51:42 +00001499/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1500///
1501/// boolean-literal: [C++ 2.13.5]
1502/// 'true'
1503/// 'false'
John McCalldadc5752010-08-24 06:29:42 +00001504ExprResult Parser::ParseCXXBoolLiteral() {
Bill Wendling4073ed52007-02-13 01:51:42 +00001505 tok::TokenKind Kind = Tok.getKind();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001506 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Bill Wendling4073ed52007-02-13 01:51:42 +00001507}
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001508
1509/// ParseThrowExpression - This handles the C++ throw expression.
1510///
1511/// throw-expression: [C++ 15]
1512/// 'throw' assignment-expression[opt]
John McCalldadc5752010-08-24 06:29:42 +00001513ExprResult Parser::ParseThrowExpression() {
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001514 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001515 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redld65cea82008-12-11 22:51:44 +00001516
Chris Lattner65dd8432008-04-06 06:02:23 +00001517 // If the current token isn't the start of an assignment-expression,
1518 // then the expression is not present. This handles things like:
1519 // "C ? throw : (void)42", which is crazy but legal.
1520 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1521 case tok::semi:
1522 case tok::r_paren:
1523 case tok::r_square:
1524 case tok::r_brace:
1525 case tok::colon:
1526 case tok::comma:
Craig Topper161e4db2014-05-21 06:02:52 +00001527 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001528
Chris Lattner65dd8432008-04-06 06:02:23 +00001529 default:
John McCalldadc5752010-08-24 06:29:42 +00001530 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001531 if (Expr.isInvalid()) return Expr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001532 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner65dd8432008-04-06 06:02:23 +00001533 }
Chris Lattnerb7e656b2008-02-26 00:51:44 +00001534}
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001535
1536/// ParseCXXThis - This handles the C++ 'this' pointer.
1537///
1538/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1539/// a non-lvalue expression whose value is the address of the object for which
1540/// the function is called.
John McCalldadc5752010-08-24 06:29:42 +00001541ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001542 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1543 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001544 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis7bbb20e2008-06-24 22:12:16 +00001545}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001546
1547/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1548/// Can be interpreted either as function-style casting ("int(x)")
1549/// or class type construction ("ClassType(x,y,z)")
1550/// or creation of a value-initialized type ("int()").
Sebastian Redl3da34892011-06-05 12:23:16 +00001551/// See [C++ 5.2.3].
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001552///
1553/// postfix-expression: [C++ 5.2p1]
Sebastian Redl3da34892011-06-05 12:23:16 +00001554/// simple-type-specifier '(' expression-list[opt] ')'
1555/// [C++0x] simple-type-specifier braced-init-list
1556/// typename-specifier '(' expression-list[opt] ')'
1557/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001558///
John McCalldadc5752010-08-24 06:29:42 +00001559ExprResult
Sebastian Redld65cea82008-12-11 22:51:44 +00001560Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001561 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallba7bf592010-08-24 05:47:05 +00001562 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001563
Sebastian Redl3da34892011-06-05 12:23:16 +00001564 assert((Tok.is(tok::l_paren) ||
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001565 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redl3da34892011-06-05 12:23:16 +00001566 && "Expected '(' or '{'!");
Douglas Gregor94a32472011-01-11 00:33:19 +00001567
Sebastian Redl3da34892011-06-05 12:23:16 +00001568 if (Tok.is(tok::l_brace)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001569 ExprResult Init = ParseBraceInitializer();
1570 if (Init.isInvalid())
1571 return Init;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001572 Expr *InitList = Init.get();
Sebastian Redld74dd492012-02-12 18:41:05 +00001573 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1574 MultiExprArg(&InitList, 1),
1575 SourceLocation());
Sebastian Redl3da34892011-06-05 12:23:16 +00001576 } else {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001577 BalancedDelimiterTracker T(*this, tok::l_paren);
1578 T.consumeOpen();
Sebastian Redl3da34892011-06-05 12:23:16 +00001579
Benjamin Kramerf0623432012-08-23 22:51:59 +00001580 ExprVector Exprs;
Sebastian Redl3da34892011-06-05 12:23:16 +00001581 CommaLocsTy CommaLocs;
1582
1583 if (Tok.isNot(tok::r_paren)) {
1584 if (ParseExpressionList(Exprs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001585 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redl3da34892011-06-05 12:23:16 +00001586 return ExprError();
1587 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001588 }
Sebastian Redl3da34892011-06-05 12:23:16 +00001589
1590 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001591 T.consumeClose();
Sebastian Redl3da34892011-06-05 12:23:16 +00001592
1593 // TypeRep could be null, if it references an invalid typedef.
1594 if (!TypeRep)
1595 return ExprError();
1596
1597 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1598 "Unexpected number of commas!");
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001599 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001600 Exprs,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00001601 T.getCloseLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001602 }
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001603}
1604
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001605/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001606///
1607/// condition:
1608/// expression
1609/// type-specifier-seq declarator '=' assignment-expression
Richard Smith2a15b742012-02-22 06:49:09 +00001610/// [C++11] type-specifier-seq declarator '=' initializer-clause
1611/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001612/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1613/// '=' assignment-expression
1614///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001615/// \param ExprOut if the condition was parsed as an expression, the parsed
1616/// expression.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001617///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001618/// \param DeclOut if the condition was parsed as a declaration, the parsed
1619/// declaration.
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001620///
Douglas Gregore60e41a2010-05-06 17:25:47 +00001621/// \param Loc The location of the start of the statement that requires this
1622/// condition, e.g., the "for" in a for loop.
1623///
1624/// \param ConvertToBoolean Whether the condition expression should be
1625/// converted to a boolean value.
1626///
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001627/// \returns true if there was a parsing, false otherwise.
John McCalldadc5752010-08-24 06:29:42 +00001628bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1629 Decl *&DeclOut,
Douglas Gregore60e41a2010-05-06 17:25:47 +00001630 SourceLocation Loc,
1631 bool ConvertToBoolean) {
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001632 if (Tok.is(tok::code_completion)) {
John McCallfaf5fb42010-08-26 23:41:50 +00001633 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00001634 cutOffParsing();
1635 return true;
Douglas Gregor504a6ae2010-01-10 23:08:15 +00001636 }
1637
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001638 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00001639 MaybeParseCXX11Attributes(attrs);
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001640
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001641 if (!isCXXConditionDeclaration()) {
Alexis Hunt6aa9bee2012-06-23 05:07:58 +00001642 ProhibitAttributes(attrs);
1643
Douglas Gregore60e41a2010-05-06 17:25:47 +00001644 // Parse the expression.
John McCalldadc5752010-08-24 06:29:42 +00001645 ExprOut = ParseExpression(); // expression
Craig Topper161e4db2014-05-21 06:02:52 +00001646 DeclOut = nullptr;
John McCalldadc5752010-08-24 06:29:42 +00001647 if (ExprOut.isInvalid())
Douglas Gregore60e41a2010-05-06 17:25:47 +00001648 return true;
1649
1650 // If required, convert to a boolean value.
1651 if (ConvertToBoolean)
John McCalldadc5752010-08-24 06:29:42 +00001652 ExprOut
1653 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1654 return ExprOut.isInvalid();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001655 }
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001656
1657 // type-specifier-seq
John McCall084e83d2011-03-24 11:26:52 +00001658 DeclSpec DS(AttrFactory);
Richard Smith54ecd982013-02-20 19:22:51 +00001659 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001660 ParseSpecifierQualifierList(DS);
1661
1662 // declarator
1663 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1664 ParseDeclarator(DeclaratorInfo);
1665
1666 // simple-asm-expr[opt]
1667 if (Tok.is(tok::kw_asm)) {
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001668 SourceLocation Loc;
John McCalldadc5752010-08-24 06:29:42 +00001669 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00001670 if (AsmLabel.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00001671 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001672 return true;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001673 }
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001674 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00001675 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001676 }
1677
1678 // If attributes are present, parse them.
John McCall53fa7142010-12-24 02:08:15 +00001679 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001680
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001681 // Type-check the declaration itself.
John McCalldadc5752010-08-24 06:29:42 +00001682 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall53fa7142010-12-24 02:08:15 +00001683 DeclaratorInfo);
John McCalldadc5752010-08-24 06:29:42 +00001684 DeclOut = Dcl.get();
1685 ExprOut = ExprError();
Argyrios Kyrtzidisb5c7c512010-10-08 02:39:23 +00001686
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001687 // '=' assignment-expression
Richard Trieuc64d3232012-01-18 22:54:52 +00001688 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith2a15b742012-02-22 06:49:09 +00001689 bool CopyInitialization = isTokenEqualOrEqualTypo();
1690 if (CopyInitialization)
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00001691 ConsumeToken();
Richard Smith2a15b742012-02-22 06:49:09 +00001692
1693 ExprResult InitExpr = ExprError();
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001694 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith2a15b742012-02-22 06:49:09 +00001695 Diag(Tok.getLocation(),
1696 diag::warn_cxx98_compat_generalized_initializer_lists);
1697 InitExpr = ParseBraceInitializer();
1698 } else if (CopyInitialization) {
1699 InitExpr = ParseAssignmentExpression();
1700 } else if (Tok.is(tok::l_paren)) {
1701 // This was probably an attempt to initialize the variable.
1702 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataevee6507d2013-11-18 08:17:37 +00001703 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith2a15b742012-02-22 06:49:09 +00001704 RParen = ConsumeParen();
1705 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1706 diag::err_expected_init_in_condition_lparen)
1707 << SourceRange(LParen, RParen);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001708 } else {
Richard Smith2a15b742012-02-22 06:49:09 +00001709 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1710 diag::err_expected_init_in_condition);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001711 }
Richard Smith2a15b742012-02-22 06:49:09 +00001712
1713 if (!InitExpr.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001714 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smith74aeef52013-04-26 16:15:35 +00001715 DS.containsPlaceholderType());
Richard Smith27d807c2013-04-30 13:56:41 +00001716 else
1717 Actions.ActOnInitializerError(DeclOut);
Richard Smith2a15b742012-02-22 06:49:09 +00001718
Douglas Gregore60e41a2010-05-06 17:25:47 +00001719 // FIXME: Build a reference to this declaration? Convert it to bool?
1720 // (This is currently handled by Sema).
Richard Smithb2bc2e62011-02-21 20:05:19 +00001721
1722 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregore60e41a2010-05-06 17:25:47 +00001723
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00001724 return false;
Argyrios Kyrtzidis2b4072f2008-09-09 20:38:47 +00001725}
1726
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001727/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1728/// This should only be called when the current token is known to be part of
1729/// simple-type-specifier.
1730///
1731/// simple-type-specifier:
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001732/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001733/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1734/// char
1735/// wchar_t
1736/// bool
1737/// short
1738/// int
1739/// long
1740/// signed
1741/// unsigned
1742/// float
1743/// double
1744/// void
1745/// [GNU] typeof-specifier
1746/// [C++0x] auto [TODO]
1747///
1748/// type-name:
1749/// class-name
1750/// enum-name
1751/// typedef-name
1752///
1753void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1754 DS.SetRangeStart(Tok.getLocation());
1755 const char *PrevSpec;
John McCall49bfce42009-08-03 20:12:06 +00001756 unsigned DiagID;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001757 SourceLocation Loc = Tok.getLocation();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001758 const clang::PrintingPolicy &Policy =
1759 Actions.getASTContext().getPrintingPolicy();
Mike Stump11289f42009-09-09 15:08:12 +00001760
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001761 switch (Tok.getKind()) {
Chris Lattner45ddec32009-01-05 00:13:00 +00001762 case tok::identifier: // foo::bar
1763 case tok::coloncolon: // ::foo::bar
David Blaikie83d382b2011-09-23 05:06:16 +00001764 llvm_unreachable("Annotation token should already be formed!");
Mike Stump11289f42009-09-09 15:08:12 +00001765 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001766 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner45ddec32009-01-05 00:13:00 +00001767
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001768 // type-name
Chris Lattnera8a3f732009-01-06 05:06:21 +00001769 case tok::annot_typename: {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001770 if (getTypeAnnotation(Tok))
1771 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001772 getTypeAnnotation(Tok), Policy);
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001773 else
1774 DS.SetTypeSpecError();
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001775
1776 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1777 ConsumeToken();
1778
1779 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1780 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1781 // Objective-C interface. If we don't have Objective-C or a '<', this is
1782 // just a normal reference to a typedef name.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001784 ParseObjCProtocolQualifiers(DS);
1785
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001786 DS.Finish(Diags, PP, Policy);
Douglas Gregor06e41ae2010-10-21 23:17:00 +00001787 return;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001790 // builtin types
1791 case tok::kw_short:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001792 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001793 break;
1794 case tok::kw_long:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001795 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001796 break;
Francois Pichet84133e42011-04-28 01:59:37 +00001797 case tok::kw___int64:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001798 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet84133e42011-04-28 01:59:37 +00001799 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001800 case tok::kw_signed:
John McCall49bfce42009-08-03 20:12:06 +00001801 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001802 break;
1803 case tok::kw_unsigned:
John McCall49bfce42009-08-03 20:12:06 +00001804 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001805 break;
1806 case tok::kw_void:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001807 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001808 break;
1809 case tok::kw_char:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001810 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001811 break;
1812 case tok::kw_int:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001813 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001814 break;
Richard Smithf016bbc2012-04-04 06:24:32 +00001815 case tok::kw___int128:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001816 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smithf016bbc2012-04-04 06:24:32 +00001817 break;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001818 case tok::kw_half:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001819 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001820 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001821 case tok::kw_float:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001822 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001823 break;
1824 case tok::kw_double:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001825 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001826 break;
1827 case tok::kw_wchar_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001828 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001829 break;
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001830 case tok::kw_char16_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001831 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001832 break;
1833 case tok::kw_char32_t:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001834 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Mereditha9ad47d2009-07-14 06:30:34 +00001835 break;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001836 case tok::kw_bool:
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001837 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001838 break;
David Blaikie25896afb2012-01-24 05:47:35 +00001839 case tok::annot_decltype:
1840 case tok::kw_decltype:
1841 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001842 return DS.Finish(Diags, PP, Policy);
Mike Stump11289f42009-09-09 15:08:12 +00001843
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001844 // GNU typeof support.
1845 case tok::kw_typeof:
1846 ParseTypeofSpecifier(DS);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001847 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001848 return;
1849 }
Chris Lattnera8a3f732009-01-06 05:06:21 +00001850 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001851 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1852 else
1853 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001854 ConsumeToken();
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001855 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001856}
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00001857
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001858/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1859/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1860/// e.g., "const short int". Note that the DeclSpec is *not* finished
1861/// by parsing the type-specifier-seq, because these sequences are
1862/// typically followed by some form of declarator. Returns true and
1863/// emits diagnostics if this is not a type-specifier-seq, false
1864/// otherwise.
1865///
1866/// type-specifier-seq: [C++ 8.1]
1867/// type-specifier type-specifier-seq[opt]
1868///
1869bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smithc5b05522012-03-12 07:56:15 +00001870 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Erik Verbruggen888d52a2014-01-15 09:15:43 +00001871 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00001872 return false;
1873}
1874
Douglas Gregor7861a802009-11-03 01:35:08 +00001875/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1876/// some form.
1877///
1878/// This routine is invoked when a '<' is encountered after an identifier or
1879/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1880/// whether the unqualified-id is actually a template-id. This routine will
1881/// then parse the template arguments and form the appropriate template-id to
1882/// return to the caller.
1883///
1884/// \param SS the nested-name-specifier that precedes this template-id, if
1885/// we're actually parsing a qualified-id.
1886///
1887/// \param Name for constructor and destructor names, this is the actual
1888/// identifier that may be a template-name.
1889///
1890/// \param NameLoc the location of the class-name in a constructor or
1891/// destructor.
1892///
1893/// \param EnteringContext whether we're entering the scope of the
1894/// nested-name-specifier.
1895///
Douglas Gregor127ea592009-11-03 21:24:04 +00001896/// \param ObjectType if this unqualified-id occurs within a member access
1897/// expression, the type of the base object whose member is being accessed.
1898///
Douglas Gregor7861a802009-11-03 01:35:08 +00001899/// \param Id as input, describes the template-name or operator-function-id
1900/// that precedes the '<'. If template arguments were parsed successfully,
1901/// will be updated with the template-id.
1902///
Douglas Gregore610ada2010-02-24 18:44:31 +00001903/// \param AssumeTemplateId When true, this routine will assume that the name
1904/// refers to a template without performing name lookup to verify.
1905///
Douglas Gregor7861a802009-11-03 01:35:08 +00001906/// \returns true if a parse error occurred, false otherwise.
1907bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001908 SourceLocation TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00001909 IdentifierInfo *Name,
1910 SourceLocation NameLoc,
1911 bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00001912 ParsedType ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00001913 UnqualifiedId &Id,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001914 bool AssumeTemplateId) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00001915 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1916 "Expected '<' to finish parsing a template-id");
Douglas Gregor7861a802009-11-03 01:35:08 +00001917
1918 TemplateTy Template;
1919 TemplateNameKind TNK = TNK_Non_template;
1920 switch (Id.getKind()) {
1921 case UnqualifiedId::IK_Identifier:
Douglas Gregor3cf81312009-11-03 23:16:33 +00001922 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunted0530f2009-11-28 08:58:14 +00001923 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregore610ada2010-02-24 18:44:31 +00001924 if (AssumeTemplateId) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001925 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregorbb119652010-06-16 23:00:59 +00001926 Id, ObjectType, EnteringContext,
1927 Template);
1928 if (TNK == TNK_Non_template)
1929 return true;
Douglas Gregor786123d2010-05-21 23:18:07 +00001930 } else {
1931 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001932 TNK = Actions.isTemplateName(getCurScope(), SS,
1933 TemplateKWLoc.isValid(), Id,
1934 ObjectType, EnteringContext, Template,
Douglas Gregor786123d2010-05-21 23:18:07 +00001935 MemberOfUnknownSpecialization);
1936
1937 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1938 ObjectType && IsTemplateArgumentList()) {
1939 // We have something like t->getAs<T>(), where getAs is a
1940 // member of an unknown specialization. However, this will only
1941 // parse correctly as a template, so suggest the keyword 'template'
1942 // before 'getAs' and treat this as a dependent template name.
1943 std::string Name;
1944 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1945 Name = Id.Identifier->getName();
1946 else {
1947 Name = "operator ";
1948 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1949 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1950 else
1951 Name += Id.Identifier->getName();
1952 }
1953 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1954 << Name
1955 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnara7945c982012-01-27 09:46:47 +00001956 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1957 SS, TemplateKWLoc, Id,
1958 ObjectType, EnteringContext,
1959 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001960 if (TNK == TNK_Non_template)
Douglas Gregor786123d2010-05-21 23:18:07 +00001961 return true;
1962 }
1963 }
Douglas Gregor7861a802009-11-03 01:35:08 +00001964 break;
1965
Douglas Gregor3cf81312009-11-03 23:16:33 +00001966 case UnqualifiedId::IK_ConstructorName: {
1967 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001968 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001969 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001970 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1971 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001972 EnteringContext, Template,
1973 MemberOfUnknownSpecialization);
Douglas Gregor7861a802009-11-03 01:35:08 +00001974 break;
1975 }
1976
Douglas Gregor3cf81312009-11-03 23:16:33 +00001977 case UnqualifiedId::IK_DestructorName: {
1978 UnqualifiedId TemplateName;
Douglas Gregor786123d2010-05-21 23:18:07 +00001979 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001980 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001981 if (ObjectType) {
Abramo Bagnara7945c982012-01-27 09:46:47 +00001982 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1983 SS, TemplateKWLoc, TemplateName,
1984 ObjectType, EnteringContext,
1985 Template);
Douglas Gregorbb119652010-06-16 23:00:59 +00001986 if (TNK == TNK_Non_template)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001987 return true;
1988 } else {
Abramo Bagnara7c5dee42010-08-06 12:11:11 +00001989 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
1990 TemplateName, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001991 EnteringContext, Template,
1992 MemberOfUnknownSpecialization);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001993
John McCallba7bf592010-08-24 05:47:05 +00001994 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00001995 Diag(NameLoc, diag::err_destructor_template_id)
1996 << Name << SS.getRange();
Douglas Gregor30d60cb2009-11-03 19:44:04 +00001997 return true;
1998 }
1999 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002000 break;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002001 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002002
2003 default:
2004 return false;
2005 }
2006
2007 if (TNK == TNK_Non_template)
2008 return false;
2009
2010 // Parse the enclosed template argument list.
2011 SourceLocation LAngleLoc, RAngleLoc;
2012 TemplateArgList TemplateArgs;
Douglas Gregorb22ee882010-05-05 05:58:24 +00002013 if (Tok.is(tok::less) &&
2014 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregore7c20652011-03-02 00:47:37 +00002015 SS, true, LAngleLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002016 TemplateArgs,
Douglas Gregor7861a802009-11-03 01:35:08 +00002017 RAngleLoc))
2018 return true;
2019
2020 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Alexis Hunted0530f2009-11-28 08:58:14 +00002021 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2022 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002023 // Form a parsed representation of the template-id to be stored in the
2024 // UnqualifiedId.
2025 TemplateIdAnnotation *TemplateId
Benjamin Kramer1e6b6062012-04-14 12:14:03 +00002026 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor7861a802009-11-03 01:35:08 +00002027
Richard Smith72bfbd82013-12-04 00:28:23 +00002028 // FIXME: Store name for literal operator too.
Douglas Gregor7861a802009-11-03 01:35:08 +00002029 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2030 TemplateId->Name = Id.Identifier;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002031 TemplateId->Operator = OO_None;
Douglas Gregor7861a802009-11-03 01:35:08 +00002032 TemplateId->TemplateNameLoc = Id.StartLocation;
2033 } else {
Craig Topper161e4db2014-05-21 06:02:52 +00002034 TemplateId->Name = nullptr;
Douglas Gregor3cf81312009-11-03 23:16:33 +00002035 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2036 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor7861a802009-11-03 01:35:08 +00002037 }
2038
Douglas Gregore7c20652011-03-02 00:47:37 +00002039 TemplateId->SS = SS;
Benjamin Kramer807c2db2012-02-19 23:37:39 +00002040 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall3e56fd42010-08-23 07:28:44 +00002041 TemplateId->Template = Template;
Douglas Gregor7861a802009-11-03 01:35:08 +00002042 TemplateId->Kind = TNK;
2043 TemplateId->LAngleLoc = LAngleLoc;
2044 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002045 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor7861a802009-11-03 01:35:08 +00002046 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregorb53edfb2009-11-10 19:49:08 +00002047 Arg != ArgEnd; ++Arg)
Douglas Gregor7861a802009-11-03 01:35:08 +00002048 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor7861a802009-11-03 01:35:08 +00002049
2050 Id.setTemplateId(TemplateId);
2051 return false;
2052 }
2053
2054 // Bundle the template arguments together.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002055 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnara4244b432012-01-27 08:46:19 +00002056
Douglas Gregor7861a802009-11-03 01:35:08 +00002057 // Constructor and destructor names.
John McCallfaf5fb42010-08-26 23:41:50 +00002058 TypeResult Type
Abramo Bagnara48c05be2012-02-06 14:41:24 +00002059 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2060 Template, NameLoc,
Abramo Bagnara4244b432012-01-27 08:46:19 +00002061 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2062 /*IsCtorOrDtorName=*/true);
Douglas Gregor7861a802009-11-03 01:35:08 +00002063 if (Type.isInvalid())
2064 return true;
2065
2066 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2067 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2068 else
2069 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2070
2071 return false;
2072}
2073
Douglas Gregor71395fa2009-11-04 00:56:37 +00002074/// \brief Parse an operator-function-id or conversion-function-id as part
2075/// of a C++ unqualified-id.
2076///
2077/// This routine is responsible only for parsing the operator-function-id or
2078/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor7861a802009-11-03 01:35:08 +00002079///
2080/// \code
Douglas Gregor7861a802009-11-03 01:35:08 +00002081/// operator-function-id: [C++ 13.5]
2082/// 'operator' operator
2083///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002084/// operator: one of
Douglas Gregor7861a802009-11-03 01:35:08 +00002085/// new delete new[] delete[]
2086/// + - * / % ^ & | ~
2087/// ! = < > += -= *= /= %=
2088/// ^= &= |= << >> >>= <<= == !=
2089/// <= >= && || ++ -- , ->* ->
2090/// () []
2091///
2092/// conversion-function-id: [C++ 12.3.2]
2093/// operator conversion-type-id
2094///
2095/// conversion-type-id:
2096/// type-specifier-seq conversion-declarator[opt]
2097///
2098/// conversion-declarator:
2099/// ptr-operator conversion-declarator[opt]
2100/// \endcode
2101///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002102/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor7861a802009-11-03 01:35:08 +00002103/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2104///
2105/// \param EnteringContext whether we are entering the scope of the
2106/// nested-name-specifier.
2107///
Douglas Gregor71395fa2009-11-04 00:56:37 +00002108/// \param ObjectType if this unqualified-id occurs within a member access
2109/// expression, the type of the base object whose member is being accessed.
2110///
2111/// \param Result on a successful parse, contains the parsed unqualified-id.
2112///
2113/// \returns true if parsing fails, false otherwise.
2114bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallba7bf592010-08-24 05:47:05 +00002115 ParsedType ObjectType,
Douglas Gregor71395fa2009-11-04 00:56:37 +00002116 UnqualifiedId &Result) {
2117 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2118
2119 // Consume the 'operator' keyword.
2120 SourceLocation KeywordLoc = ConsumeToken();
2121
2122 // Determine what kind of operator name we have.
2123 unsigned SymbolIdx = 0;
2124 SourceLocation SymbolLocations[3];
2125 OverloadedOperatorKind Op = OO_None;
2126 switch (Tok.getKind()) {
2127 case tok::kw_new:
2128 case tok::kw_delete: {
2129 bool isNew = Tok.getKind() == tok::kw_new;
2130 // Consume the 'new' or 'delete'.
2131 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002132 // Check for array new/delete.
2133 if (Tok.is(tok::l_square) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002134 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002135 // Consume the '[' and ']'.
2136 BalancedDelimiterTracker T(*this, tok::l_square);
2137 T.consumeOpen();
2138 T.consumeClose();
2139 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002140 return true;
2141
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002142 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2143 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002144 Op = isNew? OO_Array_New : OO_Array_Delete;
2145 } else {
2146 Op = isNew? OO_New : OO_Delete;
2147 }
2148 break;
2149 }
2150
2151#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2152 case tok::Token: \
2153 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2154 Op = OO_##Name; \
2155 break;
2156#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2157#include "clang/Basic/OperatorKinds.def"
2158
2159 case tok::l_paren: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002160 // Consume the '(' and ')'.
2161 BalancedDelimiterTracker T(*this, tok::l_paren);
2162 T.consumeOpen();
2163 T.consumeClose();
2164 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002165 return true;
2166
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002167 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2168 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002169 Op = OO_Call;
2170 break;
2171 }
2172
2173 case tok::l_square: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002174 // Consume the '[' and ']'.
2175 BalancedDelimiterTracker T(*this, tok::l_square);
2176 T.consumeOpen();
2177 T.consumeClose();
2178 if (T.getCloseLocation().isInvalid())
Douglas Gregor71395fa2009-11-04 00:56:37 +00002179 return true;
2180
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002181 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2182 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002183 Op = OO_Subscript;
2184 break;
2185 }
2186
2187 case tok::code_completion: {
2188 // Code completion for the operator name.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002189 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +00002190 cutOffParsing();
Douglas Gregor71395fa2009-11-04 00:56:37 +00002191 // Don't try to parse any further.
2192 return true;
2193 }
2194
2195 default:
2196 break;
2197 }
2198
2199 if (Op != OO_None) {
2200 // We have parsed an operator-function-id.
2201 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2202 return false;
2203 }
Alexis Hunt34458502009-11-28 04:44:28 +00002204
2205 // Parse a literal-operator-id.
2206 //
Richard Smith6f212062012-10-20 08:41:10 +00002207 // literal-operator-id: C++11 [over.literal]
2208 // operator string-literal identifier
2209 // operator user-defined-string-literal
Alexis Hunt34458502009-11-28 04:44:28 +00002210
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002211 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002212 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Alexis Hunt34458502009-11-28 04:44:28 +00002213
Richard Smith7d182a72012-03-08 23:06:02 +00002214 SourceLocation DiagLoc;
2215 unsigned DiagId = 0;
2216
2217 // We're past translation phase 6, so perform string literal concatenation
2218 // before checking for "".
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002219 SmallVector<Token, 4> Toks;
2220 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith7d182a72012-03-08 23:06:02 +00002221 while (isTokenStringLiteral()) {
2222 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smith6f212062012-10-20 08:41:10 +00002223 // C++11 [over.literal]p1:
2224 // The string-literal or user-defined-string-literal in a
2225 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith7d182a72012-03-08 23:06:02 +00002226 DiagLoc = Tok.getLocation();
2227 DiagId = diag::err_literal_operator_string_prefix;
2228 }
2229 Toks.push_back(Tok);
2230 TokLocs.push_back(ConsumeStringToken());
2231 }
2232
Craig Topper9d5583e2014-06-26 04:58:39 +00002233 StringLiteralParser Literal(Toks, PP);
Richard Smith7d182a72012-03-08 23:06:02 +00002234 if (Literal.hadError)
2235 return true;
2236
2237 // Grab the literal operator's suffix, which will be either the next token
2238 // or a ud-suffix from the string literal.
Craig Topper161e4db2014-05-21 06:02:52 +00002239 IdentifierInfo *II = nullptr;
Richard Smith7d182a72012-03-08 23:06:02 +00002240 SourceLocation SuffixLoc;
2241 if (!Literal.getUDSuffix().empty()) {
2242 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2243 SuffixLoc =
2244 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2245 Literal.getUDSuffixOffset(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002246 PP.getSourceManager(), getLangOpts());
Richard Smith7d182a72012-03-08 23:06:02 +00002247 } else if (Tok.is(tok::identifier)) {
2248 II = Tok.getIdentifierInfo();
2249 SuffixLoc = ConsumeToken();
2250 TokLocs.push_back(SuffixLoc);
2251 } else {
Alp Tokerec543272013-12-24 09:48:30 +00002252 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Alexis Hunt34458502009-11-28 04:44:28 +00002253 return true;
2254 }
2255
Richard Smith7d182a72012-03-08 23:06:02 +00002256 // The string literal must be empty.
2257 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smith6f212062012-10-20 08:41:10 +00002258 // C++11 [over.literal]p1:
2259 // The string-literal or user-defined-string-literal in a
2260 // literal-operator-id shall [...] contain no characters
2261 // other than the implicit terminating '\0'.
Richard Smith7d182a72012-03-08 23:06:02 +00002262 DiagLoc = TokLocs.front();
2263 DiagId = diag::err_literal_operator_string_not_empty;
2264 }
2265
2266 if (DiagId) {
2267 // This isn't a valid literal-operator-id, but we think we know
2268 // what the user meant. Tell them what they should have written.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002269 SmallString<32> Str;
Richard Smith7d182a72012-03-08 23:06:02 +00002270 Str += "\"\" ";
2271 Str += II->getName();
2272 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2273 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2274 }
2275
2276 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Richard Smithd091dc12013-12-05 00:58:33 +00002277
2278 return Actions.checkLiteralOperatorId(SS, Result);
Alexis Hunt34458502009-11-28 04:44:28 +00002279 }
Richard Smithd091dc12013-12-05 00:58:33 +00002280
Douglas Gregor71395fa2009-11-04 00:56:37 +00002281 // Parse a conversion-function-id.
2282 //
2283 // conversion-function-id: [C++ 12.3.2]
2284 // operator conversion-type-id
2285 //
2286 // conversion-type-id:
2287 // type-specifier-seq conversion-declarator[opt]
2288 //
2289 // conversion-declarator:
2290 // ptr-operator conversion-declarator[opt]
2291
2292 // Parse the type-specifier-seq.
John McCall084e83d2011-03-24 11:26:52 +00002293 DeclSpec DS(AttrFactory);
Douglas Gregora25d65d2009-11-20 22:03:38 +00002294 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregor71395fa2009-11-04 00:56:37 +00002295 return true;
2296
2297 // Parse the conversion-declarator, which is merely a sequence of
2298 // ptr-operators.
Richard Smith01518fa2013-05-04 01:26:46 +00002299 Declarator D(DS, Declarator::ConversionIdContext);
Craig Topper161e4db2014-05-21 06:02:52 +00002300 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2301
Douglas Gregor71395fa2009-11-04 00:56:37 +00002302 // Finish up the type.
John McCallfaf5fb42010-08-26 23:41:50 +00002303 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregor71395fa2009-11-04 00:56:37 +00002304 if (Ty.isInvalid())
2305 return true;
2306
2307 // Note that this is a conversion-function-id.
2308 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2309 D.getSourceRange().getEnd());
2310 return false;
2311}
2312
2313/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2314/// name of an entity.
2315///
2316/// \code
2317/// unqualified-id: [C++ expr.prim.general]
2318/// identifier
2319/// operator-function-id
2320/// conversion-function-id
2321/// [C++0x] literal-operator-id [TODO]
2322/// ~ class-name
2323/// template-id
2324///
2325/// \endcode
2326///
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00002327/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor71395fa2009-11-04 00:56:37 +00002328/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2329///
2330/// \param EnteringContext whether we are entering the scope of the
2331/// nested-name-specifier.
2332///
Douglas Gregor7861a802009-11-03 01:35:08 +00002333/// \param AllowDestructorName whether we allow parsing of a destructor name.
2334///
2335/// \param AllowConstructorName whether we allow parsing a constructor name.
2336///
Douglas Gregor127ea592009-11-03 21:24:04 +00002337/// \param ObjectType if this unqualified-id occurs within a member access
2338/// expression, the type of the base object whose member is being accessed.
2339///
Douglas Gregor7861a802009-11-03 01:35:08 +00002340/// \param Result on a successful parse, contains the parsed unqualified-id.
2341///
2342/// \returns true if parsing fails, false otherwise.
2343bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2344 bool AllowDestructorName,
2345 bool AllowConstructorName,
John McCallba7bf592010-08-24 05:47:05 +00002346 ParsedType ObjectType,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002347 SourceLocation& TemplateKWLoc,
Douglas Gregor7861a802009-11-03 01:35:08 +00002348 UnqualifiedId &Result) {
Douglas Gregorb22ee882010-05-05 05:58:24 +00002349
2350 // Handle 'A::template B'. This is for template-ids which have not
2351 // already been annotated by ParseOptionalCXXScopeSpecifier().
2352 bool TemplateSpecified = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002353 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002354 (ObjectType || SS.isSet())) {
2355 TemplateSpecified = true;
2356 TemplateKWLoc = ConsumeToken();
2357 }
2358
Douglas Gregor7861a802009-11-03 01:35:08 +00002359 // unqualified-id:
2360 // identifier
2361 // template-id (when it hasn't already been annotated)
2362 if (Tok.is(tok::identifier)) {
2363 // Consume the identifier.
2364 IdentifierInfo *Id = Tok.getIdentifierInfo();
2365 SourceLocation IdLoc = ConsumeToken();
2366
David Blaikiebbafb8a2012-03-11 07:00:24 +00002367 if (!getLangOpts().CPlusPlus) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002368 // If we're not in C++, only identifiers matter. Record the
2369 // identifier and return.
2370 Result.setIdentifier(Id, IdLoc);
2371 return false;
2372 }
2373
Douglas Gregor7861a802009-11-03 01:35:08 +00002374 if (AllowConstructorName &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002375 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002376 // We have parsed a constructor name.
Abramo Bagnara4244b432012-01-27 08:46:19 +00002377 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2378 &SS, false, false,
2379 ParsedType(),
2380 /*IsCtorOrDtorName=*/true,
2381 /*NonTrivialTypeSourceInfo=*/true);
2382 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002383 } else {
2384 // We have parsed an identifier.
2385 Result.setIdentifier(Id, IdLoc);
2386 }
2387
2388 // If the next token is a '<', we may have a template.
Douglas Gregorb22ee882010-05-05 05:58:24 +00002389 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002390 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2391 EnteringContext, ObjectType,
2392 Result, TemplateSpecified);
Douglas Gregor7861a802009-11-03 01:35:08 +00002393
2394 return false;
2395 }
2396
2397 // unqualified-id:
2398 // template-id (already parsed and annotated)
2399 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidisc0c5dd22011-06-22 06:09:49 +00002400 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002401
2402 // If the template-name names the current class, then this is a constructor
2403 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor0be31a22010-07-02 17:43:08 +00002404 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002405 if (SS.isSet()) {
2406 // C++ [class.qual]p2 specifies that a qualified template-name
2407 // is taken as the constructor name where a constructor can be
2408 // declared. Thus, the template arguments are extraneous, so
2409 // complain about them and remove them entirely.
2410 Diag(TemplateId->TemplateNameLoc,
2411 diag::err_out_of_line_constructor_template_id)
2412 << TemplateId->Name
Douglas Gregora771f462010-03-31 17:46:05 +00002413 << FixItHint::CreateRemoval(
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002414 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnara4244b432012-01-27 08:46:19 +00002415 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2416 TemplateId->TemplateNameLoc,
2417 getCurScope(),
2418 &SS, false, false,
2419 ParsedType(),
2420 /*IsCtorOrDtorName=*/true,
2421 /*NontrivialTypeSourceInfo=*/true);
2422 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002423 TemplateId->RAngleLoc);
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002424 ConsumeToken();
2425 return false;
2426 }
2427
2428 Result.setConstructorTemplateId(TemplateId);
2429 ConsumeToken();
2430 return false;
2431 }
2432
Douglas Gregor7861a802009-11-03 01:35:08 +00002433 // We have already parsed a template-id; consume the annotation token as
2434 // our unqualified-id.
Douglas Gregor9de54ea2010-01-13 17:31:36 +00002435 Result.setTemplateId(TemplateId);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002436 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor7861a802009-11-03 01:35:08 +00002437 ConsumeToken();
2438 return false;
2439 }
2440
2441 // unqualified-id:
2442 // operator-function-id
2443 // conversion-function-id
2444 if (Tok.is(tok::kw_operator)) {
Douglas Gregor71395fa2009-11-04 00:56:37 +00002445 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor7861a802009-11-03 01:35:08 +00002446 return true;
2447
Alexis Hunted0530f2009-11-28 08:58:14 +00002448 // If we have an operator-function-id or a literal-operator-id and the next
2449 // token is a '<', we may have a
Douglas Gregor71395fa2009-11-04 00:56:37 +00002450 //
2451 // template-id:
2452 // operator-function-id < template-argument-list[opt] >
Alexis Hunted0530f2009-11-28 08:58:14 +00002453 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2454 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregorb22ee882010-05-05 05:58:24 +00002455 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnara7945c982012-01-27 09:46:47 +00002456 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Craig Topper161e4db2014-05-21 06:02:52 +00002457 nullptr, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002458 EnteringContext, ObjectType,
2459 Result, TemplateSpecified);
Craig Topper161e4db2014-05-21 06:02:52 +00002460
Douglas Gregor7861a802009-11-03 01:35:08 +00002461 return false;
2462 }
2463
David Blaikiebbafb8a2012-03-11 07:00:24 +00002464 if (getLangOpts().CPlusPlus &&
Douglas Gregor411e5ac2010-01-11 23:29:10 +00002465 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor7861a802009-11-03 01:35:08 +00002466 // C++ [expr.unary.op]p10:
2467 // There is an ambiguity in the unary-expression ~X(), where X is a
2468 // class-name. The ambiguity is resolved in favor of treating ~ as a
2469 // unary complement rather than treating ~X as referring to a destructor.
2470
2471 // Parse the '~'.
2472 SourceLocation TildeLoc = ConsumeToken();
David Blaikieecd8a942011-12-08 16:13:53 +00002473
2474 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2475 DeclSpec DS(AttrFactory);
2476 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2477 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2478 Result.setDestructorName(TildeLoc, Type, EndLoc);
2479 return false;
2480 }
2481 return true;
2482 }
Douglas Gregor7861a802009-11-03 01:35:08 +00002483
2484 // Parse the class-name.
2485 if (Tok.isNot(tok::identifier)) {
Douglas Gregorfe17d252010-02-16 19:09:40 +00002486 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor7861a802009-11-03 01:35:08 +00002487 return true;
2488 }
2489
Richard Smithefa6f732014-09-06 02:06:12 +00002490 // If the user wrote ~T::T, correct it to T::~T.
2491 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
2492 if (SS.isSet()) {
2493 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2494 SS.clear();
2495 }
2496 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2497 return true;
2498 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon)) {
2499 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2500 return true;
2501 }
2502
2503 // Recover as if the tilde had been written before the identifier.
2504 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2505 << FixItHint::CreateRemoval(TildeLoc)
2506 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
2507 }
2508
Douglas Gregor7861a802009-11-03 01:35:08 +00002509 // Parse the class-name (or template-name in a simple-template-id).
2510 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2511 SourceLocation ClassNameLoc = ConsumeToken();
Richard Smithefa6f732014-09-06 02:06:12 +00002512
Douglas Gregorb22ee882010-05-05 05:58:24 +00002513 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallba7bf592010-08-24 05:47:05 +00002514 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnara7945c982012-01-27 09:46:47 +00002515 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2516 ClassName, ClassNameLoc,
2517 EnteringContext, ObjectType,
2518 Result, TemplateSpecified);
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002519 }
Richard Smithefa6f732014-09-06 02:06:12 +00002520
Douglas Gregor7861a802009-11-03 01:35:08 +00002521 // Note that this is a destructor name.
John McCallba7bf592010-08-24 05:47:05 +00002522 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2523 ClassNameLoc, getCurScope(),
2524 SS, ObjectType,
2525 EnteringContext);
Douglas Gregorfe17d252010-02-16 19:09:40 +00002526 if (!Ty)
Douglas Gregor7861a802009-11-03 01:35:08 +00002527 return true;
Douglas Gregorfe17d252010-02-16 19:09:40 +00002528
Douglas Gregor7861a802009-11-03 01:35:08 +00002529 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor7861a802009-11-03 01:35:08 +00002530 return false;
2531 }
2532
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002533 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikiebbafb8a2012-03-11 07:00:24 +00002534 << getLangOpts().CPlusPlus;
Douglas Gregor7861a802009-11-03 01:35:08 +00002535 return true;
2536}
2537
Sebastian Redlbd150f42008-11-21 19:14:01 +00002538/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2539/// memory in a typesafe manner and call constructors.
Mike Stump11289f42009-09-09 15:08:12 +00002540///
Chris Lattner109faf22009-01-04 21:25:24 +00002541/// This method is called to parse the new expression after the optional :: has
2542/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2543/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002544///
2545/// new-expression:
2546/// '::'[opt] 'new' new-placement[opt] new-type-id
2547/// new-initializer[opt]
2548/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2549/// new-initializer[opt]
2550///
2551/// new-placement:
2552/// '(' expression-list ')'
2553///
Sebastian Redl351bb782008-12-02 14:43:59 +00002554/// new-type-id:
2555/// type-specifier-seq new-declarator[opt]
Douglas Gregora3a020a2011-04-15 19:40:02 +00002556/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redl351bb782008-12-02 14:43:59 +00002557///
2558/// new-declarator:
2559/// ptr-operator new-declarator[opt]
2560/// direct-new-declarator
2561///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002562/// new-initializer:
2563/// '(' expression-list[opt] ')'
Sebastian Redl3da34892011-06-05 12:23:16 +00002564/// [C++0x] braced-init-list
Sebastian Redlbd150f42008-11-21 19:14:01 +00002565///
John McCalldadc5752010-08-24 06:29:42 +00002566ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002567Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2568 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2569 ConsumeToken(); // Consume 'new'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002570
2571 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2572 // second form of new-expression. It can't be a new-type-id.
2573
Benjamin Kramerf0623432012-08-23 22:51:59 +00002574 ExprVector PlacementArgs;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002575 SourceLocation PlacementLParen, PlacementRParen;
2576
Douglas Gregorf2753b32010-07-13 15:54:32 +00002577 SourceRange TypeIdParens;
John McCall084e83d2011-03-24 11:26:52 +00002578 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +00002579 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002580 if (Tok.is(tok::l_paren)) {
2581 // If it turns out to be a placement, we change the type location.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002582 BalancedDelimiterTracker T(*this, tok::l_paren);
2583 T.consumeOpen();
2584 PlacementLParen = T.getOpenLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002585 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002586 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002587 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002588 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002589
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002590 T.consumeClose();
2591 PlacementRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002592 if (PlacementRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002593 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002594 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002595 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002596
Sebastian Redl351bb782008-12-02 14:43:59 +00002597 if (PlacementArgs.empty()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002598 // Reset the placement locations. There was no placement.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002599 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002600 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002601 } else {
2602 // We still need the type.
2603 if (Tok.is(tok::l_paren)) {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002604 BalancedDelimiterTracker T(*this, tok::l_paren);
2605 T.consumeOpen();
Douglas Gregora3a020a2011-04-15 19:40:02 +00002606 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002607 ParseSpecifierQualifierList(DS);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002608 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002609 ParseDeclarator(DeclaratorInfo);
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002610 T.consumeClose();
2611 TypeIdParens = T.getRange();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002612 } else {
Douglas Gregora3a020a2011-04-15 19:40:02 +00002613 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002614 if (ParseCXXTypeSpecifierSeq(DS))
2615 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002616 else {
2617 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002618 ParseDeclaratorInternal(DeclaratorInfo,
2619 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002620 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002621 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002622 }
2623 } else {
Sebastian Redl351bb782008-12-02 14:43:59 +00002624 // A new-type-id is a simplified type-id, where essentially the
2625 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregora3a020a2011-04-15 19:40:02 +00002626 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redl351bb782008-12-02 14:43:59 +00002627 if (ParseCXXTypeSpecifierSeq(DS))
2628 DeclaratorInfo.setInvalidType(true);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002629 else {
2630 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002631 ParseDeclaratorInternal(DeclaratorInfo,
2632 &Parser::ParseDirectNewDeclarator);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002633 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002634 }
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002635 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002636 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002637 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002638 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002639
Sebastian Redl6047f072012-02-16 12:22:20 +00002640 ExprResult Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002641
2642 if (Tok.is(tok::l_paren)) {
Sebastian Redl6047f072012-02-16 12:22:20 +00002643 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramerf0623432012-08-23 22:51:59 +00002644 ExprVector ConstructorArgs;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002645 BalancedDelimiterTracker T(*this, tok::l_paren);
2646 T.consumeOpen();
2647 ConstructorLParen = T.getOpenLocation();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002648 if (Tok.isNot(tok::r_paren)) {
2649 CommaLocsTy CommaLocs;
Sebastian Redl351bb782008-12-02 14:43:59 +00002650 if (ParseExpressionList(ConstructorArgs, CommaLocs)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002651 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002652 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002653 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002654 }
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002655 T.consumeClose();
2656 ConstructorRParen = T.getCloseLocation();
Sebastian Redl351bb782008-12-02 14:43:59 +00002657 if (ConstructorRParen.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002658 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redld65cea82008-12-11 22:51:44 +00002659 return ExprError();
Sebastian Redl351bb782008-12-02 14:43:59 +00002660 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002661 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2662 ConstructorRParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002663 ConstructorArgs);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002664 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith5d164bc2011-10-15 05:09:34 +00002665 Diag(Tok.getLocation(),
2666 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl6047f072012-02-16 12:22:20 +00002667 Initializer = ParseBraceInitializer();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002668 }
Sebastian Redl6047f072012-02-16 12:22:20 +00002669 if (Initializer.isInvalid())
2670 return Initializer;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002671
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002672 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002673 PlacementArgs, PlacementRParen,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002674 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002675}
2676
Sebastian Redlbd150f42008-11-21 19:14:01 +00002677/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2678/// passed to ParseDeclaratorInternal.
2679///
2680/// direct-new-declarator:
2681/// '[' expression ']'
2682/// direct-new-declarator '[' constant-expression ']'
2683///
Chris Lattner109faf22009-01-04 21:25:24 +00002684void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002685 // Parse the array dimensions.
2686 bool first = true;
2687 while (Tok.is(tok::l_square)) {
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002688 // An array-size expression can't start with a lambda.
2689 if (CheckProhibitedCXX11Attribute())
2690 continue;
2691
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002692 BalancedDelimiterTracker T(*this, tok::l_square);
2693 T.consumeOpen();
2694
John McCalldadc5752010-08-24 06:29:42 +00002695 ExprResult Size(first ? ParseExpression()
Sebastian Redl59b5e512008-12-11 21:36:32 +00002696 : ParseConstantExpression());
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002697 if (Size.isInvalid()) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002698 // Recover
Alexey Bataevee6507d2013-11-18 08:17:37 +00002699 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002700 return;
2701 }
2702 first = false;
2703
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002704 T.consumeClose();
John McCall084e83d2011-03-24 11:26:52 +00002705
Bill Wendling44426052012-12-20 19:22:21 +00002706 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002707 ParsedAttributes Attrs(AttrFactory);
Richard Smith89645bc2013-01-02 12:01:23 +00002708 MaybeParseCXX11Attributes(Attrs);
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002709
John McCall084e83d2011-03-24 11:26:52 +00002710 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall53fa7142010-12-24 02:08:15 +00002711 /*static=*/false, /*star=*/false,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002712 Size.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002713 T.getOpenLocation(),
2714 T.getCloseLocation()),
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002715 Attrs, T.getCloseLocation());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002716
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002717 if (T.getCloseLocation().isInvalid())
Sebastian Redlbd150f42008-11-21 19:14:01 +00002718 return;
2719 }
2720}
2721
2722/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2723/// This ambiguity appears in the syntax of the C++ new operator.
2724///
2725/// new-expression:
2726/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2727/// new-initializer[opt]
2728///
2729/// new-placement:
2730/// '(' expression-list ')'
2731///
John McCall37ad5512010-08-23 06:44:23 +00002732bool Parser::ParseExpressionListOrTypeId(
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002733 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner109faf22009-01-04 21:25:24 +00002734 Declarator &D) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002735 // The '(' was already consumed.
2736 if (isTypeIdInParens()) {
Sebastian Redl351bb782008-12-02 14:43:59 +00002737 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002738 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00002739 ParseDeclarator(D);
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00002740 return D.isInvalidType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002741 }
2742
2743 // It's not a type, it has to be an expression list.
2744 // Discard the comma locations - ActOnCXXNew has enough parameters.
2745 CommaLocsTy CommaLocs;
2746 return ParseExpressionList(PlacementArgs, CommaLocs);
2747}
2748
2749/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2750/// to free memory allocated by new.
2751///
Chris Lattner109faf22009-01-04 21:25:24 +00002752/// This method is called to parse the 'delete' expression after the optional
2753/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2754/// and "Start" is its location. Otherwise, "Start" is the location of the
2755/// 'delete' token.
2756///
Sebastian Redlbd150f42008-11-21 19:14:01 +00002757/// delete-expression:
2758/// '::'[opt] 'delete' cast-expression
2759/// '::'[opt] 'delete' '[' ']' cast-expression
John McCalldadc5752010-08-24 06:29:42 +00002760ExprResult
Chris Lattner109faf22009-01-04 21:25:24 +00002761Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2762 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2763 ConsumeToken(); // Consume 'delete'
Sebastian Redlbd150f42008-11-21 19:14:01 +00002764
2765 // Array delete?
2766 bool ArrayDelete = false;
Richard Smith7bdcc4a2012-04-10 01:32:12 +00002767 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith10c60722012-08-09 19:01:51 +00002768 // C++11 [expr.delete]p1:
2769 // Whenever the delete keyword is followed by empty square brackets, it
2770 // shall be interpreted as [array delete].
2771 // [Footnote: A lambda expression with a lambda-introducer that consists
2772 // of empty square brackets can follow the delete keyword if
2773 // the lambda expression is enclosed in parentheses.]
2774 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2775 // lambda-introducer.
Sebastian Redlbd150f42008-11-21 19:14:01 +00002776 ArrayDelete = true;
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002777 BalancedDelimiterTracker T(*this, tok::l_square);
2778
2779 T.consumeOpen();
2780 T.consumeClose();
2781 if (T.getCloseLocation().isInvalid())
Sebastian Redld65cea82008-12-11 22:51:44 +00002782 return ExprError();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002783 }
2784
John McCalldadc5752010-08-24 06:29:42 +00002785 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl17f2c7d2008-12-09 13:15:23 +00002786 if (Operand.isInvalid())
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002787 return Operand;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002788
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002789 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redlbd150f42008-11-21 19:14:01 +00002790}
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002791
Douglas Gregor29c42f22012-02-24 07:38:34 +00002792static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2793 switch (kind) {
2794 default: llvm_unreachable("Not a known type trait");
Alp Toker95e7ff22014-01-01 05:57:51 +00002795#define TYPE_TRAIT_1(Spelling, Name, Key) \
2796case tok::kw_ ## Spelling: return UTT_ ## Name;
Alp Tokercbb90342013-12-13 20:49:58 +00002797#define TYPE_TRAIT_2(Spelling, Name, Key) \
2798case tok::kw_ ## Spelling: return BTT_ ## Name;
2799#include "clang/Basic/TokenKinds.def"
Alp Toker40f9b1c2013-12-12 21:23:03 +00002800#define TYPE_TRAIT_N(Spelling, Name, Key) \
2801 case tok::kw_ ## Spelling: return TT_ ## Name;
2802#include "clang/Basic/TokenKinds.def"
Douglas Gregor29c42f22012-02-24 07:38:34 +00002803 }
2804}
2805
John Wiegley6242b6a2011-04-28 00:16:57 +00002806static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2807 switch(kind) {
2808 default: llvm_unreachable("Not a known binary type trait");
2809 case tok::kw___array_rank: return ATT_ArrayRank;
2810 case tok::kw___array_extent: return ATT_ArrayExtent;
2811 }
2812}
2813
John Wiegleyf9f65842011-04-25 06:54:41 +00002814static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2815 switch(kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002816 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegleyf9f65842011-04-25 06:54:41 +00002817 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2818 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2819 }
2820}
2821
Alp Toker40f9b1c2013-12-12 21:23:03 +00002822static unsigned TypeTraitArity(tok::TokenKind kind) {
2823 switch (kind) {
2824 default: llvm_unreachable("Not a known type trait");
2825#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2826#include "clang/Basic/TokenKinds.def"
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002827 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002828}
2829
Douglas Gregor29c42f22012-02-24 07:38:34 +00002830/// \brief Parse the built-in type-trait pseudo-functions that allow
2831/// implementation of the TR1/C++11 type traits templates.
2832///
2833/// primary-expression:
Alp Toker40f9b1c2013-12-12 21:23:03 +00002834/// unary-type-trait '(' type-id ')'
2835/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor29c42f22012-02-24 07:38:34 +00002836/// type-trait '(' type-id-seq ')'
2837///
2838/// type-id-seq:
2839/// type-id ...[opt] type-id-seq[opt]
2840///
2841ExprResult Parser::ParseTypeTrait() {
Alp Toker40f9b1c2013-12-12 21:23:03 +00002842 tok::TokenKind Kind = Tok.getKind();
2843 unsigned Arity = TypeTraitArity(Kind);
2844
Douglas Gregor29c42f22012-02-24 07:38:34 +00002845 SourceLocation Loc = ConsumeToken();
2846
2847 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002848 if (Parens.expectAndConsume())
Douglas Gregor29c42f22012-02-24 07:38:34 +00002849 return ExprError();
2850
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002851 SmallVector<ParsedType, 2> Args;
Douglas Gregor29c42f22012-02-24 07:38:34 +00002852 do {
2853 // Parse the next type.
2854 TypeResult Ty = ParseTypeName();
2855 if (Ty.isInvalid()) {
2856 Parens.skipToEnd();
2857 return ExprError();
2858 }
2859
2860 // Parse the ellipsis, if present.
2861 if (Tok.is(tok::ellipsis)) {
2862 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2863 if (Ty.isInvalid()) {
2864 Parens.skipToEnd();
2865 return ExprError();
2866 }
2867 }
2868
2869 // Add this type to the list of arguments.
2870 Args.push_back(Ty.get());
Alp Tokera3ebe6e2013-12-17 14:12:37 +00002871 } while (TryConsumeToken(tok::comma));
2872
Douglas Gregor29c42f22012-02-24 07:38:34 +00002873 if (Parens.consumeClose())
2874 return ExprError();
Alp Toker40f9b1c2013-12-12 21:23:03 +00002875
2876 SourceLocation EndLoc = Parens.getCloseLocation();
2877
2878 if (Arity && Args.size() != Arity) {
2879 Diag(EndLoc, diag::err_type_trait_arity)
2880 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2881 return ExprError();
2882 }
2883
2884 if (!Arity && Args.empty()) {
2885 Diag(EndLoc, diag::err_type_trait_arity)
2886 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2887 return ExprError();
2888 }
2889
Alp Toker88f64e62013-12-13 21:19:30 +00002890 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor29c42f22012-02-24 07:38:34 +00002891}
2892
John Wiegley6242b6a2011-04-28 00:16:57 +00002893/// ParseArrayTypeTrait - Parse the built-in array type-trait
2894/// pseudo-functions.
2895///
2896/// primary-expression:
2897/// [Embarcadero] '__array_rank' '(' type-id ')'
2898/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2899///
2900ExprResult Parser::ParseArrayTypeTrait() {
2901 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2902 SourceLocation Loc = ConsumeToken();
2903
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002904 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002905 if (T.expectAndConsume())
John Wiegley6242b6a2011-04-28 00:16:57 +00002906 return ExprError();
2907
2908 TypeResult Ty = ParseTypeName();
2909 if (Ty.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002910 SkipUntil(tok::comma, StopAtSemi);
2911 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002912 return ExprError();
2913 }
2914
2915 switch (ATT) {
2916 case ATT_ArrayRank: {
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002917 T.consumeClose();
Craig Topper161e4db2014-05-21 06:02:52 +00002918 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002919 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002920 }
2921 case ATT_ArrayExtent: {
Alp Toker383d2c42014-01-01 03:08:43 +00002922 if (ExpectAndConsume(tok::comma)) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00002923 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley6242b6a2011-04-28 00:16:57 +00002924 return ExprError();
2925 }
2926
2927 ExprResult DimExpr = ParseExpression();
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002928 T.consumeClose();
John Wiegley6242b6a2011-04-28 00:16:57 +00002929
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002930 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2931 T.getCloseLocation());
John Wiegley6242b6a2011-04-28 00:16:57 +00002932 }
John Wiegley6242b6a2011-04-28 00:16:57 +00002933 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002934 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley6242b6a2011-04-28 00:16:57 +00002935}
2936
John Wiegleyf9f65842011-04-25 06:54:41 +00002937/// ParseExpressionTrait - Parse built-in expression-trait
2938/// pseudo-functions like __is_lvalue_expr( xxx ).
2939///
2940/// primary-expression:
2941/// [Embarcadero] expression-trait '(' expression ')'
2942///
2943ExprResult Parser::ParseExpressionTrait() {
2944 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2945 SourceLocation Loc = ConsumeToken();
2946
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002947 BalancedDelimiterTracker T(*this, tok::l_paren);
Alp Toker383d2c42014-01-01 03:08:43 +00002948 if (T.expectAndConsume())
John Wiegleyf9f65842011-04-25 06:54:41 +00002949 return ExprError();
2950
2951 ExprResult Expr = ParseExpression();
2952
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002953 T.consumeClose();
John Wiegleyf9f65842011-04-25 06:54:41 +00002954
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00002955 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
2956 T.getCloseLocation());
John Wiegleyf9f65842011-04-25 06:54:41 +00002957}
2958
2959
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002960/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
2961/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
2962/// based on the context past the parens.
John McCalldadc5752010-08-24 06:29:42 +00002963ExprResult
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002964Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallba7bf592010-08-24 05:47:05 +00002965 ParsedType &CastTy,
Richard Smith87e11a42014-05-15 02:43:47 +00002966 BalancedDelimiterTracker &Tracker,
2967 ColonProtectionRAIIObject &ColonProt) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002968 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002969 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
2970 assert(isTypeIdInParens() && "Not a type-id!");
2971
John McCalldadc5752010-08-24 06:29:42 +00002972 ExprResult Result(true);
John McCallba7bf592010-08-24 05:47:05 +00002973 CastTy = ParsedType();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002974
2975 // We need to disambiguate a very ugly part of the C++ syntax:
2976 //
2977 // (T())x; - type-id
2978 // (T())*x; - type-id
2979 // (T())/x; - expression
2980 // (T()); - expression
2981 //
2982 // The bad news is that we cannot use the specialized tentative parser, since
2983 // it can only verify that the thing inside the parens can be parsed as
2984 // type-id, it is not useful for determining the context past the parens.
2985 //
2986 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidis24ad6922009-05-22 15:12:46 +00002987 // making any unnecessary Action calls.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002988 //
2989 // It uses a scheme similar to parsing inline methods. The parenthesized
2990 // tokens are cached, the context that follows is determined (possibly by
2991 // parsing a cast-expression), and then we re-introduce the cached tokens
2992 // into the token stream and parse them appropriately.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002993
Mike Stump11289f42009-09-09 15:08:12 +00002994 ParenParseOption ParseAs;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002995 CachedTokens Toks;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00002996
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00002997 // Store the tokens of the parentheses. We will parse them after we determine
2998 // the context that follows them.
Argyrios Kyrtzidis8d7bdba2010-04-23 21:20:12 +00002999 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003000 // We didn't find the ')' we expected.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003001 Tracker.consumeClose();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003002 return ExprError();
3003 }
3004
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003005 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003006 ParseAs = CompoundLiteral;
3007 } else {
3008 bool NotCastExpr;
Eli Friedmancf7530f2009-05-25 19:41:42 +00003009 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3010 NotCastExpr = true;
3011 } else {
3012 // Try parsing the cast-expression that may follow.
3013 // If it is not a cast-expression, NotCastExpr will be true and no token
3014 // will be consumed.
Richard Smith87e11a42014-05-15 02:43:47 +00003015 ColonProt.restore();
Eli Friedmancf7530f2009-05-25 19:41:42 +00003016 Result = ParseCastExpression(false/*isUnaryExpression*/,
3017 false/*isAddressofOperand*/,
John McCallba7bf592010-08-24 05:47:05 +00003018 NotCastExpr,
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003019 // type-id has priority.
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00003020 IsTypeCast);
Eli Friedmancf7530f2009-05-25 19:41:42 +00003021 }
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003022
3023 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3024 // an expression.
3025 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003026 }
3027
Mike Stump11289f42009-09-09 15:08:12 +00003028 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003029 Toks.push_back(Tok);
3030 // Re-enter the stored parenthesized tokens into the token stream, so we may
3031 // parse them now.
3032 PP.EnterTokenStream(Toks.data(), Toks.size(),
3033 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3034 // Drop the current token and bring the first cached one. It's the same token
3035 // as when we entered this function.
3036 ConsumeAnyToken();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003037
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003038 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003039 // Parse the type declarator.
3040 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003041 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Richard Smith87e11a42014-05-15 02:43:47 +00003042 {
3043 ColonProtectionRAIIObject InnerColonProtection(*this);
3044 ParseSpecifierQualifierList(DS);
3045 ParseDeclarator(DeclaratorInfo);
3046 }
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003047
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003048 // Match the ')'.
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003049 Tracker.consumeClose();
Richard Smith87e11a42014-05-15 02:43:47 +00003050 ColonProt.restore();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003051
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003052 if (ParseAs == CompoundLiteral) {
3053 ExprType = CompoundLiteral;
Richard Smithaba8b362014-05-15 02:51:15 +00003054 if (DeclaratorInfo.isInvalidType())
3055 return ExprError();
3056
3057 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
Richard Smith87e11a42014-05-15 02:43:47 +00003058 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003059 Tracker.getOpenLocation(),
3060 Tracker.getCloseLocation());
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003061 }
Mike Stump11289f42009-09-09 15:08:12 +00003062
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003063 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3064 assert(ParseAs == CastExpr);
3065
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00003066 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003067 return ExprError();
3068
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003069 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003070 if (!Result.isInvalid())
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003071 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3072 DeclaratorInfo, CastTy,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003073 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003074 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003075 }
Mike Stump11289f42009-09-09 15:08:12 +00003076
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003077 // Not a compound literal, and not followed by a cast-expression.
3078 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003079
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003080 ExprType = SimpleExpr;
Argyrios Kyrtzidisf73f2d22009-05-22 21:09:47 +00003081 Result = ParseExpression();
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003082 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003083 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003084 Tok.getLocation(), Result.get());
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003085
3086 // Match the ')'.
3087 if (Result.isInvalid()) {
Alexey Bataevee6507d2013-11-18 08:17:37 +00003088 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003089 return ExprError();
3090 }
Mike Stump11289f42009-09-09 15:08:12 +00003091
Douglas Gregore7a8e3b2011-10-12 16:37:45 +00003092 Tracker.consumeClose();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00003093 return Result;
Argyrios Kyrtzidis12179bc2009-05-22 10:24:42 +00003094}