blob: 1030072068ff69c50af255298934825bebf402f5 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expression parsing implementation for C++.
11//
12//===----------------------------------------------------------------------===//
Stephen Hines651f13c2014-04-23 16:59:28 -070013#include "clang/AST/ASTContext.h"
Douglas Gregorbc61bd82011-01-11 00:33:19 +000014#include "RAIIObjectsForParser.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070015#include "clang/AST/DeclTemplate.h"
Eli Friedmandc3b7232012-01-04 02:40:39 +000016#include "clang/Basic/PrettyStackTrace.h"
Richard Smith33762772012-03-08 23:06:02 +000017#include "clang/Lex/LiteralSupport.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Parse/ParseDiagnostic.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070019#include "clang/Parse/Parser.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/ParsedTemplate.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Scope.h"
Douglas Gregor3f9a0562009-11-03 01:35:08 +000023#include "llvm/Support/ErrorHandling.h"
24
Faisal Valifad9e132013-09-26 19:54:12 +000025
Reid Spencer5f016e22007-07-11 17:01:13 +000026using namespace clang;
27
Richard Smithea698b32011-04-14 21:45:45 +000028static int SelectDigraphErrorMessage(tok::TokenKind Kind) {
29 switch (Kind) {
Stephen Hines651f13c2014-04-23 16:59:28 -070030 // template name
31 case tok::unknown: return 0;
32 // casts
Richard Smithea698b32011-04-14 21:45:45 +000033 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:
David Blaikieb219cfc2011-09-23 05:06:16 +000038 llvm_unreachable("Unknown type for digraph error message.");
Richard Smithea698b32011-04-14 21:45:45 +000039 }
40}
41
42// Are the two tokens adjacent in the same source file?
Richard Smith19a27022012-06-18 06:11:04 +000043bool Parser::areTokensAdjacent(const Token &First, const Token &Second) {
Richard Smithea698b32011-04-14 21:45:45 +000044 SourceManager &SM = PP.getSourceManager();
45 SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation());
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000046 SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength());
Richard Smithea698b32011-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)
62 << SelectDigraphErrorMessage(Kind)
63 << FixItHint::CreateReplacement(Range, "< ::");
64
65 // Update token information to reflect their change in token type.
66 ColonToken.setKind(tok::coloncolon);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000067 ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1));
Richard Smithea698b32011-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 Trieu950be712011-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 Trieuc11030e2011-09-20 20:03:50 +000083 if (!Next.is(tok::l_square) || Next.getLength() != 2)
Richard Trieu950be712011-09-19 19:01:00 +000084 return;
85
86 Token SecondToken = GetLookAheadToken(2);
Richard Smith19a27022012-06-18 06:11:04 +000087 if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken))
Richard Trieu950be712011-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
Stephen Hines651f13c2014-04-23 16:59:28 -070099 FixDigraph(*this, PP, Next, SecondToken, tok::unknown,
Richard Trieu950be712011-09-19 19:01:00 +0000100 /*AtDigraph*/false);
101}
102
Richard Trieu919b9552012-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 Weberbba91b82012-11-29 05:29:23 +0000106/// stream by removing the '(', and the matching ')' if found.
Richard Trieu919b9552012-11-02 01:08:58 +0000107void Parser::CheckForLParenAfterColonColon() {
108 if (!Tok.is(tok::l_paren))
109 return;
110
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700111 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 Trieu919b9552012-11-02 01:08:58 +0000117 return;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700118 // Eat the '('.
119 ConsumeParen();
120 Token RParen;
Pirama Arumuga Nainar3ea9e332015-04-08 08:57:32 -0700121 RParen.setLocation(SourceLocation());
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700122 // Do we have a ')' ?
123 NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1);
124 if (NextTok.is(tok::r_paren)) {
125 RParen = NextTok;
126 // Eat the '*' if it is present.
127 if (StarTok.is(tok::star))
Richard Trieu919b9552012-11-02 01:08:58 +0000128 ConsumeToken();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700129 // Eat the identifier.
130 ConsumeToken();
131 // Add the identifier token back.
132 PP.EnterToken(IdentifierTok);
133 // Add the '*' back if it was present.
134 if (StarTok.is(tok::star))
135 PP.EnterToken(StarTok);
136 // Eat the ')'.
137 ConsumeParen();
Richard Trieu919b9552012-11-02 01:08:58 +0000138 }
139
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700140 Diag(LParen.getLocation(), diag::err_paren_after_colon_colon)
141 << FixItHint::CreateRemoval(LParen.getLocation())
142 << FixItHint::CreateRemoval(RParen.getLocation());
Richard Trieu919b9552012-11-02 01:08:58 +0000143}
144
Mike Stump1eb44332009-09-09 15:08:12 +0000145/// \brief Parse global scope or nested-name-specifier if present.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000146///
147/// Parses a C++ global scope specifier ('::') or nested-name-specifier (which
Mike Stump1eb44332009-09-09 15:08:12 +0000148/// may be preceded by '::'). Note that this routine will not parse ::new or
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000149/// ::delete; it will just leave them in the token stream.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000150///
151/// '::'[opt] nested-name-specifier
152/// '::'
153///
154/// nested-name-specifier:
155/// type-name '::'
156/// namespace-name '::'
157/// nested-name-specifier identifier '::'
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000158/// nested-name-specifier 'template'[opt] simple-template-id '::'
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000159///
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000160///
Mike Stump1eb44332009-09-09 15:08:12 +0000161/// \param SS the scope specifier that will be set to the parsed
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000162/// nested-name-specifier (or empty)
163///
Mike Stump1eb44332009-09-09 15:08:12 +0000164/// \param ObjectType if this nested-name-specifier is being parsed following
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000165/// the "." or "->" of a member access expression, this parameter provides the
166/// type of the object whose members are being accessed.
167///
168/// \param EnteringContext whether we will be entering into the context of
169/// the nested-name-specifier after parsing it.
170///
Douglas Gregord4dca082010-02-24 18:44:31 +0000171/// \param MayBePseudoDestructor When non-NULL, points to a flag that
172/// indicates whether this nested-name-specifier may be part of a
173/// pseudo-destructor name. In this case, the flag will be set false
174/// if we don't actually end up parsing a destructor name. Moreorover,
175/// if we do end up determining that we are parsing a destructor name,
176/// the last component of the nested-name-specifier is not parsed as
177/// part of the scope specifier.
Richard Smith2db075b2013-03-26 01:15:19 +0000178///
179/// \param IsTypename If \c true, this nested-name-specifier is known to be
180/// part of a type name. This is used to improve error recovery.
181///
182/// \param LastII When non-NULL, points to an IdentifierInfo* that will be
183/// filled in with the leading identifier in the last component of the
184/// nested-name-specifier, if any.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000185///
John McCall9ba61662010-02-26 08:45:28 +0000186/// \returns true if there was an error parsing a scope specifier
Douglas Gregor495c35d2009-08-25 22:51:20 +0000187bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +0000188 ParsedType ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000189 bool EnteringContext,
Francois Pichet4147d302011-03-27 19:41:34 +0000190 bool *MayBePseudoDestructor,
Richard Smith2db075b2013-03-26 01:15:19 +0000191 bool IsTypename,
192 IdentifierInfo **LastII) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000193 assert(getLangOpts().CPlusPlus &&
Chris Lattner7452c6f2009-01-05 01:24:05 +0000194 "Call sites of this function should be guarded by checking for C++");
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000196 if (Tok.is(tok::annot_cxxscope)) {
Richard Smith2db075b2013-03-26 01:15:19 +0000197 assert(!LastII && "want last identifier but have already annotated scope");
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700198 assert(!MayBePseudoDestructor && "unexpected annot_cxxscope");
Douglas Gregorc34348a2011-02-24 17:54:50 +0000199 Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(),
200 Tok.getAnnotationRange(),
201 SS);
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000202 ConsumeToken();
John McCall9ba61662010-02-26 08:45:28 +0000203 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000204 }
Chris Lattnere607e802009-01-04 21:14:15 +0000205
Larisse Voufo9c90f7f2013-08-06 05:49:26 +0000206 if (Tok.is(tok::annot_template_id)) {
207 // If the current token is an annotated template id, it may already have
208 // a scope specifier. Restore it.
209 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
210 SS = TemplateId->SS;
211 }
212
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700213 // Has to happen before any "return false"s in this function.
214 bool CheckForDestructor = false;
215 if (MayBePseudoDestructor && *MayBePseudoDestructor) {
216 CheckForDestructor = true;
217 *MayBePseudoDestructor = false;
218 }
219
Richard Smith2db075b2013-03-26 01:15:19 +0000220 if (LastII)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700221 *LastII = nullptr;
Richard Smith2db075b2013-03-26 01:15:19 +0000222
Douglas Gregor39a8de12009-02-25 19:37:18 +0000223 bool HasScopeSpecifier = false;
224
Chris Lattner5b454732009-01-05 03:55:46 +0000225 if (Tok.is(tok::coloncolon)) {
226 // ::new and ::delete aren't nested-name-specifiers.
227 tok::TokenKind NextKind = NextToken().getKind();
228 if (NextKind == tok::kw_new || NextKind == tok::kw_delete)
229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700231 if (NextKind == tok::l_brace) {
232 // It is invalid to have :: {, consume the scope qualifier and pretend
233 // like we never saw it.
234 Diag(ConsumeToken(), diag::err_expected) << tok::identifier;
235 } else {
236 // '::' - Global scope qualifier.
237 if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS))
238 return true;
Richard Trieu919b9552012-11-02 01:08:58 +0000239
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700240 CheckForLParenAfterColonColon();
Richard Trieu919b9552012-11-02 01:08:58 +0000241
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700242 HasScopeSpecifier = true;
243 }
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000244 }
245
Stephen Hines176edba2014-12-01 14:53:08 -0800246 if (Tok.is(tok::kw___super)) {
247 SourceLocation SuperLoc = ConsumeToken();
248 if (!Tok.is(tok::coloncolon)) {
249 Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super);
250 return true;
251 }
252
253 return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS);
254 }
255
Stephen Hines176edba2014-12-01 14:53:08 -0800256 if (!HasScopeSpecifier &&
257 (Tok.is(tok::kw_decltype) || Tok.is(tok::annot_decltype))) {
David Blaikie42d6d0c2011-12-04 05:04:18 +0000258 DeclSpec DS(AttrFactory);
259 SourceLocation DeclLoc = Tok.getLocation();
260 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -0700261
262 SourceLocation CCLoc;
263 if (!TryConsumeToken(tok::coloncolon, CCLoc)) {
David Blaikie42d6d0c2011-12-04 05:04:18 +0000264 AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc);
265 return false;
266 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700267
David Blaikie42d6d0c2011-12-04 05:04:18 +0000268 if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc))
269 SS.SetInvalid(SourceRange(DeclLoc, CCLoc));
270
271 HasScopeSpecifier = true;
272 }
273
Douglas Gregor39a8de12009-02-25 19:37:18 +0000274 while (true) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000275 if (HasScopeSpecifier) {
276 // C++ [basic.lookup.classref]p5:
277 // If the qualified-id has the form
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000278 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000279 // ::class-name-or-namespace-name::...
Douglas Gregor3b6afbb2009-09-09 00:23:06 +0000280 //
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000281 // the class-name-or-namespace-name is looked up in global scope as a
282 // class-name or namespace-name.
283 //
284 // To implement this, we clear out the object type as soon as we've
285 // seen a leading '::' or part of a nested-name-specifier.
John McCallb3d87482010-08-24 05:47:05 +0000286 ObjectType = ParsedType();
Douglas Gregor81b747b2009-09-17 21:32:03 +0000287
288 if (Tok.is(tok::code_completion)) {
289 // Code completion for a nested-name-specifier, where the code
290 // code completion token follows the '::'.
Douglas Gregor23c94db2010-07-02 17:43:08 +0000291 Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext);
Argyrios Kyrtzidisb6b2b182011-04-23 01:04:12 +0000292 // Include code completion token into the range of the scope otherwise
293 // when we try to annotate the scope tokens the dangling code completion
294 // token will cause assertion in
295 // Preprocessor::AnnotatePreviousCachedTokens.
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000296 SS.setEndLoc(Tok.getLocation());
297 cutOffParsing();
298 return true;
Douglas Gregor81b747b2009-09-17 21:32:03 +0000299 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000300 }
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Douglas Gregor39a8de12009-02-25 19:37:18 +0000302 // nested-name-specifier:
Chris Lattner77cf72a2009-06-26 03:47:46 +0000303 // nested-name-specifier 'template'[opt] simple-template-id '::'
304
305 // Parse the optional 'template' keyword, then make sure we have
306 // 'identifier <' after it.
307 if (Tok.is(tok::kw_template)) {
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000308 // If we don't have a scope specifier or an object type, this isn't a
Eli Friedmaneab975d2009-08-29 04:08:08 +0000309 // nested-name-specifier, since they aren't allowed to start with
310 // 'template'.
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000311 if (!HasScopeSpecifier && !ObjectType)
Eli Friedmaneab975d2009-08-29 04:08:08 +0000312 break;
313
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000314 TentativeParsingAction TPA(*this);
Chris Lattner77cf72a2009-06-26 03:47:46 +0000315 SourceLocation TemplateKWLoc = ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -0700316
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000317 UnqualifiedId TemplateName;
318 if (Tok.is(tok::identifier)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000319 // Consume the identifier.
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000320 TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000321 ConsumeToken();
322 } else if (Tok.is(tok::kw_operator)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700323 // We don't need to actually parse the unqualified-id in this case,
324 // because a simple-template-id cannot start with 'operator', but
325 // go ahead and parse it anyway for consistency with the case where
326 // we already annotated the template-id.
327 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType,
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000328 TemplateName)) {
329 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000330 break;
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000331 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700332
Sean Hunte6252d12009-11-28 08:58:14 +0000333 if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId &&
334 TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000335 Diag(TemplateName.getSourceRange().getBegin(),
336 diag::err_id_after_template_in_nested_name_spec)
337 << TemplateName.getSourceRange();
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000338 TPA.Commit();
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000339 break;
340 }
341 } else {
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000342 TPA.Revert();
Chris Lattner77cf72a2009-06-26 03:47:46 +0000343 break;
344 }
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Douglas Gregor7bb87fc2009-11-11 16:39:34 +0000346 // If the next token is not '<', we have a qualified-id that refers
347 // to a template name, such as T::template apply, but is not a
348 // template-id.
349 if (Tok.isNot(tok::less)) {
350 TPA.Revert();
351 break;
352 }
353
354 // Commit to parsing the template-id.
355 TPA.Commit();
Douglas Gregord6ab2322010-06-16 23:00:59 +0000356 TemplateTy Template;
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000357 if (TemplateNameKind TNK
358 = Actions.ActOnDependentTemplateName(getCurScope(),
359 SS, TemplateKWLoc, TemplateName,
360 ObjectType, EnteringContext,
361 Template)) {
362 if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc,
363 TemplateName, false))
Douglas Gregord6ab2322010-06-16 23:00:59 +0000364 return true;
365 } else
John McCall9ba61662010-02-26 08:45:28 +0000366 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Chris Lattner77cf72a2009-06-26 03:47:46 +0000368 continue;
369 }
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Douglas Gregor39a8de12009-02-25 19:37:18 +0000371 if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000372 // We have
Douglas Gregor39a8de12009-02-25 19:37:18 +0000373 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700374 // template-id '::'
Douglas Gregor39a8de12009-02-25 19:37:18 +0000375 //
Stephen Hines651f13c2014-04-23 16:59:28 -0700376 // So we need to check whether the template-id is a simple-template-id of
377 // the right kind (it should name a type or be dependent), and then
Douglas Gregorc45c2322009-03-31 00:43:58 +0000378 // convert it into a type within the nested-name-specifier.
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +0000379 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregord4dca082010-02-24 18:44:31 +0000380 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) {
381 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000382 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000383 }
384
Richard Smith2db075b2013-03-26 01:15:19 +0000385 if (LastII)
386 *LastII = TemplateId->Name;
387
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000388 // Consume the template-id token.
389 ConsumeToken();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700390
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000391 assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!");
392 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
David Blaikie6796fc12011-11-07 03:30:03 +0000394 HasScopeSpecifier = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700395
Benjamin Kramer5354e772012-08-23 23:38:35 +0000396 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000397 TemplateId->NumArgs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700398
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000399 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000400 SS,
401 TemplateId->TemplateKWLoc,
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000402 TemplateId->Template,
403 TemplateId->TemplateNameLoc,
404 TemplateId->LAngleLoc,
405 TemplateArgsPtr,
406 TemplateId->RAngleLoc,
407 CCLoc,
408 EnteringContext)) {
409 SourceLocation StartLoc
410 = SS.getBeginLoc().isValid()? SS.getBeginLoc()
411 : TemplateId->TemplateNameLoc;
412 SS.SetInvalid(SourceRange(StartLoc, CCLoc));
Chris Lattner67b9e832009-06-26 03:45:46 +0000413 }
Argyrios Kyrtzidiseccce7e2011-05-03 18:45:38 +0000414
Douglas Gregor6cd9d4a2011-03-04 21:37:14 +0000415 continue;
Douglas Gregor39a8de12009-02-25 19:37:18 +0000416 }
417
Chris Lattner5c7f7862009-06-26 03:52:38 +0000418 // The rest of the nested-name-specifier possibilities start with
419 // tok::identifier.
420 if (Tok.isNot(tok::identifier))
421 break;
422
423 IdentifierInfo &II = *Tok.getIdentifierInfo();
424
425 // nested-name-specifier:
426 // type-name '::'
427 // namespace-name '::'
428 // nested-name-specifier identifier '::'
429 Token Next = NextToken();
Chris Lattner46646492009-12-07 01:36:53 +0000430
431 // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover
432 // and emit a fixit hint for it.
Douglas Gregorb10cd042010-02-21 18:36:56 +0000433 if (Next.is(tok::colon) && !ColonIsSacred) {
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000434 if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II,
435 Tok.getLocation(),
436 Next.getLocation(), ObjectType,
Douglas Gregorb10cd042010-02-21 18:36:56 +0000437 EnteringContext) &&
438 // If the token after the colon isn't an identifier, it's still an
439 // error, but they probably meant something else strange so don't
440 // recover like this.
441 PP.LookAhead(1).is(tok::identifier)) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700442 Diag(Next, diag::err_unexpected_colon_in_nested_name_spec)
Douglas Gregor849b2432010-03-31 17:46:05 +0000443 << FixItHint::CreateReplacement(Next.getLocation(), "::");
Douglas Gregorb10cd042010-02-21 18:36:56 +0000444 // Recover as if the user wrote '::'.
445 Next.setKind(tok::coloncolon);
446 }
Chris Lattner46646492009-12-07 01:36:53 +0000447 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700448
449 if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) {
450 // It is invalid to have :: {, consume the scope qualifier and pretend
451 // like we never saw it.
452 Token Identifier = Tok; // Stash away the identifier.
453 ConsumeToken(); // Eat the identifier, current token is now '::'.
454 Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected)
455 << tok::identifier;
456 UnconsumeToken(Identifier); // Stick the identifier back.
457 Next = NextToken(); // Point Next at the '{' token.
458 }
459
Chris Lattner5c7f7862009-06-26 03:52:38 +0000460 if (Next.is(tok::coloncolon)) {
Douglas Gregor77549082010-02-24 21:29:12 +0000461 if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) &&
Stephen Hines176edba2014-12-01 14:53:08 -0800462 !Actions.isNonTypeNestedNameSpecifier(
463 getCurScope(), SS, Tok.getLocation(), II, ObjectType)) {
Douglas Gregord4dca082010-02-24 18:44:31 +0000464 *MayBePseudoDestructor = true;
John McCall9ba61662010-02-26 08:45:28 +0000465 return false;
Douglas Gregord4dca082010-02-24 18:44:31 +0000466 }
467
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700468 if (ColonIsSacred) {
469 const Token &Next2 = GetLookAheadToken(2);
470 if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) ||
471 Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) {
472 Diag(Next2, diag::err_unexpected_token_in_nested_name_spec)
473 << Next2.getName()
474 << FixItHint::CreateReplacement(Next.getLocation(), ":");
475 Token ColonColon;
476 PP.Lex(ColonColon);
477 ColonColon.setKind(tok::colon);
478 PP.EnterToken(ColonColon);
479 break;
480 }
481 }
482
Richard Smith2db075b2013-03-26 01:15:19 +0000483 if (LastII)
484 *LastII = &II;
485
Chris Lattner5c7f7862009-06-26 03:52:38 +0000486 // We have an identifier followed by a '::'. Lookup this name
487 // as the name in a nested-name-specifier.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700488 Token Identifier = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000489 SourceLocation IdLoc = ConsumeToken();
Chris Lattner46646492009-12-07 01:36:53 +0000490 assert((Tok.is(tok::coloncolon) || Tok.is(tok::colon)) &&
491 "NextToken() not working properly!");
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700492 Token ColonColon = Tok;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000493 SourceLocation CCLoc = ConsumeToken();
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Richard Trieu919b9552012-11-02 01:08:58 +0000495 CheckForLParenAfterColonColon();
496
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700497 bool IsCorrectedToColon = false;
498 bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr;
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000499 if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700500 ObjectType, EnteringContext, SS,
501 false, CorrectionFlagPtr)) {
502 // Identifier is not recognized as a nested name, but we can have
503 // mistyped '::' instead of ':'.
504 if (CorrectionFlagPtr && IsCorrectedToColon) {
505 ColonColon.setKind(tok::colon);
506 PP.EnterToken(Tok);
507 PP.EnterToken(ColonColon);
508 Tok = Identifier;
509 break;
510 }
Douglas Gregor2e4c34a2011-02-24 00:17:56 +0000511 SS.SetInvalid(SourceRange(IdLoc, CCLoc));
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700512 }
513 HasScopeSpecifier = true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000514 continue;
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Richard Trieu950be712011-09-19 19:01:00 +0000517 CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS);
Richard Smithea698b32011-04-14 21:45:45 +0000518
Chris Lattner5c7f7862009-06-26 03:52:38 +0000519 // nested-name-specifier:
520 // type-name '<'
521 if (Next.is(tok::less)) {
522 TemplateTy Template;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000523 UnqualifiedId TemplateName;
524 TemplateName.setIdentifier(&II, Tok.getLocation());
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000525 bool MemberOfUnknownSpecialization;
Douglas Gregor23c94db2010-07-02 17:43:08 +0000526 if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000527 /*hasTemplateKeyword=*/false,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000528 TemplateName,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000529 ObjectType,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000530 EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000531 Template,
532 MemberOfUnknownSpecialization)) {
David Blaikie6796fc12011-11-07 03:30:03 +0000533 // We have found a template name, so annotate this token
Chris Lattner5c7f7862009-06-26 03:52:38 +0000534 // with a template-id annotation. We do not permit the
535 // template-id to be translated into a type annotation,
536 // because some clients (e.g., the parsing of class template
537 // specializations) still want to see the original template-id
538 // token.
Douglas Gregorca1bdd72009-11-04 00:56:37 +0000539 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000540 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
541 TemplateName, false))
John McCall9ba61662010-02-26 08:45:28 +0000542 return true;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000543 continue;
Larisse Voufoef4579c2013-08-06 01:03:05 +0000544 }
545
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000546 if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) &&
Francois Pichet4147d302011-03-27 19:41:34 +0000547 (IsTypename || IsTemplateArgumentList(1))) {
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000548 // We have something like t::getAs<T>, where getAs is a
549 // member of an unknown specialization. However, this will only
550 // parse correctly as a template, so suggest the keyword 'template'
551 // before 'getAs' and treat this as a dependent template name.
Francois Pichet4147d302011-03-27 19:41:34 +0000552 unsigned DiagID = diag::err_missing_dependent_template_keyword;
David Blaikie4e4d0842012-03-11 07:00:24 +0000553 if (getLangOpts().MicrosoftExt)
Francois Pichetcf320c62011-04-22 08:25:24 +0000554 DiagID = diag::warn_missing_dependent_template_keyword;
Francois Pichet4147d302011-03-27 19:41:34 +0000555
556 Diag(Tok.getLocation(), DiagID)
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000557 << II.getName()
558 << FixItHint::CreateInsertion(Tok.getLocation(), "template ");
559
Douglas Gregord6ab2322010-06-16 23:00:59 +0000560 if (TemplateNameKind TNK
Douglas Gregor23c94db2010-07-02 17:43:08 +0000561 = Actions.ActOnDependentTemplateName(getCurScope(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000562 SS, SourceLocation(),
Douglas Gregord6ab2322010-06-16 23:00:59 +0000563 TemplateName, ObjectType,
564 EnteringContext, Template)) {
565 // Consume the identifier.
566 ConsumeToken();
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000567 if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(),
568 TemplateName, false))
569 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000570 }
571 else
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000572 return true;
Douglas Gregord6ab2322010-06-16 23:00:59 +0000573
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000574 continue;
Chris Lattner5c7f7862009-06-26 03:52:38 +0000575 }
576 }
577
Douglas Gregor39a8de12009-02-25 19:37:18 +0000578 // We don't have any tokens that form the beginning of a
579 // nested-name-specifier, so we're done.
580 break;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000581 }
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Douglas Gregord4dca082010-02-24 18:44:31 +0000583 // Even if we didn't see any pieces of a nested-name-specifier, we
584 // still check whether there is a tilde in this position, which
585 // indicates a potential pseudo-destructor.
586 if (CheckForDestructor && Tok.is(tok::tilde))
587 *MayBePseudoDestructor = true;
588
John McCall9ba61662010-02-26 08:45:28 +0000589 return false;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000590}
591
Stephen Hines176edba2014-12-01 14:53:08 -0800592ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand,
593 Token &Replacement) {
594 SourceLocation TemplateKWLoc;
595 UnqualifiedId Name;
596 if (ParseUnqualifiedId(SS,
597 /*EnteringContext=*/false,
598 /*AllowDestructorName=*/false,
599 /*AllowConstructorName=*/false,
600 /*ObjectType=*/ParsedType(), TemplateKWLoc, Name))
601 return ExprError();
602
603 // This is only the direct operand of an & operator if it is not
604 // followed by a postfix-expression suffix.
605 if (isAddressOfOperand && isPostfixExpressionSuffixStart())
606 isAddressOfOperand = false;
607
608 return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name,
609 Tok.is(tok::l_paren), isAddressOfOperand,
610 nullptr, /*IsInlineAsmIdentifier=*/false,
611 &Replacement);
612}
613
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000614/// ParseCXXIdExpression - Handle id-expression.
615///
616/// id-expression:
617/// unqualified-id
618/// qualified-id
619///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000620/// qualified-id:
621/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
622/// '::' identifier
623/// '::' operator-function-id
Douglas Gregoredce4dd2009-06-30 22:34:41 +0000624/// '::' template-id
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000625///
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000626/// NOTE: The standard specifies that, for qualified-id, the parser does not
627/// expect:
628///
629/// '::' conversion-function-id
630/// '::' '~' class-name
631///
632/// This may cause a slight inconsistency on diagnostics:
633///
634/// class C {};
635/// namespace A {}
636/// void f() {
637/// :: A :: ~ C(); // Some Sema error about using destructor with a
638/// // namespace.
639/// :: ~ C(); // Some Parser error like 'unexpected ~'.
640/// }
641///
642/// We simplify the parser a bit and make it work like:
643///
644/// qualified-id:
645/// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
646/// '::' unqualified-id
647///
648/// That way Sema can handle and report similar errors for namespaces and the
649/// global scope.
650///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000651/// The isAddressOfOperand parameter indicates that this id-expression is a
652/// direct operand of the address-of operator. This is, besides member contexts,
653/// the only place where a qualified-id naming a non-static class member may
654/// appear.
655///
John McCall60d7b3a2010-08-24 06:29:42 +0000656ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) {
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000657 // qualified-id:
658 // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id
659 // '::' unqualified-id
660 //
661 CXXScopeSpec SS;
Douglas Gregorefaa93a2011-11-07 17:33:42 +0000662 ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000663
Stephen Hines176edba2014-12-01 14:53:08 -0800664 Token Replacement;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700665 ExprResult Result =
666 tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
Stephen Hines176edba2014-12-01 14:53:08 -0800667 if (Result.isUnset()) {
668 // If the ExprResult is valid but null, then typo correction suggested a
669 // keyword replacement that needs to be reparsed.
670 UnconsumeToken(Replacement);
671 Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement);
672 }
673 assert(!Result.isUnset() && "Typo correction suggested a keyword replacement "
674 "for a previous keyword suggestion");
675 return Result;
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000676}
677
Richard Smith0a664b82013-05-09 21:36:41 +0000678/// ParseLambdaExpression - Parse a C++11 lambda expression.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000679///
680/// lambda-expression:
681/// lambda-introducer lambda-declarator[opt] compound-statement
682///
683/// lambda-introducer:
684/// '[' lambda-capture[opt] ']'
685///
686/// lambda-capture:
687/// capture-default
688/// capture-list
689/// capture-default ',' capture-list
690///
691/// capture-default:
692/// '&'
693/// '='
694///
695/// capture-list:
696/// capture
697/// capture-list ',' capture
698///
699/// capture:
Richard Smith0a664b82013-05-09 21:36:41 +0000700/// simple-capture
701/// init-capture [C++1y]
702///
703/// simple-capture:
Douglas Gregorae7902c2011-08-04 15:30:47 +0000704/// identifier
705/// '&' identifier
706/// 'this'
707///
Richard Smith0a664b82013-05-09 21:36:41 +0000708/// init-capture: [C++1y]
709/// identifier initializer
710/// '&' identifier initializer
711///
Douglas Gregorae7902c2011-08-04 15:30:47 +0000712/// lambda-declarator:
713/// '(' parameter-declaration-clause ')' attribute-specifier[opt]
714/// 'mutable'[opt] exception-specification[opt]
715/// trailing-return-type[opt]
716///
717ExprResult Parser::ParseLambdaExpression() {
718 // Parse lambda-introducer.
719 LambdaIntroducer Intro;
Bill Wendling2434dcf2013-12-05 05:25:04 +0000720 Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000721 if (DiagID) {
722 Diag(Tok, DiagID.getValue());
Alexey Bataev8fe24752013-11-18 08:17:37 +0000723 SkipUntil(tok::r_square, StopAtSemi);
724 SkipUntil(tok::l_brace, StopAtSemi);
725 SkipUntil(tok::r_brace, StopAtSemi);
Eli Friedmandc3b7232012-01-04 02:40:39 +0000726 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000727 }
728
729 return ParseLambdaExpressionAfterIntroducer(Intro);
730}
731
732/// TryParseLambdaExpression - Use lookahead and potentially tentative
733/// parsing to determine if we are looking at a C++0x lambda expression, and parse
734/// it if we are.
735///
736/// If we are not looking at a lambda expression, returns ExprError().
737ExprResult Parser::TryParseLambdaExpression() {
Richard Smith80ad52f2013-01-02 11:42:31 +0000738 assert(getLangOpts().CPlusPlus11
Douglas Gregorae7902c2011-08-04 15:30:47 +0000739 && Tok.is(tok::l_square)
740 && "Not at the start of a possible lambda expression.");
741
742 const Token Next = NextToken(), After = GetLookAheadToken(2);
743
744 // If lookahead indicates this is a lambda...
745 if (Next.is(tok::r_square) || // []
746 Next.is(tok::equal) || // [=
747 (Next.is(tok::amp) && // [&] or [&,
748 (After.is(tok::r_square) ||
749 After.is(tok::comma))) ||
750 (Next.is(tok::identifier) && // [identifier]
751 After.is(tok::r_square))) {
752 return ParseLambdaExpression();
753 }
754
Eli Friedmandc3b7232012-01-04 02:40:39 +0000755 // If lookahead indicates an ObjC message send...
756 // [identifier identifier
Douglas Gregorae7902c2011-08-04 15:30:47 +0000757 if (Next.is(tok::identifier) && After.is(tok::identifier)) {
Eli Friedmandc3b7232012-01-04 02:40:39 +0000758 return ExprEmpty();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000759 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000760
Eli Friedmandc3b7232012-01-04 02:40:39 +0000761 // Here, we're stuck: lambda introducers and Objective-C message sends are
762 // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a
763 // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of
764 // writing two routines to parse a lambda introducer, just try to parse
765 // a lambda introducer first, and fall back if that fails.
766 // (TryParseLambdaIntroducer never produces any diagnostic output.)
Douglas Gregorae7902c2011-08-04 15:30:47 +0000767 LambdaIntroducer Intro;
768 if (TryParseLambdaIntroducer(Intro))
Eli Friedmandc3b7232012-01-04 02:40:39 +0000769 return ExprEmpty();
Bill Wendling2434dcf2013-12-05 05:25:04 +0000770
Douglas Gregorae7902c2011-08-04 15:30:47 +0000771 return ParseLambdaExpressionAfterIntroducer(Intro);
772}
773
Richard Smith440d4562013-05-21 22:21:19 +0000774/// \brief Parse a lambda introducer.
775/// \param Intro A LambdaIntroducer filled in with information about the
776/// contents of the lambda-introducer.
777/// \param SkippedInits If non-null, we are disambiguating between an Obj-C
778/// message send and a lambda expression. In this mode, we will
779/// sometimes skip the initializers for init-captures and not fully
780/// populate \p Intro. This flag will be set to \c true if we do so.
781/// \return A DiagnosticID if it hit something unexpected. The location for
782/// for the diagnostic is that of the current token.
783Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro,
784 bool *SkippedInits) {
David Blaikiedc84cd52013-02-20 22:23:23 +0000785 typedef Optional<unsigned> DiagResult;
Douglas Gregorae7902c2011-08-04 15:30:47 +0000786
787 assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['.");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +0000788 BalancedDelimiterTracker T(*this, tok::l_square);
789 T.consumeOpen();
790
791 Intro.Range.setBegin(T.getOpenLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +0000792
793 bool first = true;
794
795 // Parse capture-default.
796 if (Tok.is(tok::amp) &&
797 (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) {
798 Intro.Default = LCD_ByRef;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000799 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000800 first = false;
801 } else if (Tok.is(tok::equal)) {
802 Intro.Default = LCD_ByCopy;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000803 Intro.DefaultLoc = ConsumeToken();
Douglas Gregorae7902c2011-08-04 15:30:47 +0000804 first = false;
805 }
806
807 while (Tok.isNot(tok::r_square)) {
808 if (!first) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000809 if (Tok.isNot(tok::comma)) {
Douglas Gregor437fbc52012-07-31 00:50:07 +0000810 // Provide a completion for a lambda introducer here. Except
811 // in Objective-C, where this is Almost Surely meant to be a message
812 // send. In that case, fail here and let the ObjC message
813 // expression parser perform the completion.
Douglas Gregord48ab062012-07-31 15:27:48 +0000814 if (Tok.is(tok::code_completion) &&
815 !(getLangOpts().ObjC1 && Intro.Default == LCD_None &&
816 !Intro.Captures.empty())) {
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000817 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
818 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700819 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000820 break;
821 }
822
Douglas Gregorae7902c2011-08-04 15:30:47 +0000823 return DiagResult(diag::err_expected_comma_or_rsquare);
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000824 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000825 ConsumeToken();
826 }
827
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000828 if (Tok.is(tok::code_completion)) {
829 // If we're in Objective-C++ and we have a bare '[', then this is more
830 // likely to be a message receiver.
David Blaikie4e4d0842012-03-11 07:00:24 +0000831 if (getLangOpts().ObjC1 && first)
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000832 Actions.CodeCompleteObjCMessageReceiver(getCurScope());
833 else
834 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
835 /*AfterAmpersand=*/false);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700836 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000837 break;
838 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000839
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000840 first = false;
841
Douglas Gregorae7902c2011-08-04 15:30:47 +0000842 // Parse capture.
843 LambdaCaptureKind Kind = LCK_ByCopy;
844 SourceLocation Loc;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700845 IdentifierInfo *Id = nullptr;
Douglas Gregora7365242012-02-14 19:27:52 +0000846 SourceLocation EllipsisLoc;
Richard Smith0a664b82013-05-09 21:36:41 +0000847 ExprResult Init;
Douglas Gregora7365242012-02-14 19:27:52 +0000848
Douglas Gregorae7902c2011-08-04 15:30:47 +0000849 if (Tok.is(tok::kw_this)) {
850 Kind = LCK_This;
851 Loc = ConsumeToken();
852 } else {
853 if (Tok.is(tok::amp)) {
854 Kind = LCK_ByRef;
855 ConsumeToken();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000856
857 if (Tok.is(tok::code_completion)) {
858 Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro,
859 /*AfterAmpersand=*/true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700860 cutOffParsing();
Douglas Gregor81f3bff2012-02-15 15:34:24 +0000861 break;
862 }
Douglas Gregorae7902c2011-08-04 15:30:47 +0000863 }
864
865 if (Tok.is(tok::identifier)) {
866 Id = Tok.getIdentifierInfo();
867 Loc = ConsumeToken();
868 } else if (Tok.is(tok::kw_this)) {
869 // FIXME: If we want to suggest a fixit here, will need to return more
870 // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be
871 // Clear()ed to prevent emission in case of tentative parsing?
872 return DiagResult(diag::err_this_captured_by_reference);
873 } else {
874 return DiagResult(diag::err_expected_capture);
875 }
Richard Smith0a664b82013-05-09 21:36:41 +0000876
877 if (Tok.is(tok::l_paren)) {
878 BalancedDelimiterTracker Parens(*this, tok::l_paren);
879 Parens.consumeOpen();
880
881 ExprVector Exprs;
882 CommaLocsTy Commas;
Richard Smith440d4562013-05-21 22:21:19 +0000883 if (SkippedInits) {
884 Parens.skipToEnd();
885 *SkippedInits = true;
886 } else if (ParseExpressionList(Exprs, Commas)) {
Richard Smith0a664b82013-05-09 21:36:41 +0000887 Parens.skipToEnd();
888 Init = ExprError();
889 } else {
890 Parens.consumeClose();
891 Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(),
892 Parens.getCloseLocation(),
893 Exprs);
894 }
895 } else if (Tok.is(tok::l_brace) || Tok.is(tok::equal)) {
Bill Wendling2434dcf2013-12-05 05:25:04 +0000896 // Each lambda init-capture forms its own full expression, which clears
897 // Actions.MaybeODRUseExprs. So create an expression evaluation context
898 // to save the necessary state, and restore it later.
899 EnterExpressionEvaluationContext EC(Actions,
900 Sema::PotentiallyEvaluated);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700901 bool HadEquals = TryConsumeToken(tok::equal);
Richard Smith0a664b82013-05-09 21:36:41 +0000902
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700903 if (!SkippedInits) {
904 // Warn on constructs that will change meaning when we implement N3922
905 if (!HadEquals && Tok.is(tok::l_brace)) {
906 Diag(Tok, diag::warn_init_capture_direct_list_init)
907 << FixItHint::CreateInsertion(Tok.getLocation(), "=");
908 }
Richard Smith440d4562013-05-21 22:21:19 +0000909 Init = ParseInitializer();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700910 } else if (Tok.is(tok::l_brace)) {
Richard Smith440d4562013-05-21 22:21:19 +0000911 BalancedDelimiterTracker Braces(*this, tok::l_brace);
912 Braces.consumeOpen();
913 Braces.skipToEnd();
914 *SkippedInits = true;
915 } else {
916 // We're disambiguating this:
917 //
918 // [..., x = expr
919 //
920 // We need to find the end of the following expression in order to
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700921 // determine whether this is an Obj-C message send's receiver, a
922 // C99 designator, or a lambda init-capture.
Richard Smith440d4562013-05-21 22:21:19 +0000923 //
924 // Parse the expression to find where it ends, and annotate it back
925 // onto the tokens. We would have parsed this expression the same way
926 // in either case: both the RHS of an init-capture and the RHS of an
927 // assignment expression are parsed as an initializer-clause, and in
928 // neither case can anything be added to the scope between the '[' and
929 // here.
930 //
931 // FIXME: This is horrible. Adding a mechanism to skip an expression
932 // would be much cleaner.
933 // FIXME: If there is a ',' before the next ']' or ':', we can skip to
934 // that instead. (And if we see a ':' with no matching '?', we can
935 // classify this as an Obj-C message send.)
936 SourceLocation StartLoc = Tok.getLocation();
937 InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true);
938 Init = ParseInitializer();
939
940 if (Tok.getLocation() != StartLoc) {
941 // Back out the lexing of the token after the initializer.
942 PP.RevertCachedTokens(1);
943
944 // Replace the consumed tokens with an appropriate annotation.
945 Tok.setLocation(StartLoc);
946 Tok.setKind(tok::annot_primary_expr);
947 setExprAnnotation(Tok, Init);
948 Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation());
949 PP.AnnotateCachedTokens(Tok);
950
951 // Consume the annotated initializer.
952 ConsumeToken();
953 }
954 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700955 } else
956 TryConsumeToken(tok::ellipsis, EllipsisLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +0000957 }
Bill Wendling2434dcf2013-12-05 05:25:04 +0000958 // If this is an init capture, process the initialization expression
959 // right away. For lambda init-captures such as the following:
960 // const int x = 10;
961 // auto L = [i = x+1](int a) {
962 // return [j = x+2,
963 // &k = x](char b) { };
964 // };
965 // keep in mind that each lambda init-capture has to have:
966 // - its initialization expression executed in the context
967 // of the enclosing/parent decl-context.
968 // - but the variable itself has to be 'injected' into the
969 // decl-context of its lambda's call-operator (which has
970 // not yet been created).
971 // Each init-expression is a full-expression that has to get
972 // Sema-analyzed (for capturing etc.) before its lambda's
973 // call-operator's decl-context, scope & scopeinfo are pushed on their
974 // respective stacks. Thus if any variable is odr-used in the init-capture
975 // it will correctly get captured in the enclosing lambda, if one exists.
976 // The init-variables above are created later once the lambdascope and
977 // call-operators decl-context is pushed onto its respective stack.
Douglas Gregorae7902c2011-08-04 15:30:47 +0000978
Bill Wendling2434dcf2013-12-05 05:25:04 +0000979 // Since the lambda init-capture's initializer expression occurs in the
980 // context of the enclosing function or lambda, therefore we can not wait
981 // till a lambda scope has been pushed on before deciding whether the
982 // variable needs to be captured. We also need to process all
983 // lvalue-to-rvalue conversions and discarded-value conversions,
984 // so that we can avoid capturing certain constant variables.
985 // For e.g.,
986 // void test() {
987 // const int x = 10;
988 // auto L = [&z = x](char a) { <-- don't capture by the current lambda
989 // return [y = x](int i) { <-- don't capture by enclosing lambda
990 // return y;
991 // }
992 // };
993 // If x was not const, the second use would require 'L' to capture, and
994 // that would be an error.
995
996 ParsedType InitCaptureParsedType;
997 if (Init.isUsable()) {
998 // Get the pointer and store it in an lvalue, so we can use it as an
999 // out argument.
1000 Expr *InitExpr = Init.get();
1001 // This performs any lvalue-to-rvalue conversions if necessary, which
1002 // can affect what gets captured in the containing decl-context.
1003 QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization(
1004 Loc, Kind == LCK_ByRef, Id, InitExpr);
1005 Init = InitExpr;
1006 InitCaptureParsedType.set(InitCaptureType);
1007 }
1008 Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001009 }
1010
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001011 T.consumeClose();
1012 Intro.Range.setEnd(T.getCloseLocation());
Douglas Gregorae7902c2011-08-04 15:30:47 +00001013 return DiagResult();
1014}
1015
Douglas Gregor81f3bff2012-02-15 15:34:24 +00001016/// TryParseLambdaIntroducer - Tentatively parse a lambda introducer.
Douglas Gregorae7902c2011-08-04 15:30:47 +00001017///
1018/// Returns true if it hit something unexpected.
1019bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) {
1020 TentativeParsingAction PA(*this);
1021
Richard Smith440d4562013-05-21 22:21:19 +00001022 bool SkippedInits = false;
1023 Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits));
Douglas Gregorae7902c2011-08-04 15:30:47 +00001024
1025 if (DiagID) {
1026 PA.Revert();
1027 return true;
1028 }
1029
Richard Smith440d4562013-05-21 22:21:19 +00001030 if (SkippedInits) {
1031 // Parse it again, but this time parse the init-captures too.
1032 PA.Revert();
1033 Intro = LambdaIntroducer();
1034 DiagID = ParseLambdaIntroducer(Intro);
1035 assert(!DiagID && "parsing lambda-introducer failed on reparse");
1036 return false;
1037 }
1038
Douglas Gregorae7902c2011-08-04 15:30:47 +00001039 PA.Commit();
1040 return false;
1041}
1042
1043/// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda
1044/// expression.
1045ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
1046 LambdaIntroducer &Intro) {
Eli Friedmandc3b7232012-01-04 02:40:39 +00001047 SourceLocation LambdaBeginLoc = Intro.Range.getBegin();
1048 Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda);
1049
1050 PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc,
1051 "lambda expression parsing");
1052
Faisal Valifad9e132013-09-26 19:54:12 +00001053
1054
Richard Smith0a664b82013-05-09 21:36:41 +00001055 // FIXME: Call into Actions to add any init-capture declarations to the
1056 // scope while parsing the lambda-declarator and compound-statement.
1057
Douglas Gregorae7902c2011-08-04 15:30:47 +00001058 // Parse lambda-declarator[opt].
1059 DeclSpec DS(AttrFactory);
Eli Friedmanf88c4002012-01-04 04:41:38 +00001060 Declarator D(DS, Declarator::LambdaExprContext);
Faisal Valifad9e132013-09-26 19:54:12 +00001061 TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth);
1062 Actions.PushLambdaScope();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001063
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001064 TypeResult TrailingReturnType;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001065 if (Tok.is(tok::l_paren)) {
1066 ParseScope PrototypeScope(this,
1067 Scope::FunctionPrototypeScope |
Richard Smith3a2b7a12013-01-28 22:42:45 +00001068 Scope::FunctionDeclarationScope |
Douglas Gregorae7902c2011-08-04 15:30:47 +00001069 Scope::DeclScope);
1070
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001071 SourceLocation DeclEndLoc;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001072 BalancedDelimiterTracker T(*this, tok::l_paren);
1073 T.consumeOpen();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001074 SourceLocation LParenLoc = T.getOpenLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001075
1076 // Parse parameter-declaration-clause.
1077 ParsedAttributes Attr(AttrFactory);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001078 SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001079 SourceLocation EllipsisLoc;
Faisal Valifad9e132013-09-26 19:54:12 +00001080
1081 if (Tok.isNot(tok::r_paren)) {
Faisal Valifad9e132013-09-26 19:54:12 +00001082 Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001083 ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc);
Faisal Valifad9e132013-09-26 19:54:12 +00001084 // For a generic lambda, each 'auto' within the parameter declaration
1085 // clause creates a template type parameter, so increment the depth.
1086 if (Actions.getCurGenericLambda())
1087 ++CurTemplateDepthTracker;
1088 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001089 T.consumeClose();
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001090 SourceLocation RParenLoc = T.getCloseLocation();
1091 DeclEndLoc = RParenLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001092
Stephen Hines651f13c2014-04-23 16:59:28 -07001093 // GNU-style attributes must be parsed before the mutable specifier to be
1094 // compatible with GCC.
1095 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1096
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001097 // MSVC-style attributes must be parsed before the mutable specifier to be
1098 // compatible with MSVC.
1099 while (Tok.is(tok::kw___declspec))
1100 ParseMicrosoftDeclSpec(Attr);
1101
Douglas Gregorae7902c2011-08-04 15:30:47 +00001102 // Parse 'mutable'[opt].
1103 SourceLocation MutableLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001104 if (TryConsumeToken(tok::kw_mutable, MutableLoc))
Douglas Gregorae7902c2011-08-04 15:30:47 +00001105 DeclEndLoc = MutableLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001106
1107 // Parse exception-specification[opt].
1108 ExceptionSpecificationType ESpecType = EST_None;
1109 SourceRange ESpecRange;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001110 SmallVector<ParsedType, 2> DynamicExceptions;
1111 SmallVector<SourceRange, 2> DynamicExceptionRanges;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001112 ExprResult NoexceptExpr;
Stephen Hines176edba2014-12-01 14:53:08 -08001113 CachedTokens *ExceptionSpecTokens;
1114 ESpecType = tryParseExceptionSpecification(/*Delayed=*/false,
1115 ESpecRange,
Douglas Gregor74e2fc32012-04-16 18:27:27 +00001116 DynamicExceptions,
1117 DynamicExceptionRanges,
Stephen Hines176edba2014-12-01 14:53:08 -08001118 NoexceptExpr,
1119 ExceptionSpecTokens);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001120
1121 if (ESpecType != EST_None)
1122 DeclEndLoc = ESpecRange.getEnd();
1123
1124 // Parse attribute-specifier[opt].
Richard Smith4e24f0f2013-01-02 12:01:23 +00001125 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001126
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001127 SourceLocation FunLocalRangeEnd = DeclEndLoc;
1128
Douglas Gregorae7902c2011-08-04 15:30:47 +00001129 // Parse trailing-return-type[opt].
Douglas Gregorae7902c2011-08-04 15:30:47 +00001130 if (Tok.is(tok::arrow)) {
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001131 FunLocalRangeEnd = Tok.getLocation();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001132 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001133 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001134 if (Range.getEnd().isValid())
1135 DeclEndLoc = Range.getEnd();
1136 }
1137
1138 PrototypeScope.Exit();
1139
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001140 SourceLocation NoLoc;
Douglas Gregorae7902c2011-08-04 15:30:47 +00001141 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001142 /*isAmbiguous=*/false,
1143 LParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001144 ParamInfo.data(), ParamInfo.size(),
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001145 EllipsisLoc, RParenLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001146 DS.getTypeQualifiers(),
1147 /*RefQualifierIsLValueRef=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001148 /*RefQualifierLoc=*/NoLoc,
1149 /*ConstQualifierLoc=*/NoLoc,
1150 /*VolatileQualifierLoc=*/NoLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001151 /*RestrictQualifierLoc=*/NoLoc,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001152 MutableLoc,
1153 ESpecType, ESpecRange.getBegin(),
1154 DynamicExceptions.data(),
1155 DynamicExceptionRanges.data(),
1156 DynamicExceptions.size(),
1157 NoexceptExpr.isUsable() ?
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001158 NoexceptExpr.get() : nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001159 /*ExceptionSpecTokens*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001160 LParenLoc, FunLocalRangeEnd, D,
Douglas Gregorae7902c2011-08-04 15:30:47 +00001161 TrailingReturnType),
1162 Attr, DeclEndLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07001163 } else if (Tok.is(tok::kw_mutable) || Tok.is(tok::arrow) ||
1164 Tok.is(tok::kw___attribute) ||
1165 (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) {
1166 // It's common to forget that one needs '()' before 'mutable', an attribute
1167 // specifier, or the result type. Deal with this.
1168 unsigned TokKind = 0;
1169 switch (Tok.getKind()) {
1170 case tok::kw_mutable: TokKind = 0; break;
1171 case tok::arrow: TokKind = 1; break;
1172 case tok::kw___attribute:
1173 case tok::l_square: TokKind = 2; break;
1174 default: llvm_unreachable("Unknown token kind");
1175 }
1176
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001177 Diag(Tok, diag::err_lambda_missing_parens)
Stephen Hines651f13c2014-04-23 16:59:28 -07001178 << TokKind
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001179 << FixItHint::CreateInsertion(Tok.getLocation(), "() ");
1180 SourceLocation DeclLoc = Tok.getLocation();
1181 SourceLocation DeclEndLoc = DeclLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001182
1183 // GNU-style attributes must be parsed before the mutable specifier to be
1184 // compatible with GCC.
1185 ParsedAttributes Attr(AttrFactory);
1186 MaybeParseGNUAttributes(Attr, &DeclEndLoc);
1187
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001188 // Parse 'mutable', if it's there.
1189 SourceLocation MutableLoc;
1190 if (Tok.is(tok::kw_mutable)) {
1191 MutableLoc = ConsumeToken();
1192 DeclEndLoc = MutableLoc;
1193 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001194
1195 // Parse attribute-specifier[opt].
1196 MaybeParseCXX11Attributes(Attr, &DeclEndLoc);
1197
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001198 // Parse the return type, if there is one.
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001199 if (Tok.is(tok::arrow)) {
1200 SourceRange Range;
Richard Smith54655be2012-06-12 01:51:59 +00001201 TrailingReturnType = ParseTrailingReturnType(Range);
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001202 if (Range.getEnd().isValid())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001203 DeclEndLoc = Range.getEnd();
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001204 }
1205
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001206 SourceLocation NoLoc;
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001207 D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001208 /*isAmbiguous=*/false,
1209 /*LParenLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001210 /*Params=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001211 /*NumParams=*/0,
1212 /*EllipsisLoc=*/NoLoc,
1213 /*RParenLoc=*/NoLoc,
1214 /*TypeQuals=*/0,
1215 /*RefQualifierIsLValueRef=*/true,
1216 /*RefQualifierLoc=*/NoLoc,
1217 /*ConstQualifierLoc=*/NoLoc,
1218 /*VolatileQualifierLoc=*/NoLoc,
Stephen Hines176edba2014-12-01 14:53:08 -08001219 /*RestrictQualifierLoc=*/NoLoc,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001220 MutableLoc,
1221 EST_None,
1222 /*ESpecLoc=*/NoLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001223 /*Exceptions=*/nullptr,
1224 /*ExceptionRanges=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001225 /*NumExceptions=*/0,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001226 /*NoexceptExpr=*/nullptr,
Stephen Hines176edba2014-12-01 14:53:08 -08001227 /*ExceptionSpecTokens=*/nullptr,
Abramo Bagnara59c0a812012-10-04 21:42:10 +00001228 DeclLoc, DeclEndLoc, D,
1229 TrailingReturnType),
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001230 Attr, DeclEndLoc);
Douglas Gregorae7902c2011-08-04 15:30:47 +00001231 }
Douglas Gregorc9ecec42012-02-16 21:53:36 +00001232
Douglas Gregorae7902c2011-08-04 15:30:47 +00001233
Eli Friedman906a7e12012-01-06 03:05:34 +00001234 // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using
1235 // it.
Douglas Gregorfccfb622012-02-21 22:51:27 +00001236 unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope;
Douglas Gregorfccfb622012-02-21 22:51:27 +00001237 ParseScope BodyScope(this, ScopeFlags);
Eli Friedman906a7e12012-01-06 03:05:34 +00001238
Eli Friedmanec9ea722012-01-05 03:35:19 +00001239 Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope());
1240
Douglas Gregorae7902c2011-08-04 15:30:47 +00001241 // Parse compound-statement.
Eli Friedmandc3b7232012-01-04 02:40:39 +00001242 if (!Tok.is(tok::l_brace)) {
Douglas Gregorae7902c2011-08-04 15:30:47 +00001243 Diag(Tok, diag::err_expected_lambda_body);
Eli Friedmandc3b7232012-01-04 02:40:39 +00001244 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1245 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001246 }
1247
Eli Friedmandc3b7232012-01-04 02:40:39 +00001248 StmtResult Stmt(ParseCompoundStatementBody());
1249 BodyScope.Exit();
1250
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001251 if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001252 return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001253
Eli Friedmandeeab902012-01-04 02:46:53 +00001254 Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope());
1255 return ExprError();
Douglas Gregorae7902c2011-08-04 15:30:47 +00001256}
1257
Reid Spencer5f016e22007-07-11 17:01:13 +00001258/// ParseCXXCasts - This handles the various ways to cast expressions to another
1259/// type.
1260///
1261/// postfix-expression: [C++ 5.2p1]
1262/// 'dynamic_cast' '<' type-name '>' '(' expression ')'
1263/// 'static_cast' '<' type-name '>' '(' expression ')'
1264/// 'reinterpret_cast' '<' type-name '>' '(' expression ')'
1265/// 'const_cast' '<' type-name '>' '(' expression ')'
1266///
John McCall60d7b3a2010-08-24 06:29:42 +00001267ExprResult Parser::ParseCXXCasts() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 tok::TokenKind Kind = Tok.getKind();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001269 const char *CastName = nullptr; // For error messages
Reid Spencer5f016e22007-07-11 17:01:13 +00001270
1271 switch (Kind) {
David Blaikieeb2d1f12011-09-23 20:26:49 +00001272 default: llvm_unreachable("Unknown C++ cast!");
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 case tok::kw_const_cast: CastName = "const_cast"; break;
1274 case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break;
1275 case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break;
1276 case tok::kw_static_cast: CastName = "static_cast"; break;
1277 }
1278
1279 SourceLocation OpLoc = ConsumeToken();
1280 SourceLocation LAngleBracketLoc = Tok.getLocation();
1281
Richard Smithea698b32011-04-14 21:45:45 +00001282 // Check for "<::" which is parsed as "[:". If found, fix token stream,
1283 // diagnose error, suggest fix, and recover parsing.
Richard Smith78fe3e02012-08-20 17:37:52 +00001284 if (Tok.is(tok::l_square) && Tok.getLength() == 2) {
1285 Token Next = NextToken();
1286 if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next))
1287 FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true);
1288 }
Richard Smithea698b32011-04-14 21:45:45 +00001289
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001291 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001292
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001293 // Parse the common declaration-specifiers piece.
1294 DeclSpec DS(AttrFactory);
1295 ParseSpecifierQualifierList(DS);
1296
1297 // Parse the abstract-declarator, if present.
1298 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
1299 ParseDeclarator(DeclaratorInfo);
1300
Reid Spencer5f016e22007-07-11 17:01:13 +00001301 SourceLocation RAngleBracketLoc = Tok.getLocation();
1302
Stephen Hines651f13c2014-04-23 16:59:28 -07001303 if (ExpectAndConsume(tok::greater))
1304 return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less);
Reid Spencer5f016e22007-07-11 17:01:13 +00001305
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001306 SourceLocation LParenLoc, RParenLoc;
1307 BalancedDelimiterTracker T(*this, tok::l_paren);
Reid Spencer5f016e22007-07-11 17:01:13 +00001308
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001309 if (T.expectAndConsume(diag::err_expected_lparen_after, CastName))
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001310 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001311
John McCall60d7b3a2010-08-24 06:29:42 +00001312 ExprResult Result = ParseExpression();
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Argyrios Kyrtzidis21e7ad22009-05-22 10:23:16 +00001314 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001315 T.consumeClose();
Reid Spencer5f016e22007-07-11 17:01:13 +00001316
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001317 if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType())
Douglas Gregor49badde2008-10-27 19:41:14 +00001318 Result = Actions.ActOnCXXNamedCast(OpLoc, Kind,
Argyrios Kyrtzidis31862ba2011-07-01 22:22:50 +00001319 LAngleBracketLoc, DeclaratorInfo,
Douglas Gregor809070a2009-02-18 17:45:20 +00001320 RAngleBracketLoc,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001321 T.getOpenLocation(), Result.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001322 T.getCloseLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001323
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001324 return Result;
Reid Spencer5f016e22007-07-11 17:01:13 +00001325}
1326
Sebastian Redlc42e1182008-11-11 11:37:55 +00001327/// ParseCXXTypeid - This handles the C++ typeid expression.
1328///
1329/// postfix-expression: [C++ 5.2p1]
1330/// 'typeid' '(' expression ')'
1331/// 'typeid' '(' type-id ')'
1332///
John McCall60d7b3a2010-08-24 06:29:42 +00001333ExprResult Parser::ParseCXXTypeid() {
Sebastian Redlc42e1182008-11-11 11:37:55 +00001334 assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!");
1335
1336 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001337 SourceLocation LParenLoc, RParenLoc;
1338 BalancedDelimiterTracker T(*this, tok::l_paren);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001339
1340 // typeid expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001341 if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid"))
Sebastian Redl20df9b72008-12-11 22:51:44 +00001342 return ExprError();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001343 LParenLoc = T.getOpenLocation();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001344
John McCall60d7b3a2010-08-24 06:29:42 +00001345 ExprResult Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001346
Richard Smith05766812012-08-18 00:55:03 +00001347 // C++0x [expr.typeid]p3:
1348 // When typeid is applied to an expression other than an lvalue of a
1349 // polymorphic class type [...] The expression is an unevaluated
1350 // operand (Clause 5).
1351 //
1352 // Note that we can't tell whether the expression is an lvalue of a
1353 // polymorphic class type until after we've parsed the expression; we
1354 // speculatively assume the subexpression is unevaluated, and fix it up
1355 // later.
1356 //
1357 // We enter the unevaluated context before trying to determine whether we
1358 // have a type-id, because the tentative parse logic will try to resolve
1359 // names, and must treat them as unevaluated.
Eli Friedman80bfa3d2012-09-26 04:34:21 +00001360 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated,
1361 Sema::ReuseLambdaContextDecl);
Richard Smith05766812012-08-18 00:55:03 +00001362
Sebastian Redlc42e1182008-11-11 11:37:55 +00001363 if (isTypeIdInParens()) {
Douglas Gregor809070a2009-02-18 17:45:20 +00001364 TypeResult Ty = ParseTypeName();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001365
1366 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001367 T.consumeClose();
1368 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001369 if (Ty.isInvalid() || RParenLoc.isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00001370 return ExprError();
Sebastian Redlc42e1182008-11-11 11:37:55 +00001371
1372 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true,
John McCallb3d87482010-08-24 05:47:05 +00001373 Ty.get().getAsOpaquePtr(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001374 } else {
1375 Result = ParseExpression();
1376
1377 // Match the ')'.
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001378 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001379 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001380 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001381 T.consumeClose();
1382 RParenLoc = T.getCloseLocation();
Douglas Gregor4eb4f0f2010-09-08 23:14:30 +00001383 if (RParenLoc.isInvalid())
1384 return ExprError();
Douglas Gregorfadb53b2011-03-12 01:48:56 +00001385
Sebastian Redlc42e1182008-11-11 11:37:55 +00001386 Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001387 Result.get(), RParenLoc);
Sebastian Redlc42e1182008-11-11 11:37:55 +00001388 }
1389 }
1390
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001391 return Result;
Sebastian Redlc42e1182008-11-11 11:37:55 +00001392}
1393
Francois Pichet01b7c302010-09-08 12:20:18 +00001394/// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression.
1395///
1396/// '__uuidof' '(' expression ')'
1397/// '__uuidof' '(' type-id ')'
1398///
1399ExprResult Parser::ParseCXXUuidof() {
1400 assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!");
1401
1402 SourceLocation OpLoc = ConsumeToken();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001403 BalancedDelimiterTracker T(*this, tok::l_paren);
Francois Pichet01b7c302010-09-08 12:20:18 +00001404
1405 // __uuidof expressions are always parenthesized.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001406 if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof"))
Francois Pichet01b7c302010-09-08 12:20:18 +00001407 return ExprError();
1408
1409 ExprResult Result;
1410
1411 if (isTypeIdInParens()) {
1412 TypeResult Ty = ParseTypeName();
1413
1414 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001415 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001416
1417 if (Ty.isInvalid())
1418 return ExprError();
1419
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001420 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true,
1421 Ty.get().getAsOpaquePtr(),
1422 T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001423 } else {
1424 EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated);
1425 Result = ParseExpression();
1426
1427 // Match the ')'.
1428 if (Result.isInvalid())
Alexey Bataev8fe24752013-11-18 08:17:37 +00001429 SkipUntil(tok::r_paren, StopAtSemi);
Francois Pichet01b7c302010-09-08 12:20:18 +00001430 else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001431 T.consumeClose();
Francois Pichet01b7c302010-09-08 12:20:18 +00001432
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001433 Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(),
1434 /*isType=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001435 Result.get(), T.getCloseLocation());
Francois Pichet01b7c302010-09-08 12:20:18 +00001436 }
1437 }
1438
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001439 return Result;
Francois Pichet01b7c302010-09-08 12:20:18 +00001440}
1441
Douglas Gregord4dca082010-02-24 18:44:31 +00001442/// \brief Parse a C++ pseudo-destructor expression after the base,
1443/// . or -> operator, and nested-name-specifier have already been
1444/// parsed.
1445///
1446/// postfix-expression: [C++ 5.2]
1447/// postfix-expression . pseudo-destructor-name
1448/// postfix-expression -> pseudo-destructor-name
1449///
1450/// pseudo-destructor-name:
1451/// ::[opt] nested-name-specifier[opt] type-name :: ~type-name
1452/// ::[opt] nested-name-specifier template simple-template-id ::
1453/// ~type-name
1454/// ::[opt] nested-name-specifier[opt] ~type-name
1455///
John McCall60d7b3a2010-08-24 06:29:42 +00001456ExprResult
Stephen Hines176edba2014-12-01 14:53:08 -08001457Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc,
Douglas Gregord4dca082010-02-24 18:44:31 +00001458 tok::TokenKind OpKind,
1459 CXXScopeSpec &SS,
John McCallb3d87482010-08-24 05:47:05 +00001460 ParsedType ObjectType) {
Douglas Gregord4dca082010-02-24 18:44:31 +00001461 // We're parsing either a pseudo-destructor-name or a dependent
1462 // member access that has the same form as a
1463 // pseudo-destructor-name. We parse both in the same way and let
1464 // the action model sort them out.
1465 //
1466 // Note that the ::[opt] nested-name-specifier[opt] has already
1467 // been parsed, and if there was a simple-template-id, it has
1468 // been coalesced into a template-id annotation token.
1469 UnqualifiedId FirstTypeName;
1470 SourceLocation CCLoc;
1471 if (Tok.is(tok::identifier)) {
1472 FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation());
1473 ConsumeToken();
1474 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1475 CCLoc = ConsumeToken();
1476 } else if (Tok.is(tok::annot_template_id)) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001477 // FIXME: retrieve TemplateKWLoc from template-id annotation and
1478 // store it in the pseudo-dtor node (to be used when instantiating it).
Douglas Gregord4dca082010-02-24 18:44:31 +00001479 FirstTypeName.setTemplateId(
1480 (TemplateIdAnnotation *)Tok.getAnnotationValue());
1481 ConsumeToken();
1482 assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail");
1483 CCLoc = ConsumeToken();
1484 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001485 FirstTypeName.setIdentifier(nullptr, SourceLocation());
Douglas Gregord4dca082010-02-24 18:44:31 +00001486 }
1487
1488 // Parse the tilde.
1489 assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail");
1490 SourceLocation TildeLoc = ConsumeToken();
David Blaikie91ec7892011-12-16 16:03:09 +00001491
1492 if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) {
1493 DeclSpec DS(AttrFactory);
Benjamin Kramer85c60db2011-12-18 12:18:02 +00001494 ParseDecltypeSpecifier(DS);
David Blaikie91ec7892011-12-16 16:03:09 +00001495 if (DS.getTypeSpecType() == TST_error)
1496 return ExprError();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001497 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1498 TildeLoc, DS);
David Blaikie91ec7892011-12-16 16:03:09 +00001499 }
1500
Douglas Gregord4dca082010-02-24 18:44:31 +00001501 if (!Tok.is(tok::identifier)) {
1502 Diag(Tok, diag::err_destructor_tilde_identifier);
1503 return ExprError();
1504 }
1505
1506 // Parse the second type.
1507 UnqualifiedId SecondTypeName;
1508 IdentifierInfo *Name = Tok.getIdentifierInfo();
1509 SourceLocation NameLoc = ConsumeToken();
1510 SecondTypeName.setIdentifier(Name, NameLoc);
1511
1512 // If there is a '<', the second type name is a template-id. Parse
1513 // it as such.
1514 if (Tok.is(tok::less) &&
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001515 ParseUnqualifiedIdTemplateId(SS, SourceLocation(),
1516 Name, NameLoc,
1517 false, ObjectType, SecondTypeName,
1518 /*AssumeTemplateName=*/true))
Douglas Gregord4dca082010-02-24 18:44:31 +00001519 return ExprError();
1520
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001521 return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind,
1522 SS, FirstTypeName, CCLoc, TildeLoc,
1523 SecondTypeName);
Douglas Gregord4dca082010-02-24 18:44:31 +00001524}
1525
Reid Spencer5f016e22007-07-11 17:01:13 +00001526/// ParseCXXBoolLiteral - This handles the C++ Boolean literals.
1527///
1528/// boolean-literal: [C++ 2.13.5]
1529/// 'true'
1530/// 'false'
John McCall60d7b3a2010-08-24 06:29:42 +00001531ExprResult Parser::ParseCXXBoolLiteral() {
Reid Spencer5f016e22007-07-11 17:01:13 +00001532 tok::TokenKind Kind = Tok.getKind();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001533 return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind);
Reid Spencer5f016e22007-07-11 17:01:13 +00001534}
Chris Lattner50dd2892008-02-26 00:51:44 +00001535
1536/// ParseThrowExpression - This handles the C++ throw expression.
1537///
1538/// throw-expression: [C++ 15]
1539/// 'throw' assignment-expression[opt]
John McCall60d7b3a2010-08-24 06:29:42 +00001540ExprResult Parser::ParseThrowExpression() {
Chris Lattner50dd2892008-02-26 00:51:44 +00001541 assert(Tok.is(tok::kw_throw) && "Not throw!");
Chris Lattner50dd2892008-02-26 00:51:44 +00001542 SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token.
Sebastian Redl20df9b72008-12-11 22:51:44 +00001543
Chris Lattner2a2819a2008-04-06 06:02:23 +00001544 // If the current token isn't the start of an assignment-expression,
1545 // then the expression is not present. This handles things like:
1546 // "C ? throw : (void)42", which is crazy but legal.
1547 switch (Tok.getKind()) { // FIXME: move this predicate somewhere common.
1548 case tok::semi:
1549 case tok::r_paren:
1550 case tok::r_square:
1551 case tok::r_brace:
1552 case tok::colon:
1553 case tok::comma:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001554 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr);
Chris Lattner50dd2892008-02-26 00:51:44 +00001555
Chris Lattner2a2819a2008-04-06 06:02:23 +00001556 default:
John McCall60d7b3a2010-08-24 06:29:42 +00001557 ExprResult Expr(ParseAssignmentExpression());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001558 if (Expr.isInvalid()) return Expr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001559 return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get());
Chris Lattner2a2819a2008-04-06 06:02:23 +00001560 }
Chris Lattner50dd2892008-02-26 00:51:44 +00001561}
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001562
1563/// ParseCXXThis - This handles the C++ 'this' pointer.
1564///
1565/// C++ 9.3.2: In the body of a non-static member function, the keyword this is
1566/// a non-lvalue expression whose value is the address of the object for which
1567/// the function is called.
John McCall60d7b3a2010-08-24 06:29:42 +00001568ExprResult Parser::ParseCXXThis() {
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001569 assert(Tok.is(tok::kw_this) && "Not 'this'!");
1570 SourceLocation ThisLoc = ConsumeToken();
Sebastian Redlf53597f2009-03-15 17:47:39 +00001571 return Actions.ActOnCXXThis(ThisLoc);
Argyrios Kyrtzidis4cc18a42008-06-24 22:12:16 +00001572}
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001573
1574/// ParseCXXTypeConstructExpression - Parse construction of a specified type.
1575/// Can be interpreted either as function-style casting ("int(x)")
1576/// or class type construction ("ClassType(x,y,z)")
1577/// or creation of a value-initialized type ("int()").
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001578/// See [C++ 5.2.3].
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001579///
1580/// postfix-expression: [C++ 5.2p1]
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001581/// simple-type-specifier '(' expression-list[opt] ')'
1582/// [C++0x] simple-type-specifier braced-init-list
1583/// typename-specifier '(' expression-list[opt] ')'
1584/// [C++0x] typename-specifier braced-init-list
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001585///
John McCall60d7b3a2010-08-24 06:29:42 +00001586ExprResult
Sebastian Redl20df9b72008-12-11 22:51:44 +00001587Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) {
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001588 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
John McCallb3d87482010-08-24 05:47:05 +00001589 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get();
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001590
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001591 assert((Tok.is(tok::l_paren) ||
Richard Smith80ad52f2013-01-02 11:42:31 +00001592 (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)))
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001593 && "Expected '(' or '{'!");
Douglas Gregorbc61bd82011-01-11 00:33:19 +00001594
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001595 if (Tok.is(tok::l_brace)) {
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001596 ExprResult Init = ParseBraceInitializer();
1597 if (Init.isInvalid())
1598 return Init;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001599 Expr *InitList = Init.get();
Sebastian Redl6dc00f62012-02-12 18:41:05 +00001600 return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(),
1601 MultiExprArg(&InitList, 1),
1602 SourceLocation());
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001603 } else {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001604 BalancedDelimiterTracker T(*this, tok::l_paren);
1605 T.consumeOpen();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001606
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00001607 ExprVector Exprs;
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001608 CommaLocsTy CommaLocs;
1609
1610 if (Tok.isNot(tok::r_paren)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001611 if (ParseExpressionList(Exprs, CommaLocs, [&] {
1612 Actions.CodeCompleteConstructor(getCurScope(),
1613 TypeRep.get()->getCanonicalTypeInternal(),
1614 DS.getLocEnd(), Exprs);
1615 })) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001616 SkipUntil(tok::r_paren, StopAtSemi);
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001617 return ExprError();
1618 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001619 }
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001620
1621 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001622 T.consumeClose();
Sebastian Redldbef1bb2011-06-05 12:23:16 +00001623
1624 // TypeRep could be null, if it references an invalid typedef.
1625 if (!TypeRep)
1626 return ExprError();
1627
1628 assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&&
1629 "Unexpected number of commas!");
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001630 return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(),
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001631 Exprs,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00001632 T.getCloseLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001633 }
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001634}
1635
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001636/// ParseCXXCondition - if/switch/while condition expression.
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001637///
1638/// condition:
1639/// expression
1640/// type-specifier-seq declarator '=' assignment-expression
Richard Smith0635aa72012-02-22 06:49:09 +00001641/// [C++11] type-specifier-seq declarator '=' initializer-clause
1642/// [C++11] type-specifier-seq declarator braced-init-list
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001643/// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt]
1644/// '=' assignment-expression
1645///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001646/// \param ExprOut if the condition was parsed as an expression, the parsed
1647/// expression.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001648///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00001649/// \param DeclOut if the condition was parsed as a declaration, the parsed
1650/// declaration.
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001651///
Douglas Gregor586596f2010-05-06 17:25:47 +00001652/// \param Loc The location of the start of the statement that requires this
1653/// condition, e.g., the "for" in a for loop.
1654///
1655/// \param ConvertToBoolean Whether the condition expression should be
1656/// converted to a boolean value.
1657///
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001658/// \returns true if there was a parsing, false otherwise.
John McCall60d7b3a2010-08-24 06:29:42 +00001659bool Parser::ParseCXXCondition(ExprResult &ExprOut,
1660 Decl *&DeclOut,
Douglas Gregor586596f2010-05-06 17:25:47 +00001661 SourceLocation Loc,
1662 bool ConvertToBoolean) {
Douglas Gregor01dfea02010-01-10 23:08:15 +00001663 if (Tok.is(tok::code_completion)) {
John McCallf312b1e2010-08-26 23:41:50 +00001664 Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00001665 cutOffParsing();
1666 return true;
Douglas Gregor01dfea02010-01-10 23:08:15 +00001667 }
1668
Sean Hunt2edf0a22012-06-23 05:07:58 +00001669 ParsedAttributesWithRange attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00001670 MaybeParseCXX11Attributes(attrs);
Sean Hunt2edf0a22012-06-23 05:07:58 +00001671
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001672 if (!isCXXConditionDeclaration()) {
Sean Hunt2edf0a22012-06-23 05:07:58 +00001673 ProhibitAttributes(attrs);
1674
Douglas Gregor586596f2010-05-06 17:25:47 +00001675 // Parse the expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001676 ExprOut = ParseExpression(); // expression
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001677 DeclOut = nullptr;
John McCall60d7b3a2010-08-24 06:29:42 +00001678 if (ExprOut.isInvalid())
Douglas Gregor586596f2010-05-06 17:25:47 +00001679 return true;
1680
1681 // If required, convert to a boolean value.
1682 if (ConvertToBoolean)
John McCall60d7b3a2010-08-24 06:29:42 +00001683 ExprOut
1684 = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get());
1685 return ExprOut.isInvalid();
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001686 }
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001687
1688 // type-specifier-seq
John McCall0b7e6782011-03-24 11:26:52 +00001689 DeclSpec DS(AttrFactory);
Richard Smith6b3d3e52013-02-20 19:22:51 +00001690 DS.takeAttributesFrom(attrs);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001691 ParseSpecifierQualifierList(DS);
1692
1693 // declarator
1694 Declarator DeclaratorInfo(DS, Declarator::ConditionContext);
1695 ParseDeclarator(DeclaratorInfo);
1696
1697 // simple-asm-expr[opt]
1698 if (Tok.is(tok::kw_asm)) {
Sebastian Redlab197ba2009-02-09 18:23:29 +00001699 SourceLocation Loc;
John McCall60d7b3a2010-08-24 06:29:42 +00001700 ExprResult AsmLabel(ParseSimpleAsm(&Loc));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00001701 if (AsmLabel.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00001702 SkipUntil(tok::semi, StopAtSemi);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001703 return true;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001704 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001705 DeclaratorInfo.setAsmLabel(AsmLabel.get());
Sebastian Redlab197ba2009-02-09 18:23:29 +00001706 DeclaratorInfo.SetRangeEnd(Loc);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001707 }
1708
1709 // If attributes are present, parse them.
John McCall7f040a92010-12-24 02:08:15 +00001710 MaybeParseGNUAttributes(DeclaratorInfo);
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001711
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001712 // Type-check the declaration itself.
John McCall60d7b3a2010-08-24 06:29:42 +00001713 DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(),
John McCall7f040a92010-12-24 02:08:15 +00001714 DeclaratorInfo);
John McCall60d7b3a2010-08-24 06:29:42 +00001715 DeclOut = Dcl.get();
1716 ExprOut = ExprError();
Argyrios Kyrtzidisa6eb5f82010-10-08 02:39:23 +00001717
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001718 // '=' assignment-expression
Richard Trieud6c7c672012-01-18 22:54:52 +00001719 // If a '==' or '+=' is found, suggest a fixit to '='.
Richard Smith0635aa72012-02-22 06:49:09 +00001720 bool CopyInitialization = isTokenEqualOrEqualTypo();
1721 if (CopyInitialization)
Jeffrey Yasskindec09842011-01-18 02:00:16 +00001722 ConsumeToken();
Richard Smith0635aa72012-02-22 06:49:09 +00001723
1724 ExprResult InitExpr = ExprError();
Richard Smith80ad52f2013-01-02 11:42:31 +00001725 if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
Richard Smith0635aa72012-02-22 06:49:09 +00001726 Diag(Tok.getLocation(),
1727 diag::warn_cxx98_compat_generalized_initializer_lists);
1728 InitExpr = ParseBraceInitializer();
1729 } else if (CopyInitialization) {
1730 InitExpr = ParseAssignmentExpression();
1731 } else if (Tok.is(tok::l_paren)) {
1732 // This was probably an attempt to initialize the variable.
1733 SourceLocation LParen = ConsumeParen(), RParen = LParen;
Alexey Bataev8fe24752013-11-18 08:17:37 +00001734 if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch))
Richard Smith0635aa72012-02-22 06:49:09 +00001735 RParen = ConsumeParen();
1736 Diag(DeclOut ? DeclOut->getLocation() : LParen,
1737 diag::err_expected_init_in_condition_lparen)
1738 << SourceRange(LParen, RParen);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001739 } else {
Richard Smith0635aa72012-02-22 06:49:09 +00001740 Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(),
1741 diag::err_expected_init_in_condition);
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001742 }
Richard Smith0635aa72012-02-22 06:49:09 +00001743
1744 if (!InitExpr.isInvalid())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001745 Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization,
Richard Smitha2c36462013-04-26 16:15:35 +00001746 DS.containsPlaceholderType());
Richard Smithdc7a4f52013-04-30 13:56:41 +00001747 else
1748 Actions.ActOnInitializerError(DeclOut);
Richard Smith0635aa72012-02-22 06:49:09 +00001749
Douglas Gregor586596f2010-05-06 17:25:47 +00001750 // FIXME: Build a reference to this declaration? Convert it to bool?
1751 // (This is currently handled by Sema).
Richard Smith483b9f32011-02-21 20:05:19 +00001752
1753 Actions.FinalizeDeclaration(DeclOut);
Douglas Gregor586596f2010-05-06 17:25:47 +00001754
Douglas Gregor99e9b4d2009-11-25 00:27:52 +00001755 return false;
Argyrios Kyrtzidis71b914b2008-09-09 20:38:47 +00001756}
1757
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001758/// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers.
1759/// This should only be called when the current token is known to be part of
1760/// simple-type-specifier.
1761///
1762/// simple-type-specifier:
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001763/// '::'[opt] nested-name-specifier[opt] type-name
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001764/// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO]
1765/// char
1766/// wchar_t
1767/// bool
1768/// short
1769/// int
1770/// long
1771/// signed
1772/// unsigned
1773/// float
1774/// double
1775/// void
1776/// [GNU] typeof-specifier
1777/// [C++0x] auto [TODO]
1778///
1779/// type-name:
1780/// class-name
1781/// enum-name
1782/// typedef-name
1783///
1784void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) {
1785 DS.SetRangeStart(Tok.getLocation());
1786 const char *PrevSpec;
John McCallfec54012009-08-03 20:12:06 +00001787 unsigned DiagID;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001788 SourceLocation Loc = Tok.getLocation();
Stephen Hines651f13c2014-04-23 16:59:28 -07001789 const clang::PrintingPolicy &Policy =
1790 Actions.getASTContext().getPrintingPolicy();
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001792 switch (Tok.getKind()) {
Chris Lattner55a7cef2009-01-05 00:13:00 +00001793 case tok::identifier: // foo::bar
1794 case tok::coloncolon: // ::foo::bar
David Blaikieb219cfc2011-09-23 05:06:16 +00001795 llvm_unreachable("Annotation token should already be formed!");
Mike Stump1eb44332009-09-09 15:08:12 +00001796 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00001797 llvm_unreachable("Not a simple-type-specifier token!");
Chris Lattner55a7cef2009-01-05 00:13:00 +00001798
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001799 // type-name
Chris Lattnerb31757b2009-01-06 05:06:21 +00001800 case tok::annot_typename: {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001801 if (getTypeAnnotation(Tok))
1802 DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID,
Stephen Hines651f13c2014-04-23 16:59:28 -07001803 getTypeAnnotation(Tok), Policy);
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001804 else
1805 DS.SetTypeSpecError();
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001806
1807 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1808 ConsumeToken();
1809
1810 // Objective-C supports syntax of the form 'id<proto1,proto2>' where 'id'
1811 // is a specific typedef and 'itf<proto1,proto2>' where 'itf' is an
1812 // Objective-C interface. If we don't have Objective-C or a '<', this is
1813 // just a normal reference to a typedef name.
David Blaikie4e4d0842012-03-11 07:00:24 +00001814 if (Tok.is(tok::less) && getLangOpts().ObjC1)
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001815 ParseObjCProtocolQualifiers(DS);
1816
Stephen Hines651f13c2014-04-23 16:59:28 -07001817 DS.Finish(Diags, PP, Policy);
Douglas Gregor9bd1d8d2010-10-21 23:17:00 +00001818 return;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001819 }
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001821 // builtin types
1822 case tok::kw_short:
Stephen Hines651f13c2014-04-23 16:59:28 -07001823 DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001824 break;
1825 case tok::kw_long:
Stephen Hines651f13c2014-04-23 16:59:28 -07001826 DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001827 break;
Francois Pichet338d7f72011-04-28 01:59:37 +00001828 case tok::kw___int64:
Stephen Hines651f13c2014-04-23 16:59:28 -07001829 DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy);
Francois Pichet338d7f72011-04-28 01:59:37 +00001830 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001831 case tok::kw_signed:
John McCallfec54012009-08-03 20:12:06 +00001832 DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001833 break;
1834 case tok::kw_unsigned:
John McCallfec54012009-08-03 20:12:06 +00001835 DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001836 break;
1837 case tok::kw_void:
Stephen Hines651f13c2014-04-23 16:59:28 -07001838 DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001839 break;
1840 case tok::kw_char:
Stephen Hines651f13c2014-04-23 16:59:28 -07001841 DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001842 break;
1843 case tok::kw_int:
Stephen Hines651f13c2014-04-23 16:59:28 -07001844 DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001845 break;
Richard Smith5a5a9712012-04-04 06:24:32 +00001846 case tok::kw___int128:
Stephen Hines651f13c2014-04-23 16:59:28 -07001847 DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy);
Richard Smith5a5a9712012-04-04 06:24:32 +00001848 break;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001849 case tok::kw_half:
Stephen Hines651f13c2014-04-23 16:59:28 -07001850 DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001851 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001852 case tok::kw_float:
Stephen Hines651f13c2014-04-23 16:59:28 -07001853 DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001854 break;
1855 case tok::kw_double:
Stephen Hines651f13c2014-04-23 16:59:28 -07001856 DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001857 break;
1858 case tok::kw_wchar_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001859 DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001860 break;
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001861 case tok::kw_char16_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001862 DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001863 break;
1864 case tok::kw_char32_t:
Stephen Hines651f13c2014-04-23 16:59:28 -07001865 DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy);
Alisdair Meredithf5c209d2009-07-14 06:30:34 +00001866 break;
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001867 case tok::kw_bool:
Stephen Hines651f13c2014-04-23 16:59:28 -07001868 DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001869 break;
David Blaikie5e089fe2012-01-24 05:47:35 +00001870 case tok::annot_decltype:
1871 case tok::kw_decltype:
1872 DS.SetRangeEnd(ParseDecltypeSpecifier(DS));
Stephen Hines651f13c2014-04-23 16:59:28 -07001873 return DS.Finish(Diags, PP, Policy);
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001875 // GNU typeof support.
1876 case tok::kw_typeof:
1877 ParseTypeofSpecifier(DS);
Stephen Hines651f13c2014-04-23 16:59:28 -07001878 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001879 return;
1880 }
Chris Lattnerb31757b2009-01-06 05:06:21 +00001881 if (Tok.is(tok::annot_typename))
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00001882 DS.SetRangeEnd(Tok.getAnnotationEndLoc());
1883 else
1884 DS.SetRangeEnd(Tok.getLocation());
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001885 ConsumeToken();
Stephen Hines651f13c2014-04-23 16:59:28 -07001886 DS.Finish(Diags, PP, Policy);
Argyrios Kyrtzidis987a14b2008-08-22 15:38:55 +00001887}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001888
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001889/// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++
1890/// [dcl.name]), which is a non-empty sequence of type-specifiers,
1891/// e.g., "const short int". Note that the DeclSpec is *not* finished
1892/// by parsing the type-specifier-seq, because these sequences are
1893/// typically followed by some form of declarator. Returns true and
1894/// emits diagnostics if this is not a type-specifier-seq, false
1895/// otherwise.
1896///
1897/// type-specifier-seq: [C++ 8.1]
1898/// type-specifier type-specifier-seq[opt]
1899///
1900bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) {
Richard Smith69730c12012-03-12 07:56:15 +00001901 ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier);
Stephen Hines651f13c2014-04-23 16:59:28 -07001902 DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001903 return false;
1904}
1905
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001906/// \brief Finish parsing a C++ unqualified-id that is a template-id of
1907/// some form.
1908///
1909/// This routine is invoked when a '<' is encountered after an identifier or
1910/// operator-function-id is parsed by \c ParseUnqualifiedId() to determine
1911/// whether the unqualified-id is actually a template-id. This routine will
1912/// then parse the template arguments and form the appropriate template-id to
1913/// return to the caller.
1914///
1915/// \param SS the nested-name-specifier that precedes this template-id, if
1916/// we're actually parsing a qualified-id.
1917///
1918/// \param Name for constructor and destructor names, this is the actual
1919/// identifier that may be a template-name.
1920///
1921/// \param NameLoc the location of the class-name in a constructor or
1922/// destructor.
1923///
1924/// \param EnteringContext whether we're entering the scope of the
1925/// nested-name-specifier.
1926///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00001927/// \param ObjectType if this unqualified-id occurs within a member access
1928/// expression, the type of the base object whose member is being accessed.
1929///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001930/// \param Id as input, describes the template-name or operator-function-id
1931/// that precedes the '<'. If template arguments were parsed successfully,
1932/// will be updated with the template-id.
1933///
Douglas Gregord4dca082010-02-24 18:44:31 +00001934/// \param AssumeTemplateId When true, this routine will assume that the name
1935/// refers to a template without performing name lookup to verify.
1936///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001937/// \returns true if a parse error occurred, false otherwise.
1938bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001939 SourceLocation TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001940 IdentifierInfo *Name,
1941 SourceLocation NameLoc,
1942 bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00001943 ParsedType ObjectType,
Douglas Gregord4dca082010-02-24 18:44:31 +00001944 UnqualifiedId &Id,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001945 bool AssumeTemplateId) {
Douglas Gregor0278e122010-05-05 05:58:24 +00001946 assert((AssumeTemplateId || Tok.is(tok::less)) &&
1947 "Expected '<' to finish parsing a template-id");
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001948
1949 TemplateTy Template;
1950 TemplateNameKind TNK = TNK_Non_template;
1951 switch (Id.getKind()) {
1952 case UnqualifiedId::IK_Identifier:
Douglas Gregor014e88d2009-11-03 23:16:33 +00001953 case UnqualifiedId::IK_OperatorFunctionId:
Sean Hunte6252d12009-11-28 08:58:14 +00001954 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregord4dca082010-02-24 18:44:31 +00001955 if (AssumeTemplateId) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001956 TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001957 Id, ObjectType, EnteringContext,
1958 Template);
1959 if (TNK == TNK_Non_template)
1960 return true;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001961 } else {
1962 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001963 TNK = Actions.isTemplateName(getCurScope(), SS,
1964 TemplateKWLoc.isValid(), Id,
1965 ObjectType, EnteringContext, Template,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001966 MemberOfUnknownSpecialization);
1967
1968 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization &&
1969 ObjectType && IsTemplateArgumentList()) {
1970 // We have something like t->getAs<T>(), where getAs is a
1971 // member of an unknown specialization. However, this will only
1972 // parse correctly as a template, so suggest the keyword 'template'
1973 // before 'getAs' and treat this as a dependent template name.
1974 std::string Name;
1975 if (Id.getKind() == UnqualifiedId::IK_Identifier)
1976 Name = Id.Identifier->getName();
1977 else {
1978 Name = "operator ";
1979 if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId)
1980 Name += getOperatorSpelling(Id.OperatorFunctionId.Operator);
1981 else
1982 Name += Id.Identifier->getName();
1983 }
1984 Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword)
1985 << Name
1986 << FixItHint::CreateInsertion(Id.StartLocation, "template ");
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001987 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
1988 SS, TemplateKWLoc, Id,
1989 ObjectType, EnteringContext,
1990 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00001991 if (TNK == TNK_Non_template)
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001992 return true;
1993 }
1994 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00001995 break;
1996
Douglas Gregor014e88d2009-11-03 23:16:33 +00001997 case UnqualifiedId::IK_ConstructorName: {
1998 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001999 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002000 TemplateName.setIdentifier(Name, NameLoc);
Abramo Bagnara7c153532010-08-06 12:11:11 +00002001 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2002 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002003 EnteringContext, Template,
2004 MemberOfUnknownSpecialization);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002005 break;
2006 }
2007
Douglas Gregor014e88d2009-11-03 23:16:33 +00002008 case UnqualifiedId::IK_DestructorName: {
2009 UnqualifiedId TemplateName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002010 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002011 TemplateName.setIdentifier(Name, NameLoc);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002012 if (ObjectType) {
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002013 TNK = Actions.ActOnDependentTemplateName(getCurScope(),
2014 SS, TemplateKWLoc, TemplateName,
2015 ObjectType, EnteringContext,
2016 Template);
Douglas Gregord6ab2322010-06-16 23:00:59 +00002017 if (TNK == TNK_Non_template)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002018 return true;
2019 } else {
Abramo Bagnara7c153532010-08-06 12:11:11 +00002020 TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(),
2021 TemplateName, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00002022 EnteringContext, Template,
2023 MemberOfUnknownSpecialization);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002024
John McCallb3d87482010-08-24 05:47:05 +00002025 if (TNK == TNK_Non_template && !Id.DestructorName.get()) {
Douglas Gregor124b8782010-02-16 19:09:40 +00002026 Diag(NameLoc, diag::err_destructor_template_id)
2027 << Name << SS.getRange();
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002028 return true;
2029 }
2030 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002031 break;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002032 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002033
2034 default:
2035 return false;
2036 }
2037
2038 if (TNK == TNK_Non_template)
2039 return false;
2040
2041 // Parse the enclosed template argument list.
2042 SourceLocation LAngleLoc, RAngleLoc;
2043 TemplateArgList TemplateArgs;
Douglas Gregor0278e122010-05-05 05:58:24 +00002044 if (Tok.is(tok::less) &&
2045 ParseTemplateIdAfterTemplateName(Template, Id.StartLocation,
Douglas Gregor059101f2011-03-02 00:47:37 +00002046 SS, true, LAngleLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002047 TemplateArgs,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002048 RAngleLoc))
2049 return true;
2050
2051 if (Id.getKind() == UnqualifiedId::IK_Identifier ||
Sean Hunte6252d12009-11-28 08:58:14 +00002052 Id.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2053 Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002054 // Form a parsed representation of the template-id to be stored in the
2055 // UnqualifiedId.
2056 TemplateIdAnnotation *TemplateId
Benjamin Kramer13bb7012012-04-14 12:14:03 +00002057 = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002058
Stephen Hines651f13c2014-04-23 16:59:28 -07002059 // FIXME: Store name for literal operator too.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002060 if (Id.getKind() == UnqualifiedId::IK_Identifier) {
2061 TemplateId->Name = Id.Identifier;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002062 TemplateId->Operator = OO_None;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002063 TemplateId->TemplateNameLoc = Id.StartLocation;
2064 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002065 TemplateId->Name = nullptr;
Douglas Gregor014e88d2009-11-03 23:16:33 +00002066 TemplateId->Operator = Id.OperatorFunctionId.Operator;
2067 TemplateId->TemplateNameLoc = Id.StartLocation;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002068 }
2069
Douglas Gregor059101f2011-03-02 00:47:37 +00002070 TemplateId->SS = SS;
Benjamin Kramer2b28bf12012-02-19 23:37:39 +00002071 TemplateId->TemplateKWLoc = TemplateKWLoc;
John McCall2b5289b2010-08-23 07:28:44 +00002072 TemplateId->Template = Template;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002073 TemplateId->Kind = TNK;
2074 TemplateId->LAngleLoc = LAngleLoc;
2075 TemplateId->RAngleLoc = RAngleLoc;
Douglas Gregor314b97f2009-11-10 19:49:08 +00002076 ParsedTemplateArgument *Args = TemplateId->getTemplateArgs();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002077 for (unsigned Arg = 0, ArgEnd = TemplateArgs.size();
Douglas Gregor314b97f2009-11-10 19:49:08 +00002078 Arg != ArgEnd; ++Arg)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002079 Args[Arg] = TemplateArgs[Arg];
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002080
2081 Id.setTemplateId(TemplateId);
2082 return false;
2083 }
2084
2085 // Bundle the template arguments together.
Benjamin Kramer5354e772012-08-23 23:38:35 +00002086 ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs);
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002087
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002088 // Constructor and destructor names.
John McCallf312b1e2010-08-26 23:41:50 +00002089 TypeResult Type
Abramo Bagnara55d23c92012-02-06 14:41:24 +00002090 = Actions.ActOnTemplateIdType(SS, TemplateKWLoc,
2091 Template, NameLoc,
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002092 LAngleLoc, TemplateArgsPtr, RAngleLoc,
2093 /*IsCtorOrDtorName=*/true);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002094 if (Type.isInvalid())
2095 return true;
2096
2097 if (Id.getKind() == UnqualifiedId::IK_ConstructorName)
2098 Id.setConstructorName(Type.get(), NameLoc, RAngleLoc);
2099 else
2100 Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc);
2101
2102 return false;
2103}
2104
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002105/// \brief Parse an operator-function-id or conversion-function-id as part
2106/// of a C++ unqualified-id.
2107///
2108/// This routine is responsible only for parsing the operator-function-id or
2109/// conversion-function-id; it does not handle template arguments in any way.
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002110///
2111/// \code
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002112/// operator-function-id: [C++ 13.5]
2113/// 'operator' operator
2114///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002115/// operator: one of
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002116/// new delete new[] delete[]
2117/// + - * / % ^ & | ~
2118/// ! = < > += -= *= /= %=
2119/// ^= &= |= << >> >>= <<= == !=
2120/// <= >= && || ++ -- , ->* ->
2121/// () []
2122///
2123/// conversion-function-id: [C++ 12.3.2]
2124/// operator conversion-type-id
2125///
2126/// conversion-type-id:
2127/// type-specifier-seq conversion-declarator[opt]
2128///
2129/// conversion-declarator:
2130/// ptr-operator conversion-declarator[opt]
2131/// \endcode
2132///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002133/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002134/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2135///
2136/// \param EnteringContext whether we are entering the scope of the
2137/// nested-name-specifier.
2138///
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002139/// \param ObjectType if this unqualified-id occurs within a member access
2140/// expression, the type of the base object whose member is being accessed.
2141///
2142/// \param Result on a successful parse, contains the parsed unqualified-id.
2143///
2144/// \returns true if parsing fails, false otherwise.
2145bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext,
John McCallb3d87482010-08-24 05:47:05 +00002146 ParsedType ObjectType,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002147 UnqualifiedId &Result) {
2148 assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword");
2149
2150 // Consume the 'operator' keyword.
2151 SourceLocation KeywordLoc = ConsumeToken();
2152
2153 // Determine what kind of operator name we have.
2154 unsigned SymbolIdx = 0;
2155 SourceLocation SymbolLocations[3];
2156 OverloadedOperatorKind Op = OO_None;
2157 switch (Tok.getKind()) {
2158 case tok::kw_new:
2159 case tok::kw_delete: {
2160 bool isNew = Tok.getKind() == tok::kw_new;
2161 // Consume the 'new' or 'delete'.
2162 SymbolLocations[SymbolIdx++] = ConsumeToken();
Richard Smith6ee326a2012-04-10 01:32:12 +00002163 // Check for array new/delete.
2164 if (Tok.is(tok::l_square) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00002165 (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002166 // Consume the '[' and ']'.
2167 BalancedDelimiterTracker T(*this, tok::l_square);
2168 T.consumeOpen();
2169 T.consumeClose();
2170 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002171 return true;
2172
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002173 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2174 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002175 Op = isNew? OO_Array_New : OO_Array_Delete;
2176 } else {
2177 Op = isNew? OO_New : OO_Delete;
2178 }
2179 break;
2180 }
2181
2182#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2183 case tok::Token: \
2184 SymbolLocations[SymbolIdx++] = ConsumeToken(); \
2185 Op = OO_##Name; \
2186 break;
2187#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2188#include "clang/Basic/OperatorKinds.def"
2189
2190 case tok::l_paren: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002191 // Consume the '(' and ')'.
2192 BalancedDelimiterTracker T(*this, tok::l_paren);
2193 T.consumeOpen();
2194 T.consumeClose();
2195 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002196 return true;
2197
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002198 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2199 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002200 Op = OO_Call;
2201 break;
2202 }
2203
2204 case tok::l_square: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002205 // Consume the '[' and ']'.
2206 BalancedDelimiterTracker T(*this, tok::l_square);
2207 T.consumeOpen();
2208 T.consumeClose();
2209 if (T.getCloseLocation().isInvalid())
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002210 return true;
2211
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002212 SymbolLocations[SymbolIdx++] = T.getOpenLocation();
2213 SymbolLocations[SymbolIdx++] = T.getCloseLocation();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002214 Op = OO_Subscript;
2215 break;
2216 }
2217
2218 case tok::code_completion: {
2219 // Code completion for the operator name.
Douglas Gregor23c94db2010-07-02 17:43:08 +00002220 Actions.CodeCompleteOperatorName(getCurScope());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +00002221 cutOffParsing();
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002222 // Don't try to parse any further.
2223 return true;
2224 }
2225
2226 default:
2227 break;
2228 }
2229
2230 if (Op != OO_None) {
2231 // We have parsed an operator-function-id.
2232 Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations);
2233 return false;
2234 }
Sean Hunt0486d742009-11-28 04:44:28 +00002235
2236 // Parse a literal-operator-id.
2237 //
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002238 // literal-operator-id: C++11 [over.literal]
2239 // operator string-literal identifier
2240 // operator user-defined-string-literal
Sean Hunt0486d742009-11-28 04:44:28 +00002241
Richard Smith80ad52f2013-01-02 11:42:31 +00002242 if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) {
Richard Smith7fe62082011-10-15 05:09:34 +00002243 Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator);
Sean Hunt0486d742009-11-28 04:44:28 +00002244
Richard Smith33762772012-03-08 23:06:02 +00002245 SourceLocation DiagLoc;
2246 unsigned DiagId = 0;
2247
2248 // We're past translation phase 6, so perform string literal concatenation
2249 // before checking for "".
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002250 SmallVector<Token, 4> Toks;
2251 SmallVector<SourceLocation, 4> TokLocs;
Richard Smith33762772012-03-08 23:06:02 +00002252 while (isTokenStringLiteral()) {
2253 if (!Tok.is(tok::string_literal) && !DiagId) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002254 // C++11 [over.literal]p1:
2255 // The string-literal or user-defined-string-literal in a
2256 // literal-operator-id shall have no encoding-prefix [...].
Richard Smith33762772012-03-08 23:06:02 +00002257 DiagLoc = Tok.getLocation();
2258 DiagId = diag::err_literal_operator_string_prefix;
2259 }
2260 Toks.push_back(Tok);
2261 TokLocs.push_back(ConsumeStringToken());
2262 }
2263
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002264 StringLiteralParser Literal(Toks, PP);
Richard Smith33762772012-03-08 23:06:02 +00002265 if (Literal.hadError)
2266 return true;
2267
2268 // Grab the literal operator's suffix, which will be either the next token
2269 // or a ud-suffix from the string literal.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002270 IdentifierInfo *II = nullptr;
Richard Smith33762772012-03-08 23:06:02 +00002271 SourceLocation SuffixLoc;
2272 if (!Literal.getUDSuffix().empty()) {
2273 II = &PP.getIdentifierTable().get(Literal.getUDSuffix());
2274 SuffixLoc =
2275 Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()],
2276 Literal.getUDSuffixOffset(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002277 PP.getSourceManager(), getLangOpts());
Richard Smith33762772012-03-08 23:06:02 +00002278 } else if (Tok.is(tok::identifier)) {
2279 II = Tok.getIdentifierInfo();
2280 SuffixLoc = ConsumeToken();
2281 TokLocs.push_back(SuffixLoc);
2282 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07002283 Diag(Tok.getLocation(), diag::err_expected) << tok::identifier;
Sean Hunt0486d742009-11-28 04:44:28 +00002284 return true;
2285 }
2286
Richard Smith33762772012-03-08 23:06:02 +00002287 // The string literal must be empty.
2288 if (!Literal.GetString().empty() || Literal.Pascal) {
Richard Smithaa9a8ce2012-10-20 08:41:10 +00002289 // C++11 [over.literal]p1:
2290 // The string-literal or user-defined-string-literal in a
2291 // literal-operator-id shall [...] contain no characters
2292 // other than the implicit terminating '\0'.
Richard Smith33762772012-03-08 23:06:02 +00002293 DiagLoc = TokLocs.front();
2294 DiagId = diag::err_literal_operator_string_not_empty;
2295 }
2296
2297 if (DiagId) {
2298 // This isn't a valid literal-operator-id, but we think we know
2299 // what the user meant. Tell them what they should have written.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002300 SmallString<32> Str;
Richard Smith33762772012-03-08 23:06:02 +00002301 Str += "\"\" ";
2302 Str += II->getName();
2303 Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement(
2304 SourceRange(TokLocs.front(), TokLocs.back()), Str);
2305 }
2306
2307 Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -07002308
2309 return Actions.checkLiteralOperatorId(SS, Result);
Sean Hunt0486d742009-11-28 04:44:28 +00002310 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002311
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002312 // Parse a conversion-function-id.
2313 //
2314 // conversion-function-id: [C++ 12.3.2]
2315 // operator conversion-type-id
2316 //
2317 // conversion-type-id:
2318 // type-specifier-seq conversion-declarator[opt]
2319 //
2320 // conversion-declarator:
2321 // ptr-operator conversion-declarator[opt]
2322
2323 // Parse the type-specifier-seq.
John McCall0b7e6782011-03-24 11:26:52 +00002324 DeclSpec DS(AttrFactory);
Douglas Gregorf6e6fc82009-11-20 22:03:38 +00002325 if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType?
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002326 return true;
2327
2328 // Parse the conversion-declarator, which is merely a sequence of
2329 // ptr-operators.
Richard Smith14f78f42013-05-04 01:26:46 +00002330 Declarator D(DS, Declarator::ConversionIdContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002331 ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr);
2332
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002333 // Finish up the type.
John McCallf312b1e2010-08-26 23:41:50 +00002334 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D);
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002335 if (Ty.isInvalid())
2336 return true;
2337
2338 // Note that this is a conversion-function-id.
2339 Result.setConversionFunctionId(KeywordLoc, Ty.get(),
2340 D.getSourceRange().getEnd());
2341 return false;
2342}
2343
2344/// \brief Parse a C++ unqualified-id (or a C identifier), which describes the
2345/// name of an entity.
2346///
2347/// \code
2348/// unqualified-id: [C++ expr.prim.general]
2349/// identifier
2350/// operator-function-id
2351/// conversion-function-id
2352/// [C++0x] literal-operator-id [TODO]
2353/// ~ class-name
2354/// template-id
2355///
2356/// \endcode
2357///
Dmitri Gribenko1ddbd892012-08-24 00:01:24 +00002358/// \param SS The nested-name-specifier that preceded this unqualified-id. If
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002359/// non-empty, then we are parsing the unqualified-id of a qualified-id.
2360///
2361/// \param EnteringContext whether we are entering the scope of the
2362/// nested-name-specifier.
2363///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002364/// \param AllowDestructorName whether we allow parsing of a destructor name.
2365///
2366/// \param AllowConstructorName whether we allow parsing a constructor name.
2367///
Douglas Gregor46df8cc2009-11-03 21:24:04 +00002368/// \param ObjectType if this unqualified-id occurs within a member access
2369/// expression, the type of the base object whose member is being accessed.
2370///
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002371/// \param Result on a successful parse, contains the parsed unqualified-id.
2372///
2373/// \returns true if parsing fails, false otherwise.
2374bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext,
2375 bool AllowDestructorName,
2376 bool AllowConstructorName,
John McCallb3d87482010-08-24 05:47:05 +00002377 ParsedType ObjectType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002378 SourceLocation& TemplateKWLoc,
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002379 UnqualifiedId &Result) {
Douglas Gregor0278e122010-05-05 05:58:24 +00002380
2381 // Handle 'A::template B'. This is for template-ids which have not
2382 // already been annotated by ParseOptionalCXXScopeSpecifier().
2383 bool TemplateSpecified = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00002384 if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002385 (ObjectType || SS.isSet())) {
2386 TemplateSpecified = true;
2387 TemplateKWLoc = ConsumeToken();
2388 }
2389
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002390 // unqualified-id:
2391 // identifier
2392 // template-id (when it hasn't already been annotated)
2393 if (Tok.is(tok::identifier)) {
2394 // Consume the identifier.
2395 IdentifierInfo *Id = Tok.getIdentifierInfo();
2396 SourceLocation IdLoc = ConsumeToken();
2397
David Blaikie4e4d0842012-03-11 07:00:24 +00002398 if (!getLangOpts().CPlusPlus) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002399 // If we're not in C++, only identifiers matter. Record the
2400 // identifier and return.
2401 Result.setIdentifier(Id, IdLoc);
2402 return false;
2403 }
2404
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002405 if (AllowConstructorName &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002406 Actions.isCurrentClassName(*Id, getCurScope(), &SS)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002407 // We have parsed a constructor name.
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002408 ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(),
2409 &SS, false, false,
2410 ParsedType(),
2411 /*IsCtorOrDtorName=*/true,
2412 /*NonTrivialTypeSourceInfo=*/true);
2413 Result.setConstructorName(Ty, IdLoc, IdLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002414 } else {
2415 // We have parsed an identifier.
2416 Result.setIdentifier(Id, IdLoc);
2417 }
2418
2419 // If the next token is a '<', we may have a template.
Douglas Gregor0278e122010-05-05 05:58:24 +00002420 if (TemplateSpecified || Tok.is(tok::less))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002421 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc,
2422 EnteringContext, ObjectType,
2423 Result, TemplateSpecified);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002424
2425 return false;
2426 }
2427
2428 // unqualified-id:
2429 // template-id (already parsed and annotated)
2430 if (Tok.is(tok::annot_template_id)) {
Argyrios Kyrtzidis25a76762011-06-22 06:09:49 +00002431 TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002432
2433 // If the template-name names the current class, then this is a constructor
2434 if (AllowConstructorName && TemplateId->Name &&
Douglas Gregor23c94db2010-07-02 17:43:08 +00002435 Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) {
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002436 if (SS.isSet()) {
2437 // C++ [class.qual]p2 specifies that a qualified template-name
2438 // is taken as the constructor name where a constructor can be
2439 // declared. Thus, the template arguments are extraneous, so
2440 // complain about them and remove them entirely.
2441 Diag(TemplateId->TemplateNameLoc,
2442 diag::err_out_of_line_constructor_template_id)
2443 << TemplateId->Name
Douglas Gregor849b2432010-03-31 17:46:05 +00002444 << FixItHint::CreateRemoval(
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002445 SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc));
Abramo Bagnarafad03b72012-01-27 08:46:19 +00002446 ParsedType Ty = Actions.getTypeName(*TemplateId->Name,
2447 TemplateId->TemplateNameLoc,
2448 getCurScope(),
2449 &SS, false, false,
2450 ParsedType(),
2451 /*IsCtorOrDtorName=*/true,
2452 /*NontrivialTypeSourceInfo=*/true);
2453 Result.setConstructorName(Ty, TemplateId->TemplateNameLoc,
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002454 TemplateId->RAngleLoc);
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002455 ConsumeToken();
2456 return false;
2457 }
2458
2459 Result.setConstructorTemplateId(TemplateId);
2460 ConsumeToken();
2461 return false;
2462 }
2463
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002464 // We have already parsed a template-id; consume the annotation token as
2465 // our unqualified-id.
Douglas Gregor0efc2c12010-01-13 17:31:36 +00002466 Result.setTemplateId(TemplateId);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002467 TemplateKWLoc = TemplateId->TemplateKWLoc;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002468 ConsumeToken();
2469 return false;
2470 }
2471
2472 // unqualified-id:
2473 // operator-function-id
2474 // conversion-function-id
2475 if (Tok.is(tok::kw_operator)) {
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002476 if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result))
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002477 return true;
2478
Sean Hunte6252d12009-11-28 08:58:14 +00002479 // If we have an operator-function-id or a literal-operator-id and the next
2480 // token is a '<', we may have a
Douglas Gregorca1bdd72009-11-04 00:56:37 +00002481 //
2482 // template-id:
2483 // operator-function-id < template-argument-list[opt] >
Sean Hunte6252d12009-11-28 08:58:14 +00002484 if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId ||
2485 Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) &&
Douglas Gregor0278e122010-05-05 05:58:24 +00002486 (TemplateSpecified || Tok.is(tok::less)))
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002487 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002488 nullptr, SourceLocation(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002489 EnteringContext, ObjectType,
2490 Result, TemplateSpecified);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002491
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002492 return false;
2493 }
2494
David Blaikie4e4d0842012-03-11 07:00:24 +00002495 if (getLangOpts().CPlusPlus &&
Douglas Gregorb862b8f2010-01-11 23:29:10 +00002496 (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) {
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002497 // C++ [expr.unary.op]p10:
2498 // There is an ambiguity in the unary-expression ~X(), where X is a
2499 // class-name. The ambiguity is resolved in favor of treating ~ as a
2500 // unary complement rather than treating ~X as referring to a destructor.
2501
2502 // Parse the '~'.
2503 SourceLocation TildeLoc = ConsumeToken();
David Blaikie53a75c02011-12-08 16:13:53 +00002504
2505 if (SS.isEmpty() && Tok.is(tok::kw_decltype)) {
2506 DeclSpec DS(AttrFactory);
2507 SourceLocation EndLoc = ParseDecltypeSpecifier(DS);
2508 if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) {
2509 Result.setDestructorName(TildeLoc, Type, EndLoc);
2510 return false;
2511 }
2512 return true;
2513 }
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002514
2515 // Parse the class-name.
2516 if (Tok.isNot(tok::identifier)) {
Douglas Gregor124b8782010-02-16 19:09:40 +00002517 Diag(Tok, diag::err_destructor_tilde_identifier);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002518 return true;
2519 }
2520
Stephen Hines176edba2014-12-01 14:53:08 -08002521 // If the user wrote ~T::T, correct it to T::~T.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002522 DeclaratorScopeObj DeclScopeObj(*this, SS);
Stephen Hines176edba2014-12-01 14:53:08 -08002523 if (!TemplateSpecified && NextToken().is(tok::coloncolon)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002524 // Don't let ParseOptionalCXXScopeSpecifier() "correct"
2525 // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`,
2526 // it will confuse this recovery logic.
2527 ColonProtectionRAIIObject ColonRAII(*this, false);
2528
Stephen Hines176edba2014-12-01 14:53:08 -08002529 if (SS.isSet()) {
2530 AnnotateScopeToken(SS, /*NewAnnotation*/true);
2531 SS.clear();
2532 }
2533 if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext))
2534 return true;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002535 if (SS.isNotEmpty())
2536 ObjectType = ParsedType();
2537 if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) ||
2538 SS.isInvalid()) {
Stephen Hines176edba2014-12-01 14:53:08 -08002539 Diag(TildeLoc, diag::err_destructor_tilde_scope);
2540 return true;
2541 }
2542
2543 // Recover as if the tilde had been written before the identifier.
2544 Diag(TildeLoc, diag::err_destructor_tilde_scope)
2545 << FixItHint::CreateRemoval(TildeLoc)
2546 << FixItHint::CreateInsertion(Tok.getLocation(), "~");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002547
2548 // Temporarily enter the scope for the rest of this function.
2549 if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS))
2550 DeclScopeObj.EnterDeclaratorScope();
Stephen Hines176edba2014-12-01 14:53:08 -08002551 }
2552
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002553 // Parse the class-name (or template-name in a simple-template-id).
2554 IdentifierInfo *ClassName = Tok.getIdentifierInfo();
2555 SourceLocation ClassNameLoc = ConsumeToken();
Stephen Hines176edba2014-12-01 14:53:08 -08002556
Douglas Gregor0278e122010-05-05 05:58:24 +00002557 if (TemplateSpecified || Tok.is(tok::less)) {
John McCallb3d87482010-08-24 05:47:05 +00002558 Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc);
Abramo Bagnarae4b92762012-01-27 09:46:47 +00002559 return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc,
2560 ClassName, ClassNameLoc,
2561 EnteringContext, ObjectType,
2562 Result, TemplateSpecified);
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002563 }
Stephen Hines176edba2014-12-01 14:53:08 -08002564
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002565 // Note that this is a destructor name.
John McCallb3d87482010-08-24 05:47:05 +00002566 ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName,
2567 ClassNameLoc, getCurScope(),
2568 SS, ObjectType,
2569 EnteringContext);
Douglas Gregor124b8782010-02-16 19:09:40 +00002570 if (!Ty)
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002571 return true;
Douglas Gregor124b8782010-02-16 19:09:40 +00002572
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002573 Result.setDestructorName(TildeLoc, Ty, ClassNameLoc);
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002574 return false;
2575 }
2576
Douglas Gregor2d1c2142009-11-03 19:44:04 +00002577 Diag(Tok, diag::err_expected_unqualified_id)
David Blaikie4e4d0842012-03-11 07:00:24 +00002578 << getLangOpts().CPlusPlus;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00002579 return true;
2580}
2581
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002582/// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate
2583/// memory in a typesafe manner and call constructors.
Mike Stump1eb44332009-09-09 15:08:12 +00002584///
Chris Lattner59232d32009-01-04 21:25:24 +00002585/// This method is called to parse the new expression after the optional :: has
2586/// been already parsed. If the :: was present, "UseGlobal" is true and "Start"
2587/// is its location. Otherwise, "Start" is the location of the 'new' token.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002588///
2589/// new-expression:
2590/// '::'[opt] 'new' new-placement[opt] new-type-id
2591/// new-initializer[opt]
2592/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2593/// new-initializer[opt]
2594///
2595/// new-placement:
2596/// '(' expression-list ')'
2597///
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002598/// new-type-id:
2599/// type-specifier-seq new-declarator[opt]
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002600/// [GNU] attributes type-specifier-seq new-declarator[opt]
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002601///
2602/// new-declarator:
2603/// ptr-operator new-declarator[opt]
2604/// direct-new-declarator
2605///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002606/// new-initializer:
2607/// '(' expression-list[opt] ')'
Sebastian Redldbef1bb2011-06-05 12:23:16 +00002608/// [C++0x] braced-init-list
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002609///
John McCall60d7b3a2010-08-24 06:29:42 +00002610ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002611Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) {
2612 assert(Tok.is(tok::kw_new) && "expected 'new' token");
2613 ConsumeToken(); // Consume 'new'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002614
2615 // A '(' now can be a new-placement or the '(' wrapping the type-id in the
2616 // second form of new-expression. It can't be a new-type-id.
2617
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002618 ExprVector PlacementArgs;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002619 SourceLocation PlacementLParen, PlacementRParen;
2620
Douglas Gregor4bd40312010-07-13 15:54:32 +00002621 SourceRange TypeIdParens;
John McCall0b7e6782011-03-24 11:26:52 +00002622 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0b8c98f2011-06-28 03:01:23 +00002623 Declarator DeclaratorInfo(DS, Declarator::CXXNewContext);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002624 if (Tok.is(tok::l_paren)) {
2625 // If it turns out to be a placement, we change the type location.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002626 BalancedDelimiterTracker T(*this, tok::l_paren);
2627 T.consumeOpen();
2628 PlacementLParen = T.getOpenLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002629 if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002630 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002631 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002632 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002633
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002634 T.consumeClose();
2635 PlacementRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002636 if (PlacementRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002637 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002638 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002639 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002640
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002641 if (PlacementArgs.empty()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002642 // Reset the placement locations. There was no placement.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002643 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002644 PlacementLParen = PlacementRParen = SourceLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002645 } else {
2646 // We still need the type.
2647 if (Tok.is(tok::l_paren)) {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002648 BalancedDelimiterTracker T(*this, tok::l_paren);
2649 T.consumeOpen();
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002650 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002651 ParseSpecifierQualifierList(DS);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002652 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002653 ParseDeclarator(DeclaratorInfo);
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002654 T.consumeClose();
2655 TypeIdParens = T.getRange();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002656 } else {
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002657 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002658 if (ParseCXXTypeSpecifierSeq(DS))
2659 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002660 else {
2661 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002662 ParseDeclaratorInternal(DeclaratorInfo,
2663 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002664 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002665 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002666 }
2667 } else {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002668 // A new-type-id is a simplified type-id, where essentially the
2669 // direct-declarator is replaced by a direct-new-declarator.
Douglas Gregor893e1cc2011-04-15 19:40:02 +00002670 MaybeParseGNUAttributes(DeclaratorInfo);
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002671 if (ParseCXXTypeSpecifierSeq(DS))
2672 DeclaratorInfo.setInvalidType(true);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002673 else {
2674 DeclaratorInfo.SetSourceRange(DS.getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002675 ParseDeclaratorInternal(DeclaratorInfo,
2676 &Parser::ParseDirectNewDeclarator);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002677 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002678 }
Chris Lattnereaaebc72009-04-25 08:06:05 +00002679 if (DeclaratorInfo.isInvalidType()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002680 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002681 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002682 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002683
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002684 ExprResult Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002685
2686 if (Tok.is(tok::l_paren)) {
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002687 SourceLocation ConstructorLParen, ConstructorRParen;
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00002688 ExprVector ConstructorArgs;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002689 BalancedDelimiterTracker T(*this, tok::l_paren);
2690 T.consumeOpen();
2691 ConstructorLParen = T.getOpenLocation();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002692 if (Tok.isNot(tok::r_paren)) {
2693 CommaLocsTy CommaLocs;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002694 if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] {
2695 ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(),
2696 DeclaratorInfo).get();
2697 Actions.CodeCompleteConstructor(getCurScope(),
2698 TypeRep.get()->getCanonicalTypeInternal(),
2699 DeclaratorInfo.getLocEnd(),
2700 ConstructorArgs);
2701 })) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002702 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002703 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002704 }
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002705 }
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002706 T.consumeClose();
2707 ConstructorRParen = T.getCloseLocation();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002708 if (ConstructorRParen.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002709 SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch);
Sebastian Redl20df9b72008-12-11 22:51:44 +00002710 return ExprError();
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002711 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002712 Initializer = Actions.ActOnParenListExpr(ConstructorLParen,
2713 ConstructorRParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002714 ConstructorArgs);
Richard Smith80ad52f2013-01-02 11:42:31 +00002715 } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) {
Richard Smith7fe62082011-10-15 05:09:34 +00002716 Diag(Tok.getLocation(),
2717 diag::warn_cxx98_compat_generalized_initializer_lists);
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002718 Initializer = ParseBraceInitializer();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002719 }
Sebastian Redl2aed8b82012-02-16 12:22:20 +00002720 if (Initializer.isInvalid())
2721 return Initializer;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002722
Sebastian Redlf53597f2009-03-15 17:47:39 +00002723 return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen,
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002724 PlacementArgs, PlacementRParen,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002725 TypeIdParens, DeclaratorInfo, Initializer.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002726}
2727
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002728/// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be
2729/// passed to ParseDeclaratorInternal.
2730///
2731/// direct-new-declarator:
2732/// '[' expression ']'
2733/// direct-new-declarator '[' constant-expression ']'
2734///
Chris Lattner59232d32009-01-04 21:25:24 +00002735void Parser::ParseDirectNewDeclarator(Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002736 // Parse the array dimensions.
2737 bool first = true;
2738 while (Tok.is(tok::l_square)) {
Richard Smith6ee326a2012-04-10 01:32:12 +00002739 // An array-size expression can't start with a lambda.
2740 if (CheckProhibitedCXX11Attribute())
2741 continue;
2742
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002743 BalancedDelimiterTracker T(*this, tok::l_square);
2744 T.consumeOpen();
2745
John McCall60d7b3a2010-08-24 06:29:42 +00002746 ExprResult Size(first ? ParseExpression()
Sebastian Redl2f7ece72008-12-11 21:36:32 +00002747 : ParseConstantExpression());
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002748 if (Size.isInvalid()) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002749 // Recover
Alexey Bataev8fe24752013-11-18 08:17:37 +00002750 SkipUntil(tok::r_square, StopAtSemi);
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002751 return;
2752 }
2753 first = false;
2754
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002755 T.consumeClose();
John McCall0b7e6782011-03-24 11:26:52 +00002756
Bill Wendlingad017fa2012-12-20 19:22:21 +00002757 // Attributes here appertain to the array type. C++11 [expr.new]p5.
Richard Smith6ee326a2012-04-10 01:32:12 +00002758 ParsedAttributes Attrs(AttrFactory);
Richard Smith4e24f0f2013-01-02 12:01:23 +00002759 MaybeParseCXX11Attributes(Attrs);
Richard Smith6ee326a2012-04-10 01:32:12 +00002760
John McCall0b7e6782011-03-24 11:26:52 +00002761 D.AddTypeInfo(DeclaratorChunk::getArray(0,
John McCall7f040a92010-12-24 02:08:15 +00002762 /*static=*/false, /*star=*/false,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002763 Size.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002764 T.getOpenLocation(),
2765 T.getCloseLocation()),
Richard Smith6ee326a2012-04-10 01:32:12 +00002766 Attrs, T.getCloseLocation());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002767
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002768 if (T.getCloseLocation().isInvalid())
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002769 return;
2770 }
2771}
2772
2773/// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id.
2774/// This ambiguity appears in the syntax of the C++ new operator.
2775///
2776/// new-expression:
2777/// '::'[opt] 'new' new-placement[opt] '(' type-id ')'
2778/// new-initializer[opt]
2779///
2780/// new-placement:
2781/// '(' expression-list ')'
2782///
John McCallca0408f2010-08-23 06:44:23 +00002783bool Parser::ParseExpressionListOrTypeId(
Chris Lattner5f9e2722011-07-23 10:55:15 +00002784 SmallVectorImpl<Expr*> &PlacementArgs,
Chris Lattner59232d32009-01-04 21:25:24 +00002785 Declarator &D) {
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002786 // The '(' was already consumed.
2787 if (isTypeIdInParens()) {
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002788 ParseSpecifierQualifierList(D.getMutableDeclSpec());
Sebastian Redlab197ba2009-02-09 18:23:29 +00002789 D.SetSourceRange(D.getDeclSpec().getSourceRange());
Sebastian Redlcee63fb2008-12-02 14:43:59 +00002790 ParseDeclarator(D);
Chris Lattnereaaebc72009-04-25 08:06:05 +00002791 return D.isInvalidType();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002792 }
2793
2794 // It's not a type, it has to be an expression list.
2795 // Discard the comma locations - ActOnCXXNew has enough parameters.
2796 CommaLocsTy CommaLocs;
2797 return ParseExpressionList(PlacementArgs, CommaLocs);
2798}
2799
2800/// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used
2801/// to free memory allocated by new.
2802///
Chris Lattner59232d32009-01-04 21:25:24 +00002803/// This method is called to parse the 'delete' expression after the optional
2804/// '::' has been already parsed. If the '::' was present, "UseGlobal" is true
2805/// and "Start" is its location. Otherwise, "Start" is the location of the
2806/// 'delete' token.
2807///
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002808/// delete-expression:
2809/// '::'[opt] 'delete' cast-expression
2810/// '::'[opt] 'delete' '[' ']' cast-expression
John McCall60d7b3a2010-08-24 06:29:42 +00002811ExprResult
Chris Lattner59232d32009-01-04 21:25:24 +00002812Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) {
2813 assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword");
2814 ConsumeToken(); // Consume 'delete'
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002815
2816 // Array delete?
2817 bool ArrayDelete = false;
Richard Smith6ee326a2012-04-10 01:32:12 +00002818 if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) {
Richard Smith950435c2012-08-09 19:01:51 +00002819 // C++11 [expr.delete]p1:
2820 // Whenever the delete keyword is followed by empty square brackets, it
2821 // shall be interpreted as [array delete].
2822 // [Footnote: A lambda expression with a lambda-introducer that consists
2823 // of empty square brackets can follow the delete keyword if
2824 // the lambda expression is enclosed in parentheses.]
2825 // FIXME: Produce a better diagnostic if the '[]' is unambiguously a
2826 // lambda-introducer.
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002827 ArrayDelete = true;
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002828 BalancedDelimiterTracker T(*this, tok::l_square);
2829
2830 T.consumeOpen();
2831 T.consumeClose();
2832 if (T.getCloseLocation().isInvalid())
Sebastian Redl20df9b72008-12-11 22:51:44 +00002833 return ExprError();
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002834 }
2835
John McCall60d7b3a2010-08-24 06:29:42 +00002836 ExprResult Operand(ParseCastExpression(false));
Sebastian Redl0e9eabc2008-12-09 13:15:23 +00002837 if (Operand.isInvalid())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00002838 return Operand;
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002839
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002840 return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get());
Sebastian Redl4c5d3202008-11-21 19:14:01 +00002841}
Sebastian Redl64b45f72009-01-05 20:52:13 +00002842
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002843static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) {
2844 switch (kind) {
2845 default: llvm_unreachable("Not a known type trait");
Stephen Hines651f13c2014-04-23 16:59:28 -07002846#define TYPE_TRAIT_1(Spelling, Name, Key) \
2847case tok::kw_ ## Spelling: return UTT_ ## Name;
2848#define TYPE_TRAIT_2(Spelling, Name, Key) \
2849case tok::kw_ ## Spelling: return BTT_ ## Name;
2850#include "clang/Basic/TokenKinds.def"
2851#define TYPE_TRAIT_N(Spelling, Name, Key) \
2852 case tok::kw_ ## Spelling: return TT_ ## Name;
2853#include "clang/Basic/TokenKinds.def"
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002854 }
2855}
2856
John Wiegley21ff2e52011-04-28 00:16:57 +00002857static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) {
2858 switch(kind) {
2859 default: llvm_unreachable("Not a known binary type trait");
2860 case tok::kw___array_rank: return ATT_ArrayRank;
2861 case tok::kw___array_extent: return ATT_ArrayExtent;
2862 }
2863}
2864
John Wiegley55262202011-04-25 06:54:41 +00002865static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) {
2866 switch(kind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002867 default: llvm_unreachable("Not a known unary expression trait.");
John Wiegley55262202011-04-25 06:54:41 +00002868 case tok::kw___is_lvalue_expr: return ET_IsLValueExpr;
2869 case tok::kw___is_rvalue_expr: return ET_IsRValueExpr;
2870 }
2871}
2872
Stephen Hines651f13c2014-04-23 16:59:28 -07002873static unsigned TypeTraitArity(tok::TokenKind kind) {
2874 switch (kind) {
2875 default: llvm_unreachable("Not a known type trait");
2876#define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N;
2877#include "clang/Basic/TokenKinds.def"
Francois Pichet6ad6f282010-12-07 00:08:36 +00002878 }
Francois Pichet6ad6f282010-12-07 00:08:36 +00002879}
2880
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002881/// \brief Parse the built-in type-trait pseudo-functions that allow
2882/// implementation of the TR1/C++11 type traits templates.
2883///
2884/// primary-expression:
Stephen Hines651f13c2014-04-23 16:59:28 -07002885/// unary-type-trait '(' type-id ')'
2886/// binary-type-trait '(' type-id ',' type-id ')'
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002887/// type-trait '(' type-id-seq ')'
2888///
2889/// type-id-seq:
2890/// type-id ...[opt] type-id-seq[opt]
2891///
2892ExprResult Parser::ParseTypeTrait() {
Stephen Hines651f13c2014-04-23 16:59:28 -07002893 tok::TokenKind Kind = Tok.getKind();
2894 unsigned Arity = TypeTraitArity(Kind);
2895
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002896 SourceLocation Loc = ConsumeToken();
2897
2898 BalancedDelimiterTracker Parens(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002899 if (Parens.expectAndConsume())
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002900 return ExprError();
2901
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002902 SmallVector<ParsedType, 2> Args;
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002903 do {
2904 // Parse the next type.
2905 TypeResult Ty = ParseTypeName();
2906 if (Ty.isInvalid()) {
2907 Parens.skipToEnd();
2908 return ExprError();
2909 }
2910
2911 // Parse the ellipsis, if present.
2912 if (Tok.is(tok::ellipsis)) {
2913 Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken());
2914 if (Ty.isInvalid()) {
2915 Parens.skipToEnd();
2916 return ExprError();
2917 }
2918 }
2919
2920 // Add this type to the list of arguments.
2921 Args.push_back(Ty.get());
Stephen Hines651f13c2014-04-23 16:59:28 -07002922 } while (TryConsumeToken(tok::comma));
2923
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002924 if (Parens.consumeClose())
2925 return ExprError();
Stephen Hines651f13c2014-04-23 16:59:28 -07002926
2927 SourceLocation EndLoc = Parens.getCloseLocation();
2928
2929 if (Arity && Args.size() != Arity) {
2930 Diag(EndLoc, diag::err_type_trait_arity)
2931 << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc);
2932 return ExprError();
2933 }
2934
2935 if (!Arity && Args.empty()) {
2936 Diag(EndLoc, diag::err_type_trait_arity)
2937 << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc);
2938 return ExprError();
2939 }
2940
2941 return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc);
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00002942}
2943
John Wiegley21ff2e52011-04-28 00:16:57 +00002944/// ParseArrayTypeTrait - Parse the built-in array type-trait
2945/// pseudo-functions.
2946///
2947/// primary-expression:
2948/// [Embarcadero] '__array_rank' '(' type-id ')'
2949/// [Embarcadero] '__array_extent' '(' type-id ',' expression ')'
2950///
2951ExprResult Parser::ParseArrayTypeTrait() {
2952 ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind());
2953 SourceLocation Loc = ConsumeToken();
2954
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002955 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002956 if (T.expectAndConsume())
John Wiegley21ff2e52011-04-28 00:16:57 +00002957 return ExprError();
2958
2959 TypeResult Ty = ParseTypeName();
2960 if (Ty.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002961 SkipUntil(tok::comma, StopAtSemi);
2962 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002963 return ExprError();
2964 }
2965
2966 switch (ATT) {
2967 case ATT_ArrayRank: {
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002968 T.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002969 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr,
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002970 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002971 }
2972 case ATT_ArrayExtent: {
Stephen Hines651f13c2014-04-23 16:59:28 -07002973 if (ExpectAndConsume(tok::comma)) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00002974 SkipUntil(tok::r_paren, StopAtSemi);
John Wiegley21ff2e52011-04-28 00:16:57 +00002975 return ExprError();
2976 }
2977
2978 ExprResult DimExpr = ParseExpression();
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002979 T.consumeClose();
John Wiegley21ff2e52011-04-28 00:16:57 +00002980
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002981 return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(),
2982 T.getCloseLocation());
John Wiegley21ff2e52011-04-28 00:16:57 +00002983 }
John Wiegley21ff2e52011-04-28 00:16:57 +00002984 }
David Blaikie30263482012-01-20 21:50:17 +00002985 llvm_unreachable("Invalid ArrayTypeTrait!");
John Wiegley21ff2e52011-04-28 00:16:57 +00002986}
2987
John Wiegley55262202011-04-25 06:54:41 +00002988/// ParseExpressionTrait - Parse built-in expression-trait
2989/// pseudo-functions like __is_lvalue_expr( xxx ).
2990///
2991/// primary-expression:
2992/// [Embarcadero] expression-trait '(' expression ')'
2993///
2994ExprResult Parser::ParseExpressionTrait() {
2995 ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind());
2996 SourceLocation Loc = ConsumeToken();
2997
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00002998 BalancedDelimiterTracker T(*this, tok::l_paren);
Stephen Hines651f13c2014-04-23 16:59:28 -07002999 if (T.expectAndConsume())
John Wiegley55262202011-04-25 06:54:41 +00003000 return ExprError();
3001
3002 ExprResult Expr = ParseExpression();
3003
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003004 T.consumeClose();
John Wiegley55262202011-04-25 06:54:41 +00003005
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003006 return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(),
3007 T.getCloseLocation());
John Wiegley55262202011-04-25 06:54:41 +00003008}
3009
3010
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003011/// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a
3012/// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate
3013/// based on the context past the parens.
John McCall60d7b3a2010-08-24 06:29:42 +00003014ExprResult
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003015Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType,
John McCallb3d87482010-08-24 05:47:05 +00003016 ParsedType &CastTy,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003017 BalancedDelimiterTracker &Tracker,
3018 ColonProtectionRAIIObject &ColonProt) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003019 assert(getLangOpts().CPlusPlus && "Should only be called for C++!");
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003020 assert(ExprType == CastExpr && "Compound literals are not ambiguous!");
3021 assert(isTypeIdInParens() && "Not a type-id!");
3022
John McCall60d7b3a2010-08-24 06:29:42 +00003023 ExprResult Result(true);
John McCallb3d87482010-08-24 05:47:05 +00003024 CastTy = ParsedType();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003025
3026 // We need to disambiguate a very ugly part of the C++ syntax:
3027 //
3028 // (T())x; - type-id
3029 // (T())*x; - type-id
3030 // (T())/x; - expression
3031 // (T()); - expression
3032 //
3033 // The bad news is that we cannot use the specialized tentative parser, since
3034 // it can only verify that the thing inside the parens can be parsed as
3035 // type-id, it is not useful for determining the context past the parens.
3036 //
3037 // The good news is that the parser can disambiguate this part without
Argyrios Kyrtzidisa558a892009-05-22 15:12:46 +00003038 // making any unnecessary Action calls.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003039 //
3040 // It uses a scheme similar to parsing inline methods. The parenthesized
3041 // tokens are cached, the context that follows is determined (possibly by
3042 // parsing a cast-expression), and then we re-introduce the cached tokens
3043 // into the token stream and parse them appropriately.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003044
Mike Stump1eb44332009-09-09 15:08:12 +00003045 ParenParseOption ParseAs;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003046 CachedTokens Toks;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003047
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003048 // Store the tokens of the parentheses. We will parse them after we determine
3049 // the context that follows them.
Argyrios Kyrtzidis14b91622010-04-23 21:20:12 +00003050 if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003051 // We didn't find the ')' we expected.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003052 Tracker.consumeClose();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003053 return ExprError();
3054 }
3055
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003056 if (Tok.is(tok::l_brace)) {
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003057 ParseAs = CompoundLiteral;
3058 } else {
3059 bool NotCastExpr;
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003060 if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) {
3061 NotCastExpr = true;
3062 } else {
3063 // Try parsing the cast-expression that may follow.
3064 // If it is not a cast-expression, NotCastExpr will be true and no token
3065 // will be consumed.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003066 ColonProt.restore();
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003067 Result = ParseCastExpression(false/*isUnaryExpression*/,
3068 false/*isAddressofOperand*/,
John McCallb3d87482010-08-24 05:47:05 +00003069 NotCastExpr,
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003070 // type-id has priority.
Kaelyn Uhraincd78e612012-01-25 20:49:08 +00003071 IsTypeCast);
Eli Friedmanb53f08a2009-05-25 19:41:42 +00003072 }
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003073
3074 // If we parsed a cast-expression, it's really a type-id, otherwise it's
3075 // an expression.
3076 ParseAs = NotCastExpr ? SimpleExpr : CastExpr;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003077 }
3078
Mike Stump1eb44332009-09-09 15:08:12 +00003079 // The current token should go after the cached tokens.
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003080 Toks.push_back(Tok);
3081 // Re-enter the stored parenthesized tokens into the token stream, so we may
3082 // parse them now.
3083 PP.EnterTokenStream(Toks.data(), Toks.size(),
3084 true/*DisableMacroExpansion*/, false/*OwnsTokens*/);
3085 // Drop the current token and bring the first cached one. It's the same token
3086 // as when we entered this function.
3087 ConsumeAnyToken();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003088
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003089 if (ParseAs >= CompoundLiteral) {
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003090 // Parse the type declarator.
3091 DeclSpec DS(AttrFactory);
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003092 Declarator DeclaratorInfo(DS, Declarator::TypeNameContext);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003093 {
3094 ColonProtectionRAIIObject InnerColonProtection(*this);
3095 ParseSpecifierQualifierList(DS);
3096 ParseDeclarator(DeclaratorInfo);
3097 }
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003098
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003099 // Match the ')'.
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003100 Tracker.consumeClose();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003101 ColonProt.restore();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003102
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003103 if (ParseAs == CompoundLiteral) {
3104 ExprType = CompoundLiteral;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003105 if (DeclaratorInfo.isInvalidType())
3106 return ExprError();
3107
3108 TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo);
3109 return ParseCompoundLiteralExpression(Ty.get(),
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003110 Tracker.getOpenLocation(),
3111 Tracker.getCloseLocation());
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003112 }
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003114 // We parsed '(' type-id ')' and the thing after it wasn't a '{'.
3115 assert(ParseAs == CastExpr);
3116
Argyrios Kyrtzidis0a851832011-07-01 22:22:59 +00003117 if (DeclaratorInfo.isInvalidType())
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003118 return ExprError();
3119
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003120 // Result is what ParseCastExpression returned earlier.
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003121 if (!Result.isInvalid())
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003122 Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(),
3123 DeclaratorInfo, CastTy,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003124 Tracker.getCloseLocation(), Result.get());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003125 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003126 }
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003128 // Not a compound literal, and not followed by a cast-expression.
3129 assert(ParseAs == SimpleExpr);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003130
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003131 ExprType = SimpleExpr;
Argyrios Kyrtzidisf40882a2009-05-22 21:09:47 +00003132 Result = ParseExpression();
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003133 if (!Result.isInvalid() && Tok.is(tok::r_paren))
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003134 Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(),
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003135 Tok.getLocation(), Result.get());
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003136
3137 // Match the ')'.
3138 if (Result.isInvalid()) {
Alexey Bataev8fe24752013-11-18 08:17:37 +00003139 SkipUntil(tok::r_paren, StopAtSemi);
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003140 return ExprError();
3141 }
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Douglas Gregor4a8dfb52011-10-12 16:37:45 +00003143 Tracker.consumeClose();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003144 return Result;
Argyrios Kyrtzidisf58f45e2009-05-22 10:24:42 +00003145}